コード例 #1
0
ファイル: test_monitor.py プロジェクト: dwlehman/pyudev
 def test_from_netlink_source_udev(self, context):
     monitor = Monitor.from_netlink(context)
     assert monitor._as_parameter_
     assert not monitor.started
     monitor = Monitor.from_netlink(context, source='udev')
     assert monitor._as_parameter_
     assert not monitor.started
コード例 #2
0
 def test_from_netlink_source_udev(self, context):
     monitor = Monitor.from_netlink(context)
     assert monitor._as_parameter_
     assert not monitor.started
     monitor = Monitor.from_netlink(context, source='udev')
     assert monitor._as_parameter_
     assert not monitor.started
コード例 #3
0
ファイル: test_monitor.py プロジェクト: csleex/pyudev
 def test_from_netlink_source_udev_mock(self, context):
     calls = {'udev_monitor_new_from_netlink':
              [(context, b'udev'), (context, b'udev')]}
     with pytest.calls_to_libudev(calls):
         libudev.udev_monitor_new_from_netlink.return_value = sentinel.monitor
         monitor = Monitor.from_netlink(context)
         assert monitor._as_parameter_ is sentinel.monitor
         assert not monitor.started
         monitor = Monitor.from_netlink(context, 'udev')
         assert monitor._as_parameter_ is sentinel.monitor
         assert not monitor.started
コード例 #4
0
ファイル: test_monitor.py プロジェクト: lanstat/pyudev
 def test_from_socket_mock(self, context, socket_path):
     socket_path = str(socket_path)
     new_from_socket = 'udev_monitor_new_from_socket'
     with pytest.patch_libudev(new_from_socket) as new_from_socket:
         new_from_socket.return_value = mock.sentinel.pointer
         monitor = Monitor.from_socket(context, socket_path)
         new_from_socket.assert_called_with(
             context, socket_path.encode(sys.getfilesystemencoding()))
         assert monitor._as_parameter_ is mock.sentinel.pointer
         Monitor.from_socket(context, 'foobar')
         new_from_socket.assert_called_with(context, b'foobar')
         assert isinstance(new_from_socket.call_args[0][1], bytes)
コード例 #5
0
 def test_from_netlink_source_udev_mock(self, context):
     calls = {
         'udev_monitor_new_from_netlink': [(context, b'udev'),
                                           (context, b'udev')]
     }
     with pytest.calls_to_libudev(calls):
         libudev.udev_monitor_new_from_netlink.return_value = sentinel.monitor
         monitor = Monitor.from_netlink(context)
         assert monitor._as_parameter_ is sentinel.monitor
         assert not monitor.started
         monitor = Monitor.from_netlink(context, 'udev')
         assert monitor._as_parameter_ is sentinel.monitor
         assert not monitor.started
コード例 #6
0
 def test_from_netlink_source_udev_mock(self, context):
     funcname = "udev_monitor_new_from_netlink"
     spec = lambda c, s: None
     with mock.patch.object(context._libudev, funcname,
                            autospec=spec) as func:
         func.return_value = mock.sentinel.monitor
         monitor = Monitor.from_netlink(context)
         assert monitor._as_parameter_ is mock.sentinel.monitor
         assert not monitor.started
         func.assert_called_once_with(context, b"udev")
         func.reset_mock()
         monitor = Monitor.from_netlink(context, "udev")
         assert monitor._as_parameter_ is mock.sentinel.monitor
         assert not monitor.started
         func.assert_called_once_with(context, b"udev")
コード例 #7
0
ファイル: test_monitor.py プロジェクト: dwlehman/pyudev
 def test_from_netlink_source_udev_mock(self, context):
     funcname = 'udev_monitor_new_from_netlink'
     spec = lambda c, s: None
     with mock.patch.object(context._libudev, funcname,
                            autospec=spec) as func:
         func.return_value = mock.sentinel.monitor
         monitor = Monitor.from_netlink(context)
         assert monitor._as_parameter_ is mock.sentinel.monitor
         assert not monitor.started
         func.assert_called_once_with(context, b'udev')
         func.reset_mock()
         monitor = Monitor.from_netlink(context, 'udev')
         assert monitor._as_parameter_ is mock.sentinel.monitor
         assert not monitor.started
         func.assert_called_once_with(context, b'udev')
