From db4cc657fe245361427af4c435696d7c3edfa856 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Mon, 5 Oct 2026 16:13:02 -0400 Subject: [PATCH] The Cardputer's battery reading survives the Cap's noisy bus With the Cap powered, I2C bus 1 doesn't only fail reads: some come back garbled (a capacity of 56414, clamped to a confident 100), and the kernel's bq27xxx driver caches whatever it read, failure or garbage, for five seconds. Retrying 0.1 s apart only re-read the cache, so every retry missed. Now an unreadable or out-of-range percent is asked again 5.5 s later, past the cache; a step of more than 5 points between polls waits for the next poll to confirm it, which catches garbage that lands inside 0-100; and the sysfs reads leave the event loop, since a failing transfer on that bus takes its time. Measured on the device with the Cap on: a steady 96%, where it showed nothing or 100 before. Co-Authored-By: Claude Opus 5.5 (1M context) --- meshterm/services/battery_service.py | 82 +++++++++++++++++++--------- tests/test_battery.py | 51 ++++++++++++++++- 2 files changed, 105 insertions(+), 28 deletions(-) diff --git a/meshterm/services/battery_service.py b/meshterm/services/battery_service.py index 4735b4f..5c0b3ec 100644 --- a/meshterm/services/battery_service.py +++ b/meshterm/services/battery_service.py @@ -86,36 +86,57 @@ _TREND_SAMPLES = int(_TREND_WINDOW_S / POLL_S) + 2 #: 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, +#: How often the pack's percent is asked for before a poll gives up, and the pause between +#: asks. 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 +#: a quarter to three quarters of the gauge's reads fail with an I/O error (one in ten of +#: the clock's), against none with the header off, and some that "succeed" are garbled — +#: a ``capacity`` of 56414. The kernel's ``bq27xxx`` driver caches what it read, failure or +#: garbage alike, for five seconds, so asking again sooner only gets the same answer back: +#: the pause is just past that. +_HOST_READ_ATTEMPTS = 3 +_HOST_RETRY_S = 5.5 #: 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 +#: The most a percent may move between two polls and be believed at once. A pack doesn't +#: gain or lose this much in :data:`POLL_S`; a bigger step is held until the next poll says +#: the same, which catches a garbled read that happens to land inside 0–100. +_HOST_STEP_PCT = 5 -async def _read_value(path: Path) -> str: - """One sysfs value, asked again on an I/O error (see :data:`_HOST_READ_ATTEMPTS`). + +async def _sysfs(path: Path) -> str: + """One sysfs value, read off the event loop. + + Reading a gauge's value can make the kernel talk to it over I2C, and on a noisy bus a + failing transfer takes its time; the loop drawing the screen shouldn't wait on it. + """ + return (await asyncio.to_thread(path.read_text)).strip() + + +async def _read_percent(path: Path) -> int: + """The pack's percent from ``capacity``, asked again while it is unreadable or garbled. + + An I/O error and a percent outside 0–100 are the same thing here — no reading — and are + asked again after :data:`_HOST_RETRY_S`, by which time the driver reads the gauge anew. Raises: - OSError: When every try failed. + OSError: When :data:`_HOST_READ_ATTEMPTS` tries gave no percent. """ for attempt in range(_HOST_READ_ATTEMPTS): + if attempt: + await asyncio.sleep(_HOST_RETRY_S) try: - return path.read_text().strip() + value = int(await _sysfs(path)) 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 + except (OSError, ValueError): + continue + if 0 <= value <= 100: + return value + raise OSError(f"{path} gave no percent") def host_supply(root: Path = _POWER_SUPPLIES) -> Path | None: @@ -235,6 +256,8 @@ class BatteryService: 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 + #: A host percent too far from the shown one to believe yet (:data:`_HOST_STEP_PCT`). + self._host_unconfirmed: int | None = None @property def active(self) -> bool: @@ -322,32 +345,41 @@ class BatteryService: path's voltage-curve or trend estimation applies. An unreadable supply (driver 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. + good one keeps the good one. The percent is asked again while it is unreadable or + out of range (:func:`_read_percent`), and a step bigger than + :data:`_HOST_STEP_PCT` waits for the next poll to confirm it. ``status`` is read + from the same driver snapshot as the percent; when it won't read, the charging + verdict the last good one gave stands: the percent is the reading, the flag its + garnish. """ supply = host_supply(_POWER_SUPPLIES) try: if supply is None: raise OSError("no battery power_supply") - percent = int(await _read_value(supply / "capacity")) - except (OSError, ValueError): + percent = await _read_percent(supply / "capacity") + except OSError: self._host_misses += 1 if self._host_misses > _HOST_MISSES_KEPT: self._reading = None return self._host_misses = 0 + shown = self._reading + if shown is not None and abs(percent - shown.percent) > _HOST_STEP_PCT: + if percent != self._host_unconfirmed: + self._host_unconfirmed = percent # believed when the next poll says it too + return + self._host_unconfirmed = None try: - charging = await _read_value(supply / "status") == "Charging" + charging = await _sysfs(supply / "status") == "Charging" except OSError: - charging = self._reading.charging if self._reading is not None else False + charging = shown.charging if shown is not None else False try: # informational only; the header draws percent + charging - mv = int((supply / "voltage_now").read_text().strip()) // 1000 + mv = int(await _sysfs(supply / "voltage_now")) // 1000 except (OSError, ValueError): mv = 0 self._reading = BatteryReading( millivolts=mv, - percent=max(0, min(100, percent)), + percent=percent, charging=charging, ) diff --git a/tests/test_battery.py b/tests/test_battery.py index 44a7a6a..5a316e4 100644 --- a/tests/test_battery.py +++ b/tests/test_battery.py @@ -12,6 +12,8 @@ import asyncio import time from types import SimpleNamespace +import pytest + from meshterm.core.connection import charging_from_battery_level_status from meshterm.services import battery_service from meshterm.services.battery_service import ( @@ -276,6 +278,12 @@ def test_battery_poller_charging_ignores_load_sag_and_flat_or_falling_packs() -> # --- the host pack (the PicoCalc's own power_supply) --------------------------------------- +@pytest.fixture(autouse=True) +def _no_retry_pause(monkeypatch) -> None: + """The host pack's retries wait out a kernel cache on the device; here, nothing to wait.""" + monkeypatch.setattr(battery_service, "_HOST_RETRY_S", 0) + + 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 @@ -296,11 +304,12 @@ def test_host_pack_reads_the_drivers_own_percent_and_charging_flag(tmp_path, mon asyncio.run(svc._poll()) assert svc.reading().percent == 76 and svc.reading().charging is False # Plugged in: the flag flips on the driver's word alone, with no history to trend over. - _host_supply(tmp_path, monkeypatch, capacity="22", status="Charging") + _host_supply(tmp_path, monkeypatch, capacity="77", status="Charging") asyncio.run(svc._poll()) assert svc.reading().charging is True assert not svc._history # the trend machinery never runs on this path # A topped-off pack is *not* taking charge, whatever is plugged into it. + svc = _service([]) _host_supply(tmp_path, monkeypatch, capacity="100", status="Full") asyncio.run(svc._poll()) assert svc.reading().percent == 100 and svc.reading().charging is False @@ -366,7 +375,7 @@ def _flaky_reads(monkeypatch, failures: dict[str, int]) -> None: 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.""" + """With the Cap powered, a gauge read fails often and a later 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}) @@ -375,6 +384,42 @@ def test_an_io_error_is_asked_again_not_believed(tmp_path, monkeypatch) -> None: assert svc.reading().percent == 84 and svc.reading().charging is True +def _scripted_capacity(monkeypatch, answers: list[str]) -> None: + """Make ``capacity`` answer each of ``answers`` in turn, as a garbling bus would.""" + script = iter(answers) + real = battery_service.Path.read_text + + def read_text(self, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN202 + return f"{next(script)}\n" if self.name == "capacity" else real(self, *args, **kwargs) + + monkeypatch.setattr(battery_service.Path, "read_text", read_text) + monkeypatch.setattr(battery_service, "_HOST_RETRY_S", 0) + + +def test_a_garbled_percent_is_never_shown(tmp_path, monkeypatch) -> None: + """56414 is no percent; it is asked again, after the driver's cache has let it go.""" + monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) + _host_supply(tmp_path, monkeypatch, capacity="94", status="Discharging") + _scripted_capacity(monkeypatch, ["56414", "94"]) + svc = _service([]) + asyncio.run(svc._poll()) + assert svc.reading().percent == 94 + + +def test_a_big_step_waits_for_the_next_poll(tmp_path, monkeypatch) -> None: + """A garbled read can land in 0-100; a pack can't fall 57 points between two polls.""" + monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host")) + _host_supply(tmp_path, monkeypatch, capacity="94", status="Discharging") + _scripted_capacity(monkeypatch, ["94", "37", "93", "60", "60"]) + svc = _service([]) + shown = [] + for _ in range(5): + asyncio.run(svc._poll()) + shown.append(svc.reading().percent) + # 37 is held and never confirmed; a small step is believed at once; 60 twice is real. + assert shown == [94, 94, 93, 93, 60] + + 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")) @@ -382,7 +427,7 @@ def test_a_status_that_will_not_read_keeps_the_last_verdict(tmp_path, monkeypatc svc = _service([]) asyncio.run(svc._poll()) (supply / "capacity").write_text("85\n") - _flaky_reads(monkeypatch, {"status": battery_service._HOST_READ_ATTEMPTS}) + _flaky_reads(monkeypatch, {"status": 1}) asyncio.run(svc._poll()) assert svc.reading().percent == 85 and svc.reading().charging is True