maemo.org - Talk

maemo.org - Talk (https://talk.maemo.org/index.php)
-   Development (https://talk.maemo.org/forumdisplay.php?f=13)
-   -   python - how to read information from light meter, microphone and accelerometers? (https://talk.maemo.org/showthread.php?t=55436)

blubbi 2010-06-07 11:11

python - how to read information from light meter, microphone and accelerometers?
 
Hi,

does any know how I can retrieve the information provided by the light meter, microphone and accelerometers?

Are there ready to use classes? D-BUS?

Any hints, examples are appreciated.

Thanks and kind regards
blubbi

blubbi 2010-06-07 11:15

Re: python - how to read information from light meter, microphone and accelerometers?
 
Okay, for the accelerometers I found some information here:
http://wiki.maemo.org/Accelerometers

Cheers
Bjoern

noobmonkey 2010-06-07 11:56

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by blubbi (Post 703318)
Hi,

does any know how I can retrieve the information provided by the light meter, microphone and accelerometers?

Are there ready to use classes? D-BUS?

Any hints, examples are appreciated.

Thanks and kind regards
blubbi

Take a look at the healthcheck code - it's simple and just uses CLI style access to things. There is also some DBUS'yness in there too
(Once installed the python files will be in
/opt/healthcheck/

Example code (Functions file):
Code:

# -*- coding: utf-8 -*-
import os
import dbus

def funcAccel():
        print "** Start Function - Accel Co-ords **"
        f = open("/sys/class/i2c-adapter/i2c-3/3-001d/coord", 'r')
        coords = [int(w) for w in f.readline().split()]
        f.close()
        print " ** Getting orientation**"
        b = os.popen('run-standalone.sh dbus-send --system --type=signal /com/nokia/mce/signal com.nokia.mce.signal.sig_device_orientation_ind').read()
        coords = str(coords)
        jaccel = str(coords) + str(b)
        return jaccel

def funcBatchrg():
        print "** Start Function - Battery Charge **"
        gl = os.popen('hal-device bme | awk \'/l.p/ {perc = $3}; /s_c/ {isch = $3} END if (isch == "false") {print perc" %"} else {print "Charging"}\'').read()
        gl = gl.strip()
        return gl

def funcBatLastChrg():
        print " ** Start Function - battery last charge**"
        gl = os.popen('hal-device bme | awk \'/g.la/ {print $3" mAh"}\'').read()
        return gl.strip()

def funcBattcurr():
        print "** Start Function - Battery Current **"
        gl = os.popen('hal-device bme | awk \'/g.c/ {print $3" mAh"}\'').read()
        gl = gl.strip()
        return gl

def funcCamState():
        print "** Start Function - Cam Shutter State **"
        gl = os.popen('cat /sys/devices/platform/gpio-switch/cam_shutter/state').read()
        gl = gl.strip()
        return gl

def funcFMTrans():
        print "** Start Function - FM Transmitter power level **"
        ge = os.popen('cat /sys/class/i2c-adapter/i2c-2/2-0063/power_level').read()
        ge = ge.strip()
        return ge

def funcHeadphoneState():
        print "** Start Function - Headphone State **"
        gl = os.popen('cat /sys/devices/platform/gpio-switch/headphone/state').read()
        gl = gl.strip()
        return gl

def funcKeySlider():
        print "** Start Function - Keyboard Slider State **"
        gl = os.popen('cat /sys/devices/platform/gpio-switch/slide/state').read()
        gl = gl.strip()
        return gl

def funcProxState():
        print " ** Start Function - proximity sensor state**"
        gl = os.popen('cat /sys/devices/platform/gpio-switch/proximity/state').read()
        gl = gl.strip()
        return gl

def funcSysUptime():
        print "** Start Function - system uptime**"
        ge = os.popen('uptime | sed -e \'s/.*p *//\' -e \'s/, l.*//\' -e \'s/  / /\'').read()
        return ge

def funcCurrentCPUFreq():
        print "** Start Function - CPU Frequency **"
        gl = os.popen('echo $((`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq`/1000)) MHz').read()
        gl = gl.strip()
        return gl

def funcAppUsed():
        print "** Start Function - App Used **"
        gl = os.popen('df /home | awk \'/ho/ {print $5}\'').read()
        gl = gl.strip()
        return gl

def funcAppFree():
        print "** Start Function - App Free **"
        gl = os.popen('df -h /home | awk \'/ho/ {print $4}\'').read()
        gl = gl.strip()
        return gl

def funcBacklightAct():
        print "** Start Function - Backlight Info **"
        gl = os.popen('cat /sys/class/backlight/acx565akm/brightness').read()
        gl = gl.strip()
        return gl

def funcBacklightMax():
        print "** Start Function - Backlight Info MAX **"
        gl = os.popen('cat /sys/class/backlight/acx565akm/max_brightness').read()
        gl = gl.strip()
        return gl

def funcKernelInfo():
        print "** Start Function - Kernel Core Info **"
        gl = os.popen('cat /sys/kernel/vmcoreinfo').read()
        return gl.strip()

def funcBootCount():
        print "** Start Function - boot count**"
        gd = os.popen('cat /var/lib/dsme/boot_count').read()
        gd = gd.strip()
        return gd

def funcBootReason():
        print "** Start Function - Boot Reason**"
        gl = os.popen('cat /proc/bootreason').read()
        gl = gl.strip()
        return gl

def funcMMCState():
        print "** Start Function - MMC Cover/latch **"
        gl = os.popen('cat /sys/class/mmc_host/mmc0/cover_switch').read()
        gl = gl.strip()
        return gl

def funcMemoryCUsed():
        print "** Start Function - Memory Card Used **"
        gl = os.popen('df /media/mmc1 | awk \'/mm/ {print $5}\'').read()
        gl = gl.strip()
        return gl

def funcMemoryCFree():
        print "** Start Function - Memory Card Free **"
        gl = os.popen('df -h /media/mmc1 | awk \'/mm/ {print $4}\'').read()
        gl = gl.strip()
        return gl

def funcMyDocsUsed():
        print "** Start Function - MyDocs % Used **"
        gl = os.popen('df /home/user/MyDocs | awk \'/My/ {print $5}\'').read()
        gl = gl.strip()
        return gl

def funcMyDocsFree():
        print "** Start Function - myDocs MB Free **"
        gl = os.popen('df -h /home/user/MyDocs | awk \'/My/ {print $4}\'').read()
        gl = gl.strip()
        return gl

def funcRootUsed():
        print "** Start Function - rootfs % used **"
        gl = os.popen('df | awk \'$1 == "rootfs" {print $5}\'').read()
        gl = gl.strip()
        return gl

def funcRootFree():
        print "** Start Function - rootfs free MB **"
        gl = os.popen('df -h | awk \'$1 == "rootfs" {print $4}\'').read()
        gl = gl.strip()
        return gl

def funcSysLoad():
        print "** Start Function - load from uptime **"
        ge = os.popen('uptime | sed \'s/.*e: //\'').read()
        return ge

def funcDevOri():
        print "** Start Function - Device Orientation **"
        bus = dbus.SystemBus()           
        accel = bus.get_object('com.nokia.mce','/com/nokia/mce/request','com.nokia.mce.request')
        orientation , stand , face , x , y , z = accel.get_device_orientation()
        return orientation

def funcCPUfreq():
        print "** Start Function - CPU Frequency File **"
        fh = open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies","r")
        igot = fh.readlines()
        print "** Adding CPUQ Frequencies **"
        aa = ""
        counter = 0
        for line in igot:
                s = line.split()
                for words in s:
                        counter = counter +1
                        if counter == 5:
                                aa = str(aa) +"\n \t\t\t\t"
                        if counter == 9:
                                aa = str(aa) +"\n \t\t\t\t"
                        if counter == 13:
                                aa = str(aa) +"\n \t\t\t\t"
                        aa = str(aa) + str((int(words)/1000)) + "MHz, "
        aa = aa.strip()[:-1]
        return aa

def funcProcInfo():
        print "** Start Function - Processor Information **"
        ga = os.popen('cat /proc/cpuinfo | grep Processor').read()       
        return ga.strip()[11:]

def funcN900Board():
        print "** Start Function - N900 Board Information **"
        gb = os.popen('cat /proc/cpuinfo | grep Hardware').read()
        return gb.strip()[11:]

def funcBoardVer():
        print "** Start Function - Board Version **"
        gj = os.popen('cat /proc/cpuinfo | grep Revision').read()
        return gj.strip()[11:]

def funcSysLocale():
        print "** Start Function - System Locale **"
        gc = os.popen('locale | grep LANG').read()
        return gc.strip()[5:]

def funcHostName():
        print "** Start Function - Device Hostname **"
        ga = os.popen('cat /etc/hostname').read()
        return ga.strip()

def funcIMEI():
        print "** Start Function - Device IMEI **"
        b = os.popen('run-standalone.sh dbus-send --system --print-reply --type=method_call --dest=com.nokia.phone.SIM /com/nokia/phone/SIM/security Phone.Sim.Security.get_imei').read()
        b = str(b)
        b = b.strip()
        b = str(b)[-27:]
        b = b.strip()
        b = str(b)[:-12]
        return b

def funcInternalIP():
        print "** Start Function - Internal IP **"
        ga = os.popen('/sbin/ifconfig | awk \'/Bc/ {print $2}\' | cut -c6-').read()
        return ga.strip()

def funcWifiLinkQ():
        print "** Start Function - Wireless Link Quality **"
        ga = os.popen('cat /proc/net/wireless | awk \'/0/ {print $3}\' | awk -F. \'/./ {print $1" %"}\'').read()
        return ga.strip()

def funcWifiRSSI():
        print "** Start Function - Wireless RSSI **"
        ga = os.popen('cat /proc/net/wireless | awk \'/0/ {print $4" dBm"}\'').read()
        return ga.strip()

def funcWifiNoise():
        print "** Start Function - Wireless Noise **"
        ga = os.popen('cat /proc/net/wireless | awk \'/0/ {print $5}\' | awk -F. \'/./ {print $1" dBm"}\'').read()
        return ga.strip()

def funcMacAddress():
        print "** Start Function - MAC Address **"
        gl = os.popen('cat /sys/class/ieee80211/phy0/macaddress').read()
        return gl.strip()

def funcBluetooth():
        print "** Start Function - Bluetooth Name **"
        gl = os.popen('grep \'^Name =\' /etc/bluetooth/main.conf').read()
        return gl.strip()[7:]

def funcBluetoothMAC():
        print "** Start Function - Bluetooth MAC**"
        gl = os.popen('/usr/sbin/hciconfig hci0 | grep BD').read()           
        s = gl.split(" ")
        return s[2].strip()

def funcCPUMinMax():
        print "** Start Function - Bluetooth MAC**"
        a = os.popen('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq').read()
        a = a.strip()
        a = int(a) / 1000
        b = os.popen('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq').read()
        b = b.strip()
        b = int(b) / 1000
        c = str(b) + "MHz" + " / " + str(a) + "MHz"
        return c.strip()


noobmonkey 2010-06-07 12:08

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by blubbi (Post 703318)
Hi,

does any know how I can retrieve the information provided by the light meter, microphone and accelerometers?

Forgot to add - with the microphone part i'm struggling on that one.
Looking into and waiting for qtmultimedia/mobility :)

blubbi 2010-06-07 12:17

Re: python - how to read information from light meter, microphone and accelerometers?
 
This answers most. Thanks a lot.

But why call external tools to read the "files"

why not simply use
Code:

def funcProxState():
        print " ** Start Function - proximity sensor state**"
        gl = open('/sys/devices/platform/gpio-switch/proximity/state', 'r').read().strip()
        return gl

There is no need to make system calls to grep, cat, awk and others in python. Python has excellent string handling capabilities.


Cheers
blubbi

Radicalz38 2010-06-07 12:18

Re: python - how to read information from light meter, microphone and accelerometers?
 
I have just managed to play with accelerometer so here's a simple script to output the phone's state.

Code:

from ctypes import *
import os
import sys
import time
from math import atan2
from pprint import pprint

xlib = cdll.LoadLibrary("libX11.so.6")
rr = cdll.LoadLibrary("libXrandr.so.2")

def out_rotate():
    f = open("/sys/class/i2c-adapter/i2c-3/3-001d/coord", 'r' )
    cdinate = [int(w) for w in f.readline().split()]
    f.close()
    return cdinate

print out_rotate()
time.sleep(1)


noobmonkey 2010-06-07 12:23

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by blubbi (Post 703393)
This answers most. Thanks a lot.

But why call external tools to read the "files"

why not simply use
Code:

def funcProxState():
        print " ** Start Function - proximity sensor state**"
        gl = open('/sys/devices/platform/gpio-switch/proximity/state', 'r').read().strip()
        return gl

There is no need to make system calls to grep, cat, awk and others in python. Python has excellent string handling capabilities.


Cheers
blubbi

Because........ erm..... errr..... it worked, and i stuck with it :) hehehe
(Very new to python, linux and QT, so the whole thing is a learning curve!

blubbi 2010-06-07 12:24

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by noobmonkey (Post 703385)
Forgot to add - with the microphone part i'm struggling on that one.
Looking into and waiting for qtmultimedia/mobility :)

The higher purpose of my question is the following:
I want to emit a IR-Signal when the signal level of on of the sensors (Proximity sensor, Microphone, Accelerometers) raises above a certain threshold and remotely trigger my Canon EOS 7D ;-)

Cheers
blubbi

blubbi 2010-06-07 12:29

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by noobmonkey (Post 703400)
Because........ erm..... errr..... it worked, and i stuck with it :) hehehe
(Very new to python, linux and QT, so the whole thing is a learning curve!

Hehe, okay, I could have guessed that ;-)

