keypad.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. self.last_ms = None # time of the previous reading
  102. def feed(self, raw, now_ms):
  103. # readings stalled (a long panel update holds the main loop): whether
  104. # a key was held all along is unknown, so no repeat on this reading
  105. stalled = self.last_ms is not None and now_ms - self.last_ms > self.delay_ms
  106. self.last_ms = now_ms
  107. down = raw & KEY_MASK
  108. self.faulty = self.max_keys is not None and _bits(down) > self.max_keys
  109. if self.faulty:
  110. self.repeat_at.clear()
  111. self.candidate = None
  112. return []
  113. # the first valid reading: a fault says nothing about what is held
  114. if self.ignore_initial and not self.started:
  115. self.pressed = self.candidate = down
  116. self.count = self.samples
  117. self.started = True
  118. if down == self.candidate:
  119. self.count += 1
  120. else:
  121. self.candidate, self.count = down, 1
  122. events = []
  123. if self.count >= self.samples and down != self.pressed:
  124. for bit in sorted(KEY_PINS):
  125. m = 1 << bit
  126. if (down ^ self.pressed) & m:
  127. if down & m:
  128. events.append((KEY_PINS[bit], 1))
  129. self.repeat_at[bit] = now_ms + self.delay_ms
  130. else:
  131. events.append((KEY_PINS[bit], 0))
  132. self.repeat_at.pop(bit, None)
  133. self.pressed = down
  134. for bit in sorted(self.repeat_at):
  135. if now_ms < self.repeat_at[bit]:
  136. continue
  137. # only while this reading has it down too: a release still
  138. # being debounced is not a held key
  139. if stalled or not down & (1 << bit):
  140. self.repeat_at[bit] = max(self.repeat_at[bit], now_ms + self.period_ms)
  141. continue
  142. events.append((KEY_PINS[bit], 2))
  143. self.repeat_at[bit] = now_ms + self.period_ms
  144. return events
  145. def pressed_keys(self):
  146. return [KEY_PINS[b] for b in sorted(KEY_PINS) if self.pressed & (1 << b)]
  147. class KeyPoller(object):
  148. """Polls the expander from the GLib main loop.
  149. on_event(key, value) gets every event; on_raw(raw), if given, every reading
  150. that differs from the last one. A failed read is reported once and polling
  151. goes on, so the keys come back after a bus glitch or a replug."""
  152. def __init__(self, expander, on_event, on_raw=None, poll_ms=POLL_MS, scanner=None):
  153. self.expander = expander
  154. self.on_event, self.on_raw = on_event, on_raw
  155. self.scanner = scanner or KeyScanner()
  156. self.last_raw = None
  157. self.errors = 0
  158. self.failing = False
  159. self.timer_id = GLib.timeout_add(poll_ms, self._poll)
  160. def _poll(self):
  161. try:
  162. raw = self.expander.read_inputs()
  163. except OSError as e:
  164. self.errors += 1
  165. if not self.failing:
  166. print("keys at 0x%02x: %s" % (self.expander.addr, e.strerror),
  167. file=sys.stderr)
  168. self.failing = True
  169. return True
  170. if self.failing:
  171. print("keys at 0x%02x: reading again" % self.expander.addr, file=sys.stderr)
  172. self.failing = False
  173. # pins may have changed state unseen; also redo the setup
  174. try:
  175. self.expander.setup()
  176. except OSError:
  177. pass
  178. if raw != self.last_raw:
  179. self.last_raw = raw
  180. if self.on_raw:
  181. self.on_raw(raw)
  182. for key, value in self.scanner.feed(raw, st.monotonic_ms()):
  183. self.on_event(key, value)
  184. return True
  185. def close(self):
  186. if self.timer_id:
  187. GLib.source_remove(self.timer_id)
  188. self.timer_id = 0
  189. def start(fd, addr, on_key, poll_ms=POLL_MS):
  190. """Feed presses and repeats to on_key(name, repeat), like evdev. Returns the
  191. poller, or None if the expander does not answer. Keys held at start, or
  192. too many at once, are ignored: these presses send player commands."""
  193. exp = Expander(fd, addr)
  194. try:
  195. exp.setup()
  196. raw = exp.read_inputs()
  197. except OSError as e:
  198. print("keys at 0x%02x: %s" % (addr, e.strerror), file=sys.stderr)
  199. return None
  200. down = raw & KEY_MASK
  201. if down:
  202. print("keys at 0x%02x: ignored until released: %s%s"
  203. % (addr, ", ".join(KEY_PINS[b] for b in sorted(KEY_PINS) if down & (1 << b)),
  204. " (more than %d down: bus fault?)" % MAX_KEYS
  205. if _bits(down) > MAX_KEYS else ""), file=sys.stderr)
  206. def on_event(key, value):
  207. if value:
  208. on_key(key, value == 2)
  209. scanner = KeyScanner(max_keys=MAX_KEYS, ignore_initial=True)
  210. scanner.feed(raw, st.monotonic_ms()) # what is held now
  211. return KeyPoller(exp, on_event, poll_ms=poll_ms, scanner=scanner)