def start(self):
     """ Observe added and removed events """
     monitor = pyudev.Monitor.from_netlink(pyudev.Context())
     monitor.filter_by(subsystem="input")
     observer = GUDevMonitorObserver(monitor)
     observer.connect("device-added", self.on_device_added)
     observer.connect("device-removed", self.on_device_removed)
     monitor.enable_receiving()
Ejemplo n.º 2
0
def monitor():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')  
    observer = MonitorObserver(monitor)
    observer.connect('device-removed', remove_event)
    observer.connect('device-added', add_event)
    monitor.start()
    glib.MainLoop().run()
Ejemplo n.º 3
0
def monitor():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')
    observer = MonitorObserver(monitor)
    observer.connect('device-removed', remove_event)
    observer.connect('device-added', add_event)
    monitor.start()
    glib.MainLoop().run()
Ejemplo n.º 4
0
class TestDeprecatedGlibObserver(DeprecatedObserverTestBase):

    ACTION_SIGNAL_MAP = {
        'add': 'device-added',
        'remove': 'device-removed',
        'change': 'device-changed',
        'move': 'device-moved',
    }

    def setup(self):
        self.event_sources = []
        self.glib = pytest.importorskip('glib')
        # make sure that we also have gobject
        pytest.importorskip('gobject')

    def teardown(self):
        for source in self.event_sources:
            self.glib.source_remove(source)

    def create_observer(self, monitor):
        from pyudev.glib import GUDevMonitorObserver
        self.observer = GUDevMonitorObserver(monitor)

    def connect_signal(self, callback, action=None):
        # drop the sender argument from glib signal connections
        def _wrapper(obj, *args, **kwargs):
            return callback(*args, **kwargs)

        if action is None:
            self.observer.connect('device-event', _wrapper)
        else:
            self.observer.connect(self.ACTION_SIGNAL_MAP[action], _wrapper)

    def create_event_loop(self, self_stop_timeout=5000):
        self.mainloop = self.glib.MainLoop()
        self.event_sources.append(
            self.glib.timeout_add(self_stop_timeout, self.stop_event_loop))

    def start_event_loop(self, start_callback):
        def _wrapper(*args, **kwargs):
            start_callback(*args, **kwargs)
            return False

        self.event_sources.append(self.glib.timeout_add(0, _wrapper))
        self.mainloop.run()

    def stop_event_loop(self):
        self.mainloop.quit()
        return False
Ejemplo n.º 5
0
class TestDeprecatedGlibObserver(DeprecatedObserverTestBase):

    ACTION_SIGNAL_MAP = {
        "add": "device-added",
        "remove": "device-removed",
        "change": "device-changed",
        "move": "device-moved",
    }

    def setup(self):
        self.event_sources = []
        self.glib = pytest.importorskip("glib")
        # make sure that we also have gobject
        pytest.importorskip("gobject")

    def teardown(self):
        for source in self.event_sources:
            self.glib.source_remove(source)

    def create_observer(self, monitor):
        from pyudev.glib import GUDevMonitorObserver

        self.observer = GUDevMonitorObserver(monitor)

    def connect_signal(self, callback, action=None):
        # drop the sender argument from glib signal connections
        def _wrapper(obj, *args, **kwargs):
            return callback(*args, **kwargs)

        if action is None:
            self.observer.connect("device-event", _wrapper)
        else:
            self.observer.connect(self.ACTION_SIGNAL_MAP[action], _wrapper)

    def create_event_loop(self, self_stop_timeout=5000):
        self.mainloop = self.glib.MainLoop()
        self.event_sources.append(self.glib.timeout_add(self_stop_timeout, self.stop_event_loop))

    def start_event_loop(self, start_callback):
        def _wrapper(*args, **kwargs):
            start_callback(*args, **kwargs)
            return False

        self.event_sources.append(self.glib.timeout_add(0, _wrapper))
        self.mainloop.run()

    def stop_event_loop(self):
        self.mainloop.quit()
        return False
 def get_event_devices(self):
     '''filter all connected input devices and watch those not used by eventlircd'''
     for device in self.context.list_devices(subsystem='input',ID_INPUT_KEYBOARD=True):
         if device.sys_name.startswith('event') and not (('eventlircd_enable' in device) or ('eventlircd_enable' in device and device['eventlircd_enable'] is ('true'))):
             self.paths[device['DEVNAME']] = open(device['DEVNAME'],'rb')
             syslog.syslog(codecs.encode(u"watching %s: %s"%(device.parent['NAME'], device['DEVNAME']),'utf-8'))
             self.devices[device['DEVNAME']] = gobject.io_add_watch(self.paths[device['DEVNAME']], gobject.IO_IN, self.evthandler)
     self.observer = GUDevMonitorObserver(self.monitor)
     self.observer.connect('device-event',self.udev_event)
     self.monitor.start()
     syslog.syslog("started udev monitoring of input devices")
