ソースを参照

Read the keys from the U2 expander over I2C

U2 is a TCA9539 at 0x76 with active-high keys and pull-downs. Its INT
line is not wired on the USB test board, so radio/keypad.py polls it
through i2c-dev every 20 ms, debounces over two samples and autorepeats
like gpio-keys. Keys held at start are ignored until released, and a
reading with more than three keys down counts as a bus fault, so neither
can send player commands.

radio-ui i2c reads the keys from its own bus by default; radio-ui drm
does so from the panel's bus when there is no radio-keys evdev device,
or from --keys-bus. radio-ui keytest draws the keys on the panel, and
tests/hw_test.sh runs it, the patterns or the full UI against the fake
MPD on the USB rig. Its init mode sets up the panel and keys over
i2c-dev and leaves them on; drm binds the DRM driver to 0x74 with a
pattern and leaves it active, and release unbinds it.

Move the overlay's U2 to 0x76 with the new pins and active-high flags,
and drop its stale gpio-backlight node: the backlight is U1 P1.0.
k4be 2 週間 前
親
コミット
bc025c935b
9 ファイル変更、907 行追加、32 行削除
  1. 52 14
      README.md
  2. 26 7
      docs/REPORT.md
  3. 159 10
      radio/__main__.py
  4. 9 0
      radio/drm.py
  5. 239 0
      radio/keypad.py
  6. 93 0
      radio/keytest.py
  7. 9 0
      radio/platform.py
  8. 163 0
      tests/hw_test.sh
  9. 157 1
      tests/test_ui.py

+ 52 - 14
README.md

@@ -2,7 +2,8 @@
 
 Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
 Linux board. The panel runs on real hardware through `radio-ui i2c` and
-`radio-ui drm`; keys and the overlay have not run yet.
+`radio-ui drm`. The key expander answers on the test rig and reads idle; no
+key has been pressed yet. The overlay has not run.
 
 | Path | What |
 |---|---|
