LukeShortCloud / rootpages

Root Pages is a collection of easy-to-reference tutorials and guides primarily for Linux and other UNIX-like systems.
Other
57 stars 6 forks source link

[programming][python] Read raw Linux device input #781

Open LukeShortCloud opened 2 years ago

LukeShortCloud commented 2 years ago

This is useful for creating programs that involve using an input device (such as an infrared receiver, keyboard, etc.).

#!/usr/bin/python
import struct
import time
import sys

infile_path = "/dev/input/event" + (sys.argv[1] if len(sys.argv) > 1 else "0")

"""
FORMAT represents the format used by linux kernel input event struct
See https://github.com/torvalds/linux/blob/v5.5-rc5/include/uapi/linux/input.h#L28
Stands for: long int, long int, unsigned short, unsigned short, unsigned int
"""
FORMAT = 'llHHI'
EVENT_SIZE = struct.calcsize(FORMAT)

#open file in binary mode
in_file = open(infile_path, "rb")

event = in_file.read(EVENT_SIZE)

while event:
    (tv_sec, tv_usec, type, code, value) = struct.unpack(FORMAT, event)

    if type != 0 or code != 0 or value != 0:
        print("Event type %u, code %u, value %u at %d.%d" % \
            (type, code, value, tv_sec, tv_usec))
    else:
        # Events with code, type and value == 0 are "separator" events
        print("===========================================")

    event = in_file.read(EVENT_SIZE)

in_file.close()

/dev/input/<EVENT_DEVICE> returns four values: (1) the type, (2) the code, (3) seconds, and (4) microseconds. The most important part is the code value as that is the key/button that was pressed.

https://stackoverflow.com/questions/5060710/format-of-dev-input-event

To find the input device, view this directory:

$ ls -1 /dev/input/by-id/

For example, /dev/input/by-id/usb-Apple__Inc_Apple_Keyboard-event-kbd may show up as a human-friendly symlink to /dev/input/event24. The symlink or the actual event file can be used with the above Python code.

LukeShortCloud commented 2 years ago

For direct access to input devices, a user must either be (1) the root user or (2) a user in the input group.

All of the definitions for codes and their related physical keys on a keyboard can be found here: /usr/include/linux/input-event-codes.h.

https://www.developer.com/languages/map-event-codes-python/