Fix auto-path traces, harden contacts retrieval, add device config tooling
Trace: - Auto-path now ends every route at the target's own hash (verified on hardware: a trace only replies when its destination is the final hop), so direct neighbors and learned multi-hop routes both resolve correctly. - Retry the transient "no event received during contacts retrieval" blip and surface a clean DeviceCommandError instead of a raw traceback. - Route summary annotates each node with its hash at the command's path-hash width, wrapping after an arrow when the line is too long. - Default trace count changed from 5 to 3. Also includes the in-progress device-config feature (config_io, device_config, config tool, config editor UI, tests) and related supporting edits. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
43353f83a9
commit
421781f13d
19 files changed
+3081
-108
No files matched your search
@@ -105,15 +105,18 @@ class Tool(ABC):
|
||||
Raises:
|
||||
Exception: Re-raises any error from :meth:`run` after recording it.
|
||||
"""
|
||||
from ..core.connection import DeviceCommandError
|
||||
from ..core.device_config import DeviceConfigError
|
||||
from ..core.selection import DeviceSelectionError
|
||||
|
||||
run_id = ctx.repo.start_run(self.name, params, ctx.profile_name)
|
||||
ctx.log.debug("run %s start: tool=%s params=%s", run_id, self.name, params)
|
||||
try:
|
||||
result = await self.run(ctx, {**params, "_run_id": run_id})
|
||||
except DeviceSelectionError as exc:
|
||||
# Expected user-facing condition (no/ambiguous device): record it but don't
|
||||
# dump a traceback; callers print the guidance message cleanly.
|
||||
except (DeviceSelectionError, DeviceConfigError, DeviceCommandError) as exc:
|
||||
# Expected user-facing condition (no/ambiguous device, bad config value, or
|
||||
# a transient command failure): record it but don't dump a traceback;
|
||||
# callers print the message cleanly.
|
||||
ctx.repo.finish_run(run_id, "error", {"error": str(exc)})
|
||||
ctx.log.debug("run %s aborted: %s", run_id, exc)
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"""The ``config`` tool: view and change every device configuration value.
|
||||
|
||||
Interactively it launches a full editor (see :mod:`meshtools.ui.config_editor`); on the
|
||||
CLI it exposes generic key/value subcommands plus backup/restore, channels, custom vars,
|
||||
and a gated set of destructive operations. Both paths funnel into :meth:`ConfigTool.run`,
|
||||
which executes a list of operation tuples so every change is logged through the run record.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from ..context import AppContext
|
||||
from ..core.config_io import backup_config, plan_restore, read_backup
|
||||
from ..core.connection import Device
|
||||
from ..core.device_config import (
|
||||
build_snapshot,
|
||||
format_value,
|
||||
get_spec,
|
||||
parse_value,
|
||||
)
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
# How many channel slots to probe when backing up.
|
||||
_MAX_CHANNELS = 8
|
||||
|
||||
|
||||
@register
|
||||
class ConfigTool(Tool):
|
||||
"""View and edit the connected device's full configuration."""
|
||||
|
||||
name = "config"
|
||||
help = "View and change device configuration (name, radio, experimental, ...)."
|
||||
category = "Device"
|
||||
order = 8
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
|
||||
"""Launch the interactive editor and collect the operations to perform.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
``{"ops": [...]}`` to execute, or ``None`` if the user cancelled.
|
||||
"""
|
||||
from ..ui.config_editor import edit_config
|
||||
|
||||
ops = await edit_config(ctx)
|
||||
if not ops:
|
||||
return None
|
||||
return {"ops": ops}
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Execute a list of configuration operations against the device.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``ops`` — a list of operation tuples (see module docstring).
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing how many values changed.
|
||||
"""
|
||||
device = await ctx.device()
|
||||
ops: list[tuple] = list(params.get("ops") or [])
|
||||
snapshot = await build_snapshot(device)
|
||||
changes, artifacts = await apply_ops(ctx, device, snapshot, ops)
|
||||
|
||||
message = f"[ok]✓[/ok] applied [brand]{changes}[/brand] change(s)" if changes else None
|
||||
return ToolResult(summary={"changes": changes}, message=message, artifacts=artifacts)
|
||||
|
||||
# -- CLI --------------------------------------------------------------------
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``config`` subcommand group.
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
config_app = typer.Typer(
|
||||
help=self.help, no_args_is_help=False, rich_markup_mode="rich"
|
||||
)
|
||||
|
||||
@config_app.callback(invoke_without_command=True)
|
||||
def _root(ctx: typer.Context) -> None:
|
||||
"""Show the configuration when no subcommand is given."""
|
||||
if ctx.invoked_subcommand is None:
|
||||
run_tool_command(self, {"ops": [("show",)]})
|
||||
|
||||
@config_app.command("show", help="Show all current settings.")
|
||||
def _show_cmd() -> None:
|
||||
run_tool_command(self, {"ops": [("show",)]})
|
||||
|
||||
@config_app.command("get", help="Print one setting's value.")
|
||||
def _get_cmd(key: str = typer.Argument(..., help="Setting key.")) -> None:
|
||||
run_tool_command(self, {"ops": [("get", key)]})
|
||||
|
||||
@config_app.command("set", help="Set one setting to a value.")
|
||||
def _set_cmd(
|
||||
key: str = typer.Argument(..., help="Setting key."),
|
||||
value: str = typer.Argument(..., help="New value."),
|
||||
) -> None:
|
||||
run_tool_command(self, {"ops": [("set", key, value)]})
|
||||
|
||||
@config_app.command("backup", help="Write all settings to a TOML file.")
|
||||
def _backup_cmd(path: Path = typer.Argument(..., help="Destination file.")) -> None:
|
||||
run_tool_command(self, {"ops": [("backup", path)]})
|
||||
|
||||
@config_app.command("restore", help="Apply settings from a TOML backup.")
|
||||
def _restore_cmd(
|
||||
path: Path = typer.Argument(..., help="Backup file."),
|
||||
dry_run: bool = typer.Option(False, "--dry-run", help="Preview without applying."),
|
||||
) -> None:
|
||||
run_tool_command(self, {"ops": [("restore", path, dry_run)]})
|
||||
|
||||
@config_app.command("custom", help="Set an experimental custom variable.")
|
||||
def _custom_cmd(
|
||||
key: str = typer.Argument(..., help="Variable name."),
|
||||
value: str = typer.Argument(..., help="Variable value."),
|
||||
) -> None:
|
||||
run_tool_command(self, {"ops": [("set_custom", key, value)]})
|
||||
|
||||
@config_app.command("channel", help="Configure a channel slot.")
|
||||
def _channel_cmd(
|
||||
index: int = typer.Argument(..., help="Channel slot index."),
|
||||
name: str = typer.Argument(..., help="Channel name (# derives the secret)."),
|
||||
secret: Optional[str] = typer.Option(None, "--secret", help="16-byte hex secret."),
|
||||
) -> None:
|
||||
secret_bytes = bytes.fromhex(secret) if secret else None
|
||||
run_tool_command(self, {"ops": [("set_channel", index, name, secret_bytes)]})
|
||||
|
||||
@config_app.command("advert", help="Broadcast an advertisement.")
|
||||
def _advert_cmd(
|
||||
flood: bool = typer.Option(False, "--flood", help="Flood across the mesh."),
|
||||
) -> None:
|
||||
run_tool_command(self, {"ops": [("advert", flood)]})
|
||||
|
||||
@config_app.command("export-key", help="Export the private key (sensitive).")
|
||||
def _export_key_cmd(
|
||||
out: Optional[Path] = typer.Option(None, "--out", help="Write to file instead of stdout."),
|
||||
) -> None:
|
||||
ops = [("export_key", out)] if out else [("export_key",)]
|
||||
run_tool_command(self, {"ops": ops})
|
||||
|
||||
@config_app.command("import-key", help="Import a private key (overwrites identity).")
|
||||
def _import_key_cmd(
|
||||
key_hex: str = typer.Argument(..., help="Private key as hex."),
|
||||
yes: bool = typer.Option(False, "--yes", help="Confirm this destructive action."),
|
||||
) -> None:
|
||||
_require_yes(yes, "import-key overwrites the device identity")
|
||||
run_tool_command(self, {"ops": [("import_key", key_hex)]})
|
||||
|
||||
@config_app.command("reboot", help="Reboot the device.")
|
||||
def _reboot_cmd(
|
||||
yes: bool = typer.Option(False, "--yes", help="Confirm reboot."),
|
||||
) -> None:
|
||||
_require_yes(yes, "reboot restarts the device")
|
||||
run_tool_command(self, {"ops": [("reboot",)]})
|
||||
|
||||
@config_app.command("factory-reset", help="Erase all data and reset to defaults.")
|
||||
def _factory_reset_cmd(
|
||||
yes: bool = typer.Option(False, "--yes", help="Confirm this destructive action."),
|
||||
) -> None:
|
||||
_require_yes(yes, "factory-reset erases ALL data on the device")
|
||||
run_tool_command(self, {"ops": [("factory_reset",)]})
|
||||
|
||||
app.add_typer(config_app, name=self.name)
|
||||
|
||||
|
||||
# -- op execution (shared by the tool and the interactive editor) -------------
|
||||
|
||||
|
||||
async def apply_ops(
|
||||
ctx: AppContext, device: Device, snapshot: dict, ops: list[tuple]
|
||||
) -> tuple[int, list[str]]:
|
||||
"""Execute a list of configuration operation tuples against ``device``.
|
||||
|
||||
This is the single executor for every config operation, used both by
|
||||
:meth:`ConfigTool.run` (for staged, applied changes) and by the interactive editor's
|
||||
danger zone (which runs its action immediately rather than staging it).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context (for console output).
|
||||
device: The connected device to act on.
|
||||
snapshot: The current device snapshot; updated in place as settings change so
|
||||
coupled commands rebuild from current values.
|
||||
ops: Operation tuples (see the module docstring).
|
||||
|
||||
Returns:
|
||||
A ``(changes, artifacts)`` pair: the number of value changes applied and any
|
||||
file paths produced.
|
||||
"""
|
||||
changes = 0
|
||||
artifacts: list[str] = []
|
||||
for op in ops:
|
||||
kind = op[0]
|
||||
if kind == "show":
|
||||
await _show(ctx, device, snapshot)
|
||||
elif kind == "get":
|
||||
spec = get_spec(op[1])
|
||||
ctx.console.print(
|
||||
f"[muted]{spec.key}[/muted] = {format_value(spec, spec.getter(snapshot))}"
|
||||
)
|
||||
elif kind == "set":
|
||||
changes += await _apply_setting(ctx, device, op[1], op[2], snapshot)
|
||||
elif kind == "set_custom":
|
||||
await device.set_custom_var(op[1], op[2])
|
||||
ctx.console.print(f"[ok]✓[/ok] custom [brand]{op[1]}[/brand] = {op[2]}")
|
||||
changes += 1
|
||||
elif kind == "set_channel":
|
||||
await device.set_channel(op[1], op[2], op[3])
|
||||
ctx.console.print(f"[ok]✓[/ok] channel {op[1]} = [brand]{op[2]}[/brand]")
|
||||
changes += 1
|
||||
elif kind == "backup":
|
||||
artifacts.append(str(await _backup(device, snapshot, op[1])))
|
||||
elif kind == "restore":
|
||||
changes += await _restore(ctx, device, snapshot, op[1], op[2])
|
||||
elif kind == "advert":
|
||||
await device.send_advert(len(op) > 1 and bool(op[1]))
|
||||
ctx.console.print("[ok]✓[/ok] advertisement sent")
|
||||
elif kind == "reboot":
|
||||
await device.reboot()
|
||||
ctx.console.print("[warn]device rebooting[/warn]")
|
||||
elif kind == "export_key":
|
||||
await _export_key(ctx, device, op[1] if len(op) > 1 else None, artifacts)
|
||||
elif kind == "import_key":
|
||||
await device.import_private_key(op[1])
|
||||
ctx.console.print("[ok]✓[/ok] private key imported")
|
||||
changes += 1
|
||||
elif kind == "factory_reset":
|
||||
await device.factory_reset()
|
||||
ctx.console.print("[err]device factory-reset[/err]")
|
||||
else: # pragma: no cover - guarded by the call sites that build ops
|
||||
ctx.console.print(f"[err]unknown config op: {kind}[/err]")
|
||||
return changes, artifacts
|
||||
|
||||
|
||||
async def _apply_setting(
|
||||
ctx: AppContext, device: Device, key: str, raw: Any, snapshot: dict
|
||||
) -> int:
|
||||
"""Parse, apply and record one setting; keep ``snapshot`` consistent.
|
||||
|
||||
The local snapshot is updated with the new value so a later coupled change in the
|
||||
same batch (e.g. another radio field) is rebuilt from current values.
|
||||
|
||||
Returns:
|
||||
``1`` (a change was applied).
|
||||
"""
|
||||
spec = get_spec(key)
|
||||
value = parse_value(spec, raw)
|
||||
await spec.apply(device, value, snapshot)
|
||||
snapshot[key] = value
|
||||
ctx.console.print(f"[ok]✓[/ok] [brand]{key}[/brand] = {format_value(spec, value)}")
|
||||
return 1
|
||||
|
||||
|
||||
async def _show(ctx: AppContext, device: Device, snapshot: dict) -> None:
|
||||
"""Render the full configuration table plus custom variables."""
|
||||
from ..ui.config_editor import render_config
|
||||
|
||||
custom = await device.get_custom_vars()
|
||||
render_config(ctx.console, snapshot, custom)
|
||||
|
||||
|
||||
async def _backup(device: Device, snapshot: dict, path: Path) -> Path:
|
||||
"""Write a TOML backup of the current configuration."""
|
||||
custom = await device.get_custom_vars()
|
||||
channels = await _read_channels(device)
|
||||
return backup_config(Path(path), snapshot, custom, channels)
|
||||
|
||||
|
||||
async def _restore(
|
||||
ctx: AppContext, device: Device, snapshot: dict, path: Path, dry_run: bool
|
||||
) -> int:
|
||||
"""Apply (or preview) a backup file against the current configuration.
|
||||
|
||||
Returns:
|
||||
The number of changes applied (always ``0`` for a dry run).
|
||||
"""
|
||||
backup = read_backup(Path(path))
|
||||
custom = await device.get_custom_vars()
|
||||
ops = plan_restore(backup, snapshot, custom)
|
||||
if not ops:
|
||||
ctx.console.print("[muted]restore: device already matches the backup.[/muted]")
|
||||
return 0
|
||||
|
||||
if dry_run:
|
||||
table = Table(title="Restore preview", border_style="warn", expand=False)
|
||||
table.add_column("Operation")
|
||||
table.add_column("Target")
|
||||
table.add_column("Value")
|
||||
for op in ops:
|
||||
table.add_row(op[0], str(op[1]), str(op[2] if len(op) > 2 else ""))
|
||||
ctx.console.print(table)
|
||||
ctx.console.print("[muted]dry run — nothing was changed.[/muted]")
|
||||
return 0
|
||||
|
||||
changes = 0
|
||||
for op in ops:
|
||||
if op[0] == "set":
|
||||
changes += await _apply_setting(ctx, device, op[1], op[2], snapshot)
|
||||
elif op[0] == "set_custom":
|
||||
await device.set_custom_var(op[1], op[2])
|
||||
changes += 1
|
||||
elif op[0] == "set_channel":
|
||||
await device.set_channel(op[1], op[2], op[3])
|
||||
changes += 1
|
||||
return changes
|
||||
|
||||
|
||||
async def _export_key(
|
||||
ctx: AppContext, device: Device, out: Optional[Path], artifacts: list[str]
|
||||
) -> None:
|
||||
"""Export the private key, to a file if ``out`` is given, else to the console."""
|
||||
key_hex = await device.export_private_key()
|
||||
if out is not None:
|
||||
path = Path(out)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(key_hex, encoding="utf-8")
|
||||
artifacts.append(str(path))
|
||||
ctx.console.print("[warn]private key written — keep this file secret.[/warn]")
|
||||
else:
|
||||
ctx.console.print(
|
||||
"[warn]private key (keep secret):[/warn] [muted]" + key_hex + "[/muted]"
|
||||
)
|
||||
|
||||
|
||||
async def _read_channels(device: Device) -> list[dict]:
|
||||
"""Probe channel slots and return the configured ones."""
|
||||
channels: list[dict] = []
|
||||
for idx in range(_MAX_CHANNELS):
|
||||
try:
|
||||
ch = await device.get_channel(idx)
|
||||
except Exception: # noqa: BLE001 - firmware may not support channel reads
|
||||
break
|
||||
if ch:
|
||||
channels.append(ch)
|
||||
return channels
|
||||
|
||||
|
||||
def _require_yes(yes: bool, what: str) -> None:
|
||||
"""Abort a destructive CLI command unless ``--yes`` was passed.
|
||||
|
||||
Args:
|
||||
yes: Whether the user passed ``--yes``.
|
||||
what: Human-readable description of the consequence.
|
||||
|
||||
Raises:
|
||||
typer.Exit: With code 1 if confirmation was not given.
|
||||
"""
|
||||
if not yes:
|
||||
typer.secho(f"Refusing: {what}. Re-run with --yes to confirm.", fg="red")
|
||||
raise typer.Exit(1)
|
||||
+9
-10
@@ -21,7 +21,7 @@ class InfoTool(Tool):
|
||||
order = 10
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Query the device and render its self-info and contacts.
|
||||
"""Query the device and render its full configuration and contacts.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
@@ -30,17 +30,16 @@ class InfoTool(Tool):
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing device name and contact count.
|
||||
"""
|
||||
from ..core.device_config import build_snapshot
|
||||
from ..ui.config_editor import render_config
|
||||
|
||||
device = await ctx.device()
|
||||
info = await device.get_self_info()
|
||||
snapshot = await build_snapshot(device)
|
||||
custom = await device.get_custom_vars()
|
||||
contacts = await device.get_contacts()
|
||||
|
||||
table = Table(title="Device", border_style="muted", expand=False)
|
||||
table.add_column("Field", style="muted")
|
||||
table.add_column("Value")
|
||||
for key in ("name", "tx_power", "freq", "bw", "sf", "cr"):
|
||||
if key in info:
|
||||
table.add_row(key, str(info[key]))
|
||||
ctx.console.print(table)
|
||||
# Render every current setting with a short explanation of each.
|
||||
render_config(ctx.console, snapshot, custom)
|
||||
|
||||
if contacts:
|
||||
ctable = Table(title=f"Contacts ({len(contacts)})", border_style="muted")
|
||||
@@ -51,7 +50,7 @@ class InfoTool(Tool):
|
||||
ctx.console.print(ctable)
|
||||
|
||||
return ToolResult(
|
||||
summary={"name": info.get("name"), "contacts": len(contacts)},
|
||||
summary={"name": snapshot.get("name"), "contacts": len(contacts)},
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
|
||||
+121
-23
@@ -13,10 +13,15 @@ import questionary
|
||||
import typer
|
||||
|
||||
from ..context import AppContext
|
||||
from ..core.models import LOCAL_DEVICE_LABEL
|
||||
from ..services import trace_runner
|
||||
from ..ui.widgets import make_progress, stats_panel, trace_table
|
||||
from ..ui.widgets import make_progress, stats_panel, traces_table
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
#: Upper bound on traces per run — the per-trace table renders one column each, so
|
||||
#: this keeps the output readable and the radio's duty cycle in check.
|
||||
MAX_TRACES = 8
|
||||
|
||||
|
||||
@register
|
||||
class TraceTool(Tool):
|
||||
@@ -52,11 +57,30 @@ class TraceTool(Tool):
|
||||
return None
|
||||
|
||||
samples_raw = await questionary.text(
|
||||
"How many traces?", default="5", validate=_is_positive_int
|
||||
f"How many traces? (1-{MAX_TRACES})", default="3", validate=_is_valid_sample_count
|
||||
).ask_async()
|
||||
if samples_raw is None:
|
||||
return None
|
||||
return {"target": target.strip(), "samples": int(samples_raw)}
|
||||
|
||||
# Optional explicit path, MeshCore-app style: comma-separated contact names
|
||||
# and/or hex key prefixes (e.g. ``3d,f2,3d``). Blank lets the device route.
|
||||
path_prompt = "Force a path? (comma-separated contacts/hex prefixes, blank = auto):"
|
||||
validate_path = lambda v: _validate_path(v, contacts) # noqa: E731
|
||||
if choices:
|
||||
path_spec = await questionary.autocomplete(
|
||||
path_prompt, choices=choices, ignore_case=True, validate=validate_path
|
||||
).ask_async()
|
||||
else:
|
||||
path_spec = await questionary.text(
|
||||
path_prompt, validate=validate_path
|
||||
).ask_async()
|
||||
if path_spec is None:
|
||||
return None
|
||||
|
||||
params: dict[str, Any] = {"target": target.strip(), "samples": int(samples_raw)}
|
||||
if path_spec.strip():
|
||||
params["path"] = path_spec.strip()
|
||||
return params
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run the traces, persist each one, and render the summary.
|
||||
@@ -69,41 +93,80 @@ class TraceTool(Tool):
|
||||
A :class:`ToolResult` with the aggregated statistics.
|
||||
"""
|
||||
target = params["target"]
|
||||
samples = int(params.get("samples", 5))
|
||||
samples = max(1, min(MAX_TRACES, int(params.get("samples", 3))))
|
||||
if int(params.get("samples", 3)) > MAX_TRACES:
|
||||
ctx.console.print(f"[warn]capping at {MAX_TRACES} traces[/warn]")
|
||||
run_id = params["_run_id"]
|
||||
device = await ctx.device()
|
||||
|
||||
last_trace = None
|
||||
# Our own device's name labels both endpoints of the path (first hop's origin,
|
||||
# last hop's destination); fall back to a neutral label if it's unavailable.
|
||||
self_info = await device.get_self_info()
|
||||
device_label = str(self_info.get("name") or LOCAL_DEVICE_LABEL)
|
||||
|
||||
# Resolve repeater hashes in the results to contact names where we know them,
|
||||
# so the tables read as names instead of opaque hex prefixes.
|
||||
contacts = await device.get_contacts()
|
||||
resolve = trace_runner.make_node_resolver(contacts)
|
||||
|
||||
# Resolve an optional forced path (names/hex) to the hex string the radio wants.
|
||||
# Leaving it blank is fully supported: the device reuses the route it already
|
||||
# learned for the target (or floods if it has none).
|
||||
path: Optional[str] = None
|
||||
path_spec = params.get("path")
|
||||
if path_spec:
|
||||
path = trace_runner.parse_trace_path(path_spec, contacts)
|
||||
ctx.console.print(f"[dim]forcing path:[/dim] [brand]{path}[/brand]")
|
||||
else:
|
||||
ctx.console.print("[dim]path:[/dim] [muted]auto (device-routed)[/muted]")
|
||||
|
||||
traces: list = []
|
||||
with make_progress(ctx.console) as progress:
|
||||
task = progress.add_task(f"tracing {target}", total=samples)
|
||||
|
||||
def on_result(done: int, total: int, result) -> None: # noqa: ANN001
|
||||
nonlocal last_trace
|
||||
last_trace = result
|
||||
traces.append(result)
|
||||
progress.advance(task)
|
||||
|
||||
stats = await trace_runner.measure(
|
||||
device,
|
||||
target,
|
||||
samples=samples,
|
||||
path=path,
|
||||
cooldown_s=ctx.settings.trace_cooldown_s,
|
||||
on_result=on_result,
|
||||
persist=lambda t: ctx.repo.record_trace(run_id, t),
|
||||
)
|
||||
|
||||
if last_trace is not None and last_trace.success:
|
||||
ctx.console.print(trace_table(last_trace))
|
||||
ctx.console.print(stats_panel(stats))
|
||||
# Use the first reply we got as the representative route shown in the summary
|
||||
# (forced path, or the route the device resolved when auto-routing).
|
||||
current = next((t for t in traces if t.success), None)
|
||||
if traces:
|
||||
ctx.console.print(traces_table(traces, device_label, resolve))
|
||||
ctx.console.print(stats_panel(stats, device_label, resolve, route=current))
|
||||
|
||||
summary: dict[str, Any] = {
|
||||
"target": stats.target,
|
||||
"samples": stats.samples,
|
||||
"success_rate": round(stats.success_rate, 3),
|
||||
"median_min_snr": stats.median_min_snr,
|
||||
"median_rtt_ms": stats.median_rtt_ms,
|
||||
"median_hop_snrs": [
|
||||
{
|
||||
"hop": agg.index,
|
||||
"from": agg.origin or device_label,
|
||||
"to": agg.destination or device_label,
|
||||
"median_snr": agg.median_snr,
|
||||
}
|
||||
for agg in stats.hop_snrs
|
||||
],
|
||||
}
|
||||
if path:
|
||||
summary["path"] = path
|
||||
via = f" via [brand]{path}[/brand]" if path else ""
|
||||
return ToolResult(
|
||||
summary={
|
||||
"target": stats.target,
|
||||
"samples": stats.samples,
|
||||
"success_rate": round(stats.success_rate, 3),
|
||||
"median_min_snr": stats.median_min_snr,
|
||||
"median_rtt_ms": stats.median_rtt_ms,
|
||||
},
|
||||
message=f"[ok]✓[/ok] traced [brand]{target}[/brand] x{samples}",
|
||||
summary=summary,
|
||||
message=f"[ok]✓[/ok] traced [brand]{target}[/brand] x{samples}{via}",
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
@@ -117,13 +180,43 @@ class TraceTool(Tool):
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _trace(
|
||||
target: str = typer.Option(..., "--target", "-t", help="Target node name/prefix."),
|
||||
samples: int = typer.Option(5, "--samples", "-n", help="Number of traces."),
|
||||
samples: int = typer.Option(
|
||||
3, "--samples", "-n", help=f"Number of traces (max {MAX_TRACES})."
|
||||
),
|
||||
path: Optional[str] = typer.Option(
|
||||
None,
|
||||
"--path",
|
||||
"-p",
|
||||
help="Force a route: comma-separated contact names/hex prefixes (e.g. 3d,f2,3d).",
|
||||
),
|
||||
) -> None:
|
||||
run_tool_command(self, {"target": target, "samples": samples})
|
||||
tool_params: dict[str, Any] = {"target": target, "samples": samples}
|
||||
if path:
|
||||
tool_params["path"] = path
|
||||
run_tool_command(self, tool_params)
|
||||
|
||||
|
||||
def _is_positive_int(value: str) -> bool | str:
|
||||
"""Validate that a questionary text answer is a positive integer.
|
||||
def _validate_path(value: str, contacts: list[Any]) -> bool | str:
|
||||
"""Validate an optional forced-path spec for the interactive prompt.
|
||||
|
||||
Args:
|
||||
value: The raw comma-separated path entry; blank means "let the device route".
|
||||
contacts: Known contacts used to resolve names in the spec.
|
||||
|
||||
Returns:
|
||||
``True`` if valid (including blank), otherwise an error message string.
|
||||
"""
|
||||
if not value.strip():
|
||||
return True
|
||||
try:
|
||||
trace_runner.parse_trace_path(value, contacts)
|
||||
return True
|
||||
except ValueError as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
def _is_valid_sample_count(value: str) -> bool | str:
|
||||
"""Validate that a questionary text answer is a trace count in ``1..MAX_TRACES``.
|
||||
|
||||
Args:
|
||||
value: The raw user input.
|
||||
@@ -132,6 +225,11 @@ def _is_positive_int(value: str) -> bool | str:
|
||||
``True`` if valid, otherwise an error message string.
|
||||
"""
|
||||
try:
|
||||
return int(value) > 0 or "Enter a number greater than zero."
|
||||
count = int(value)
|
||||
except ValueError:
|
||||
return "Enter a whole number."
|
||||
if count < 1:
|
||||
return "Enter a number greater than zero."
|
||||
if count > MAX_TRACES:
|
||||
return f"Maximum {MAX_TRACES} traces."
|
||||
return True
|
||||
Reference in new issue
Block a user