From 3333201df8ef5b21b62458e49e2321340b7f4278 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Mon, 5 Oct 2026 16:00:13 -0400 Subject: [PATCH] MeshTerm starts from the Cardputer Zero's launcher, on its own battery Tried on a real Cardputer Zero for the first time. It draws on the panel, takes the keyboard, and opens from M5's app launcher: scripts/cardputer-zero/launcher-entry.sh puts a source checkout there (and `remove` takes it off) until there is a store package. Three things the hardware showed: - The splash opened with the highlight on /dev/ttyS0, the Cap's GPS UART, because serial is listed first as found. Below the companions we've used, anything that looks like one now comes before a port nothing vouches for, across transports. - The title bar's battery is the handheld's own BQ27220, as the PicoCalc's is. The host pack is now found by what it is (a Battery supply that isn't a peripheral's), not by the PicoCalc's name. - While the Cap is powered, I2C bus 1 turns noisy: a quarter to three quarters of the gauge's reads fail with an I/O error (one in ten of the clock's), none with the header off. A failed read is asked again, a status that won't read keeps its last verdict, and a good reading stands through six failed polls instead of blinking out. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/devices/cardputer-zero.md | 55 +++++++++--- meshterm/platforms.py | 7 +- meshterm/services/battery_service.py | 107 +++++++++++++++++++---- meshterm/ui/device_picker.py | 11 ++- scripts/README.md | 1 + scripts/cardputer-zero/launcher-entry.sh | 64 ++++++++++++++ scripts/cardputer-zero/meshterm.png | Bin 0 -> 7579 bytes tests/test_battery.py | 83 ++++++++++++++++-- tests/test_picocalc_lyra_chrome.py | 24 +++-- tests/test_tui.py | 16 ++++ 10 files changed, 317 insertions(+), 51 deletions(-) create mode 100644 scripts/cardputer-zero/launcher-entry.sh create mode 100644 scripts/cardputer-zero/meshterm.png diff --git a/docs/devices/cardputer-zero.md b/docs/devices/cardputer-zero.md index acaafbb..02eef4b 100644 --- a/docs/devices/cardputer-zero.md +++ b/docs/devices/cardputer-zero.md @@ -3,12 +3,12 @@ > [!CAUTION] > **The Cardputer Zero is not supported yet.** > -> MeshTerm has never run on a real Cardputer Zero. Everything on this page was built from -> M5Stack's published source code and documentation, and tested only in an emulator on a -> desktop computer. There is no package to install on the device, the screen and keyboard -> code has never touched the hardware, and the LoRa add-on board is not wired up at all. +> MeshTerm now runs on a real Cardputer Zero, with M5Stack's Cap LoRa-1262 as its radio, +> but only from a copy of the source code you set up yourself. There is no package in +> M5Stack's app store, and the keyboard has only been checked by sending key events to it +> from another computer, not by someone typing on it. > -> Don't buy a Cardputer Zero to run MeshTerm on it. This page will say so when that +> Don't buy a Cardputer Zero to run MeshTerm on it yet. This page will say so when that > changes. M5Stack makes three Cardputers. This page is about the **Cardputer Zero**: the one with a @@ -18,6 +18,7 @@ applies to them. - [The device](#the-device) - [Where the work stands](#where-the-work-stands) +- [Installing it on the device](#installing-it-on-the-device) - [Trying it in the emulator](#trying-it-in-the-emulator) - [Radios](#radios) @@ -41,21 +42,51 @@ character on the screen itself and reads the keys directly. ## Where the work stands -**Done, and tested only in the emulator:** +**Done, and tried on a real Cardputer Zero:** +- MeshTerm starts from M5Stack's app launcher and draws on the screen itself. - MeshTerm's layout for the 14-row screen: a title bar that also carries the unread count and the battery, one-row tab strips, and dialogs sized for the short screen. +- The battery in the title bar is the Cardputer Zero's own. - The row of function-key labels along the bottom of the screen, driven by **Fn+4** to **Fn+8**, the keys that sit right under the display. **Shift** with them is a second set. -- The program that draws MeshTerm on the screen, and a desktop emulator built on it. +- M5Stack's Cap LoRa-1262 radio add-on (see [Radios](#radios)). +- Holding **Esc** for three seconds, which is how the launcher closes any app, closes + MeshTerm properly. **Not done:** -- Running on the real device at all. -- A package for M5Stack's app store, so the launcher can start MeshTerm. -- The LoRa radio add-on (see [Radios](#radios)). -- Checking the keyboard on the device. Its layout was read from M5Stack's driver code, - and two printings of the keyboard exist. +- A package for M5Stack's app store. Until there is one, you install MeshTerm yourself + (see below). +- Typing on the real keyboard. The arrows, Enter, Esc, Fn+4 to Fn+8, and Shift have been + checked by sending their key events to the keyboard from another computer, and the + symbols on the Sym layer match M5Stack's own keymap on the device. Nobody has typed a + message on it yet. + +## Installing it on the device + +This is for people comfortable with a Linux command line. You need the Cardputer Zero on +Wi-Fi, and a way to type commands on it: SSH from another computer is easiest. + +Get MeshTerm and the radio library, and fetch the font the screen is drawn in: + +```bash +git clone https://github.com/jpmartineau/MeshTerm.git +cd MeshTerm +python3 -m venv .venv +.venv/bin/pip install -e '.[spi]' +.venv/bin/meshterm emulate --fetch-fonts +``` + +Then put MeshTerm in the launcher. This asks for your password once, because the launcher's +list of apps belongs to the system: + +```bash +scripts/cardputer-zero/launcher-entry.sh +``` + +MeshTerm now has an icon in the launcher. `scripts/cardputer-zero/launcher-entry.sh remove` +takes it out again. ## Trying it in the emulator diff --git a/meshterm/platforms.py b/meshterm/platforms.py index ced6050..c08c5d9 100644 --- a/meshterm/platforms.py +++ b/meshterm/platforms.py @@ -266,8 +266,9 @@ PICOCALC_LYRA = Platform( #: keys), dealing the PicoCalc's lanes for now (JP, 2026-09-30). MeshTerm draws the panel #: itself in RGB565 (:mod:`meshterm.emulator`), so it is not held to a 16-slot palette #: (``truecolor``). Provisional until measured on the device: the cadences, taken from the -#: PicoCalc; ``effects`` off; and the battery, read from the companion until the device's -#: own gauge (a BQ27220) has a known ``power_supply`` name. +#: PicoCalc; and ``effects`` off. The battery is the handheld's own BQ27220 gauge, which the +#: kernel publishes as the ``power_supply`` ``bq27220-0`` (seen on the device, 2026-10-05) — +#: the pack the reader is holding, whichever radio is connected, as on the PicoCalc. CARDPUTER_ZERO = Platform( name="cardputer-zero", readable_cols=53, @@ -293,7 +294,7 @@ CARDPUTER_ZERO = Platform( effects=False, tick_s=2.0, spinner_tick_s=0.5, - battery="companion", + battery="host", own_display=True, modifier_watch="tca8418c", ) diff --git a/meshterm/services/battery_service.py b/meshterm/services/battery_service.py index 4f3f50d..4735b4f 100644 --- a/meshterm/services/battery_service.py +++ b/meshterm/services/battery_service.py @@ -8,11 +8,11 @@ it holds no device subscription — each pass just checks whether a device is co skips quietly otherwise — so it is indifferent to reconnects, ticking across a link drop and resuming once the radio is back. -Which pack it reads is platform data (``Platform.battery``). On the **PicoCalc** the gauge is -the handheld's own — its BMS hangs off the keyboard MCU's I2C register block and the kernel -publishes it as a standard ``power_supply`` (:data:`_HOST_SUPPLY`), so both numbers are the -device's own ground truth: ``capacity`` is a real percent and ``status`` a real charging flag -(the MCU's battery register carries charge in its low bits and *charging* in its top one). +Which pack it reads is platform data (``Platform.battery``). On the **PicoCalc** and the +**Cardputer Zero** the gauge is the handheld's own, published by the kernel as a standard +``power_supply`` (:func:`host_supply`) — the PicoCalc's BMS through its keyboard MCU's I2C +register block, the Cardputer's through a BQ27220 fuel gauge — so both numbers are the +device's own ground truth: ``capacity`` is a real percent and ``status`` a real charging flag. Nothing below is estimated there — no voltage curve, no trend. The rest of this module is the **companion** path, where the radio gives far less. Two device @@ -80,9 +80,68 @@ _CHARGING_RISE_HOLD_MV = 8 #: How many samples to retain — the trend window plus a little slack at the poll cadence. _TREND_SAMPLES = int(_TREND_WINDOW_S / POLL_S) + 2 -#: The PicoCalc's own battery gauge, a standard kernel ``power_supply`` driver -#: (confirmed present in P0: ``capacity``, ``status``, Li-ion, uevent format). -_HOST_SUPPLY = Path("/sys/class/power_supply/picocalc") +#: Where the kernel lists every ``power_supply``. The host's own pack is the one of type +#: ``Battery`` that isn't a peripheral's (:func:`host_supply`): the PicoCalc's ``picocalc`` +#: (confirmed in P0) and the Cardputer Zero's BQ27220 gauge, ``bq27220-0``, both qualify by +#: what they are rather than by a name kept on a list. +_POWER_SUPPLIES = Path("/sys/class/power_supply") + +#: How often one sysfs value is tried before a poll gives up on it, and the pause between +#: tries. The Cardputer Zero's BQ27220 shares I2C bus 1 with the keyboard and the clock, +#: and while the Cap on its header is powered that bus turns noisy: measured on the device, +#: a quarter to three quarters of the gauge's reads fail with an I/O error, and one in ten +#: of the clock's, against none with the header off. A failed read says nothing about the +#: pack, so it is simply asked again. +_HOST_READ_ATTEMPTS = 6 +_HOST_RETRY_S = 0.1 + +#: How many polls in a row a host pack may fail to read before its gauge is taken down — a +#: pack doesn't change in two minutes, so the last reading stands rather than blinking out. +_HOST_MISSES_KEPT = 6 + + +async def _read_value(path: Path) -> str: + """One sysfs value, asked again on an I/O error (see :data:`_HOST_READ_ATTEMPTS`). + + Raises: + OSError: When every try failed. + """ + for attempt in range(_HOST_READ_ATTEMPTS): + try: + return path.read_text().strip() + except FileNotFoundError: + raise # no such value: asking again won't make one + except OSError: + if attempt == _HOST_READ_ATTEMPTS - 1: + raise + await asyncio.sleep(_HOST_RETRY_S) + raise OSError(f"{path} could not be read") # pragma: no cover - the loop always returns + + +def host_supply(root: Path = _POWER_SUPPLIES) -> Path | None: + """The host's own battery: the first ``Battery`` supply that isn't a peripheral's. + + A wireless mouse's or a game pad's battery is a ``power_supply`` too, and carries + ``scope = Device``; the host's carries no scope, or ``System``. ``None`` when there is + none, or the directory can't be read. + """ + try: + supplies = sorted(root.iterdir()) + except OSError: + return None + for supply in supplies: + try: + kind = (supply / "type").read_text().strip() + except OSError: + continue + try: + scope = (supply / "scope").read_text().strip() + except OSError: + scope = "" + if kind == "Battery" and scope != "Device": + return supply + return None + #: Single-cell LiPo terminal-voltage → state-of-charge lookup ``(millivolts, percent)``, #: high to low. The discharge curve is far from a straight line — most of the usable charge @@ -174,6 +233,8 @@ class BatteryService: self._reading: BatteryReading | None = None #: Recent ``(monotonic_time, millivolts)`` samples, for the charging trend. self._history: deque[tuple[float, int]] = deque(maxlen=_TREND_SAMPLES) + #: Host-pack reads failed in a row (see :data:`_HOST_MISSES_KEPT`). + self._host_misses = 0 @property def active(self) -> bool: @@ -226,7 +287,7 @@ class BatteryService: regular platform polls the connected companion radio over the mesh link. """ if get_platform().battery == "host": - self._poll_host() + await self._poll_host() return ctx = self._ctx if not ctx.is_connected: @@ -253,21 +314,33 @@ class BatteryService: charging=charging, ) - def _poll_host(self) -> None: - """Read the host's own pack from sysfs (the PicoCalc's ``picocalc`` supply). + async def _poll_host(self) -> None: + """Read the host's own pack from sysfs (:func:`host_supply`). The driver is a standard ``power_supply``: ``capacity`` is a true percent and ``status`` a real charging flag (verified in P0), so none of the companion path's voltage-curve or trend estimation applies. An unreadable supply (driver - missing, permissions) reports *absent* and the header simply draws no gauge. + missing, permissions) reports *absent* and the header simply draws no gauge — + once it has failed :data:`_HOST_MISSES_KEPT` polls running; a failed poll after a + good one keeps the good one. Each value is asked again on an I/O error first + (:func:`_read_value`), and a ``status`` that still won't read keeps the charging + verdict the last good one gave: the percent is the reading, the flag its garnish. """ - supply = _HOST_SUPPLY + supply = host_supply(_POWER_SUPPLIES) try: - percent = int((supply / "capacity").read_text().strip()) - status = (supply / "status").read_text().strip() + if supply is None: + raise OSError("no battery power_supply") + percent = int(await _read_value(supply / "capacity")) except (OSError, ValueError): - self._reading = None + self._host_misses += 1 + if self._host_misses > _HOST_MISSES_KEPT: + self._reading = None return + self._host_misses = 0 + try: + charging = await _read_value(supply / "status") == "Charging" + except OSError: + charging = self._reading.charging if self._reading is not None else False try: # informational only; the header draws percent + charging mv = int((supply / "voltage_now").read_text().strip()) // 1000 except (OSError, ValueError): @@ -275,7 +348,7 @@ class BatteryService: self._reading = BatteryReading( millivolts=mv, percent=max(0, min(100, percent)), - charging=status == "Charging", + charging=charging, ) def _charging(self, now: float) -> bool: diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 8257374..6c4e6cf 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -824,15 +824,20 @@ def _tag(device: DiscoveredDevice, is_known: bool) -> tuple[str, str]: def _order( devices: list[DiscoveredDevice], registry: dict[str, RememberedDevice] ) -> list[DiscoveredDevice]: - """Confirmed companions first (most-recently-used first), then everything else as found. + """Confirmed companions first (most-recently-used first), then likely ones, then the rest. The devices we've actually spoken to are the ones the user almost always wants, so they - rise to the top ordered by their last-connected timestamp (newest first). Unknown ports - keep their incoming discovery order — a stable sort preserves it since they all tie. + rise to the top ordered by their last-connected timestamp (newest first). Below them, + anything that looks like a companion — a MeshCore advert, a known board, a radio on the + SPI bus — comes before a port nothing vouches for, *across* transports: serial is listed + first as found, so a board's bare UART (a Cardputer Zero's ``/dev/ttyS0``, wired to its + Cap's GPS) used to open the splash with the highlight on it, above the Cap itself. Ties + keep their discovery order — the sort is stable. """ known = [d for d in devices if d.stable_id in registry] others = [d for d in devices if d.stable_id not in registry] known.sort(key=lambda d: registry[d.stable_id].last_connected, reverse=True) + others.sort(key=lambda d: not d.is_likely_lora) return known + others diff --git a/scripts/README.md b/scripts/README.md index 1b914a8..dbffa64 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -5,6 +5,7 @@ Repo-side tools. None of these ship in the wheel. | Script | What it is for | |---|---| | `basemap-doctor.py` | Why a user's map has no basemap — certificates, DNS, proxy, or colour depth | +| `cardputer-zero/` | `launcher-entry.sh` puts a source checkout on the Cardputer Zero's app launcher (and `remove` takes it off), until there is a store package; `meshterm.png` is its placeholder icon | | `picocalc-lyra/` | Calculinux device setup: console font, palette, Wi-Fi; `xiao-radio/` is the XIAO radio kit (firmware build, flashing, UART setup) | | `uconsole/` | The uConsole's always-on SPI bridge service (MeshTerm can also drive that radio directly, with no script at all — see `docs/devices/uconsole.md`) | diff --git a/scripts/cardputer-zero/launcher-entry.sh b/scripts/cardputer-zero/launcher-entry.sh new file mode 100644 index 0000000..ddd0dee --- /dev/null +++ b/scripts/cardputer-zero/launcher-entry.sh @@ -0,0 +1,64 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# launcher-entry -- put MeshTerm on the Cardputer Zero's app launcher, from a checkout. +# +# Usage: scripts/cardputer-zero/launcher-entry.sh [install|remove] +# +# The stock launcher (APPLaunch) lists what it finds in +# /usr/share/APPLaunch/applications. An entry with Terminal=false gets the panel and the +# keyboard to itself, the launcher naming them in APPLAUNCH_LINUX_FBDEV_DEVICE and +# APPLAUNCH_LINUX_KEYBOARD_DEVICE -- which is how `python -m meshterm.emulator` knows to +# draw on the panel rather than open a window. Holding Esc for three seconds still ends it: +# the launcher sends SIGTERM, and MeshTerm takes that as a quit. +# +# This is the developer's entry, run from a source checkout with its venv at .venv (see +# docs/devices/cardputer-zero.md). It writes into /usr/share, so it asks sudo for the two +# files and nothing else, then restarts the launcher so the icon appears. A store package +# will replace it; `remove` takes it out again. +set -eu + +HERE=$(cd "$(dirname "$0")" && pwd) +CHECKOUT=$(cd "$HERE/../.." && pwd) +PYTHON="$CHECKOUT/.venv/bin/python" +APPS=/usr/share/APPLaunch/applications +IMAGES=/usr/share/APPLaunch/share/images + +case "${1:-install}" in +install) + if [ ! -d "$APPS" ]; then + echo "no $APPS here -- this is for the Cardputer Zero's stock launcher" >&2 + exit 1 + fi + if ! "$PYTHON" -c "import meshterm.emulator" 2>/dev/null; then + echo "$PYTHON can't import MeshTerm -- make the venv first:" >&2 + echo " python3 -m venv .venv && .venv/bin/pip install -e '.[spi]'" >&2 + exit 1 + fi + entry=$(mktemp) + cat >"$entry" <&2 + exit 2 + ;; +esac + +if [ "${1:-install}" = install ] && [ ! -f "$HOME/.meshterm/fonts/ter-u12n.bdf" ]; then + echo "fetch the screen's font once: $CHECKOUT/.venv/bin/meshterm emulate --fetch-fonts" +fi +systemctl --user restart APPLaunch.service 2>/dev/null || echo "restart the launcher to see the change" diff --git a/scripts/cardputer-zero/meshterm.png b/scripts/cardputer-zero/meshterm.png new file mode 100644 index 0000000000000000000000000000000000000000..959a32f38449dfeb3d0fa406aa4052190b897426 GIT binary patch literal 7579 zcmV;M9c1E(P)E!PsC}0-I|IAtA@IA-f5(lZ7lvUO2Nr zUc%yC*u^&9m~iHR_*#r@3^5ql*zzISl68!Zxo5h&s`mZWGm2!%vSb~W760$GMl;h> z-CbY(XZ=+_z!@4=L{5`7hZBjxY`ou{S5Z-+tY5!gDJdxtYi7+7uwn&=kxgXDk|j!G zVyv0Y)ODC_o6=CkPw?0h@r*cSdRH9c$LCVI6>x z{|^Zu9WS`xy1%=e5OE(DaH*=QDt;ye2hIkRgNGd{3I(EIw-Mls;X{8U2s|1w%;ziD ztT6#96o3`tWILg^fRKuc3bJCw3V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7Q)ilgF0N*sANUBHMNf zgrTyJwlwDoUu9)^pZ5A9e?#DqJP?@Mg*v0OOmarf8AcyYV3FX1yZ`ddnti)Ipp<%Z zfK&qj7BcR3m;2+zvUo+s14_-lj}Fuw-1l8(+bJx*ixn)HWkIkY43nnKgm7VrJQ-!B zQ>ZuJ{_ymk2ZHj^2WdHSE~|S^DxWTO27ZnUMNyJaRaGKKYaXfDw`&Kb)SnYoxb(`I zJUW?LxH<3HKW6fbFHW9y{tv0Dg>B13w^&w)#*vXpryw4U%HqUWnAoJR0sMWa!J9ymJA zj${Ca742l)FO#V~vcK}-L!W%OBd5gC?x#7wTvsiXO9>2YhAGsVC=|FrFlnAEX$N#bPK{__S@y&L)$8s@$>p znMAZXk`q%1hFs+i09ybc+7ox=uhP3afnW$AF&BVk!X;(J6K0%uy)O{_oT?eJd=EO1 zGXE7FkdcQ*JISg=3hpo9)UC2D)5;{1Z`B>#yXMHj-FwgzrV?D~F$6#HA$z5N(On#iNlnGnI97?_bHv9kE<&s;NUbkIX xV;}bW*#~n3k7VxnTO4?2=nS2qGX%%b{{twL!>h+W;M)KI002ovPDHLkV1jYlmUaLD literal 0 HcmV?d00001 diff --git a/tests/test_battery.py b/tests/test_battery.py index d7092bd..44a7a6a 100644 --- a/tests/test_battery.py +++ b/tests/test_battery.py @@ -276,13 +276,14 @@ def test_battery_poller_charging_ignores_load_sag_and_flat_or_falling_packs() -> # --- the host pack (the PicoCalc's own power_supply) --------------------------------------- -def _host_supply(tmp_path, monkeypatch, **files: str): - """Stand a fake ``power_supply`` directory up and point the poller at it.""" - supply = tmp_path / "picocalc" +def _host_supply(tmp_path, monkeypatch, name: str = "picocalc", **files: str): + """Stand a fake ``power_supply`` class up, holding one battery, and point the poller at it.""" + supply = tmp_path / name supply.mkdir(exist_ok=True) - for name, value in files.items(): - (supply / name).write_text(f"{value}\n") - monkeypatch.setattr(battery_service, "_HOST_SUPPLY", supply) + (supply / "type").write_text("Battery\n") + for key, value in files.items(): + (supply / key).write_text(f"{value}\n") + monkeypatch.setattr(battery_service, "_POWER_SUPPLIES", tmp_path) return supply @@ -309,7 +310,7 @@ def test_host_pack_absent_when_the_supply_cant_be_read(tmp_path, monkeypatch) -> """No driver (or an unreadable one) reports *no battery*, so the header draws no gauge.""" monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) svc = _service([]) - monkeypatch.setattr(battery_service, "_HOST_SUPPLY", tmp_path / "nothing-here") + monkeypatch.setattr(battery_service, "_POWER_SUPPLIES", tmp_path / "nothing-here") asyncio.run(svc._poll()) assert svc.reading() is None # A supply that answers with junk is just as absent — never a bogus gauge. @@ -318,6 +319,74 @@ def test_host_pack_absent_when_the_supply_cant_be_read(tmp_path, monkeypatch) -> assert svc.reading() is None +def test_the_host_pack_is_found_by_what_it_is(tmp_path, monkeypatch) -> None: + """The Cardputer Zero's gauge has another name; a peripheral's battery is not the host's.""" + monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) + mouse = _host_supply(tmp_path, monkeypatch, name="hid-mouse-battery", capacity="5") + (mouse / "scope").write_text("Device\n") + charger = tmp_path / "AC" + charger.mkdir() + (charger / "type").write_text("Mains\n") + _host_supply(tmp_path, monkeypatch, name="bq27220-0", capacity="84", status="Charging") + svc = _service([]) + asyncio.run(svc._poll()) + assert svc.reading().percent == 84 and svc.reading().charging is True + + +def test_a_failed_read_keeps_the_last_reading_for_a_while(tmp_path, monkeypatch) -> None: + """A BQ27220 read fails now and then on the CM0's I2C; the gauge must not blink out.""" + monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) + supply = _host_supply(tmp_path, monkeypatch, capacity="84", status="Discharging") + svc = _service([]) + asyncio.run(svc._poll()) + (supply / "capacity").unlink() # the driver's read now fails + for _ in range(battery_service._HOST_MISSES_KEPT): + asyncio.run(svc._poll()) + assert svc.reading().percent == 84 + asyncio.run(svc._poll()) # one miss too many: the pack is gone, not just slow + assert svc.reading() is None + (supply / "capacity").write_text("83\n") + asyncio.run(svc._poll()) + assert svc.reading().percent == 83 + + +def _flaky_reads(monkeypatch, failures: dict[str, int]) -> None: + """Make each named sysfs file fail its next N reads with an I/O error, as on a noisy bus.""" + real = battery_service.Path.read_text + left = dict(failures) + + def read_text(self, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN202 + if left.get(self.name, 0) > 0: + left[self.name] -= 1 + raise OSError(121, "Remote I/O error") + return real(self, *args, **kwargs) + + monkeypatch.setattr(battery_service.Path, "read_text", read_text) + monkeypatch.setattr(battery_service, "_HOST_RETRY_S", 0) + + +def test_an_io_error_is_asked_again_not_believed(tmp_path, monkeypatch) -> None: + """With the Cap powered, a gauge read fails often and the next one answers.""" + monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) + _host_supply(tmp_path, monkeypatch, capacity="84", status="Charging") + _flaky_reads(monkeypatch, {"capacity": battery_service._HOST_READ_ATTEMPTS - 1}) + svc = _service([]) + asyncio.run(svc._poll()) + assert svc.reading().percent == 84 and svc.reading().charging is True + + +def test_a_status_that_will_not_read_keeps_the_last_verdict(tmp_path, monkeypatch) -> None: + """The percent is the reading; a flag lost to the bus keeps the one it had.""" + monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) + supply = _host_supply(tmp_path, monkeypatch, capacity="84", status="Charging") + svc = _service([]) + asyncio.run(svc._poll()) + (supply / "capacity").write_text("85\n") + _flaky_reads(monkeypatch, {"status": battery_service._HOST_READ_ATTEMPTS}) + asyncio.run(svc._poll()) + assert svc.reading().percent == 85 and svc.reading().charging is True + + # --- the standard BLE charging flag (GATT Battery Level Status, 0x2BED) -------------------- diff --git a/tests/test_picocalc_lyra_chrome.py b/tests/test_picocalc_lyra_chrome.py index e4ea295..0708cfd 100644 --- a/tests/test_picocalc_lyra_chrome.py +++ b/tests/test_picocalc_lyra_chrome.py @@ -3,6 +3,8 @@ from __future__ import annotations +import asyncio + from rich.cells import cell_len from rich.text import Text @@ -384,22 +386,26 @@ def test_host_battery_reads_the_sysfs_supply(tmp_path, monkeypatch) -> None: """The PicoCalc battery path: a true percent and charging flag straight from sysfs.""" from meshterm.services import battery_service - (tmp_path / "capacity").write_text("53\n") - (tmp_path / "status").write_text("Discharging\n") - (tmp_path / "voltage_now").write_text("4012000\n") - monkeypatch.setattr(battery_service, "_HOST_SUPPLY", tmp_path) + supply = tmp_path / "picocalc" + supply.mkdir() + (supply / "type").write_text("Battery\n") + (supply / "capacity").write_text("53\n") + (supply / "status").write_text("Discharging\n") + (supply / "voltage_now").write_text("4012000\n") + monkeypatch.setattr(battery_service, "_POWER_SUPPLIES", tmp_path) service = battery_service.BatteryService(ctx=None) - service._poll_host() + asyncio.run(service._poll_host()) reading = service.reading() assert reading is not None assert (reading.percent, reading.charging, reading.millivolts) == (53, False, 4012) - (tmp_path / "status").write_text("Charging\n") - service._poll_host() + (supply / "status").write_text("Charging\n") + asyncio.run(service._poll_host()) assert service.reading().charging is True - monkeypatch.setattr(battery_service, "_HOST_SUPPLY", tmp_path / "gone") - service._poll_host() + monkeypatch.setattr(battery_service, "_POWER_SUPPLIES", tmp_path / "gone") + for _ in range(battery_service._HOST_MISSES_KEPT + 1): + asyncio.run(service._poll_host()) assert service.reading() is None # unreadable supply = absent, header draws nothing diff --git a/tests/test_tui.py b/tests/test_tui.py index f032ae4..a7c390f 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -1717,6 +1717,22 @@ def test_device_picker_names_and_sorts_known_devices(tmp_path) -> None: assert any(_BLE_ICON in row.plain for row in device_rows) +def test_device_picker_ranks_likely_companions_above_a_bare_port() -> None: + """A board's own UART (no USB identity) sinks below companions on any transport. + + On a Cardputer Zero, ``/dev/ttyS0`` is the Cap's GPS: listed first because serial is + scanned first, it opened the splash with the highlight on a port that can't be a node. + """ + from meshterm.core.config import SpiWiring + from meshterm.core.discovery import DiscoveredDevice, spi_device + from meshterm.ui.device_picker import _order + + uart = DiscoveredDevice(port="/dev/ttyS0", description="n/a") + ble = DiscoveredDevice(transport="ble", address="AA:BB", name="MeshCore-Roam") + cap = spi_device(SpiWiring(bus_id=0, cs_id=1), name="Cap LoRa-1262") + assert _order([uart, ble, cap], {}) == [ble, cap, uart] + + def test_device_picker_reinjects_remembered_tcp_device(tmp_path) -> None: """A remembered TCP companion reappears in the picker even though it can't be scanned for.""" from meshterm.core.device_store import DeviceStore