Here some fine links:
http://gnosis.cx/TPiP/
http://docs.python.org/lib/string-methods.html

By the way, do you know how I can get the light intensity like the app "luxus" does?

Cheers
blubbi

noobmonkey 2010-06-07 12:37

Re: python - how to read information from light meter, microphone and accelerometers?
 
not seen luxus, but can check later.
which light intensity? the screen brightness intensity should be in the code above.

:) (out on lunch, so not near a pc)

blubbi 2010-06-07 12:48

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by noobmonkey (Post 703416)
not seen luxus, but can check later.
which light intensity? the screen brightness intensity should be in the code above.

:) (out on lunch, so not near a pc)

No I really mean light intensity of the ambient light recorded by the proximity sensor (or also called ambient light sensor).

If I can make the program react fast enough it might be possible to use it for such photos: http://gallery.olausson.de/v/20082211_-_wings_of_fire/

Since I want to try it again with a way sharper lense and some more experience it would be very nice if the N900 could trigger the Canon EOS 7D as soon as the match ignites. This would reduce the junk images tremendous :-)

Once I know how to read the ambient light intensity the rest should be straight forward ;-)

Cheers
blubbi

Joorin 2010-06-07 19:16

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by Radicalz38 (Post 703395)
I have just managed to play with accelerometer so here's a simple script to output the phone's state.

