class Udev(QObject): def __init__(self): super(Udev, self).__init__() 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))) def monitorStop(self): try: self.observer.stop() except Exception as e: pass
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
def main(): lcd.lcd_init() #initialize lcd display in preparation for sending messages setConfiguration( ) #query configuration and set remote properties for testing against context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='tty') observer = MonitorObserver(monitor, device_event) observer.start() while True: n = input("Jeelink Tester v 1.0 type 'stop' to end\n") if n == 'stop': observer.stop() lcd.cleanup() break
class CDMonitor(): """ Monitor Kernel events asynchronously for CD (drive) and CDROM (media) and trigger the CD2Cloud process """ 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 def start(self): """Start monitor""" self.observer.start() self.log.info('Started CD2Cloud monitor... listening for CD events') def stop(self): """Stop monitor""" self.observer.stop() self.log.info('Stopped CD2Cloud monitor')
class UsbStorageMonitor(object): """ USB storage device add monitor This monitor is listening to UDEV for USB storage device 'add' events. The callback that is provided to the constructor is called for every USB storage device that is added to the system. """ 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') def start(self): if self._for_gui: self._udev_monitor.start() else: self._udev_observer.start() def stop(self): if self._for_gui: self._udev_monitor.stop() else: self._udev_observer.stop() def _handle_gui_device_event(self, observer, device): self._handle_device_event(device) def _handle_device_event(self, device): self._debug_device(device) if (device.get("ID_BUS") != "usb"): return self._logger.info("Action %s for device %s" % (device.action, device.device_node)) if device.action == "add": wrapped_device = self._wrap_device(device) self._external_add_callback(wrapped_device) elif device.action == "remove" and self._external_remove_callback != None: wrapped_device = self._wrap_device(device) self._external_remove_callback(wrapped_device) elif device.action == "change" and self._external_change_callback != None: wrapped_device = self._wrap_device(device) self._external_change_callback(wrapped_device) else: self._logger.info("Unhandled action: %s" % device.action) def _debug_device(self, device): self._logger.debug("Device:") self._logger.debug("\tSubsystem: %s" % device.subsystem) self._logger.debug("\tType: %s" % device.device_type) self._logger.debug("\tName: %s" % device.sys_name) self._logger.debug("\tNumber: %s" % device.sys_number) self._logger.debug("\tSYS-fs path: %s" % device.sys_path) self._logger.debug("\tDriver: %s" % device.driver) self._logger.debug("\tAction: %s" % device.action) self._logger.debug("\tFile: %s" % device.device_node) #self._logger.debug("\tLinks: %s" % device.get_device_file_symlinks()) #self._logger.debug("\tProperties: %s" % device.get_property_keys()) #self._logger.debug("\tSYBSYSTEM: %s" % device.get_property("SUBSYSTEM")) #self._logger.debug("\tDEVTYPE: %s" % device.get_property("DEVTYPE")) ##self._logger.debug("\tID_VENDOR: %s" % device.get("ID_VENDOR")) self._logger.debug("\tID_SERIAL: %s" % device.properties.get("ID_SERIAL")) self._logger.debug("\tID_MODEL: %s" % device.get("ID_MODEL")) self._logger.debug("\tID_TYPE: %s" % device.get("ID_TYPE")) self._logger.debug("\tID_BUS: %s" % device.get("ID_BUS")) self._logger.debug("\tID_FS_LABEL: %s" % device.get("ID_FS_LABEL")) self._logger.debug("\tID_FS_TYPE: %s" % device.get("ID_FS_TYPE")) self._logger.debug("\tID_PART_ENTRY_SIZE: %s" % device.get("ID_PART_ENTRY_SIZE")) #self._logger.debug("All attributes:") #for attrName in device.__iter__(): # self._logger.debug(attrName) def _wrap_device(self, device): """ Convert a PyUdev device to an efaLive device """ if device is None: return None wrapped_device = UsbStorageDevice(device.device_node) if device.get("ID_VENDOR"): wrapped_device.vendor = device.get("ID_VENDOR") if device.get("ID_MODEL"): wrapped_device.model = device.get("ID_MODEL") if device.get("ID_PART_ENTRY_SIZE"): byte_size = float(device.get("ID_PART_ENTRY_SIZE")) size = byte_size / 1024 unit = "KB" if (size > 1024): size = size / 1024 unit = "MB" if (size > 1024): size = size / 1024 unit = "GB" if (size > 1024): size = size / 1024 unit = "TB" wrapped_device.size = "%.1f %s" % (size, unit) if device.get("ID_FS_TYPE"): wrapped_device.fs_type = device.get("ID_FS_TYPE") if device.get("ID_FS_LABEL"): wrapped_device.label = device.get("ID_FS_LABEL") if device.get("ID_VENDOR_ID") and device.get("ID_MODEL_ID"): wrapped_device.bus_id = "%s:%s" % (device.get("ID_VENDOR_ID"), device.get("ID_MODEL_ID")) if device.properties.get("ID_SERIAL"): wrapped_device.serial = device.properties.get("ID_SERIAL") return wrapped_device def search_for_usb_block_devices(self): for usb_device in self._udev_context.list_devices(subsystem='block', DEVTYPE='partition'): if (usb_device.get("ID_BUS") != "usb"): continue wrapped_device = self._wrap_device(usb_device) self._external_add_callback(wrapped_device)
if action == 'add': print('get a device') subprocess.call([DOWNLOAD_TOOL, DOWNLOAD_FILE]) GPIO.output(BLUE_LED, GPIO.HIGH) elif action == 'remove': print('device is removed') GPIO.output(BLUE_LED, GPIO.LOW) print('Auto download deamon') context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='block') observer = MonitorObserver(monitor, device_event) print('Start to detect usb mass storage') observer.start() try: while True: GPIO.output(GREEN_LED, GPIO.HIGH) sleep(1) GPIO.output(GREEN_LED, GPIO.LOW) sleep(1) except Exception as e: print(e) print('exit') GPIO.cleanup() observer.stop()
class USB_Session_Blocker(dbus.service.Object): # Create context context = Context() # Create monitor monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='usb', device_type='usb_device') def __init__(self): try: with open(expanduser("~") + '/.local/share/trusted_devices', 'rt') as f_in: try: self.trusted_devices = json.load(f_in) except ValueError: self.trusted_devices = [] except IOError: self.trusted_devices = [] self.usb_blocker = dbus.SystemBus().get_object( 'org.gnome.USBBlocker', '/org/gnome/USBBlocker') self.notifier = dbus.SessionBus().get_object( 'org.freedesktop.Notifications', '/org/freedesktop/Notifications') self.observer = None self.number_notifications = {} self.allowed_devices = [] bus_name = dbus.service.BusName('org.gnome.USBInhibit', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/org/gnome/USBInhibit') @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='', out_signature='b') def get_status(self): return self.usb_blocker.get_dbus_method( 'get_status', 'org.gnome.USBBlocker.inhibit')() @dbus.service.method(dbus_interface='org.gnome.USBInhibit') def start_inhibit(self): self.notification = self.notifier.get_dbus_method('Notify', \ 'org.freedesktop.Notifications') self.observer = MonitorObserver(self.monitor, callback=self.device_detected, name='monitor-usb-session') self.notifier.connect_to_signal('ActionInvoked', self.action_new_device) self.observer.daemon = True self.observer.start() print("Start monitoring Dbus session message") self.usb_blocker.get_dbus_method('start', 'org.gnome.USBBlocker.inhibit')() def action_new_device(self, id, action): if id in self.number_notifications: if action == "Allow": print "Allowed" bus_id, dev_id = self.number_notifications.pop(id) if self.usb_blocker.get_dbus_method( 'enable_device', 'org.gnome.USBBlocker.device')(bus_id, dev_id): self.trusted_devices.append(dev_id) self.write_trusted_devices() print(bus_id) print(dev_id) # If the action is Block then the device must remain blocked if action == "Block": print "Blocked" @dbus.service.method(dbus_interface='org.gnome.USBInhibit') def stop_inhibit(self): print("Stop monitoring Dbus session message") if self.observer != None: self.observer.stop() self.usb_blocker.get_dbus_method('stop', 'org.gnome.USBBlocker.inhibit')() @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='n', out_signature='') def add_nonblock_device(self, bDeviceClass): print("Add device with the bDeviceClass code " + str(bDeviceClass)) self.allowed_devices.append(bDeviceClass) @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='n', out_signature='') def remove_nonblock_device(self, bDeviceClass): print("Remove device with the bDeviceClass code " + str(bDeviceClass)) if bDeviceClass in self.allowed_devices: self.allowed_devices.remove(bDeviceClass) @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='', out_signature='s') def show_nonblock_devices(self): return str(self.allowed_devices) def device_detected(self, device): import usb.core bus_id = device.sys_name action = device.action # Check only new connected devices to see if they are on an allowed list if action == 'add': print("Device attached") devnum = int(device.attributes.get("devnum")) busnum = int(device.attributes.get("busnum")) dev = usb.core.find(address=devnum, bus=busnum) # Get the device unique id dev_id = read_device.get_descriptors(dev) if dev_id in self.trusted_devices: self.usb_blocker.get_dbus_method( 'enable_device', 'org.gnome.USBBlocker.device')(bus_id, dev_id) return if read_device.find_device( dev, list( usb.core.find(find_all=True, custom_match=read_device.custom_search( self.allowed_devices)))): print("Device found on the non blocking list -- session") if self.usb_blocker.get_dbus_method( 'enable_device', 'org.gnome.USBBlocker.device')(bus_id, dev_id): self.trusted_devices.append(dev_id) self.write_trusted_devices() return id_notification = self.notification( "USB-inhibitor", "0", "", "Unknown device connected", "An unknown device has been connected to the system. Do you want to allow it to connect?", ["Allow", "Connect", "Block", "Block"], {}, 5) self.number_notifications[id_notification] = [bus_id, dev_id] def write_trusted_devices(self): with open(expanduser("~") + '/.local/share/trusted_devices', 'wt') as f_out: json.dump(self.trusted_devices, f_out)
class USB_Session_Blocker(dbus.service.Object): # Create context context = Context() # Create monitor monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='usb', device_type='usb_device') def __init__(self): try: with open(expanduser("~") + '/.local/share/trusted_devices', 'rt') as f_in: try: self.trusted_devices = json.load(f_in) except ValueError: self.trusted_devices = [] except IOError: self.trusted_devices = [] self.usb_blocker = dbus.SystemBus().get_object('org.gnome.USBBlocker', '/org/gnome/USBBlocker') self.notifier = dbus.SessionBus().get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications') self.observer = None self.number_notifications = {} self.allowed_devices = [] bus_name = dbus.service.BusName('org.gnome.USBInhibit', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/org/gnome/USBInhibit') @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='', out_signature='b') def get_status(self): return self.usb_blocker.get_dbus_method('get_status', 'org.gnome.USBBlocker.inhibit')() @dbus.service.method(dbus_interface='org.gnome.USBInhibit') def start_inhibit(self): self.notification = self.notifier.get_dbus_method('Notify', \ 'org.freedesktop.Notifications') self.observer = MonitorObserver(self.monitor, callback = self.device_detected, name='monitor-usb-session') self.notifier.connect_to_signal('ActionInvoked', self.action_new_device) self.observer.daemon = True self.observer.start() print("Start monitoring Dbus session message") self.usb_blocker.get_dbus_method('start', 'org.gnome.USBBlocker.inhibit')() def action_new_device(self, id, action): if id in self.number_notifications: if action == "Allow": print "Allowed" bus_id, dev_id = self.number_notifications.pop(id) if self.usb_blocker.get_dbus_method('enable_device', 'org.gnome.USBBlocker.device')(bus_id, dev_id): self.trusted_devices.append(dev_id) self.write_trusted_devices() print (bus_id) print (dev_id) # If the action is Block then the device must remain blocked if action == "Block": print "Blocked" @dbus.service.method(dbus_interface='org.gnome.USBInhibit') def stop_inhibit(self): print("Stop monitoring Dbus session message") if self.observer != None: self.observer.stop() self.usb_blocker.get_dbus_method('stop', 'org.gnome.USBBlocker.inhibit')() @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='n', out_signature='') def add_nonblock_device(self, bDeviceClass): print ("Add device with the bDeviceClass code " + str(bDeviceClass)) self.allowed_devices.append(bDeviceClass) @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='n', out_signature='') def remove_nonblock_device(self, bDeviceClass): print ("Remove device with the bDeviceClass code " + str(bDeviceClass)) if bDeviceClass in self.allowed_devices: self.allowed_devices.remove(bDeviceClass) @dbus.service.method(dbus_interface='org.gnome.USBInhibit', \ in_signature='', out_signature='s') def show_nonblock_devices(self): return str(self.allowed_devices) def device_detected(self, device): import usb.core bus_id = device.sys_name action = device.action # Check only new connected devices to see if they are on an allowed list if action == 'add': print ("Device attached") devnum = int(device.attributes.get("devnum")) busnum = int(device.attributes.get("busnum")) dev = usb.core.find(address=devnum, bus=busnum) # Get the device unique id dev_id = read_device.get_descriptors(dev) if dev_id in self.trusted_devices: self.usb_blocker.get_dbus_method('enable_device', 'org.gnome.USBBlocker.device')(bus_id, dev_id) return if read_device.find_device(dev, list(usb.core.find(find_all = True, custom_match = read_device.custom_search(self.allowed_devices)))): print ("Device found on the non blocking list -- session") if self.usb_blocker.get_dbus_method('enable_device', 'org.gnome.USBBlocker.device')(bus_id, dev_id): self.trusted_devices.append(dev_id) self.write_trusted_devices() return id_notification = self.notification("USB-inhibitor", "0", "", "Unknown device connected", "An unknown device has been connected to the system. Do you want to allow it to connect?", ["Allow", "Connect", "Block", "Block"], {}, 5) self.number_notifications[id_notification] = [bus_id, dev_id] def write_trusted_devices(self): with open(expanduser("~") + '/.local/share/trusted_devices', 'wt') as f_out: json.dump(self.trusted_devices, f_out)