platform.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. """What the real-hardware frontends share: evdev keys, the backlight, the I2C
  2. bus check and running the main loop."""
  3. import fcntl
  4. import os
  5. import signal
  6. import struct
  7. import sys
  8. from gi.repository import GLib
  9. DEFAULT_KEYS_NAME = "radio-keys"
  10. DEFAULT_BACKLIGHT = "/sys/class/backlight/radio-backlight/brightness"
  11. # linux/input-event-codes.h; the overlay's radio-keys sends these
  12. EVDEV_KEYS = {
  13. 1: "esc", # KEY_ESC
  14. 163: "next", # KEY_NEXTSONG
  15. 166: "stop", # KEY_STOPCD
  16. 139: "menu", # KEY_MENU
  17. 395: "list", # KEY_LIST
  18. 103: "up", # KEY_UP
  19. 165: "prev", # KEY_PREVIOUSSONG
  20. 106: "right", # KEY_RIGHT
  21. 108: "down", # KEY_DOWN
  22. 201: "pause", # KEY_PAUSECD
  23. 352: "ok", # KEY_OK
  24. 105: "left", # KEY_LEFT
  25. 200: "play", # KEY_PLAYCD
  26. }
  27. EV_KEY = 1
  28. # struct input_event: a struct timeval of two longs, then type, code, value.
  29. # The kernel keeps the two longs even for 32-bit time64 userspace.
  30. _EVENT = struct.Struct("llHHi")
  31. def _eviocgname(size):
  32. # _IOC(_IOC_READ, 'E', 0x06, size)
  33. return (2 << 30) | (size << 16) | (ord("E") << 8) | 0x06
  34. def _device_name(fd):
  35. buf = bytearray(256)
  36. try:
  37. n = fcntl.ioctl(fd, _eviocgname(len(buf)), buf, True)
  38. except OSError:
  39. return None
  40. return bytes(buf[:max(n, 0)]).split(b"\0", 1)[0].decode("utf-8", "replace")
  41. def _find_keys_device():
  42. for i in range(32):
  43. path = "/dev/input/event%d" % i
  44. try:
  45. fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
  46. except OSError:
  47. continue
  48. if _device_name(fd) == DEFAULT_KEYS_NAME:
  49. return fd
  50. os.close(fd)
  51. return -1
  52. def have_keys_device():
  53. """Whether a readable evdev device named DEFAULT_KEYS_NAME exists"""
  54. fd = _find_keys_device()
  55. if fd < 0:
  56. return False
  57. os.close(fd)
  58. return True
  59. def start_evdev_keys(on_key, path=None):
  60. """Feed presses from an evdev device to on_key(name, repeat). path None looks for
  61. the device named DEFAULT_KEYS_NAME. False if there is none."""
  62. if path:
  63. try:
  64. fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
  65. except OSError as e:
  66. print("%s: %s" % (path, e.strerror), file=sys.stderr)
  67. return False
  68. else:
  69. fd = _find_keys_device()
  70. if fd < 0:
  71. return False
  72. def on_input(fd_, cond):
  73. while True:
  74. try:
  75. data = os.read(fd, _EVENT.size * 32)
  76. except BlockingIOError:
  77. return True
  78. except OSError:
  79. return False # device gone
  80. if not data:
  81. return False
  82. for off in range(0, len(data) - _EVENT.size + 1, _EVENT.size):
  83. _, _, etype, code, value = _EVENT.unpack_from(data, off)
  84. # 1 press, 2 autorepeat: the app applies the lockout
  85. if etype == EV_KEY and value and code in EVDEV_KEYS:
  86. on_key(EVDEV_KEYS[code], value == 2)
  87. GLib.io_add_watch(fd, GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR,
  88. on_input)
  89. return True
  90. def backlight_set(path, on):
  91. """Write to a sysfs brightness file; a None path does nothing"""
  92. if not path:
  93. return
  94. try:
  95. with open(path, "w") as f:
  96. f.write("1\n" if on else "0\n")
  97. except OSError:
  98. pass
  99. # ---- i2c-dev ---------------------------------------------------------------
  100. # Never, whatever the options: motherboard and display buses
  101. DENIED_ADAPTERS = ("PIIX4", "AMDGPU", "DPMST", "i801", "SMBus")
  102. # Known to be a dedicated bus for this panel
  103. KNOWN_ADAPTERS = ("MCP2221", "FT260", "i2c-tiny-usb", "mv64xxx")
  104. I2C_FUNCS = 0x0705
  105. I2C_FUNC_I2C = 0x00000001
  106. class BusRefused(Exception):
  107. pass
  108. def open_i2c_bus(bus, allow=None):
  109. """Open /dev/i2c-N only if its adapter is known to be safe for the panel.
  110. Writing a raw byte stream to the wrong bus can reach anything on it."""
  111. try:
  112. with open("/sys/class/i2c-dev/i2c-%d/name" % bus) as f:
  113. name = f.readline().strip()
  114. except OSError:
  115. raise BusRefused("i2c-%d: cannot read the adapter name" % bus)
  116. for bad in DENIED_ADAPTERS:
  117. if bad in name:
  118. raise BusRefused("i2c-%d (%s): refusing, this is not a panel bus" % (bus, name))
  119. ok = any(k in name for k in KNOWN_ADAPTERS) or (allow is not None and allow == name)
  120. if not ok:
  121. raise BusRefused('i2c-%d (%s): unknown adapter; if it really is the panel\'s bus,\n'
  122. 'pass --allow-adapter="%s"' % (bus, name, name))
  123. path = "/dev/i2c-%d" % bus
  124. try:
  125. fd = os.open(path, os.O_RDWR | os.O_CLOEXEC)
  126. except OSError as e:
  127. raise BusRefused("%s: %s" % (path, e.strerror))
  128. funcs = bytearray(struct.calcsize("L"))
  129. try:
  130. fcntl.ioctl(fd, I2C_FUNCS, funcs, True)
  131. has_i2c = struct.unpack("L", bytes(funcs))[0] & I2C_FUNC_I2C
  132. except OSError:
  133. has_i2c = False
  134. if not has_i2c:
  135. os.close(fd)
  136. raise BusRefused("i2c-%d (%s): no raw I2C support" % (bus, name))
  137. print("using i2c-%d (%s)" % (bus, name))
  138. return fd
  139. # ---- main loop ---------------------------------------------------------------
  140. def run(loop=None):
  141. """Run the GLib main loop until SIGINT or SIGTERM, or loop.quit()"""
  142. loop = loop or GLib.MainLoop()
  143. def on_signal(*_):
  144. loop.quit()
  145. return False
  146. for sig in (signal.SIGINT, signal.SIGTERM):
  147. GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, sig, on_signal)
  148. loop.run()