| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
""" |
| 4 |
This is an example of using pyudev[1] alongside evdev. |
| 5 |
[1]: https://pyudev.readthedocs.org/ |
| 6 |
""" |
| 7 |
|
| 8 |
import functools |
| 9 |
import pyudev |
| 10 |
|
| 11 |
from select import select |
| 12 |
from evdev import InputDevice |
| 13 |
|
| 14 |
context = pyudev.Context() |
| 15 |
monitor = pyudev.Monitor.from_netlink(context) |
| 16 |
monitor.filter_by(subsystem="input") |
| 17 |
monitor.start() |
| 18 |
|
| 19 |
fds = {monitor.fileno(): monitor} |
| 20 |
finalizers = [] |
| 21 |
|
| 22 |
while True: |
| 23 |
r, w, x = select(fds, [], []) |
| 24 |
|
| 25 |
if monitor.fileno() in r: |
| 26 |
r.remove(monitor.fileno()) |
| 27 |
|
| 28 |
for udev in iter(functools.partial(monitor.poll, 0), None): |
| 29 |
# we're only interested in devices that have a device node |
| 30 |
# (e.g. /dev/input/eventX) |
| 31 |
if not udev.device_node: |
| 32 |
break |
| 33 |
|
| 34 |
# find the device we're interested in and add it to fds |
| 35 |
for name in (i["NAME"] for i in udev.ancestors if "NAME" in i): |
| 36 |
# I used a virtual input device for this test - you |
| 37 |
# should adapt this to your needs |
| 38 |
if "py-evdev-uinput" in name: |
| 39 |
if udev.action == "add": |
| 40 |
print("Device added: %s" % udev) |
| 41 |
fds[dev.fd] = InputDevice(udev.device_node) |
| 42 |
break |
| 43 |
if udev.action == "remove": |
| 44 |
print("Device removed: %s" % udev) |
| 45 |
|
| 46 |
def helper(): |
| 47 |
global fds |
| 48 |
fds = {monitor.fileno(): monitor} |
| 49 |
|
| 50 |
finalizers.append(helper) |
| 51 |
break |
| 52 |
|
| 53 |
for fd in r: |
| 54 |
dev = fds[fd] |
| 55 |
for event in dev.read(): |
| 56 |
print(event) |
| 57 |
|
| 58 |
for i in range(len(finalizers)): |
| 59 |
finalizers.pop()() |