"""Keys on U2, a TCA9539 read directly through i2c-dev. For kernels without the overlay, and for the test rig: the expander is polled over the same bus as the panel. Each key pulls its pin high against a pull-down, so a pin reading 1 is a pressed key; the pins are debounced here and held keys repeat like evdev autorepeat, so the app sees the same presses as from gpio-keys. The INT line is not wired on the USB test board, so this polls. Reading the input registers also clears INT, which matters if the kernel's pca953x driver ever owns the chip; never run both. """ import ctypes import fcntl import sys from gi.repository import GLib from . import state as st DEFAULT_ADDR = 0x76 # A1 high, A0 low POLL_MS = 20 DEBOUNCE_SAMPLES = 2 # the same reading twice in a row: 20 ms at POLL_MS REPEAT_DELAY_MS = 250 # the input core's defaults, as gpio-keys "autorepeat" REPEAT_PERIOD_MS = 33 # More keys than this down at once is taken as a fault (say a floating bus # or a short to the supply), not as presses. An unplugged key board reads # every pin low through the pull-downs, which is simply no keys. MAX_KEYS = 3 # bit = pin: P0.n is n, P1.n is 8 + n. P0.0-P0.2 are unused, pulled down. KEY_PINS = { 3: "next", 4: "left", 5: "down", 6: "up", 7: "right", 8: "esc", 9: "ok", 10: "menu", 11: "list", 12: "stop", 13: "pause", 14: "play", 15: "prev", } KEY_MASK = sum(1 << b for b in KEY_PINS) # TCA9539 registers; auto-increment stays within a pair REG_INPUT0 = 0x00 REG_POLARITY0 = 0x04 REG_CONFIG0 = 0x06 # linux/i2c.h, linux/i2c-dev.h I2C_RDWR = 0x0707 I2C_M_RD = 0x0001 class _I2cMsg(ctypes.Structure): _fields_ = [("addr", ctypes.c_uint16), ("flags", ctypes.c_uint16), ("len", ctypes.c_uint16), ("buf", ctypes.c_void_p)] class _I2cRdwr(ctypes.Structure): _fields_ = [("msgs", ctypes.c_void_p), ("nmsgs", ctypes.c_uint32)] def pin_name(bit): return "P%d.%d" % (bit // 8, bit % 8) class Expander(object): """The key expander on an open, already checked /dev/i2c-N""" def __init__(self, fd, addr=DEFAULT_ADDR): self.fd, self.addr = fd, addr def _transfer(self, *msgs): """msgs: (flags, buffer); raises OSError""" arr = (_I2cMsg * len(msgs))() keep = [] for m, (flags, data) in zip(arr, msgs): buf = (ctypes.c_char * len(data)).from_buffer(data) keep.append(buf) m.addr, m.flags, m.len, m.buf = self.addr, flags, len(data), ctypes.addressof(buf) req = _I2cRdwr(ctypes.addressof(arr), len(msgs)) fcntl.ioctl(self.fd, I2C_RDWR, req) def write(self, reg, *values): self._transfer((0, bytearray((reg,) + values))) def setup(self): """All pins inputs, no inversion: the power-on state, made sure of""" self.write(REG_POLARITY0, 0x00, 0x00) self.write(REG_CONFIG0, 0xff, 0xff) def read_inputs(self): """Both input ports as P1 << 8 | P0; a pressed key reads 1""" data = bytearray(2) self._transfer((0, bytearray((REG_INPUT0,))), (I2C_M_RD, data)) return data[0] | data[1] << 8 def _bits(v): return bin(v).count("1") class KeyScanner(object): """Debounce and autorepeat. feed() takes raw input port readings and returns (key, value) events, value as evdev: 1 press, 0 release, 2 repeat. max_keys: readings with more keys down are ignored, and stop repeats. ignore_initial: keys down in the first reading give no press, only a release later, so a stuck key cannot send commands from the start.""" def __init__(self, samples=DEBOUNCE_SAMPLES, delay_ms=REPEAT_DELAY_MS, period_ms=REPEAT_PERIOD_MS, max_keys=None, ignore_initial=False): self.samples = samples self.delay_ms, self.period_ms = delay_ms, period_ms self.max_keys = max_keys self.ignore_initial = ignore_initial self.started = False self.faulty = False # last reading had too many keys down self.candidate = None self.count = 0 self.pressed = 0 # debounced, bit set = key down self.repeat_at = {} # bit: monotonic ms of its next repeat self.last_ms = None # time of the previous reading def feed(self, raw, now_ms): # readings stalled (a long panel update holds the main loop): whether # a key was held all along is unknown, so no repeat on this reading stalled = self.last_ms is not None and now_ms - self.last_ms > self.delay_ms self.last_ms = now_ms down = raw & KEY_MASK self.faulty = self.max_keys is not None and _bits(down) > self.max_keys if self.faulty: self.repeat_at.clear() self.candidate = None return [] # the first valid reading: a fault says nothing about what is held if self.ignore_initial and not self.started: self.pressed = self.candidate = down self.count = self.samples self.started = True if down == self.candidate: self.count += 1 else: self.candidate, self.count = down, 1 events = [] if self.count >= self.samples and down != self.pressed: for bit in sorted(KEY_PINS): m = 1 << bit if (down ^ self.pressed) & m: if down & m: events.append((KEY_PINS[bit], 1)) self.repeat_at[bit] = now_ms + self.delay_ms else: events.append((KEY_PINS[bit], 0)) self.repeat_at.pop(bit, None) self.pressed = down for bit in sorted(self.repeat_at): if now_ms < self.repeat_at[bit]: continue # only while this reading has it down too: a release still # being debounced is not a held key if stalled or not down & (1 << bit): self.repeat_at[bit] = max(self.repeat_at[bit], now_ms + self.period_ms) continue events.append((KEY_PINS[bit], 2)) self.repeat_at[bit] = now_ms + self.period_ms return events def pressed_keys(self): return [KEY_PINS[b] for b in sorted(KEY_PINS) if self.pressed & (1 << b)] class KeyPoller(object): """Polls the expander from the GLib main loop. on_event(key, value) gets every event; on_raw(raw), if given, every reading that differs from the last one. A failed read is reported once and polling goes on, so the keys come back after a bus glitch or a replug.""" def __init__(self, expander, on_event, on_raw=None, poll_ms=POLL_MS, scanner=None): self.expander = expander self.on_event, self.on_raw = on_event, on_raw self.scanner = scanner or KeyScanner() self.last_raw = None self.errors = 0 self.failing = False self.timer_id = GLib.timeout_add(poll_ms, self._poll) def _poll(self): try: raw = self.expander.read_inputs() except OSError as e: self.errors += 1 if not self.failing: print("keys at 0x%02x: %s" % (self.expander.addr, e.strerror), file=sys.stderr) self.failing = True return True if self.failing: print("keys at 0x%02x: reading again" % self.expander.addr, file=sys.stderr) self.failing = False # pins may have changed state unseen; also redo the setup try: self.expander.setup() except OSError: pass if raw != self.last_raw: self.last_raw = raw if self.on_raw: self.on_raw(raw) for key, value in self.scanner.feed(raw, st.monotonic_ms()): self.on_event(key, value) return True def close(self): if self.timer_id: GLib.source_remove(self.timer_id) self.timer_id = 0 def start(fd, addr, on_key, poll_ms=POLL_MS): """Feed presses and repeats to on_key(name, repeat), like evdev. Returns the poller, or None if the expander does not answer. Keys held at start, or too many at once, are ignored: these presses send player commands.""" exp = Expander(fd, addr) try: exp.setup() raw = exp.read_inputs() except OSError as e: print("keys at 0x%02x: %s" % (addr, e.strerror), file=sys.stderr) return None down = raw & KEY_MASK if down: print("keys at 0x%02x: ignored until released: %s%s" % (addr, ", ".join(KEY_PINS[b] for b in sorted(KEY_PINS) if down & (1 << b)), " (more than %d down: bus fault?)" % MAX_KEYS if _bits(down) > MAX_KEYS else ""), file=sys.stderr) def on_event(key, value): if value: on_key(key, value == 2) scanner = KeyScanner(max_keys=MAX_KEYS, ignore_initial=True) scanner.feed(raw, st.monotonic_ms()) # what is held now return KeyPoller(exp, on_event, poll_ms=poll_ms, scanner=scanner)