Battery gauge: a braille fuel gauge pinned to the header's right edge

Add a one-cell braille battery indicator to the status bar, shown only when
the companion reports a pack. The cell fills bottom-to-top in four tiers —
green healthy, orange at a quarter, red near empty — with the true percent
beside it; it blinks red↔dim when critically low and sweeps a filling
animation while charging. A session-long BatteryService polls the pack,
maps millivolts to a state-of-charge estimate off a single-cell LiPo curve,
and infers charging from a rising terminal voltage (firmware exposes no
charging flag). The header pins the gauge flush right and the activity
pulse cedes exactly the cells it needs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-13 18:12:43 -04:00
1 parent cba3be3f69
commit dfd7d2332d
7 files changed
+553 -11

No files matched your search

+59 -8
View File
@@ -29,6 +29,7 @@ from ..tools import all_tools
from .surface import TuiUi
from .braillechart import activity_sparkline
from .theme import make_console
from .widgets import battery_cell
from .tui import (
CANCEL,
Choice,
@@ -133,9 +134,11 @@ def _header(ctx: AppContext, cache: dict, width: int) -> Text:
(``(COM5)`` / ``(BLE)``), unread-message and Watchtower badges (shown only when
something is waiting), and the braille activity pulse counting every packet the hub
hears at one minute per dot column — newest at the right edge, like every MeshTerm
timeline — stretched to fill every remaining cell of the row, so a wider terminal
simply shows deeper history. Separators are roomy by default and drop to a compact
``·`` when that would squeeze the pulse below :data:`_SPARK_MIN_CELLS`.
timeline. The pulse fills the middle of the row; a battery gauge (only when the
companion reports a pack) is pinned to the right edge and the pulse cedes exactly the
cells it needs, so a wider terminal simply shows deeper history. Separators are roomy
by default and drop to a compact ``·`` when that would squeeze the pulse below
:data:`_SPARK_MIN_CELLS`.
Args:
ctx: The shared application context, read live on every repaint.
@@ -149,11 +152,19 @@ def _header(ctx: AppContext, cache: dict, width: int) -> Text:
single line (see ``frame.compose_base``), so a too-narrow terminal chops the
tail rather than wrapping.
"""
header = _header_segments(ctx, cache, " · ")
if width - header.cell_len < _SPARK_MIN_CELLS:
header = _header_segments(ctx, cache, " · ")
# Two dot columns per cell: every cell left of the row's edge shows two minutes.
room = width - header.cell_len
# The battery gauge is pinned to the row's right edge, so reserve its width (plus a
# leading separator) before the pulse claims the rest; a wider separator estimate for
# the fit decision is harmless slack.
battery = _battery_segment(ctx)
reserve = (cell_len(" · ") + battery.cell_len) if battery.cell_len else 0
sep = " · "
header = _header_segments(ctx, cache, sep)
if width - header.cell_len - reserve < _SPARK_MIN_CELLS:
sep = " · "
header = _header_segments(ctx, cache, sep)
reserve = (cell_len(sep) + battery.cell_len) if battery.cell_len else 0
# Two dot columns per cell: every cell left of the reserved tail shows two minutes.
room = width - header.cell_len - reserve
if room > 0:
# Buckets seeded from a previous session's stored history draw grey; only
# traffic this session actually heard pulses green.
@@ -168,9 +179,46 @@ def _header(ctx: AppContext, cache: dict, width: int) -> Text:
column_styles=styles,
)
)
if battery.cell_len:
# Pin the gauge flush right: once the pulse has filled `room`, the separator and
# gauge land against the edge. With no room for a pulse (a very narrow terminal),
# pad instead so the gauge still sits in the corner rather than trailing the text.
if room <= 0:
header.append(" " * max(0, width - header.cell_len - reserve))
header.append(sep)
header.append_text(battery)
return header
#: Seconds per animation step of the header battery gauge (the charging sweep and the
#: low-battery blink). Matched to the session's ~1 Hz idle repaint (see the app's
#: ``refresh_interval``) so each repaint advances the animation by one clean step rather
#: than aliasing across skipped frames.
_BATTERY_ANIM_S = 1.0
def _battery_segment(ctx: AppContext) -> Text:
"""The header's right-anchored battery gauge, or an empty Text when there is no pack.
Reads the poller's cached snapshot (:meth:`~meshterm.services.battery_service.
BatteryService.reading`) — never the radio — so it is safe on the render path. The
animation frame is derived from the wall clock, so the charging sweep and low-battery
blink advance on their own without the header threading a counter through.
Args:
ctx: The shared application context, read for the latest battery snapshot.
Returns:
The gauge as a Rich :class:`Text` (glyph + ``%``), or an empty one when the
companion reports no battery.
"""
reading = ctx.battery.reading()
if reading is None:
return Text()
frame = int(time.monotonic() / _BATTERY_ANIM_S)
return battery_cell(reading.percent, charging=reading.charging, frame=frame)
def _header_segments(ctx: AppContext, cache: dict, sep: str) -> Text:
"""The header's fixed segments — everything left of the pulse — at one separator width.
@@ -548,6 +596,9 @@ async def _resume_monitor(ctx: AppContext) -> None:
# The courier drains the outbox on its own paced schedule; each pass checks for a
# connected device and skips quietly without one, exactly like the advert scheduler.
await ctx.courier.start()
# The battery poller reads the pack for the header's fuel gauge; it only ever reads,
# and skips quietly without a device, so it too is safe to run from launch.
await ctx.battery.start()
if not ctx.settings.connect_on_start:
return
try:
+7
View File
@@ -61,6 +61,13 @@ MESH_THEME = Theme(
"snr.good": "bold #4ade80",
"snr.ok": "bold #fbbf24",
"snr.bad": "bold #f87171",
# The status-bar battery gauge, as a fuel-gauge palette: green healthy, orange at
# a quarter, red near empty. ``batt.dim`` is the off-beat of the critically-low
# blink — a dark slate the red glyph flickers to, so it pulses without vanishing.
"batt.high": "bold #4ade80",
"batt.mid": "bold #fb923c",
"batt.low": "bold #f87171",
"batt.dim": "#475569",
}
)
+82
View File
@@ -844,3 +844,85 @@ def tx_opt_summary(result: TxOptResult) -> Panel:
("status ", "muted"), Text.from_markup(applied),
)
return Panel(body, title="[accent]TX optimization[/accent]", border_style="accent", expand=False)
# -- battery gauge --------------------------------------------------------------------------
#: Unicode braille pattern base; add an 8-bit dot mask (a 2×4 cell) to get the glyph.
_BRAILLE_BASE = 0x2800
#: Dot bit per (column, row) within a braille cell — the Unicode standard layout, the same
#: mapping the map canvas rasters with. Kept here so the one-cell battery glyph needn't reach
#: into the canvas module for two constants.
_BRAILLE_DOTS = ((0x01, 0x02, 0x04, 0x40), (0x08, 0x10, 0x20, 0x80))
#: Battery charge tiers: ``(percent floor, braille rows lit from the bottom, colour)``,
#: highest first. The glyph is one braille cell (2×4 dots) filled from its bottom row up, so
#: four coarse levels read as a shrinking fuel gauge: the whole cell above three-quarters,
#: six dots above half, four above a quarter, two below it — green while healthy, orange at a
#: quarter, red near empty (the app's ok/warn/err semantics as a gauge).
_BATTERY_TIERS: tuple[tuple[int, int, str], ...] = (
(75, 4, "batt.high"),
(50, 3, "batt.high"),
(25, 2, "batt.mid"),
(0, 1, "batt.low"),
)
#: At or below this charge the red glyph blinks with a dim frame — a can't-miss low warning.
_BATTERY_CRITICAL = 10
#: Frames in the charging sweep: empty → four fills → round again (bottom-to-full loop).
_CHARGE_FRAMES = 5
def _braille_fill(rows: int) -> str:
"""A single braille cell with its bottom ``rows`` (0–4) dot rows lit."""
rows = max(0, min(4, rows))
bits = 0
for row in range(4 - rows, 4):
bits |= _BRAILLE_DOTS[0][row] | _BRAILLE_DOTS[1][row]
return chr(_BRAILLE_BASE + bits)
def _battery_tier(percent: int) -> tuple[int, str]:
"""The ``(rows lit, colour)`` a charge level draws at (see :data:`_BATTERY_TIERS`)."""
for floor, rows, color in _BATTERY_TIERS:
if percent >= floor:
return rows, color
return 1, "batt.low"
def battery_cell(percent: int, *, charging: bool = False, frame: int = 0) -> 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
:data:`_BATTERY_TIERS`), coloured green while healthy, orange at a quarter, red near
empty. Two live states animate off the caller's ``frame`` counter (advanced one step per
repaint tick), so the gauge moves without any per-frame plumbing:
* **Charging** overrides the fill: the cell sweeps empty-to-full on a loop, the charge
colour held, so a plugged-in pack visibly climbs — while the number beside it stays the
*true* charge, never the animation's.
* **Critically low** (≤ :data:`_BATTERY_CRITICAL`%, not charging) blinks the red cell to a
dim slate on alternate frames — an unmissable pulse in the corner.
Args:
percent: State of charge, 0–100 (clamped).
charging: Whether the pack is taking charge (drives the fill sweep).
frame: A monotonically advancing tick; only its phase is read, so any
steadily-incrementing integer animates the two live states.
Returns:
A Rich :class:`Text`: the coloured glyph, a space, and ``NN%`` in muted text.
"""
pct = max(0, min(100, int(percent)))
rows, color = _battery_tier(pct)
if charging:
# 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:
color = "batt.dim"
out = Text(_braille_fill(rows), style=color)
out.append(f" {pct}%", style="muted")
return out