diff --git a/CHANGELOG.md b/CHANGELOG.md index c07c89b..7e13bb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,27 @@ can change how things behave. It does not only add new things. ### Added +- **Device info says everything that the companion reports.** The status panel grew from + nine rows to twenty-six, in four groups. **What the node is**: its role, its public key + with the routed bytes lit, its model, its firmware with the companion protocol version, + and the place where it says it is. **What MeshTerm does with it**: the default flood + scope and the transport key of that scope, the active site with the outbound paths and + the kept device routes that apply here, and the name of the radio preset that the four + radio settings match. **How it is doing**: the battery, the storage, the sensor readings + of the node itself, the clock with its drift as a readable duration, the uptime, the + contacts and the channels against the capacities of the device, the packets that wait to + go out, and the firmware error count. **What it heard and sent**: the noise floor with + the last RSSI and SNR, the airtime, and the packet counts, now split into flood and + direct for both directions. A node with no scope says that its floods reach everyone. A + node that stores a scope key that its own scope name does not give says so, which + nothing else in MeshTerm could show. Each value wraps under its own column, so a long + reading never goes back to the left edge, and a 64-digit key stays whole. +- **`meshterm info` answers with the settings too.** It gives three parts: the status, the + sensor readings as a listing, and every setting of the device. The settings come from + the one definition that `config show` answers with, under the keys that `config get` and + `config set` take. Thus the scripted face says the same about a device as the page does, + and no setting is spelled two ways. `--json` gives the status at the top level, the + readings under `telemetry`, and the settings under `settings`. - **A channel message that you send shows whether a repeater relayed it.** A channel has no acknowledgement, but your radio hears each repeater that relays your message. The end of your message shows a spinner, then `✓` and the number of repeaters that sent a diff --git a/docs/guide/features.md b/docs/guide/features.md index f46081e..4fd1a73 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -48,7 +48,7 @@ This page lists each interactive screen with its scripted equivalent, where one | Feature | What it does | Scripted | | --- | --- | --- | -| **📋 Device info** | The identity of the connected companion and its full radio configuration, on one screen. | `meshterm info` | +| **📋 Device info** | Everything that the connected companion knows about itself, on one screen. A status panel names the node, its key, its firmware and companion protocol version, and the place where it says it is. Then it names what MeshTerm does with the node: its flood scope and the key of that scope, the site and the outbound paths that apply here, and its radio preset. Then it names how the node is doing: the battery, the storage, its own sensor readings, the clock and its drift, the uptime, the contacts and channels against the capacities of the device, the packets that wait to go out, and the firmware errors. Last, it names what the node heard and sent, with the packet counts split into flood and direct. Under the panel is every setting of the device. The scripted face gives the same three parts: the status, the sensor readings, and every setting under the keys that `config get` and `config set` take. | `meshterm info` | | **🔧 Device config** | Each setting that the companion firmware has: name, radio, client repeat, auto-add, telemetry, and custom variables. MeshTerm stages your changes for review and then applies them in place. The screen also has operations on the device itself: clock sync, TOML backup and restore, the identity key, reboot, and factory reset. Each operation acts when you confirm it, and the destructive operations need a confirm step. The screen has the same layout as Repeater admin. Thus you configure the radio in your hand and a radio over the mesh in the same way. | `meshterm config` / `config set ` / `config backup` / `config reboot` / … | | **📡 Send advert** | Announce this node to the mesh with a zero-hop advert or a flood advert. You can also share the contact card of this node as a QR code. | `meshterm config advert` / `config share` | | **🔌 Devices** | This is not a menu screen. You select the companion on the startup splash. The splash lists the serial companions and the Bluetooth LE companions. If only one companion is present, MeshTerm selects it. You can add a network (TCP) companion with host:port. MeshTerm remembers the last good default. If the link drops, MeshTerm detects it at once and offers to reconnect. `meshterm devices` lists what discovery finds. | `meshterm devices` | diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 1bea200..4f45d65 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -1216,6 +1216,50 @@ def serial_port_present(port: str) -> bool: return False +def lpp_readings(raw: object) -> list[dict]: + """Turn the Cayenne LPP frame of a telemetry answer into one dict for each reading. + + The library decodes the frame already. It gives a list of entries, each with the + channel that the reading came from, the kind of value (``type``, which is a word and + not a number), and the value itself. This function keeps those three fields, names the + kind ``name``, and drops anything that it cannot read. Thus a malformed answer costs + the readings that it broke, and not the page that shows them. + + Args: + raw: The ``lpp`` field of a telemetry answer. + + Returns: + One dict for each reading, with ``channel``, ``name``, and ``value``. + """ + readings: list[dict] = [] + for item in raw if isinstance(raw, list) else (): + if not isinstance(item, dict): + continue + name = str(item.get("type") or "").strip() + if not name: + continue + readings.append({"channel": item.get("channel"), "name": name, "value": item.get("value")}) + return readings + + +def derived_scope_key(name: str | None) -> str | None: + """Return the transport key that a scope name gives, or ``None`` when there is no name. + + Args: + name: A region name, bare or with its ``#``. An empty name means no scope. + + Returns: + The 16-byte key as lowercase hex, or ``None`` for no scope and for a name that no + region can carry. + """ + if not name: + return None + try: + return region_key(name).hex() + except Exception: # noqa: BLE001 - a name the firmware stored can still be invalid here + return None + + class Device(ABC): """An abstract companion device, with the operations that MeshTerm uses. @@ -1885,6 +1929,42 @@ class Device(ABC): is set, or ``None`` if the firmware is older than flood scopes. """ + async def get_default_flood_scope_detail(self) -> dict: + """Return the stored default flood scope: its name, and its transport key. + + The firmware sends both in one frame. :meth:`get_default_flood_scope` gives only + the name, because that is all a send needs. The Device info page also shows the + key, so that the user can compare what the device stores with what the name gives. + + A transport that cannot report the key derives it from the name + (:func:`~meshterm.core.regions.region_key`), because the key is a pure function of + the name. A transport that reads the frame overrides this method and returns the + key of the device itself. Thus a device that stores a key that does not match its + own name is visible. + + Returns: + ``{"name": str | None, "key": str | None}``. The name is ``""`` when no scope + is set, and ``None`` on firmware that is older than flood scopes. The key is + lowercase hex, or ``None`` when there is no scope. + """ + name = await self.get_default_flood_scope() + return {"name": name, "key": derived_scope_key(name)} + + async def get_self_telemetry(self) -> list[dict]: + """Return the sensor readings of this node, as the firmware reports them. + + The firmware answers with a Cayenne LPP frame: one entry for each reading, each + with the channel that it came from and the kind of value that it holds. Firmware + that does not support the query, and a transport that cannot ask, both answer with + an empty list. Thus a caller never has to test which device it has. + + Returns: + One dict for each reading: ``channel`` (int), ``name`` (the kind of reading, + for example ``temperature``), and ``value`` (a number, or a dict of fields for + a reading that has several). + """ + return [] + @abstractmethod async def get_time(self) -> int | None: """Return the device clock as a UNIX epoch timestamp, or ``None`` if not known.""" @@ -4624,13 +4704,28 @@ class MeshCoreDevice(Device): ] async def get_default_flood_scope(self) -> str | None: # noqa: D102 + detail = await self.get_default_flood_scope_detail() + name = detail.get("name") + return None if name is None else str(name) + + async def get_default_flood_scope_detail(self) -> dict: # noqa: D102 event = self._ok(await self._require().commands.get_default_flood_scope()) payload = getattr(event, "payload", {}) or {} name = payload.get("scope_name") + key = payload.get("scope_key") # Return the name bare, whatever client wrote it. MeshTerm (before it built its own # frames) and the library (still now) stored a ``#`` that the firmware and the apps - # do not use. - return None if name is None else normalize_region(str(name)) + # do not use. The key comes from the same frame, so it is the key of the device and + # not a key that MeshTerm derived. + return { + "name": None if name is None else normalize_region(str(name)), + "key": str(key).lower() or None if key else None, + } + + async def get_self_telemetry(self) -> list[dict]: # noqa: D102 + event = self._ok(await self._require().commands.get_self_telemetry()) + payload = getattr(event, "payload", {}) or {} + return lpp_readings(payload.get("lpp")) async def get_time(self) -> int | None: # noqa: D102 - inherited docstring event = self._ok(await self._require().commands.get_time()) @@ -5198,10 +5293,22 @@ class MockDevice(Device): "model": "MeshCore Simulator", "ver": "mock", "fw_build": "mock", + "fw ver": 12, + "max_contacts": 300, + "max_channels": self._max_channels, "ble_pin": self._device_pin, "repeat": self._client_repeat, } + async def get_self_telemetry(self) -> list[dict]: # noqa: D102 - inherited docstring + # The readings that almost every board reports: the battery on channel 0, and one + # environment sensor. Thus the Device info page has a telemetry block to draw. + return [ + {"channel": 0, "name": "voltage", "value": 4.1}, + {"channel": 0, "name": "percentage", "value": 86}, + {"channel": 1, "name": "temperature", "value": 21.5}, + ] + async def get_contacts(self) -> list[Contact]: # noqa: D102 - inherited docstring return list(self._contacts) diff --git a/meshterm/core/device_config.py b/meshterm/core/device_config.py index 5f564a6..ce44906 100644 --- a/meshterm/core/device_config.py +++ b/meshterm/core/device_config.py @@ -274,9 +274,10 @@ async def build_snapshot( Returns: A dict with the keys of ``SELF_INFO``, and also ``rx_delay``, ``airtime_factor``, ``path_hash_mode``, ``autoadd_config``, - ``autoadd_max_hops``, and ``flood_scope``. Below these, it has the facts of the - device-query frame (``ble_pin``, ``model``, client ``repeat``). If the firmware - can relay, the dict also has its ``repeat_freqs``. + ``autoadd_max_hops``, ``flood_scope``, and ``flood_scope_key``. Below these, it + has the facts of the device-query frame (``ble_pin``, ``model``, ``fw ver``, + ``max_contacts``, ``max_channels``, client ``repeat``). If the firmware can relay, + the dict also has its ``repeat_freqs``. """ snapshot = dict(self_info if self_info is not None else await device.get_self_info()) try: @@ -300,10 +301,16 @@ async def build_snapshot( hops = None if hops is not None: snapshot["autoadd_max_hops"] = hops + # One read gives the scope name and the transport key that the device stores for it. + # The settings registry uses the name. The Device info page shows the key beside it. try: - snapshot["flood_scope"] = await device.get_default_flood_scope() + scope = await device.get_default_flood_scope_detail() except Exception: # noqa: BLE001 - an optional read. Its absence is acceptable. - pass + scope = {} + if scope.get("name") is not None: + snapshot["flood_scope"] = scope["name"] + if scope.get("key"): + snapshot["flood_scope_key"] = scope["key"] # The device-query frame is a payload that is different from SELF_INFO, and some # settings are only there. One of them is the BLE pairing code: real firmware reports # it as ``ble_pin``, and never puts it in SELF_INFO. Without this read, the Device PIN diff --git a/meshterm/demo/device.py b/meshterm/demo/device.py index 9e60921..d401611 100644 --- a/meshterm/demo/device.py +++ b/meshterm/demo/device.py @@ -112,10 +112,22 @@ class DemoDevice(MockDevice): "model": "MeshCore Simulator", "ver": "v1.15.0", "fw_build": "demo", + "fw ver": 12, + "max_contacts": 300, + "max_channels": self._max_channels, "ble_pin": self._device_pin, "repeat": self._client_repeat, } + async def get_self_telemetry(self) -> list[dict]: # noqa: D102 - inherited docstring + # The board of our node: the battery, and the sensor on its expansion header. + return [ + {"channel": 0, "name": "voltage", "value": 3.98}, + {"channel": 0, "name": "percentage", "value": 74}, + {"channel": 1, "name": "temperature", "value": 18.5}, + {"channel": 1, "name": "humidity", "value": 46.0}, + ] + async def get_battery(self) -> dict: # noqa: D102 - inherited docstring return {"level": 3980, "used_kb": 412, "total_kb": 1024} diff --git a/meshterm/services/device_state.py b/meshterm/services/device_state.py index 2356bf7..d9070e5 100644 --- a/meshterm/services/device_state.py +++ b/meshterm/services/device_state.py @@ -444,6 +444,17 @@ class DeviceState: return slots return self._channels + def peek_channel_slots(self) -> list[ChannelSlot] | None: + """The channel slots that the cache already has, or ``None`` when it has none yet. + + This method never reads from the device. It is for a page that names how many + channels the device holds as one fact among many (the Device info page). The probe + behind :meth:`channel_slots` reads every slot index, which is one of the slowest + reads of a session. A count is not worth that cost, and the prewarm fills this + cache anyway. + """ + return None if self._channels is None else list(self._channels) + async def channel_capacity(self) -> int: """Return the channel-slot capacity of the device, found once and kept for the session. diff --git a/meshterm/services/places.py b/meshterm/services/places.py index 2ac8406..a6ff1af 100644 --- a/meshterm/services/places.py +++ b/meshterm/services/places.py @@ -144,6 +144,39 @@ def current() -> PlaceService | None: return _CURRENT +def place_of(ctx: AppContext, node: str | None) -> Place | None: + """The place of a node, with or without a running place service. + + A menu session always has a service, and its cache answers at once. A scripted run has + none, so this function reads the two sources that the service reads: the place that the + user typed, and the places that the job stored before. Thus one command gets the same + answer on both faces. + + Args: + ctx: The shared application context. + node: The key prefix or the full public key of the node. + + Returns: + The place, or ``None`` when MeshTerm knows none. + """ + service = current() + if service is not None: + return service.get(node) + if not node: + return None + key = _norm(node) + typed = ctx.place_store.get(key) if ctx.place_store is not None else None + if typed: + return Place(typed, None, SOURCE_USER) + try: + found = ctx.repo.node_places() + except Exception as exc: # noqa: BLE001 - no place is better than no answer + ctx.log.debug("places: read failed: %s", exc) + return None + hit = found.get(key) + return None if hit is None or hit[0].empty else hit[0] + + class PlaceService: """The places of the nodes: a read side from memory, and a background job that finds them.""" diff --git a/meshterm/tools/config.py b/meshterm/tools/config.py index 501dbcb..0546e2b 100644 --- a/meshterm/tools/config.py +++ b/meshterm/tools/config.py @@ -426,15 +426,36 @@ async def _show(ctx: AppContext, device: Device, snapshot: dict) -> Listing | No the one value in it that lets the phone of another person connect to the radio. ``config get device_pin`` names it on purpose. """ - from ..ui import fields, script - from ..ui.config_editor import PIN_KEY, conceal, config_table - from ..ui.report import Listing + from ..ui.config_editor import config_table from ..ui.surface import TuiUi custom = await device.get_custom_vars() if isinstance(ctx.ui, TuiUi): ctx.ui.show(config_table(snapshot, custom)) return None + return settings_listing(snapshot, custom) + + +def settings_listing(snapshot: dict, custom: dict[str, str]) -> Listing: + """Every setting and custom variable of a snapshot, as one listing. + + This is the scripted face of the settings table, and it is the only definition of it. + ``config show`` answers with it. ``info`` puts it under its status block, so that the + scripted face says the same about a device as the Device info page does + (:func:`~meshterm.tools.info.InfoTool.run`). Both faces use these keys, exactly as + ``config get`` and ``config set`` name them. Thus one setting is never spelled two + ways. + + Args: + snapshot: The device snapshot from ``build_snapshot``. + custom: The current custom variables of the device. + + Returns: + The listing, with one record for each setting and each custom variable. + """ + from ..ui import fields, script + from ..ui.config_editor import PIN_KEY, conceal + from ..ui.report import Listing rows: list[dict[str, Any]] = [] for _category, specs in settings_by_category(): diff --git a/meshterm/tools/info.py b/meshterm/tools/info.py index 4e2f9fa..ef30b29 100644 --- a/meshterm/tools/info.py +++ b/meshterm/tools/info.py @@ -5,20 +5,77 @@ from __future__ import annotations import time from collections.abc import Callable +from dataclasses import dataclass from datetime import datetime, timezone from typing import TYPE_CHECKING, Any import typer from rich.panel import Panel +from rich.table import Table from rich.text import Text from ..context import AppContext -from ..core.connection import Device +from ..core.connection import Device, derived_scope_key +from ..core.device_config import current_preset from ..core.models import node_type_label from .base import Tool, ToolResult, register if TYPE_CHECKING: # pragma: no cover - typing only - from ..ui.report import Column, Facts + from ..ui.report import Column, Facts, Listing + +#: The unit of each kind of telemetry reading that a companion can report. A reading whose +#: kind is not here has no unit (a count, a state, or a reading with several fields). The +#: names are the names that the Cayenne LPP decoder gives +#: (refer to :func:`~meshterm.core.connection.lpp_readings`). +_UNITS = { + "temperature": "°C", + "humidity": "%", + "percentage": "%", + "voltage": "V", + "current": "A", + "barometer": "hPa", + "illuminance": "lux", + "altitude": "m", + "distance": "m", + "energy": "kWh", + "power": "W", + "load": "kg", + "concentration": "ppm", + "direction": "°", + "frequency": "Hz", + "time": "s", +} + + +@dataclass(frozen=True, slots=True) +class AppFacts: + """What MeshTerm itself knows about the connected node, beside what the radio reports. + + The radio answers for its own settings and its own counters. These facts come from the + other side: the stores of this computer, the caches of the session, and what MeshTerm + derives from the radio settings. The Device info page shows them with the facts of the + radio, because the user reads one node and not two sources. + + Attributes: + place: The named area nearest the location of the node, or ``None``. + site: The name of the active site, or ``None`` when no site is active. + outbound_paths: How many outbound paths apply to this device. + fixed: Whether those paths come from a fixed-device list and not from the site. + kept_routes: How many device routes the user keeps for this device. + contacts: How many contacts the device holds, or ``None`` when no read gave them. + channels: How many channels are set, or ``None`` when no read gave them. + preset: The name of the radio preset that the four radio settings match, or + ``None`` when they match no preset. + """ + + place: str | None = None + site: str | None = None + outbound_paths: int | None = None + fixed: bool = False + kept_routes: int | None = None + contacts: int | None = None + channels: int | None = None + preset: str | None = None @register @@ -38,6 +95,15 @@ class InfoTool(Tool): async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: """Query the device, and render its live status and all its settings. + Both faces answer with the same three parts, in the same order: the status of the + device, its sensor readings, and every setting that it holds. The menu draws the + parts as a panel over the settings table. The scripted face returns them as three + blocks, and the renderer of the boundary prints them. + + The settings come from one definition, :func:`~meshterm.tools.config.settings_listing`, + which ``config show`` answers with. Thus the scripted face of this command says the + same about a device as the page does, and no setting is spelled two ways. + Args: ctx: The shared application context. params: Not used. @@ -51,32 +117,39 @@ class InfoTool(Tool): device = await ctx.device() snapshot = await cached_snapshot(ctx, device) + readings = await read_status(device) + app = await app_facts(ctx, snapshot) - # On the CLI, this is only the status report: the current condition of the device, - # one fact on each line. The settings are the answer of `config show`, with the - # same keys that `config get` and `config set` take. If this command also prints - # the settings, the same table shows two times, with two different spellings. + # On the CLI, the status block, the sensor readings, and the settings, in that + # order. The settings keep the keys that `config get` and `config set` take. session = getattr(ctx.ui, "session", None) if session is None: + from .config import settings_listing + + custom = await device.get_custom_vars() return ToolResult( summary={"name": snapshot.get("name")}, - report=(await status_facts(device, snapshot),), + report=( + status_facts(snapshot, readings, app), + telemetry_listing(readings["telemetry"]), + settings_listing(snapshot, custom), + ), ) from ..ui.device_info_screen import DeviceInfoScreen custom = await device.get_custom_vars() - # A live status panel (role, firmware, battery, clock, radio and packet statistics) - # above all the current settings, each with a short explanation. The panel is read - # one time. Only the table is different between the two states, and it is fast to - # build again. - panel = await _status_panel(device, snapshot) + # A live status panel (identity, place, scope, site, health, and the traffic + # statistics) above all the current settings, each with a short explanation. The + # panel is built one time. Only the table is different between the two states, and + # it is fast to build again. + panel = status_panel(snapshot, readings, app) def page(reveal_pin: bool) -> Group: return Group(panel, Text(""), config_table(snapshot, custom, reveal_pin=reveal_pin)) # The page is a separate screen, because it has its own keyboard key: the pairing - # PIN is masked until ``p`` shows it. + # PIN is masked until ``^E`` shows it. await session.run_screen( DeviceInfoScreen(session, page, title=self.title, conceals=has_pin(snapshot)) ) @@ -95,116 +168,391 @@ class InfoTool(Tool): run_tool_command(self, {}) -# -- the status panel ----------------------------------------------------------- +# -- the reads ------------------------------------------------------------------ -async def _read_status(device: Device) -> dict[str, Any]: +async def read_status(device: Device) -> dict: """Read each live status value that the firmware gives, as a best effort. - This is the only place that asks the device. Both faces use what it returns: the panel - of the menu makes prose rows from these values, and the CLI prints them one fact on - each line (refer to :func:`_status_panel` and :func:`status_facts`). Each read is - optional, because firmware that is older than a query gives nothing for it. Thus this - function works on any device. + This is the only place that asks the device for its live state. Both faces use what it + returns: the panel of the menu makes prose rows from these values, and the CLI prints + them one fact on each line (refer to :func:`status_panel` and :func:`status_facts`). + Each read is optional, because firmware that is older than a query gives nothing for + it. Thus this function works on any device. + + The device-query frame is not read here. :func:`~meshterm.core.device_config.build_snapshot` + already merges it into the snapshot, and one frame read one time is enough. Args: device: The connected device to query. Returns: - The merged raw readings: ``info``, ``battery``, ``stats``, and ``clock``. + The merged raw readings: ``battery``, ``stats``, ``clock``, and ``telemetry``. """ return { - "info": await _try(device.get_device_info) or {}, "battery": await _try(device.get_battery) or {}, "stats": await _try(device.get_stats) or {}, "clock": await _try(device.get_time), + "telemetry": await _try(device.get_self_telemetry) or [], } -async def _status_panel(device: Device, snapshot: dict) -> Panel: - """Build the live status panel: role, firmware, battery, clock, and statistics. +async def app_facts(ctx: AppContext, snapshot: dict) -> AppFacts: + """Collect what MeshTerm knows about the connected node, from its own stores. - This is the menu face of :func:`_read_status`. Each row is a short phrase, not an - atomic value, because a person reads "-110 dBm noise floor · last RSSI -62 dBm" in one - step. A script wants the three numbers separately. + Nothing here asks the radio. The place comes from the place service or from what it + stored before, the site and the paths from the outbound store, the counts from the + caches of the session, and the preset from the four radio settings. + + The count of contacts comes from the device-state cache, which is one read and which + the menu fills at startup. The count of channels comes from the same cache, but this + function never fills it: that probe reads every slot index, and a count is not worth + that cost on a report command. Thus the scripted face leaves the count of channels out + and keeps the capacity, which the device-query frame gives for nothing. Args: - device: The connected device to query. - snapshot: The settings snapshot that is already built (for the role and identity - fields). + ctx: The shared application context. + snapshot: The device snapshot (it gives the key, the location, and the radio + settings). + + Returns: + The facts, each one ``None`` where MeshTerm has nothing to say. + """ + key = str(snapshot.get("public_key") or "") + preset = current_preset(snapshot) + site, paths, fixed, kept = _outbound(ctx, key) + return AppFacts( + place=_place(ctx, key, snapshot), + site=site, + outbound_paths=paths, + fixed=fixed, + kept_routes=kept, + contacts=await _contact_count(ctx), + channels=_channel_count(ctx), + preset=preset.name if preset is not None else None, + ) + + +def _place(ctx: AppContext, key: str, snapshot: dict) -> str | None: + """The place of our own node, and a request to find it when a session can. + + MeshTerm never hears its own node, so the finder knows where this node is only when a + page tells it. The node page does the same (refer to + :meth:`~meshterm.services.places.PlaceService.want_at`). The request is for the next + time that this page opens: the panel is built one time, and a place that arrives after + that is not drawn again. + """ + from ..services import places as place_service + + service = place_service.current() + if service is not None: + service.want_at(key, snapshot.get("adv_lat"), snapshot.get("adv_lon")) + place = place_service.place_of(ctx, key) + return place.label if place is not None else None + + +def _outbound(ctx: AppContext, key: str) -> tuple[str | None, int | None, bool, int | None]: + """The active site, the outbound paths that apply here, and the kept device routes.""" + from ..core.outbound_store import SOURCE_DEVICE + + store = getattr(ctx, "outbound_store", None) + if store is None: + return None, None, False, None + try: + choice = store.lookup(key or None) + site = store.active_site() + if not choice.name and site is None: + return None, None, False, None + return ( + site.name if site is not None else None, + len(choice.paths), + choice.source == SOURCE_DEVICE, + len(store.kept_routes(key or None)), + ) + except Exception: # noqa: BLE001 - a store that cannot be read costs one row, not the page + return None, None, False, None + + +async def _contact_count(ctx: AppContext) -> int | None: + """How many contacts the device holds, or ``None`` when the read did not answer.""" + devstate = getattr(ctx, "devstate", None) + if devstate is None: + return None + try: + return len(await devstate.contacts()) + except Exception: # noqa: BLE001 - an optional count. Its absence is acceptable. + return None + + +def _channel_count(ctx: AppContext) -> int | None: + """How many channels are set, from the cache only (refer to :func:`app_facts`).""" + devstate = getattr(ctx, "devstate", None) + if devstate is None: + return None + try: + slots = devstate.peek_channel_slots() + except Exception: # noqa: BLE001 - an optional count. Its absence is acceptable. + return None + return None if slots is None else len(slots) + + +# -- the status panel ----------------------------------------------------------- + + +def status_panel(snapshot: dict, readings: dict, app: AppFacts) -> Panel: + """Build the live status panel: who this node is, how it is, and what it heard. + + This is the menu face of :func:`read_status` and :func:`app_facts`. Each row is a short + phrase, not an atomic value, because a person reads "-110 dBm noise floor · last RSSI + -62 dBm" in one step. A script wants the three numbers separately. + + The rows sit in a two-column grid, so a value that is wider than the panel wraps under + its own column and never goes back to column zero. A key is the one value that this + always costs a second line, and it stays whole: the page is where a user reads the key + of this node out to another person. + + Args: + snapshot: The device snapshot (the identity, the radio settings, and the facts of + the device-query frame). + readings: The live readings from :func:`read_status`. + app: What MeshTerm knows itself, from :func:`app_facts`. Returns: A Rich :class:`Panel` of status rows, each with a label and a value. """ - rows: list[tuple[str, Text]] = [] - readings = await _read_status(device) - info, battery, stats = readings["info"], readings["battery"], readings["stats"] + rows = _status_rows(snapshot, readings, app) + if not rows: + return Panel( + Text("no status reported", style="muted"), + title="[title.border]Status[/]", + border_style="border", + expand=False, + ) + grid = Table.grid(padding=(0, 2)) + grid.add_column(style="muted", no_wrap=True) + grid.add_column(overflow="fold") + for label, value in rows: + grid.add_row(label, value if value is not None else "") + return Panel(grid, title="[title.border]Status[/]", border_style="border", expand=False) + +def _status_rows(snapshot: dict, readings: dict, app: AppFacts) -> list[tuple[str, Text | None]]: + """The rows of the status panel, in four groups with a blank row between them. + + The groups answer four questions, in the order in which a user asks them: what this + node is, what MeshTerm does with it, how it is doing, and what it heard and sent. A row + whose value nothing reported is left out, so a panel never has a column of question + marks. + """ + battery, stats = readings["battery"], readings["stats"] + groups: list[list[tuple[str, Text]]] = [[], [], [], []] + + # 1. What this node is. adv_type = snapshot.get("adv_type") if adv_type is not None: - role = node_type_label(adv_type) - rows.append(("role", Text(role, style="brand"))) + groups[0].append(("role", Text(node_type_label(adv_type), style="brand"))) + key = str(snapshot.get("public_key") or "") + if key: + groups[0].append(("key", _key_text(key, snapshot))) + if snapshot.get("model"): + groups[0].append(("model", Text(str(snapshot["model"])))) + firmware = _firmware_text(snapshot) + if firmware is not None: + groups[0].append(("firmware", firmware)) + if app.place: + groups[0].append(("place", Text(app.place))) - if info.get("model"): - rows.append(("model", Text(str(info["model"])))) - firmware = _firmware(info) - if firmware: - rows.append(("firmware", Text(firmware))) + # 2. What MeshTerm does with it. + groups[1].append(("scope", _scope_text(snapshot))) + site = _site_text(app) + if site is not None: + groups[1].append(("site", site)) + groups[1].append(("preset", Text(app.preset or "custom", style="" if app.preset else "muted"))) + # 3. How it is doing. level = battery.get("level") if level: - rows.append(("battery", Text(f"{int(level) / 1000:.2f} V"))) + groups[2].append(("battery", Text(f"{int(level) / 1000:.2f} V"))) if battery.get("total_kb"): - rows.append(("storage", Text(f"{battery.get('used_kb', 0)} / {battery['total_kb']} kB"))) - + groups[2].append( + ("storage", Text(f"{battery.get('used_kb', 0)} / {battery['total_kb']} kB")) + ) + telemetry = _telemetry_text(readings["telemetry"]) + if telemetry is not None: + groups[2].append(("telemetry", telemetry)) clock = readings["clock"] if clock: stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(clock)) - rows.append(("clock", Text.assemble(stamp, (f" {_drift(clock)}", "muted")))) - + groups[2].append(("clock", Text.assemble(stamp, (f" {_drift(clock)}", "muted")))) if stats.get("uptime_secs") is not None: - rows.append(("uptime", Text(_uptime(int(stats["uptime_secs"]))))) + groups[2].append(("uptime", Text(_uptime(int(stats["uptime_secs"]))))) + contacts = _capacity_text(app.contacts, snapshot.get("max_contacts")) + if contacts is not None: + groups[2].append(("contacts", contacts)) + channels = _capacity_text(app.channels, snapshot.get("max_channels")) + if channels is not None: + groups[2].append(("channels", channels)) + if stats.get("queue_len") is not None: + groups[2].append(("queue", Text(f"{stats['queue_len']} waiting to send"))) + if stats.get("errors") is not None: + groups[2].append(("errors", _count_text(int(stats["errors"])))) + + # 4. What it heard and sent. if stats.get("noise_floor") is not None: parts = Text(f"{stats['noise_floor']} dBm noise floor") if stats.get("last_rssi") is not None: parts.append(f" · last RSSI {stats['last_rssi']} dBm", style="muted") if stats.get("last_snr") is not None: parts.append(f" · last SNR {stats['last_snr']:+.1f} dB", style="muted") - rows.append(("radio", parts)) + groups[3].append(("radio", parts)) if stats.get("tx_air_secs") is not None: - rows.append( + groups[3].append( ("airtime", Text(f"TX {stats['tx_air_secs']} s · RX {stats.get('rx_air_secs', 0)} s")) ) if stats.get("recv") is not None: packets = Text(f"{stats.get('sent', 0)} sent · {stats['recv']} received") if stats.get("recv_errors"): packets.append(f" · {stats['recv_errors']} receive errors", style="warn") - rows.append(("packets", packets)) + groups[3].append(("packets", packets)) + for label, sent, received in ( + ("flood", "flood_tx", "flood_rx"), + ("direct", "direct_tx", "direct_rx"), + ): + if stats.get(sent) is None and stats.get(received) is None: + continue + groups[3].append( + (label, Text(f"{stats.get(sent, 0)} sent · {stats.get(received, 0)} received")) + ) - width = max((len(label) for label, _ in rows), default=0) - body = Text() - for i, (label, value) in enumerate(rows): + rows: list[tuple[str, Text | None]] = [] + for group in groups: + if not group: + continue + if rows: + rows.append(("", None)) + rows.extend(group) + return rows + + +def _key_text(key: str, snapshot: dict) -> Text: + """The public key of this node, with the bytes that the mesh routes on lit.""" + from ..ui.widgets import highlighted_hash + + mode = snapshot.get("path_hash_mode") + prefix = (int(mode) + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0 + return highlighted_hash(key, prefix) + + +def _firmware_text(snapshot: dict) -> Text | None: + """The firmware version and build, with the companion protocol version after it.""" + version = _firmware(snapshot) + protocol = snapshot.get("fw ver") + if not version and protocol is None: + return None + text = Text(version or "unknown", style="" if version else "muted") + if protocol is not None: + text.append(f" · protocol {protocol}", style="muted") + return text + + +def _scope_text(snapshot: dict) -> Text: + """The default flood scope: its name and key, or the plain statement that it has none. + + A scope that the device stores with a key that its own name does not give is a fault + that nothing else shows. The row says so, because a packet that goes out under that + key reaches nobody who listens for the name. + """ + name = snapshot.get("flood_scope") + if not name: + text = Text("unscoped") + text.append(" · floods reach everyone", style="muted") + return text + text = Text(str(name)) + stored = str(snapshot.get("flood_scope_key") or "") + if stored: + text.append(f" · key {stored}", style="muted") + if stored != derived_scope_key(str(name)): + text.append(" · the key does not match the name", style="warn") + return text + + +def _site_text(app: AppFacts) -> Text | None: + """The active site, the outbound paths that apply, and the kept device routes.""" + if app.site is None and app.outbound_paths is None: + return None + text = Text(app.site or "no site", style="" if app.site else "muted") + if app.outbound_paths is not None: + text.append(f" · {app.outbound_paths} paths", style="muted") + text.append(" (this device)" if app.fixed else "", style="muted") + if app.kept_routes: + text.append(f" · {app.kept_routes} kept routes", style="muted") + return text + + +def _capacity_text(count: int | None, capacity: Any) -> Text | None: + """``27 / 300``, or one of the two numbers when the other one is not known.""" + total = int(capacity) if isinstance(capacity, (int, float)) else None + if count is None and total is None: + return None + if count is None: + return Text.assemble((f"{total}", "muted"), (" capacity", "muted")) + if total is None: + return Text(f"{count}") + return Text.assemble(f"{count}", (f" / {total}", "muted")) + + +def _count_text(count: int) -> Text: + """A count of faults: plain while it is zero, and in the warn colour once it is not.""" + return Text(str(count), style="warn" if count else "") + + +def _telemetry_text(telemetry: list[dict]) -> Text | None: + """The sensor readings of this node on one line, each with its unit.""" + if not telemetry: + return None + text = Text() + for i, reading in enumerate(telemetry): if i: - body.append("\n") - body.append(f"{label.ljust(width)} ", style="muted") - body.append_text(value) - if not rows: - body = Text("no status reported", style="muted") - return Panel(body, title="[title.border]Status[/]", border_style="border", expand=False) + text.append(" · ", style="muted") + text.append(f"{reading.get('name')} ", style="muted") + text.append(_reading_value(reading)) + return text -def _firmware(info: dict) -> str: +def _reading_value(reading: dict) -> str: + """One telemetry value with its unit: ``21.5 °C``, or the fields of a compound reading.""" + value = reading.get("value") + if isinstance(value, dict): + return ", ".join(f"{name} {_number(item)}" for name, item in value.items()) + unit = _UNITS.get(str(reading.get("name") or ""), "") + return f"{_number(value)} {unit}".strip() + + +def _number(value: Any) -> str: + """A reading as the shortest form that keeps it exact (``4.1``, not ``4.100000``).""" + if isinstance(value, bool): + return "yes" if value else "no" + if isinstance(value, (int, float)): + return f"{value:g}" + return str(value) + + +def _firmware(snapshot: dict) -> str: """The firmware version and build, joined, or ``""`` if the device reported neither.""" - return " ".join(str(info[k]) for k in ("ver", "fw_build") if info.get(k)) + return " ".join(str(snapshot[k]) for k in ("ver", "fw_build") if snapshot.get(k)) -async def status_facts(device: Device, snapshot: dict) -> Facts: +# -- the scripted faces --------------------------------------------------------- + + +def status_facts(snapshot: dict, readings: dict, app: AppFacts) -> Facts: """The live status of the device, as one set of facts. - This is the CLI face of :func:`_read_status`. The panel writes a phrase in each row, - but this function writes one value for each key. It puts the unit in the key - (``battery_v``, ``uptime_s``, ``noise_floor_dbm``), so that no program must get the - number out of prose. On both faces, a number never has a unit in its value. + This is the scripted face of :func:`read_status` and :func:`app_facts`. The panel + writes a phrase in each row, but this function writes one value for each key. It puts + the unit in the key (``battery_v``, ``uptime_s``, ``noise_floor_dbm``), so that no + program must get the number out of prose. On both faces, a number never has a unit in + its value. The three readings in seconds and the clock drift have a **gloss** next to the number: ``uptime_s 93784 (1d 2h)``. This is the only key/value block that can have a gloss. @@ -213,6 +561,11 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: ``93784`` is a value that no person can easily understand. The document holds only the number, because it has no useful place for a phrase. + ``flood_scope`` is also a setting, and the settings block of this command has it too. + Both blocks print the one value that ``config get flood_scope`` returns, in the one + spelling that ``config set`` takes back. The status block keeps it because + ``flood_scope_key`` is here, and a key with no name next to it says little. + If the firmware gave no answer for a reading, the plain block **leaves out** that reading, and it does not show a dash. These are optional queries. A missing key says "this device does not report it", but a dash says that it reported nothing. The @@ -221,8 +574,10 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: different here on purpose. Args: - device: The connected device to query. - snapshot: The settings snapshot that is already built (for the role and identity). + snapshot: The device snapshot (the identity, the settings, and the facts of the + device-query frame). + readings: The live readings from :func:`read_status`. + app: What MeshTerm knows itself, from :func:`app_facts`. Returns: The facts block. @@ -230,35 +585,52 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: from ..ui import fields from ..ui.report import Facts - readings = await _read_status(device) - info, battery, stats = readings["info"], readings["battery"], readings["stats"] - + battery, stats = readings["battery"], readings["stats"] level = battery.get("level") adv_type = snapshot.get("adv_type") clock = readings["clock"] + scope = snapshot.get("flood_scope") values: dict[str, Any] = { # The identity is first: which device this is. All the values that it can be set - # to are the answer of `config show`, not of this command. + # to are in the settings block below the status block. "name": snapshot.get("name"), "public_key": str(snapshot.get("public_key") or "").lower() or None, "role": node_type_label(adv_type), - "model": info.get("model"), - "firmware": _firmware(info) or None, + "model": snapshot.get("model"), + "firmware": _firmware(snapshot) or None, + "protocol_version": snapshot.get("fw ver"), + "place": app.place, + "flood_scope": None if scope is None else fields.Rendered(scope, scope or '""'), + "flood_scope_key": snapshot.get("flood_scope_key"), + "preset": app.preset, + "site": app.site, + "outbound_paths": app.outbound_paths, + "kept_routes": app.kept_routes, "battery_v": round(int(level) / 1000, 2) if level else None, "storage_used_kb": battery.get("used_kb", 0) if battery.get("total_kb") else None, "storage_total_kb": battery.get("total_kb"), + "contacts": app.contacts, + "max_contacts": snapshot.get("max_contacts"), + "channels": app.channels, + "max_channels": snapshot.get("max_channels"), "clock_at": ( datetime.fromtimestamp(clock, tz=timezone.utc).astimezone() if clock else None ), "clock_drift_s": (clock - int(time.time())) if clock else None, "uptime_s": stats.get("uptime_secs"), + "queue_len": stats.get("queue_len"), + "firmware_errors": stats.get("errors"), "noise_floor_dbm": stats.get("noise_floor"), "last_rssi_dbm": stats.get("last_rssi"), "last_snr_db": stats.get("last_snr"), "tx_air_s": stats.get("tx_air_secs"), "rx_air_s": stats.get("rx_air_secs"), "packets_sent": stats.get("sent"), + "packets_sent_flood": stats.get("flood_tx"), + "packets_sent_direct": stats.get("direct_tx"), "packets_received": stats.get("recv"), + "packets_received_flood": stats.get("flood_rx"), + "packets_received_direct": stats.get("direct_rx"), "receive_errors": stats.get("recv_errors"), } return Facts( @@ -269,19 +641,37 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: fields.word("role", "role"), fields.word("model", "model"), fields.word("firmware", "firmware"), + fields.integer("protocol_version", "protocol_version"), + fields.name("place", "place"), + fields.rendered("flood_scope", "flood_scope"), + fields.hexid("flood_scope_key", "flood_scope_key"), + fields.word("preset", "preset"), + fields.name("site", "site"), + fields.integer("outbound_paths", "outbound_paths"), + fields.integer("kept_routes", "kept_routes"), fields.decimal("battery_v", "battery_v", ".2f"), fields.integer("storage_used_kb", "storage_used_kb"), fields.integer("storage_total_kb", "storage_total_kb"), + fields.integer("contacts", "contacts"), + fields.integer("max_contacts", "max_contacts"), + fields.integer("channels", "channels"), + fields.integer("max_channels", "max_channels"), fields.instant("clock_at", "clock_at"), _glossed("clock_drift_s", _drift_gloss), _glossed("uptime_s", _span_gloss), + fields.integer("queue_len", "queue_len"), + fields.integer("firmware_errors", "firmware_errors"), fields.integer("noise_floor_dbm", "noise_floor_dbm"), fields.integer("last_rssi_dbm", "last_rssi_dbm"), fields.snr("last_snr_db", "last_snr_db"), _glossed("tx_air_s", _span_gloss), _glossed("rx_air_s", _span_gloss), fields.integer("packets_sent", "packets_sent"), + fields.integer("packets_sent_flood", "packets_sent_flood"), + fields.integer("packets_sent_direct", "packets_sent_direct"), fields.integer("packets_received", "packets_received"), + fields.integer("packets_received_flood", "packets_received_flood"), + fields.integer("packets_received_direct", "packets_received_direct"), fields.integer("receive_errors", "receive_errors"), ), values=values, @@ -289,6 +679,50 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: ) +def telemetry_listing(telemetry: list[dict]) -> Listing: + """The sensor readings of this node, one record for each reading. + + The readings are a listing and not more keys in the status block, because a device + reports whichever sensors it has. A key for each possible sensor would be a contract + that no firmware keeps. A record names the channel that the reading came from, the kind + of reading, and its value. + + The unit is a field of the record and not part of the key, because the kind of reading + is data here and not a key that MeshTerm declared. The plain face puts the unit in the + value, where a person reads it. The document keeps the number alone and the unit beside + it. + + Args: + telemetry: The readings from :func:`read_status`. + + Returns: + The listing. It has no records on a device that reports no sensors, and the plain + face then draws nothing. + """ + from ..ui import fields + from ..ui.report import Listing + + rows = [ + { + "channel": reading.get("channel"), + "name": reading.get("name"), + "unit": _UNITS.get(str(reading.get("name") or "")) or None, + "value": fields.Rendered(reading.get("value"), _reading_value(reading)), + } + for reading in telemetry + ] + return Listing( + key="telemetry", + columns=( + fields.integer("channel", "CHANNEL"), + fields.name("name", "READING"), + fields.rendered("value", "VALUE"), + fields.hidden("unit"), + ), + rows=rows, + ) + + def _glossed(key: str, gloss: Callable[[int], str]) -> Column: """A reading in seconds, printed as its number with a readable duration next to it.""" from ..ui import script @@ -327,12 +761,20 @@ async def _try(read) -> Any | None: def _drift(device_epoch: int) -> str: - """Describe the drift of the device clock, compared with the clock of this computer.""" + """Describe the drift of the device clock, compared with the clock of this computer. + + The drift is a duration that a person reads, and not a count of seconds: a clock that + was never set is a year out, and ``31330116 s`` says nothing. The scripted face writes + the same duration beside its own number (refer to :func:`_drift_gloss`), so the two + faces spell one drift one way. + """ + from ..ui import script + drift = device_epoch - int(time.time()) if abs(drift) < 2: return "(in sync)" direction = "ahead" if drift > 0 else "behind" - return f"({abs(drift)} s {direction})" + return f"({script.duration(abs(drift))} {direction})" def _uptime(secs: int) -> str: diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index 8bdda1e..b942ddc 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -53,7 +53,14 @@ _PATH_SPEC = re.compile(r"[0-9a-f]+(?:,[0-9a-f]+)*") _LISTINGS: list[tuple[str, list[str], list[str]]] = [ # (command, arguments, headings or keys the output must carry) ("contacts", [], ["NAME", "TYPE", "HEARD", "PKTS", "HASH", "LOCATION", "PLACE", "KEY"]), - ("info", [], ["name", "public_key", "role"]), + # ``info`` answers with three blocks: the status, the sensor readings, and every + # setting. The settings come from the definition that ``config show`` answers with, so + # one setting is never spelled two ways. + ( + "info", + [], + ["name", "public_key", "role", "queue_len", "packets_sent_flood", "CHANNEL", "radio_freq"], + ), ("config", ["show"], ["name", "radio_freq", "tx_power"]), ("preferences", ["show"], ["PREFERENCE", "VALUE", "DEFAULT", "DESCRIPTION"]), ("chat", ["list"], ["CONVERSATION", "KIND", "UNREAD", "LAST", "LAST_TEXT"]), diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 1f54b9f..96f796c 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -12,7 +12,7 @@ import pytest import typer from meshterm.core.config_io import backup_config, plan_restore, read_backup -from meshterm.core.connection import MockDevice +from meshterm.core.connection import MockDevice, derived_scope_key from meshterm.core.device_config import ( RADIO_PRESETS, DeviceConfigError, @@ -1818,11 +1818,12 @@ async def test_status_panel_reports_role_battery_clock_and_stats() -> None: from rich.console import Console - from meshterm.tools.info import _status_panel + from meshterm.tools.info import AppFacts, read_status, status_panel from meshterm.ui.theme import MESH_THEME device = await _connected_mock() - panel = await _status_panel(device, await build_snapshot(device)) + snapshot = await build_snapshot(device) + panel = status_panel(snapshot, await read_status(device), AppFacts(preset="Default")) console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) console.print(panel) out = console.file.getvalue() @@ -1836,6 +1837,97 @@ async def test_status_panel_reports_role_battery_clock_and_stats() -> None: assert "210 sent" in out and "1234 received" in out +async def test_status_panel_reports_the_facts_that_only_the_newer_frames_give() -> None: + """The panel draws each fact that the firmware reports and that no screen drew before.""" + import io + + from rich.console import Console + + from meshterm.tools.info import AppFacts, read_status, status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + await device.set_default_flood_scope("yul") + snapshot = await build_snapshot(device) + app = AppFacts(place="Villeray", site="Home", outbound_paths=2, kept_routes=3, contacts=27) + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(status_panel(snapshot, await read_status(device), app)) + out = console.file.getvalue() + + assert "protocol 12" in out # the companion API version of the device-query frame + assert "yul" in out and derived_scope_key("yul") in out # the scope and its key + assert "Villeray" in out and "Home" in out and "3 kept routes" in out + assert "27 / 300" in out # the contacts of the device against its capacity + assert "waiting to send" in out # the outbound queue of the firmware + assert "40 sent" in out and "900 received" in out # the flood split of the packets + assert "170 sent" in out and "334 received" in out # and the direct split + assert "temperature 21.5 °C" in out # the sensor readings of the node itself + + +async def test_status_panel_warns_when_a_stored_scope_key_is_not_the_key_of_its_name() -> None: + """A device that stores a key that its scope name does not give gets a warning on the row. + + Nothing else in MeshTerm can show this fault. A flood that goes out under that key + reaches no repeater that listens for the name. + """ + import io + + from rich.console import Console + + from meshterm.tools.info import AppFacts, read_status, status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + await device.set_default_flood_scope("yul") + snapshot = {**await build_snapshot(device), "flood_scope_key": "ff" * 16} + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(status_panel(snapshot, await read_status(device), AppFacts())) + + assert "does not match the name" in console.file.getvalue() + + +async def test_an_unscoped_device_says_that_its_floods_reach_everyone() -> None: + """With no default scope, the row is a statement and not an empty value.""" + import io + + from rich.console import Console + + from meshterm.tools.info import AppFacts, read_status, status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + snapshot = await build_snapshot(device) + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(status_panel(snapshot, await read_status(device), AppFacts())) + out = console.file.getvalue() + + assert "unscoped" in out and "floods reach everyone" in out + + +async def test_the_snapshot_holds_the_transport_key_of_the_default_scope() -> None: + """``build_snapshot`` reads the scope name and its key in one frame.""" + device = await _connected_mock() + await device.set_default_flood_scope("yul") + + snapshot = await build_snapshot(device) + + assert snapshot["flood_scope"] == "yul" + assert snapshot["flood_scope_key"] == derived_scope_key("yul") + + +async def test_telemetry_readings_carry_their_unit_on_each_face() -> None: + """The plain face puts the unit in the value. The document keeps the number alone.""" + from meshterm.tools.info import read_status, telemetry_listing + + device = await _connected_mock() + listing = telemetry_listing((await read_status(device))["telemetry"]) + rows = {row["name"]: row for row in listing.rows} + + assert rows["temperature"]["value"].text == "21.5 °C" + assert rows["temperature"]["value"].value == 21.5 + assert rows["temperature"]["unit"] == "°C" + + def test_uptime_renders_compact_units() -> None: """Uptime shows only seconds under a minute. Then it shows the d, h, and m parts as needed.""" from meshterm.tools.info import _uptime diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 36c3580..4c9a550 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -36,9 +36,11 @@ from types import SimpleNamespace import pytest from rich.cells import cell_len +from rich.console import Group from rich.text import Text from meshterm.core.channels import DEFAULT_PUBLIC_SECRET, derive_secret +from meshterm.core.connection import derived_scope_key from meshterm.core.courier_store import CourierStore from meshterm.core.models import ( NODE_TYPE_CHAT, @@ -73,6 +75,7 @@ from meshterm.services.message_paths import Arrival from meshterm.services.monitor_service import ACTIVITY_BUCKETS from meshterm.services.records import CATEGORY_BY_ID from meshterm.services.topology import MeshTopology, build_topology +from meshterm.tools.info import AppFacts, status_panel from meshterm.ui.about import ( AboutPage, about_author, @@ -1730,9 +1733,17 @@ def _tx_sweep(cols: int, rows: int) -> Screen: #: field that the config table draws, with the pairing PIN that the table conceals. _DEVICE_SNAPSHOT = { "name": "Homestead-Hub", + "public_key": "3d63c6429436b1e8a4f2c0d5768e9a1b2c3d4e5f60718293a4b5c6d7e8f90a1b", + "adv_type": 1, "adv_lat": 45.5017, "adv_lon": -73.5673, "ble_pin": 123456, + "model": "Heltec V3", + "ver": "v1.15.0", + "fw_build": "1a2b3c4d", + "fw ver": 12, + "max_contacts": 300, + "max_channels": 8, "radio_freq": 869525, "radio_bw": 250, "radio_sf": 11, @@ -1743,7 +1754,8 @@ _DEVICE_SNAPSHOT = { "rx_delay": 0.0, "manual_add_contacts": 0, "autoadd_config": 0, - "flood_scope": "", + "flood_scope": "yul", + "flood_scope_key": derived_scope_key("yul"), "adv_loc_policy": 1, "multi_acks": 0, "telemetry_mode_base": 1, @@ -1753,10 +1765,61 @@ _DEVICE_SNAPSHOT = { } +#: The live readings behind the status panel of the Device info page. Every field that any +#: of the three statistics frames reports is here, so that the gallery measures the widest +#: row that a real device can draw. +_DEVICE_READINGS = { + "battery": {"level": 4100, "used_kb": 412, "total_kb": 1024}, + "stats": { + "uptime_secs": 273_640, + "errors": 0, + "queue_len": 2, + "noise_floor": -112, + "last_rssi": -96, + "last_snr": 7.25, + "tx_air_secs": 318, + "rx_air_secs": 9_412, + "recv": 14_803, + "sent": 1_212, + "flood_tx": 388, + "direct_tx": 824, + "flood_rx": 11_590, + "direct_rx": 3_213, + "recv_errors": 41, + }, + "clock": 1_764_000_000, + "telemetry": [ + {"channel": 0, "name": "voltage", "value": 4.1}, + {"channel": 1, "name": "temperature", "value": 21.5}, + ], +} + +#: What MeshTerm knows about its own node, with each field filled: the panel then draws +#: every row that it has. +_DEVICE_APP_FACTS = AppFacts( + place="Villeray, Montréal", + site="Home", + outbound_paths=2, + kept_routes=3, + contacts=27, + channels=4, + preset="Default", +) + + +def _device_info_page(reveal: bool) -> Group: + """The Device info page: the status panel over the settings table, as the tool draws it.""" + return Group( + status_panel(_DEVICE_SNAPSHOT, _DEVICE_READINGS, _DEVICE_APP_FACTS), + Text(""), + config_table(_DEVICE_SNAPSHOT, {}, reveal_pin=reveal), + ) + + def _device_info(cols: int, rows: int) -> Screen: return DeviceInfoScreen( _GallerySession(cols, rows), - lambda reveal: config_table(_DEVICE_SNAPSHOT, {}, reveal_pin=reveal), + _device_info_page, title="Device info", conceals=has_pin(_DEVICE_SNAPSHOT), ) diff --git a/tests/test_places.py b/tests/test_places.py index 26de05e..0854012 100644 --- a/tests/test_places.py +++ b/tests/test_places.py @@ -268,6 +268,40 @@ def _run(coro): # noqa: ANN001, ANN202 - a small helper for the async steps return asyncio.run(coro) +def test_place_of_answers_through_a_running_service(tmp_path: Path) -> None: + """With a service, ``place_of`` gives what the service holds.""" + service, repo = _service(tmp_path) + repo.save_node_place("aaaaaaaaaaaa", 45.0, -73.0, Place("Villeray", "Montréal", SOURCE_TILES)) + + place = places_service.place_of(service._ctx, "aaaaaaaaaaaa") + + assert place is not None and place.label == "Villeray, Montréal" + + +def test_place_of_reads_the_stores_when_no_service_runs(tmp_path: Path) -> None: + """A scripted run has no service, so the function reads the two sources itself. + + The Device info page and ``meshterm info`` must name the same place. The page has a + service and the command has none, so this path is the one that the command takes. + """ + service, repo = _service(tmp_path) + ctx = service._ctx + places_service._CURRENT = None # the state of a scripted run: no session made a service + try: + repo.save_node_place( + "aaaaaaaaaaaa", 45.0, -73.0, Place("Villeray", "Montréal", SOURCE_TILES) + ) + repo.save_node_place("bbbbbbbbbbbb", 45.0, -73.0, Place(None, None, SOURCE_TILES)) + ctx.place_store.set("cccccccccccc", "The Shed", when=0) + + assert places_service.place_of(ctx, "aaaaaaaaaaaa").label == "Villeray, Montréal" + assert places_service.place_of(ctx, "bbbbbbbbbbbb") is None # an empty place is none + assert places_service.place_of(ctx, "cccccccccccc").label == "The Shed" # typed + assert places_service.place_of(ctx, None) is None + finally: + places_service._CURRENT = service + + def test_a_typed_place_wins_and_an_empty_place_is_none(tmp_path: Path) -> None: """A typed place wins over a found place, and an empty found place is none.""" service, repo = _service(tmp_path)