TX optimize rebuilt on the trace screen's armed-idle pattern
The old flow asked for a hand-typed comma-separated path, logged in before showing anything, and started transmitting the moment the screen opened, on parameters you couldn't touch. It now walks like the trace feature: two pickers choose the link — the node to tune (credentialed repeaters lead, wearing the key glyph), then the target whose reception is optimized — and the screen opens armed but idle. An action list drives it: Route opens the trace path composer pinned at the tuned node (suggestions from observed links; direct by default), Range/Step/Samples float small dialogs, and the Sweep row always quotes the worst-case transmission count, so the cost of a commit is on screen before anything goes on the air (coarse_levels goes public to price it). Sweep logs in first — the password prompt floats only when nothing is remembered — then runs coarse → refine → verify under the trace tool's in-flight dialog with Abort, levels landing in the bar chart behind it, best starred. Completion parks the cursor on a new Apply-winner action row (the after-sweep dialog's second chance), and a finished sweep leaves the screen armed: adjust and sweep again, the chart clearing as a new measurement starts. The scripted CLI keeps its one-shot flag set, table, and HTML chart. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
85fc82a606
commit
5046a86980
4 files changed
+880
-229
No files matched your search
@@ -202,7 +202,7 @@ async def optimize_tx_power(
|
||||
traces_by_tx: dict[int, list[TraceResult]] = {}
|
||||
levels: dict[int, TxLevelResult] = {}
|
||||
|
||||
coarse = _coarse_levels(tx_min, tx_max, coarse_step)
|
||||
coarse = coarse_levels(tx_min, tx_max, coarse_step)
|
||||
total_estimate = len(coarse) + (2 * coarse_step if refine else 0) + (1 if verify else 0)
|
||||
completed = 0
|
||||
|
||||
@@ -308,9 +308,12 @@ def _round_trip_path(outbound: list[str]) -> str:
|
||||
return ",".join(outbound + outbound[-2::-1])
|
||||
|
||||
|
||||
def _coarse_levels(tx_min: int, tx_max: int, step: int) -> list[int]:
|
||||
def coarse_levels(tx_min: int, tx_max: int, step: int) -> list[int]:
|
||||
"""Build the coarse sweep grid, always including both endpoints.
|
||||
|
||||
Public so the live sweep screen can quote the worst-case transmission count
|
||||
of a commit before anything goes on the air.
|
||||
|
||||
Args:
|
||||
tx_min: Lowest TX power.
|
||||
tx_max: Highest TX power.
|
||||
|
||||
+159
-51
@@ -5,11 +5,14 @@ measured. The node one hop *before* the target — one you hold admin rights on
|
||||
node whose transmit power gets swept and tuned. Admin passwords are remembered between
|
||||
runs.
|
||||
|
||||
In the interactive menu one prompt picks the path and the live sweep screen
|
||||
(:mod:`meshterm.ui.tx_screen`) takes it from there: levels land in a bar chart as they
|
||||
are measured, and the apply decision is made *after* the sweep, over the evidence. On the
|
||||
CLI it stays a scriptable one-shot with the full flag set (range, step, samples,
|
||||
``--apply``, the HTML chart), and progress streams like a trace.
|
||||
In the interactive menu two pickers choose the link — the node to tune (repeaters
|
||||
you hold credentials for lead the list), then the target whose reception is optimized —
|
||||
and the live sweep screen (:mod:`meshterm.ui.tx_screen`) takes it from there, armed but
|
||||
idle: route, range, step, and samples are adjusted in place, nothing transmits until
|
||||
Sweep is committed, levels land in a bar chart as they are measured, and the apply
|
||||
decision is made *after* the sweep, over the evidence. On the CLI it stays a scriptable
|
||||
one-shot with the full flag set (``--path``, range, step, samples, ``--apply``, the HTML
|
||||
chart), and progress streams like a trace.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +23,7 @@ import typer
|
||||
|
||||
from ..context import AppContext
|
||||
from ..core.connection import DeviceCommandError
|
||||
from ..core.models import Contact
|
||||
from ..core.models import NODE_TYPE_REPEATER, NODE_TYPE_ROOM, Contact
|
||||
from ..services import trace_runner, tx_optimizer
|
||||
from ..ui.widgets import tx_opt_summary, tx_opt_table
|
||||
from ..viz.tx_plot import render_tx_optimization
|
||||
@@ -43,34 +46,26 @@ class TxOptimizeTool(Tool):
|
||||
order = 15 # right after Trace, its measurement sibling
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
|
||||
"""Pick the path for the live sweep (everything else defaults, tuned in-screen).
|
||||
"""Pick the tuned link for the live sweep: the admin node, then the target.
|
||||
|
||||
Everything else — route, range, step, samples — is adjusted on the armed-idle
|
||||
sweep screen itself, so the entry flow is two quick pickers, not a typed path.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
``{"live": True, "path": spec}``, or ``None`` if the user cancelled.
|
||||
``{"live": True, "admin": name, "target": name}``, or ``None`` on cancel.
|
||||
"""
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
choices = [c.name for c in contacts]
|
||||
|
||||
prompt = (
|
||||
"Comma-separated contacts/hex, ending at the target — "
|
||||
"the node just before it is tuned"
|
||||
)
|
||||
validate_path = lambda v: _validate_link_path(v, contacts) # noqa: E731
|
||||
if choices:
|
||||
path_spec = await ctx.ui.autocomplete(
|
||||
"Path to the target", choices, prompt=prompt, validate=validate_path
|
||||
)
|
||||
else:
|
||||
path_spec = await ctx.ui.text(
|
||||
"Path to the target", prompt=prompt, validate=validate_path
|
||||
)
|
||||
if not path_spec:
|
||||
admin = await _pick_admin(ctx, contacts)
|
||||
if admin is None:
|
||||
return None
|
||||
return {"live": True, "path": path_spec.strip()}
|
||||
target = await _pick_target(ctx, contacts, admin)
|
||||
if target is None:
|
||||
return None
|
||||
return {"live": True, "admin": admin.name, "target": target}
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run — without the outer run row on the live path.
|
||||
@@ -95,39 +90,56 @@ class TxOptimizeTool(Tool):
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``live`` + ``path`` from the menu prompt; or ``path``, ``samples``,
|
||||
``tx_min``, ``tx_max``, ``step``, ``apply``, optional ``password``/
|
||||
``viz``, and the injected ``_run_id`` from the CLI.
|
||||
params: ``live`` + ``admin``/``target`` from the menu pickers; or ``path``,
|
||||
``samples``, ``tx_min``, ``tx_max``, ``step``, ``apply``, optional
|
||||
``password``/``viz``, and the injected ``_run_id`` from the CLI.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the optimum and any chart path.
|
||||
"""
|
||||
if params.get("live"):
|
||||
return await self._run_live(ctx, str(params["path"]))
|
||||
return await self._run_live(ctx, params)
|
||||
return await self._run_cli(ctx, params)
|
||||
|
||||
# -- interactive (menu) ---------------------------------------------------------
|
||||
|
||||
async def _run_live(self, ctx: AppContext, path_spec: str) -> ToolResult:
|
||||
"""Resolve the link, log in, and hand off to the live sweep screen.
|
||||
async def _run_live(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Resolve the picked link and hand off to the armed-idle sweep screen.
|
||||
|
||||
No login here: the screen logs in inside the first Sweep commit, so backing
|
||||
out of an idle screen never touched the radio beyond the contact reads.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
path_spec: The user's comma-separated path entry (names and/or hex).
|
||||
params: ``admin`` and ``target`` — the picker's contact names (the target
|
||||
may also be a typed hex prefix).
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` echoing the sweep's recorded summary.
|
||||
A :class:`ToolResult` echoing the last sweep's recorded summary.
|
||||
"""
|
||||
from ..ui.tx_screen import open_tx_optimize
|
||||
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
path = trace_runner.parse_trace_path(path_spec, contacts)
|
||||
admin_node, target_label = _resolve_link(path, contacts)
|
||||
await self._login(ctx, admin_node, {})
|
||||
admin_node = next(
|
||||
(c for c in contacts if c.name == str(params["admin"])), None
|
||||
)
|
||||
if admin_node is None:
|
||||
raise DeviceCommandError(f"unknown contact: {params['admin']!r}")
|
||||
target = str(params["target"])
|
||||
target_contact = next((c for c in contacts if c.name == target), None)
|
||||
if target_contact is not None:
|
||||
target_label = target_contact.name
|
||||
target_hash = target_contact.public_key or target_contact.key_prefix
|
||||
else:
|
||||
target_label = target
|
||||
target_hash = target # a typed hex prefix stands for itself
|
||||
|
||||
summary = await open_tx_optimize(
|
||||
ctx, admin_node=admin_node, target_label=target_label, path=path
|
||||
ctx,
|
||||
admin_node=admin_node,
|
||||
target_label=target_label,
|
||||
target_hash=target_hash,
|
||||
)
|
||||
return ToolResult(summary=summary)
|
||||
|
||||
@@ -383,25 +395,121 @@ def _contact_for_hash(hash_hex: str, contacts: list[Contact]) -> Optional[Contac
|
||||
return None
|
||||
|
||||
|
||||
def _validate_link_path(value: str, contacts: list[Contact]) -> bool | str:
|
||||
"""Validate the interactive path entry: parseable and at least two hops.
|
||||
async def _pick_admin(ctx: AppContext, contacts: list[Contact]) -> Optional[Contact]:
|
||||
"""Pick the node to tune: credentialed repeaters lead, the rest follow by recency.
|
||||
|
||||
Repeaters (and room servers) with a remembered admin password sit in their own
|
||||
section wearing a key glyph — those are the nodes previously tuned or administered,
|
||||
the likeliest picks. Any contact with a public key can be chosen, since holding a
|
||||
password is a fact about the *user*, not the node.
|
||||
|
||||
Args:
|
||||
value: The raw comma-separated path entry.
|
||||
contacts: Known contacts used to resolve names.
|
||||
ctx: Shared application context (for the UI surface and the admin store).
|
||||
contacts: The device's known contacts.
|
||||
|
||||
Returns:
|
||||
``True`` if valid, otherwise an error message string.
|
||||
The chosen contact, or ``None`` if cancelled (or there is nothing to pick).
|
||||
"""
|
||||
if not value.strip():
|
||||
return "Enter a path ending at the target node."
|
||||
try:
|
||||
path = trace_runner.parse_trace_path(value, contacts)
|
||||
except ValueError as exc:
|
||||
return str(exc)
|
||||
if len([h for h in path.split(",") if h]) < 2:
|
||||
return "Need at least two hops: the node to tune, then the target."
|
||||
return True
|
||||
from ..ui.tui import Choice, Separator
|
||||
from ..ui.widgets import _DEFAULT_GLYPH, _NODE_GLYPHS
|
||||
|
||||
candidates = [c for c in contacts if (c.public_key or c.key_prefix).strip()]
|
||||
if not candidates:
|
||||
ctx.ui.note("[err]no contacts with a key — receive an advert first[/err]")
|
||||
await ctx.ui.present(title="TX optimize")
|
||||
return None
|
||||
|
||||
def row(contact: Contact) -> Any:
|
||||
glyph, style = _NODE_GLYPHS.get(contact.node_type, _DEFAULT_GLYPH)
|
||||
from rich.text import Text
|
||||
|
||||
label = Text(glyph, style=style)
|
||||
label.append(f" {contact.name}")
|
||||
return Choice(title=label, value=contact.name)
|
||||
|
||||
def recency(contact: Contact) -> float:
|
||||
return -(contact.last_seen.timestamp() if contact.last_seen else 0.0)
|
||||
|
||||
remembered = [c for c in candidates if ctx.admin_store.get(c) is not None]
|
||||
infrastructure = [
|
||||
c for c in candidates
|
||||
if c not in remembered and c.node_type in (NODE_TYPE_REPEATER, NODE_TYPE_ROOM)
|
||||
]
|
||||
others = [c for c in candidates if c not in remembered and c not in infrastructure]
|
||||
|
||||
items: list = []
|
||||
if remembered:
|
||||
items.append(Separator("── 🔑 Remembered admins ──", style="accent"))
|
||||
items.extend(row(c) for c in sorted(remembered, key=recency))
|
||||
if infrastructure:
|
||||
items.append(Separator("── Repeaters & rooms ──", style="accent"))
|
||||
items.extend(row(c) for c in sorted(infrastructure, key=recency))
|
||||
if others:
|
||||
items.append(Separator("── Other contacts ──", style="accent"))
|
||||
items.extend(row(c) for c in sorted(others, key=recency))
|
||||
items.append(Separator(" "))
|
||||
items.append(Choice(title="Back", value=None))
|
||||
|
||||
choice = await ctx.ui.select(
|
||||
"TX optimize — node to tune",
|
||||
items,
|
||||
prompt="Whose transmit power gets tuned (you need its admin password):",
|
||||
wrap=False,
|
||||
)
|
||||
if choice is None:
|
||||
return None
|
||||
return next((c for c in candidates if c.name == choice), None)
|
||||
|
||||
|
||||
async def _pick_target(
|
||||
ctx: AppContext, contacts: list[Contact], admin: Contact
|
||||
) -> Optional[str]:
|
||||
"""Pick the target the tuned node's signal is measured at, by recency heard.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context (for the UI surface).
|
||||
contacts: The device's known contacts.
|
||||
admin: The already-picked tuned node (excluded — it can't measure itself).
|
||||
|
||||
Returns:
|
||||
The chosen contact name, or ``None`` if cancelled. With no other contacts,
|
||||
falls back to a free-text prompt so a hex key prefix can be typed.
|
||||
"""
|
||||
from ..ui.tui import Choice, Separator
|
||||
from ..ui.widgets import _DEFAULT_GLYPH, _NODE_GLYPHS
|
||||
|
||||
candidates = [c for c in contacts if c.name != admin.name]
|
||||
if not candidates:
|
||||
entered = await ctx.ui.text(
|
||||
"Target node",
|
||||
prompt=f"Name or hex key prefix of the node that hears {admin.name}:",
|
||||
)
|
||||
return entered.strip() if entered else None
|
||||
|
||||
from rich.text import Text
|
||||
|
||||
def row(contact: Contact) -> Any:
|
||||
glyph, style = _NODE_GLYPHS.get(contact.node_type, _DEFAULT_GLYPH)
|
||||
label = Text(glyph, style=style)
|
||||
label.append(f" {contact.name}")
|
||||
return Choice(title=label, value=contact.name)
|
||||
|
||||
items: list = [
|
||||
row(c)
|
||||
for c in sorted(
|
||||
candidates,
|
||||
key=lambda c: -(c.last_seen.timestamp() if c.last_seen else 0.0),
|
||||
)
|
||||
]
|
||||
items.append(Separator(" "))
|
||||
items.append(Choice(title="Back", value=None))
|
||||
choice = await ctx.ui.select(
|
||||
"TX optimize — measure at",
|
||||
items,
|
||||
prompt=f"The node whose reception of {admin.name} gets optimized:",
|
||||
wrap=False,
|
||||
)
|
||||
return str(choice) if choice is not None else None
|
||||
|
||||
|
||||
def _fmt_snr(snr: Optional[float]) -> str:
|
||||
|
||||
+641
-154
File diff suppressed because it is too large.
Load diff
+75
-22
@@ -679,18 +679,21 @@ def _level(tx: int, snr: float | None, successes: int = 2, samples: int = 2) ->
|
||||
)
|
||||
|
||||
|
||||
def _sweep_screen(offer_apply=None) -> tuple[TxSweepScreen, _FakeSession]:
|
||||
def _sweep_screen(apply_winner=None, run_sweep=None) -> tuple[TxSweepScreen, _FakeSession]:
|
||||
session = _FakeSession()
|
||||
screen = TxSweepScreen(
|
||||
admin_label="Repeater",
|
||||
target_label="Alice",
|
||||
path="a1b2,d4e5",
|
||||
device_label="us",
|
||||
device_hash="00" * 32,
|
||||
resolve=lambda h: h,
|
||||
session=session,
|
||||
tx_min=12,
|
||||
tx_max=28,
|
||||
step=3,
|
||||
samples=3,
|
||||
session=session,
|
||||
offer_apply=offer_apply or (lambda: None),
|
||||
run_sweep=run_sweep or (lambda: None),
|
||||
apply_winner=apply_winner or (lambda: None),
|
||||
)
|
||||
return screen, session
|
||||
|
||||
@@ -709,15 +712,37 @@ def _result(best_tx: int = 19, best_snr: float | None = 8.8) -> TxOptResult:
|
||||
)
|
||||
|
||||
|
||||
def test_sweep_screen_opens_armed_and_idle_on_sweep() -> None:
|
||||
"""The screen opens with the cursor on Sweep and nothing transmitted."""
|
||||
ran: list[bool] = []
|
||||
screen, _ = _sweep_screen(run_sweep=lambda: ran.append(True))
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "Sweep — up to" in body and "Route — direct to Repeater" in body
|
||||
assert not screen.running and ran == []
|
||||
screen.handle("enter") # the cursor opens on Sweep
|
||||
assert ran == [True]
|
||||
|
||||
|
||||
def test_sweep_screen_quotes_the_transmission_budget() -> None:
|
||||
"""The Sweep row's worst case tracks the window, step, and samples."""
|
||||
screen, _ = _sweep_screen()
|
||||
# 12–28 step 3 → 7 coarse levels (28 appended); refine ≤ 4; verify 1 → 12 × 3.
|
||||
assert screen.estimated_traces() == 36
|
||||
screen.samples = 1
|
||||
screen.step = 1
|
||||
# Every level measured up front (17), no refine grid, one verify batch.
|
||||
assert screen.estimated_traces() == 18
|
||||
assert "up to 18 paced transmissions" in _plain(screen.render_body(100))
|
||||
|
||||
|
||||
def test_sweep_screen_stars_the_running_best() -> None:
|
||||
"""Each landed level renders ascending by TX with the current best starred."""
|
||||
screen, _ = _sweep_screen()
|
||||
screen.on_phase("coarse")
|
||||
screen.on_level(1, 7, _level(12, -2.0))
|
||||
screen.on_level(2, 7, _level(18, 7.5))
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "coarse sweep" in body and "level 2/7" in body
|
||||
starred = next(line for line in body.splitlines() if "★" in line)
|
||||
assert screen.phase_label() == "coarse sweep · level 2/7"
|
||||
starred = next(line for line in _plain(screen.render_body(100)).splitlines() if "★" in line)
|
||||
assert "18" in starred
|
||||
|
||||
|
||||
@@ -729,38 +754,38 @@ def test_sweep_screen_shows_failed_levels_distinctly() -> None:
|
||||
|
||||
|
||||
def test_sweep_screen_completion_offers_the_winner() -> None:
|
||||
"""After completion the outcome shows and `a` re-offers the apply dialog."""
|
||||
"""Completion lands the cursor on the new Apply row; Enter re-offers the dialog."""
|
||||
offered: list[bool] = []
|
||||
screen, _ = _sweep_screen(offer_apply=lambda: offered.append(True))
|
||||
screen.handle("text", "a") # mid-sweep: nothing to offer yet
|
||||
assert offered == []
|
||||
screen, _ = _sweep_screen(apply_winner=lambda: offered.append(True))
|
||||
assert "apply" not in screen._actions # nothing to apply while measuring
|
||||
screen.complete(_result())
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "sweep complete" in body and "TX 19" in body and "press a to apply" in body
|
||||
assert "a apply winner" in screen.footer_hint
|
||||
screen.handle("text", "a")
|
||||
assert "best" in body and "TX 19" in body
|
||||
assert "Apply winner — set TX 19 on Repeater" in body
|
||||
screen.handle("enter") # the cursor parked itself on Apply
|
||||
assert offered == [True]
|
||||
|
||||
|
||||
def test_sweep_screen_apply_updates_status_and_retires_the_key() -> None:
|
||||
"""Marking the winner applied flips the status line and stops offering `a`."""
|
||||
def test_sweep_screen_apply_updates_status_and_retires_the_row() -> None:
|
||||
"""Marking the winner applied flips the status line and removes the Apply row."""
|
||||
offered: list[bool] = []
|
||||
screen, _ = _sweep_screen(offer_apply=lambda: offered.append(True))
|
||||
screen, _ = _sweep_screen(apply_winner=lambda: offered.append(True))
|
||||
screen.complete(_result())
|
||||
screen.mark_applied()
|
||||
assert "✓ TX 19 set on Repeater" in _plain(screen.render_body(100))
|
||||
assert "a apply winner" not in screen.footer_hint
|
||||
screen.handle("text", "a")
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "✓ TX 19 set on Repeater" in body
|
||||
assert "Apply winner" not in body
|
||||
screen.handle("enter")
|
||||
assert offered == []
|
||||
|
||||
|
||||
def test_sweep_screen_no_result_never_offers_apply() -> None:
|
||||
"""A sweep where nothing got through warns and keeps the apply key retired."""
|
||||
"""A sweep where nothing got through warns and never grows an Apply row."""
|
||||
screen, _ = _sweep_screen()
|
||||
screen.complete(_result(best_snr=None))
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "no traces reached" in body
|
||||
assert "a apply winner" not in screen.footer_hint
|
||||
assert "Apply winner" not in body
|
||||
|
||||
|
||||
def test_sweep_screen_failure_keeps_measured_levels_on_screen() -> None:
|
||||
@@ -773,6 +798,23 @@ def test_sweep_screen_failure_keeps_measured_levels_on_screen() -> None:
|
||||
assert "-2.0" in body
|
||||
|
||||
|
||||
def test_sweep_screen_new_sweep_clears_the_old_evidence() -> None:
|
||||
"""Starting another sweep is a new measurement: chart and outcome reset."""
|
||||
screen, _ = _sweep_screen()
|
||||
screen.on_level(1, 7, _level(12, -2.0))
|
||||
screen.complete(_result())
|
||||
|
||||
async def go() -> None:
|
||||
task = asyncio.ensure_future(asyncio.sleep(0))
|
||||
screen.sweep_started(task)
|
||||
assert screen.running
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "TX 19" not in body and "-2.0" not in body
|
||||
await task
|
||||
|
||||
asyncio.get_event_loop_policy().new_event_loop().run_until_complete(go())
|
||||
|
||||
|
||||
def test_sweep_screen_escape_resolves() -> None:
|
||||
"""Esc resolves the screen (the controller then cancels and restores)."""
|
||||
screen, _ = _sweep_screen()
|
||||
@@ -792,3 +834,14 @@ def test_sweep_screen_escape_resolves() -> None:
|
||||
screen.future = _Fut()
|
||||
screen.handle("escape")
|
||||
assert screen.future.done()
|
||||
|
||||
|
||||
def test_parse_tx_range_clamps_and_rejects() -> None:
|
||||
"""The typed window accepts two ordered numbers and clamps to the remote range."""
|
||||
from meshterm.ui.tx_screen import parse_tx_range
|
||||
|
||||
assert parse_tx_range("14-24") == (14, 24)
|
||||
assert parse_tx_range("14 24") == (14, 24)
|
||||
assert parse_tx_range("2-99") == (12, 28) # clamped to the firmware window
|
||||
assert parse_tx_range("24-14") is None
|
||||
assert parse_tx_range("banana") is None
|
||||
Reference in new issue
Block a user