Ejemplo n.º 7
0
 def start(self):
     """ Observe added and removed events """
     monitor = pyudev.Monitor.from_netlink(pyudev.Context())
     monitor.filter_by(subsystem="input")
     observer = GUDevMonitorObserver(monitor)
     observer.connect("device-added", self.on_device_added)
     observer.connect("device-removed", self.on_device_removed)
     monitor.enable_receiving()
Ejemplo n.º 8
0
	ret = {}
	config = ConfigParser.ConfigParser()
	config.read("config")
	global DEBUG
	ret["url"]       = config.get('MQTT', 'url')
	ret["port"]      = int(config.get('MQTT', 'port'))
	ret["keepalive"] = int(config.get('MQTT', 'keepalive'))
	return ret

def device_event(observer, device):
	if device.device_type=='usb_interface':
	    if device.action == 'add':
        	print('{} connected'.format(device))
                clnt.publish('usb_inserted', str(device))
            if device.action == 'remove':
                print('{} disconnected'.format(device))
                clnt.publish('usb_removed', str(device))

if __name__ == '__main__':
    	conf = init()
    	clnt = initMQTT(conf["url"], conf["port"], conf["keepalive"])
	context = Context()
	monitor = Monitor.from_netlink(context)
	monitor.filter_by(subsystem='usb')
	observer = MonitorObserver(monitor)
	observer.connect('device-added', device_event)
        observer.connect('device-removed', device_event)
	monitor.start()
	glib.MainLoop().run()

Ejemplo n.º 9
0
        print "Pinlock is active"
        pinlock()

    lcd.clear()
    lcd.write('Pocket FM 2.0')
    lcd.cursor(2, 1)
    lcd.write('F: 106,4 Mhz')
    lcd.cursor(3, 1)
    lcd.write('S: SAT')

    # enter digital mode for radio
    radio.init_radio()

    context = Context()
    monitor = Monitor.from_netlink(context)

    monitor.filter_by(subsystem='usb')
    observer = MonitorObserver(monitor)

    observer.connect('device-event', device_event)
    monitor.start()

    gobject.threads_init()
    glib.idle_add(update_loop)
    glib.MainLoop().run()

finally:
    # close the fifo
    mplayer_fifo.close()
    GPIO.cleanup()
Ejemplo n.º 10
0
 def create_observer(self, monitor):
     from pyudev.glib import GUDevMonitorObserver
     self.observer = GUDevMonitorObserver(monitor)
Ejemplo n.º 11
0
Archivo: pfmd.py Proyecto: honsey/pfm
        pinlock()
	

    lcd.clear()
    lcd.write('Pocket FM 2.0')
    lcd.cursor(2,1)
    lcd.write('F: 106,4 Mhz')
    lcd.cursor(3,1)
    lcd.write('S: SAT')

    # enter digital mode for radio
    radio.init_radio()
    
    context = Context()
    monitor = Monitor.from_netlink(context)

    monitor.filter_by(subsystem='usb')
    observer = MonitorObserver(monitor)

    observer.connect('device-event', device_event)
    monitor.start()
    
    gobject.threads_init()
    glib.idle_add(update_loop)
    glib.MainLoop().run() 
        
finally:
    # close the fifo
    mplayer_fifo.close()
    GPIO.cleanup()
