"""What the real-hardware frontends share: evdev keys, the backlight, the I2C bus check and running the main loop.""" import fcntl import os import signal import struct import sys from gi.repository import GLib DEFAULT_KEYS_NAME = "radio-keys" DEFAULT_BACKLIGHT = "/sys/class/backlight/radio-backlight/brightness" # linux/input-event-codes.h; the overlay's radio-keys sends these EVDEV_KEYS = { 1: "esc", # KEY_ESC 163: "next", # KEY_NEXTSONG 166: "stop", # KEY_STOPCD 139: "menu", # KEY_MENU 395: "list", # KEY_LIST 103: "up", # KEY_UP 165: "prev", # KEY_PREVIOUSSONG 106: "right", # KEY_RIGHT 108: "down", # KEY_DOWN 201: "pause", # KEY_PAUSECD 352: "ok", # KEY_OK 105: "left", # KEY_LEFT 200: "play", # KEY_PLAYCD } EV_KEY = 1 # struct input_event: a struct timeval of two longs, then type, code, value. # The kernel keeps the two longs even for 32-bit time64 userspace. _EVENT = struct.Struct("llHHi") def _eviocgname(size): # _IOC(_IOC_READ, 'E', 0x06, size) return (2 << 30) | (size << 16) | (ord("E") << 8) | 0x06 def _device_name(fd): buf = bytearray(256) try: n = fcntl.ioctl(fd, _eviocgname(len(buf)), buf, True) except OSError: return None return bytes(buf[:max(n, 0)]).split(b"\0", 1)[0].decode("utf-8", "replace") def _find_keys_device(): for i in range(32): path = "/dev/input/event%d" % i try: fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC) except OSError: continue if _device_name(fd) == DEFAULT_KEYS_NAME: return fd os.close(fd) return -1 def start_evdev_keys(on_key, path=None): """Feed presses from an evdev device to on_key(name). path None looks for the device named DEFAULT_KEYS_NAME. False if there is none.""" if path: try: fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC) except OSError as e: print("%s: %s" % (path, e.strerror), file=sys.stderr) return False else: fd = _find_keys_device() if fd < 0: return False def on_input(fd_, cond): while True: try: data = os.read(fd, _EVENT.size * 32) except BlockingIOError: return True except OSError: return False # device gone if not data: return False for off in range(0, len(data) - _EVENT.size + 1, _EVENT.size): _, _, etype, code, value = _EVENT.unpack_from(data, off) # 1 press, 2 autorepeat: the app applies the lockout if etype == EV_KEY and value and code in EVDEV_KEYS: on_key(EVDEV_KEYS[code]) GLib.io_add_watch(fd, GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, on_input) return True def backlight_set(path, on): """Write to a sysfs brightness file; a None path does nothing""" if not path: return try: with open(path, "w") as f: f.write("1\n" if on else "0\n") except OSError: pass # ---- i2c-dev --------------------------------------------------------------- # Never, whatever the options: motherboard and display buses DENIED_ADAPTERS = ("PIIX4", "AMDGPU", "DPMST", "i801", "SMBus") # Known to be a dedicated bus for this panel KNOWN_ADAPTERS = ("MCP2221", "FT260", "i2c-tiny-usb", "mv64xxx") I2C_FUNCS = 0x0705 I2C_FUNC_I2C = 0x00000001 class BusRefused(Exception): pass def open_i2c_bus(bus, allow=None): """Open /dev/i2c-N only if its adapter is known to be safe for the panel. Writing a raw byte stream to the wrong bus can reach anything on it.""" try: with open("/sys/class/i2c-dev/i2c-%d/name" % bus) as f: name = f.readline().strip() except OSError: raise BusRefused("i2c-%d: cannot read the adapter name" % bus) for bad in DENIED_ADAPTERS: if bad in name: raise BusRefused("i2c-%d (%s): refusing, this is not a panel bus" % (bus, name)) ok = any(k in name for k in KNOWN_ADAPTERS) or (allow is not None and allow == name) if not ok: raise BusRefused('i2c-%d (%s): unknown adapter; if it really is the panel\'s bus,\n' 'pass --allow-adapter="%s"' % (bus, name, name)) path = "/dev/i2c-%d" % bus try: fd = os.open(path, os.O_RDWR | os.O_CLOEXEC) except OSError as e: raise BusRefused("%s: %s" % (path, e.strerror)) funcs = bytearray(struct.calcsize("L")) try: fcntl.ioctl(fd, I2C_FUNCS, funcs, True) has_i2c = struct.unpack("L", bytes(funcs))[0] & I2C_FUNC_I2C except OSError: has_i2c = False if not has_i2c: os.close(fd) raise BusRefused("i2c-%d (%s): no raw I2C support" % (bus, name)) print("using i2c-%d (%s)" % (bus, name)) return fd # ---- main loop --------------------------------------------------------------- def run(loop=None): """Run the GLib main loop until SIGINT or SIGTERM, or loop.quit()""" loop = loop or GLib.MainLoop() def on_signal(*_): loop.quit() return False for sig in (signal.SIGINT, signal.SIGTERM): GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, sig, on_signal) loop.run()