コード例 #8
0
    def __init__(self, player):
        try:
            self.player = player
            
             # Create a context, create monitor at kernel level, select devices
            context = Context()
            monitor = Monitor.from_netlink(context)
            monitor.filter_by(subsystem='input')

            self.observer = MonitorObserver(monitor, self.usb_event_callback, name="keyboard")
            self.observer.start()

            self.pressed = False    # Stores state of press
            
            # Check if there is already a keyboard attached
            for device in context.list_devices(subsystem='input'):
                if device.get('ID_INPUT_KEYBOARD') == '1':
                    if device.get('DEVNAME') != None:
                        device_name = InputDevice(device.get('DEVNAME'))
                        thread = threading.Thread(target=self.keyboard_event, args=(device_name,), daemon=True)
                        thread.start()
                        continue


        except Exception as ex:
            print('Keyboard Control: Error starting: ' + str(ex))
コード例 #9
0
ファイル: notify.py プロジェクト: matthewelse/lmtools
 def __init__(self):
     self.context = Context()
     self.monitor = Monitor.from_netlink(self.context)
     self.monitor.filter_by(subsystem='usb')
     self.observer = MonitorObserver(
         self.monitor, callback=self.event_handler, name="blahblah")
     self.observer.daemon = True
コード例 #10
0
def main2():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='input')
    observer = MonitorObserver(monitor)
    observer.connect('device-event', device_event)
    monitor.start()
コード例 #11
0
 def __init__(self, callback):
     # set up udev device monitor
     context = Context()
     self._monitor = Monitor.from_netlink(context)
     self._monitor.filter_by(subsystem='sound')
     self._observer = MonitorObserver(self._monitor)
     self._observer.connect('device-event', callback)
コード例 #12
0
    async def monitor_start(self):
        """
        Start watching for device changes

        Listen for relevant add/remove events from udev and fire callbacks.
        """

        if self._monitor:
            return

        udev_monitor = Monitor.from_netlink(self._udev_context)
        udev_monitor.filter_by_tag('uchroma')
        udev_monitor.filter_by(subsystem='usb', device_type=u'usb_device')

        self._udev_observer = AsyncMonitorObserver(udev_monitor,
                                                   callback=self._udev_event,
                                                   name='uchroma-monitor')
        ensure_future(self._udev_observer.start())
        self._monitor = True

        if self._callbacks:
            for device in self._devices.values():
                ensure_future(self._fire_callbacks('add', device),
                              loop=self._loop)

        self._logger.debug('Udev monitor started')
コード例 #13
0
    def run(self):
        try:
            try:
                from pyudev.glib import MonitorObserver

                def device_event(observer, device):
                    self.sessaoMultiseat.evento_dispositivo(
                        device.action, device.device_path)
            except:
                from pyudev.glib import GUDevMonitorObserver as MonitorObserver

                def device_event(observer, action, device):
                    self.sessaoMultiseat.evento_dispositivo(
                        action, device.device_path)

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

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

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

            self.loop.run()
        except:
            logging.exception('')
コード例 #14
0
 def _init_udev_monitor(self):
     self._udev_context = Context()
     udev_monitor = Monitor.from_netlink(self._udev_context)
     udev_monitor.filter_by(subsystem='hid')
     self._udev_observer = MonitorObserver(udev_monitor,
                                           callback=self._udev_input_event,
                                           name='device-monitor')
コード例 #15
0
def initialize():
	context = Context()
	monitor = Monitor.from_netlink(context)
	monitor.filter_by(subsystem='tty')
	observer = MonitorObserver(monitor, callback=print_device_event, name = 'monitor-observer')
	observer.daemon
	observer.start()