class Settings():
    ''' read and store configuration, handle input devices using udev'''
    def __init__(self):
        global gobject
        self.frontend_active = 0
        self.env = os.environ
        self.timer = None
        self.updateDisplay()
        self.manualstart = shutdown.manualstart()
        try:
            self.acpi_wakeup = self.check_acpi()
        except:
            self.acpi_wakeup = None
        self.context = pyudev.Context()
        self.monitor = pyudev.Monitor.from_netlink(self.context)
        self.monitor.filter_by(subsystem='input')
        self.devices = {}
        self.paths = {}
        # struct for kernel input devices on 64-Bit linux systems
        self.inputEventFormat = 'llHHi'
        self.inputEventSize = 24
        # on 32-Bit systems try
        # inputEventFormat = 'iihhi'
        # inputEventSize = 16
        # (untested)
        self.conf = {
        'logo_attached':"/usr/share/yavdr/images/yavdr_logo.png",
        'logo_detached':"/usr/share/yavdr/images/yaVDR_background_detached.jpg",
        'key_detach':"KEY_PROG1",
        'key_power':"KEY_POWER2",
        'start_always_detached':'0',
        'graphtft_view':"NonLiveTv"
        }
        for i in self.conf:
            if i in os.environ:
                self.conf[i] = os.environ[i]
        self.check_graphtft()
        self.get_event_devices()
    
    def check_graphtft(self):
        plugins = get_dbusPlugins()
        if 'graphtft' in plugins:
            #print "found graphtft"
            self.graphtft = True
        else:
            self.graphtft = False


    def get_event_devices(self):
        '''filter all connected input devices and watch those not used by eventlircd'''
        for device in self.context.list_devices(subsystem='input',ID_INPUT_KEYBOARD=True):
            if device.sys_name.startswith('event') and not (('eventlircd_enable' in device) or ('eventlircd_enable' in device and device['eventlircd_enable'] is ('true'))):
                self.paths[device['DEVNAME']] = open(device['DEVNAME'],'rb')
                syslog.syslog(codecs.encode(u"watching %s: %s"%(device.parent['NAME'], device['DEVNAME']),'utf-8'))
                self.devices[device['DEVNAME']] = gobject.io_add_watch(self.paths[device['DEVNAME']], gobject.IO_IN, self.evthandler)
        self.observer = GUDevMonitorObserver(self.monitor)
        self.observer.connect('device-event',self.udev_event)
        self.monitor.start()
        syslog.syslog("started udev monitoring of input devices")

    def udev_event(self,observer,action, device):
        '''callback function to add/remove input devices'''
        if action == "add" and 'DEVNAME' in device:
            syslog.syslog("added %s"%device['DEVNAME'])
            if not "eventlircd_enable" in device:
                self.paths[device['DEVNAME']] = open(device['DEVNAME'],'rb')
                syslog.syslog(codecs.encode(u"watching %s: %s - %s"%(device.parent['NAME'], device['DEVNAME'],self.paths[device['DEVNAME']]),'utf-8'))
                self.devices[device['DEVNAME']] = gobject.io_add_watch(self.paths[device['DEVNAME']], gobject.IO_IN, self.evthandler)
        elif action == "remove" and 'DEVNAME' in device:
            try:
	            self.paths[device['DEVNAME']].close()
            except:
                pass
            try:
                gobject.source_remove(self.devices[device['DEVNAME']])
                syslog.syslog("removed %s"%device['DEVNAME'])
            except: pass #device already removed from watchlist

    def GetActiveWindowTitle(self):
        '''get title of active window'''
        return subprocess.Popen(["xprop", "-id", subprocess.Popen(["xprop", "-root", "_NET_ACTIVE_WINDOW"], stdout=subprocess.PIPE, env=settings.env).communicate()[0].strip().split()[-1], "WM_NAME"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].strip().split('"', 1)[-1][:-1]

    def evthandler(self,path, *args):
        '''callback function to handle keys sent by inputdevices'''
        try:
            event = path.read(self.inputEventSize)
        except:
            syslog.syslog('can not read from %s'%(path))
            return False
        (time1, time2, typeev, code, value) = struct.unpack(self.inputEventFormat, event)
        
        if typeev == 1 and code == 115: # code 115 = KEY_VOLUMEUP
           remote.sendkey("Volume+") 
	if typeev == 1 and code == 114: # code 115 = KEY_VOLUMEDOWN
           remote.sendkey("Volume-")
        if typeev == 1 and code == 113 and value == 1: # code 115 = KEY_MUTE
           remote.sendkey("Mute")
        if typeev == 1 and code == 172 and value == 1: # code 172 = KEY_HOMEPAGE - toggle frontend (attach/detach) 
           if self.frontend_active == 1:
               syslog.syslog("detached frontend")
               detach()
           elif self.frontend_active == 0:
               syslog.syslog("attached frontend")
               resume(frontend.status())
        if self.frontend_active == 0:
           if typeev == 1 and code == 28 and self.GetActiveWindowTitle() == 'WM_NAM': # resume frontend on KEY_ENTER if no window has focus
               syslog.syslog("frontend attached by keyboard activity")
               resume(frontend.status())
        return True

        
    def updateDisplay(self):
        self.env["DISPLAY"] = <?cs alt:desktop_display ?>":0"<?cs /alt ?>+self.getTempDisplay()
        
    def getTempDisplay(self):
        tempdisplay = subprocess.check_output(["dbget","vdr.tempdisplay"])
        if len(tempdisplay) == 0:
            tempdisplay = ".0"
        return tempdisplay

    def check_acpi(self):
        timestr = open('/var/cache/vdr/acpiwakeup.time.old','r').read().splitlines()[0]
        wakeup = datetime.datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S")
        now = datetime.datetime.utcnow()
        syslog.syslog(u"acip-wakeup.time.old hatte Wert: %s"%(wakeup.ctime()))
        syslog.syslog(u"vergleiche mit jetzt: %s"%(now.ctime()))
        if wakeup < now:
            d = now - wakeup
        else:
            d = wakeup - now
        if d.seconds > 360:
            syslog.syslog("assuming manual start")
            return False
        else:
            syslog.syslog("assuming start for acpi-wakeup")
            return True
Ejemplo n.º 13
0
 def create_observer(self, monitor):
     from pyudev.glib import GUDevMonitorObserver
     self.observer = GUDevMonitorObserver(monitor)
Ejemplo n.º 14
0
BIN=os.path.join(DEVDIR, "autoimport.sh")

def device_added_callback(device, event, b):

    if event != "add":
        return
    if b['ID_MODEL'] != "CP2104_USB_to_UART_Bridge_Controller":
        return

    if not os.path.exists(DESTDIR):
        os.makedirs(DESTDIR)
    os.chdir(DESTDIR)
    os.system("gnome-terminal --window --working-directory='%s' --profile=keep-open --title 'Importing gps track to %s' --command '%s %s'" % (DESTDIR, DESTDIR, BIN, b['DEVNAME']))



context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem = 'tty')

observer = MonitorObserver(monitor)

observer.connect('device-event', device_added_callback)
monitor.start();

os.system("notify-send --expire-time=5000 'starting tcx auto importer'")

mainloop = gobject.MainLoop();
mainloop.run()

Ejemplo n.º 15
0
wiifus.connect('activate', wiifus_callback)
menu.append(wiifus)
wiifus.show()
tmp = gtk.MenuItem('Quit')
tmp.connect('activate', gtk.main_quit)
menu.append(tmp)
tmp.show()

# HANDLE CONNECT AND DISCONNECT OF THE PERSWITCH
# Find out the device path of our perswitch
context = Context()
handle_resume_callback()

# Monitor changes to the connection status of perswitch
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
observer = GUDevMonitorObserver(monitor)
observer.connect('device-added', perswitch_added_callback)
observer.connect('device-removed', perswitch_removed_callback)
monitor.enable_receiving()

# Detect hibernate/resume
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
bus.add_signal_receiver(handle_resume_callback, 'Resuming',
                        'org.freedesktop.UPower', 'org.freedesktop.UPower')

# USE THE WHOLE THING
ind.set_menu(menu)
gtk.main()