From 43353f83a97d483d78885c6f06211a97c3497a36 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 20 Jun 2026 17:02:34 -0400 Subject: [PATCH] Initial commit: MeshTools with device discovery & selection MeshTools is a Rich+Questionary interactive / Typer-scriptable toolkit for tuning a MeshCore mesh over a serial companion device, with SQLite-logged runs and Plotly visualizations. Includes the skeleton (trace, info, history), TX-power optimization, and a MockDevice simulator (--mock). Device discovery & selection: - core/discovery.py: enumerate serial ports (pyserial), flag/sort likely LoRa hardware by USB vendor id, stable_id for replug-safe identity. - core/device_store.py: remember the last successfully connected device in /devices.json (independent of --db). - core/selection.py: non-interactive resolver (--port > profile > remembered > sole device > guidance error) for the CLI. - ui/device_picker.py + menu startup: interactive picker preselecting the remembered default; banner reflects the choice. - tools/devices.py: `meshtools devices` lists/marks attached devices. - AppContext resolves the port and records last-known-good on connect success. Fixes: - theme.py: force UTF-8 on stdout/stderr so glyphs don't crash legacy consoles. - connection.py: friendly message when meshcore is missing; pin meshcore>=2.3. - trace/tx-optimize: fall back to free-text target entry when the device reports no contacts (autocomplete requires non-empty choices). Co-Authored-By: Claude Opus 4.8 --- .claude/settings.json | 12 + .gitignore | 25 ++ README.md | 62 +++++ config.example.toml | 31 +++ meshtools/__init__.py | 3 + meshtools/__main__.py | 6 + meshtools/cli.py | 159 ++++++++++++ meshtools/context.py | 109 +++++++++ meshtools/core/__init__.py | 1 + meshtools/core/config.py | 133 +++++++++++ meshtools/core/connection.py | 359 ++++++++++++++++++++++++++++ meshtools/core/device_store.py | 98 ++++++++ meshtools/core/discovery.py | 124 ++++++++++ meshtools/core/models.py | 198 +++++++++++++++ meshtools/core/selection.py | 116 +++++++++ meshtools/persistence/__init__.py | 1 + meshtools/persistence/db.py | 104 ++++++++ meshtools/persistence/logging.py | 93 +++++++ meshtools/persistence/repository.py | 182 ++++++++++++++ meshtools/services/__init__.py | 6 + meshtools/services/trace_runner.py | 96 ++++++++ meshtools/services/tx_optimizer.py | 157 ++++++++++++ meshtools/tools/__init__.py | 30 +++ meshtools/tools/base.py | 171 +++++++++++++ meshtools/tools/devices.py | 139 +++++++++++ meshtools/tools/history.py | 68 ++++++ meshtools/tools/info.py | 67 ++++++ meshtools/tools/trace.py | 137 +++++++++++ meshtools/tools/tx_optimize.py | 205 ++++++++++++++++ meshtools/ui/__init__.py | 1 + meshtools/ui/device_picker.py | 68 ++++++ meshtools/ui/menu.py | 123 ++++++++++ meshtools/ui/theme.py | 60 +++++ meshtools/ui/widgets.py | 172 +++++++++++++ meshtools/viz/__init__.py | 11 + meshtools/viz/tx_plot.py | 108 +++++++++ pyproject.toml | 53 ++++ tests/__init__.py | 0 tests/test_discovery.py | 170 +++++++++++++ tests/test_skeleton.py | 109 +++++++++ 40 files changed, 3767 insertions(+) create mode 100644 .claude/settings.json create mode 100644 .gitignore create mode 100644 README.md create mode 100644 config.example.toml create mode 100644 meshtools/__init__.py create mode 100644 meshtools/__main__.py create mode 100644 meshtools/cli.py create mode 100644 meshtools/context.py create mode 100644 meshtools/core/__init__.py create mode 100644 meshtools/core/config.py create mode 100644 meshtools/core/connection.py create mode 100644 meshtools/core/device_store.py create mode 100644 meshtools/core/discovery.py create mode 100644 meshtools/core/models.py create mode 100644 meshtools/core/selection.py create mode 100644 meshtools/persistence/__init__.py create mode 100644 meshtools/persistence/db.py create mode 100644 meshtools/persistence/logging.py create mode 100644 meshtools/persistence/repository.py create mode 100644 meshtools/services/__init__.py create mode 100644 meshtools/services/trace_runner.py create mode 100644 meshtools/services/tx_optimizer.py create mode 100644 meshtools/tools/__init__.py create mode 100644 meshtools/tools/base.py create mode 100644 meshtools/tools/devices.py create mode 100644 meshtools/tools/history.py create mode 100644 meshtools/tools/info.py create mode 100644 meshtools/tools/trace.py create mode 100644 meshtools/tools/tx_optimize.py create mode 100644 meshtools/ui/__init__.py create mode 100644 meshtools/ui/device_picker.py create mode 100644 meshtools/ui/menu.py create mode 100644 meshtools/ui/theme.py create mode 100644 meshtools/ui/widgets.py create mode 100644 meshtools/viz/__init__.py create mode 100644 meshtools/viz/tx_plot.py create mode 100644 pyproject.toml create mode 100644 tests/__init__.py create mode 100644 tests/test_discovery.py create mode 100644 tests/test_skeleton.py diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..a566692 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,12 @@ +{ + "permissions": { + "allow": [ + "WebSearch", + "WebFetch(domain:pypi.org)", + "Bash(.venv/Scripts/python.exe -c \"import meshcore; print\\('meshcore', getattr\\(meshcore,'__version__','?'\\)\\)\")", + "Bash(.venv/Scripts/python.exe -m pytest -q)", + "Bash(git -C d:/vibe/MeshTools status)", + "Bash(git -C d:/vibe/MeshTools log --oneline -5)" + ] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..db15f9c --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ + +# Virtual environments +.venv/ +venv/ + +# Tooling caches +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ + +# Editor +.vscode/ + +# Local Claude settings (project settings.json is tracked) +.claude/settings.local.json + +# MeshTools runtime data +*.db +output/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..78bcb0b --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# MeshTools + +A modern, extensible command-line toolkit for tuning and exploring a +[MeshCore](https://meshcore.co.uk/) mesh through a serial-connected companion device. + +MeshTools is interactive by default (a Rich + Questionary menu) and fully scriptable +(every menu option is also a Typer subcommand). Every run is logged to SQLite and can be +turned into interactive HTML visualizations. + +## Features + +| Feature | Status | What it does | +| --- | --- | --- | +| **Trace** | โœ… skeleton | Run repeated path traces to a target and aggregate per-hop SNR. | +| **Device info** | โœ… skeleton | Show the connected companion device's identity and radio config. | +| **History / DB** | โœ… skeleton | Every tool execution and measurement is persisted and queryable. | +| **TX-power optimization** | โœ… working | Sweep transmit power (coarse + refine), converge on the best signal, optionally apply, render an interactive chart. | +| **Path optimization** | ๐Ÿšง planned | Discover and score mesh paths from neighbors outward. | +| **Visualizations** | ๐ŸŸก partial | Plotly TX-sweep chart (HTML) done; pyvis mesh graph + time-series planned. | + +## Install + +```bash +pip install -e ".[dev]" +``` + +Python 3.10+ is required (matching the `meshcore` library). + +## Usage + +```bash +# Interactive menu (default) +meshtools + +# Scripted: every menu option is also a subcommand +meshtools trace --target Alice --samples 10 --profile yagi +meshtools tx-optimize --target Alice --samples 6 --step 3 --apply +meshtools info +meshtools history + +# No radio attached? Use the built-in simulator for development. +meshtools --mock trace --target Alice +``` + +## Architecture + +MeshTools is layered so features are added by dropping a single file in `meshtools/tools/`: + +``` +cli.py Typer app; no subcommand -> interactive menu +context.py AppContext (console, config, repository, device) dependency container +core/ Domain: models, config + device profiles, connection abstraction (+ mock) +tools/ Pluggable "menu options"; each self-registers and gets logging for free +services/ Algorithms (trace aggregation, tx search, path exploration) โ€” no UI +persistence/ SQLite schema, repository, structured logging +ui/ Rich theme/widgets + Questionary menu +viz/ Plotly / pyvis renderers -> HTML & PNG +``` + +Adding a feature means subclassing `Tool`, decorating it with `@register`, and +implementing `run()`. The same registry builds both the CLI and the menu, and the base +class wraps every execution in a logged `runs` row automatically. diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..dc719a0 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,31 @@ +# MeshTools configuration. +# Copy to ~/.config/meshtools/config.toml (or pass --db / --port on the CLI). +# +# Profiles are optional. With no profile and no --port, MeshTools discovers attached +# serial devices, lets you pick one (interactively) or uses the single one present, and +# remembers the last device that connected as the default for next time. Define profiles +# below only to give your hardware stable aliases (e.g. --profile yagi). + +default_profile = "s3" +trace_cooldown_s = 1.0 +# db_path = "C:/Users/you/meshtools/meshtools.db" +# output_dir = "C:/Users/you/meshtools/output" + +# One [profiles.] block per physical companion device. +[profiles.s3] +port = "COM5" +baudrate = 115200 +default_tx_power = 20 +description = "XIAO ESP32-S3 + Wio SX1262 serial companion" + +[profiles.yagi] +port = "COM6" +description = "Yagi repeater (reaching the wider mesh)" + +[profiles.local] +port = "COM7" +description = "Local-range repeater" + +[profiles.observer] +port = "COM8" +description = "XIAO observer running a bot" diff --git a/meshtools/__init__.py b/meshtools/__init__.py new file mode 100644 index 0000000..dae4477 --- /dev/null +++ b/meshtools/__init__.py @@ -0,0 +1,3 @@ +"""MeshTools: a modern command-line toolkit for tuning and exploring a MeshCore mesh.""" + +__version__ = "0.1.0" diff --git a/meshtools/__main__.py b/meshtools/__main__.py new file mode 100644 index 0000000..dd96f59 --- /dev/null +++ b/meshtools/__main__.py @@ -0,0 +1,6 @@ +"""Enable ``python -m meshtools``.""" + +from .cli import main + +if __name__ == "__main__": + main() diff --git a/meshtools/cli.py b/meshtools/cli.py new file mode 100644 index 0000000..b4bab27 --- /dev/null +++ b/meshtools/cli.py @@ -0,0 +1,159 @@ +"""Typer entry point. + +Global options are parsed once in the callback, which builds the shared +:class:`~meshtools.context.AppContext`. Running with no subcommand launches the +interactive menu; otherwise the selected tool's subcommand runs. Both paths funnel +through :func:`run_tool_command` / :func:`run_menu`, so behavior stays identical. +""" + +from __future__ import annotations + +import asyncio +import logging +from pathlib import Path +from typing import Optional + +import typer + +from .context import AppContext +from .core.config import Settings +from .core.device_store import DeviceStore +from .core.selection import DeviceSelectionError +from .persistence.logging import configure_logging +from .persistence.repository import Repository +from .tools import all_tools +from .tools.base import Tool, ToolResult +from .ui.theme import make_console + +app = typer.Typer( + add_completion=False, + no_args_is_help=False, + rich_markup_mode="rich", + help="MeshTools โ€” a modern toolkit for tuning and exploring your MeshCore mesh.", +) + +# The context built by the callback and consumed by subcommands within one process. +_state: Optional[AppContext] = None + + +@app.callback(invoke_without_command=True) +def main_callback( + ctx: typer.Context, + profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Device profile."), + port: Optional[str] = typer.Option(None, "--port", help="Serial port override."), + mock: bool = typer.Option(False, "--mock", help="Use the built-in simulator."), + db_path: Optional[Path] = typer.Option(None, "--db", help="SQLite database path."), + json_output: bool = typer.Option(False, "--json", help="Machine-readable output."), + quiet: bool = typer.Option(False, "--quiet", "-q", help="Suppress console logging."), +) -> None: + """Build the application context and dispatch to the menu or a subcommand. + + Args: + ctx: The Click/Typer context. + profile: Named device profile to use. + port: Explicit serial port, overriding the profile. + mock: Whether to use the simulator instead of real hardware. + db_path: Override the database location. + json_output: Request machine-readable output from tools. + quiet: Suppress console logging (file logging continues). + """ + global _state + + settings = Settings.load() + if db_path is not None: + settings.db_path = db_path + + console = make_console() + configure_logging( + console, settings.config_dir, level=logging.INFO, quiet=quiet or json_output + ) + + app_ctx = AppContext( + console=console, + settings=settings, + repo=Repository(settings.db_path), + device_store=DeviceStore(settings.config_dir / "devices.json"), + profile=settings.resolve_profile(profile), + mock=mock, + port_override=port, + json_output=json_output, + explicit_selection=profile is not None or port is not None, + ) + _state = app_ctx + ctx.call_on_close(app_ctx.repo.close) + + if ctx.invoked_subcommand is None: + from .ui.menu import run_menu + + asyncio.run(_drive(run_menu(app_ctx), app_ctx)) + + +def run_tool_command(tool: Tool, params: dict) -> None: + """Execute a tool from a CLI subcommand and render its result. + + Builds and tears down the device connection within a single event loop so the + ``meshcore`` client is never used across loops. + + Args: + tool: The tool to run. + params: Parameters parsed from the subcommand's options. + """ + assert _state is not None # set by the callback before any subcommand runs + try: + asyncio.run(_drive(_execute_and_render(tool, params, _state), _state)) + except DeviceSelectionError as exc: + # Ambiguous/absent device: show the guidance message, not a traceback. + _state.console.print(f"[err]โœ—[/err] {exc}") + raise typer.Exit(1) from exc + + +async def _drive(coro, ctx: AppContext) -> None: + """Await a coroutine then disconnect the device (but keep the repo open). + + Args: + coro: The coroutine to run (a tool execution or the menu loop). + ctx: The application context whose device should be closed afterward. + """ + try: + await coro + finally: + if ctx._device is not None: + await ctx._device.disconnect() + ctx._device = None + + +async def _execute_and_render(tool: Tool, params: dict, ctx: AppContext) -> ToolResult: + """Run a tool and print its closing message and artifact list. + + Args: + tool: The tool to execute. + params: Parameters for the tool. + ctx: The application context. + + Returns: + The tool's :class:`ToolResult`. + """ + result = await tool.execute(ctx, params) + if result.message: + ctx.console.print(result.message) + for artifact in result.artifacts: + ctx.console.print(f"[ok]โ—[/ok] wrote [accent]{artifact}[/accent]") + return result + + +def _register_all() -> None: + """Register every tool's CLI subcommand with the Typer app.""" + for tool in all_tools(): + tool.register_cli(app) + + +_register_all() + + +def main() -> None: + """Console-script entry point.""" + app() + + +if __name__ == "__main__": + main() diff --git a/meshtools/context.py b/meshtools/context.py new file mode 100644 index 0000000..902a3dc --- /dev/null +++ b/meshtools/context.py @@ -0,0 +1,109 @@ +"""The application context: a small dependency container passed to every tool. + +``AppContext`` owns the shared, expensive singletons (console, settings, repository, +logger) and lazily manages the device connection so tools that don't touch the radio +never open a serial port. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional + +from rich.console import Console + +from .core.config import DeviceProfile, Settings +from .core.connection import Device, make_device +from .core.device_store import DeviceStore +from .core.discovery import DiscoveredDevice, discover_devices +from .core.selection import resolve_device +from .persistence.logging import get_logger +from .persistence.repository import Repository + + +@dataclass(slots=True) +class AppContext: + """Shared services and per-invocation state handed to tools. + + Attributes: + console: Rich console for all rendering. + settings: Loaded application settings. + repo: Database repository. + profile: Active device profile, if one was resolved. + device_store: Store for the remembered "last known good" device. + mock: Whether the simulator device is in use. + port_override: Explicit serial port (from ``--port`` or the interactive picker), + overriding the profile. + json_output: Whether tools should emit machine-readable output. + selected_device: The discovered device chosen for this session, when known, so it + can be remembered after a successful connection. + explicit_selection: Whether ``--port``/``--profile`` was passed explicitly (which + suppresses the interactive picker and auto-discovery). + """ + + console: Console + settings: Settings + repo: Repository + device_store: DeviceStore + profile: Optional[DeviceProfile] = None + mock: bool = False + port_override: Optional[str] = None + json_output: bool = False + selected_device: Optional[DiscoveredDevice] = None + explicit_selection: bool = False + _device: Optional[Device] = field(default=None, init=False, repr=False) + + @property + def profile_name(self) -> Optional[str]: + """Name of the active profile, if any.""" + return self.profile.name if self.profile else None + + @property + def log(self): # type: ignore[no-untyped-def] + """The application logger.""" + return get_logger() + + async def device(self) -> Device: + """Return a connected :class:`Device`, opening the connection on first use. + + For real hardware this resolves which serial port to use (explicit ``--port`` / + profile / remembered default / sole attached device) and, on a successful + connection, records the device as the new "last known good" default. + + Returns: + The shared, connected device for this invocation. + + Raises: + ValueError: If no serial port can be chosen and the simulator is not enabled. + DeviceSelectionError: If discovery is ambiguous (subclass of ``ValueError``). + """ + if self._device is not None: + return self._device + + if self.mock: + self._device = make_device(mock=True, port=None) + await self._device.connect() + return self._device + + resolution = resolve_device( + discover_devices(), + self.device_store.load(), + explicit_port=self.port_override, + profile=self.profile, + ) + if resolution.device is not None: + self.selected_device = resolution.device + baudrate = self.profile.baudrate if self.profile else 115200 + self._device = make_device(mock=False, port=resolution.port, baudrate=baudrate) + await self._device.connect() + # Connection succeeded: this is now the last known good device. + if self.selected_device is not None: + self.device_store.remember(self.selected_device) + return self._device + + async def aclose(self) -> None: + """Disconnect the device (if connected) and close the repository.""" + if self._device is not None: + await self._device.disconnect() + self._device = None + self.repo.close() diff --git a/meshtools/core/__init__.py b/meshtools/core/__init__.py new file mode 100644 index 0000000..0b9e91b --- /dev/null +++ b/meshtools/core/__init__.py @@ -0,0 +1 @@ +"""Core domain layer: models, configuration, and the device connection abstraction.""" diff --git a/meshtools/core/config.py b/meshtools/core/config.py new file mode 100644 index 0000000..ebc876a --- /dev/null +++ b/meshtools/core/config.py @@ -0,0 +1,133 @@ +"""Configuration and named device profiles. + +Settings are read from a TOML file (default ``~/.config/meshtools/config.toml``) and may +be overridden per-invocation by CLI flags. Profiles let you alias your hardware +(``yagi`` repeater, ``local`` repeater, ``observer`` bot, ``s3`` serial companion) to a +serial port and defaults so commands can target them by name. +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Optional + +if sys.version_info >= (3, 11): + import tomllib +else: # pragma: no cover - exercised only on 3.10 + import tomli as tomllib + + +def default_config_dir() -> Path: + """Return the directory MeshTools uses for config and data. + + Honors ``$XDG_CONFIG_HOME`` when set; otherwise falls back to ``~/.config``. + + Returns: + The resolved configuration directory path (not guaranteed to exist). + """ + import os + + base = os.environ.get("XDG_CONFIG_HOME") + root = Path(base) if base else Path.home() / ".config" + return root / "meshtools" + + +@dataclass(slots=True) +class DeviceProfile: + """Connection defaults for one physical companion device. + + Attributes: + name: The profile alias (e.g. ``"yagi"``). + port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``). + baudrate: Serial baud rate. + default_tx_power: TX power to assume/restore for this device, if known. + description: Free-text note about the hardware. + """ + + name: str + port: Optional[str] = None + baudrate: int = 115200 + default_tx_power: Optional[int] = None + description: str = "" + + +@dataclass(slots=True) +class Settings: + """Top-level application settings. + + Attributes: + config_dir: Directory holding the config file and database. + db_path: SQLite database location. + output_dir: Where generated visualizations are written. + default_profile: Profile used when ``--profile`` is omitted. + profiles: Mapping of profile name to :class:`DeviceProfile`. + trace_cooldown_s: Minimum delay between transmit bursts (duty-cycle safety). + """ + + config_dir: Path = field(default_factory=default_config_dir) + db_path: Optional[Path] = None + output_dir: Optional[Path] = None + default_profile: Optional[str] = None + profiles: dict[str, DeviceProfile] = field(default_factory=dict) + trace_cooldown_s: float = 1.0 + + def __post_init__(self) -> None: + """Derive dependent paths that were not explicitly provided.""" + if self.db_path is None: + self.db_path = self.config_dir / "meshtools.db" + if self.output_dir is None: + self.output_dir = self.config_dir / "output" + + def resolve_profile(self, name: Optional[str]) -> Optional[DeviceProfile]: + """Look up a profile by name, falling back to the default profile. + + Args: + name: Requested profile name, or ``None`` to use the default. + + Returns: + The matching :class:`DeviceProfile`, or ``None`` if neither the requested + nor the default profile is defined. + """ + key = name or self.default_profile + if key is None: + return None + return self.profiles.get(key) + + @classmethod + def load(cls, config_path: Optional[Path] = None) -> "Settings": + """Load settings from a TOML file, returning defaults if it is absent. + + Args: + config_path: Explicit path to a config file. Defaults to + ``/config.toml``. + + Returns: + A populated :class:`Settings` instance. + """ + config_dir = default_config_dir() + path = config_path or (config_dir / "config.toml") + data: dict[str, Any] = {} + if path.exists(): + with path.open("rb") as fh: + data = tomllib.load(fh) + + profiles: dict[str, DeviceProfile] = {} + for pname, pdata in (data.get("profiles") or {}).items(): + profiles[pname] = DeviceProfile( + name=pname, + port=pdata.get("port"), + baudrate=pdata.get("baudrate", 115200), + default_tx_power=pdata.get("default_tx_power"), + description=pdata.get("description", ""), + ) + + return cls( + config_dir=config_dir, + db_path=Path(data["db_path"]) if data.get("db_path") else None, + output_dir=Path(data["output_dir"]) if data.get("output_dir") else None, + default_profile=data.get("default_profile"), + profiles=profiles, + trace_cooldown_s=float(data.get("trace_cooldown_s", 1.0)), + ) diff --git a/meshtools/core/connection.py b/meshtools/core/connection.py new file mode 100644 index 0000000..f864b9f --- /dev/null +++ b/meshtools/core/connection.py @@ -0,0 +1,359 @@ +"""Device connection abstraction. + +Services and tools depend only on the :class:`Device` interface, never on the +``meshcore`` library directly. This keeps the algorithms testable and lets the +:class:`MockDevice` simulator stand in for real hardware during development. + +Two implementations are provided: + +* :class:`MeshCoreDevice` - wraps the async ``meshcore`` companion-protocol client. +* :class:`MockDevice` - a deterministic simulator with a physically plausible + SNR-vs-TX-power response, used by ``--mock`` and the test suite. +""" + +from __future__ import annotations + +import asyncio +import random +from abc import ABC, abstractmethod +from typing import Optional + +from .models import Contact, Hop, TraceResult, utcnow + +TX_POWER_MIN = 1 +TX_POWER_MAX = 22 + + +class Device(ABC): + """Abstract companion device exposing the operations MeshTools needs. + + Implementations manage their own connection lifecycle and translate raw protocol + events into the domain models in :mod:`meshtools.core.models`. + """ + + @abstractmethod + async def connect(self) -> None: + """Open the connection to the device. Idempotent.""" + + @abstractmethod + async def disconnect(self) -> None: + """Close the connection and release resources. Idempotent.""" + + @abstractmethod + async def get_self_info(self) -> dict: + """Return identity and radio configuration of the connected device. + + Returns: + A dict with at least ``name`` and, when available, ``tx_power`` and radio + parameters (``freq``, ``bw``, ``sf``, ``cr``). + """ + + @abstractmethod + async def get_contacts(self) -> list[Contact]: + """Return the device's known contacts. + + Returns: + The list of :class:`Contact` records currently stored on the device. + """ + + @abstractmethod + async def get_tx_power(self) -> Optional[int]: + """Return the current TX power level, or ``None`` if unknown.""" + + @abstractmethod + async def set_tx_power(self, value: int) -> None: + """Set the radio transmit power. + + Args: + value: TX power level, clamped by the caller to the device's valid range. + """ + + @abstractmethod + async def run_trace( + self, + target: str, + *, + path: Optional[list[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. + timeout: Seconds to wait for the trace reply. + + Returns: + A :class:`TraceResult`; ``success`` is ``False`` on timeout. + """ + + async def __aenter__(self) -> "Device": + """Enter the async context manager, connecting the device.""" + await self.connect() + return self + + async def __aexit__(self, *exc: object) -> None: + """Exit the async context manager, disconnecting the device.""" + await self.disconnect() + + +class MeshCoreDevice(Device): + """A :class:`Device` backed by the ``meshcore`` serial companion client. + + Note: + The trace mapping here follows the documented companion protocol (trace replies + carry per-hop SNR encoded as ``SNR * 4``) but should be validated against your + firmware version, as event payload field names vary between releases. + """ + + def __init__(self, port: str, baudrate: int = 115200) -> None: + """Initialize the device wrapper. + + Args: + port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``). + baudrate: Serial baud rate. + """ + self._port = port + self._baudrate = baudrate + self._mc = None # type: ignore[var-annotated] # meshcore.MeshCore + + async def connect(self) -> None: # noqa: D102 - inherited docstring + if self._mc is not None: + return + try: + from meshcore import MeshCore # lazy import so --mock needs no hardware deps + except ImportError as exc: # pragma: no cover - environment-dependent + raise RuntimeError( + "The 'meshcore' library is required to talk to real hardware but is not " + "installed. Run `pip install -e .` (or `pip install meshcore`), or use " + "--mock for the simulator." + ) from exc + + self._mc = await MeshCore.create_serial(self._port, self._baudrate) + + async def disconnect(self) -> None: # noqa: D102 - inherited docstring + if self._mc is None: + return + disconnect = getattr(self._mc, "disconnect", None) + if disconnect is not None: + await disconnect() + self._mc = None + + def _require(self): # type: ignore[no-untyped-def] + """Return the live client or raise if not connected.""" + if self._mc is None: + raise RuntimeError("Device is not connected; call connect() first.") + return self._mc + + async def get_self_info(self) -> dict: # noqa: D102 - inherited docstring + mc = self._require() + result = await mc.commands.send_appstart() + return dict(getattr(result, "payload", {}) or {}) + + 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 {} + contacts: list[Contact] = [] + for name, info in payload.items(): + info = info or {} + contacts.append( + Contact( + name=info.get("adv_name", name), + public_key=info.get("public_key", ""), + key_prefix=info.get("public_key", "")[:12], + ) + ) + return contacts + + async def get_tx_power(self) -> Optional[int]: # noqa: D102 - inherited docstring + info = await self.get_self_info() + value = info.get("tx_power") + return int(value) if value is not None else None + + async def set_tx_power(self, value: int) -> None: # noqa: D102 - inherited docstring + mc = self._require() + await mc.commands.set_tx_power(value) + + async def run_trace( # noqa: D102 - inherited docstring + self, + target: str, + *, + path: Optional[list[str]] = None, + timeout: float = 10.0, + ) -> TraceResult: + from meshcore import EventType # local import keeps mock path dependency-free + + 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) + 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 + if event is None: + return TraceResult(target=target, success=False, round_trip_ms=None) + + 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) + ] + return TraceResult( + target=target, + success=True, + hops=hops, + round_trip_ms=elapsed_ms, + tx_power=await self.get_tx_power(), + raw=payload, + ) + + +class MockDevice(Device): + """A deterministic simulator implementing the full :class:`Device` interface. + + The simulated SNR follows an inverted-U response to TX power: too low and the signal + sits in the noise floor, too high and the receiver saturates. This gives the TX + optimizer a realistic, unimodal-with-noise curve to converge on without hardware. + + Attributes: + optimal_tx: The TX power at which the simulated link peaks. + """ + + def __init__(self, seed: int = 1234, optimal_tx: int = 14) -> None: + """Initialize the simulator. + + Args: + seed: RNG seed for reproducible measurement noise. + optimal_tx: TX power level at which simulated SNR is maximized. + """ + self.optimal_tx = optimal_tx + self._rng = random.Random(seed) + self._tx_power = 20 + self._connected = False + self._contacts = [ + Contact(name="Yagi-Repeater", key_prefix="a1b2c3d4"), + Contact(name="Local-Repeater", key_prefix="b2c3d4e5"), + Contact(name="Observer-Bot", key_prefix="c3d4e5f6"), + Contact(name="Alice", key_prefix="d4e5f6a7"), + ] + + async def connect(self) -> None: # noqa: D102 - inherited docstring + await asyncio.sleep(0) + self._connected = True + + async def disconnect(self) -> None: # noqa: D102 - inherited docstring + 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, + } + + async def get_contacts(self) -> list[Contact]: # noqa: D102 - inherited docstring + return list(self._contacts) + + async def get_tx_power(self) -> Optional[int]: # noqa: D102 - inherited docstring + return self._tx_power + + async def set_tx_power(self, value: int) -> None: # noqa: D102 - inherited docstring + self._tx_power = value + + def _expected_snr(self, hop_index: int) -> float: + """Model SNR for a hop as an inverted-U in TX power plus distance falloff. + + Args: + hop_index: Zero-based hop position; deeper hops are weaker. + + Returns: + The noise-free expected SNR in dB for the current TX power. + """ + # Inverted parabola peaking at ``optimal_tx``; ~10 dB swing across the range. + span = (TX_POWER_MAX - TX_POWER_MIN) / 2 + offset = (self._tx_power - self.optimal_tx) / span + peak = 8.0 - 10.0 * (offset**2) + return peak - 2.5 * hop_index + + async def run_trace( # noqa: D102 - inherited docstring + self, + target: str, + *, + path: Optional[list[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) + 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}" + hops.append(Hop(index=i, node=node, snr=round(snr, 1))) + + # Very weak links occasionally drop entirely. + success = (hops[-1].snr if hops else -99) > -12 or self._rng.random() > 0.1 + 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, + ) + + +def clamp_tx_power(value: int) -> int: + """Clamp a TX power value to the supported range. + + Args: + value: Requested TX power level. + + Returns: + ``value`` constrained to ``[TX_POWER_MIN, TX_POWER_MAX]``. + """ + return max(TX_POWER_MIN, min(TX_POWER_MAX, value)) + + +def make_device( + *, + mock: bool, + port: Optional[str], + baudrate: int = 115200, + mock_optimal_tx: int = 14, +) -> Device: + """Construct the appropriate :class:`Device` for the current invocation. + + Args: + mock: When ``True`` return a :class:`MockDevice` simulator. + port: Serial port for a real device. Required unless ``mock`` is set. + baudrate: Serial baud rate for a real device. + mock_optimal_tx: Peak TX power for the simulator. + + Returns: + A connected-on-enter :class:`Device` instance. + + Raises: + ValueError: If a real device is requested without a serial port. + """ + if mock: + return MockDevice(optimal_tx=mock_optimal_tx) + if not port: + raise ValueError( + "No serial port configured. Pass --port, set a profile, or use --mock." + ) + return MeshCoreDevice(port=port, baudrate=baudrate) diff --git a/meshtools/core/device_store.py b/meshtools/core/device_store.py new file mode 100644 index 0000000..f5d1ebf --- /dev/null +++ b/meshtools/core/device_store.py @@ -0,0 +1,98 @@ +"""Persistence for the last successfully connected companion device. + +The "last known good" device is remembered in a small JSON file in the config directory +(``/devices.json``), deliberately *not* in the SQLite database: the database +can be swapped per-invocation with ``--db``, whereas the remembered device is global +machine state that should survive that. The record is matched back to currently attached +hardware by :attr:`~meshtools.core.discovery.DiscoveredDevice.stable_id`. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +from .discovery import DiscoveredDevice +from .models import utcnow + + +@dataclass(slots=True) +class RememberedDevice: + """A previously connected device recorded for next-time defaulting. + + Attributes: + stable_id: The device's :attr:`DiscoveredDevice.stable_id` at connect time. + port: The serial port it was last seen on (informational; may have changed). + label: A friendly label for display in prompts and tables. + last_connected: ISO-8601 timestamp of the last successful connection. + """ + + stable_id: str + port: str + label: str + last_connected: str + + def matches(self, device: DiscoveredDevice) -> bool: + """Return whether ``device`` is the same hardware as this record.""" + return device.stable_id == self.stable_id + + +class DeviceStore: + """Reads and writes the remembered "last known good" device.""" + + def __init__(self, path: Path) -> None: + """Open the store against a JSON file location. + + Args: + path: Path to the JSON state file (created lazily on first write). + """ + self._path = path + + def load(self) -> Optional[RememberedDevice]: + """Return the remembered device, or ``None`` if absent or unreadable. + + A missing or corrupt file is treated as "nothing remembered" rather than an + error, so a stray edit never blocks startup. + + Returns: + The :class:`RememberedDevice`, or ``None``. + """ + try: + data = json.loads(self._path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + try: + return RememberedDevice( + stable_id=data["stable_id"], + port=data["port"], + label=data.get("label", data["port"]), + last_connected=data.get("last_connected", ""), + ) + except (KeyError, TypeError): + return None + + def remember(self, device: DiscoveredDevice) -> None: + """Record ``device`` as the last known good connection. + + Args: + device: The device that just connected successfully. + """ + record = RememberedDevice( + stable_id=device.stable_id, + port=device.port, + label=device.label, + last_connected=utcnow().isoformat(), + ) + self._path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "stable_id": record.stable_id, + "port": record.port, + "label": record.label, + "last_connected": record.last_connected, + } + # Atomic-ish replace so a crash mid-write can't truncate the existing record. + tmp = self._path.with_suffix(self._path.suffix + ".tmp") + tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8") + tmp.replace(self._path) diff --git a/meshtools/core/discovery.py b/meshtools/core/discovery.py new file mode 100644 index 0000000..aac689d --- /dev/null +++ b/meshtools/core/discovery.py @@ -0,0 +1,124 @@ +"""Serial-port enumeration for companion-device discovery. + +Discovery is protocol-agnostic: it lists USB serial ports via ``pyserial`` and flags the +ones whose USB vendor ID matches hardware commonly used for LoRa companion devices +(ESP32/nRF boards and their USB-UART bridges). Nothing is hidden โ€” unrecognized adapters +still appear, just sorted after the likely candidates. + +This module has no UI and no persistent state; it only reads what is currently plugged in. +The companion connection itself still goes through +:class:`~meshtools.core.connection.MeshCoreDevice`. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +# USB vendor IDs frequently seen on MeshCore/Meshtastic companion hardware and the +# USB-UART bridges they ship with. Used only to flag and sort likely devices. +KNOWN_LORA_VIDS: dict[int, str] = { + 0x303A: "Espressif", # ESP32-S3 / native USB (e.g. XIAO ESP32-S3) + 0x10C4: "Silicon Labs", # CP210x UART bridge + 0x1A86: "QinHeng", # CH340 / CH9102 UART bridge + 0x0403: "FTDI", # FT232 UART bridge + 0x239A: "Adafruit", # nRF52840 boards + 0x2886: "Seeed Studio", # XIAO / Wio boards + 0x1915: "Nordic", # nRF52 native USB +} + + +@dataclass(slots=True) +class DiscoveredDevice: + """A serial port found on the system, with USB metadata when available. + + Attributes: + port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``). + description: Human-readable description reported by the OS/driver. + hwid: Raw hardware id string from ``pyserial`` (VID/PID/serial blob). + vid: USB vendor ID, if the port is a USB device. + pid: USB product ID, if the port is a USB device. + serial_number: USB serial number, if exposed by the device. + manufacturer: USB manufacturer string, if available. + product: USB product string, if available. + """ + + port: str + description: str = "" + hwid: str = "" + vid: Optional[int] = None + pid: Optional[int] = None + serial_number: Optional[str] = None + manufacturer: Optional[str] = None + product: Optional[str] = None + + @property + def stable_id(self) -> str: + """Return an identifier stable across replug/reboot. + + Prefers the USB serial number (survives a changed COM number), then the + ``vid:pid`` pair, and finally the port name as a last resort. + + Returns: + A non-empty identifier string used to recognize this device later. + """ + if self.serial_number: + return f"sn:{self.serial_number}" + if self.vid is not None and self.pid is not None: + return f"vidpid:{self.vid:04x}:{self.pid:04x}" + return f"port:{self.port}" + + @property + def is_likely_lora(self) -> bool: + """Whether this device's USB vendor ID matches known companion hardware.""" + return self.vid in KNOWN_LORA_VIDS + + @property + def vendor_label(self) -> str: + """A friendly vendor name from the known-VID table, or the manufacturer string.""" + if self.vid in KNOWN_LORA_VIDS: + return KNOWN_LORA_VIDS[self.vid] + return self.manufacturer or "" + + @property + def label(self) -> str: + """A concise human-friendly label, e.g. ``"Wio SX1262 (COM5)"``.""" + name = self.product or self.description or self.vendor_label or "Serial device" + return f"{name} ({self.port})" + + +def _sort_key(device: DiscoveredDevice) -> tuple[int, str]: + """Sort likely-LoRa devices first, then by port name for stable ordering.""" + return (0 if device.is_likely_lora else 1, device.port) + + +def discover_devices() -> list[DiscoveredDevice]: + """Enumerate serial ports currently attached to the system. + + Likely LoRa companion devices (by known USB vendor ID) are returned first. If + ``pyserial`` is unavailable the function returns an empty list rather than raising, + so callers can fall back to ``--port``/``--mock`` with a friendly message. + + Returns: + Discovered devices, likely candidates first, then sorted by port name. + """ + try: + from serial.tools import list_ports + except ImportError: # pragma: no cover - pyserial is a declared dependency + return [] + + devices = [ + DiscoveredDevice( + port=info.device, + description=info.description or "", + hwid=info.hwid or "", + vid=info.vid, + pid=info.pid, + serial_number=info.serial_number, + manufacturer=info.manufacturer, + product=info.product, + ) + for info in list_ports.comports() + ] + devices.sort(key=_sort_key) + return devices diff --git a/meshtools/core/models.py b/meshtools/core/models.py new file mode 100644 index 0000000..09812fb --- /dev/null +++ b/meshtools/core/models.py @@ -0,0 +1,198 @@ +"""Domain models shared across services, tools, persistence, and visualizations. + +These are plain dataclasses with no I/O dependencies so they can be constructed by the +real device, the simulator, or rehydrated from the database identically. +""" + +from __future__ import annotations + +import statistics +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Optional + + +def utcnow() -> datetime: + """Return a timezone-aware UTC timestamp. + + Returns: + The current time in UTC. + """ + return datetime.now(timezone.utc) + + +@dataclass(slots=True) +class Contact: + """A node known to the connected companion device. + + Attributes: + name: Human-friendly name advertised by the node. + public_key: Full public key hex string, if known. + key_prefix: Short key prefix used to address the node. + last_seen: When the node was last heard, if known. + """ + + name: str + public_key: str = "" + key_prefix: str = "" + last_seen: Optional[datetime] = None + + +@dataclass(slots=True) +class Hop: + """A single hop in a path trace. + + Attributes: + index: Zero-based position of the hop along the path. + node: Identifier of the relaying node (name or key prefix), if resolved. + snr: Signal-to-noise ratio in dB recorded at this hop. + """ + + index: int + node: Optional[str] + snr: float + + +@dataclass(slots=True) +class TraceResult: + """The aggregated outcome of a single path trace to a target. + + Attributes: + target: Name or key prefix of the trace destination. + success: Whether a trace reply was received before timeout. + 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. + timestamp: When the trace completed. + raw: Optional raw event payload for debugging/replay. + """ + + target: str + success: bool + hops: list[Hop] = field(default_factory=list) + round_trip_ms: Optional[float] = None + tx_power: Optional[int] = None + timestamp: datetime = field(default_factory=utcnow) + raw: Optional[dict] = None + + @property + def hop_count(self) -> int: + """Number of hops recorded in the trace.""" + return len(self.hops) + + @property + def min_snr(self) -> Optional[float]: + """The bottleneck (weakest) SNR along the path, or ``None`` if no hops.""" + if not self.hops: + return None + return min(h.snr for h in self.hops) + + @property + def path_str(self) -> str: + """A compact ``a -> b -> c`` rendering of the resolved path.""" + if not self.hops: + return self.target + nodes = [h.node or f"hop{h.index}" for h in self.hops] + return " -> ".join(nodes) + + +@dataclass(slots=True) +class TraceStats: + """Robust statistics aggregated over several traces to the same target. + + Robust (median-based) metrics are used throughout because mesh SNR readings are + noisy and prone to outliers. + + Attributes: + target: The trace destination these statistics describe. + samples: Number of traces attempted. + successes: Number of traces that returned a reply. + 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. + """ + + target: str + samples: int + successes: int + median_min_snr: Optional[float] + median_rtt_ms: Optional[float] + tx_power: Optional[int] = None + + @property + def success_rate(self) -> float: + """Fraction of traces that returned a reply, in the range ``[0, 1]``.""" + return self.successes / self.samples if self.samples else 0.0 + + @classmethod + def from_traces(cls, target: str, traces: list[TraceResult]) -> "TraceStats": + """Aggregate a list of traces into robust statistics. + + Args: + target: The trace destination. + traces: The individual trace results to aggregate. + + Returns: + A :class:`TraceStats` summarizing the supplied traces. + """ + successes = [t for t in traces if t.success] + min_snrs = [t.min_snr for t in successes if t.min_snr is not None] + rtts = [t.round_trip_ms for t in successes if t.round_trip_ms is not None] + tx_powers = {t.tx_power for t in traces if t.tx_power is not None} + return cls( + target=target, + samples=len(traces), + successes=len(successes), + 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, + ) + + +@dataclass(slots=True) +class TxLevelResult: + """Robust measurement of one TX power level during an optimization sweep. + + Attributes: + tx_power: The transmit power level tested. + stats: Aggregated trace statistics at this level. + score: Scalar objective value (higher is better) combining SNR and reliability. + """ + + tx_power: int + stats: TraceStats + score: float + + +@dataclass(slots=True) +class TxOptResult: + """The outcome of a TX-power optimization run. + + Attributes: + target: Node the optimization was tuned against. + original_tx: TX power in effect before the sweep (restored afterward). + best_tx: TX power with the highest score. + best_score: The winning score. + applied: Whether ``best_tx`` was written back to the device. + levels: Every level measured, in the order tested. + """ + + target: str + original_tx: Optional[int] + best_tx: int + best_score: float + applied: bool + levels: list[TxLevelResult] = field(default_factory=list) + + @property + def best_level(self) -> Optional[TxLevelResult]: + """The :class:`TxLevelResult` for ``best_tx``, if present.""" + return next((lv for lv in self.levels if lv.tx_power == self.best_tx), None) + + def sorted_by_tx(self) -> list[TxLevelResult]: + """Return measured levels sorted ascending by TX power. + + Returns: + The levels ordered by TX power, suitable for plotting. + """ + return sorted(self.levels, key=lambda lv: lv.tx_power) diff --git a/meshtools/core/selection.py b/meshtools/core/selection.py new file mode 100644 index 0000000..f72aa60 --- /dev/null +++ b/meshtools/core/selection.py @@ -0,0 +1,116 @@ +"""Non-interactive device selection: turn discovery + memory into a chosen port. + +This is the logic used on the scripted CLI path (and as the fallback when the interactive +picker is unavailable). It is pure and UI-free: it takes the currently discovered devices, +the remembered default, and any explicit overrides, and returns a :class:`Resolution` โ€” or +raises :class:`DeviceSelectionError` with a ready-to-print, user-facing message. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +from .config import DeviceProfile +from .device_store import RememberedDevice +from .discovery import DiscoveredDevice + + +class DeviceSelectionError(ValueError): + """Raised when no device can be chosen unambiguously. + + The message is already formatted for display to the user (it lists the discovered + devices and how to disambiguate), so callers can print ``str(exc)`` directly. + """ + + +@dataclass(slots=True) +class Resolution: + """The outcome of resolving which device to use. + + Attributes: + port: The chosen serial port. + device: The matching discovered device, when enumeration knows it (so the caller + can remember it on a successful connection). ``None`` for an explicit + ``--port``/profile port that is not currently enumerable. + source: Where the choice came from (``"port"``, ``"profile"``, ``"remembered"``, + or ``"only"``), for logging and messaging. + """ + + port: str + device: Optional[DiscoveredDevice] + source: str + + +def _find_by_port(devices: list[DiscoveredDevice], port: str) -> Optional[DiscoveredDevice]: + """Return the discovered device on ``port``, if enumeration found one.""" + return next((d for d in devices if d.port == port), None) + + +def _format_device_list(devices: list[DiscoveredDevice]) -> str: + """Render discovered devices as an indented, human-readable bullet list.""" + if not devices: + return " (no serial devices detected)" + lines = [] + for d in devices: + flag = " [likely LoRa]" if d.is_likely_lora else "" + lines.append(f" โ€ข {d.port} โ€” {d.product or d.description or 'serial device'}{flag}") + return "\n".join(lines) + + +def resolve_device( + devices: list[DiscoveredDevice], + remembered: Optional[RememberedDevice], + *, + explicit_port: Optional[str] = None, + profile: Optional[DeviceProfile] = None, +) -> Resolution: + """Decide which serial port to use without prompting. + + Resolution priority: + + 1. ``explicit_port`` (an explicit ``--port``). + 2. ``profile.port`` (an explicitly chosen profile with a port). + 3. The remembered "last known good" device, if it is currently attached. + 4. The single attached device, if exactly one is present. + + Otherwise a :class:`DeviceSelectionError` is raised listing the candidates. + + Args: + devices: Currently discovered devices (see ``discover_devices``). + remembered: The remembered default, if any. + explicit_port: A serial port supplied on the command line. + profile: A device profile supplied on the command line. + + Returns: + A :class:`Resolution` naming the chosen port. + + Raises: + DeviceSelectionError: If no port can be chosen unambiguously. + """ + if explicit_port: + return Resolution(explicit_port, _find_by_port(devices, explicit_port), "port") + + if profile is not None and profile.port: + return Resolution(profile.port, _find_by_port(devices, profile.port), "profile") + + if remembered is not None: + match = next((d for d in devices if remembered.matches(d)), None) + if match is not None: + return Resolution(match.port, match, "remembered") + + if len(devices) == 1: + return Resolution(devices[0].port, devices[0], "only") + + if not devices: + raise DeviceSelectionError( + "No serial devices detected. Connect a companion device, or pass --port " + "explicitly, or use --mock for the simulator." + ) + + raise DeviceSelectionError( + "Multiple serial devices detected and no default to fall back on.\n" + f"{_format_device_list(devices)}\n" + "Choose one with --port (or run 'meshtools devices' to inspect them). " + "The chosen device is remembered as the default after it connects." + ) diff --git a/meshtools/persistence/__init__.py b/meshtools/persistence/__init__.py new file mode 100644 index 0000000..31891e0 --- /dev/null +++ b/meshtools/persistence/__init__.py @@ -0,0 +1 @@ +"""Persistence layer: SQLite schema, repository, and structured logging.""" diff --git a/meshtools/persistence/db.py b/meshtools/persistence/db.py new file mode 100644 index 0000000..15e1da3 --- /dev/null +++ b/meshtools/persistence/db.py @@ -0,0 +1,104 @@ +"""SQLite database bootstrap and schema. + +The schema is intentionally generic: a central ``runs`` table records every tool +execution (with arguments and a JSON summary), and measurement tables reference it so +new tools can persist data without schema churn. +""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path + +SCHEMA_VERSION = 1 + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS schema_meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +-- One row per tool execution; the spine that measurements hang off of. +CREATE TABLE IF NOT EXISTS runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tool TEXT NOT NULL, + profile TEXT, + args_json TEXT NOT NULL DEFAULT '{}', + status TEXT NOT NULL DEFAULT 'running', -- running | ok | error + summary_json TEXT, + started_at TEXT NOT NULL, + finished_at TEXT +); + +-- Aggregated outcome of a single path trace, linked to its run. +CREATE TABLE IF NOT EXISTS traces ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_id INTEGER NOT NULL REFERENCES runs(id) ON DELETE CASCADE, + target TEXT NOT NULL, + success INTEGER NOT NULL, + hop_count INTEGER NOT NULL DEFAULT 0, + min_snr REAL, + round_trip_ms REAL, + tx_power INTEGER, + created_at TEXT NOT NULL +); + +-- Per-hop SNR for a trace. +CREATE TABLE IF NOT EXISTS trace_hops ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trace_id INTEGER NOT NULL REFERENCES traces(id) ON DELETE CASCADE, + hop_index INTEGER NOT NULL, + node TEXT, + snr REAL NOT NULL +); + +-- One robust sample per (tx_power) tried during TX-power optimization. +CREATE TABLE IF NOT EXISTS tx_samples ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_id INTEGER NOT NULL REFERENCES runs(id) ON DELETE CASCADE, + target TEXT NOT NULL, + tx_power INTEGER NOT NULL, + median_min_snr REAL, + success_rate REAL, + samples INTEGER NOT NULL, + created_at TEXT NOT NULL +); + +-- A candidate path evaluated during path optimization. +CREATE TABLE IF NOT EXISTS path_candidates ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_id INTEGER NOT NULL REFERENCES runs(id) ON DELETE CASCADE, + target TEXT NOT NULL, + path_json TEXT NOT NULL, + bottleneck_snr REAL, + success_rate REAL, + median_rtt_ms REAL, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_traces_run ON traces(run_id); +CREATE INDEX IF NOT EXISTS idx_trace_hops_trace ON trace_hops(trace_id); +CREATE INDEX IF NOT EXISTS idx_tx_samples_run ON tx_samples(run_id); +""" + + +def connect(db_path: Path) -> sqlite3.Connection: + """Open (creating if needed) the SQLite database and ensure the schema exists. + + Args: + db_path: Filesystem location of the database. Parent directories are created. + + Returns: + An open connection with ``Row`` factory and foreign keys enabled. + """ + db_path.parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(db_path) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON;") + conn.executescript(_SCHEMA) + conn.execute( + "INSERT OR REPLACE INTO schema_meta(key, value) VALUES ('version', ?)", + (str(SCHEMA_VERSION),), + ) + conn.commit() + return conn diff --git a/meshtools/persistence/logging.py b/meshtools/persistence/logging.py new file mode 100644 index 0000000..e72855c --- /dev/null +++ b/meshtools/persistence/logging.py @@ -0,0 +1,93 @@ +"""Structured logging setup. + +Two sinks are configured: a Rich-formatted console handler for human-readable output, +and a JSON-lines file handler that captures every record for later replay/analysis. +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +from typing import Optional + +from rich.console import Console +from rich.logging import RichHandler + +_LOGGER_NAME = "meshtools" + + +class JsonlFormatter(logging.Formatter): + """Format log records as one JSON object per line.""" + + def format(self, record: logging.LogRecord) -> str: + """Serialize a log record to a compact JSON string. + + Args: + record: The record to format. + + Returns: + A single-line JSON document. + """ + payload = { + "ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"), + "level": record.levelname, + "logger": record.name, + "msg": record.getMessage(), + } + if record.exc_info: + payload["exc"] = self.formatException(record.exc_info) + return json.dumps(payload) + + +def configure_logging( + console: Console, + log_dir: Path, + *, + level: int = logging.INFO, + quiet: bool = False, +) -> logging.Logger: + """Configure and return the application logger. + + Args: + console: The Rich console the handler should render to. + log_dir: Directory for the ``meshtools.log.jsonl`` event file. + level: Console log level. + quiet: When ``True``, suppress console output (file logging continues). + + Returns: + The configured ``meshtools`` logger. + """ + logger = logging.getLogger(_LOGGER_NAME) + logger.setLevel(logging.DEBUG) + logger.handlers.clear() + logger.propagate = False + + if not quiet: + rich_handler = RichHandler( + console=console, rich_tracebacks=True, show_path=False, markup=True + ) + rich_handler.setLevel(level) + logger.addHandler(rich_handler) + + log_dir.mkdir(parents=True, exist_ok=True) + file_handler = logging.FileHandler(log_dir / "meshtools.log.jsonl", encoding="utf-8") + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(JsonlFormatter()) + logger.addHandler(file_handler) + + return logger + + +def get_logger(name: Optional[str] = None) -> logging.Logger: + """Return a child of the application logger. + + Args: + name: Optional child name; when ``None`` the root app logger is returned. + + Returns: + The requested logger. + """ + if name is None: + return logging.getLogger(_LOGGER_NAME) + return logging.getLogger(f"{_LOGGER_NAME}.{name}") diff --git a/meshtools/persistence/repository.py b/meshtools/persistence/repository.py new file mode 100644 index 0000000..7dc0a91 --- /dev/null +++ b/meshtools/persistence/repository.py @@ -0,0 +1,182 @@ +"""Repository: the single gateway between the app and the database. + +Tools and services never issue SQL directly; they call typed methods here. This keeps +persistence concerns in one place and makes the storage backend swappable. +""" + +from __future__ import annotations + +import json +import sqlite3 +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional + +from ..core.models import TraceResult, TraceStats, utcnow +from . import db + + +@dataclass(slots=True) +class RunRecord: + """A summary row from the ``runs`` table. + + Attributes: + id: Primary key of the run. + tool: Name of the tool that executed. + profile: Device profile used, if any. + status: ``running``, ``ok``, or ``error``. + started_at: ISO-8601 start timestamp. + finished_at: ISO-8601 finish timestamp, or ``None`` if still running. + summary: Decoded JSON summary, or ``None``. + """ + + id: int + tool: str + profile: Optional[str] + status: str + started_at: str + finished_at: Optional[str] + summary: Optional[dict] + + +class Repository: + """Typed data-access layer over the SQLite database.""" + + def __init__(self, db_path: Path) -> None: + """Open the repository against a database file. + + Args: + db_path: Location of the SQLite database (created if absent). + """ + self._conn = db.connect(db_path) + + def close(self) -> None: + """Close the underlying database connection.""" + self._conn.close() + + # -- runs ------------------------------------------------------------------- + + def start_run( + self, tool: str, args: dict[str, Any], profile: Optional[str] = None + ) -> int: + """Record the start of a tool execution. + + Args: + tool: Tool name. + args: Arguments the tool was invoked with (must be JSON-serializable). + profile: Active device profile name, if any. + + Returns: + The new run's primary key. + """ + cur = self._conn.execute( + "INSERT INTO runs (tool, profile, args_json, status, started_at) " + "VALUES (?, ?, ?, 'running', ?)", + (tool, profile, json.dumps(args, default=str), utcnow().isoformat()), + ) + self._conn.commit() + return int(cur.lastrowid) + + def finish_run(self, run_id: int, status: str, summary: Optional[dict] = None) -> None: + """Mark a run as finished. + + Args: + run_id: The run to update. + status: Terminal status (``ok`` or ``error``). + summary: Optional JSON-serializable result summary. + """ + self._conn.execute( + "UPDATE runs SET status = ?, summary_json = ?, finished_at = ? WHERE id = ?", + ( + status, + json.dumps(summary, default=str) if summary is not None else None, + utcnow().isoformat(), + run_id, + ), + ) + self._conn.commit() + + def list_runs(self, limit: int = 50) -> list[RunRecord]: + """Return the most recent runs, newest first. + + Args: + limit: Maximum number of rows to return. + + Returns: + A list of :class:`RunRecord`. + """ + rows = self._conn.execute( + "SELECT * FROM runs ORDER BY id DESC LIMIT ?", (limit,) + ).fetchall() + return [self._row_to_run(r) for r in rows] + + @staticmethod + def _row_to_run(row: sqlite3.Row) -> RunRecord: + """Map a ``runs`` row to a :class:`RunRecord`.""" + return RunRecord( + id=row["id"], + tool=row["tool"], + profile=row["profile"], + status=row["status"], + started_at=row["started_at"], + finished_at=row["finished_at"], + summary=json.loads(row["summary_json"]) if row["summary_json"] else None, + ) + + # -- traces ----------------------------------------------------------------- + + def record_trace(self, run_id: int, trace: TraceResult) -> int: + """Persist a single trace and its per-hop SNR readings. + + Args: + run_id: The owning run. + trace: The trace result to store. + + Returns: + The new trace's primary key. + """ + cur = self._conn.execute( + "INSERT INTO traces " + "(run_id, target, success, hop_count, min_snr, round_trip_ms, tx_power, created_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + ( + run_id, + trace.target, + int(trace.success), + trace.hop_count, + trace.min_snr, + trace.round_trip_ms, + trace.tx_power, + trace.timestamp.isoformat(), + ), + ) + trace_id = int(cur.lastrowid) + self._conn.executemany( + "INSERT INTO trace_hops (trace_id, hop_index, node, snr) VALUES (?, ?, ?, ?)", + [(trace_id, h.index, h.node, h.snr) for h in trace.hops], + ) + self._conn.commit() + return trace_id + + def record_tx_sample(self, run_id: int, stats: TraceStats) -> None: + """Persist one robust TX-power sample from an optimization sweep. + + Args: + run_id: The owning run. + stats: Aggregated trace statistics for a single TX power level. + """ + self._conn.execute( + "INSERT INTO tx_samples " + "(run_id, target, tx_power, median_min_snr, success_rate, samples, created_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + run_id, + stats.target, + stats.tx_power, + stats.median_min_snr, + stats.success_rate, + stats.samples, + utcnow().isoformat(), + ), + ) + self._conn.commit() diff --git a/meshtools/services/__init__.py b/meshtools/services/__init__.py new file mode 100644 index 0000000..f907e1a --- /dev/null +++ b/meshtools/services/__init__.py @@ -0,0 +1,6 @@ +"""Algorithm layer: pure logic for tracing, TX search, and path exploration. + +Services depend on the :class:`~meshtools.core.connection.Device` interface and domain +models only. They contain no UI or persistence code, so they are straightforward to unit +test against the simulator. +""" diff --git a/meshtools/services/trace_runner.py b/meshtools/services/trace_runner.py new file mode 100644 index 0000000..e159f54 --- /dev/null +++ b/meshtools/services/trace_runner.py @@ -0,0 +1,96 @@ +"""Repeated-trace execution with robust aggregation and duty-cycle pacing. + +This is the measurement primitive both the trace tool and the TX/path optimizers build +on: run a trace N times, optionally reporting progress, and aggregate into robust +statistics while persisting every individual trace. +""" + +from __future__ import annotations + +import asyncio +from typing import Awaitable, Callable, Optional + +from ..core.connection import Device +from ..core.models import TraceResult, TraceStats + +ProgressCallback = Callable[[int, int, TraceResult], None] + + +async def run_traces( + device: Device, + target: str, + *, + samples: int = 5, + path: Optional[list[str]] = None, + cooldown_s: float = 1.0, + timeout: float = 10.0, + on_result: Optional[ProgressCallback] = None, + persist: Optional[Callable[[TraceResult], Awaitable[None] | None]] = None, +) -> list[TraceResult]: + """Run ``samples`` traces to ``target`` with pacing between transmissions. + + Args: + device: The connected device to trace through. + target: Destination node name or key prefix. + samples: Number of traces to run. + path: Optional explicit path to force on every trace. + cooldown_s: Delay between traces to respect radio duty cycle. + timeout: Per-trace reply timeout in seconds. + on_result: Optional callback invoked as ``(completed, total, result)`` after + each trace, e.g. to advance a progress bar. + persist: Optional callback to store each trace (sync or async). + + Returns: + The list of individual :class:`TraceResult` objects, in order. + """ + results: list[TraceResult] = [] + for i in range(samples): + result = await device.run_trace(target, path=path, timeout=timeout) + results.append(result) + + if persist is not None: + maybe = persist(result) + if asyncio.iscoroutine(maybe): + await maybe + if on_result is not None: + on_result(i + 1, samples, result) + + if i < samples - 1 and cooldown_s > 0: + await asyncio.sleep(cooldown_s) + return results + + +async def measure( + device: Device, + target: str, + *, + samples: int = 5, + path: Optional[list[str]] = None, + cooldown_s: float = 1.0, + on_result: Optional[ProgressCallback] = None, + persist: Optional[Callable[[TraceResult], Awaitable[None] | None]] = None, +) -> TraceStats: + """Run traces and return their robust aggregate statistics. + + Args: + device: The connected device to trace through. + target: Destination node name or key prefix. + samples: Number of traces to run. + path: Optional explicit path to force. + cooldown_s: Delay between traces. + on_result: Optional per-trace progress callback. + persist: Optional per-trace persistence callback. + + Returns: + A :class:`TraceStats` summarizing the run. + """ + results = await run_traces( + device, + target, + samples=samples, + path=path, + cooldown_s=cooldown_s, + on_result=on_result, + persist=persist, + ) + return TraceStats.from_traces(target, results) diff --git a/meshtools/services/tx_optimizer.py b/meshtools/services/tx_optimizer.py new file mode 100644 index 0000000..1e2c0a8 --- /dev/null +++ b/meshtools/services/tx_optimizer.py @@ -0,0 +1,157 @@ +"""TX-power optimization. + +The transmit-power response is non-monotonic: too low and the signal sits in the noise +floor, too high and the receiver saturates. The optimum is therefore an interior peak, +and trace measurements are noisy, so this module uses a robust two-phase search: + +1. A **coarse sweep** across the TX range at a fixed step, taking several traces per + level and scoring each level by a reliability-weighted median bottleneck SNR. +2. A **local refine** that fills in every integer level around the coarse winner, so the + reported optimum is exact within the bracket without paying for a full fine sweep. + +The device's original TX power is always restored when the sweep finishes; writing the +winner back is the caller's decision. +""" + +from __future__ import annotations + +from typing import Callable, Optional + +from ..core.connection import Device, clamp_tx_power +from ..core.models import TraceStats, TxLevelResult, TxOptResult +from . import trace_runner + +#: How many dB of SNR a fully-unreliable link is penalized, blending reliability into +#: the scalar objective so a strong-but-flaky level cannot beat a solid one. +RELIABILITY_PENALTY_DB = 10.0 + +LevelCallback = Callable[[int, int, TxLevelResult], None] +PersistLevel = Callable[[TraceStats], None] + + +def score_level(stats: TraceStats) -> float: + """Score a measured TX level; higher is better. + + Combines the robust bottleneck SNR with the success rate so an intermittently + failing level cannot outrank a reliable one. + + Args: + stats: Aggregated trace statistics for the level. + + Returns: + The scalar objective value, or negative infinity if nothing got through. + """ + if stats.successes == 0 or stats.median_min_snr is None: + return float("-inf") + return stats.median_min_snr - (1.0 - stats.success_rate) * RELIABILITY_PENALTY_DB + + +async def optimize_tx_power( + device: Device, + target: str, + *, + tx_min: int = 1, + tx_max: int = 22, + coarse_step: int = 3, + samples_per_level: int = 5, + refine: bool = True, + cooldown_s: float = 1.0, + on_level: Optional[LevelCallback] = None, + persist_level: Optional[PersistLevel] = None, + persist_trace: Optional[Callable] = None, +) -> TxOptResult: + """Search for the TX power that maximizes the reliability-weighted SNR to ``target``. + + Args: + device: Connected device to tune. + target: Destination node name or key prefix. + tx_min: Lowest TX power to consider (clamped to the device range). + tx_max: Highest TX power to consider (clamped to the device range). + coarse_step: Step between coarse-sweep levels. + samples_per_level: Traces averaged at each level. + refine: Whether to fill in integer levels around the coarse winner. + cooldown_s: Delay between individual traces (duty-cycle safety). + on_level: Optional progress callback ``(completed, total, level_result)``. + persist_level: Optional callback to store each level's aggregated stats. + persist_trace: Optional callback to store each individual trace. + + Returns: + A :class:`TxOptResult`. The device is left at its original TX power. + + Raises: + ValueError: If the resolved TX range is empty. + """ + tx_min = clamp_tx_power(tx_min) + tx_max = clamp_tx_power(tx_max) + if tx_min > tx_max: + raise ValueError(f"Empty TX range: {tx_min}..{tx_max}") + + original_tx = await device.get_tx_power() + measured: dict[int, TxLevelResult] = {} + + # Phase 1 + 2 share this planner so progress totals stay accurate. + coarse = _coarse_levels(tx_min, tx_max, coarse_step) + total_estimate = len(coarse) + (2 * coarse_step if refine else 0) + completed = 0 + + async def measure_level(tx: int) -> TxLevelResult: + nonlocal completed + await device.set_tx_power(tx) + stats = await trace_runner.measure( + device, + target, + samples=samples_per_level, + cooldown_s=cooldown_s, + persist=persist_trace, + ) + level = TxLevelResult(tx_power=tx, stats=stats, score=score_level(stats)) + measured[tx] = level + if persist_level is not None: + persist_level(stats) + completed += 1 + if on_level is not None: + on_level(completed, max(total_estimate, completed), level) + return level + + try: + for tx in coarse: + await measure_level(tx) + + best_tx = max(measured, key=lambda t: measured[t].score) + + if refine: + lo = clamp_tx_power(best_tx - coarse_step + 1) + hi = clamp_tx_power(best_tx + coarse_step - 1) + for tx in range(lo, hi + 1): + if tx not in measured: + await measure_level(tx) + best_tx = max(measured, key=lambda t: measured[t].score) + finally: + if original_tx is not None: + await device.set_tx_power(original_tx) + + return TxOptResult( + target=target, + original_tx=original_tx, + best_tx=best_tx, + best_score=measured[best_tx].score, + applied=False, + levels=list(measured.values()), + ) + + +def _coarse_levels(tx_min: int, tx_max: int, step: int) -> list[int]: + """Build the coarse sweep grid, always including both endpoints. + + Args: + tx_min: Lowest TX power. + tx_max: Highest TX power. + step: Grid spacing. + + Returns: + The ascending list of TX levels to sample in the coarse phase. + """ + levels = list(range(tx_min, tx_max + 1, max(1, step))) + if levels[-1] != tx_max: + levels.append(tx_max) + return levels diff --git a/meshtools/tools/__init__.py b/meshtools/tools/__init__.py new file mode 100644 index 0000000..50ea32b --- /dev/null +++ b/meshtools/tools/__init__.py @@ -0,0 +1,30 @@ +"""Pluggable tools (menu options / CLI subcommands). + +Importing this package eagerly imports every tool module so that each one's ``@register`` +decorator populates the shared registry. New features only need to add a module here. +""" + +from __future__ import annotations + +import importlib +import pkgutil + +from .base import Tool, all_tools, get_tool, register + +__all__ = ["Tool", "all_tools", "get_tool", "register", "load_all_tools"] + + +def load_all_tools() -> None: + """Import every sibling module so its tools self-register. + + Modules whose names start with an underscore (and ``base``) are skipped. + """ + package = __name__ + for mod in pkgutil.iter_modules(__path__): + if mod.name.startswith("_") or mod.name == "base": + continue + importlib.import_module(f"{package}.{mod.name}") + + +# Populate the registry on import so the CLI and menu see every tool. +load_all_tools() diff --git a/meshtools/tools/base.py b/meshtools/tools/base.py new file mode 100644 index 0000000..c45d395 --- /dev/null +++ b/meshtools/tools/base.py @@ -0,0 +1,171 @@ +"""The tool plugin contract and registry. + +A *tool* is one menu option / CLI subcommand. Subclass :class:`Tool`, decorate it with +:func:`register`, and implement :meth:`Tool.run`. The same registry drives both the +interactive menu and the Typer CLI, and :meth:`Tool.execute` wraps every invocation in a +logged ``runs`` row, so new tools get persistence and logging for free. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Optional + +if TYPE_CHECKING: # avoid importing typer/context at module load for fast startup + import typer + + from ..context import AppContext + + +@dataclass(slots=True) +class ToolResult: + """The outcome of a tool execution. + + Attributes: + summary: JSON-serializable summary persisted to the run record. + message: Optional human-readable closing message. + artifacts: Paths to any files produced (e.g. generated visualizations). + """ + + summary: dict[str, Any] = field(default_factory=dict) + message: Optional[str] = None + artifacts: list[str] = field(default_factory=list) + + +class Tool(ABC): + """Base class for all MeshTools features. + + Class Attributes: + name: CLI/menu identifier (kebab-case), unique across tools. + help: One-line description shown in the menu and ``--help``. + category: Grouping label used to organize the interactive menu. + order: Sort key within a category (lower sorts first). + """ + + name: str = "" + help: str = "" + category: str = "General" + order: int = 100 + + @abstractmethod + async def run(self, ctx: "AppContext", params: dict[str, Any]) -> ToolResult: + """Execute the tool's work. + + Args: + ctx: Shared application context (console, device, repository, ...). + params: Validated parameters for this invocation. + + Returns: + A :class:`ToolResult` describing the outcome. + """ + + async def prompt_params(self, ctx: "AppContext") -> dict[str, Any]: + """Interactively gather parameters for the menu. + + The default implementation requires no parameters. Tools override this to ask + the user via ``questionary``. + + Args: + ctx: Shared application context. + + Returns: + A parameter dict compatible with :meth:`run`. + """ + return {} + + def register_cli(self, app: "typer.Typer") -> None: + """Register this tool as a Typer subcommand. + + The default registers a no-argument command. Tools with parameters override this + to declare typed options, then delegate to :meth:`execute`. + + Args: + app: The Typer application to add the command to. + """ + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _command() -> None: + run_tool_command(self, {}) + + async def execute(self, ctx: "AppContext", params: dict[str, Any]) -> ToolResult: + """Run the tool wrapped in run-logging and error capture. + + Opens a ``runs`` row before execution and closes it with the final status and + summary afterward, regardless of success. + + Args: + ctx: Shared application context. + params: Parameters for this invocation. + + Returns: + The :class:`ToolResult` from :meth:`run`. + + Raises: + Exception: Re-raises any error from :meth:`run` after recording it. + """ + 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. + ctx.repo.finish_run(run_id, "error", {"error": str(exc)}) + ctx.log.debug("run %s aborted: %s", run_id, exc) + raise + except Exception as exc: # noqa: BLE001 - we record then re-raise + ctx.repo.finish_run(run_id, "error", {"error": str(exc)}) + ctx.log.exception("run %s failed: %s", run_id, exc) + raise + ctx.repo.finish_run(run_id, "ok", result.summary) + ctx.log.debug("run %s ok", run_id) + return result + + +_REGISTRY: dict[str, Tool] = {} + + +def register(cls: type[Tool]) -> type[Tool]: + """Class decorator that instantiates a tool and adds it to the registry. + + Args: + cls: The :class:`Tool` subclass to register. + + Returns: + The unchanged class (so the decorator is transparent). + + Raises: + ValueError: If the tool has no ``name`` or the name is already registered. + """ + instance = cls() + if not instance.name: + raise ValueError(f"{cls.__name__} must define a non-empty 'name'.") + if instance.name in _REGISTRY: + raise ValueError(f"Duplicate tool name: {instance.name!r}") + _REGISTRY[instance.name] = instance + return cls + + +def all_tools() -> list[Tool]: + """Return all registered tools sorted by category then order then name. + + Returns: + The registered tool instances in stable menu order. + """ + return sorted(_REGISTRY.values(), key=lambda t: (t.category, t.order, t.name)) + + +def get_tool(name: str) -> Optional[Tool]: + """Look up a registered tool by name. + + Args: + name: The tool's ``name``. + + Returns: + The tool instance, or ``None`` if not registered. + """ + return _REGISTRY.get(name) diff --git a/meshtools/tools/devices.py b/meshtools/tools/devices.py new file mode 100644 index 0000000..1ba7beb --- /dev/null +++ b/meshtools/tools/devices.py @@ -0,0 +1,139 @@ +"""The ``devices`` tool: enumerate serial companion devices and (in the menu) pick one. + +Discovery never opens the radio โ€” it only lists what is attached. On the CLI this is a +read-only inventory; selection there happens by passing ``--port`` to a command, which is +remembered after it connects. In the interactive menu this tool additionally offers the +device picker to change the session's active device. +""" + +from __future__ import annotations + +from typing import Any + +import typer +from rich.table import Table + +from ..context import AppContext +from ..core.discovery import discover_devices +from .base import Tool, ToolResult, register + + +@register +class DevicesTool(Tool): + """List attached serial devices, flag likely LoRa hardware, mark the default.""" + + name = "devices" + help = "List attached serial devices and pick the companion to use." + category = "Device" + order = 5 + + async def prompt_params(self, ctx: AppContext) -> dict[str, Any]: + """In the menu, offer to change the session's active device. + + Args: + ctx: Shared application context. + + Returns: + ``{"select": True}`` when the user opted to re-pick a device, else ``{}``. + """ + import questionary + + if ctx.mock: + return {} + change = await questionary.confirm( + "Change the active companion device?", default=False + ).ask_async() + if not change: + return {} + + from ..ui.device_picker import prompt_device + + devices = discover_devices() + chosen = await prompt_device(ctx.console, devices, ctx.device_store.load()) + if chosen is not None: + ctx.selected_device = chosen + ctx.port_override = chosen.port + ctx.console.print( + f"[ok]โ—[/ok] active device set to [accent]{chosen.label}[/accent] " + "[muted](remembered once it connects)[/muted]" + ) + return {"select": True} + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Enumerate serial devices and render them as a table. + + Args: + ctx: Shared application context. + params: Unused beyond the menu's selection bookkeeping. + + Returns: + A :class:`ToolResult` summarizing how many devices were found. + """ + devices = discover_devices() + remembered = ctx.device_store.load() + active = ctx.selected_device + active_port = ctx.port_override or (active.port if active else None) + + if ctx.json_output: + import json + + payload = [ + { + "port": d.port, + "label": d.label, + "vendor": d.vendor_label, + "likely_lora": d.is_likely_lora, + "serial_number": d.serial_number, + "stable_id": d.stable_id, + "remembered": remembered is not None and remembered.matches(d), + "active": d.port == active_port, + } + for d in devices + ] + ctx.console.print_json(json.dumps(payload)) + return ToolResult(summary={"count": len(devices)}) + + if not devices: + ctx.console.print( + "[warn]No serial devices detected.[/warn] " + "Connect a companion device, or use [accent]--mock[/accent] for the simulator." + ) + return ToolResult(summary={"count": 0}) + + table = Table(title="Serial devices", border_style="muted", expand=False) + table.add_column("", style="ok", no_wrap=True) # active/remembered markers + table.add_column("Port", style="brand") + table.add_column("Device") + table.add_column("Vendor", style="muted") + table.add_column("LoRa?", justify="center") + table.add_column("Serial", style="muted") + for d in devices: + is_remembered = remembered is not None and remembered.matches(d) + is_active = d.port == active_port + marker = ("โ—" if is_active else "") + ("โ˜…" if is_remembered else "") + table.add_row( + marker, + d.port, + d.product or d.description or "[muted]?[/muted]", + d.vendor_label or "[muted]?[/muted]", + "[ok]yes[/ok]" if d.is_likely_lora else "[muted]โ€”[/muted]", + d.serial_number or "[muted]โ€”[/muted]", + ) + ctx.console.print(table) + ctx.console.print( + "[muted]โ— active โ˜… remembered default. " + "Pass --port to select on the CLI.[/muted]" + ) + return ToolResult(summary={"count": len(devices)}) + + def register_cli(self, app: typer.Typer) -> None: + """Register the ``devices`` subcommand (inventory only; no connection). + + Args: + app: The Typer application. + """ + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _devices() -> None: + run_tool_command(self, {}) diff --git a/meshtools/tools/history.py b/meshtools/tools/history.py new file mode 100644 index 0000000..0c0c5f0 --- /dev/null +++ b/meshtools/tools/history.py @@ -0,0 +1,68 @@ +"""The ``history`` tool: browse logged tool executions from the database.""" + +from __future__ import annotations + +from typing import Any + +import typer +from rich.table import Table + +from ..context import AppContext +from .base import Tool, ToolResult, register + +_STATUS_STYLE = {"ok": "ok", "error": "err", "running": "warn"} + + +@register +class HistoryTool(Tool): + """List recent runs recorded in the database (no device needed).""" + + name = "history" + help = "Show recent tool executions and their outcomes." + category = "Data" + order = 10 + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Render the most recent runs as a table. + + Args: + ctx: Shared application context. + params: Optional ``limit`` (int) controlling row count. + + Returns: + A :class:`ToolResult` noting how many runs were shown. + """ + limit = int(params.get("limit", 20)) + runs = ctx.repo.list_runs(limit=limit) + + table = Table(title=f"Recent runs (last {limit})", border_style="muted") + table.add_column("#", justify="right", style="muted") + table.add_column("Tool", style="brand") + table.add_column("Profile", style="muted") + table.add_column("Status") + table.add_column("Started") + for r in runs: + style = _STATUS_STYLE.get(r.status, "muted") + table.add_row( + str(r.id), + r.tool, + r.profile or "-", + f"[{style}]{r.status}[/{style}]", + r.started_at.replace("T", " ")[:19], + ) + ctx.console.print(table) + return ToolResult(summary={"shown": len(runs)}) + + def register_cli(self, app: typer.Typer) -> None: + """Register the ``history`` subcommand. + + Args: + app: The Typer application. + """ + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _history( + limit: int = typer.Option(20, "--limit", "-n", help="Number of runs to show."), + ) -> None: + run_tool_command(self, {"limit": limit}) diff --git a/meshtools/tools/info.py b/meshtools/tools/info.py new file mode 100644 index 0000000..3bf37ab --- /dev/null +++ b/meshtools/tools/info.py @@ -0,0 +1,67 @@ +"""The ``info`` tool: show the connected companion device's identity and contacts.""" + +from __future__ import annotations + +from typing import Any + +import typer +from rich.table import Table + +from ..context import AppContext +from .base import Tool, ToolResult, register + + +@register +class InfoTool(Tool): + """Display device identity, radio configuration, and known contacts.""" + + name = "info" + help = "Show device identity, radio config, and contacts." + category = "Device" + order = 10 + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Query the device and render its self-info and contacts. + + Args: + ctx: Shared application context. + params: Unused. + + Returns: + A :class:`ToolResult` summarizing device name and contact count. + """ + device = await ctx.device() + info = await device.get_self_info() + 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) + + if contacts: + ctable = Table(title=f"Contacts ({len(contacts)})", border_style="muted") + ctable.add_column("Name", style="brand") + ctable.add_column("Key prefix", style="muted") + for c in contacts: + ctable.add_row(c.name, c.key_prefix or "[muted]?[/muted]") + ctx.console.print(ctable) + + return ToolResult( + summary={"name": info.get("name"), "contacts": len(contacts)}, + ) + + def register_cli(self, app: typer.Typer) -> None: + """Register the ``info`` subcommand. + + Args: + app: The Typer application. + """ + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _info() -> None: + run_tool_command(self, {}) diff --git a/meshtools/tools/trace.py b/meshtools/tools/trace.py new file mode 100644 index 0000000..fc3557f --- /dev/null +++ b/meshtools/tools/trace.py @@ -0,0 +1,137 @@ +"""The ``trace`` tool: run repeated path traces and report aggregated SNR. + +This is the measurement workhorse of the skeleton and the template every other tool +follows: it gathers params (interactively or from CLI flags), runs a service, persists +results, and renders modern Rich output. +""" + +from __future__ import annotations + +from typing import Any, Optional + +import questionary +import typer + +from ..context import AppContext +from ..services import trace_runner +from ..ui.widgets import make_progress, stats_panel, trace_table +from .base import Tool, ToolResult, register + + +@register +class TraceTool(Tool): + """Trace the path to a target N times and summarize per-hop SNR.""" + + name = "trace" + help = "Run repeated path traces to a target and aggregate SNR." + category = "Diagnostics" + order = 10 + + async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]: + """Interactively choose a target contact and sample count. + + Args: + ctx: Shared application context. + + Returns: + A parameter dict, or ``None`` if the user cancelled. + """ + device = await ctx.device() + contacts = await device.get_contacts() + choices = [c.name for c in contacts] + prompt = "Target node (name or key prefix):" + # ``autocomplete`` requires a non-empty choice list; with no known contacts fall + # back to a free-text entry so the user can still type a name or key prefix. + if choices: + target = await questionary.autocomplete( + prompt, choices=choices, ignore_case=True + ).ask_async() + else: + target = await questionary.text(prompt).ask_async() + if not target: + return None + + samples_raw = await questionary.text( + "How many traces?", default="5", validate=_is_positive_int + ).ask_async() + if samples_raw is None: + return None + return {"target": target.strip(), "samples": int(samples_raw)} + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Run the traces, persist each one, and render the summary. + + Args: + ctx: Shared application context. + params: ``target`` (str), ``samples`` (int), and the injected ``_run_id``. + + Returns: + A :class:`ToolResult` with the aggregated statistics. + """ + target = params["target"] + samples = int(params.get("samples", 5)) + run_id = params["_run_id"] + device = await ctx.device() + + last_trace = None + 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 + progress.advance(task) + + stats = await trace_runner.measure( + device, + target, + samples=samples, + 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)) + + 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}", + ) + + def register_cli(self, app: typer.Typer) -> None: + """Register the ``trace`` subcommand. + + Args: + app: The Typer application. + """ + from ..cli import run_tool_command + + @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."), + ) -> None: + run_tool_command(self, {"target": target, "samples": samples}) + + +def _is_positive_int(value: str) -> bool | str: + """Validate that a questionary text answer is a positive integer. + + Args: + value: The raw user input. + + Returns: + ``True`` if valid, otherwise an error message string. + """ + try: + return int(value) > 0 or "Enter a number greater than zero." + except ValueError: + return "Enter a whole number." diff --git a/meshtools/tools/tx_optimize.py b/meshtools/tools/tx_optimize.py new file mode 100644 index 0000000..e5822c2 --- /dev/null +++ b/meshtools/tools/tx_optimize.py @@ -0,0 +1,205 @@ +"""The ``tx-optimize`` tool: sweep transmit power and converge on the best setting. + +Wraps :func:`meshtools.services.tx_optimizer.optimize_tx_power` with interactive prompts, +a live progress bar, persistence of every level, an interactive HTML chart, and an opt-in +apply step (changing the radio's TX power is a hardware change, so it is never implicit). +""" + +from __future__ import annotations + +from typing import Any, Optional + +import questionary +import typer + +from ..context import AppContext +from ..core.connection import TX_POWER_MAX, TX_POWER_MIN +from ..services import tx_optimizer +from ..ui.widgets import make_progress, tx_opt_summary, tx_opt_table +from ..viz.tx_plot import render_tx_optimization +from .base import Tool, ToolResult, register + + +@register +class TxOptimizeTool(Tool): + """Find the transmit power with the strongest, most reliable signal to a target.""" + + name = "tx-optimize" + help = "Sweep TX power and converge on the value with the best signal." + category = "Optimization" + order = 10 + + async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]: + """Interactively gather target, range, sampling, and apply choices. + + Args: + ctx: Shared application context. + + Returns: + A parameter dict, or ``None`` if the user cancelled. + """ + device = await ctx.device() + contacts = await device.get_contacts() + choices = [c.name for c in contacts] + prompt = "Target node to optimize against:" + # ``autocomplete`` requires a non-empty choice list; with no known contacts fall + # back to a free-text entry so the user can still type a name or key prefix. + if choices: + target = await questionary.autocomplete( + prompt, choices=choices, ignore_case=True + ).ask_async() + else: + target = await questionary.text(prompt).ask_async() + if not target: + return None + + samples = await questionary.text( + "Traces per TX level:", default="5", validate=_positive_int + ).ask_async() + if samples is None: + return None + step = await questionary.text( + "Coarse step:", default="3", validate=_positive_int + ).ask_async() + if step is None: + return None + refine = await questionary.confirm( + "Refine around the best level?", default=True + ).ask_async() + apply = await questionary.confirm( + "Apply the winning TX power to the device afterward?", default=False + ).ask_async() + + return { + "target": target.strip(), + "samples": int(samples), + "step": int(step), + "refine": bool(refine), + "apply": bool(apply), + "tx_min": TX_POWER_MIN, + "tx_max": TX_POWER_MAX, + "viz": True, + } + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Run the sweep, persist levels, render results, and optionally apply the winner. + + Args: + ctx: Shared application context. + params: ``target``, ``samples``, ``step``, ``refine``, ``apply``, + ``tx_min``, ``tx_max``, ``viz``, and the injected ``_run_id``. + + Returns: + A :class:`ToolResult` with the optimum and the chart path. + """ + target = params["target"] + run_id = params["_run_id"] + device = await ctx.device() + + with make_progress(ctx.console) as progress: + task = progress.add_task(f"optimizing TX -> {target}", total=None) + + def on_level(done: int, total: int, level) -> None: # noqa: ANN001 + progress.update( + task, total=total, completed=done, + description=f"TX {level.tx_power:>2} " + f"SNR {_fmt_snr(level.stats.median_min_snr)}", + ) + + result = await tx_optimizer.optimize_tx_power( + device, + target, + tx_min=int(params.get("tx_min", TX_POWER_MIN)), + tx_max=int(params.get("tx_max", TX_POWER_MAX)), + coarse_step=int(params.get("step", 3)), + samples_per_level=int(params.get("samples", 5)), + refine=bool(params.get("refine", True)), + cooldown_s=ctx.settings.trace_cooldown_s, + on_level=on_level, + persist_level=lambda stats: ctx.repo.record_tx_sample(run_id, stats), + persist_trace=lambda t: ctx.repo.record_trace(run_id, t), + ) + + if params.get("apply"): + await device.set_tx_power(result.best_tx) + result.applied = True + ctx.log.info("applied TX power %s to device", result.best_tx) + + ctx.console.print(tx_opt_table(result)) + ctx.console.print(tx_opt_summary(result)) + + artifacts: list[str] = [] + if params.get("viz", True): + assert ctx.settings.output_dir is not None + path = render_tx_optimization(result, ctx.settings.output_dir) + artifacts.append(str(path)) + + return ToolResult( + summary={ + "target": target, + "best_tx": result.best_tx, + "best_score": round(result.best_score, 3), + "original_tx": result.original_tx, + "applied": result.applied, + "levels_measured": len(result.levels), + }, + message=f"[ok]โœ“[/ok] optimum TX for [brand]{target}[/brand] is " + f"[brand]{result.best_tx}[/brand]" + + (" [ok](applied)[/ok]" if result.applied else ""), + artifacts=artifacts, + ) + + def register_cli(self, app: typer.Typer) -> None: + """Register the ``tx-optimize`` subcommand. + + Args: + app: The Typer application. + """ + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _tx_optimize( + target: str = typer.Option(..., "--target", "-t", help="Target node."), + samples: int = typer.Option(5, "--samples", "-n", help="Traces per level."), + step: int = typer.Option(3, "--step", help="Coarse sweep step."), + tx_min: int = typer.Option(TX_POWER_MIN, "--min", help="Lowest TX power."), + tx_max: int = typer.Option(TX_POWER_MAX, "--max", help="Highest TX power."), + refine: bool = typer.Option(True, "--refine/--no-refine", help="Local refine."), + apply: bool = typer.Option(False, "--apply", help="Write the winner to device."), + viz: bool = typer.Option(True, "--viz/--no-viz", help="Generate HTML chart."), + ) -> None: + run_tool_command( + self, + { + "target": target, "samples": samples, "step": step, + "tx_min": tx_min, "tx_max": tx_max, "refine": refine, + "apply": apply, "viz": viz, + }, + ) + + +def _positive_int(value: str) -> bool | str: + """Validate a positive-integer questionary answer. + + Args: + value: Raw input. + + Returns: + ``True`` if valid, else an error message. + """ + try: + return int(value) > 0 or "Enter a number greater than zero." + except ValueError: + return "Enter a whole number." + + +def _fmt_snr(snr: Optional[float]) -> str: + """Format an optional SNR for the progress description. + + Args: + snr: SNR in dB, or ``None``. + + Returns: + A short fixed-width string like ``+5.1`` or `` n/a``. + """ + return f"{snr:+.1f}" if snr is not None else " n/a" diff --git a/meshtools/ui/__init__.py b/meshtools/ui/__init__.py new file mode 100644 index 0000000..8992b2d --- /dev/null +++ b/meshtools/ui/__init__.py @@ -0,0 +1 @@ +"""Presentation layer: Rich theme/widgets and the Questionary-driven menu.""" diff --git a/meshtools/ui/device_picker.py b/meshtools/ui/device_picker.py new file mode 100644 index 0000000..abf8190 --- /dev/null +++ b/meshtools/ui/device_picker.py @@ -0,0 +1,68 @@ +"""Interactive companion-device picker (questionary). + +Shown at the start of the interactive menu (and from the ``devices`` tool) when no port +was given explicitly. It lists the discovered devices, marks the remembered "last known +good" one, and preselects it as the default. The chosen device becomes the session's +active device; it is persisted as the new default once it actually connects. +""" + +from __future__ import annotations + +from typing import Optional + +import questionary +from rich.console import Console + +from ..core.device_store import RememberedDevice +from ..core.discovery import DiscoveredDevice +from .menu import _MENU_STYLE + + +async def prompt_device( + console: Console, + devices: list[DiscoveredDevice], + remembered: Optional[RememberedDevice], +) -> Optional[DiscoveredDevice]: + """Prompt the user to choose a companion device. + + Args: + console: Console used for any surrounding messaging. + devices: Discovered devices (likely-LoRa first). + remembered: The remembered default, if any, used to mark and preselect a row. + + Returns: + The chosen :class:`DiscoveredDevice`, or ``None`` if the user cancelled or chose + to skip device selection (e.g. to run against ``--mock`` / configure later). + """ + if not devices: + console.print( + "[warn]No serial devices detected.[/warn] " + "Plug one in, pass [accent]--port[/accent], or run with [accent]--mock[/accent]." + ) + return None + + default_choice: Optional[questionary.Choice] = None + choices: list[questionary.Choice | questionary.Separator] = [] + for device in devices: + is_remembered = remembered is not None and remembered.matches(device) + star = "โ˜… " if is_remembered else " " + vendor = f" [{device.vendor_label}]" if device.vendor_label else "" + lora = " ยท likely LoRa" if device.is_likely_lora else "" + choice = questionary.Choice(title=f"{star}{device.label}{vendor}{lora}", value=device) + choices.append(choice) + # Preselect the remembered device; else default to the first (top-ranked) row. + if is_remembered: + default_choice = choice + if default_choice is None: + default_choice = choices[0] # type: ignore[assignment] # always a Choice here + + choices.append(questionary.Separator(" ")) + choices.append(questionary.Choice(title="skip (use --mock / configure later)", value=None)) + + return await questionary.select( + "Select a companion device:", + choices=choices, + default=default_choice, + style=_MENU_STYLE, + qmark="โ—†", + ).ask_async() diff --git a/meshtools/ui/menu.py b/meshtools/ui/menu.py new file mode 100644 index 0000000..2dbf29e --- /dev/null +++ b/meshtools/ui/menu.py @@ -0,0 +1,123 @@ +"""The interactive main menu, built dynamically from the tool registry. + +The menu groups registered tools by category and runs the selected tool's interactive +flow. Because it is generated from the registry, adding a tool automatically adds a menu +entry with no changes here. +""" + +from __future__ import annotations + +import questionary + +from ..context import AppContext +from ..tools import all_tools +from .theme import make_console +from .widgets import banner + +_MENU_STYLE = questionary.Style( + [ + ("qmark", "fg:#5eead4 bold"), + ("pointer", "fg:#818cf8 bold"), + ("highlighted", "fg:#5eead4 bold"), + ("selected", "fg:#4ade80"), + ("separator", "fg:#475569"), + ] +) + + +async def run_menu(ctx: AppContext) -> None: + """Run the interactive menu loop until the user quits. + + Before showing the menu, prompts for a companion device (unless the simulator is in + use or a port/profile was already chosen explicitly), so the banner reflects the + target and tools connect to the right radio. + + Args: + ctx: The shared application context. + """ + console = ctx.console + await _select_device_at_startup(ctx) + console.print(banner(ctx.profile_name, ctx.mock, ctx.selected_device)) + + while True: + choices: list[questionary.Choice | questionary.Separator] = [] + current_category: str | None = None + for tool in all_tools(): + if tool.category != current_category: + current_category = tool.category + choices.append(questionary.Separator(f"โ”€โ”€ {current_category} โ”€โ”€")) + choices.append( + questionary.Choice(title=f"{tool.name} โ€” {tool.help}", value=tool.name) + ) + choices.append(questionary.Separator(" ")) + choices.append(questionary.Choice(title="quit", value="__quit__")) + + selection = await questionary.select( + "What would you like to do?", + choices=choices, + style=_MENU_STYLE, + qmark="โ—†", + ).ask_async() + + if selection in (None, "__quit__"): + console.print("[muted]bye 73![/muted]") + return + + await _run_selection(ctx, selection) + console.print() + + +async def _select_device_at_startup(ctx: AppContext) -> None: + """Discover devices and let the user pick one, recording it on the context. + + No-ops when the simulator is in use or a ``--port``/``--profile`` was given + explicitly. A cancelled prompt leaves the context unresolved; tools needing the radio + will then surface a clear error (or the user can pick again via the ``devices`` tool). + + Args: + ctx: The shared application context to update with the selection. + """ + if ctx.mock or ctx.explicit_selection: + return + + from ..core.discovery import discover_devices + from .device_picker import prompt_device + + devices = discover_devices() + chosen = await prompt_device(ctx.console, devices, ctx.device_store.load()) + if chosen is not None: + ctx.selected_device = chosen + ctx.port_override = chosen.port + + +async def _run_selection(ctx: AppContext, name: str) -> None: + """Gather parameters for and execute a single tool from the menu. + + Args: + ctx: The shared application context. + name: The selected tool's name. + """ + from ..tools import get_tool + + tool = get_tool(name) + if tool is None: # pragma: no cover - registry and menu are always in sync + ctx.console.print(f"[err]Unknown tool: {name}[/err]") + return + + try: + params = await tool.prompt_params(ctx) + if params is None: # user cancelled a prompt + return + result = await tool.execute(ctx, params) + except Exception as exc: # noqa: BLE001 - surface errors without crashing the menu + ctx.console.print(f"[err]โœ— {tool.name} failed:[/err] {exc}") + return + + if result.message: + ctx.console.print(result.message) + for artifact in result.artifacts: + ctx.console.print(f"[ok]โ—[/ok] wrote [accent]{artifact}[/accent]") + + +# Exposed for tools that need a standalone console outside a context (rare). +default_console = make_console diff --git a/meshtools/ui/theme.py b/meshtools/ui/theme.py new file mode 100644 index 0000000..c201692 --- /dev/null +++ b/meshtools/ui/theme.py @@ -0,0 +1,60 @@ +"""Shared Rich theme and console factory for a consistent, modern look.""" + +from __future__ import annotations + +from rich.console import Console +from rich.theme import Theme + +MESH_THEME = Theme( + { + "brand": "bold #5eead4", + "accent": "bold #818cf8", + "ok": "bold #4ade80", + "warn": "bold #fbbf24", + "err": "bold #f87171", + "muted": "#94a3b8", + "snr.good": "bold #4ade80", + "snr.ok": "bold #fbbf24", + "snr.bad": "bold #f87171", + } +) + + +def make_console() -> Console: + """Create the application's themed Rich console. + + On legacy Windows consoles the standard streams default to ``cp1252``, which cannot + encode the box-drawing and marker glyphs (``โ—† โ— โ˜…``) the UI uses; this reconfigures + them to UTF-8 where the runtime supports it so output never raises ``UnicodeEncodeError``. + + Returns: + A :class:`rich.console.Console` configured with the MeshTools theme. + """ + import sys + + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is not None: + try: + reconfigure(encoding="utf-8") + except (ValueError, OSError): # pragma: no cover - stream not reconfigurable + pass + return Console(theme=MESH_THEME) + + +def snr_style(snr: float | None) -> str: + """Return a theme style name describing an SNR value's quality. + + Args: + snr: An SNR reading in dB, or ``None``. + + Returns: + ``"snr.good"``, ``"snr.ok"``, ``"snr.bad"``, or ``"muted"`` for ``None``. + """ + if snr is None: + return "muted" + if snr >= 5: + return "snr.good" + if snr >= -5: + return "snr.ok" + return "snr.bad" diff --git a/meshtools/ui/widgets.py b/meshtools/ui/widgets.py new file mode 100644 index 0000000..0f1b39e --- /dev/null +++ b/meshtools/ui/widgets.py @@ -0,0 +1,172 @@ +"""Reusable Rich widgets: banner, status pill, trace tables, and progress bars.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional + +from rich.console import Console +from rich.panel import Panel +from rich.progress import ( + BarColumn, + MofNCompleteColumn, + Progress, + SpinnerColumn, + TextColumn, + TimeElapsedColumn, +) +from rich.table import Table +from rich.text import Text + +from .. import __version__ +from ..core.models import TraceResult, TraceStats, TxOptResult +from .theme import snr_style + +if TYPE_CHECKING: + from ..core.discovery import DiscoveredDevice + + +def banner( + profile: Optional[str], mock: bool, selected_device: Optional["DiscoveredDevice"] = None +) -> Panel: + """Build the application header panel. + + Args: + profile: Active device profile name, if any. + mock: Whether the simulator is in use. + selected_device: The discovered device chosen for this session, if any, shown + when no named profile is in use. + + Returns: + A Rich :class:`Panel` showing the app name, version, and connection target. + """ + if mock: + target = "[warn]simulator[/warn]" + elif profile: + target = profile + elif selected_device is not None: + target = selected_device.label + else: + target = "[muted]no device[/muted]" + body = Text.from_markup( + f"[brand]MeshTools[/brand] [muted]v{__version__}[/muted]\n" + f"[muted]device:[/muted] {target}" + ) + return Panel(body, border_style="accent", expand=False, title="[accent]mesh[/accent]") + + +def make_progress(console: Console) -> Progress: + """Create a themed progress bar for trace sweeps. + + Args: + console: The console to render into. + + Returns: + A configured :class:`rich.progress.Progress` (use as a context manager). + """ + return Progress( + SpinnerColumn(style="accent"), + TextColumn("[accent]{task.description}"), + BarColumn(complete_style="brand", finished_style="ok"), + MofNCompleteColumn(), + TimeElapsedColumn(), + console=console, + transient=False, + ) + + +def trace_table(result: TraceResult) -> Table: + """Render a single trace's per-hop SNR as a table. + + Args: + result: The trace to display. + + Returns: + A Rich :class:`Table` of hops and SNR values. + """ + table = Table(title=f"Trace -> {result.target}", border_style="muted", expand=False) + table.add_column("Hop", justify="right", style="muted") + table.add_column("Node") + table.add_column("SNR (dB)", justify="right") + if not result.success: + table.add_row("-", "[err]no reply[/err]", "-") + return table + for hop in result.hops: + table.add_row( + str(hop.index), + hop.node or "[muted]?[/muted]", + Text(f"{hop.snr:+.1f}", style=snr_style(hop.snr)), + ) + return table + + +def stats_panel(stats: TraceStats) -> Panel: + """Summarize aggregated trace statistics in a panel. + + Args: + stats: The aggregated statistics to display. + + Returns: + A Rich :class:`Panel` with success rate and robust SNR/RTT. + """ + snr = stats.median_min_snr + snr_text = Text(f"{snr:+.1f} dB", style=snr_style(snr)) if snr is not None else Text("n/a") + rtt = f"{stats.median_rtt_ms:.0f} ms" if stats.median_rtt_ms is not None else "n/a" + body = Text.assemble( + ("target ", "muted"), (f"{stats.target}\n", ""), + ("success rate ", "muted"), (f"{stats.success_rate:.0%} " + f"({stats.successes}/{stats.samples})\n", ""), + ("median min SNR ", "muted"), snr_text, ("\n", ""), + ("median RTT ", "muted"), (rtt, ""), + ) + return Panel(body, title="[accent]trace summary[/accent]", border_style="accent", expand=False) + + +def tx_opt_table(result: TxOptResult) -> Table: + """Render every measured TX level of an optimization sweep, best row highlighted. + + Args: + result: The optimization result to display. + + Returns: + A Rich :class:`Table` of TX level, SNR, success rate, and score. + """ + table = Table(title=f"TX sweep -> {result.target}", border_style="muted", expand=False) + table.add_column("TX", justify="right") + table.add_column("median min SNR", justify="right") + table.add_column("success", justify="right") + table.add_column("score", justify="right") + for lv in result.sorted_by_tx(): + is_best = lv.tx_power == result.best_tx + marker = "[ok]โ˜…[/ok] " if is_best else " " + snr = lv.stats.median_min_snr + snr_cell = Text(f"{snr:+.1f}", style=snr_style(snr)) if snr is not None else Text("โ€”") + score_txt = f"{lv.score:.2f}" if lv.score != float("-inf") else "โ€”" + tx_cell = f"{marker}{lv.tx_power}" + row_style = "ok" if is_best else None + table.add_row( + tx_cell, snr_cell, f"{lv.stats.success_rate:.0%}", score_txt, style=row_style + ) + return table + + +def tx_opt_summary(result: TxOptResult) -> Panel: + """Summarize a TX optimization outcome. + + Args: + result: The optimization result to summarize. + + Returns: + A Rich :class:`Panel` stating the chosen optimum and whether it was applied. + """ + best = result.best_level + snr = best.stats.median_min_snr if best else None + snr_text = Text(f"{snr:+.1f} dB", style=snr_style(snr)) if snr is not None else Text("n/a") + applied = "[ok]applied to device[/ok]" if result.applied else "[muted]not applied[/muted]" + body = Text.assemble( + ("optimal TX ", "muted"), (f"{result.best_tx}", "brand"), ("\n", ""), + ("at SNR ", "muted"), snr_text, ("\n", ""), + ("previous TX ", "muted"), + (f"{result.original_tx if result.original_tx is not None else '?'}\n", ""), + ("status ", "muted"), Text.from_markup(applied), + ) + return Panel(body, title="[accent]tx optimization[/accent]", border_style="accent", expand=False) diff --git a/meshtools/viz/__init__.py b/meshtools/viz/__init__.py new file mode 100644 index 0000000..2a84e59 --- /dev/null +++ b/meshtools/viz/__init__.py @@ -0,0 +1,11 @@ +"""Visualization layer: Plotly / pyvis renderers producing interactive HTML (and PNG). + +Planned renderers (see the project plan): + +* ``tx_plot`` โ€” SNR-vs-TX-power curve with confidence band and chosen optimum. +* ``path_graph`` โ€” interactive pyvis mesh graph, edges colored by SNR. +* ``timeseries`` โ€” link SNR / success-rate dashboards over time. + +This package is intentionally empty in the skeleton; renderers are added alongside the +TX-power and path-optimization tools. +""" diff --git a/meshtools/viz/tx_plot.py b/meshtools/viz/tx_plot.py new file mode 100644 index 0000000..7dbe59d --- /dev/null +++ b/meshtools/viz/tx_plot.py @@ -0,0 +1,108 @@ +"""Plotly renderer for TX-power optimization sweeps. + +Produces a self-contained, interactive HTML chart: reliability-weighted score and median +bottleneck SNR versus TX power, with the chosen optimum marked. +""" + +from __future__ import annotations + +import math +from datetime import datetime +from pathlib import Path + +import plotly.graph_objects as go + +from ..core.models import TxOptResult + +_TEMPLATE = "plotly_dark" +_BRAND = "#5eead4" +_ACCENT = "#818cf8" +_MUTED = "#94a3b8" + + +def render_tx_optimization(result: TxOptResult, output_dir: Path) -> Path: + """Render a TX-power optimization sweep to an interactive HTML file. + + Args: + result: The optimization result to visualize. + output_dir: Directory the HTML file is written to (created if needed). + + Returns: + Path to the written HTML file. + """ + levels = result.sorted_by_tx() + tx = [lv.tx_power for lv in levels] + snr = [lv.stats.median_min_snr for lv in levels] + score = [lv.score if math.isfinite(lv.score) else None for lv in levels] + success = [lv.stats.success_rate * 100 for lv in levels] + + fig = go.Figure() + fig.add_trace( + go.Scatter( + x=tx, y=snr, name="median min SNR (dB)", mode="lines+markers", + line=dict(color=_BRAND, width=3), marker=dict(size=8), + hovertemplate="TX %{x}
SNR %{y:+.1f} dB", + ) + ) + fig.add_trace( + go.Scatter( + x=tx, y=score, name="score", mode="lines+markers", + line=dict(color=_ACCENT, width=2, dash="dot"), marker=dict(size=6), + hovertemplate="TX %{x}
score %{y:.2f}", + ) + ) + fig.add_trace( + go.Bar( + x=tx, y=success, name="success rate (%)", yaxis="y2", + marker=dict(color=_MUTED), opacity=0.25, + hovertemplate="TX %{x}
%{y:.0f}% success", + ) + ) + + best = result.best_level + if best is not None and best.stats.median_min_snr is not None: + fig.add_vline(x=result.best_tx, line=dict(color="#4ade80", width=2, dash="dash")) + fig.add_trace( + go.Scatter( + x=[result.best_tx], y=[best.stats.median_min_snr], + name=f"optimum (TX {result.best_tx})", mode="markers", + marker=dict(color="#4ade80", size=16, symbol="star"), + hovertemplate=f"optimum
TX {result.best_tx}" + "
%{y:+.1f} dB", + ) + ) + + fig.update_layout( + template=_TEMPLATE, + title=dict( + text=f"TX-power optimization โ€” {result.target}" + f" ยท optimum TX {result.best_tx}", + font=dict(color=_BRAND), + ), + xaxis=dict(title="TX power", dtick=1), + yaxis=dict(title="SNR (dB) / score"), + yaxis2=dict( + title="success rate (%)", overlaying="y", side="right", + range=[0, 105], showgrid=False, + ), + legend=dict(orientation="h", yanchor="bottom", y=1.02), + bargap=0.4, + ) + + output_dir.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + path = output_dir / f"tx-optimize_{_slug(result.target)}_{stamp}.html" + fig.write_html(path, include_plotlyjs=True) # fully self-contained / offline + return path + + +def _slug(value: str) -> str: + """Make a filesystem-safe slug from a node name. + + Args: + value: Arbitrary node name or key prefix. + + Returns: + A lowercase slug containing only alphanumerics, dashes, and underscores. + """ + return "".join(c if c.isalnum() or c in "-_" else "-" for c in value).strip("-").lower() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9638cb5 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,53 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "meshtools" +version = "0.1.0" +description = "A modern command-line toolkit for tuning and exploring a MeshCore mesh." +readme = "README.md" +requires-python = ">=3.10" +authors = [{ name = "Jean-Pierre Martineau" }] +license = { text = "MIT" } +keywords = ["meshcore", "lora", "mesh", "radio", "cli"] + +dependencies = [ + "meshcore>=2.3", # companion-device protocol (serial/BLE/TCP) + "pyserial>=3.5", # serial-port enumeration for device discovery + "typer>=0.12", # scripted CLI; subcommands mirror the menu + "rich>=13.7", # modern console rendering (progress, tables, panels) + "questionary>=2.0", # interactive arrow-key menu navigation + "plotly>=5.20", # interactive self-contained HTML charts + "pyvis>=0.3.2", # interactive HTML mesh graphs + "networkx>=3.2", # graph model + path scoring + "tomli>=2.0; python_version < '3.11'", # TOML config reader on 3.10 +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0", + "pytest-asyncio>=0.23", + "ruff>=0.4", +] + +[project.scripts] +meshtools = "meshtools.cli:main" + +[tool.hatch.build.targets.wheel] +packages = ["meshtools"] + +[tool.ruff] +line-length = 100 +target-version = "py310" + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B", "D"] +ignore = ["D203", "D213"] # pick one blank-line-before-class / multi-line-summary style + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_discovery.py b/tests/test_discovery.py new file mode 100644 index 0000000..bdeec79 --- /dev/null +++ b/tests/test_discovery.py @@ -0,0 +1,170 @@ +"""Tests for device discovery, the remembered-device store, and selection. + +All run without hardware: serial enumeration is monkeypatched, and the store/selection +logic is pure. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +import pytest + +from meshtools.core.config import DeviceProfile +from meshtools.core.device_store import DeviceStore +from meshtools.core.discovery import DiscoveredDevice, discover_devices +from meshtools.core.selection import DeviceSelectionError, resolve_device + + +@dataclass +class FakePortInfo: + """Stand-in for ``serial.tools.list_ports_common.ListPortInfo``.""" + + device: str + description: Optional[str] = None + hwid: Optional[str] = None + vid: Optional[int] = None + pid: Optional[int] = None + serial_number: Optional[str] = None + manufacturer: Optional[str] = None + product: Optional[str] = None + + +def _patch_ports(monkeypatch: pytest.MonkeyPatch, ports: list[FakePortInfo]) -> None: + """Make ``discover_devices`` see exactly ``ports``.""" + from serial.tools import list_ports + + monkeypatch.setattr(list_ports, "comports", lambda: list(ports)) + + +# -- discovery ----------------------------------------------------------------- + + +def test_discover_maps_fields_and_flags_lora(monkeypatch: pytest.MonkeyPatch) -> None: + """USB metadata is mapped through and known vendors are flagged as likely LoRa.""" + _patch_ports( + monkeypatch, + [ + FakePortInfo( + device="COM5", + description="USB Serial", + vid=0x303A, # Espressif โ†’ likely LoRa + pid=0x1001, + serial_number="ABC123", + product="Wio SX1262", + ) + ], + ) + [dev] = discover_devices() + assert dev.port == "COM5" + assert dev.product == "Wio SX1262" + assert dev.is_likely_lora + assert dev.vendor_label == "Espressif" + assert "COM5" in dev.label + + +def test_discover_sorts_likely_lora_first(monkeypatch: pytest.MonkeyPatch) -> None: + """Likely-LoRa devices sort ahead of unrecognized adapters.""" + _patch_ports( + monkeypatch, + [ + FakePortInfo(device="COM9", vid=0x1234, pid=0x0001), # unknown vendor + FakePortInfo(device="COM3", vid=0x10C4, pid=0xEA60), # Silabs โ†’ LoRa + ], + ) + devices = discover_devices() + assert [d.port for d in devices] == ["COM3", "COM9"] + assert devices[0].is_likely_lora and not devices[1].is_likely_lora + + +def test_stable_id_precedence() -> None: + """stable_id prefers serial number, then vid:pid, then the port name.""" + assert DiscoveredDevice("COM5", serial_number="SN1", vid=1, pid=2).stable_id == "sn:SN1" + assert DiscoveredDevice("COM5", vid=0x303A, pid=0x1001).stable_id == "vidpid:303a:1001" + assert DiscoveredDevice("COM5").stable_id == "port:COM5" + + +# -- device store -------------------------------------------------------------- + + +def test_device_store_round_trip(tmp_path: Path) -> None: + """A remembered device writes and reads back, matched by stable_id.""" + store = DeviceStore(tmp_path / "devices.json") + assert store.load() is None # nothing remembered yet + + dev = DiscoveredDevice("COM5", serial_number="SN1", product="Wio SX1262") + store.remember(dev) + + loaded = store.load() + assert loaded is not None + assert loaded.stable_id == "sn:SN1" + assert loaded.matches(dev) + assert not loaded.matches(DiscoveredDevice("COM6", serial_number="OTHER")) + + +def test_device_store_tolerates_corrupt_file(tmp_path: Path) -> None: + """A corrupt state file is treated as 'nothing remembered'.""" + path = tmp_path / "devices.json" + path.write_text("{not valid json", encoding="utf-8") + assert DeviceStore(path).load() is None + + +# -- selection ----------------------------------------------------------------- + + +def test_resolve_prefers_explicit_port() -> None: + """An explicit --port wins over everything else.""" + devices = [DiscoveredDevice("COM3", serial_number="SN1")] + res = resolve_device(devices, None, explicit_port="COM9") + assert res.port == "COM9" and res.source == "port" + + +def test_resolve_uses_profile_port() -> None: + """A profile with a port is used when no --port is given.""" + profile = DeviceProfile(name="yagi", port="COM6") + res = resolve_device([], None, profile=profile) + assert res.port == "COM6" and res.source == "profile" + + +def test_resolve_uses_remembered_when_present() -> None: + """The remembered default is used when that device is still attached.""" + dev = DiscoveredDevice("COM3", serial_number="SN1") + store_dev = DiscoveredDevice("COM7", serial_number="SN1") # same hardware, new port + store = _remember(store_dev) + res = resolve_device([dev], store, profile=None) + assert res.port == "COM3" and res.source == "remembered" + assert res.device is dev + + +def test_resolve_single_device_auto() -> None: + """With exactly one device and no default, it is chosen automatically.""" + dev = DiscoveredDevice("COM3", serial_number="SN1") + res = resolve_device([dev], None) + assert res.port == "COM3" and res.source == "only" + + +def test_resolve_ambiguous_raises(tmp_path: Path) -> None: + """Multiple devices with no usable default raise a guidance error.""" + devices = [ + DiscoveredDevice("COM3", serial_number="SN1"), + DiscoveredDevice("COM4", serial_number="SN2"), + ] + with pytest.raises(DeviceSelectionError, match="Multiple serial devices"): + resolve_device(devices, None) + + +def test_resolve_no_devices_raises() -> None: + """No devices at all raises a clear error mentioning --mock.""" + with pytest.raises(DeviceSelectionError, match="No serial devices"): + resolve_device([], None) + + +def _remember(device: DiscoveredDevice): + """Build a RememberedDevice for ``device`` without touching disk.""" + from meshtools.core.device_store import RememberedDevice + + return RememberedDevice( + stable_id=device.stable_id, port=device.port, label=device.label, last_connected="" + ) diff --git a/tests/test_skeleton.py b/tests/test_skeleton.py new file mode 100644 index 0000000..e782499 --- /dev/null +++ b/tests/test_skeleton.py @@ -0,0 +1,109 @@ +"""Smoke tests for the skeleton: models, mock device, service, and persistence. + +These run without hardware against the :class:`MockDevice` simulator. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from meshtools.core.connection import MockDevice, clamp_tx_power +from meshtools.core.models import TraceResult, TraceStats +from meshtools.persistence.repository import Repository +from meshtools.services import trace_runner + + +def test_clamp_tx_power() -> None: + """TX power clamps to the supported range.""" + assert clamp_tx_power(-5) == 1 + assert clamp_tx_power(99) == 22 + assert clamp_tx_power(14) == 14 + + +def test_trace_stats_aggregation() -> None: + """Robust stats reflect successes and bottleneck SNR.""" + from meshtools.core.models import Hop + + traces = [ + TraceResult(target="x", success=True, hops=[Hop(0, "a", 5.0), Hop(1, "b", -2.0)]), + TraceResult(target="x", success=False), + TraceResult(target="x", success=True, hops=[Hop(0, "a", 7.0), Hop(1, "b", 0.0)]), + ] + stats = TraceStats.from_traces("x", traces) + assert stats.samples == 3 + assert stats.successes == 2 + assert stats.success_rate == pytest.approx(2 / 3) + assert stats.median_min_snr == pytest.approx(-1.0) # median of [-2.0, 0.0] + + +async def test_mock_device_trace_is_unimodal_in_tx() -> None: + """The simulator peaks near its optimal TX power (averaged over noise).""" + device = MockDevice(optimal_tx=14) + await device.connect() + + async def avg_snr(tx: int) -> float: + await device.set_tx_power(tx) + stats = await trace_runner.measure(device, "Alice", samples=15, cooldown_s=0) + return stats.median_min_snr or -99.0 + + low, peak, high = await avg_snr(2), await avg_snr(14), await avg_snr(22) + assert peak > low + assert peak > high + + +async def test_tx_optimizer_finds_simulator_peak(tmp_path: Path) -> None: + """The optimizer converges near the simulator's known optimal TX power.""" + from meshtools.services import tx_optimizer + + device = MockDevice(optimal_tx=14) + await device.connect() + await device.set_tx_power(20) + + result = await tx_optimizer.optimize_tx_power( + device, "Alice", samples_per_level=12, coarse_step=3, cooldown_s=0 + ) + assert abs(result.best_tx - 14) <= 2 # within a step of the true peak + assert result.original_tx == 20 + assert await device.get_tx_power() == 20 # original restored, not the winner + assert not result.applied + + +def test_tx_plot_writes_html(tmp_path: Path) -> None: + """The Plotly renderer produces a self-contained HTML file.""" + import asyncio + + from meshtools.services import tx_optimizer + from meshtools.viz.tx_plot import render_tx_optimization + + async def _build(): + device = MockDevice(optimal_tx=14) + await device.connect() + return await tx_optimizer.optimize_tx_power( + device, "Alice", samples_per_level=4, coarse_step=4, refine=False, cooldown_s=0 + ) + + result = asyncio.run(_build()) + path = render_tx_optimization(result, tmp_path) + assert path.exists() + assert path.suffix == ".html" + assert path.stat().st_size > 1000 # plotly.js inlined โ†’ non-trivial size + + +async def test_repository_round_trip(tmp_path: Path) -> None: + """A run and its traces persist and read back.""" + repo = Repository(tmp_path / "test.db") + run_id = repo.start_run("trace", {"target": "Alice", "samples": 2}) + + device = MockDevice() + await device.connect() + results = await trace_runner.run_traces( + device, "Alice", samples=2, cooldown_s=0, persist=lambda t: repo.record_trace(run_id, t) + ) + repo.finish_run(run_id, "ok", {"count": len(results)}) + + runs = repo.list_runs() + assert runs[0].tool == "trace" + assert runs[0].status == "ok" + repo.close()