deimus
deimus

Reputation: 9893

How to detect if USB keyboard is plugged and unplugged

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 and unplugged. Any ideas on how to do this?

Upvotes: 6

Views: 8982

Answers (3)

ephemient
ephemient

Reputation: 204964

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.

Upvotes: 3

abbot
abbot

Reputation: 27890

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()

Upvotes: -2

peoro
peoro

Reputation: 26060

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.

Upvotes: 4

Related Questions