Last year, just before the holidays Benjamin Tissoires and I worked on a 'new' project - python-libevdev. This is, unsurprisingly, a Python wrapper to libevdev. It's not exactly new since we took the git tree from 2016 when I was working on it the first time round but this time we whipped it into a better shape. Now it's at the point where I think it has the API it should have, pythonic and very easy to use but still with libevdev as the actual workhorse in the background. It's available via pip3 and should be packaged for your favourite distributions soonish.
Who is this for? Basically anyone who needs to work with the evdev protocol. While C is still a thing, there are many use-cases where Python is a much more sensible choice. The python-libevdev documentation on ReadTheDocs provides a few examples which I'll copy here, just so you get a quick overview. The first example shows how to open a device and then continuously loop through all events, searching for button events:
import libevdev fd = open('/dev/input/event0', 'rb') d = libevdev.Device(fd) if not d.has(libevdev.EV_KEY.BTN_LEFT): print('This does not look like a mouse device') sys.exit(0) # Loop indefinitely while pulling the currently available events off # the file descriptor while True: for e in d.events(): if not e.matches(libevdev.EV_KEY): continue if e.matches(libevdev.EV_KEY.BTN_LEFT): print('Left button event') elif e.matches(libevdev.EV_KEY.BTN_RIGHT): print('Right button event')The second example shows how to create a virtual uinput device and send events through that device:
import libevdev d = libevdev.Device() d.name = 'some test device' d.enable(libevdev.EV_REL.REL_X) d.enable(libevdev.EV_REL.REL_Y) d.enable(libevdev.EV_KEY.BTN_LEFT) d.enable(libevdev.EV_KEY.BTN_MIDDLE) d.enable(libevdev.EV_KEY.BTN_RIGHT) uinput = d.create_uinput_device() print('new uinput test device at {}'.format(uinput.devnode)) events = [InputEvent(libevdev.EV_REL.REL_X, 1), InputEvent(libevdev.EV_REL.REL_Y, 1), InputEvent(libevdev.EV_SYN.SYN_REPORT, 0)] uinput.send_events(events)And finally, if you have a textual or binary representation of events, the evbit function helps to convert it to something useful:
>>> import libevdev >>> print(libevdev.evbit(0)) EV_SYN:0 >>> print(libevdev.evbit(2)) EV_REL:2 >>> print(libevdev.evbit(3, 4)) ABS_RY:4 >>> print(libevdev.evbit('EV_ABS')) EV_ABS:3 >>> print(libevdev.evbit('EV_ABS', 'ABS_X')) ABS_X:0 >>> print(libevdev.evbit('ABS_X')) ABS_X:0The latter is particularly helpful if you have a script that needs to analyse event sequences and look for protocol bugs (or hw/fw issues).
More explanations and details are available in the python-libevdev documentation. That doc also answers the question why python-libevdev exists when there's already a python-evdev package. The code is up on github.
No comments:
Post a Comment