コード例 #16
0
    async def _async_start_monitor(self) -> None:
        """Start monitoring hardware with pyudev."""
        if not sys.platform.startswith("linux"):
            return
        info = await system_info.async_get_system_info(self.hass)
        if info.get("docker"):
            return

        from pyudev import (  # pylint: disable=import-outside-toplevel
            Context, Monitor, MonitorObserver,
        )

        try:
            context = Context()
        except (ImportError, OSError):
            return

        monitor = Monitor.from_netlink(context)
        try:
            monitor.filter_by(subsystem="tty")
        except ValueError as ex:  # this fails on WSL
            _LOGGER.debug(
                "Unable to setup pyudev filtering; This is expected on WSL: %s",
                ex)
            return
        observer = MonitorObserver(monitor,
                                   callback=self._device_discovered,
                                   name="usb-observer")
        observer.start()
        self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                        lambda event: observer.stop())
        self.observer_active = True
コード例 #17
0
    def disk_src(self):
        try:
            from pyudev.glib import MonitorObserver

            def device_event(observer, device):
                print 'event {0} on device {1}'.format(device.action, device)
                if device.action == "add":
                    manager.disk_mnt(context)
                elif device.action == "remove":
                    manager.disk_umnt(device)
        except:
            from pyudev.glib import GUDevMonitorObserver as MonitorObserver

            def device_event(observer, action, device):
                print 'event {0} on device {1}'.format(action, device)
                if action == "add":
                    manager.disk_mnt(context)
                elif action == "remove":
                    manager.disk_umnt(device)
        context = Context()
        manager = Storage(self.cfg, self.log)
        monitor = Monitor.from_netlink(context)
        monitor.filter_by(subsystem='block', device_type='partition')
        observer = MonitorObserver(monitor)
        observer.connect('device-event', device_event)
        monitor.start()
        glib.MainLoop().run()
コード例 #18
0
ファイル: main.py プロジェクト: romanz/trezor-tray
 def _observe(self):
     self.context = Context()
     self.monitor = Monitor.from_netlink(self.context)
     self.monitor.filter_by(subsystem='hid')
     self.observer = MonitorObserver(self.monitor)
     self.observer.deviceEvent.connect(self.on_device_event)
     self.monitor.start()
コード例 #19
0
 def setupUdevMonitor(self, filter_subsystem='usb'):
     logger.debug('Setting up udev context...')
     self.udev_context = Context()
     logger.debug('Setting up monitor context...')
     self.udev_monitor = Monitor.from_netlink(self.udev_context)
     logger.debug('Setting up monitor filter...')
     self.udev_monitor.filter_by(subsystem=filter_subsystem)
コード例 #20
0
    def wait(self, on_new_device_attached_callback):
        context = Context()
        monitor = Monitor.from_netlink(context)
        monitor.filter_by("usb")

        while True:
            device = monitor.poll()

            if device.get("ACTION", "") == "remove":
                continue

            if device.get("DEVTYPE", "") != "usb_device":
                continue

            # system devices
            pattern = Manager.get_device_pattern(section="system_devices", device=device)
            if pattern in self.model["system_devices"]:
                print("System device plugged in: {}".format(pattern))
                continue

            # if device in blacklist
            pattern = Manager.get_device_pattern(section="blacklist_devices", device=device)
            if pattern in self.model["blacklist_devices"]:
                print("Blacklist-device plugged in: {}".format(pattern))
                continue

            # if device in whitelist
            pattern = Manager.get_device_pattern(section="whitelist_devices", device=device)
            if pattern in self.model["whitelist_devices"]:
                print("Whitelist-device plugged in: {}".format(pattern))
                continue

            on_new_device_attached_callback(device)
コード例 #21
0
def get_usb_devices():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')
    observer = MonitorObserver(monitor)
    observer.connect('device-event', device_event)
    monitor.start()
    glib.MainLoop().run()
コード例 #22
0
ファイル: camera.py プロジェクト: rrobe53/CameraSync
	def watch(self, filtername, callback):
		context = Context()
		monitor = Monitor.from_netlink(context)

		monitor.filter_by(filtername)

		observer = MonitorObserver(monitor, callback=callback, name="monitor-observer")
		observer.start()