Code:

from ctypes import *
import os
import sys
import time
from math import atan2
from pprint import pprint

xlib = cdll.LoadLibrary("libX11.so.6")
rr = cdll.LoadLibrary("libXrandr.so.2")

def out_rotate():
    f = open("/sys/class/i2c-adapter/i2c-3/3-001d/coord", 'r' )
    cdinate = [int(w) for w in f.readline().split()]
    f.close()
    return cdinate

print out_rotate()
time.sleep(1)


Why do you load X11 libraries to read from a file and write to the console? And lots of import?

blubbi 2010-06-07 20:16

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by Joorin (Post 704035)
Why do you load X11 libraries to read from a file and write to the console? And lots of import?

I guess it is only en excerpt of a program.

Cheers
blubbi

toninikkanen 2010-06-07 21:40

Re: python - how to read information from light meter, microphone and accelerometers?
 
Hi, am the author of the Luxus program.

I would like to help you and I will, but I seem to have temporary problems. My development PC just died and it will take some days to get it going again. Of course I have the backups but I can't easily access them right now.

Meanwhile I was going to just look at the source code package from the web: http://maemo.org/packages/source/vie...e/luxus/0.4-1/ and copy paste the relevant code lines here for reading the ambient light sensor, but that web address isn't working for me either. :(