@@ -13,7 +14,7 @@ Linux board. The panel runs on real hardware through `radio-ui i2c` and
 | `radio/libpanel.c` | The panel core and simulator as a library for the application |
 | `radio-ui` | Starts the application |
 | `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
-| `tests/` | Panel core tests, application tests and a fake MPD server |
+| `tests/` | Panel core tests, application tests, a fake MPD server and `hw_test.sh` |
 
 ## Building
 
@@ -53,6 +54,41 @@ or through the DRM driver:
 refused. Only use the bus number of the adapter the panel is wired to.
 `./radio-ui FRONTEND --help` lists all options.
 
+### Hardware test: panel and keys
+
+`tests/hw_test.sh` finds the i2c-tiny-usb bus, checks that no kernel driver
+holds 0x74 or 0x76, builds the library if needed and runs:
+
+    tests/hw_test.sh             # panel shows the 13 keys; pressed ones inverted
+    tests/hw_test.sh keys-only   # keys printed to the terminal, panel untouched
+    tests/hw_test.sh pattern     # geometry and gray patterns, then the keys
+    tests/hw_test.sh ui          # full UI with the I2C keys, against the fake MPD
+    tests/hw_test.sh init        # panel and U2 set up over i2c-dev, left on
+    tests/hw_test.sh drm         # sudo: bind the DRM driver to 0x74, pattern,
+                                 # backlight on, U2 set up; left active
+    tests/hw_test.sh release     # sudo: unbind the DRM driver again
+    tests/hw_test.sh -b 11 keys  # a given bus
+
+The key screen (`radio-ui keytest --bus N`) also shows the raw input ports,
+press and repeat counts and read errors; each event is printed too. Ctrl-C
+quits and switches the panel off. The i2c-dev modes refuse to run while a
+kernel driver holds 0x74 or 0x76; `release` frees 0x74 after `drm`.
+
+After `drm`, `./radio-ui drm --host radio.lo` drives the panel through the
+driver and reads the keys from U2 on the same bus.
+
+### Keys over I²C
+
+`radio-ui i2c` polls U2 at 0x76 on its own bus every 20 ms (`--keys-addr`,
+`--keys-poll`; `--no-i2c-keys` falls back to evdev). `radio-ui drm` uses the
+evdev device `radio-keys` if it exists (the overlay on the target), otherwise
+U2 on the bus the DRM panel is on; `--keys-bus N` names another bus and
+`--no-i2c-keys` disables this. The polling reads debounce over two samples and
+autorepeat like gpio-keys (250 ms, then every 33 ms; the app's 300 ms lockout
+applies). Keys held at start are ignored until released, and a reading with
+more than 3 keys down is taken as a bus fault, so a fault cannot send player
+commands. Do not load the overlay's U2 node while doing this.
+
 ### Test mode: real panel, PC keyboard
 
 `--window-keys` opens a small window on the X display; keys typed into it (the
@@ -115,24 +151,26 @@ whatever `--input` names. On the PC without the U2 keypad:
 | P1.5 | CS# (held low after reset; was hardwired low on the old board) | CS0 |
 | P1.6-7 | spare | |
 
-**U2, TCA9539 at 0x75** (A1=L, A0=H), stock `gpio-pca953x`
+**U2, TCA9539 at 0x76** (A1=H, A0=L): polled by `radio-ui i2c`, or stock
+`gpio-pca953x` with the overlay
 
-Each key has its own pin to ground and a 10k pull-up (the TCA9539 has no
-internal ones). `INT` goes to a host GPIO with a pull-up.
+Keys are active high: each pin has a pull-down (the TCA9539 has no internal
+ones) and its key connects it to the supply. `INT` is not connected on the USB
+test board, so the keys are polled; the final board wires it to a host GPIO.
 
 | Pin | Key | Pin | Key |
 |---|---|---|---|
-| P0.0 | Esc | P1.0 | Down |
-| P0.1 | Next | P1.1 | Pause |
-| P0.2 | Stop | P1.2 | OK |
-| P0.3 | Menu | P1.3 | Left |
-| P0.4 | List | P1.4 | Play |
-| P0.5 | Up | P1.5 | Backlight enable (active high, pull-down) |
-| P0.6 | Prev | P1.6-7 | spare |
-| P0.7 | Right | | |
+| P0.0-2 | unused (pull-down) | P1.0 | Esc |
+| P0.3 | Next | P1.1 | OK |
+| P0.4 | Left | P1.2 | Menu |
+| P0.5 | Down | P1.3 | List |
+| P0.6 | Up | P1.4 | Play |
+| P0.7 | Right | P1.5 | Pause |
+| | | P1.6 | Stop |
+| | | P1.7 | Prev |
 
 ## To confirm on hardware
 
 - TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
-- Keys (`evtest`) and the overlay
+- Every key on the key screen (`tests/hw_test.sh`); then the overlay (`evtest`)
 - The application on the target's Python 3.7.3

+ 26 - 7
docs/REPORT.md

@@ -41,6 +41,24 @@ against the fake MPD. The command names below were updated:
 `radio-gtk` → `radio-ui sim`, `radio-i2c` → `radio-ui i2c`, `radio-drm` →
 `radio-ui drm`.
 
+**Update 2026-11-13:** keys over I²C. U2 sits at **0x76** (A1 high, A0 low),
+and its keys are **active high with pull-downs**, wired P0.3-P0.7 Next, Left,
+Down, Up, Right and P1.0-P1.7 Esc, OK, Menu, List, Play, Pause, Stop, Prev
+(P0.0-P0.2 unused). `INT` is not connected on the USB test board, so
+`radio/keypad.py` polls the expander through i2c-dev every 20 ms, with
+debouncing, gpio-keys-style autorepeat, and protection against stuck keys and
+bus faults. `radio-ui i2c` uses it by default; `radio-ui drm --keys-bus N` can
+too, and falls back to it on its own when there is no `radio-keys` evdev
+device. `radio-ui keytest` shows the keys on the panel, and `tests/hw_test.sh`
+runs it, the patterns or the full UI on the rig. It can also set up the panel
+and U2 and leave them on (`init`, over i2c-dev), or bind the DRM driver to 0x74
+and leave it active (`drm`, undone by `release`). Both ran on the rig: the
+driver bound as card1, and `radio-ui drm` with no options found U2 on i2c-11. On the rig, the expander answers,
+setup reads back (config `ffff`, polarity `0000`) and all keys read up. No key
+has been pressed yet. The overlay was moved to 0x76 with the new pins and
+active-high flags, and its stale `gpio-backlight` node on U2 P1.5 (now Pause)
+was dropped: the backlight is U1 P1.0.
+
 ## 1. Summary
 
 The LPC1114 is replaced by software on the Linux board, with the S1D13700 LCD
@@ -166,8 +184,8 @@ TC/R are module parameters.
 
 ### Device tree (`linux/dts/radio-panel.dts`)
 
-Binds U1 to the driver, U2 to `gpio-pca953x`, and defines `radio-keys` and
-`radio-backlight`. Numeric constants are used so it works with
+Binds U1 to the driver, U2 (0x76) to `gpio-pca953x`, and defines
+`radio-keys`; the backlight comes from the driver. Numeric constants are used so it works with
 `armbian-add-overlay`. Wiring tables are in `linux/README.md`.
 
 ## 5. Bus cost
@@ -256,7 +274,10 @@ cost on the board.
 - [ ] Decide whether the A0 extra cycle can go
 
 **Phase 1: keys and backlight**
-- [ ] Rewire the keypad for direct sensing, 13 pull-ups (see section 11)
+- [x] Rewire the keypad for direct sensing: active high, pull-downs, U2 at 0x76
+- [x] Key expander answers on the rig, idle reading clean
+- [ ] Press every key on `tests/hw_test.sh` (key screen), check repeat on Up/Down
+- [ ] Full UI with I²C keys against the fake MPD (`tests/hw_test.sh ui`)
 - [ ] Set the real root `compatible`, I²C bus and INT pin in the overlay
 - [ ] Check with `evtest`: all 13 keys, no bus traffic while idle
 - [ ] Check the backlight through sysfs
@@ -292,10 +313,8 @@ cost on the board.
 - Only XRGB8888 is exposed by the driver; gray conversion is a plain threshold with no dithering.
 - The layout assumes 240×160; other sizes need its constants changed.
 - `SLEEP` power save is not used; blanking is display-off only.
-- The overlay's `gpio-backlight` node (U2 P1.5) and the DRM driver (U1 P1.0)
-  both want the name `radio-backlight`. Only one may exist: drop the node from
-  the overlay if the backlight stays on U1, or the driver's registration if it
-  moves to U2.
+- Keys over i2c-dev are polled (50 reads/s) until `INT` is wired; the final
+  board can use the overlay's `gpio-keys` instead.
 - The window's log pane shows only application messages unless `--kmsg` is given, and then shows the desktop's log rather than the radio's.
 
 ## 11. Open questions

+ 159 - 10
radio/__main__.py

@@ -3,15 +3,18 @@
     radio-ui sim  [--host radio.lo]           window with the simulated panel
     radio-ui i2c  --bus N [--host H]          real panel through i2c-dev
     radio-ui drm  [--host H]                  real panel through the DRM driver
+    radio-ui keytest --bus N                  hardware test: panel shows the keys
 
-i2c and drm read keys from evdev; with --window-keys (test mode) they read the
-PC keyboard through a window on $DISPLAY instead.
+i2c reads the keys from the U2 expander on its bus (0x76). drm reads the evdev
+device radio-keys if there is one, otherwise U2 on the panel's own bus. With
+--window-keys (test mode) they also take the PC keyboard through a window on
+$DISPLAY.
 """
 import argparse
 import os
 import sys
 
-from . import platform
+from . import keypad, platform
 
 
 def _int(text):
@@ -44,6 +47,13 @@ def _add_keys(p, backlight_help):
     p.add_argument("--backlight", metavar="PATH", help=backlight_help)
 
 
+def _add_i2c_keys(p):
+    p.add_argument("--keys-addr", type=_int, default=keypad.DEFAULT_ADDR,
+                   help="key expander address (0x%02x)" % keypad.DEFAULT_ADDR)
+    p.add_argument("--keys-poll", type=int, default=keypad.POLL_MS, metavar="MS",
+                   help="key polling period (%(default)s ms)")
+
+
 def parse_args(argv):
     ap = argparse.ArgumentParser(prog="radio-ui", description="Radio front panel UI")
     sub = ap.add_subparsers(dest="frontend", metavar="FRONTEND")
@@ -73,10 +83,40 @@ def parse_args(argv):
     p.add_argument("--pattern", choices=("geometry", "gray"),
                    help="show a test pattern and exit")
     _add_keys(p, "backlight sysfs brightness file (default: expander pin P1.0)")
+    _add_i2c_keys(p)
+    p.add_argument("--no-i2c-keys", action="store_true",
+                   help="do not read the key expander; use evdev instead")
 
     p = sub.add_parser("drm", help="real panel through the s1d13700-tca DRM driver")
     _add_common(p, "localhost")
     _add_keys(p, "backlight sysfs brightness file (%s)" % platform.DEFAULT_BACKLIGHT)
+    p.add_argument("--keys-bus", type=int, metavar="N",
+                   help="read the key expander on /dev/i2c-N (default: the "
+                   "panel's bus, unless the evdev device %s exists)"
+                   % platform.DEFAULT_KEYS_NAME)
+    p.add_argument("--no-i2c-keys", action="store_true",
+                   help="never read the key expander; evdev only")
+    p.add_argument("--allow-adapter", metavar="NAME",
+                   help="accept the key bus adapter with this exact name")
+    p.add_argument("--pattern", choices=("geometry", "gray"),
+                   help="show a test pattern and exit")
+    _add_i2c_keys(p)
+
+    p = sub.add_parser("keytest", help="hardware test: the panel shows the key expander")
+    _add_geometry(p)
+    p.add_argument("--bus", type=int, required=True, help="I2C bus number")
+    p.add_argument("--addr", type=_int, default=0x74, help="panel expander address (0x74)")
+    p.add_argument("--allow-adapter", metavar="NAME",
+                   help="accept the adapter with this exact name")
+    p.add_argument("--no-panel", action="store_true",
+                   help="keys only, printed to stdout; leave the panel alone")
+    p.add_argument("--init-only", action="store_true",
+                   help="set up the panel (display and backlight on, key "
+                   "screen shown) and the key expander, then exit leaving "
+                   "them on")
+    p.add_argument("--exit-after", type=int, default=0, metavar="MS",
+                   help="quit after this many ms (default: on Ctrl-C)")
+    _add_i2c_keys(p)
 
     args = ap.parse_args(argv)
     if getattr(args, "tx_cap", 7) < 7 or getattr(args, "tx_cap", 0) > 1025:
@@ -124,16 +164,30 @@ def make_pattern(name, w, h):
 
 # ---- frontends -------------------------------------------------------------------
 
-def _start_keys(args, app, loop):
+def _start_keys(args, app, loop, i2c_fd=None):
+    """Key sources: the test mode window, the I2C expander (when i2c_fd is
+    given), an evdev device named by --input, or else the radio-keys one."""
+    found = False
     if args.window_keys:
         from . import gtkkeys
         gtkkeys.require_display()
         gtkkeys.KeyWindow(app.key, loop.quit)
         print("test mode: keys from the window on %s" % os.environ.get("DISPLAY", "?"))
-        if args.input and not platform.start_evdev_keys(app.key, args.input):
+        found = True
+    if i2c_fd is not None:
+        if keypad.start(i2c_fd, args.keys_addr, app.key, args.keys_poll):
+            print("keys: expander at 0x%02x, polled every %d ms"
+                  % (args.keys_addr, args.keys_poll))
+            found = True
+    if args.input:
+        if platform.start_evdev_keys(app.key, args.input):
+            found = True
+        else:
             print("cannot read %s" % args.input, file=sys.stderr)
-    elif not platform.start_evdev_keys(app.key, args.input):
-        print("no key input device, running display-only", file=sys.stderr)
+    elif not found:
+        found = platform.start_evdev_keys(app.key)
+    if not found:
+        print("no key input, running display-only", file=sys.stderr)
 
 
 def run_i2c(args):
@@ -187,7 +241,7 @@ def run_i2c(args):
 
     loop = GLib.MainLoop()
     app = App(args.host, args.port, args.width, args.height, present, backlight, args.kmsg)
-    _start_keys(args, app, loop)
+    _start_keys(args, app, loop, None if args.no_i2c_keys else fd)
     platform.run(loop)
     app.close()
     try:
@@ -210,6 +264,26 @@ def run_drm(args):
         return 1
     blpath = args.backlight or platform.DEFAULT_BACKLIGHT
 
+    if args.pattern:
+        dev.present(make_pattern(args.pattern, dev.width, dev.height), dev.width * 4,
+                    0, 0, dev.width, dev.height)
+        platform.backlight_set(blpath, True)
+        print("pattern shown on card%d" % dev.card)
+        return 0
+
+    keys_bus = args.keys_bus
+    if keys_bus is None and not args.no_i2c_keys and not args.input \
+            and not platform.have_keys_device():
+        keys_bus = dev.i2c_bus()
+    keys_fd = None
+    if keys_bus is not None:
+        try:
+            keys_fd = platform.open_i2c_bus(keys_bus, args.allow_adapter)
+        except platform.BusRefused as e:
+            print(e, file=sys.stderr)
+            if args.keys_bus is not None:
+                return 1
+
     def present(*a):
         try:
             dev.present(*a)
@@ -219,12 +293,86 @@ def run_drm(args):
     loop = GLib.MainLoop()
     app = App(args.host, args.port, dev.width, dev.height, present,
               lambda on: platform.backlight_set(blpath, on), args.kmsg)
-    _start_keys(args, app, loop)
+    _start_keys(args, app, loop, keys_fd)
     platform.run(loop)
     app.close()
     return 0
 
 
+def run_keytest(args):
+    from gi.repository import GLib
+
+    from .keytest import KeyTest
+
+    try:
+        fd = platform.open_i2c_bus(args.bus, args.allow_adapter)
+    except platform.BusRefused as e:
+        print(e, file=sys.stderr)
+        return 1
+
+    exp = keypad.Expander(fd, args.keys_addr)
+    try:
+        exp.setup()
+        raw = exp.read_inputs()
+    except OSError as e:
+        print("key expander at 0x%02x: %s" % (args.keys_addr, e.strerror), file=sys.stderr)
+        return 1
+    print("key expander at 0x%02x: P0=%02x P1=%02x (all keys up: 00 00)"
+          % (args.keys_addr, raw & 0xff, raw >> 8))
+    stuck = [keypad.KEY_PINS[b] for b in sorted(keypad.KEY_PINS) if raw & (1 << b)]
+    if stuck:
+        print("held or stuck high at start: " + ", ".join(stuck))
+    if raw & ~keypad.KEY_MASK:
+        print("unused pins P0.0-P0.2 read high: %02x" % (raw & ~keypad.KEY_MASK))
+
+    present = lambda *a: None   # noqa: E731
+    panel = None
+    if not args.no_panel:
+        from .panel import Panel
+        panel = Panel(args.width, args.height, args.bpp, args.tcr, fd=fd, addr=args.addr)
+        try:
+            panel.backlight(True)
+            panel.init()
+        except OSError as e:
+            print(e, file=sys.stderr)
+            return 1
+
+        def present(data, stride, x, y, w, h):
+            try:
+                panel.update(data, stride, x, y, w, h)
+            except OSError as e:
+                print("panel update failed: %s" % e, file=sys.stderr)
+
+    test = KeyTest(args.width, args.height, present)
+    if args.init_only:
+        test.on_raw(raw)    # draws the key screen
+        print("initialised; panel and backlight left on")
+        return 0
+    poller = keypad.KeyPoller(exp, test.on_event, test.on_raw, args.keys_poll)
+
+    def watch_errors():
+        if poller.errors != test.errors:
+            test.draw(poller.errors)
+        return True
+
+    GLib.timeout_add(500, watch_errors)
+    loop = GLib.MainLoop()
+    if args.exit_after:
+        GLib.timeout_add(args.exit_after, lambda: loop.quit() or False)
+    print("press the keys; Ctrl-C quits")
+    platform.run(loop)
+    poller.close()
+    print("%d presses, %d repeats, %d read errors"
+          % (test.presses, test.repeats, poller.errors))
+    if panel:
+        try:
+            panel.display(False)
+            panel.backlight(False)
+        except OSError:
+            pass
+    return 0
+
+
 def run_sim(args):
     from . import sim   # first: it picks the Gtk version
     from gi.repository import GLib, Gtk
@@ -236,7 +384,8 @@ def run_sim(args):
 
 def main(argv=None):
     args = parse_args(sys.argv[1:] if argv is None else argv)
-    return {"sim": run_sim, "i2c": run_i2c, "drm": run_drm}[args.frontend](args)
+    return {"sim": run_sim, "i2c": run_i2c, "drm": run_drm,
+            "keytest": run_keytest}[args.frontend](args)
 
 
 if __name__ == "__main__":

+ 9 - 0
radio/drm.py

@@ -124,6 +124,7 @@ class DrmPanel(object):
             if v:
                 self.lib.drmFreeVersion(v)
             if match:
+                self.card = i
                 return fd
             os.close(fd)
         raise DrmError("no %s DRM device found" % DRIVER_NAME)
@@ -176,6 +177,14 @@ class DrmPanel(object):
                               ctypes.byref(self.mode)):
             raise _errno_error("SETCRTC")
 
+    def i2c_bus(self):
+        """Number of the I2C bus the panel is on, from sysfs, or None"""
+        try:
+            dev = os.path.realpath("/sys/class/drm/card%d/device" % self.card)
+            return int(os.path.basename(dev).split("-", 1)[0])
+        except (OSError, ValueError):
+            return None
+
     def present(self, data, stride, x, y, w, h):
         for row in range(y, y + h):
             src = row * stride + x * 4

+ 239 - 0
radio/keypad.py

@@ -0,0 +1,239 @@
+"""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: "play",
+    13: "pause",
+    14: "stop",
+    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
+
+    def feed(self, raw, 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]:
+                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), 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)
+
+    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)

+ 93 - 0
radio/keytest.py

@@ -0,0 +1,93 @@
+"""Hardware test: the panel shows the keys of U2, a pressed key drawn inverted,
+with the raw input ports and an event count. Every event goes to stdout too.
+
+No MPD and no backlight timeout: only the panel and the key expander."""
+import cairo
+
+from . import keypad, render    # render picks the Pango version
+from gi.repository import Pango  # noqa: E402
+
+# pin order, as wired: P0.3-P0.7, then P1.0-P1.3, then P1.4-P1.7
+ROWS = (
+    (3, 4, 5, 6, 7),
+    (8, 9, 10, 11),
+    (12, 13, 14, 15),
+)
+BOX_W, BOX_H, GAP = 44, 26, 3
+TOP = 16
+INFO_Y = TOP + 3 * (BOX_H + GAP) + 4
+
+
+class KeyTest(object):
+    def __init__(self, width, height, present):
+        self.width, self.height = width, height
+        self.present = present
+        self.surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
+        self.raw = None
+        self.presses = 0
+        self.repeats = 0
+        self.last = ""
+        self.errors = 0
+        self.down = set()
+
+    def on_event(self, key, value):
+        if value == 1:
+            self.presses += 1
+            self.down.add(key)
+            self.last = key
+        elif value == 2:
+            self.repeats += 1
+        else:
+            self.down.discard(key)
+        print("%-6s %s" % (key, ("released", "pressed", "repeat")[value]), flush=True)
+        if value != 2:
+            self.draw()
+
+    def on_raw(self, raw):
+        self.raw = raw
+        print("raw P0=%02x P1=%02x" % (raw & 0xff, raw >> 8), flush=True)
+        self.draw()
+
+    def draw(self, errors=None):
+        if errors is not None:
+            self.errors = errors
+        cr = cairo.Context(self.surface)
+        cr.set_source_rgb(1, 1, 1)
+        cr.paint()
+        cr.set_source_rgb(0, 0, 0)
+        render._text(cr, render.FONT_STATUS, 1, 1, self.width - 2, Pango.Alignment.LEFT,
+                     "Test klawiszy")
+
+        cr.set_line_width(1)
+        for r, row in enumerate(ROWS):
+            for c, bit in enumerate(row):
+                x = 1 + c * (BOX_W + GAP)
+                y = TOP + r * (BOX_H + GAP)
+                key = keypad.KEY_PINS[bit]
+                pressed = key in self.down
+                cr.set_source_rgb(0, 0, 0)
+                cr.rectangle(x + 0.5, y + 0.5, BOX_W - 1, BOX_H - 1)
+                if pressed:
+                    cr.fill()
+                    cr.set_source_rgb(1, 1, 1)
+                else:
+                    cr.stroke()
+                render._text(cr, render.FONT_SMALL, x, y + 2, BOX_W, Pango.Alignment.CENTER, key)
+                render._text(cr, render.FONT_SMALL, x, y + 13, BOX_W, Pango.Alignment.CENTER,
+                             keypad.pin_name(bit))
+
+        cr.set_source_rgb(0, 0, 0)
+        raw = "--" if self.raw is None else "P0=%02x P1=%02x" % (self.raw & 0xff, self.raw >> 8)
+        lines = (
+            "wejścia: " + raw,
+            "naciśnięcia: %d  powtórzenia: %d" % (self.presses, self.repeats),
+            "ostatni: " + (self.last or "-"),
+            "błędy odczytu: %d" % self.errors,
+        )
+        for i, text in enumerate(lines):
+            render._text(cr, render.FONT_SMALL, 1, INFO_Y + i * 11, self.width - 2,
+                         Pango.Alignment.LEFT, text)
+        del cr
+        self.surface.flush()
+        self.present(self.surface.get_data(), self.surface.get_stride(), 0, 0,
+                     self.width, self.height)

+ 9 - 0
radio/platform.py

@@ -61,6 +61,15 @@ def _find_keys_device():
     return -1
 
 
+def have_keys_device():
+    """Whether a readable evdev device named DEFAULT_KEYS_NAME exists"""
+    fd = _find_keys_device()
+    if fd < 0:
+        return False
+    os.close(fd)
+    return True
+
+
 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."""

+ 163 - 0
tests/hw_test.sh

@@ -0,0 +1,163 @@
+#!/bin/sh
+# Hardware test on the USB I2C rig: panel U1 (0x74) and keys U2 (0x76).
+#
+#   tests/hw_test.sh [-b BUS] [MODE]
+#
+# MODE:
+#   keys      (default) init the panel, show the keys on it; Ctrl-C quits
+#   keys-only the keys printed to the terminal, panel untouched
+#   pattern   geometry and gray patterns, a few seconds each, then keys
+#   ui        the full UI with the I2C keys, against the fake MPD (port 6601),
+#             never the real player; commands go to build/mpd-commands.log
+#   init      set up the panel (i2c-dev) and U2, then exit leaving them on
+#   drm       (sudo) load s1d13700-tca and bind it to 0x74, show a pattern,
+#             backlight on, set up U2; left active for radio-ui drm etc.
+#   release   (sudo) unbind the DRM driver from 0x74 again
+#
+# Without -b, the bus is the one whose adapter is named i2c-tiny-usb. Only the
+# names in /sys are read: no bus is scanned.
+set -eu
+
+cd "$(dirname "$0")/.."
+
+bus=
+while getopts b:h opt; do
+	case $opt in
+	b) bus=$OPTARG ;;
+	*) sed -n '2,18s/^# \{0,1\}//p' "$0"; exit 2 ;;
+	esac
+done
+shift $((OPTIND - 1))
+mode=${1:-keys}
+
+if [ -z "$bus" ]; then
+	for f in /sys/class/i2c-dev/i2c-*/name; do
+		case $(cat "$f") in
+		i2c-tiny-usb*)
+			[ -z "$bus" ] || { echo "more than one i2c-tiny-usb bus; pass -b" >&2; exit 1; }
+			bus=${f#/sys/class/i2c-dev/i2c-}
+			bus=${bus%/name} ;;
+		esac
+	done
+	[ -n "$bus" ] || { echo "no i2c-tiny-usb bus; plug the bridge in and run:" >&2
+		echo "  sudo modprobe i2c_tiny_usb delay=1" >&2; exit 1; }
+fi
+echo "bus i2c-$bus: $(cat /sys/class/i2c-dev/i2c-"$bus"/name)"
+
+DRV=s1d13700-tca
+KO=driver/$DRV.ko
+dev74=/sys/bus/i2c/devices/$bus-0074
+
+as_root() { if [ "$(id -u)" = 0 ]; then "$@"; else sudo "$@"; fi; }
+write_root() { echo "$2" | as_root tee "$1" >/dev/null; }
+bound_to() {	# driver name bound to $bus-$1, or nothing
+	[ -e "/sys/bus/i2c/devices/$bus-$1/driver" ] &&
+		basename "$(readlink "/sys/bus/i2c/devices/$bus-$1/driver")"
+	return 0
+}
+
+# A kernel driver bound to either chip would fight over i2c-dev access.
+# The DRM modes manage 0x74 themselves; U2 is always ours.
+for a in 0074 0076; do
+	case $mode:$a in drm:0074|release:0074) continue ;; esac
+	drv=$(bound_to $a)
+	if [ -n "$drv" ]; then
+		echo "0x${a#00} on i2c-$bus is bound to $drv; unbind it first:" >&2
+		[ "$drv" = $DRV ] && echo "  $0 -b $bus release" >&2 ||
+			echo "  echo $bus-$a | sudo tee /sys/bus/i2c/devices/$bus-$a/driver/unbind" >&2
+		exit 1
+	fi
+done
+
+[ -e build/libradiopanel.so ] || make lib
+
+ui() { ./radio-ui "$@"; }
+
+drm_setup() {
+	if [ ! -d /sys/module/s1d13700_tca ]; then
+		if [ ! -e $KO ] || [ "$(modinfo -F vermagic $KO | cut -d' ' -f1)" != "$(uname -r)" ]; then
+			make module
+		fi
+		for dep in $(modinfo -F depends $KO | tr , ' '); do
+			as_root modprobe "$dep"
+		done
+		as_root insmod $KO
+	fi
+	drv=$(bound_to 0074)
+	if [ -z "$drv" ]; then
+		if [ -e "$dev74" ]; then
+			write_root /sys/bus/i2c/drivers/$DRV/bind "$bus-0074"
+		else
+			write_root "/sys/bus/i2c/devices/i2c-$bus/new_device" "s1d13700-tca9539 0x74"
+		fi
+	elif [ "$drv" != $DRV ]; then
+		echo "0x74 on i2c-$bus is bound to $drv" >&2; exit 1
+	fi
+	i=0
+	until ls -d "$dev74"/drm/card* >/dev/null 2>&1; do
+		i=$((i + 1))
+		[ $i -lt 50 ] || { echo "no DRM card appeared for $bus-0074" >&2; exit 1; }
+		sleep 0.1
+	done
+	card=$(basename "$(ls -d "$dev74"/drm/card* | head -n 1)")
+	echo "$DRV bound to $bus-0074: /dev/dri/$card"
+	# udev sets the node's group and ACL a moment after it appears
+	command -v udevadm >/dev/null && udevadm settle --timeout=5 2>/dev/null || true
+	i=0
+	until [ -w /dev/dri/"$card" ]; do
+		i=$((i + 1))
+		[ $i -lt 50 ] || { echo "no write access to /dev/dri/$card (group video?)" >&2; exit 1; }
+		sleep 0.1
+	done
+	ui drm --pattern geometry
+	bl=/sys/class/backlight/radio-backlight/brightness
+	if [ -w $bl ]; then echo 1 > $bl; else write_root $bl 1; fi
+	ui keytest --bus "$bus" --no-panel --init-only
+	echo "left active. Try: ./radio-ui drm --host radio.lo    (keys from 0x76 on i2c-$bus)"
+	echo "undo with: $0 -b $bus release"
+}
+
+drm_release() {
+	drv=$(bound_to 0074)
+	if [ "$drv" = $DRV ]; then
+		# a device made by new_device goes away; one from DT only unbinds
+		write_root "/sys/bus/i2c/devices/i2c-$bus/delete_device" 0x74 2>/dev/null ||
+			write_root /sys/bus/i2c/drivers/$DRV/unbind "$bus-0074"
+		echo "$DRV released 0x74 on i2c-$bus (module left loaded)"
+	elif [ -n "$drv" ]; then
+		echo "0x74 on i2c-$bus is bound to $drv, not $DRV; left alone" >&2; exit 1
+	else
+		echo "nothing bound to 0x74 on i2c-$bus"
+	fi
+}
+
+case $mode in
+keys)
+	ui keytest --bus "$bus" ;;
+keys-only)
+	ui keytest --bus "$bus" --no-panel ;;
+pattern)
+	ui i2c --bus "$bus" --pattern geometry
+	sleep 3
+	ui i2c --bus "$bus" --pattern gray
+	sleep 3
+	ui keytest --bus "$bus" ;;
+ui)
+	mkdir -p build
+	log=build/mpd-commands.log
+	: > "$log"
+	python3 tests/fake_mpd.py 6601 "$log" 5 &
+	mpd_pid=$!
+	trap 'kill $mpd_pid 2>/dev/null' EXIT INT TERM
+	sleep 0.5
+	echo "MPD commands: $log"
+	ui i2c --bus "$bus" --host localhost --port 6601 || true ;;
+init)
+	ui keytest --bus "$bus" --init-only ;;
+drm)
+	drm_setup ;;
+release)
+	drm_release ;;
+*)
+	echo "unknown mode $mode (keys, keys-only, pattern, ui, init, drm, release)" >&2; exit 2 ;;
+esac

+ 157 - 1
tests/test_ui.py

@@ -2,6 +2,7 @@
 
 The MPD tests talk to tests/fake_mpd.py, never to a real player.
 """
+import ctypes
 import os
 import socket
 import subprocess
@@ -16,7 +17,7 @@ sys.path.insert(0, os.path.join(HERE, ".."))
 
 from gi.repository import GLib  # noqa: E402
 
-from radio import mpd, platform  # noqa: E402
+from radio import keypad, mpd, platform  # noqa: E402
 from radio import state as st  # noqa: E402
 from radio.__main__ import make_pattern, parse_args  # noqa: E402
 from radio.app import App  # noqa: E402
@@ -263,7 +264,162 @@ class TestPlatform(unittest.TestCase):
     def test_args(self):
         a = parse_args(["i2c", "--bus", "11", "--addr", "0x75", "--window-keys"])
         self.assertEqual((a.bus, a.addr, a.window_keys, a.host), (11, 0x75, True, "localhost"))
+        self.assertEqual((a.keys_addr, a.no_i2c_keys), (0x76, False))
         self.assertEqual(parse_args(["sim"]).host, "radio.lo")
+        a = parse_args(["keytest", "--bus", "11", "--keys-addr", "0x77"])
+        self.assertEqual((a.bus, a.addr, a.keys_addr, a.no_panel), (11, 0x74, 0x77, False))
+        a = parse_args(["drm", "--keys-bus", "11"])
+        self.assertEqual((a.keys_bus, a.keys_addr), (11, 0x76))
+        a = parse_args(["drm", "--pattern", "gray"])
+        self.assertEqual((a.keys_bus, a.no_i2c_keys, a.pattern), (None, False, "gray"))
+        self.assertTrue(parse_args(["keytest", "--bus", "1", "--init-only"]).init_only)
+
+
+def _raw(*keys):
+    """Input port reading with these keys held: every other pin reads low"""
+    raw = 0
+    for bit, name in keypad.KEY_PINS.items():
+        if name in keys:
+            raw |= 1 << bit
+    return raw
+
+
+class FakeExpander(object):
+    """Stands in for fcntl.ioctl(I2C_RDWR): records writes, answers reads"""
+
+    def __init__(self, inputs=0):
+        self.inputs = inputs
+        self.writes = []
+        self.reg = 0
+
+    def ioctl(self, fd, req, arg):
+        assert req == keypad.I2C_RDWR
+        msgs = (keypad._I2cMsg * arg.nmsgs).from_address(arg.msgs)
+        for m in msgs:
+            buf = (ctypes.c_uint8 * m.len).from_address(m.buf)
+            if m.flags & keypad.I2C_M_RD:
+                for i in range(m.len):
+                    buf[i] = (self.inputs >> (8 * ((self.reg + i) & 1))) & 0xff
+            else:
+                self.reg = buf[0]
+                if m.len > 1:
+                    self.writes.append((m.addr, list(buf)))
+        return 0
+
+
+class TestKeypad(unittest.TestCase):
+    def test_pins_match_overlay(self):
+        with open(os.path.join(HERE, "..", "dts", "radio-panel.dts")) as f:
+            dts = f.read()
+        import re
+        found = dict((int(pin), label) for label, pin in re.findall(
+            r'label = "(\w+)";\s*gpios = <&radio_u2 (\d+) 0>', dts))
+        self.assertEqual(found, keypad.KEY_PINS)
+        self.assertIn("reg = <0x%02x>" % keypad.DEFAULT_ADDR, dts)
+        self.assertEqual(keypad.KEY_MASK & 0x0007, 0)    # P0.0-P0.2 unused
+
+    def test_expander_setup_and_read(self):
+        fake = FakeExpander(_raw("next", "prev"))
+        with mock.patch.object(keypad.fcntl, "ioctl", fake.ioctl):
+            exp = keypad.Expander(3, 0x76)
+            exp.setup()
+            raw = exp.read_inputs()
+        self.assertEqual(fake.writes, [(0x76, [0x04, 0, 0]), (0x76, [0x06, 0xff, 0xff])])
+        self.assertEqual(raw, (1 << 3) | (1 << 15))
+
+    def test_debounce_and_release(self):
+        sc = keypad.KeyScanner()
+        self.assertEqual(sc.feed(_raw(), 0), [])
+        self.assertEqual(sc.feed(_raw("ok"), 20), [])          # one sample: bounce
+        self.assertEqual(sc.feed(_raw(), 40), [])
+        self.assertEqual(sc.feed(_raw("ok"), 60), [])
+        self.assertEqual(sc.feed(_raw("ok"), 80), [("ok", 1)])
+        self.assertEqual(sc.pressed_keys(), ["ok"])
+        self.assertEqual(sc.feed(_raw(), 100), [])
+        self.assertEqual(sc.feed(_raw(), 120), [("ok", 0)])
+        # unused pins pulled high change nothing
+        self.assertEqual(sc.feed(0x0007, 140), [])
+        self.assertEqual(sc.feed(0x0007, 160), [])
+
+    def test_autorepeat(self):
+        sc = keypad.KeyScanner()
+        sc.feed(_raw("up"), 0)
+        self.assertEqual(sc.feed(_raw("up"), 20), [("up", 1)])
+        self.assertEqual(sc.feed(_raw("up"), 260), [])
+        self.assertEqual(sc.feed(_raw("up"), 280), [("up", 2)])
+        self.assertEqual(sc.feed(_raw("up"), 300), [])
+        self.assertEqual(sc.feed(_raw("up"), 320), [("up", 2)])
+        sc.feed(_raw(), 340)
+        self.assertEqual(sc.feed(_raw(), 360), [("up", 0)])
+        self.assertEqual(sc.feed(_raw(), 1000), [])
+
+    def test_held_at_start_ignored(self):
+        sc = keypad.KeyScanner(ignore_initial=True)
+        self.assertEqual(sc.feed(_raw("stop"), 0), [])
+        self.assertEqual(sc.feed(_raw("stop"), 1000), [])     # no repeat either
+        sc.feed(_raw(), 1020)
+        self.assertEqual(sc.feed(_raw(), 1040), [("stop", 0)])
+        sc.feed(_raw("stop"), 1060)
+        self.assertEqual(sc.feed(_raw("stop"), 1080), [("stop", 1)])
+
+    def test_too_many_keys_ignored(self):
+        sc = keypad.KeyScanner(max_keys=3)
+        sc.feed(_raw("up"), 0)
+        self.assertEqual(sc.feed(_raw("up"), 20), [("up", 1)])
+        for t in range(40, 1000, 20):          # bus fault: all high
+            self.assertEqual(sc.feed(0xffff, t), [])
+        self.assertTrue(sc.faulty)
+        sc.feed(_raw(), 1000)
+        self.assertEqual(sc.feed(_raw(), 1020), [("up", 0)])
+        sc.feed(_raw("ok", "left", "right"), 1040)
+        self.assertEqual(len(sc.feed(_raw("ok", "left", "right"), 1060)), 3)
+
+    def test_two_keys(self):
+        sc = keypad.KeyScanner()
+        sc.feed(_raw("play", "left"), 0)
+        self.assertEqual(sc.feed(_raw("play", "left"), 20), [("left", 1), ("play", 1)])
+
+    def test_poller_feeds_app_and_survives_errors(self):
+        fake = FakeExpander()
+        got = []
+        with mock.patch.object(keypad.fcntl, "ioctl", fake.ioctl):
+            poller = keypad.start(3, 0x76, got.append, poll_ms=5)
+            try:
+                fake.inputs = 0xffff                # all high: a fault
+                run_loop_until(lambda: False, 0.1)
+                self.assertEqual(got, [])
+                fake.inputs = _raw("stop")
+                self.assertTrue(run_loop_until(lambda: got, 2))
+                failing = mock.Mock(side_effect=OSError(5, "Input/output error"))
+                with mock.patch.object(keypad.fcntl, "ioctl", failing):
+                    self.assertTrue(run_loop_until(lambda: poller.errors >= 2, 2))
+                fake.inputs = _raw()
+                self.assertTrue(run_loop_until(lambda: not poller.failing, 2))
+                fake.inputs = _raw("next")
+                self.assertTrue(run_loop_until(lambda: "next" in got, 2))
+            finally:
+                poller.close()
+        self.assertEqual(got[0], "stop")
+        # setup again after the bus came back
+        self.assertEqual(fake.writes.count((0x76, [0x06, 0xff, 0xff])), 2)
+
+    @unittest.skipUnless(have_panel_lib(), "needs `make lib`")
+    def test_keytest_screen(self):
+        from radio.keytest import KeyTest
+        panel = Panel()
+        panel.init()
+        test = KeyTest(240, 160, panel.update)
+        test.on_raw(_raw("menu"))
+        test.on_event("menu", 1)
+        self.assertEqual(panel.sim_faults(), 0)
+        shown, levels = panel.sim_render()
+        self.assertTrue(shown)
+        # the menu box (row 1, column 2) is filled: its corner is black
+        x = 1 + 2 * (44 + 3) + 2
+        y = 16 + 1 * (26 + 3) + 1
+        self.assertEqual(levels[y * 240 + x], 3)
+        test.on_event("menu", 0)
+        self.assertEqual(panel.sim_render()[1][y * 240 + x], 0)
 
 
 if __name__ == "__main__":