コード例 #23
0
ファイル: CDMonitor.py プロジェクト: marcobakos/cd2cloud
 def __init__(self, func_name):
     """initialization"""
     self.log = getLogger(__name__)
     context = Context()
     monitor = Monitor.from_netlink(context)
     self.observer = MonitorObserver(monitor, callback=func_name,
                                name='monitor-observer')
     self.observer.daemon = False
コード例 #24
0
 def __registerUdevCallback(self):
     context = pyudev.Context()
     monitor = Monitor.from_netlink(context)
     monitor.filter_by(subsystem='block')
     observer = MonitorObserver(monitor,
                                callback=self.__checkUdevEvent,
                                name='monitor-observer')
     observer.start()
コード例 #25
0
    def start_observer(self):
        """ Start plug/unplug event observer """

        monitor = Monitor.from_netlink(self.context)
        monitor.filter_by(subsystem="block", device_type="partition")
        self.observer = MonitorObserver(monitor, callback=self.usb_event_handler)
        self.observer.start()
        logging.debug("Started USB drive plug/unplug observer")
コード例 #26
0
def start_udev_monitoring():
    #Setting up Linux UDEV monitoring in a separate thread
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='block')
    observer = MonitorObserver(monitor, callback=find_garmin, name='monitor-observer')
    observer.daemon = True
    observer.start()
コード例 #27
0
def monitor_background():
    c = Context()

    monitor = Monitor.from_netlink(c)
    monitor.filter_by("block", "disk")

    obs = MonitorObserver(monitor, device_event)
    obs.start()
コード例 #28
0
ファイル: udev_interactor.py プロジェクト: leinardi/gx52
 def monitor_device_events(self, callback: Callable) -> None:
     self._callback = callback
     context = Context()
     monitor = Monitor.from_netlink(context)
     monitor.filter_by(subsystem='input')
     observer = MonitorObserver(monitor)
     observer.connect('device-event', self.device_event)
     monitor.start()
コード例 #29
0
ファイル: usb.py プロジェクト: AlexeiBuzuma/IPD
def set_monitor_func(func):
    global HANDLER
    HANDLER = func
    udev_context = Context()
    monitor = Monitor.from_netlink(udev_context)
    monitor.filter_by('block')
    observer = MonitorObserver(monitor, log_event)
    observer.start()
コード例 #30
0
def poll(callback):
    """Invoke callback upon udev activity."""
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='block')
    for dev in iter(monitor.poll, None):
        if 'ID_FS_TYPE' in dev:
            callback(dev)
コード例 #31
0
ファイル: test_monitor.py プロジェクト: lanstat/pyudev
 def test_enable_receiving_bound_socket(self, context, socket_path):
     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
     # cause an error by binding the socket, thus testing error handling in
     # this method
     sock.bind(str(socket_path))
     monitor = Monitor.from_socket(context, str(socket_path))
     with pytest.raises(EnvironmentError) as exc_info:
         monitor.enable_receiving()
     pytest.assert_env_error(exc_info.value, errno.EADDRINUSE, str(socket_path))
コード例 #32
0
def initialize():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='tty')
    observer = MonitorObserver(monitor,
                               callback=print_device_event,
                               name='monitor-observer')
    observer.daemon
    observer.start()
コード例 #33
0
ファイル: donglelock.py プロジェクト: tenderitaf/fittools
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()
コード例 #34
0
ファイル: donglelock.py プロジェクト: cryptax/fittools
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()
コード例 #35
0
ファイル: test_monitor.py プロジェクト: lanstat/pyudev
def _assert_from_netlink_called(context, *args):
    new_from_netlink = 'udev_monitor_new_from_netlink'
    with pytest.patch_libudev(new_from_netlink) as new_from_netlink:
        source = args[0].encode('ascii') if args else b'udev'
        new_from_netlink.return_value = mock.sentinel.pointer
        monitor = Monitor.from_netlink(context, *args)
        new_from_netlink.assert_called_with(context, source)
        assert isinstance(new_from_netlink.call_args[0][1], bytes)
        assert monitor._as_parameter_ is mock.sentinel.pointer
