Linux : How to detect if USB keyboard is plugged and unplugged

后端 未结 3 1528
走了就别回头了
走了就别回头了 2020-12-29 00:04

Is there any daemon/tool which will trigger some signal/event when usb keyboard is plugged and unplugged from pc ? I need to know in my program when usb keyboard is plugged

相关标签:
3条回答
  • 2020-12-29 00:46

    udevadm monitor (the udev administration binary) or udev_monitor (in libudev).

    Alternately, if you're running in X11 with input hotplugging, you can listen for the XI extension event DevicePresenceNotify.

    0 讨论(0)
  • 2020-12-29 00:53

    udev (Linux device manager) is the one that polls hardware. When it detects some changes about devices, it executes the rule associated.

    You should add a rule to udev, in order to inform your program about insertion of removal of USB keyboard. You can find documentation about udev rules here, or Look at files in /etc/udev/rules.d/ or /lib/udev/rules.d/ to find many examples.

    0 讨论(0)
  • 2020-12-29 00:53

    If HAL daemon is running (which is true for most modern linux desktops), you can listen to its DBus Signals. Here is an example how to detect if a USB mouse is plugged in (I don't have a USB keyboard at hand):

    import gobject
    import dbus
    from dbus.mainloop.glib import DBusGMainLoop
    
    DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()
    # enumerate all present mice:
    manager = dbus.Interface(bus.get_object("org.freedesktop.Hal",
                                            "/org/freedesktop/Hal/Manager"),
                             "org.freedesktop.Hal.Manager")
    mice = set(manager.FindDeviceByCapability('input.mouse'))
    
    def device_added(sender):
        dev = dbus.Interface(bus.get_object("org.freedesktop.Hal", sender),
                             "org.freedesktop.Hal.Device")
        try:
            caps = dev.GetProperty('info.capabilities')
            if 'input.mouse' in caps:
                print "mouse plugged in"
                mice.add(sender)
        except dbus.DBusException:
            pass
    
    def device_removed(sender):
        if sender in mice:
            print "mouse unplugged"
            mice.remove(sender)
    
    bus.add_signal_receiver(device_added, signal_name="DeviceAdded")
    bus.add_signal_receiver(device_removed, signal_name="DeviceRemoved")
    
    loop = gobject.MainLoop()
    loop.run()
    
    0 讨论(0)
提交回复
热议问题