Linux : How to detect is usb keyboard is plugged and unplugged

会有一股神秘感。 提交于 2019-11-30 04:07:43

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.

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.

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!