Basically it's really simple, there's a special file somewhere in /proc/sys/dev/something/something that you read, it has the light sensor value in lux units. If you are able to fetch the source code, you can locate the exact path by finding where I am opening some file from a path like that.

blubbi 2010-06-07 21:57

Re: python - how to read information from light meter, microphone and accelerometers?
 
Hej, no big deal, I'll check your source code (asap maemo is up again)
I could have come up with this idea myself... *stupid me*

Actually I plan to work out and extend this little tool with the developer of "shutter"
My first plan is to test the concept with this kind of photos:
http://gallery.olausson.de/v/20082211_-_wings_of_fire/

I got a new shiny lens (Canon EF 100mm 2.8L IS Macro) which is way sharper then the lens I made those photos.
The N900 combined with the new Lens some more experience and two new Canon flashes (Canon 580EX II) should yield more usable photos and reduces the "luck" in capturing the ignition point.
Hopefully the sensor will provide the data at a high enough freqency, so Ii I can poll the data at a high enough rate it could also be possible to capture lightnings like the CHDK scripts for compact cameras found here:
http://chdk.wikia.com/wiki/UBASIC/Sc...ghtning_Detect

Cheers
Bjoern

blubbi 2010-06-07 22:45

Re: python - how to read information from light meter, microphone and accelerometers?
 
Here we go for the ambient light meter:

Code:

while true ; do cat /sys/class/i2c-adapter/i2c-2/2-0029/lux ; done
seems quite responsive ;-)

Thanks toninikkanen

Cheers
Bjoern

noobmonkey 2010-06-07 22:48

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by blubbi (Post 704465)
Here we go for the ambient light meter:

Code:

