views:

92

answers:

2

Hi, I am stuck reading a file in /sys/ which contains the light intensity in Lux of the ambient light sensor on my Nokia N900 phone.

See thread on talk.maemo.org here

I tried to use pyinotify to poll the file but this looks some kind of wrong to me since the file is alway "process_IN_OPEN", "process_IN_ACCESS" and "process_IN_CLOSE_NOWRITE"

I basically want to get the changes ASAP and if something changed trigger an event, execute a class...

Here's the code I tried, which works, but not as I expected (I was hoping for process_IN_MODIFY to be triggered):

#!/usr/bin/env python

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_MODIFY(self, event):
     print "MODIFY event:", action(self, event)
   ...

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

wdd = wm.add_watch(ambient_sensor, mask)
wdd

time.sleep(5)

notifier.stop()

Update 1:

Mmmh, all I came up without having a clue if there is a special mechanism is the following:

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?

+1  A: 

Since the /sys/file is a pseudo-file which just presents a view on an underlying, volatile operating system value, it makes sense that there would never be a modify event raised. Since the file is "modified" from below it doesn't follow regular file-system semantics.

If a modify event is never raised, using a package like pinotify isn't going to get you anywhere. 'twould be better to look for a platform-specific mechanism.

Response to Update 1:

Since the N900 maemo runtime supports GFileMonitor, you'd do well to check if it can provide the asynchronous event that you desire.

Busy waiting - as I gather you know - is wasteful. On a phone it can really drain a battery. You should at least sleep in your busy loop.

msw
A: 

Mmmh, all I came up without having a clue if there is a special mechanism is the following:

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

Bjoern