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:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-06-21 11:19:21 -04:00
1 parent 43353f83a9
commit 421781f13d
19 files changed
+3081 -108

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
"""TOML backup and restore for device configuration.
A backup captures every registry setting's current value plus experimental custom
variables and configured channels, so a device's configuration can be archived, diffed,
or cloned onto another node. Restore turns a backup into the same operation list the
``config`` tool executes for live edits, and supports a dry-run diff against the device's
current state.
"""
from __future__ import annotations
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import tomli_w
from .device_config import DEVICE_SETTINGS, get_spec, parse_value
if sys.version_info >= (3, 11):
import tomllib
else: # pragma: no cover - exercised only on 3.10
import tomli as tomllib
@dataclass(slots=True)
class Backup:
"""A parsed configuration backup.
Attributes:
settings: Registry setting key -> raw value.
custom: Experimental custom variable name -> value.
channels: One dict per channel with ``index``, ``name`` and hex ``secret``.
"""
settings: dict[str, Any] = field(default_factory=dict)
custom: dict[str, str] = field(default_factory=dict)
channels: list[dict[str, Any]] = field(default_factory=list)
def backup_config(
path: Path,
snapshot: dict,
custom_vars: dict[str, str],
channels: list[dict],
) -> Path:
"""Write the current configuration to a TOML file.
Args:
path: Destination file path (parent directories are created).
snapshot: A device snapshot (see ``device_config.build_snapshot``).
custom_vars: Experimental custom variables.
channels: Channel dicts (``channel_idx``, ``channel_name``, ``channel_secret``
as raw bytes).
Returns:
The path written.
"""
settings: dict[str, Any] = {}
for spec in DEVICE_SETTINGS:
value = spec.getter(snapshot)
if value is not None:
settings[spec.key] = value
doc: dict[str, Any] = {"settings": settings}
if custom_vars:
doc["custom"] = dict(custom_vars)
if channels:
doc["channels"] = [
{
"index": ch.get("channel_idx", idx),
"name": ch.get("channel_name", ""),
"secret": _to_hex(ch.get("channel_secret")),
}
for idx, ch in enumerate(channels)
]
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb") as fh:
tomli_w.dump(doc, fh)
return path
def read_backup(path: Path) -> Backup:
"""Read and parse a TOML configuration backup.
Args:
path: The backup file to read.
Returns:
A :class:`Backup`.
Raises:
FileNotFoundError: If ``path`` does not exist.
"""
with path.open("rb") as fh:
doc = tomllib.load(fh)
return Backup(
settings=dict(doc.get("settings") or {}),
custom=dict(doc.get("custom") or {}),
channels=list(doc.get("channels") or []),
)
def plan_restore(
backup: Backup,
snapshot: dict,
current_custom: dict[str, str],
) -> list[tuple]:
"""Diff a backup against the current state and return the operations to apply.
Only values that differ from the device's current configuration are emitted, so a
restore (or its dry-run preview) shows exactly what would change.
Args:
backup: The parsed backup.
snapshot: The device's current snapshot.
current_custom: The device's current custom variables.
Returns:
A list of operation tuples compatible with the ``config`` tool:
``("set", key, value)``, ``("set_custom", key, value)``, and
``("set_channel", index, name, secret_bytes)``.
Raises:
DeviceConfigError: If a backed-up setting key or value is invalid.
"""
ops: list[tuple] = []
for key, raw in backup.settings.items():
spec = get_spec(key) # raises on unknown key
value = parse_value(spec, raw)
if value != spec.getter(snapshot):
ops.append(("set", key, value))
for key, value in backup.custom.items():
if current_custom.get(key) != value:
ops.append(("set_custom", key, str(value)))
for ch in backup.channels:
secret_hex = ch.get("secret") or ""
secret = bytes.fromhex(secret_hex) if secret_hex else None
ops.append(("set_channel", int(ch.get("index", 0)), str(ch.get("name", "")), secret))
return ops
def _to_hex(secret: Any) -> str:
"""Render a channel secret as a hex string, accepting bytes or str."""
if isinstance(secret, (bytes, bytearray)):
return secret.hex()
return str(secret or "")
+506 -31
View File
@@ -24,6 +24,14 @@ TX_POWER_MIN = 1
TX_POWER_MAX = 22
class DeviceCommandError(RuntimeError):
"""A device command failed in a recoverable, user-facing way.
Raised for conditions worth reporting cleanly (no traceback) — chiefly the
companion's intermittent failure to answer a query in time. Callers may retry.
"""
class Device(ABC):
"""Abstract companion device exposing the operations MeshTools needs.
@@ -73,21 +81,141 @@ class Device(ABC):
self,
target: str,
*,
path: Optional[list[str]] = None,
path: Optional[str] = None,
timeout: float = 10.0,
) -> TraceResult:
"""Run a single path trace to ``target`` and return per-hop SNR.
Args:
target: Name or key prefix of the destination node.
path: Optional explicit path to force (list of node identifiers). When
``None`` the device chooses the path.
path: Optional explicit path to force, as a comma-separated string of
single-byte hex key prefixes (e.g. ``"3d,f2,3d"``). When ``None``
the device chooses the path.
timeout: Seconds to wait for the trace reply.
Returns:
A :class:`TraceResult`; ``success`` is ``False`` on timeout.
"""
# -- configuration: extra reads ---------------------------------------------
@abstractmethod
async def get_tuning(self) -> dict:
"""Return radio tuning parameters.
Returns:
A dict with ``rx_delay`` and ``airtime_factor`` (both ints).
"""
@abstractmethod
async def get_path_hash_mode(self) -> int:
"""Return the current path-hash mode (experimental routing flag)."""
@abstractmethod
async def get_custom_vars(self) -> dict[str, str]:
"""Return the device's experimental custom key/value variables."""
@abstractmethod
async def get_channel(self, index: int) -> Optional[dict]:
"""Return one channel's configuration, or ``None`` if unset.
Args:
index: Zero-based channel slot.
Returns:
A dict with ``channel_idx``, ``channel_name`` and ``channel_secret``
(16 raw bytes), or ``None`` when the slot is empty.
"""
# -- configuration: settable values -----------------------------------------
@abstractmethod
async def set_name(self, name: str) -> None:
"""Set the node's advertised name."""
@abstractmethod
async def set_coords(self, lat: float, lon: float) -> None:
"""Set the node's advertised latitude/longitude (decimal degrees)."""
@abstractmethod
async def set_device_pin(self, pin: int) -> None:
"""Set the device's BLE pairing PIN."""
@abstractmethod
async def set_radio(self, freq: float, bw: float, sf: int, cr: int) -> None:
"""Set the core radio parameters.
Args:
freq: Frequency in MHz.
bw: Bandwidth in kHz.
sf: Spreading factor.
cr: Coding rate denominator (``5``-``8`` for 4/5-4/8).
"""
@abstractmethod
async def set_tuning(self, rx_delay: int, airtime_factor: int) -> None:
"""Set radio tuning parameters (RX delay and airtime budgeting factor)."""
@abstractmethod
async def set_manual_add_contacts(self, enabled: bool) -> None:
"""Set whether contacts must be added manually rather than automatically."""
@abstractmethod
async def set_adv_loc_policy(self, policy: int) -> None:
"""Set the advert location-sharing policy."""
@abstractmethod
async def set_multi_acks(self, value: int) -> None:
"""Set the multi-ack behavior flag."""
@abstractmethod
async def set_telemetry_modes(self, base: int, loc: int, env: int) -> None:
"""Set the three telemetry mode fields together (each ``0``-``3``)."""
@abstractmethod
async def set_path_hash_mode(self, mode: int) -> None:
"""Set the experimental path-hash routing mode."""
@abstractmethod
async def set_custom_var(self, key: str, value: str) -> None:
"""Set an experimental custom variable."""
@abstractmethod
async def set_channel(self, index: int, name: str, secret: Optional[bytes]) -> None:
"""Configure a channel slot.
Args:
index: Zero-based channel slot.
name: Channel name (a leading ``#`` derives the secret from the name).
secret: 16-byte shared secret, or ``None`` to derive it from ``name``.
"""
# -- configuration: actions -------------------------------------------------
@abstractmethod
async def set_time(self, epoch: int) -> None:
"""Set the device clock to a UNIX epoch timestamp."""
@abstractmethod
async def send_advert(self, flood: bool = False) -> None:
"""Broadcast an advertisement (``flood`` propagates it across the mesh)."""
@abstractmethod
async def reboot(self) -> None:
"""Reboot the device."""
@abstractmethod
async def export_private_key(self) -> str:
"""Export the device's private key as a hex string (sensitive)."""
@abstractmethod
async def import_private_key(self, key_hex: str) -> None:
"""Import a private key from a hex string (overwrites the device identity)."""
@abstractmethod
async def factory_reset(self) -> None:
"""Erase all device data and restore factory defaults (destructive)."""
async def __aenter__(self) -> "Device":
"""Enter the async context manager, connecting the device."""
await self.connect()
@@ -151,10 +279,45 @@ class MeshCoreDevice(Device):
result = await mc.commands.send_appstart()
return dict(getattr(result, "payload", {}) or {})
async def _contacts_payload(
self, mc, *, retries: int = 3, delay: float = 0.5
) -> dict: # noqa: ANN001
"""Fetch the raw contacts map, retrying the transient "no event" blip.
The companion intermittently fails to emit the contacts event in time and
returns an error event instead of data (``no event received during contacts
retrieval``). That's a recoverable timing hiccup, so retry a few times with a
short backoff before surfacing a clean, actionable error.
Args:
mc: The connected ``MeshCore`` client.
retries: Number of extra attempts after the first.
delay: Seconds to wait between attempts.
Returns:
The contacts payload mapping (possibly empty).
Raises:
DeviceCommandError: If every attempt fails to retrieve contacts.
"""
reason = ""
for attempt in range(retries + 1):
event = await mc.commands.get_contacts()
if event is None or not getattr(event, "is_error", lambda: False)():
return dict(getattr(event, "payload", {}) or {})
payload = getattr(event, "payload", {}) or {}
reason = str(payload.get("reason", payload))
if attempt < retries:
await asyncio.sleep(delay)
raise DeviceCommandError(
f"could not read contacts from the radio ({reason}). "
"The companion didn't respond in time — this is usually transient; "
"retry, or power-cycle/reconnect the radio if it persists."
)
async def get_contacts(self) -> list[Contact]: # noqa: D102 - inherited docstring
mc = self._require()
result = await mc.commands.get_contacts()
payload = getattr(result, "payload", {}) or {}
payload = await self._contacts_payload(mc)
contacts: list[Contact] = []
for name, info in payload.items():
info = info or {}
@@ -180,44 +343,231 @@ class MeshCoreDevice(Device):
self,
target: str,
*,
path: Optional[list[str]] = None,
path: Optional[str] = None,
timeout: float = 10.0,
) -> TraceResult:
from meshcore import EventType # local import keeps mock path dependency-free
from ..services.trace_runner import path_hash_flags
mc = self._require()
tag = random.randint(0, 0xFFFFFFFF)
started = asyncio.get_event_loop().time()
await mc.commands.send_trace(auth_code=0, tag=tag, flags=0, path=path)
# A trace packet has no destination field — it walks an explicit path of
# repeater hops. Send the path as raw bytes so any uniform hash width
# transmits; ``flags`` carries the path-hash mode (size - 1).
path_bytes: Optional[bytes] = None
flags = 0
if path:
hops = [h.strip() for h in path.split(",") if h.strip()]
path_bytes = bytes.fromhex("".join(hops))
flags = path_hash_flags(len(bytes.fromhex(hops[0]))) or 0
else:
# No forced path: build a path that ends at the target's own hash
# (prepending any learned ``out_path`` repeaters), since a trace only
# replies when its destination is the final hop. ``None`` only when the
# contact is unknown, leaving the trace to run path-less.
resolved = await self._trace_path_to_contact(mc, target)
if resolved is not None:
path_bytes, flags = resolved
await mc.commands.send_trace(auth_code=0, tag=tag, flags=flags, path=path_bytes)
event = await mc.wait_for_event(
EventType.TRACE_DATA,
attribute_filters={"tag": tag},
timeout=timeout,
)
elapsed_ms = (asyncio.get_event_loop().time() - started) * 1000.0
# The firmware addresses each hop by a hash of ``1 << flags`` bytes; record it
# so the summary can show node hashes at the width the command actually used.
hash_bytes = 1 << flags
if event is None:
return TraceResult(target=target, success=False, round_trip_ms=None)
return TraceResult(
target=target, success=False, round_trip_ms=None, path_hash_bytes=hash_bytes
)
payload = getattr(event, "payload", {}) or {}
raw_snrs = payload.get("path_snrs") or payload.get("snrs") or []
nodes = payload.get("path") or []
hops = [
Hop(
index=i,
node=str(nodes[i]) if i < len(nodes) else None,
snr=raw / 4.0, # protocol encodes SNR as a signed byte of SNR * 4
)
for i, raw in enumerate(raw_snrs)
]
hops = parse_trace_hops(payload)
return TraceResult(
target=target,
success=True,
hops=hops,
round_trip_ms=elapsed_ms,
tx_power=await self.get_tx_power(),
path_hash_bytes=hash_bytes,
raw=payload,
)
async def _trace_path_to_contact(
self, mc, target: str
) -> Optional[tuple[bytes, int]]: # noqa: ANN001
"""Resolve a target contact into a trace ``(path_bytes, flags)``.
A trace reply only comes back when the *destination's own hash* is the final
hop in the path — an empty/destination-less path is silently dropped (verified
on hardware: a direct neighbor answers a single-hop trace to its own hash but
not a path-less one). So we always end the path at the contact's key prefix,
prepending any learned repeater hops (``out_path``) ahead of it:
* direct neighbor / no learned route → just ``[destination]``;
* learned multi-hop route → ``[repeater…, destination]``.
Each hash is re-encoded at the trace's own width (``1 << flags``, only 1/2/4/8
bytes), collapsing a region's routing width (e.g. 3) to the widest representable
value (2). The firmware matches by hash prefix, so a narrower prefix still
addresses the same node.
Args:
mc: The connected ``MeshCore`` client.
target: Contact name (case-insensitive) or public-key prefix.
Returns:
``(path_bytes, flags)`` to walk, or ``None`` only when the contact is
unknown or carries no public key to address.
"""
from ..services.trace_runner import path_hash_flags
payload = await self._contacts_payload(mc)
needle = target.casefold()
for name, info in payload.items():
info = info or {}
adv = info.get("adv_name", name)
pub = (info.get("public_key", "") or "").lower().removeprefix("0x")
if adv.casefold() != needle and not pub.startswith(needle):
continue
if not pub:
return None # no key to address the trace's destination hop
# Routing hash width (bytes): the contact's stored mode, or — when it has
# no learned route (mode == -1) — our region's mode.
mode = int(info.get("out_path_hash_mode", -1))
if mode < 0:
try:
mode = int(await mc.commands.get_path_hash_mode())
except Exception:
mode = 2 # region default: 3-byte hashes
size = max(mode + 1, 1)
trace_size = max(s for s in (1, 2, 4, 8) if s <= size)
hops: list[bytes] = []
out_path = (info.get("out_path") or "").strip().lower().removeprefix("0x")
out_path_len = int(info.get("out_path_len", -1))
if 1 <= out_path_len <= 254 and out_path:
# Learned multi-hop route: walk each repeater, collapsed to trace width.
route = bytes.fromhex(out_path)[: out_path_len * size]
hops += [route[i * size : i * size + trace_size] for i in range(out_path_len)]
# Always finish at the destination's own hash so the target recognizes the
# trace and replies; for a direct neighbor this single hop is the whole path.
hops.append(bytes.fromhex(pub)[:trace_size])
return b"".join(hops), path_hash_flags(trace_size) or 0
return None
@staticmethod
def _ok(event): # type: ignore[no-untyped-def]
"""Return ``event`` if it succeeded, else raise its error payload.
Args:
event: The :class:`meshcore.events.Event` returned by a command.
Returns:
The same event, for convenient chaining.
Raises:
RuntimeError: If the device reported an error.
"""
if event is not None and getattr(event, "is_error", lambda: False)():
raise RuntimeError(f"device rejected command: {getattr(event, 'payload', {})}")
return event
async def get_tuning(self) -> dict: # noqa: D102 - inherited docstring
event = self._ok(await self._require().commands.get_tuning())
payload = getattr(event, "payload", {}) or {}
return {
"rx_delay": int(payload.get("rx_delay", 0)),
"airtime_factor": int(payload.get("airtime_factor", 0)),
}
async def get_path_hash_mode(self) -> int: # noqa: D102 - inherited docstring
return int(await self._require().commands.get_path_hash_mode())
async def get_custom_vars(self) -> dict[str, str]: # noqa: D102 - inherited docstring
event = self._ok(await self._require().commands.get_custom_vars())
return dict(getattr(event, "payload", {}) or {})
async def get_channel(self, index: int) -> Optional[dict]: # noqa: D102
event = self._ok(await self._require().commands.get_channel(index))
payload = getattr(event, "payload", {}) or {}
if not payload.get("channel_name"):
return None
return payload
async def set_name(self, name: str) -> None: # noqa: D102 - inherited docstring
self._ok(await self._require().commands.set_name(name))
async def set_coords(self, lat: float, lon: float) -> None: # noqa: D102
self._ok(await self._require().commands.set_coords(lat, lon))
async def set_device_pin(self, pin: int) -> None: # noqa: D102 - inherited docstring
self._ok(await self._require().commands.set_devicepin(pin))
async def set_radio(self, freq: float, bw: float, sf: int, cr: int) -> None: # noqa: D102
self._ok(await self._require().commands.set_radio(freq, bw, sf, cr))
async def set_tuning(self, rx_delay: int, airtime_factor: int) -> None: # noqa: D102
self._ok(await self._require().commands.set_tuning(rx_delay, airtime_factor))
async def set_manual_add_contacts(self, enabled: bool) -> None: # noqa: D102
self._ok(await self._require().commands.set_manual_add_contacts(enabled))
async def set_adv_loc_policy(self, policy: int) -> None: # noqa: D102
self._ok(await self._require().commands.set_advert_loc_policy(policy))
async def set_multi_acks(self, value: int) -> None: # noqa: D102 - inherited docstring
self._ok(await self._require().commands.set_multi_acks(value))
async def set_telemetry_modes(self, base: int, loc: int, env: int) -> None: # noqa: D102
mc = self._require()
result = self._ok(await mc.commands.send_appstart())
infos = dict(getattr(result, "payload", {}) or {})
infos["telemetry_mode_base"] = base
infos["telemetry_mode_loc"] = loc
infos["telemetry_mode_env"] = env
self._ok(await mc.commands.set_other_params_from_infos(infos))
async def set_path_hash_mode(self, mode: int) -> None: # noqa: D102
self._ok(await self._require().commands.set_path_hash_mode(mode))
async def set_custom_var(self, key: str, value: str) -> None: # noqa: D102
self._ok(await self._require().commands.set_custom_var(key, value))
async def set_channel(self, index: int, name: str, secret: Optional[bytes]) -> None: # noqa: D102
self._ok(await self._require().commands.set_channel(index, name, secret))
async def set_time(self, epoch: int) -> None: # noqa: D102 - inherited docstring
self._ok(await self._require().commands.set_time(epoch))
async def send_advert(self, flood: bool = False) -> None: # noqa: D102
self._ok(await self._require().commands.send_advert(flood))
async def reboot(self) -> None: # noqa: D102 - inherited docstring
await self._require().commands.reboot() # device reboots; no OK reply expected
async def export_private_key(self) -> str: # noqa: D102 - inherited docstring
event = self._ok(await self._require().commands.export_private_key())
payload = getattr(event, "payload", {}) or {}
key = payload.get("private_key")
if key is None:
raise RuntimeError("device did not return a private key (export may be disabled)")
return key.hex() if isinstance(key, (bytes, bytearray)) else str(key)
async def import_private_key(self, key_hex: str) -> None: # noqa: D102
self._ok(await self._require().commands.import_private_key(bytes.fromhex(key_hex)))
async def factory_reset(self) -> None: # noqa: D102 - inherited docstring
mc = self._require()
token = await mc.commands.request_factory_reset()
self._ok(await mc.commands.confirm_factory_reset(token))
class MockDevice(Device):
"""A deterministic simulator implementing the full :class:`Device` interface.
@@ -247,6 +597,33 @@ class MockDevice(Device):
Contact(name="Observer-Bot", key_prefix="c3d4e5f6"),
Contact(name="Alice", key_prefix="d4e5f6a7"),
]
# Mutable configuration state, keyed exactly like the real SELF_INFO payload so the
# settings registry behaves identically on the simulator and on hardware.
self._info: dict = {
"name": "MockCompanion",
"adv_type": 1,
"max_tx_power": 22,
"public_key": "00" * 32,
"adv_lat": 0.0,
"adv_lon": 0.0,
"multi_acks": 0,
"adv_loc_policy": 0,
"telemetry_mode_base": 0,
"telemetry_mode_loc": 0,
"telemetry_mode_env": 0,
"manual_add_contacts": False,
"radio_freq": 869.525,
"radio_bw": 250.0,
"radio_sf": 11,
"radio_cr": 5,
"simulated": True,
}
self._tuning: dict = {"rx_delay": 0, "airtime_factor": 0}
self._path_hash_mode = 0
self._custom_vars: dict[str, str] = {}
self._channels: dict[int, dict] = {}
self._device_pin = 0
self._private_key = "11" * 32
async def connect(self) -> None: # noqa: D102 - inherited docstring
await asyncio.sleep(0)
@@ -256,15 +633,7 @@ class MockDevice(Device):
self._connected = False
async def get_self_info(self) -> dict: # noqa: D102 - inherited docstring
return {
"name": "MockCompanion",
"tx_power": self._tx_power,
"freq": 869.525,
"bw": 250,
"sf": 11,
"cr": 5,
"simulated": True,
}
return {**self._info, "tx_power": self._tx_power}
async def get_contacts(self) -> list[Contact]: # noqa: D102 - inherited docstring
return list(self._contacts)
@@ -275,6 +644,80 @@ class MockDevice(Device):
async def set_tx_power(self, value: int) -> None: # noqa: D102 - inherited docstring
self._tx_power = value
async def get_tuning(self) -> dict: # noqa: D102 - inherited docstring
return dict(self._tuning)
async def get_path_hash_mode(self) -> int: # noqa: D102 - inherited docstring
return self._path_hash_mode
async def get_custom_vars(self) -> dict[str, str]: # noqa: D102 - inherited docstring
return dict(self._custom_vars)
async def get_channel(self, index: int) -> Optional[dict]: # noqa: D102
return self._channels.get(index)
async def set_name(self, name: str) -> None: # noqa: D102 - inherited docstring
self._info["name"] = name
async def set_coords(self, lat: float, lon: float) -> None: # noqa: D102
self._info["adv_lat"] = lat
self._info["adv_lon"] = lon
async def set_device_pin(self, pin: int) -> None: # noqa: D102 - inherited docstring
self._device_pin = pin
async def set_radio(self, freq: float, bw: float, sf: int, cr: int) -> None: # noqa: D102
self._info.update(radio_freq=freq, radio_bw=bw, radio_sf=sf, radio_cr=cr)
async def set_tuning(self, rx_delay: int, airtime_factor: int) -> None: # noqa: D102
self._tuning = {"rx_delay": rx_delay, "airtime_factor": airtime_factor}
async def set_manual_add_contacts(self, enabled: bool) -> None: # noqa: D102
self._info["manual_add_contacts"] = enabled
async def set_adv_loc_policy(self, policy: int) -> None: # noqa: D102
self._info["adv_loc_policy"] = policy
async def set_multi_acks(self, value: int) -> None: # noqa: D102 - inherited docstring
self._info["multi_acks"] = value
async def set_telemetry_modes(self, base: int, loc: int, env: int) -> None: # noqa: D102
self._info.update(
telemetry_mode_base=base, telemetry_mode_loc=loc, telemetry_mode_env=env
)
async def set_path_hash_mode(self, mode: int) -> None: # noqa: D102
self._path_hash_mode = mode
async def set_custom_var(self, key: str, value: str) -> None: # noqa: D102
self._custom_vars[key] = value
async def set_channel(self, index: int, name: str, secret: Optional[bytes]) -> None: # noqa: D102
self._channels[index] = {
"channel_idx": index,
"channel_name": name,
"channel_secret": secret or (b"\x00" * 16),
}
async def set_time(self, epoch: int) -> None: # noqa: D102 - inherited docstring
self._info["clock"] = epoch
async def send_advert(self, flood: bool = False) -> None: # noqa: D102
await asyncio.sleep(0)
async def reboot(self) -> None: # noqa: D102 - inherited docstring
await asyncio.sleep(0)
async def export_private_key(self) -> str: # noqa: D102 - inherited docstring
return self._private_key
async def import_private_key(self, key_hex: str) -> None: # noqa: D102
self._private_key = bytes.fromhex(key_hex).hex() # validates hex, normalizes
async def factory_reset(self) -> None: # noqa: D102 - inherited docstring
self._custom_vars.clear()
self._channels.clear()
def _expected_snr(self, hop_index: int) -> float:
"""Model SNR for a hop as an inverted-U in TX power plus distance falloff.
@@ -294,29 +737,61 @@ class MockDevice(Device):
self,
target: str,
*,
path: Optional[list[str]] = None,
path: Optional[str] = None,
timeout: float = 10.0,
) -> TraceResult:
await asyncio.sleep(0.05) # mimic radio latency so progress bars are visible
depth = len(path) if path else self._rng.randint(1, 3)
forced = [h for h in path.split(",") if h.strip()] if path else None
# Mirror the real device: the path-hash width is the byte length of a forced hop.
hash_bytes = len(bytes.fromhex(forced[0])) if forced else None
depth = len(forced) if forced else self._rng.randint(1, 3)
hops: list[Hop] = []
for i in range(depth):
expected = self._expected_snr(i)
snr = expected + self._rng.gauss(0, 1.2) # measurement noise
node = path[i] if path else f"hop{i}"
node = forced[i] if forced else f"hop{i}"
hops.append(Hop(index=i, node=node, snr=round(snr, 1)))
# Very weak links occasionally drop entirely.
# Very weak links occasionally drop entirely (judged on the repeater hops).
success = (hops[-1].snr if hops else -99) > -12 or self._rng.random() > 0.1
# The trace reply returns to us: firmware appends the local device as a final
# hash-less hop (``node=None``). Mirror that so the origin/destination framing
# naturally has our device at both ends of the path. The return link is modeled
# as symmetric to the first outbound hop, so it never alters the bottleneck SNR.
if hops:
hops.append(Hop(index=depth, node=None, snr=hops[0].snr))
return TraceResult(
target=target,
success=success,
hops=hops if success else [],
round_trip_ms=round(self._rng.uniform(120, 480), 1) if success else None,
tx_power=self._tx_power,
path_hash_bytes=hash_bytes,
)
def parse_trace_hops(payload: dict) -> list[Hop]:
"""Extract per-hop SNR from a ``TRACE_DATA`` event payload.
meshcore parses a trace reply into ``payload["path"]`` — a list of nodes, each a
dict with a repeater ``"hash"`` and its ``"snr"`` (already in dB, signed-byte / 4).
The final node is the local device and carries an ``"snr"`` but no ``"hash"``.
Args:
payload: The ``TRACE_DATA`` event payload.
Returns:
The hops in path order; nodes without an SNR reading are skipped.
"""
hops: list[Hop] = []
for node in payload.get("path") or []:
if not isinstance(node, dict) or node.get("snr") is None:
continue
hops.append(Hop(index=len(hops), node=node.get("hash"), snr=float(node["snr"])))
return hops
def clamp_tx_power(value: int) -> int:
"""Clamp a TX power value to the supported range.
+419
View File
@@ -0,0 +1,419 @@
"""Declarative registry of every settable device configuration value.
Each :class:`SettingSpec` describes one tunable setting: how to read its current value
from a device snapshot, how to parse/validate/format it, and how to apply it back to the
:class:`~meshtools.core.connection.Device`. The same registry drives the interactive
editor, the ``config`` CLI subcommands, and TOML backup/restore — add a setting once and
it appears everywhere, mirroring the tool registry pattern.
Settings whose protocol command takes several fields at once (radio, coordinates, tuning,
telemetry modes) rebuild the full command from the current snapshot plus the one changed
field, so a single setting can be edited in isolation.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Optional
from .connection import Device
# Display categories, in the order the editor and `config show` present them.
CATEGORIES = ("Identity", "Radio", "Tuning", "Behavior", "Experimental")
class DeviceConfigError(ValueError):
"""Raised when a value cannot be parsed or fails validation.
The message is user-facing (printed directly by the CLI and editor).
"""
@dataclass(slots=True)
class SettingSpec:
"""Specification for one settable configuration value.
Attributes:
key: Canonical key (matches the ``SELF_INFO`` field name where one exists).
label: Human-friendly name for display.
help: One-line description.
category: One of :data:`CATEGORIES`.
value_type: ``"str" | "int" | "float" | "bool" | "enum"``.
choices: For ``enum``, a mapping of allowed int value to label.
minimum: Inclusive lower bound for numeric types, if any.
maximum: Inclusive upper bound for numeric types, if any.
strict_choices: When ``True`` (the default) an ``enum`` value must be one of
:attr:`choices`. When ``False`` the choices are offered as a convenience menu
but any in-range integer is still accepted — used for firmware fields whose
full value domain we don't enumerate exhaustively.
getter: Extracts the current value from a snapshot dict.
apply: Coroutine applying a parsed value to a device, given the snapshot.
"""
key: str
label: str
help: str
category: str
value_type: str
getter: Callable[[dict], Any]
apply: Callable[[Device, Any, dict], Awaitable[None]]
choices: Optional[dict[int, str]] = None
minimum: Optional[float] = None
maximum: Optional[float] = None
strict_choices: bool = True
# --- value parsing / formatting ----------------------------------------------
_TRUE = {"1", "true", "yes", "on", "y"}
_FALSE = {"0", "false", "no", "off", "n"}
def parse_value(spec: SettingSpec, raw: Any) -> Any:
"""Parse and validate a raw value (typically a CLI/TOML string) for ``spec``.
Args:
spec: The target setting.
raw: The raw value to coerce (string or already-typed scalar).
Returns:
The typed, range-checked value ready for :meth:`SettingSpec.apply`.
Raises:
DeviceConfigError: If the value is the wrong type or out of range.
"""
text = str(raw).strip()
if spec.value_type == "str":
return text
if spec.value_type == "bool":
low = text.lower()
if low in _TRUE:
return True
if low in _FALSE:
return False
raise DeviceConfigError(f"{spec.key}: expected a boolean, got {raw!r}")
# Numeric (int / enum / float): wrap only the conversion, so a DeviceConfigError
# raised by the range/enum checks below is not caught and rewrapped here.
try:
if spec.value_type == "float":
value: Any = float(text)
else: # int or enum
value = int(text, 0) if isinstance(raw, str) else int(raw)
except (ValueError, TypeError) as exc:
raise DeviceConfigError(f"{spec.key}: invalid {spec.value_type} value {raw!r}") from exc
if (
spec.value_type == "enum"
and spec.strict_choices
and spec.choices is not None
and value not in spec.choices
):
allowed = ", ".join(str(k) for k in spec.choices)
raise DeviceConfigError(f"{spec.key}: must be one of {allowed}, got {value}")
if spec.minimum is not None and value < spec.minimum:
raise DeviceConfigError(f"{spec.key}: must be >= {spec.minimum}, got {value}")
if spec.maximum is not None and value > spec.maximum:
raise DeviceConfigError(f"{spec.key}: must be <= {spec.maximum}, got {value}")
return value
def format_value(spec: SettingSpec, value: Any) -> str:
"""Render a value for display.
Args:
spec: The setting the value belongs to.
value: The current value (may be ``None`` if unknown).
Returns:
A human-readable string.
"""
if value is None:
return "?"
if spec.value_type == "bool":
return "true" if value else "false"
if spec.value_type == "enum" and spec.choices is not None and value in spec.choices:
return f"{value} ({spec.choices[value]})"
return str(value)
# --- snapshot ----------------------------------------------------------------
async def build_snapshot(device: Device) -> dict:
"""Read a device's full current configuration into one dict.
Merges ``SELF_INFO`` with the separately-read tuning parameters and path-hash mode.
Optional reads that a given firmware does not support are skipped silently so the rest
of the snapshot still renders.
Args:
device: A connected device.
Returns:
A dict keyed like ``SELF_INFO`` plus ``rx_delay``, ``airtime_factor`` and
``path_hash_mode``.
"""
snapshot = dict(await device.get_self_info())
try:
snapshot.update(await device.get_tuning())
except Exception: # noqa: BLE001 - optional read; absence is acceptable
pass
try:
snapshot["path_hash_mode"] = await device.get_path_hash_mode()
except Exception: # noqa: BLE001 - optional read; absence is acceptable
pass
return snapshot
# --- coupled-command apply helpers -------------------------------------------
def _radio_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[None]]:
"""Build an apply that updates one radio field, preserving the others."""
async def apply(device: Device, value: Any, snapshot: dict) -> None:
params = {
"freq": snapshot.get("radio_freq"),
"bw": snapshot.get("radio_bw"),
"sf": snapshot.get("radio_sf"),
"cr": snapshot.get("radio_cr"),
}
params[field_name] = value
await device.set_radio(params["freq"], params["bw"], params["sf"], params["cr"])
return apply
def _coords_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[None]]:
"""Build an apply that updates one coordinate, preserving the other."""
async def apply(device: Device, value: Any, snapshot: dict) -> None:
lat = value if field_name == "adv_lat" else snapshot.get("adv_lat", 0.0)
lon = value if field_name == "adv_lon" else snapshot.get("adv_lon", 0.0)
await device.set_coords(float(lat or 0.0), float(lon or 0.0))
return apply
def _tuning_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[None]]:
"""Build an apply that updates one tuning field, preserving the other."""
async def apply(device: Device, value: Any, snapshot: dict) -> None:
rx = value if field_name == "rx_delay" else snapshot.get("rx_delay", 0)
af = value if field_name == "airtime_factor" else snapshot.get("airtime_factor", 0)
await device.set_tuning(int(rx or 0), int(af or 0))
return apply
def _telemetry_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[None]]:
"""Build an apply that updates one telemetry mode, preserving the others."""
async def apply(device: Device, value: Any, snapshot: dict) -> None:
base = value if field_name == "telemetry_mode_base" else snapshot.get("telemetry_mode_base", 0)
loc = value if field_name == "telemetry_mode_loc" else snapshot.get("telemetry_mode_loc", 0)
env = value if field_name == "telemetry_mode_env" else snapshot.get("telemetry_mode_env", 0)
await device.set_telemetry_modes(int(base or 0), int(loc or 0), int(env or 0))
return apply
def _get(key: str) -> Callable[[dict], Any]:
"""Build a getter that reads ``key`` from a snapshot."""
return lambda snapshot: snapshot.get(key)
_TELEMETRY_CHOICES = {0: "off", 1: "always", 2: "device-only", 3: "all"}
# adv_loc_policy / multi_acks are single firmware bytes; we list the values seen in the
# wild but keep them non-strict so an unfamiliar value is still accepted.
_ADV_LOC_CHOICES = {0: "don't share location", 1: "share location in adverts"}
_MULTI_ACKS_CHOICES = {0: "off", 1: "on"}
# path_hash_mode is a 2-bit field; the hash size carried per hop is mode + 1 bytes.
_PATH_HASH_CHOICES = {
0: "1-byte hashes (default)",
1: "2-byte hashes",
2: "3-byte hashes",
3: "4-byte hashes",
}
def _telemetry_spec(key: str, label: str) -> SettingSpec:
"""Build a telemetry-mode setting spec (shared shape for base/loc/env)."""
return SettingSpec(
key=key, label=label, help="Telemetry reporting mode.", category="Behavior",
value_type="enum", choices=_TELEMETRY_CHOICES, minimum=0, maximum=3,
getter=_get(key), apply=_telemetry_apply(key),
)
# --- radio presets -----------------------------------------------------------
@dataclass(frozen=True, slots=True)
class RadioPreset:
"""A named, standard set of radio parameters applied as one unit.
Attributes:
name: Human-friendly preset name (region or trade-off).
help: One-line description of when to use it.
freq: Carrier frequency in MHz.
bw: Channel bandwidth in kHz.
sf: LoRa spreading factor.
cr: LoRa coding-rate denominator (5-8 = 4/5-4/8).
"""
name: str
help: str
freq: float
bw: float
sf: int
cr: int
def as_settings(self) -> dict[str, Any]:
"""Return this preset as a ``{setting_key: value}`` mapping for staging."""
return {
"radio_freq": self.freq,
"radio_bw": self.bw,
"radio_sf": self.sf,
"radio_cr": self.cr,
}
# Standard MeshCore presets. The default modulation (250 kHz / SF11 / CR5) is shared
# across regions; the region presets differ only in the default channel frequency. The
# trade-off presets keep the EU frequency but trade airtime for range or speed.
RADIO_PRESETS: list[RadioPreset] = [
RadioPreset("EU / UK 868", "MeshCore default for the 868 MHz band.", 869.525, 250.0, 11, 5),
RadioPreset("US 915", "MeshCore default for the US 915 MHz band.", 910.525, 250.0, 11, 5),
RadioPreset("AU / NZ 915", "MeshCore default for the AU/NZ 915 MHz band.", 915.525, 250.0, 11, 5),
RadioPreset("Long range (slow)", "Narrow bandwidth + high SF: max range, low data rate.", 869.525, 125.0, 12, 8),
RadioPreset("Fast (short range)", "Wide bandwidth + low SF: short range, low airtime.", 869.525, 500.0, 7, 5),
]
# --- the registry ------------------------------------------------------------
DEVICE_SETTINGS: list[SettingSpec] = [
# Identity
SettingSpec(
"name", "Node name", "Advertised name of this node.", "Identity", "str",
getter=_get("name"), apply=lambda d, v, s: d.set_name(v),
),
SettingSpec(
"adv_lat", "Latitude", "Advertised latitude (decimal degrees).", "Identity",
"float", minimum=-90.0, maximum=90.0,
getter=_get("adv_lat"), apply=_coords_apply("adv_lat"),
),
SettingSpec(
"adv_lon", "Longitude", "Advertised longitude (decimal degrees).", "Identity",
"float", minimum=-180.0, maximum=180.0,
getter=_get("adv_lon"), apply=_coords_apply("adv_lon"),
),
SettingSpec(
"device_pin", "Device PIN", "BLE pairing PIN.", "Identity", "int",
minimum=0, maximum=999999,
getter=_get("device_pin"), apply=lambda d, v, s: d.set_device_pin(v),
),
# Radio
SettingSpec(
"radio_freq", "Frequency (MHz)", "Carrier frequency in MHz.", "Radio", "float",
minimum=100.0, maximum=1000.0,
getter=_get("radio_freq"), apply=_radio_apply("freq"),
),
SettingSpec(
"radio_bw", "Bandwidth (kHz)", "Channel bandwidth in kHz.", "Radio", "float",
minimum=1.0, maximum=1000.0,
getter=_get("radio_bw"), apply=_radio_apply("bw"),
),
SettingSpec(
"radio_sf", "Spreading factor", "LoRa spreading factor.", "Radio", "int",
minimum=5, maximum=12,
getter=_get("radio_sf"), apply=_radio_apply("sf"),
),
SettingSpec(
"radio_cr", "Coding rate", "LoRa coding-rate denominator (5-8 = 4/5-4/8).",
"Radio", "int", minimum=5, maximum=8,
getter=_get("radio_cr"), apply=_radio_apply("cr"),
),
SettingSpec(
"tx_power", "TX power (dBm)", "Transmit power.", "Radio", "int",
minimum=1, maximum=22,
getter=_get("tx_power"), apply=lambda d, v, s: d.set_tx_power(v),
),
# Tuning
SettingSpec(
"rx_delay", "RX delay", "Receive delay tuning parameter.", "Tuning", "int",
minimum=0,
getter=_get("rx_delay"), apply=_tuning_apply("rx_delay"),
),
SettingSpec(
"airtime_factor", "Airtime factor", "Airtime budgeting factor.", "Tuning", "int",
minimum=0,
getter=_get("airtime_factor"), apply=_tuning_apply("airtime_factor"),
),
# Behavior
SettingSpec(
"manual_add_contacts", "Manual add contacts",
"Require contacts to be added manually.", "Behavior", "bool",
getter=_get("manual_add_contacts"),
apply=lambda d, v, s: d.set_manual_add_contacts(v),
),
SettingSpec(
"adv_loc_policy", "Advert location policy",
"Whether this node shares its location in adverts.", "Behavior", "enum",
choices=_ADV_LOC_CHOICES, minimum=0, strict_choices=False,
getter=_get("adv_loc_policy"), apply=lambda d, v, s: d.set_adv_loc_policy(v),
),
SettingSpec(
"multi_acks", "Multi-acks",
"Send multiple acknowledgements for added delivery reliability.", "Behavior",
"enum", choices=_MULTI_ACKS_CHOICES, minimum=0, strict_choices=False,
getter=_get("multi_acks"), apply=lambda d, v, s: d.set_multi_acks(v),
),
_telemetry_spec("telemetry_mode_base", "Telemetry mode (base)"),
_telemetry_spec("telemetry_mode_loc", "Telemetry mode (location)"),
_telemetry_spec("telemetry_mode_env", "Telemetry mode (environment)"),
# Experimental
SettingSpec(
"path_hash_mode", "Path-hash mode",
"Per-hop path-hash size; larger resists hash collisions but adds packet overhead.",
"Experimental", "enum", choices=_PATH_HASH_CHOICES, minimum=0, maximum=3,
getter=_get("path_hash_mode"), apply=lambda d, v, s: d.set_path_hash_mode(v),
),
]
_BY_KEY: dict[str, SettingSpec] = {s.key: s for s in DEVICE_SETTINGS}
def get_spec(key: str) -> SettingSpec:
"""Return the spec for ``key``.
Args:
key: A setting key.
Returns:
The matching :class:`SettingSpec`.
Raises:
DeviceConfigError: If no such setting exists.
"""
spec = _BY_KEY.get(key)
if spec is None:
known = ", ".join(sorted(_BY_KEY))
raise DeviceConfigError(f"unknown setting {key!r}. Known settings: {known}")
return spec
def settings_by_category() -> list[tuple[str, list[SettingSpec]]]:
"""Return settings grouped by category in display order.
Returns:
A list of ``(category, specs)`` pairs following :data:`CATEGORIES` order.
"""
return [
(cat, [s for s in DEVICE_SETTINGS if s.category == cat])
for cat in CATEGORIES
]
+113
View File
@@ -7,10 +7,14 @@ real device, the simulator, or rehydrated from the database identically.
from __future__ import annotations
import statistics
from collections import Counter
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional
#: Label used for our own (local) device when framing a trace path's endpoints.
LOCAL_DEVICE_LABEL = "us"
def utcnow() -> datetime:
"""Return a timezone-aware UTC timestamp.
@@ -63,6 +67,8 @@ class TraceResult:
hops: Per-hop SNR readings, ordered from source to destination.
round_trip_ms: Round-trip time of the trace in milliseconds, if measured.
tx_power: TX power level in effect when the trace ran, if known.
path_hash_bytes: Per-hop path-hash width (bytes) used by the trace command, so
node hashes can be displayed at the same width the command addressed them.
timestamp: When the trace completed.
raw: Optional raw event payload for debugging/replay.
"""
@@ -72,6 +78,7 @@ class TraceResult:
hops: list[Hop] = field(default_factory=list)
round_trip_ms: Optional[float] = None
tx_power: Optional[int] = None
path_hash_bytes: Optional[int] = None
timestamp: datetime = field(default_factory=utcnow)
raw: Optional[dict] = None
@@ -95,6 +102,67 @@ class TraceResult:
nodes = [h.node or f"hop{h.index}" for h in self.hops]
return " -> ".join(nodes)
def edges(self, device_label: str = LOCAL_DEVICE_LABEL) -> list["HopEdge"]:
"""Frame the per-hop SNR as directed ``origin -> destination`` edges.
Each hop's SNR is the signal measured arriving at that node, so an edge runs
from the previous node to this one. The first edge therefore originates at our
own device, and (because firmware records the reply returning to us as a final
hash-less hop) the last edge's destination is our device too.
Args:
device_label: Name to show for our own device at the path's endpoints.
Returns:
One :class:`HopEdge` per hop, in path order.
"""
edges: list[HopEdge] = []
origin = device_label
for hop in self.hops:
destination = hop.node or device_label
edges.append(HopEdge(index=hop.index, origin=origin, destination=destination, snr=hop.snr))
origin = destination
return edges
@dataclass(slots=True)
class HopEdge:
"""A directed link in a trace path: a hop framed as ``origin -> destination``.
Attributes:
index: Zero-based position of the hop along the path.
origin: Identifier of the transmitting node (our device for the first edge).
destination: Identifier of the receiving node (our device for the last edge).
snr: Signal-to-noise ratio in dB measured at ``destination``.
"""
index: int
origin: str
destination: str
snr: float
@dataclass(slots=True)
class HopAggregate:
"""Median SNR for one hop position aggregated across several traces.
``origin`` and ``destination`` hold raw node identifiers; ``None`` means our own
device, so the display label can be applied at render time.
Attributes:
index: Zero-based hop position along the path.
origin: Representative transmitting node at this position (``None`` = us).
destination: Representative receiving node at this position (``None`` = us).
median_snr: Median SNR in dB measured at ``destination`` across the samples.
samples: Number of traces that reported this hop.
"""
index: int
origin: Optional[str]
destination: Optional[str]
median_snr: float
samples: int
@dataclass(slots=True)
class TraceStats:
@@ -110,6 +178,7 @@ class TraceStats:
median_min_snr: Median of each trace's bottleneck SNR, the headline metric.
median_rtt_ms: Median round-trip time, if measured.
tx_power: TX power level in effect for these samples, if fixed.
hop_snrs: Per-hop median SNR across the successful traces, in path order.
"""
target: str
@@ -118,6 +187,7 @@ class TraceStats:
median_min_snr: Optional[float]
median_rtt_ms: Optional[float]
tx_power: Optional[int] = None
hop_snrs: list[HopAggregate] = field(default_factory=list)
@property
def success_rate(self) -> float:
@@ -146,8 +216,51 @@ class TraceStats:
median_min_snr=statistics.median(min_snrs) if min_snrs else None,
median_rtt_ms=statistics.median(rtts) if rtts else None,
tx_power=next(iter(tx_powers)) if len(tx_powers) == 1 else None,
hop_snrs=cls._aggregate_hops(successes),
)
@staticmethod
def _aggregate_hops(successes: list["TraceResult"]) -> list[HopAggregate]:
"""Compute the median SNR per hop position across successful traces.
Hops are grouped by their path position; for each position the SNR median is
taken and the most common origin/destination nodes are used so the aggregate
path reads like a single representative trace. Node identities are kept raw
(``None`` = our device) so a display label can be applied later.
Args:
successes: The successful traces to aggregate.
Returns:
One :class:`HopAggregate` per hop position, ordered along the path.
"""
snrs_by_index: dict[int, list[float]] = {}
origins_by_index: dict[int, list[Optional[str]]] = {}
dests_by_index: dict[int, list[Optional[str]]] = {}
for trace in successes:
origin: Optional[str] = None # the first hop originates at our device
for hop in trace.hops:
snrs_by_index.setdefault(hop.index, []).append(hop.snr)
origins_by_index.setdefault(hop.index, []).append(origin)
dests_by_index.setdefault(hop.index, []).append(hop.node)
origin = hop.node
aggregates: list[HopAggregate] = []
for index in sorted(snrs_by_index):
snrs = snrs_by_index[index]
origin = Counter(origins_by_index[index]).most_common(1)[0][0]
destination = Counter(dests_by_index[index]).most_common(1)[0][0]
aggregates.append(
HopAggregate(
index=index,
origin=origin,
destination=destination,
median_snr=statistics.median(snrs),
samples=len(snrs),
)
)
return aggregates
@dataclass(slots=True)
class TxLevelResult: