Battery: a gauge that can't animate still says it's charging
The PicoCalc reads its charging flag straight off the handheld's own BMS — the kernel's power_supply status, backed by the keyboard MCU's battery register — so the state was known all along; the header simply never drew it. Charging replaces the fill with a sweep frame, and a platform without effects holds frame 0, so a charging pack drew an *empty* cell: the gauge under-read the pack outright, exactly while it was filling. Animation is now the caller's claim rather than something inferred from a held frame. Where nothing animates the gauge draws its resting state — the true fill, no blink — and says charging with an arrow beside it instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
16532ea14b
commit
88b2d347dd
4 files changed
+116
-13
No files matched your search
@@ -7,7 +7,15 @@ 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.
|
||||
|
||||
Two device facts shape what it can report:
|
||||
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).
|
||||
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
|
||||
facts shape what it can report:
|
||||
|
||||
* Firmware exposes the pack as a **terminal voltage in millivolts**, not a percentage, so
|
||||
the reading is turned into a state-of-charge estimate against a single-cell LiPo
|
||||
|
||||
+10
-6
@@ -238,12 +238,16 @@ def _battery_segment(ctx: AppContext) -> Text:
|
||||
reading = ctx.battery.reading()
|
||||
if reading is None:
|
||||
return Text()
|
||||
# Frame 0 is the gauge's resting state: the true fill, unblinking. A platform without
|
||||
# effects holds it there, so the charging sweep and the low-battery blink never run —
|
||||
# both exist to catch the eye, and neither is worth a forced repaint (nor, on a 16-slot
|
||||
# console, a colour swap) on hardware where the cells are dear.
|
||||
frame = int(time.monotonic() / _BATTERY_ANIM_S) if get_platform().effects else 0
|
||||
return battery_cell(reading.percent, charging=reading.charging, frame=frame)
|
||||
# A platform without effects draws the gauge's resting state instead: the true fill,
|
||||
# unblinking, with charging said by a static mark rather than the sweep. The blink and
|
||||
# the sweep both exist to catch the eye, and neither is worth a forced repaint (nor, on
|
||||
# a 16-slot console, a colour swap) on hardware where the cells are dear — but charging
|
||||
# is a *fact about the pack*, not decoration, so it still has to show at rest.
|
||||
effects = get_platform().effects
|
||||
frame = int(time.monotonic() / _BATTERY_ANIM_S) if effects else 0
|
||||
return battery_cell(
|
||||
reading.percent, charging=reading.charging, frame=frame, animate=effects
|
||||
)
|
||||
|
||||
|
||||
def _header_segments(ctx: AppContext, cache: dict) -> list[Text]:
|
||||
|
||||
+29
-5
@@ -1361,6 +1361,12 @@ _BATTERY_CRITICAL = 10
|
||||
#: Frames in the charging sweep: empty → four fills → round again (bottom-to-full loop).
|
||||
_CHARGE_FRAMES = 5
|
||||
|
||||
#: The charging mark for a platform that can't animate (``Platform.effects`` off): one arrow
|
||||
#: beside the true fill, saying charge is going *in*. The sweep is the desktop's way of
|
||||
#: telling the same thing over time; where time isn't available the glyph has to say it at
|
||||
#: rest, and it must stay inside the console font's inventory (see ``ui/fontset.py``).
|
||||
_CHARGE_MARK = "↑"
|
||||
|
||||
|
||||
def _braille_fill(rows: int) -> str:
|
||||
"""A single braille cell with its bottom ``rows`` (0–4) dot rows lit."""
|
||||
@@ -1379,7 +1385,9 @@ def _battery_tier(percent: int) -> tuple[int, str]:
|
||||
return 1, "batt.low"
|
||||
|
||||
|
||||
def battery_cell(percent: int, *, charging: bool = False, frame: int = 0) -> Text:
|
||||
def battery_cell(
|
||||
percent: int, *, charging: bool = False, frame: int = 0, animate: bool = True
|
||||
) -> Text:
|
||||
"""The status-bar battery gauge: one braille cell coloured by charge, then its ``%``.
|
||||
|
||||
The braille cell fills from the bottom up in four coarse steps (see
|
||||
@@ -1393,23 +1401,39 @@ def battery_cell(percent: int, *, charging: bool = False, frame: int = 0) -> Tex
|
||||
* **Critically low** (≤ :data:`_BATTERY_CRITICAL`%, not charging) blinks the red cell to a
|
||||
dim slate on alternate frames — an unmissable pulse in the corner.
|
||||
|
||||
Both are *animations*, and a platform without effects (the PicoCalc — see
|
||||
``Platform.effects``) has no frames to spend on them, so it passes ``animate=False``.
|
||||
The blink simply doesn't run there, but charging still has to be legible at rest: the
|
||||
sweep would otherwise freeze on whichever fill its held frame happened to land on and
|
||||
lie about the charge. So the static gauge keeps the **true** fill and says charging with
|
||||
:data:`_CHARGE_MARK` beside it instead.
|
||||
|
||||
Args:
|
||||
percent: State of charge, 0–100 (clamped).
|
||||
charging: Whether the pack is taking charge (drives the fill sweep).
|
||||
charging: Whether the pack is taking charge (drives the fill sweep, or the static
|
||||
mark where nothing animates).
|
||||
frame: A monotonically advancing tick; only its phase is read, so any
|
||||
steadily-incrementing integer animates the two live states.
|
||||
animate: Whether the caller repaints often enough for animation. ``False`` draws the
|
||||
gauge's resting state — true fill, no blink — and marks charging statically.
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Text`: the coloured glyph, a space, and ``NN%`` in muted text.
|
||||
A Rich :class:`Text`: the coloured glyph (plus the charge mark, when charging with
|
||||
no animation), a space, and ``NN%`` in muted text.
|
||||
"""
|
||||
pct = max(0, min(100, int(percent)))
|
||||
rows, color = _battery_tier(pct)
|
||||
if charging:
|
||||
mark = ""
|
||||
if charging and animate:
|
||||
# The charge colour is held; only the fill sweeps, so it reads as "filling", not
|
||||
# as the charge itself jumping around.
|
||||
rows = frame % _CHARGE_FRAMES
|
||||
elif pct <= _BATTERY_CRITICAL and frame % 2:
|
||||
elif charging:
|
||||
mark = _CHARGE_MARK
|
||||
elif animate and pct <= _BATTERY_CRITICAL and frame % 2:
|
||||
color = "batt.dim"
|
||||
out = Text(_braille_fill(rows), style=color)
|
||||
if mark:
|
||||
out.append(mark, style=color)
|
||||
out.append(f" {pct}%", style="muted")
|
||||
return out
|
||||
+68
-1
@@ -12,13 +12,15 @@ import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
from meshterm.core.connection import charging_from_battery_level_status
|
||||
from meshterm.services import battery_service
|
||||
from meshterm.services.battery_service import (
|
||||
_BATTERY_PRESENT_FLOOR_MV,
|
||||
POLL_S,
|
||||
BatteryService,
|
||||
battery_percent,
|
||||
)
|
||||
from meshterm.ui.widgets import _BATTERY_CRITICAL, battery_cell
|
||||
from meshterm.ui.fontset import in_font
|
||||
from meshterm.ui.widgets import _BATTERY_CRITICAL, _CHARGE_MARK, battery_cell
|
||||
|
||||
# --- the LiPo state-of-charge curve -------------------------------------------------------
|
||||
|
||||
@@ -84,6 +86,26 @@ def test_battery_cell_charging_sweeps_bottom_to_full_holding_the_percent() -> No
|
||||
assert {str(battery_cell(20, charging=True, frame=f).style) for f in range(6)} == {"batt.low"}
|
||||
|
||||
|
||||
def test_battery_cell_marks_charging_statically_when_nothing_animates() -> None:
|
||||
"""With animation off the fill stays true and a mark — not the sweep — says charging."""
|
||||
still = battery_cell(20, charging=True, frame=0, animate=False)
|
||||
# The frozen sweep used to draw an *empty* cell here, under-reading the pack outright.
|
||||
assert still.plain == chr(0x2800 | 0xC0) + _CHARGE_MARK + " 20%"
|
||||
assert still.plain[:1] == battery_cell(20).plain[:1] # the same fill as at rest
|
||||
# It says the same thing whatever the frame — there are no frames to read.
|
||||
assert {battery_cell(20, charging=True, frame=f, animate=False).plain for f in range(6)} == {
|
||||
still.plain
|
||||
}
|
||||
# Not charging draws no mark, and the low-battery blink stays still too.
|
||||
assert battery_cell(20, animate=False).plain == chr(0x2800 | 0xC0) + " 20%"
|
||||
assert {str(battery_cell(5, frame=f, animate=False).style) for f in range(4)} == {"batt.low"}
|
||||
|
||||
|
||||
def test_charge_mark_is_drawable_on_the_console_font() -> None:
|
||||
"""The static mark is only useful on the platform whose font has to have it."""
|
||||
assert in_font(_CHARGE_MARK)
|
||||
|
||||
|
||||
# --- the poller ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -186,6 +208,51 @@ def test_battery_poller_charging_ignores_load_sag_and_flat_or_falling_packs() ->
|
||||
assert svc._charging(now) is False
|
||||
|
||||
|
||||
# --- 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"
|
||||
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)
|
||||
return supply
|
||||
|
||||
|
||||
def test_host_pack_reads_the_drivers_own_percent_and_charging_flag(tmp_path, monkeypatch) -> None:
|
||||
"""On the handheld both numbers are the device's: no LiPo curve, no voltage trend."""
|
||||
monkeypatch.setattr(battery_service, "get_platform", lambda: SimpleNamespace(battery="host"))
|
||||
svc = _service([])
|
||||
# A discharging pack, as the driver reports it (no voltage_now on this one — it has none).
|
||||
_host_supply(tmp_path, monkeypatch, capacity="76", status="Discharging")
|
||||
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")
|
||||
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.
|
||||
_host_supply(tmp_path, monkeypatch, capacity="100", status="Full")
|
||||
asyncio.run(svc._poll())
|
||||
assert svc.reading().percent == 100 and svc.reading().charging is False
|
||||
|
||||
|
||||
def test_host_pack_absent_when_the_supply_cant_be_read(tmp_path, monkeypatch) -> None:
|
||||
"""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")
|
||||
asyncio.run(svc._poll())
|
||||
assert svc.reading() is None
|
||||
# A supply that answers with junk is just as absent — never a bogus gauge.
|
||||
_host_supply(tmp_path, monkeypatch, capacity="", status="Charging")
|
||||
asyncio.run(svc._poll())
|
||||
assert svc.reading() is None
|
||||
|
||||
|
||||
# --- the standard BLE charging flag (GATT Battery Level Status, 0x2BED) --------------------
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user