keypad.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """Keys on U2, a TCA9539 read directly through i2c-dev.
  2. For kernels without the overlay, and for the test rig: the expander is polled
  3. over the same bus as the panel. Each key pulls its pin high against a
  4. pull-down, so a pin reading 1 is a pressed key; the pins are
  5. debounced here and held keys repeat like evdev autorepeat, so the app sees the
  6. same presses as from gpio-keys.
  7. The INT line is not wired on the USB test board, so this polls. Reading the
  8. input registers also clears INT, which matters if the kernel's pca953x driver
  9. ever owns the chip; never run both.
  10. """
  11. import ctypes
  12. import fcntl
  13. import sys
  14. from gi.repository import GLib
  15. from . import state as st
  16. DEFAULT_ADDR = 0x76 # A1 high, A0 low
  17. POLL_MS = 20
  18. DEBOUNCE_SAMPLES = 2 # the same reading twice in a row: 20 ms at POLL_MS
  19. REPEAT_DELAY_MS = 250 # the input core's defaults, as gpio-keys "autorepeat"
  20. REPEAT_PERIOD_MS = 33
  21. # More keys than this down at once is taken as a fault (say a floating bus
  22. # or a short to the supply), not as presses. An unplugged key board reads
  23. # every pin low through the pull-downs, which is simply no keys.
  24. MAX_KEYS = 3
  25. # bit = pin: P0.n is n, P1.n is 8 + n. P0.0-P0.2 are unused, pulled down.
  26. KEY_PINS = {
  27. 3: "next",
  28. 4: "left",
  29. 5: "down",
  30. 6: "up",
  31. 7: "right",
  32. 8: "esc",
  33. 9: "ok",
  34. 10: "menu",
  35. 11: "list",
  36. 12: "stop",
  37. 13: "pause",
  38. 14: "play",
  39. 15: "prev",
  40. }
  41. KEY_MASK = sum(1 << b for b in KEY_PINS)
  42. # TCA9539 registers; auto-increment stays within a pair
  43. REG_INPUT0 = 0x00
  44. REG_POLARITY0 = 0x04
  45. REG_CONFIG0 = 0x06
  46. # linux/i2c.h, linux/i2c-dev.h
  47. I2C_RDWR = 0x0707
  48. I2C_M_RD = 0x0001
  49. class _I2cMsg(ctypes.Structure):
  50. _fields_ = [("addr", ctypes.c_uint16), ("flags", ctypes.c_uint16),
  51. ("len", ctypes.c_uint16), ("buf", ctypes.c_void_p)]
  52. class _I2cRdwr(ctypes.Structure):
  53. _fields_ = [("msgs", ctypes.c_void_p), ("nmsgs", ctypes.c_uint32)]
  54. def pin_name(bit):
  55. return "P%d.%d" % (bit // 8, bit % 8)
  56. class Expander(object):
  57. """The key expander on an open, already checked /dev/i2c-N"""
  58. def __init__(self, fd, addr=DEFAULT_ADDR):
  59. self.fd, self.addr = fd, addr
  60. def _transfer(self, *msgs):
  61. """msgs: (flags, buffer); raises OSError"""
  62. arr = (_I2cMsg * len(msgs))()
  63. keep = []
  64. for m, (flags, data) in zip(arr, msgs):
  65. buf = (ctypes.c_char * len(data)).from_buffer(data)
  66. keep.append(buf)
  67. m.addr, m.flags, m.len, m.buf = self.addr, flags, len(data), ctypes.addressof(buf)
  68. req = _I2cRdwr(ctypes.addressof(arr), len(msgs))
  69. fcntl.ioctl(self.fd, I2C_RDWR, req)
  70. def write(self, reg, *values):
  71. self._transfer((0, bytearray((reg,) + values)))
  72. def setup(self):
  73. """All pins inputs, no inversion: the power-on state, made sure of"""
  74. self.write(REG_POLARITY0, 0x00, 0x00)
  75. self.write(REG_CONFIG0, 0xff, 0xff)
  76. def read_inputs(self):
  77. """Both input ports as P1 << 8 | P0; a pressed key reads 1"""
  78. data = bytearray(2)
  79. self._transfer((0, bytearray((REG_INPUT0,))), (I2C_M_RD, data))
  80. return data[0] | data[1] << 8
  81. def _bits(v):
  82. return bin(v).count("1")
  83. class KeyScanner(object):
  84. """Debounce and autorepeat. feed() takes raw input port readings and
  85. returns (key, value) events, value as evdev: 1 press, 0 release, 2 repeat.
  86. max_keys: readings with more keys down are ignored, and stop repeats.
  87. ignore_initial: keys down in the first reading give no press, only a
  88. release later, so a stuck key cannot send commands from the start."""
  89. def __init__(self, samples=DEBOUNCE_SAMPLES, delay_ms=REPEAT_DELAY_MS,
  90. period_ms=REPEAT_PERIOD_MS, max_keys=None, ignore_initial=False):
  91. self.samples = samples
  92. self.delay_ms, self.period_ms = delay_ms, period_ms
  93. self.max_keys = max_keys
  94. self.ignore_initial = ignore_initial
  95. self.started = False
  96. self.faulty = False # last reading had too many keys down
  97. self.candidate = None
  98. self.count = 0
  99. self.pressed = 0 # debounced, bit set = key down
  100. self.repeat_at = {} # bit: monotonic ms of its next repeat
  101. def feed(self, raw, now_ms):
  102. down = raw & KEY_MASK
  103. self.faulty = self.max_keys is not None and _bits(down) > self.max_keys
  104. if self.faulty:
  105. self.repeat_at.clear()
  106. self.candidate = None
  107. return []
  108. # the first valid reading: a fault says nothing about what is held
  109. if self.ignore_initial and not self.started:
  110. self.pressed = self.candidate = down
  111. self.count = self.samples
  112. self.started = True
  113. if down == self.candidate:
  114. self.count += 1
  115. else:
  116. self.candidate, self.count = down, 1
  117. events = []
  118. if self.count >= self.samples and down != self.pressed:
  119. for bit in sorted(KEY_PINS):
  120. m = 1 << bit
  121. if (down ^ self.pressed) & m:
  122. if down & m:
  123. events.append((KEY_PINS[bit], 1))
  124. self.repeat_at[bit] = now_ms + self.delay_ms
  125. else:
  126. events.append((KEY_PINS[bit], 0))
  127. self.repeat_at.pop(bit, None)
  128. self.pressed = down
  129. for bit in sorted(self.repeat_at):
  130. if now_ms >= self.repeat_at[bit]:
  131. events.append((KEY_PINS[bit], 2))
  132. self.repeat_at[bit] = now_ms + self.period_ms
  133. return events
  134. def pressed_keys(self):
  135. return [KEY_PINS[b] for b in sorted(KEY_PINS) if self.pressed & (1 << b)]
  136. class KeyPoller(object):
  137. """Polls the expander from the GLib main loop.
  138. on_event(key, value) gets every event; on_raw(raw), if given, every reading
  139. that differs from the last one. A failed read is reported once and polling
  140. goes on, so the keys come back after a bus glitch or a replug."""
  141. def __init__(self, expander, on_event, on_raw=None, poll_ms=POLL_MS, scanner=None):
  142. self.expander = expander
  143. self.on_event, self.on_raw = on_event, on_raw
  144. self.scanner = scanner or KeyScanner()
  145. self.last_raw = None
  146. self.errors = 0
  147. self.failing = False
  148. self.timer_id = GLib.timeout_add(poll_ms, self._poll)
  149. def _poll(self):
  150. try:
  151. raw = self.expander.read_inputs()
  152. except OSError as e:
  153. self.errors += 1
  154. if not self.failing:
  155. print("keys at 0x%02x: %s" % (self.expander.addr, e.strerror),
  156. file=sys.stderr)
  157. self.failing = True
  158. return True
  159. if self.failing:
  160. print("keys at 0x%02x: reading again" % self.expander.addr, file=sys.stderr)
  161. self.failing = False
  162. # pins may have changed state unseen; also redo the setup
  163. try:
  164. self.expander.setup()
  165. except OSError:
  166. pass
  167. if raw != self.last_raw:
  168. self.last_raw = raw
  169. if self.on_raw:
  170. self.on_raw(raw)
  171. for key, value in self.scanner.feed(raw, st.monotonic_ms()):
  172. self.on_event(key, value)
  173. return True
  174. def close(self):
  175. if self.timer_id:
  176. GLib.source_remove(self.timer_id)
  177. self.timer_id = 0
  178. def start(fd, addr, on_key, poll_ms=POLL_MS):
  179. """Feed presses and repeats to on_key(name, repeat), like evdev. Returns the
  180. poller, or None if the expander does not answer. Keys held at start, or
  181. too many at once, are ignored: these presses send player commands."""
  182. exp = Expander(fd, addr)
  183. try:
  184. exp.setup()
  185. raw = exp.read_inputs()
  186. except OSError as e:
  187. print("keys at 0x%02x: %s" % (addr, e.strerror), file=sys.stderr)
  188. return None
  189. down = raw & KEY_MASK
  190. if down:
  191. print("keys at 0x%02x: ignored until released: %s%s"
  192. % (addr, ", ".join(KEY_PINS[b] for b in sorted(KEY_PINS) if down & (1 << b)),
  193. " (more than %d down: bus fault?)" % MAX_KEYS
  194. if _bits(down) > MAX_KEYS else ""), file=sys.stderr)
  195. def on_event(key, value):
  196. if value:
  197. on_key(key, value == 2)
  198. scanner = KeyScanner(max_keys=MAX_KEYS, ignore_initial=True)
  199. scanner.feed(raw, st.monotonic_ms()) # what is held now
  200. return KeyPoller(exp, on_event, poll_ms=poll_ms, scanner=scanner)