diff --git a/meshterm/core/config_io.py b/meshterm/core/config_io.py index 2ee5dda..cde6f27 100644 --- a/meshterm/core/config_io.py +++ b/meshterm/core/config_io.py @@ -129,7 +129,7 @@ def plan_restore( ops: list[tuple] = [] for key, raw in backup.settings.items(): spec = get_spec(key) # raises on unknown key - value = parse_value(spec, raw) + value = parse_value(spec, raw, snapshot) if value != spec.getter(snapshot): ops.append(("set", key, value)) diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 6662081..24a1689 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -433,7 +433,51 @@ class Device(ABC): """Return radio tuning parameters. Returns: - A dict with ``rx_delay`` and ``airtime_factor`` (both ints). + A dict with ``rx_delay`` and ``airtime_factor`` (both ints). The TX delay + factors are write-only in the companion protocol (the firmware's tuning + response carries only these two fields), so they are absent here on real + hardware; the simulator includes them for a fuller editing experience. + """ + + @abstractmethod + async def get_autoadd_config(self) -> Optional[int]: + """Return the contact auto-add bitmask, or ``None`` if the firmware predates it. + + The finer-grained sibling of :meth:`set_manual_add_contacts`: a bitmask of which + advert types the firmware adds to contacts automatically. + """ + + @abstractmethod + async def get_default_flood_scope(self) -> Optional[str]: + """Return the persisted default flood scope's name (``""`` when unset). + + Returns: + The ``#scope`` name limiting flood routing, an empty string when no scope is + configured, or ``None`` if the firmware predates flood scopes. + """ + + @abstractmethod + async def get_time(self) -> Optional[int]: + """Return the device clock as a UNIX epoch timestamp, or ``None`` if unknown.""" + + @abstractmethod + async def get_battery(self) -> dict: + """Return battery (and, when reported, storage) status. + + Returns: + A dict with ``level`` (millivolts) and, on firmware that reports storage, + ``used_kb``/``total_kb``. Empty when the read is unsupported. + """ + + @abstractmethod + async def get_stats(self) -> dict: + """Return the firmware's core/radio/packet statistics, merged into one dict. + + Each of the three stats frames is fetched best-effort — firmware predating one + simply contributes nothing — so callers get whatever subset exists: ``battery_mv``, + ``uptime_secs``, ``errors``, ``queue_len`` (core); ``noise_floor``, ``last_rssi``, + ``last_snr``, ``tx_air_secs``, ``rx_air_secs`` (radio); ``recv``, ``sent``, + ``flood_tx``, ``direct_tx``, ``flood_rx``, ``direct_rx``, ``recv_errors`` (packets). """ @abstractmethod @@ -506,8 +550,22 @@ class Device(ABC): """ @abstractmethod - async def set_tuning(self, rx_delay: int, airtime_factor: int) -> None: - """Set radio tuning parameters (RX delay and airtime budgeting factor).""" + async def set_tuning( + self, + rx_delay: int, + airtime_factor: int, + tx_delay_factor: int = 0, + direct_tx_delay_factor: int = 0, + ) -> None: + """Set radio tuning parameters. + + The firmware takes all four fields in one command, so a caller changing one must + resend the others. The two TX delay factors (single bytes: the random extra delay + before relayed transmissions, and the delay before direct/zero-hop ones) cannot be + read back from real hardware — see :meth:`get_tuning` — so an unknown current + value defaults to ``0``, which is also what the underlying library always sent + before these were exposed. + """ @abstractmethod async def set_manual_add_contacts(self, enabled: bool) -> None: @@ -525,6 +583,18 @@ class Device(ABC): 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_autoadd_config(self, flags: int) -> None: + """Set the contact auto-add bitmask (see :meth:`get_autoadd_config`).""" + + @abstractmethod + async def set_default_flood_scope(self, scope: str) -> None: + """Persist the default flood scope by name (empty string clears it). + + A missing leading ``#`` is added by the transport layer, matching how scope names + are hashed into their 16-byte keys. + """ + @abstractmethod async def set_path_hash_mode(self, mode: int) -> None: """Set the experimental path-hash routing mode.""" @@ -1509,6 +1579,45 @@ class MeshCoreDevice(Device): "airtime_factor": int(payload.get("airtime_factor", 0)), } + async def get_autoadd_config(self) -> Optional[int]: # noqa: D102 - inherited docstring + event = self._ok(await self._require().commands.get_autoadd_config()) + payload = getattr(event, "payload", {}) or {} + config = payload.get("config") + return None if config is None else int(config) + + async def get_default_flood_scope(self) -> Optional[str]: # noqa: D102 + event = self._ok(await self._require().commands.get_default_flood_scope()) + payload = getattr(event, "payload", {}) or {} + name = payload.get("scope_name") + return None if name is None else str(name) + + async def get_time(self) -> Optional[int]: # noqa: D102 - inherited docstring + event = self._ok(await self._require().commands.get_time()) + payload = getattr(event, "payload", {}) or {} + value = payload.get("time") + return None if value is None else int(value) + + async def get_battery(self) -> dict: # noqa: D102 - inherited docstring + event = self._ok(await self._require().commands.get_bat()) + return dict(getattr(event, "payload", {}) or {}) + + async def get_stats(self) -> dict: # noqa: D102 - inherited docstring + mc = self._require() + stats: dict = {} + # Each frame independently best-effort: firmware predating one stats type answers + # with an error, which must not cost us the frames it does support. + for read in ( + mc.commands.get_stats_core, + mc.commands.get_stats_radio, + mc.commands.get_stats_packets, + ): + try: + event = self._ok(await read()) + except Exception: # noqa: BLE001 - optional read; absence is acceptable + continue + stats.update(getattr(event, "payload", {}) or {}) + return stats + async def get_path_hash_mode(self) -> int: # noqa: D102 - inherited docstring return int(await self._require().commands.get_path_hash_mode()) @@ -1546,8 +1655,38 @@ class MeshCoreDevice(Device): 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_tuning( # noqa: D102 - inherited docstring + self, + rx_delay: int, + airtime_factor: int, + tx_delay_factor: int = 0, + direct_tx_delay_factor: int = 0, + ) -> None: + from meshcore import EventType + + # The library's set_tuning hardcodes the two TX delay bytes to zero, so the full + # CMD_SET_TUNING_PARAMS (0x15) frame is built here instead: rx_delay(4 LE) + + # airtime_factor(4 LE) + tx_delay_factor(1) + direct_tx_delay_factor(1). + data = ( + b"\x15" + + int(rx_delay).to_bytes(4, "little") + + int(airtime_factor).to_bytes(4, "little") + + int(tx_delay_factor).to_bytes(1, "little") + + int(direct_tx_delay_factor).to_bytes(1, "little") + ) + self._ok( + await self._require().commands.send(data, [EventType.OK, EventType.ERROR]) + ) + + async def set_autoadd_config(self, flags: int) -> None: # noqa: D102 + self._ok(await self._require().commands.set_autoadd_config(int(flags))) + + async def set_default_flood_scope(self, scope: str) -> None: # noqa: D102 + # The library treats "", "0", "None" and "*" as "clear the scope"; normalize to + # None for the empty case so only a real name gets the ``#`` treatment. + self._ok( + await self._require().commands.set_default_flood_scope(scope.strip() or None) + ) async def set_manual_add_contacts(self, enabled: bool) -> None: # noqa: D102 self._ok(await self._require().commands.set_manual_add_contacts(enabled)) @@ -1672,7 +1811,17 @@ class MockDevice(Device): "radio_cr": 5, "simulated": True, } - self._tuning: dict = {"rx_delay": 0, "airtime_factor": 0} + self._tuning: dict = { + "rx_delay": 0, + "airtime_factor": 0, + "tx_delay_factor": 0, + "direct_tx_delay_factor": 0, + } + self._autoadd_config = 0 + self._flood_scope = "" + # Simulated clock skew (seconds behind the host), so the sync-clock flow has a + # visible drift to correct until set_time is called. + self._clock_offset: Optional[int] = -125 self._path_hash_mode = 0 self._custom_vars: dict[str, str] = {} self._channels: dict[int, dict] = {} @@ -1773,6 +1922,42 @@ class MockDevice(Device): async def get_tuning(self) -> dict: # noqa: D102 - inherited docstring return dict(self._tuning) + async def get_autoadd_config(self) -> Optional[int]: # noqa: D102 + return self._autoadd_config + + async def get_default_flood_scope(self) -> Optional[str]: # noqa: D102 + return self._flood_scope + + async def get_time(self) -> Optional[int]: # noqa: D102 - inherited docstring + import time as _time + + if self._clock_offset is None: + return self._info.get("clock") + return int(_time.time()) + self._clock_offset + + async def get_battery(self) -> dict: # noqa: D102 - inherited docstring + return {"level": 4100, "used_kb": 128, "total_kb": 1024} + + async def get_stats(self) -> dict: # noqa: D102 - inherited docstring + return { + "battery_mv": 4100, + "uptime_secs": 93784, # 1d 2h 3m 4s + "errors": 0, + "queue_len": 0, + "noise_floor": -110, + "last_rssi": -62, + "last_snr": 9.5, + "tx_air_secs": 42, + "rx_air_secs": 360, + "recv": 1234, + "sent": 210, + "flood_tx": 40, + "direct_tx": 170, + "flood_rx": 900, + "direct_rx": 334, + "recv_errors": 3, + } + async def get_path_hash_mode(self) -> int: # noqa: D102 - inherited docstring return self._path_hash_mode @@ -1797,8 +1982,30 @@ class MockDevice(Device): 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_tuning( # noqa: D102 - inherited docstring + self, + rx_delay: int, + airtime_factor: int, + tx_delay_factor: int = 0, + direct_tx_delay_factor: int = 0, + ) -> None: + self._tuning = { + "rx_delay": rx_delay, + "airtime_factor": airtime_factor, + "tx_delay_factor": tx_delay_factor, + "direct_tx_delay_factor": direct_tx_delay_factor, + } + + async def set_autoadd_config(self, flags: int) -> None: # noqa: D102 + self._autoadd_config = int(flags) + + async def set_default_flood_scope(self, scope: str) -> None: # noqa: D102 + # Mirror the transport layer: empty clears, a bare name gains its leading #. + scope = scope.strip() + if not scope: + self._flood_scope = "" + else: + self._flood_scope = scope if scope.startswith("#") else f"#{scope}" async def set_manual_add_contacts(self, enabled: bool) -> None: # noqa: D102 self._info["manual_add_contacts"] = enabled @@ -1828,7 +2035,11 @@ class MockDevice(Device): } async def set_time(self, epoch: int) -> None: # noqa: D102 - inherited docstring + import time as _time + self._info["clock"] = epoch + # The simulated clock now runs from the set point (drift corrected). + self._clock_offset = epoch - int(_time.time()) async def send_advert(self, flood: bool = False) -> None: # noqa: D102 await asyncio.sleep(0) diff --git a/meshterm/core/device_config.py b/meshterm/core/device_config.py index 8df70f8..70db602 100644 --- a/meshterm/core/device_config.py +++ b/meshterm/core/device_config.py @@ -47,6 +47,12 @@ class SettingSpec: :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. + max_key: Snapshot key holding this setting's *device-reported* inclusive maximum + (e.g. ``max_tx_power`` bounding ``tx_power``). Checked by :func:`parse_value` + when it is given a snapshot, tightening the static :attr:`maximum` to what + the connected hardware actually supports. + max_length: For ``str`` values, the longest accepted string (protocol field + widths, e.g. the flood scope's 31-byte name slot). getter: Extracts the current value from a snapshot dict. apply: Coroutine applying a parsed value to a device, given the snapshot. """ @@ -62,6 +68,8 @@ class SettingSpec: minimum: Optional[float] = None maximum: Optional[float] = None strict_choices: bool = True + max_key: Optional[str] = None + max_length: Optional[int] = None # --- value parsing / formatting ---------------------------------------------- @@ -70,12 +78,15 @@ _TRUE = {"1", "true", "yes", "on", "y"} _FALSE = {"0", "false", "no", "off", "n"} -def parse_value(spec: SettingSpec, raw: Any) -> Any: +def parse_value(spec: SettingSpec, raw: Any, snapshot: Optional[dict] = None) -> 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). + snapshot: Optional device snapshot; when given and the spec names a + :attr:`~SettingSpec.max_key`, the device-reported maximum found there + tightens the static bound (e.g. TX power capped at this board's max). Returns: The typed, range-checked value ready for :meth:`SettingSpec.apply`. @@ -85,6 +96,11 @@ def parse_value(spec: SettingSpec, raw: Any) -> Any: """ text = str(raw).strip() if spec.value_type == "str": + if spec.max_length is not None and len(text) > spec.max_length: + raise DeviceConfigError( + f"{spec.key}: must be at most {spec.max_length} characters, " + f"got {len(text)}" + ) return text if spec.value_type == "bool": low = text.lower() @@ -114,11 +130,35 @@ def parse_value(spec: SettingSpec, raw: Any) -> Any: 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}") + maximum = effective_maximum(spec, snapshot) + if maximum is not None and value > maximum: + raise DeviceConfigError(f"{spec.key}: must be <= {maximum:g}, got {value}") return value +def effective_maximum(spec: SettingSpec, snapshot: Optional[dict]) -> Optional[float]: + """The inclusive maximum for ``spec``: the device-reported one when known, else static. + + Args: + spec: The setting. + snapshot: The device snapshot the reported maximum is read from (may be ``None``). + + Returns: + The tighter of the spec's static bound and the snapshot's ``max_key`` value, or + ``None`` when neither exists. + """ + maximum = spec.maximum + if snapshot is not None and spec.max_key is not None: + reported = snapshot.get(spec.max_key) + if reported is not None: + try: + reported_f = float(reported) + except (TypeError, ValueError): + return maximum + maximum = reported_f if maximum is None else min(maximum, reported_f) + return maximum + + def format_value(spec: SettingSpec, value: Any) -> str: """Render a value for display. @@ -131,6 +171,8 @@ def format_value(spec: SettingSpec, value: Any) -> str: """ if value is None: return "?" + if spec.value_type == "str" and value == "": + return "(not set)" 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: @@ -152,8 +194,8 @@ async def build_snapshot(device: Device) -> dict: device: A connected device. Returns: - A dict keyed like ``SELF_INFO`` plus ``rx_delay``, ``airtime_factor`` and - ``path_hash_mode``. + A dict keyed like ``SELF_INFO`` plus ``rx_delay``, ``airtime_factor``, + ``path_hash_mode``, ``autoadd_config`` and ``flood_scope``. """ snapshot = dict(await device.get_self_info()) try: @@ -164,6 +206,14 @@ async def build_snapshot(device: Device) -> dict: snapshot["path_hash_mode"] = await device.get_path_hash_mode() except Exception: # noqa: BLE001 - optional read; absence is acceptable pass + try: + snapshot["autoadd_config"] = await device.get_autoadd_config() + except Exception: # noqa: BLE001 - optional read; absence is acceptable + pass + try: + snapshot["flood_scope"] = await device.get_default_flood_scope() + except Exception: # noqa: BLE001 - optional read; absence is acceptable + pass return snapshot @@ -198,12 +248,23 @@ def _coords_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[No def _tuning_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[None]]: - """Build an apply that updates one tuning field, preserving the other.""" + """Build an apply that updates one tuning field, preserving the others. + + The TX delay factors cannot be read back from real hardware (see + :meth:`~meshterm.core.connection.Device.get_tuning`), so an unknown current value + falls back to ``0`` — exactly what every tuning write sent for them before they were + exposed as settings. + """ 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)) + fields = { + key: snapshot.get(key) + for key in ( + "rx_delay", "airtime_factor", "tx_delay_factor", "direct_tx_delay_factor" + ) + } + fields[field_name] = value + await device.set_tuning(*(int(v or 0) for v in fields.values())) return apply @@ -339,8 +400,8 @@ DEVICE_SETTINGS: list[SettingSpec] = [ getter=_get("radio_cr"), apply=_radio_apply("cr"), ), SettingSpec( - "tx_power", "TX power (dBm)", "Transmit power", "Radio", "int", - minimum=1, maximum=22, + "tx_power", "TX power (dBm)", "Transmit power, up to this board's reported max", + "Radio", "int", minimum=1, maximum=30, max_key="max_tx_power", getter=_get("tx_power"), apply=lambda d, v, s: d.set_tx_power(v), ), # Tuning @@ -354,6 +415,18 @@ DEVICE_SETTINGS: list[SettingSpec] = [ minimum=0, getter=_get("airtime_factor"), apply=_tuning_apply("airtime_factor"), ), + SettingSpec( + "tx_delay_factor", "TX delay", + "Random delay factor before relayed transmissions (write-only on hardware)", + "Tuning", "int", minimum=0, maximum=255, + getter=_get("tx_delay_factor"), apply=_tuning_apply("tx_delay_factor"), + ), + SettingSpec( + "direct_tx_delay_factor", "Direct TX delay", + "Delay factor before direct, zero-hop transmissions (write-only on hardware)", + "Tuning", "int", minimum=0, maximum=255, + getter=_get("direct_tx_delay_factor"), apply=_tuning_apply("direct_tx_delay_factor"), + ), # Behavior SettingSpec( "manual_add_contacts", "Manual add contacts", @@ -361,6 +434,18 @@ DEVICE_SETTINGS: list[SettingSpec] = [ getter=_get("manual_add_contacts"), apply=lambda d, v, s: d.set_manual_add_contacts(v), ), + SettingSpec( + "autoadd_config", "Contact auto-add", + "Bitmask of advert types auto-added as contacts (0 = none)", "Behavior", "int", + minimum=0, maximum=255, + getter=_get("autoadd_config"), apply=lambda d, v, s: d.set_autoadd_config(v), + ), + SettingSpec( + "flood_scope", "Flood scope", + "Limit flood routing to one #scope; empty reaches the whole mesh", "Behavior", + "str", max_length=30, + getter=_get("flood_scope"), apply=lambda d, v, s: d.set_default_flood_scope(v), + ), SettingSpec( "adv_loc_policy", "Advert location policy", "Share location in adverts", "Behavior", "enum", diff --git a/meshterm/tools/config.py b/meshterm/tools/config.py index d6d67df..34473bf 100644 --- a/meshterm/tools/config.py +++ b/meshterm/tools/config.py @@ -164,6 +164,10 @@ class ConfigTool(Tool): _require_yes(yes, "import-key overwrites the device identity") run_tool_command(self, {"ops": [("import_key", key_hex)]}) + @config_app.command("sync-clock", help="Set the device clock from this computer") + def _sync_clock_cmd() -> None: + run_tool_command(self, {"ops": [("sync_clock",)]}) + @config_app.command("reboot", help="Reboot the device") def _reboot_cmd( yes: bool = typer.Option(False, "--yes", help="Confirm reboot"), @@ -237,6 +241,15 @@ async def apply_ops( ctx.ui.note(f"[ok]✓[/ok] {kind_label} advertisement sent") elif kind == "share": _share_contact(ctx, snapshot) + elif kind == "sync_clock": + import time as _time + from datetime import datetime + + epoch = int(_time.time()) + await device.set_time(epoch) + stamp = datetime.fromtimestamp(epoch).astimezone().strftime("%Y-%m-%d %H:%M:%S") + ctx.ui.note(f"[ok]✓[/ok] device clock set to [brand]{stamp}[/brand]") + changes += 1 elif kind == "reboot": await device.reboot() ctx.ui.note("[warn]device rebooting[/warn]") @@ -266,7 +279,7 @@ async def _apply_setting( ``1`` (a change was applied). """ spec = get_spec(key) - value = parse_value(spec, raw) + value = parse_value(spec, raw, snapshot) await spec.apply(device, value, snapshot) snapshot[key] = value ctx.ui.note(f"[ok]✓[/ok] [brand]{key}[/brand] = {format_value(spec, value)}") diff --git a/meshterm/tools/info.py b/meshterm/tools/info.py index 7e00f81..8760bc2 100644 --- a/meshterm/tools/info.py +++ b/meshterm/tools/info.py @@ -2,13 +2,20 @@ from __future__ import annotations -from typing import Any +import time +from typing import Any, Optional import typer +from rich.panel import Panel +from rich.text import Text from ..context import AppContext +from ..core.connection import Device from .base import Tool, ToolResult, register +#: MeshCore advert-type byte -> human-readable node role. +_ROLES = {1: "companion", 2: "repeater", 3: "room server", 4: "sensor"} + @register class InfoTool(Tool): @@ -19,12 +26,12 @@ class InfoTool(Tool): name = "info" title = "Device info" - help = "Show device identity and radio config" + help = "Show device status, identity, and radio config" category = "Device" order = 10 async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: - """Query the device and render its full configuration. + """Query the device and render its live status plus its full configuration. Args: ctx: Shared application context. @@ -40,8 +47,9 @@ class InfoTool(Tool): snapshot = await build_snapshot(device) custom = await device.get_custom_vars() - # Render every current setting with a short explanation of each. - ctx.ui.show(config_table(snapshot, custom)) + # A live status panel (role, firmware, battery, clock, radio/packet statistics) + # above every current setting with a short explanation of each. + ctx.ui.show(await _status_panel(device, snapshot), Text(""), config_table(snapshot, custom)) return ToolResult(summary={"name": snapshot.get("name")}) @@ -56,3 +64,112 @@ class InfoTool(Tool): @app.command(name=self.name, help=self.help) def _info() -> None: run_tool_command(self, {}) + + +# -- the status panel ----------------------------------------------------------- + + +async def _status_panel(device: Device, snapshot: dict) -> Panel: + """Build the live status panel: role, firmware, battery, clock, and statistics. + + Every read beyond the snapshot is best-effort — firmware predating a query (battery, + clock, stats) simply contributes no row — so the panel renders on any device. + + Args: + device: The connected device to query. + snapshot: The already-built settings snapshot (for role and identity fields). + + Returns: + A Rich :class:`Panel` of label/value status rows. + """ + rows: list[tuple[str, Text]] = [] + + adv_type = snapshot.get("adv_type") + if adv_type is not None: + role = _ROLES.get(int(adv_type), f"type {adv_type}") + rows.append(("role", Text(role, style="brand"))) + + info = await _try(device.get_device_info) or {} + if info.get("model"): + rows.append(("model", Text(str(info["model"])))) + firmware = " ".join(str(info[k]) for k in ("ver", "fw_build") if info.get(k)) + if firmware: + rows.append(("firmware", Text(firmware))) + + battery = await _try(device.get_battery) or {} + level = battery.get("level") + if level: + rows.append(("battery", Text(f"{int(level) / 1000:.2f} V"))) + if battery.get("total_kb"): + rows.append( + ("storage", Text(f"{battery.get('used_kb', 0)} / {battery['total_kb']} kB")) + ) + + clock = await _try(device.get_time) + if clock: + stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(clock)) + rows.append(("clock", Text.assemble(stamp, (f" {_drift(clock)}", "muted")))) + + stats = await _try(device.get_stats) or {} + if stats.get("uptime_secs") is not None: + rows.append(("uptime", Text(_uptime(int(stats["uptime_secs"]))))) + if stats.get("noise_floor") is not None: + parts = Text(f"{stats['noise_floor']} dBm noise floor") + if stats.get("last_rssi") is not None: + parts.append(f" · last RSSI {stats['last_rssi']} dBm", style="muted") + if stats.get("last_snr") is not None: + parts.append(f" · last SNR {stats['last_snr']:+.1f} dB", style="muted") + rows.append(("radio", parts)) + if stats.get("tx_air_secs") is not None: + rows.append( + ("airtime", Text(f"TX {stats['tx_air_secs']} s · RX {stats.get('rx_air_secs', 0)} s")) + ) + if stats.get("recv") is not None: + packets = Text(f"{stats.get('sent', 0)} sent · {stats['recv']} received") + if stats.get("recv_errors"): + packets.append(f" · {stats['recv_errors']} receive errors", style="warn") + rows.append(("packets", packets)) + + width = max((len(label) for label, _ in rows), default=0) + body = Text() + for i, (label, value) in enumerate(rows): + if i: + body.append("\n") + body.append(f"{label.ljust(width)} ", style="muted") + body.append_text(value) + if not rows: + body = Text("no status reported", style="muted") + return Panel(body, title="[accent]Status[/accent]", border_style="accent", expand=False) + + +async def _try(read) -> Optional[Any]: + """Await a device read, returning ``None`` when the firmware doesn't support it.""" + try: + return await read() + except Exception: # noqa: BLE001 - optional read; absence is acceptable + return None + + +def _drift(device_epoch: int) -> str: + """Describe the device clock's drift against this computer's clock.""" + drift = device_epoch - int(time.time()) + if abs(drift) < 2: + return "(in sync)" + direction = "ahead" if drift > 0 else "behind" + return f"({abs(drift)} s {direction})" + + +def _uptime(secs: int) -> str: + """Render an uptime as ``3d 2h 41m`` (seconds shown only under a minute).""" + if secs < 60: + return f"{secs} s" + days, rem = divmod(secs, 86400) + hours, rem = divmod(rem, 3600) + minutes = rem // 60 + parts = [] + if days: + parts.append(f"{days}d") + if hours: + parts.append(f"{hours}h") + parts.append(f"{minutes}m") + return " ".join(parts) diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 8084400..df30280 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -40,6 +40,7 @@ from ..core.device_config import ( DeviceConfigError, SettingSpec, build_snapshot, + effective_maximum, format_value, get_spec, parse_value, @@ -56,6 +57,7 @@ _LOCATION = "__location__" _PRESETS = "__presets__" _CUSTOM = "__custom__" _ADVERT = "__advert__" +_SYNC_CLOCK = "__sync_clock__" _REBOOT = "__reboot__" _BACKUP = "__backup__" _RESTORE = "__restore__" @@ -371,7 +373,7 @@ async def _stage_setting( """Prompt for one setting's new value and stage it.""" spec = get_spec(key) current = pending.get(key, spec.getter(snapshot)) - value = await _prompt_value(ctx, spec, current) + value = await _prompt_value(ctx, spec, current, snapshot) if value is None: return if value == spec.getter(snapshot): @@ -380,18 +382,26 @@ async def _stage_setting( pending[key] = value -def _range_hint(spec: SettingSpec) -> str: - """A muted "allowed values" hint for a numeric prompt, from the spec's bounds.""" - if spec.minimum is not None and spec.maximum is not None: - return f"Allowed: {spec.minimum:g} – {spec.maximum:g}" +def _range_hint(spec: SettingSpec, snapshot: dict) -> str: + """A muted "allowed values" hint for a numeric prompt. + + Uses the *effective* maximum — the device-reported bound (e.g. this board's max TX + power) when the spec names one, else the static bound — so the hint promises exactly + what validation will accept. + """ + maximum = effective_maximum(spec, snapshot) + if spec.minimum is not None and maximum is not None: + return f"Allowed: {spec.minimum:g} – {maximum:g}" if spec.minimum is not None: return f"Allowed: ≥ {spec.minimum:g}" - if spec.maximum is not None: - return f"Allowed: ≤ {spec.maximum:g}" + if maximum is not None: + return f"Allowed: ≤ {maximum:g}" return "" -async def _prompt_value(ctx: "AppContext", spec: SettingSpec, current: Any) -> Any: +async def _prompt_value( + ctx: "AppContext", spec: SettingSpec, current: Any, snapshot: dict +) -> Any: """Prompt for a typed value for ``spec`` (in the fitting dialog), ``None`` on cancel.""" if spec.value_type == "bool": # A straight two-state choice reads best as a button pair; the current state is @@ -430,7 +440,7 @@ async def _prompt_value(ctx: "AppContext", spec: SettingSpec, current: Any) -> A def validate(text: str) -> bool | str: try: - parse_value(spec, text) + parse_value(spec, text, snapshot) return True except DeviceConfigError as exc: return str(exc) @@ -440,9 +450,9 @@ async def _prompt_value(ctx: "AppContext", spec: SettingSpec, current: Any) -> A prompt=spec.help, default="" if current is None else str(current), validate=validate, - help_text=_range_hint(spec), + help_text=_range_hint(spec, snapshot), ) - return None if raw is None else parse_value(spec, raw) + return None if raw is None else parse_value(spec, raw, snapshot) async def _stage_location( @@ -615,6 +625,8 @@ async def device_actions(ctx: "AppContext") -> None: cursor = choice if choice == _ADVERT: await _advert_menu(ctx, device, snapshot) + elif choice == _SYNC_CLOCK: + await _sync_clock(ctx, device, snapshot) elif choice == _BACKUP: await _backup_now(ctx, device, snapshot) elif choice == _RESTORE: @@ -642,6 +654,7 @@ def _action_items() -> list: """ actions: list[tuple[str, str, str, str]] = [ ("📡 Send advert…", "Zero-hop, flood, or share this node as a QR code", _ADVERT, ""), + ("🕒 Sync clock…", "Set the device clock from this computer", _SYNC_CLOCK, ""), ("💾 Back up config to a file…", "Write every setting to TOML", _BACKUP, ""), ("📂 Restore config from a backup…", "Preview or apply a saved TOML", _RESTORE, ""), ("🔐 Identity key…", "Export or import the node's private key", _IDENTITY_KEY, ""), @@ -793,6 +806,56 @@ async def _reboot(ctx: "AppContext", device: "Device", snapshot: dict) -> bool: return True +async def _sync_clock(ctx: "AppContext", device: "Device", snapshot: dict) -> None: + """Show the device clock's drift against this computer and offer to correct it. + + A companion that boots with a bad RTC stamps every message wrongly, so the dialog + leads with the measured drift (or admits the clock is unreadable) before the Sync + button writes the host's time. + """ + import time + + device_time: Optional[int] = None + try: + device_time = await device.get_time() + except Exception: # noqa: BLE001 - old firmware; offer the blind sync instead + pass + if device_time: + drift = device_time - int(time.time()) + stamp = _clock_text(device_time) + prompt = ( + f"The device clock reads {stamp} — " + f"{_drift_text(drift)}. Set it from this computer?" + ) + else: + prompt = ( + "The device did not report its clock. Set it from this computer anyway?" + ) + choice = await ctx.ui.dialog( + prompt, + [("Cancel", None), ("Sync", "sync")], + title="🕒 Sync clock", + default=1, + ) + if choice == "sync": + await _run_now(ctx, device, snapshot, [("sync_clock",)], "Sync clock") + + +def _clock_text(epoch: int) -> str: + """A device timestamp rendered in this computer's local time.""" + from datetime import datetime + + return datetime.fromtimestamp(epoch).astimezone().strftime("%Y-%m-%d %H:%M:%S") + + +def _drift_text(drift: int) -> str: + """Describe a clock drift in seconds: ``"12 s behind"``, ``"3 s ahead"``, ``"in sync"``.""" + if abs(drift) < 2: + return "in sync with this computer" + direction = "ahead of" if drift > 0 else "behind" + return f"{abs(drift)} s {direction} this computer" + + async def _backup_now(ctx: "AppContext", device: "Device", snapshot: dict) -> None: """Prompt for a destination and write the TOML backup immediately.""" path = await ctx.ui.path( diff --git a/tests/test_config_editor.py b/tests/test_config_editor.py index 4460a9e..1b08d90 100644 --- a/tests/test_config_editor.py +++ b/tests/test_config_editor.py @@ -519,6 +519,53 @@ async def test_actions_reboot_on_simulator_stays_on_the_screen(ctx: AppContext) assert any("rebooting" in n for n in ui.notes) +async def test_actions_sync_clock_corrects_the_device_time(ctx: AppContext) -> None: + """Sync clock shows the drift, and confirming writes the host time to the device.""" + import time + + device = await ctx.device() + assert (await device.get_time()) < int(time.time()) # the mock boots with drift + ui = _install(ctx, [ + ("select", "__sync_clock__"), + ("dialog", "sync"), + ("select", "__cancel__"), + ]) + await device_actions(ctx) + assert abs((await device.get_time()) - int(time.time())) <= 2 + assert any("clock set to" in n for n in ui.notes) + + +async def test_actions_sync_clock_cancel_leaves_the_clock_alone(ctx: AppContext) -> None: + """Backing out of the sync dialog changes nothing.""" + device = await ctx.device() + before = await device.get_time() + _install(ctx, [ + ("select", "__sync_clock__"), + ("dialog", None), + ("select", "__cancel__"), + ]) + await device_actions(ctx) + assert abs((await device.get_time()) - before) <= 2 # still ticking on the old drift + + +async def test_editor_stages_flood_scope(ctx: AppContext) -> None: + """The flood scope is a first-class staged setting, hashtag-normalized on apply.""" + from meshterm.core.device_config import build_snapshot + from meshterm.tools.config import apply_ops + + _install(ctx, [ + ("select", "flood_scope"), + ("text", "alpha"), + ("select", "__apply__"), + ]) + ops = await edit_config(ctx) + assert ops == [("set", "flood_scope", "alpha")] + + device = await ctx.device() + await apply_ops(ctx, device, await build_snapshot(device), ops) + assert await device.get_default_flood_scope() == "#alpha" + + async def test_actions_backup_writes_immediately(ctx: AppContext, tmp_path: Path) -> None: """Backup runs at once: the TOML lands on disk before the screen closes.""" target = tmp_path / "out" / "backup.toml" diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 70c01cc..bfc9646 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -16,6 +16,7 @@ from meshterm.core.device_config import ( RADIO_PRESETS, DeviceConfigError, build_snapshot, + effective_maximum, format_value, get_spec, parse_value, @@ -330,6 +331,133 @@ async def test_plan_restore_emits_only_differences(tmp_path: Path) -> None: assert "radio_sf" not in [op[1] for op in ops if op[0] == "set"] +# -- the device-reported TX power ceiling --------------------------------------- + + +def test_tx_power_capped_by_device_reported_maximum() -> None: + """With a snapshot, the board's max_tx_power tightens the static bound.""" + spec = get_spec("tx_power") + snapshot = {"max_tx_power": 22} + assert parse_value(spec, "22", snapshot) == 22 + with pytest.raises(DeviceConfigError, match="<= 22"): + parse_value(spec, "23", snapshot) + # Without a snapshot only the static ceiling applies. + assert parse_value(spec, "27") == 27 + assert effective_maximum(spec, snapshot) == 22 + assert effective_maximum(spec, None) == 30 + + +def test_effective_maximum_never_loosens_the_static_bound() -> None: + """A device reporting a max above the static ceiling doesn't raise it.""" + spec = get_spec("tx_power") + assert effective_maximum(spec, {"max_tx_power": 99}) == 30 + assert effective_maximum(spec, {"max_tx_power": "bogus"}) == 30 # unparseable -> static + + +# -- flood scope / auto-add / TX delays ------------------------------------------ + + +def test_flood_scope_length_limited_and_formats_empty() -> None: + """The scope name respects its 31-byte protocol slot; empty renders readably.""" + spec = get_spec("flood_scope") + assert parse_value(spec, "alpha") == "alpha" + with pytest.raises(DeviceConfigError, match="at most 30"): + parse_value(spec, "x" * 31) + assert format_value(spec, "") == "(not set)" + assert format_value(spec, "#alpha") == "#alpha" + + +async def test_flood_scope_round_trips_with_hashtag_normalization() -> None: + """Applying a bare scope name stores it with its leading #; empty clears it.""" + device = await _connected_mock() + spec = get_spec("flood_scope") + await spec.apply(device, "alpha", await build_snapshot(device)) + assert (await build_snapshot(device))["flood_scope"] == "#alpha" + await spec.apply(device, "", await build_snapshot(device)) + assert (await build_snapshot(device))["flood_scope"] == "" + + +async def test_autoadd_config_round_trips() -> None: + """The auto-add bitmask reaches the device and reads back into the snapshot.""" + device = await _connected_mock() + spec = get_spec("autoadd_config") + await spec.apply(device, parse_value(spec, "5"), await build_snapshot(device)) + assert (await build_snapshot(device))["autoadd_config"] == 5 + + +async def test_apply_tx_delay_preserves_other_tuning_fields() -> None: + """Editing one tuning field resends all four without clobbering the others.""" + device = await _connected_mock() + await device.set_tuning(7, 2, 0, 0) + spec = get_spec("tx_delay_factor") + await spec.apply(device, 5, await build_snapshot(device)) + tuning = await device.get_tuning() + assert tuning == { + "rx_delay": 7, + "airtime_factor": 2, + "tx_delay_factor": 5, + "direct_tx_delay_factor": 0, + } + # And the other direction: a direct-TX-delay edit keeps the fresh tx_delay_factor. + spec = get_spec("direct_tx_delay_factor") + await spec.apply(device, 3, await build_snapshot(device)) + assert (await device.get_tuning())["tx_delay_factor"] == 5 + assert (await device.get_tuning())["direct_tx_delay_factor"] == 3 + + +# -- clock sync ------------------------------------------------------------------- + + +async def test_mock_clock_drifts_until_set_time_corrects_it() -> None: + """The simulator's clock reads behind the host until set_time re-anchors it.""" + import time as _time + + device = await _connected_mock() + before = await device.get_time() + assert before is not None and before < int(_time.time()) # seeded drift + now = int(_time.time()) + await device.set_time(now) + after = await device.get_time() + assert after is not None and abs(after - now) <= 1 + + +# -- the Device info status panel ------------------------------------------------- + + +async def test_status_panel_reports_role_battery_clock_and_stats() -> None: + """The info tool's status panel surfaces the read-only device state in one place.""" + import io + + from rich.console import Console + + from meshterm.tools.info import _status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + panel = await _status_panel(device, await build_snapshot(device)) + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(panel) + out = console.file.getvalue() + + assert "companion" in out # adv_type 1 rendered as the node role + assert "MeshCore Simulator" in out + assert "4.10 V" in out + assert "1d 2h 3m" in out # 93784 s of simulated uptime + assert "s behind" in out # the mock's seeded clock drift + assert "-110 dBm noise floor" in out + assert "210 sent" in out and "1234 received" in out + + +def test_uptime_renders_compact_units() -> None: + """Uptime shows seconds only under a minute, then d/h/m parts as needed.""" + from meshterm.tools.info import _uptime + + assert _uptime(45) == "45 s" + assert _uptime(3660) == "1h 1m" + assert _uptime(93784) == "1d 2h 3m" + assert _uptime(86400) == "1d 0m" + + # -- safety gating -------------------------------------------------------------