コード例 #36
0
ファイル: pydle.py プロジェクト: claudemuller/pydle
    def _listenOnUsb(self):
        context = Context()
        monitor = Monitor.from_netlink(context)

        monitor.filter_by(subsystem="usb")
        observer = MonitorObserver(monitor)
        observer.connect("device-event", self._deviceEvent)
        monitor.start()

        glib.MainLoop().run()
コード例 #37
0
def main():
    """ main() -- entry point for this program
    """
    global SEND_SMS
    global DAEMONIZE
    global PID_FILE

    # Parse CLI options
    args = parse_cli()

    DAEMONIZE = args.daemonize
    PID_FILE = args.pid_file
    SEND_SMS = args.sms

    context = Context()

    # Populate list of current USB devices
    for device in context.list_devices(subsystem="usb"):
        busnum = get_device_info(device, "busnum")
        devnum = get_device_info(device, "devnum")
        id_product = get_device_info(device, "idProduct")
        id_vendor = get_device_info(device, "idVendor")
        manufacturer = get_device_info(device, "manufacturer")
        product = get_device_info(device, "product")

        if busnum:
            USB_DEVICES.append((device.device_path, busnum, devnum, id_vendor,
                                id_product, manufacturer, product))

    monitor = Monitor.from_netlink(context)

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

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

    if DAEMONIZE:
        usbwatch_pid = os.fork()

        if usbwatch_pid != 0:
            return os.EX_OK

    write_pid_file(PID_FILE, os.getpid())

    xprint("[+] usb-watch by Daniel Roberson @dmfroberson Started. PID %s" % \
        os.getpid())

    try:
        glib.MainLoop().run()
    except KeyboardInterrupt:
        print "[-] Caught Control-C. Andross has ordered us to take you down."
        print "[-] Exiting."

    return os.EX_OK
コード例 #38
0
ファイル: udev.py プロジェクト: Nek-/Solaar
def monitor(callback, *device_filters):
	m = _Monitor.from_netlink(_Context())
	m.filter_by(subsystem='hidraw')
	for action, device in m:
		hid_dev = device.find_parent('hid')
		if hid_dev:
			for filter in device_filters:
				dev_info = _match(device, hid_dev, *filter)
				if dev_info:
					callback(action, dev_info)
					break
コード例 #39
0
ファイル: hidraw.py プロジェクト: Vash63/ds4drv
    def _get_future_devices(self, context):
        """Return a generator yielding new devices."""
        monitor = Monitor.from_netlink(context)
        monitor.filter_by("hidraw")
        monitor.start()

        self._scanning_log_message()
        for device in iter(monitor.poll, None):
            if device.action == "add":
                yield device
                self._scanning_log_message()
コード例 #40
0
    def initialise(self):
        self.context = Context()

        self.monitor = Monitor.from_netlink(self.context)
        self.monitor.filter_by(subsystem='block')

        self.observer = MonitorObserver(self.monitor)
        self.observer.deviceEvent.connect(self._onDeviceEvent)
        self.monitor.start()

        self.updateRemovableDevices()
コード例 #41
0
ファイル: Main.py プロジェクト: RicherMans/USBWriter
def loopForDevices():
    context = Context()
    monitor = Monitor.from_netlink(context)
    
    monitor.filter_by(subsystem='block',device_type='partition')
#     monitor.filter_by(subsystem='usb')
    observer = MonitorObserver(monitor)
    
    observer.connect('device-event', device_event)
    monitor.start()
    glib.MainLoop().run()
コード例 #42
0
def startListener():
    # create a context, create monitor at kernel level, select devices
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='block')

    observer = MonitorObserver(monitor, usbEventCallback, name="usbdev")
    # set this as the main thread
    observer.setDaemon(False)
    observer.start()

    return observer