while true ; do cat /sys/class/i2c-adapter/i2c-2/2-0029/lux ; done
seems quite responsive ;-)

Thanks toninikkanen

Cheers
Bjoern

Any idea what the Min/Max values are?
Allllllso.... whilst i'm in that folder, what are calib0 and calib1? :)

(Useful things for healthcheck :) )

blubbi 2010-06-08 00:54

Re: python - how to read information from light meter, microphone and accelerometers?
 
Mmmh, I am now playing around with python-pyinotify to poll the file but it did not what I expected...

I get only a response for "process_IN_OPEN", "process_IN_ACCESS" and "process_IN_CLOSE_NOWRITE" but nothing for "process_IN_MODIFY"...

Any other ideas how to poll the file? Or should I build in a "only trigger event if value change caompared to last time"?

Code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import os, time, pyinotify
import pyinotify

ambient_sensor = '/sys/class/i2c-adapter/i2c-2/2-0029/lux'

wm = pyinotify.WatchManager()  # Watch Manager
mask = pyinotify.ALL_EVENTS

def action(self, the_event):
    value = open(the_event.pathname, 'r').read().strip()
    return value

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_ACCESS(self, event):
        print "ACCESS event:", action(self, event)

    def process_IN_ATTRIB(self, event):
        print "ATTRIB event:", action(self, event)

    def process_IN_CLOSE_NOWRITE(self, event):
        print "CLOSE_NOWRITE event:", action(self, event)

    def process_IN_CLOSE_WRITE(self, event):
        print "CLOSE_WRITE event:", action(self, event)

    def process_IN_CREATE(self, event):
        print "CREATE event:", action(self, event)

    def process_IN_DELETE(self, event):
        print "DELETE event:", action(self, event)

    def process_IN_MODIFY(self, event):
        print "MODIFY event:", action(self, event)

    def process_IN_OPEN(self, event):
        print "OPEN event:", action(self, event)
       

#log.setLevel(10)
notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.start()

wdd = wm.add_watch(ambient_sensor, mask)
wdd
#wm.rm_watch(wdd.values())

time.sleep(5)
notifier.stop()

Cheers
Bjoern

Joorin 2010-06-08 05:24

Re: python - how to read information from light meter, microphone and accelerometers?
 
Polling a file under /sys typically makes no sense. The files you find there act as handy nameholders for different parts of drivers and doing open + read + close makes the driver create the content on the fly.

So, do not view this as regular files but as something you can read from and get the latest value. There is often a library to use to do the same thing which might be faster since opening and reading from a file is a magnitude slower than performing one break into kernel space with an ioctl.

blubbi 2010-06-08 07:04

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by Joorin (Post 704836)
Polling a file under /sys typically makes no sense. The files you find there act as handy nameholders for different parts of drivers and doing open + read + close makes the driver create the content on the fly.

So, do not view this as regular files but as something you can read from and get the latest value. There is often a library to use to do the same thing which might be faster since opening and reading from a file is a magnitude slower than performing one break into kernel space with an ioctl.

I guess my question is superfluous since you probably would have provided the info which lib to use, but:

Do you have a idea how I can access the file correctly?

:D

Cheers
Bjoern

blubbi 2010-06-08 10:32

Re: python - how to read information from light meter, microphone and accelerometers?
 
Mmmh, all I came up without having a clue if there is a special mechanism is the following:

Code:

f = open('/sys/class/i2c-adapter/i2c-2/2-0029/lux')
while True:
    value = f.read()
    print value
    f.seek(0)

This, wrapped in a own thread, could to the trick, but does anyone have a smarter, less CPU-hogging and faster way to get the latest value?

Cheers Bjoern

thp 2010-06-08 10:44

Re: python - how to read information from light meter, microphone and accelerometers?
 
Quote:

Originally Posted by blubbi (Post 705142)
Mmmh, all I came up without having a clue if there is a special mechanism is the following:

Code:

f = open('/sys/class/i2c-adapter/i2c-2/2-0029/lux')
while True:
    value = f.read()
    print value
    f.seek(0)

This, wrapped in a own thread, could to the trick, but does anyone have a smarter, less CPU-hogging and faster way to get the latest value?

You can keep the file open and get notified in your main loop when its contents change, as in this script:

http://talk.maemo.org/showthread.php?t=54695

The interesting bits here are the call to "gobject.io_add_watch" and the "on_state_changed" callback. You don't even need to have a separate thread for it, simply start a GLib main loop (e.g. call gtk.main()) and the mainloop will call your callback when the file has changed (just waiting while it's not changing).


All times are GMT. The time now is 00:07.

vBulletin® Version 3.8.8