コード例 #43
0
ファイル: hidraw.py プロジェクト: kilomeow/ds4drv
    def add_device_observer(self, handler):
        monitor = Monitor.from_netlink(self.context)
        monitor.filter_by("hidraw")

        def trigger_event(action, device):
            if action != 'add': return
            dev = HidrawBackend.catchHidrawDevice(device)
            if dev is None: return
            return handler(self.constructDevice(dev))

        observer = MonitorObserver(monitor, trigger_event)
        return observer
コード例 #44
0
def monitor_bt_headset(**config):
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by('input')
    while True:
        led0_headset_off()
        sys_path, device_node = wait_bt_headset_add(monitor,
                                                    config['headset_addr'])
        pa_lo_idx = start_sound_forwarding(device_node=device_node, **config)
        led0_headset_on()
        wait_bt_headset_remove(monitor, sys_path)
        stop_sound_forwarding(pa_lo_idx=pa_lo_idx, **config)
コード例 #45
0
def main():
    app = QCoreApplication(sys.argv)
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='input')
    observer = QUDevMonitorObserver(monitor)
    observer.deviceAdded.connect(
        partial(print_mouse_status, status_message="added"))
    observer.deviceRemoved.connect(
        partial(print_mouse_status, status_message="removed"))
    monitor.start()

    app.exec_()
コード例 #46
0
def main():
    app = QCoreApplication(sys.argv)
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='input')
    observer = QUDevMonitorObserver(monitor)
    observer.deviceAdded.connect(
        partial(print_mouse_status, status_message="added"))
    observer.deviceRemoved.connect(
        partial(print_mouse_status, status_message="removed"))
    monitor.start()

    app.exec_()
コード例 #47
0
def monitor():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by('input')
    monitor.filter_by('usb')
    # polls forever
    for device in iter(monitor.poll, None):
        # Inserting the yubikey generates several 'add' events, but we don't
        # want to remap on every one of them.  So filter out a single one, wait
        # a bit for things to settle, and remap.
        if device.action == 'add' and match(r'.*input\d+$', device.device_path):
            sleep(2)
            remap()
コード例 #48
0
    def __init__(self):
        """
        Start listening for storage events.
        """

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

        monitor.filter_by(subsystem='block')
        monitor_observer = MonitorObserver(monitor)

        monitor_observer.connect('device-event', self._device_event)
        monitor.start()
コード例 #49
0
ファイル: udev.py プロジェクト: doctor64/Solaar
def monitor_glib(callback, *device_filters):
    from gi.repository import GLib

    c = _Context()

    # already existing devices
    # for device in c.list_devices(subsystem='hidraw'):
    #     # print (device, dict(device), dict(device.attributes))
    #     for filter in device_filters:
    #         d_info = _match('add', device, *filter)
    #         if d_info:
    #             GLib.idle_add(callback, 'add', d_info)
    #             break

    m = _Monitor.from_netlink(c)
    m.filter_by(subsystem='hidraw')

    def _process_udev_event(monitor, condition, cb, filters):
        if condition == GLib.IO_IN:
            event = monitor.receive_device()
            if event:
                action, device = event
                # print ("***", action, device)
                if action == 'add':
                    for filter in filters:
                        d_info = _match(action, device, filter)
                        if d_info:
                            GLib.idle_add(cb, action, d_info)
                            break
                elif action == 'remove':
                    # the GLib notification does _not_ match!
                    pass
        return True

    try:
        # io_add_watch_full may not be available...
        GLib.io_add_watch_full(m, GLib.PRIORITY_LOW, GLib.IO_IN,
                               _process_udev_event, callback, device_filters)
        # print ("did io_add_watch_full")
    except AttributeError:
        try:
            # and the priority parameter appeared later in the API
            GLib.io_add_watch(m, GLib.PRIORITY_LOW, GLib.IO_IN,
                              _process_udev_event, callback, device_filters)
            # print ("did io_add_watch with priority")
        except Exception:
            GLib.io_add_watch(m, GLib.IO_IN, _process_udev_event, callback,
                              device_filters)
            # print ("did io_add_watch")

    m.start()
コード例 #50
0
ファイル: udev.py プロジェクト: Linlin7/BatteryBud
    def __init__(self):
        self.context = Context()
        self.monitor = Monitor.from_netlink(self.context)
        self.monitor.filter_by('power_supply')

        self.percent_callback = None
        self.status_callback = None

        (self.battery, self.line_power) = self.find_devices()

        if not self.battery:
            raise BatteryNotFoundError()

        if not self.line_power:
            raise LinePowerNotFoundError()

        self.last_percent = -1
        self.last_status = None

        def on_udev_event(device):
            if device == self.battery:
                self.battery = device
                percent = self.get_percent()
                if percent != self.last_percent:
                    self.last_percent = percent
                    if self.percent_callback:
                        GLib.idle_add(self.percent_callback, percent)

            elif device == self.line_power:
                self.line_power = device
                status = self.get_status()
                if status != self.last_status:
                    self.last_status = status
                    if self.status_callback:
                        GLib.idle_add(self.status_callback, status)

        # XXX I can't get udev (or acpi) to give me battery discharge events
        # without requiring system configuration so we have to poll
        interval = 20000

        def poll_udev():
            battery = Device.from_path(self.context, self.battery.device_path)
            on_udev_event(battery)
            GLib.timeout_add(interval, poll_udev)

        GLib.timeout_add(interval, poll_udev)

        self.observer = MonitorObserver(self.monitor, callback=on_udev_event)

        self.observer.start()
コード例 #51
0
ファイル: udev.py プロジェクト: siwenhu/test_client_broadcast
 def monitor_async(self, subsystems, device_type, callbak):
     context = Context()
     monitor = Monitor.from_netlink(context)
     monitor.filter_by(subsystems)
     def device_event(device):
         self.emit(SIGNAL("signal_udev"), device)
         if callbak != None:
             callbak(device)
     try:
         self.observer = MonitorObserver(monitor, callback=device_event, name='udev-monitor-observer')
         self.observer.daemon
         self.observer.start()
         #observer.stop()
     except Exception as e:
         LogRecord.instance().logger.info(u'USB监听启动异常(%s)'%(str(e)))
コード例 #52
0
    def start_udev_tasks(self):
        """Start monitoring system devices using udev."""

        def udev_handler(action, device):
            if device.subsystem in ('net', 'block'):
                self.raise_event((action, device.subsystem), device)
                self.raise_event((action, device.subsystem, device.sys_name), device)

        # Monitor interesting system events.
        self.monitor = Monitor.from_netlink(self.udev)
        self.observer = MonitorObserver(self.monitor, from_thread(udev_handler))
        self.observer.start()

        # Trigger missed events.
        reactor.callLater(0, self.raise_missed_udev_events)
コード例 #53
0
ファイル: udev.py プロジェクト: 3v1n0/Solaar
def monitor_glib(callback, *device_filters):
	from gi.repository import GLib

	c = _Context()

	# already existing devices
	# for device in c.list_devices(subsystem='hidraw'):
	# 	# print (device, dict(device), dict(device.attributes))
	# 	for filter in device_filters:
	# 		d_info = _match('add', device, *filter)
	# 		if d_info:
	# 			GLib.idle_add(callback, 'add', d_info)
	# 			break

	m = _Monitor.from_netlink(c)
	m.filter_by(subsystem='hidraw')

	def _process_udev_event(monitor, condition, cb, filters):
		if condition == GLib.IO_IN:
			event = monitor.receive_device()
			if event:
				action, device = event
				# print ("***", action, device)
				if action == 'add':
					for filter in filters:
						d_info = _match(action, device, *filter)
						if d_info:
							GLib.idle_add(cb, action, d_info)
							break
				elif action == 'remove':
					# the GLib notification does _not_ match!
					pass
		return True

	try:
		# io_add_watch_full may not be available...
		GLib.io_add_watch_full(m, GLib.PRIORITY_LOW, GLib.IO_IN, _process_udev_event, callback, device_filters)
		# print ("did io_add_watch_full")
	except AttributeError:
		try:
			# and the priority parameter appeared later in the API
			GLib.io_add_watch(m, GLib.PRIORITY_LOW, GLib.IO_IN, _process_udev_event, callback, device_filters)
			# print ("did io_add_watch with priority")
		except:
			GLib.io_add_watch(m, GLib.IO_IN, _process_udev_event, callback, device_filters)
			# print ("did io_add_watch")

	m.start()
コード例 #54
0
ファイル: usbmonitor.py プロジェクト: efalive/efalive
    def __init__(self, add_callback, remove_callback = None, change_callback = None, for_gui = False):
        self._logger = logging.getLogger('efalive.UsbStorageMonitor')

        self._external_add_callback = add_callback
        self._external_remove_callback = remove_callback
        self._external_change_callback = change_callback

        self._udev_context = Context()
        self._udev_monitor = Monitor.from_netlink(self._udev_context)
        self._udev_monitor.filter_by('block', device_type='partition')
        self._for_gui = for_gui
        if for_gui:
            self._udev_observer = UdevGuiObserver(self._udev_monitor)
            self._udev_observer.connect('device-event', self._handle_gui_device_event)
        else:
            self._udev_observer = UdevObserver(self._udev_monitor, callback=self._handle_device_event, name='monitor-observer')
コード例 #55
0
ファイル: hidraw.py プロジェクト: jb55/ds4drv
    def _get_future_devices(self, context):
        """Return a generator yielding new devices."""
        monitor = Monitor.from_netlink(context)
        monitor.filter_by("hidraw")
        monitor.start()

        self._scanning_log_message()
        for device in iter(monitor.poll, None):
            if device.action == "add":
                # Sometimes udev rules has not been applied at this point,
                # causing permission denied error if we are running in user
                # mode. With this sleep this will hopefully not happen.
                sleep(1)

                yield device
                self._scanning_log_message()
コード例 #56
0
ファイル: udev.py プロジェクト: jawed123/shell
def main():
    try:
        from pyudev.glib import MonitorObserver
        def device_event(observer, device):
            remap_pokerii(device)
            remap_filco(device)
    except:
        from pyudev.glib import GUDevMonitorObserver as MonitorObserver
        def device_event(observer, action, device):
            remap_pokerii(device)
            remap_filco(device)

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

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

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

    glib.MainLoop().run()
コード例 #57
0
ファイル: scoddaemon.py プロジェクト: elemc/scod
 def start_listen(self):
     self.monitor = Monitor.from_netlink(self.context)
     for action, device in self.monitor:
         self._new_device(action, device)
コード例 #58
0
ファイル: pyudev_demo_4.py プロジェクト: Br3nda/meetings
if __name__ == "__main__":
    # Create a wx.GUI window with text.
    app = wx.App()
    frame = wx.Frame(None, -1, MESSAGE_1, size=(350,150))
    panel = wx.Panel(frame)
    sizer = wx.GridBagSizer(5, 5)
    text1 = wx.TextCtrl(panel, pos=(3, 3), size=(320, 130), style=wx.TE_MULTILINE)
    text1.AppendText(MESSAGE_2)
    sizer.Add(text1, pos=(0, 1), span=(1, 5), flag=wx.TOP|wx.EXPAND, border=5)
    panel.SetSizer(sizer)
    frame.Show()

    # Establish the monitoring and callback to the function device_event()
    context = Context()
    #Create a monitor by connecting to the kernel daemon through netlink
    monitor = Monitor.from_netlink(context, source=u'udev')

    # Filtering
    #monitor.filter_by(subsystem='input')

    observer = MonitorObserver(monitor)

    observer.Bind(EVT_DEVICE_EVENT, device_event)
    monitor.start()

    # Use the wx loop
    app.MainLoop()

'''
Notes:
コード例 #59
0
from pyudev import Context, Monitor
import glib
import gobject
import pyudev.glib

context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='input')
observer = pyudev.glib.GUDevMonitorObserver(monitor)

def device_event(observer, device):
	print('event {0} on device {1}'.format(device.action, device))

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

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

# this is a comment for dumbasses