diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 01cbac2..420cb31 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -2873,25 +2873,46 @@ class MockDevice(Device): self._admin_sessions.add(self._mock_key(node)) return LoginResult.ACCEPTED - #: The simulated repeater CLI's configuration defaults (see send_remote_command). + #: The simulated repeater CLI's configuration, keyed and answered the way MeshCore's + #: ``CommonCLI.cpp`` does (see send_remote_command). What is absent is absent on purpose: + #: a board with no front-end module and a build with no bridge, so a read of those + #: answers ``??:`` exactly as that hardware would. _REMOTE_CFG_DEFAULTS = { + "owner.info": "", + "lat": "0", + "lon": "0", "freq": "910.525", "bw": "62.5", "sf": "7", "cr": "5", - "lat": "0", - "lon": "0", + "radio.rxgain": "on", + "cad": "off", + "int.thresh": "0", + "agc.reset.interval": "0", "repeat": "on", - "txdelay": "0", - "direct.txdelay": "0", + "txdelay": "0.5", + "direct.txdelay": "0.2", "rxdelay": "0", "af": "1", - "allow.read.only": "off", + "loop.detect": "off", + "path.hash.mode": "0", + "multi.acks": "0", + "flood.max": "64", + "flood.max.unscoped": "64", + "flood.max.advert": "8", "advert.interval": "240", "flood.advert.interval": "12", - "flood.max": "64", + "guest.password": "", + "allow.read.only": "off", + "powersaving": "off", + "adc.multiplier": "0.000", + "gps advert": "none", + "bridge.type": "none", } + #: The ``get radio`` fields, in the order the reply joins them. + _REMOTE_RADIO = ("freq", "bw", "sf", "cr") + async def send_remote_command( # noqa: D102 - inherited docstring self, node: Contact, command: str, *, timeout: float = 8.0 ) -> str | None: @@ -2914,25 +2935,57 @@ class MockDevice(Device): if verb == "neighbors": table = self._neighbour_tables.get(node.key_prefix or "", []) return "\n".join(f"{p} {snr:+.1f}dB {ago}s" for p, snr, ago in table) or "none" + if verb == "powersaving": + if len(parts) == 2 and parts[1] in ("on", "off"): + cfg["powersaving"] = parts[1] + return cfg["powersaving"] # bare, no "> ": a verb, not a get + if verb == "gps": + if parts[1:2] == ["advert"]: + if len(parts) == 2: + return f"> {cfg['gps advert']}" + if parts[2] in ("none", "share", "prefs"): + cfg["gps advert"] = parts[2] + return "OK" + return "error: expected none, share or prefs" + if len(parts) == 1: + return "off" # no receiver on this board + return "gps toggle not supported" if verb == "get" and len(parts) == 2: param = parts[1].lower() if param == "tx": - return str(self._remote_tx.get(key, self._default_remote_tx)) - if param == "guest.password": - return f"ERR: unknown config: {param}" # write-only, like hardware - value = cfg.get(param) - return f"> {value}" if value is not None else f"ERR: unknown config: {param}" + return f"> {self._remote_tx.get(key, self._default_remote_tx)}" + if param == "radio": + return "> " + ",".join(cfg[name] for name in self._REMOTE_RADIO) + if param == "dutycycle": + return f"> {100.0 / (float(cfg['af']) + 1.0):.1f}%" + if param in cfg and param not in ("gps advert", "powersaving"): + return f"> {cfg[param]}" + return f"??: {param}" if verb == "set" and len(parts) >= 3: param = parts[1].lower() value = " ".join(parts[2:]) if param == "tx": self._remote_tx[key] = int(float(value)) return "OK" - if param in cfg or param == "guest.password": + if param == "radio": + fields = value.split(",") + if len(fields) != len(self._REMOTE_RADIO): + return "Error, invalid params" + cfg.update(zip(self._REMOTE_RADIO, fields, strict=True)) + return "OK - reboot to apply" + if param == "dutycycle": + duty = float(value) + if not 1 <= duty <= 100: + return "ERROR: dutycycle must be 1-100" + cfg["af"] = f"{100.0 / duty - 1.0:g}" + return f"OK - {duty:.1f}%" + # freq alone is serial-only; the rest of the radio goes through "set radio". + read_only = (*self._REMOTE_RADIO, "bridge.type", "gps advert", "powersaving") + if param in cfg and param not in read_only: cfg[param] = value return "OK" - return f"ERR: unknown config: {param}" - return f"ERR: unknown command: {command.strip()}" + return f"unknown config: {param} {value}" + return f"??: {command.strip()}" async def get_remote_tx_power(self, node: Contact) -> int | None: # noqa: D102 key = self._mock_key(node) diff --git a/meshterm/core/remote_config.py b/meshterm/core/remote_config.py index fcd7b5c..81b3739 100644 --- a/meshterm/core/remote_config.py +++ b/meshterm/core/remote_config.py @@ -7,23 +7,78 @@ companion protocol the local device-configuration editor drives. This module is data-driven bridge: one :class:`RemoteSetting` per knob the standard MeshCore repeater firmware exposes, each carrying its CLI spelling, a one-line explanation, and enough typing to prompt and validate sensibly. The repeater-admin screen renders the catalog in -the local editor's lanes, stages values, and applies them as ``set`` commands; anything -the catalog doesn't cover is one keystroke away in the raw command line. +the local editor's lanes, stages values, and applies them; anything the catalog doesn't +cover is one keystroke away in the raw command line. -Replies are parsed *loosely* on purpose: repeater firmware answers tersely and -inconsistently across versions (``"tx: 20"``, ``"TX power = 20 dBm"``, ``"> ok"``), so -values are extracted rather than pattern-matched, and the raw reply is always kept for -display. Firmware without a given key simply answers with an error string, which shows -in the value lane instead of breaking the screen. +The catalog is transcribed from the firmware itself — ``handleGetCmd``/``handleSetCmd``/ +``handleCommand`` in MeshCore's ``src/helpers/CommonCLI.cpp`` — not from convention, and +three of its shapes only make sense against that source: + +* **Some settings are not ``get``/``set`` keys at all.** ``powersaving``, ``gps`` and + ``gps advert`` are top-level verbs that answer bare and take their value as an argument + (:attr:`RemoteSetting.verb`). +* **Some settings travel together.** There is no ``get bw``: frequency, bandwidth, + spreading factor and coding rate are read as one ``get radio`` reply and written as one + ``set radio f,bw,sf,cr`` (``set freq`` alone is refused over the mesh — the firmware + honours it only on its serial console). Those four are one + :attr:`RemoteSetting.composite`, and :func:`read_plan`/:func:`write_plan` turn a screen's + worth of rows into the fewest round trips that carry them. +* **One firmware value can have two spellings.** ``dutycycle`` (1.15+) and the older + ``af`` both read and write ``airtime_factor``, so writing one stales the other + (:attr:`RemoteSetting.overlaps`). + +Replies are parsed *loosely* on purpose: repeater firmware answers tersely and has changed +its phrasing across versions (``"> 20"``, ``"tx: 20"``, ``"OK - repeat is now ON"``), so +values are extracted rather than pattern-matched. Firmware without a given key answers +with an error string (``??: key`` to a ``get``, ``unknown config: …`` to a ``set``), which +the screen records as *this node doesn't have it* rather than breaking. """ from __future__ import annotations import re +from collections.abc import Iterable, Mapping from dataclasses import dataclass -#: Reply text (lowercased) that reads as the firmware refusing/unknowing a command. -_ERRORISH = ("unknown", "error", "err:", "invalid", "denied", "bad ") +#: Reply text (lowercased) that reads as the firmware refusing/unknowing a command. ``??:`` +#: is how ``handleGetCmd`` answers a key it doesn't know; ``unknown config:`` is its ``set`` +#: twin. +_ERRORISH = ( + "??:", + "unknown", + "error", + "err:", + "invalid", + "denied", + "bad ", + "not supported", + "unsupported", +) + +#: A ``get`` reply's value echo. Whatever follows it is a value, even one that happens to +#: contain an error-ish word (a node named ``Unknown-Hill`` is not a refusal). +_ECHO = re.compile(r"^\s*-?>\s?") + +#: The words a boolean reply may use for each state, beyond the setting's own +#: :attr:`RemoteSetting.words`. +_ON_WORDS = frozenset({"on", "true", "yes", "1"}) +_OFF_WORDS = frozenset({"off", "false", "no", "0"}) + + +@dataclass(frozen=True, slots=True) +class Option: + """One value of an enumerated remote setting. + + Attributes: + value: What the firmware takes in a ``set`` and answers to a ``get`` — also what + the cache stores. + label: What the value lane and the picker show for it. + help: An optional one-line explanation for the picker row. + """ + + value: str + label: str + help: str = "" @dataclass(frozen=True, slots=True) @@ -31,16 +86,35 @@ class RemoteSetting: """One remote-CLI setting: its spelling, presentation, and typing. Attributes: - key: The CLI parameter name as the firmware spells it (e.g. ``"txdelay"``). + key: The setting's identity: the CLI parameter name as the firmware spells it + (``"txdelay"``) for a ``get``/``set`` key, the verb for a verb-shaped one, and + the field's own name for a composite member. It is also the cache key. label: The display name shown in the editor lane. help: One-line explanation (no trailing period), shown beside the value. category: Editor section heading the setting sorts under. - kind: ``"int"``, ``"float"``, ``"str"``, or ``"bool"`` (on/off). - writable: Whether the firmware accepts a ``set`` for this key. - readable: Whether the firmware answers a ``get`` (passwords do not). + kind: ``"int"``, ``"float"``, ``"str"``, ``"bool"`` (on/off) or ``"enum"``. + writable: Whether the firmware accepts a write for this setting. + readable: Whether the firmware answers a read for it. minimum: Lower bound for numeric prompts, when known. maximum: Upper bound for numeric prompts, when known. unit: Display unit hint (e.g. ``"dBm"``, ``"min"``), purely cosmetic. + decimals: Fixed decimal places a float is shown and sent with; ``None`` shows it + as the firmware gave it, trailing zeros trimmed. + zero_off: Whether ``0`` is accepted outside ``minimum``–``maximum``, meaning off + (the advert intervals: 0, or 60–240 minutes). + options: The values an ``enum`` takes, in picker order. + words: What a ``bool`` sends for on and off. Most keys take ``on``/``off``; + ``multi.acks`` is an ``atoi`` and needs ``1``/``0``. + aliases: ``(reply word, value)`` pairs consulted before the kind's own parse, for + a reply that names a value in words of its own — ``bridge.source`` answers + ``logRx`` to what it is told as ``rx``. + verb: For a verb-shaped setting, the command that reads it bare and writes it + with the value appended (``"powersaving"``); empty for a ``get``/``set`` key. + composite: The CLI key a group of settings is read and written through as one + comma-joined value (``"radio"``); empty for a setting that stands alone. + part: This setting's position within its composite's comma-joined value. + overlaps: Keys that are another spelling of the same firmware value, whose cached + reading a write to this one makes stale. """ key: str @@ -53,29 +127,81 @@ class RemoteSetting: minimum: float | None = None maximum: float | None = None unit: str = "" + decimals: int | None = None + zero_off: bool = False + options: tuple[Option, ...] = () + words: tuple[str, str] = ("on", "off") + aliases: tuple[tuple[str, str], ...] = () + verb: str = "" + composite: str = "" + part: int = 0 + overlaps: tuple[str, ...] = () @property def get_command(self) -> str: - """The CLI command that reads this setting.""" - return f"get {self.key}" + """The CLI command that reads this setting (shared by a composite's members).""" + if self.verb: + return self.verb + return f"get {self.composite or self.key}" def set_command(self, value: str) -> str: - """The CLI command that writes ``value`` to this setting.""" + """The CLI command that writes ``value`` to this setting. + + Raises: + ValueError: For a composite member, which is only ever written together with + its siblings — see :func:`write_plan`. + """ + if self.composite: + raise ValueError(f"{self.key} is written through 'set {self.composite}'") + if self.kind == "bool": + value = self.words[0] if value == "on" else self.words[1] + if self.verb: + return f"{self.verb} {value}" return f"set {self.key} {value}" + def display(self, value: str) -> str: + """The value lane's text for a stored ``value`` (an enum shows its label).""" + for option in self.options: + if option.value == value: + return option.label + return value -#: Every knob the standard MeshCore repeater/room firmware exposes over its CLI, in the -#: editor's display order. TX delay and Direct TX delay — absent from the local -#: companion editor because companions don't repeat — are first-class here. + +def _radio(key: str, label: str, help_text: str, part: int, **typing) -> RemoteSetting: + """One of the four fields ``get radio`` answers and ``set radio`` takes together.""" + return RemoteSetting( + key=key, + label=label, + help=help_text, + category="Radio", + composite="radio", + part=part, + **typing, + ) + + +#: Every setting the standard MeshCore repeater/room firmware exposes over the mesh, in the +#: editor's display order. Board- and build-dependent ones (the front-end module's gains, +#: GPS, the bridge) are listed like any other: a node built without them answers ``??:``, +#: and the row says so instead of the catalog guessing which board it is talking to. Left +#: out on purpose: ``prv.key`` and ``freq`` writes (serial console only), ``extra.sf`` +#: (LR2021 builds only, format board-defined), and the read-only diagnostics +#: (``public.key``, ``role``, ``bootloader.ver``, ``pwrmgt.*``) — facts, not settings, and +#: each one a paced round trip on every read. The command line reaches them all. REPEATER_SETTINGS: tuple[RemoteSetting, ...] = ( # -- Identity --------------------------------------------------------------- RemoteSetting( key="name", label="Name", category="Identity", - kind="str", help="The node's advertised name", ), + RemoteSetting( + key="owner.info", + label="Owner info", + category="Identity", + help="Owner contact details (| starts a new line)", + ), RemoteSetting( key="lat", label="Latitude", @@ -95,39 +221,43 @@ REPEATER_SETTINGS: tuple[RemoteSetting, ...] = ( help="Advertised position, decimal degrees", ), # -- Radio ------------------------------------------------------------------ - RemoteSetting( - key="freq", - label="Frequency", - category="Radio", + _radio( + "freq", + "Frequency", + "Carrier frequency — every node on the mesh must match; reboot to apply", + 0, kind="float", unit="MHz", - help="Carrier frequency — every node on the mesh must match", + minimum=150, + maximum=2500, ), - RemoteSetting( - key="bw", - label="Bandwidth", - category="Radio", + _radio( + "bw", + "Bandwidth", + "Channel bandwidth — must match the mesh; reboot to apply", + 1, kind="float", unit="kHz", - help="Channel bandwidth — must match the mesh", - ), - RemoteSetting( - key="sf", - label="Spreading factor", - category="Radio", - kind="int", minimum=7, - maximum=12, - help="LoRa spreading factor — must match the mesh", + maximum=500, ), - RemoteSetting( - key="cr", - label="Coding rate", - category="Radio", + _radio( + "sf", + "Spreading factor", + "LoRa spreading factor — must match the mesh; reboot to apply", + 2, + kind="int", + minimum=5, + maximum=12, + ), + _radio( + "cr", + "Coding rate", + "LoRa coding rate denominator — must match the mesh; reboot to apply", + 3, kind="int", minimum=5, maximum=8, - help="LoRa coding rate denominator — must match the mesh", ), RemoteSetting( key="tx", @@ -139,6 +269,50 @@ REPEATER_SETTINGS: tuple[RemoteSetting, ...] = ( maximum=30, help="Transmit power — the TX optimize tool tunes this by measurement", ), + RemoteSetting( + key="radio.rxgain", + label="Boosted RX gain", + category="Radio", + kind="bool", + help="The receiver's boosted gain mode (firmware 1.14.1+)", + ), + RemoteSetting( + key="radio.fem.rxgain", + label="FEM RX gain", + category="Radio", + kind="bool", + help="The front-end module's receive gain (boards with one)", + ), + RemoteSetting( + key="radio.fem.txgain", + label="FEM TX gain", + category="Radio", + kind="bool", + help="The front-end module's transmit gain (boards with one)", + ), + RemoteSetting( + key="cad", + label="Activity detection", + category="Radio", + kind="bool", + help="Listen for LoRa activity in hardware before transmitting", + ), + RemoteSetting( + key="int.thresh", + label="Interference threshold", + category="Radio", + kind="int", + help="Local interference threshold (0 = off)", + ), + RemoteSetting( + key="agc.reset.interval", + label="AGC reset interval", + category="Radio", + kind="int", + unit="s", + minimum=0, + help="Seconds between receiver gain resets, in steps of 4 (0 = off)", + ), # -- Repeating ---------------------------------------------------------------- RemoteSetting( key="repeat", @@ -151,40 +325,121 @@ REPEATER_SETTINGS: tuple[RemoteSetting, ...] = ( key="txdelay", label="TX delay", category="Repeating", - kind="int", + kind="float", + decimals=2, minimum=0, + maximum=2, help="Delay factor before rebroadcasting a flood packet", ), RemoteSetting( key="direct.txdelay", label="Direct TX delay", category="Repeating", - kind="int", + kind="float", + decimals=2, minimum=0, + maximum=2, help="Delay factor before forwarding a directed packet", ), RemoteSetting( key="rxdelay", label="RX delay", category="Repeating", - kind="int", + kind="float", + decimals=2, minimum=0, + maximum=20, help="Base delay before acting on a received packet", ), + RemoteSetting( + key="dutycycle", + label="Duty cycle", + category="Repeating", + kind="float", + decimals=1, + unit="%", + minimum=1, + maximum=100, + overlaps=("af",), + help="Share of the air the node may transmit in (firmware 1.15+)", + ), RemoteSetting( key="af", label="Airtime factor", category="Repeating", kind="float", + decimals=2, minimum=0, - help="Duty-cycle multiplier applied to every transmission", + maximum=9, + overlaps=("dutycycle",), + help="Older firmware's duty-cycle knob: duty cycle = 100 / (af + 1) %", ), RemoteSetting( - key="allow.read.only", - label="Allow read-only", + key="loop.detect", + label="Loop detection", + category="Repeating", + kind="enum", + options=( + Option("off", "off"), + Option("minimal", "minimal"), + Option("moderate", "moderate"), + Option("strict", "strict"), + ), + help="How readily the node drops a packet that loops back through it", + ), + RemoteSetting( + key="path.hash.mode", + label="Path-hash mode", + category="Repeating", + kind="enum", + # The firmware refuses 3 here (``mode < 3``), though the field has room for it. The + # labels stay short because the widest value sizes the lane for every row: "hashes" + # in each one pushed the descriptions off a 72-column screen once one was staged. + options=( + Option("0", "1-byte", "The default"), + Option("1", "2-byte"), + Option("2", "3-byte"), + ), + help="Longer hop ids mix up fewer nodes, but cost space", + ), + RemoteSetting( + key="multi.acks", + label="Multi-acks", category="Repeating", kind="bool", - help="Whether guests may log in with the guest password", + words=("1", "0"), + help="Send extra receipts so replies get through", + ), + # -- Flooding ----------------------------------------------------------------- + RemoteSetting( + key="flood.max", + label="Flood max", + category="Flooding", + kind="int", + unit="hops", + minimum=0, + maximum=64, + help="A flood that already took this many hops isn't rebroadcast", + ), + RemoteSetting( + key="flood.max.unscoped", + label="Flood max (unscoped)", + category="Flooding", + kind="int", + unit="hops", + minimum=0, + maximum=64, + help="The same cap, for floods sent without a region scope", + ), + RemoteSetting( + key="flood.max.advert", + label="Flood max (adverts)", + category="Flooding", + kind="int", + unit="hops", + minimum=0, + maximum=64, + help="The same cap, for flooded adverts", ), # -- Adverts ----------------------------------------------------------------- RemoteSetting( @@ -193,8 +448,10 @@ REPEATER_SETTINGS: tuple[RemoteSetting, ...] = ( category="Adverts", kind="int", unit="min", - minimum=0, - help="Minutes between the node's own zero-hop adverts (0 = off)", + minimum=60, + maximum=240, + zero_off=True, + help="Minutes between the node's own zero-hop adverts, in steps of 2 (0 = off)", ), RemoteSetting( key="flood.advert.interval", @@ -202,59 +459,199 @@ REPEATER_SETTINGS: tuple[RemoteSetting, ...] = ( category="Adverts", kind="int", unit="h", - minimum=0, + minimum=3, + maximum=168, + zero_off=True, help="Hours between the node's own flood adverts (0 = off)", ), - RemoteSetting( - key="flood.max", - label="Flood max", - category="Adverts", - kind="int", - minimum=0, - help="Hop cap the node applies when rebroadcasting floods (0 = no cap)", - ), # -- Access ------------------------------------------------------------------ RemoteSetting( key="guest.password", label="Guest password", category="Access", - kind="str", - readable=False, - help="Read-only login password (write-only over the CLI)", + help="Password for read-only (guest) logins", + ), + RemoteSetting( + key="allow.read.only", + label="Allow read-only", + category="Access", + kind="bool", + help="Allow read-only access (room servers)", + ), + # -- Power ------------------------------------------------------------------- + RemoteSetting( + key="powersaving", + label="Power saving", + category="Power", + kind="bool", + verb="powersaving", + help="Sleep between transmissions to save battery", + ), + RemoteSetting( + key="adc.multiplier", + label="ADC multiplier", + category="Power", + kind="float", + decimals=3, + minimum=0, + maximum=10, + help="Battery voltage calibration (0 = the board's default)", + ), + # -- GPS --------------------------------------------------------------------- + RemoteSetting( + key="gps", + label="GPS", + category="GPS", + kind="bool", + verb="gps", + # A board with a receiver answers "on, active|deactivated, fix, N sats" whether or + # not it is enabled; the second word is the one that says. + aliases=(("active", "on"), ("deactivated", "off")), + help="Run the node's GPS receiver (boards with one)", + ), + RemoteSetting( + key="gps advert", + label="Advertised position", + category="GPS", + kind="enum", + verb="gps advert", + options=( + Option("none", "none", "Advertise no position"), + Option("share", "share", "Advertise the live GPS fix"), + Option("prefs", "prefs", "Advertise the latitude and longitude set above"), + ), + help="Which position the node's adverts carry", + ), + # -- Bridge ------------------------------------------------------------------ + RemoteSetting( + key="bridge.type", + label="Bridge type", + category="Bridge", + writable=False, + help="The bridge this firmware was built with: none, rs232 or espnow", + ), + RemoteSetting( + key="bridge.enabled", + label="Bridge enabled", + category="Bridge", + kind="bool", + help="Relay packets over the bridge", + ), + RemoteSetting( + key="bridge.source", + label="Bridge source", + category="Bridge", + kind="enum", + options=( + Option("rx", "received", "Bridge the packets the node receives"), + Option("tx", "transmitted", "Bridge the packets the node transmits"), + ), + aliases=(("logrx", "rx"), ("logtx", "tx")), + help="Which packets cross the bridge", + ), + RemoteSetting( + key="bridge.delay", + label="Bridge delay", + category="Bridge", + kind="int", + unit="ms", + minimum=0, + maximum=10000, + help="Delay before a packet crosses the bridge", + ), + RemoteSetting( + key="bridge.baud", + label="Bridge baud rate", + category="Bridge", + kind="enum", + options=tuple( + Option(rate, f"{rate} baud") for rate in ("9600", "19200", "38400", "57600", "115200") + ), + help="Serial speed (RS-232 bridges)", + ), + RemoteSetting( + key="bridge.channel", + label="Bridge channel", + category="Bridge", + kind="int", + minimum=1, + maximum=14, + help="Wi-Fi channel (ESP-NOW bridges)", + ), + RemoteSetting( + key="bridge.secret", + label="Bridge secret", + category="Bridge", + help="Shared secret, up to 15 characters (ESP-NOW bridges)", ), ) -#: Commands the remote CLI screen offers as completions, beyond the catalog's -#: ``get``/``set`` spellings: the fixed verbs a MeshCore repeater understands. +#: Commands the remote CLI screen offers as completions, beyond the catalog's own read and +#: write spellings: the fixed verbs a MeshCore repeater answers over the mesh. The ones its +#: firmware keeps to the serial console (``erase``, ``log`` dumps, ``stats-*``) are left out, +#: since completing them would only invite a refusal. KNOWN_COMMANDS: tuple[str, ...] = ( "advert", + "advert.zerohop", + "board", + "clear stats", + "clkreboot", "clock", "clock sync", + "discover.neighbors", "get ", + "get public.key", + "get role", + "gps setloc", + "gps sync", + "log erase", + "log start", + "log stop", + "neighbor.remove ", "neighbors", "password ", + "poweroff", "reboot", + "region", + "region allowf ", + "region default", + "region denyf ", + "region get ", + "region home", + "region put ", + "region remove ", + "region save", + "sensor get ", + "sensor list", + "sensor set ", "set ", + "setperm ", "start ota", + "tempradio ", "time ", "ver", ) def known_commands() -> list[str]: - """Every completion the remote CLI offers: verbs plus catalog get/set spellings.""" + """Every completion the remote CLI offers: verbs plus the catalog's read/write spellings.""" commands = set(KNOWN_COMMANDS) for spec in REPEATER_SETTINGS: if spec.readable: commands.add(spec.get_command) if spec.writable: - commands.add(f"set {spec.key} ") + if spec.composite: + commands.add(f"set {spec.composite} ") + elif spec.verb: + commands.add(f"{spec.verb} ") + else: + commands.add(f"set {spec.key} ") return sorted(commands) def get_setting(key: str) -> RemoteSetting | None: - """Look up a catalog setting by its CLI key.""" + """Look up a catalog setting by its key.""" return next((s for s in REPEATER_SETTINGS if s.key == key), None) @@ -266,50 +663,103 @@ def settings_by_category() -> list[tuple[str, list[RemoteSetting]]]: return list(grouped.items()) +def composite_members(composite: str) -> list[RemoteSetting]: + """The settings a composite key carries, in their comma-joined order.""" + return sorted((s for s in REPEATER_SETTINGS if s.composite == composite), key=lambda s: s.part) + + def reply_is_error(reply: str) -> bool: - """Whether a reply text reads as the firmware refusing the command.""" + """Whether a reply text reads as the firmware refusing the command. + + A reply that opens with a ``get``'s ``>`` value echo is a value, whatever it says. + """ + if _ECHO.match(reply): + return False lowered = reply.lower() return any(marker in lowered for marker in _ERRORISH) def parse_reply_value(spec: RemoteSetting, reply: str | None) -> str | None: - """Extract a display value from a ``get`` reply, or ``None`` when unusable. + """Extract a stored value from a read's reply, or ``None`` when unusable. - Numeric settings pull the first number out of the terse, version-varying reply - text (the ``get tx`` convention); strings strip a leading ``key:``/``>`` echo. - Error-ish replies parse as ``None`` so a firmware without the key shows unknown - rather than adopting the error string as a value. + Numbers are pulled out of whatever phrasing the firmware used and formatted the way + :func:`normalize_value` formats a typed one, so a value read back compares equal to the + same value staged. A composite member takes its own field of the comma-joined reply. + Error-ish replies parse as ``None`` so a firmware without the key never adopts the error + string as a value. Args: spec: The setting the reply answers. reply: The raw reply text, or ``None`` if the node never answered. Returns: - The value as display text, or ``None``. + The value as stored text (an enum's :attr:`Option.value`, a bool's ``on``/``off``), + ``""`` for a string the node reports as empty, or ``None``. """ - if not reply or reply_is_error(reply): + if reply is None or reply_is_error(reply): return None - text = reply.strip() + echoed = bool(_ECHO.match(reply)) + text = _ECHO.sub("", reply.strip(), count=1).strip() + # Some firmware versions echo the key instead of ">": "tx: 20", "name = Yagi". + text = re.sub(rf"^{re.escape(spec.key)}\s*[:=]\s*", "", text, flags=re.I) + if spec.composite: + pieces = text.split(",") + if len(pieces) != len(composite_members(spec.composite)): + return None + text = pieces[spec.part].strip() + tokens = re.findall(r"[\w.+-]+", text.lower()) + for word, value in spec.aliases: + if word in tokens: + return value if spec.kind in ("int", "float"): match = re.search(r"-?\d+(?:\.\d+)?", text) - if match is None: - return None - raw = match.group() - if spec.kind == "int": - return str(int(float(raw))) - return f"{float(raw):g}" + return None if match is None else _format_number(spec, float(match.group())) if spec.kind == "bool": - lowered = text.lower() - if any(t in lowered for t in ("on", "true", "yes", "1")): - return "on" - if any(t in lowered for t in ("off", "false", "no", "0")): - return "off" + on_words = _ON_WORDS | {spec.words[0]} + off_words = _OFF_WORDS | {spec.words[1]} + for token in tokens: + if token in on_words: + return "on" + if token in off_words: + return "off" return None - # Strings: drop a "key:" or "-> " echo prefix if the firmware included one. - text = re.sub(rf"^\s*(?:>|->|{re.escape(spec.key)}\s*[:=])\s*", "", text, flags=re.I) + if spec.kind == "enum": + by_value = {option.value.lower(): option.value for option in spec.options} + return next((by_value[t] for t in tokens if t in by_value), None) + if echoed: + return text # "> " with nothing after it is an empty string, which is a value return text or None +def _format_number(spec: RemoteSetting, value: float) -> str: + """One number as the cache stores it: whole, fixed-decimal, or trimmed.""" + if spec.kind == "int": + return str(int(round(value))) + if spec.decimals is not None: + text = f"{value:.{spec.decimals}f}" + else: + # The firmware's own ftoa: up to 7 places, trailing zeros trimmed. + text = f"{value:.7f}".rstrip("0").rstrip(".") + return text.lstrip("-") if float(text) == 0 else text + + +def normalize_value(spec: RemoteSetting, raw: str) -> str: + """A validated typed value in the form the cache stores and the firmware is sent. + + TX delay entered as ``0.5`` becomes ``0.50``: rounded to the setting's decimals, and + spelled exactly as a read of the same value would be, so staging what the node already + holds unstages rather than queueing a no-op ``set``. + """ + text = raw.strip() + if spec.kind in ("int", "float"): + return _format_number(spec, float(text)) + if spec.kind == "bool": + return text.lower() + if spec.kind == "enum": + return next((o.value for o in spec.options if o.value.lower() == text.lower()), text) + return text + + def validate_value(spec: RemoteSetting, raw: str) -> bool | str: """Validate a prompted value for ``spec``: ``True``, or the error message to show.""" text = raw.strip() @@ -319,15 +769,127 @@ def validate_value(spec: RemoteSetting, raw: str) -> bool | str: if text.lower() in ("on", "off"): return True return "Enter on or off." + if spec.kind == "enum": + if any(o.value.lower() == text.lower() for o in spec.options): + return True + return "Enter one of " + ", ".join(o.value for o in spec.options) + "." if spec.kind in ("int", "float"): try: value = float(text) except ValueError: return "Enter a number." - if spec.kind == "int" and not float(text).is_integer(): + if spec.kind == "int" and not value.is_integer(): return "Enter a whole number." - if spec.minimum is not None and value < spec.minimum: - return f"Must be ≥ {spec.minimum:g}." - if spec.maximum is not None and value > spec.maximum: - return f"Must be ≤ {spec.maximum:g}." + if spec.zero_off and value == 0: + return True + low, high = spec.minimum, spec.maximum + if spec.zero_off and low is not None and high is not None and not low <= value <= high: + return f"Must be 0, or {low:g} – {high:g}." + if low is not None and value < low: + return f"Must be ≥ {low:g}." + if high is not None and value > high: + return f"Must be ≤ {high:g}." return True + + +def range_hint(spec: RemoteSetting) -> str: + """The prompt's help line: what validation will accept, and in what unit.""" + low, high = spec.minimum, spec.maximum + if low is not None and high is not None: + hint = f"Allowed: {low:g} – {high:g}" + elif low is not None: + hint = f"Allowed: ≥ {low:g}" + elif high is not None: + hint = f"Allowed: ≤ {high:g}" + else: + hint = "" + if hint and spec.zero_off: + hint = hint.replace("Allowed: ", "Allowed: 0 (off), or ", 1) + if spec.unit: + hint = f"{hint} ({spec.unit})" if hint else f"In {spec.unit}." + return hint + + +def read_plan(specs: Iterable[RemoteSetting]) -> list[tuple[str, list[RemoteSetting]]]: + """The read commands that answer ``specs``, each once, with the settings it fills. + + Every command is one paced round trip, so the four radio fields ask ``get radio`` a + single time between them — and asking for any one of them fills all four, because the + reply carries them anyway and a radio line half-refreshed would disagree with itself. + Unreadable settings are skipped. + """ + plan: dict[str, list[RemoteSetting]] = {} + for spec in specs: + if not spec.readable: + continue + fills = plan.setdefault(spec.get_command, []) + for member in composite_members(spec.composite) if spec.composite else [spec]: + if member not in fills: + fills.append(member) + return list(plan.items()) + + +@dataclass(frozen=True, slots=True) +class Write: + """One write command, planned from the staged values. + + Attributes: + command: The CLI command to send, or ``""`` when it cannot be built yet. + values: Setting key -> the value this command leaves the node holding. For a + composite that includes the unstaged siblings it restates. + missing: The composite siblings neither staged nor known — the reason + ``command`` is empty. Read them first (:func:`composite_reads`). + """ + + command: str + values: dict[str, str] + missing: tuple[str, ...] = () + + +def write_plan(pending: Mapping[str, str], known: Mapping[str, str]) -> list[Write]: + """Group staged values into the commands that send them, in catalog order. + + A standalone setting is its own ``set``. A composite member is sent with all its + siblings in one command, the unstaged ones restated from what the node last said — + ``set radio`` has no way to change one field alone. + + Args: + pending: Setting key -> staged value. + known: Setting key -> the node's last-read value, for composite siblings. + + Returns: + The planned writes. + """ + writes: list[Write] = [] + planned: set[str] = set() + for spec in REPEATER_SETTINGS: + if spec.key not in pending or not spec.writable: + continue + if not spec.composite: + value = pending[spec.key] + writes.append(Write(spec.set_command(value), {spec.key: value})) + continue + if spec.composite in planned: + continue + planned.add(spec.composite) + members = composite_members(spec.composite) + values = {m.key: pending.get(m.key, known.get(m.key)) for m in members} + missing = tuple(key for key, value in values.items() if value is None) + if missing: + staged = {m.key: pending[m.key] for m in members if m.key in pending} + writes.append(Write("", staged, missing)) + else: + joined = ",".join(str(values[m.key]) for m in members) + writes.append(Write(f"set {spec.composite} {joined}", dict(values))) # type: ignore[arg-type] + return writes + + +def composite_reads(pending: Mapping[str, str], known: Mapping[str, str]) -> list[str]: + """The reads a write needs first: composites staged without all their siblings known.""" + commands: list[str] = [] + for write in write_plan(pending, known): + if write.missing: + spec = get_setting(write.missing[0]) + if spec is not None and spec.get_command not in commands: + commands.append(spec.get_command) + return commands diff --git a/meshterm/core/remote_store.py b/meshterm/core/remote_store.py index d4a7658..061659c 100644 --- a/meshterm/core/remote_store.py +++ b/meshterm/core/remote_store.py @@ -29,12 +29,16 @@ class CachedValue: """One remembered remote setting: what the node last said, and when. Attributes: - value: The value as display text. + value: The value as stored text (empty when unsupported). read_at: When it was read from (or written to) the node. + supported: ``False`` when the node answered the read with an error — its firmware + has no such setting (a board without a front-end module, a build without a + bridge). Kept apart from *never read*, which is no entry at all. """ value: str read_at: datetime | None + supported: bool = True class RemoteStore: @@ -66,7 +70,10 @@ class RemoteStore: if not isinstance(raw, dict): return out for key, entry in raw.items(): - if not isinstance(entry, dict) or "value" not in entry: + if not isinstance(entry, dict): + continue + supported = not entry.get("unsupported", False) + if supported and "value" not in entry: continue read_at: datetime | None = None stamp = entry.get("read_at") @@ -75,15 +82,32 @@ class RemoteStore: read_at = datetime.fromisoformat(stamp) except ValueError: read_at = None - out[key] = CachedValue(value=str(entry["value"]), read_at=read_at) + out[key] = CachedValue( + value=str(entry.get("value", "")), read_at=read_at, supported=supported + ) return out def remember_setting(self, node: Contact, key: str, value: str) -> None: """Cache one setting's value for ``node``, stamped now.""" + self._put(node, key, {"value": value, "read_at": utcnow().isoformat()}) + + def remember_unsupported(self, node: Contact, key: str) -> None: + """Record that ``node`` answered a read of ``key`` with an error, stamped now.""" + self._put(node, key, {"unsupported": True, "read_at": utcnow().isoformat()}) + + def forget_setting(self, node: Contact, key: str) -> None: + """Drop one cached setting, so the row reads as never read.""" + records = self._load_all() + settings = records.get(admin_key(node), {}).get("settings") + if isinstance(settings, dict) and settings.pop(key, None) is not None: + self._write(records) + + def _put(self, node: Contact, key: str, entry: dict) -> None: + """Store one setting's cache entry for ``node``.""" records = self._load_all() record = records.setdefault(admin_key(node), {}) settings = record.setdefault("settings", {}) - settings[key] = {"value": value, "read_at": utcnow().isoformat()} + settings[key] = entry self._write(records) # -- the command-line history --------------------------------------------------- diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index 1e23808..878940c 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -6,14 +6,15 @@ otherwise) opens an editor deliberately shaped like the local device-configurati screen — the same setting / value / description lanes, staged ``current → new`` values, Apply — but speaking the repeater's text CLI (see :mod:`meshterm.core.remote_config`) instead of the companion's binary protocol, which brings the repeater-only knobs the -local editor never had: TX delay, Direct TX delay, airtime factor, advert intervals. +local editor never had: TX delay, Direct TX delay, duty cycle, flood caps, the bridge. Because every read is one paced mesh round trip, the editor never bulk-reads on open: -values show what the last read (or the last applied set) said, stamped with age, from -the per-node cache (:class:`~meshterm.core.remote_store.RemoteStore`); the *Read -settings* action refreshes them all under an abortable progress dialog, one paced -``get`` at a time. Apply sends the staged ``set`` commands the same way and folds each -confirmed value straight back into the cache. +values show what the last read (or the last applied set) said, from the per-node cache +(:class:`~meshterm.core.remote_store.RemoteStore`). The *Read settings* action refreshes +every one of them under an abortable progress dialog, one paced read at a time, and +``^R`` (``Read`` on the F-key lane) re-reads just the highlighted row. A setting the node's +firmware doesn't have reads as ``n/a`` — kept apart from ``?``, never read. Apply sends the +staged values the same way and folds each confirmed value straight back into the cache. Beyond the settings, the action rows cover the box itself — advert, clock sync, change admin password, reboot, each behind its own floating confirmation — and the **Command @@ -24,6 +25,9 @@ the catalog doesn't spell. from __future__ import annotations import asyncio +import re +from collections.abc import Iterable +from dataclasses import dataclass from typing import TYPE_CHECKING, Any from rich.cells import cell_len @@ -31,10 +35,18 @@ from rich.text import Text from ..core.models import Contact from ..core.remote_config import ( + REPEATER_SETTINGS, RemoteSetting, + composite_reads, + get_setting, + normalize_value, parse_reply_value, + range_hint, + read_plan, reply_is_error, settings_by_category, + validate_value, + write_plan, ) from .menus import ( confirm_discard, @@ -48,8 +60,8 @@ from .menus import ( ) from .trace_screen import TracingDialog from .tui import Choice, Separator +from .tui.select import SelectScreen, _splice_hint from .tui.spinner import Spinner, spinner_interval -from .widgets import _age_seconds, _format_age if TYPE_CHECKING: from ..context import AppContext @@ -69,6 +81,72 @@ _REBOOT = "__reboot__" _APPLY = "__apply__" _CANCEL = "__cancel__" +#: The footer atom naming the chord that re-reads the highlighted setting. +READ_ONE_HINT = "^R read" + + +@dataclass(frozen=True, slots=True) +class ReadOne: + """What the admin menu resolves with when ``^R`` asks for one setting's value again. + + Attributes: + key: The highlighted setting's catalog key. + """ + + key: str + + +class AdminMenu(SelectScreen): + """The admin editor's list, plus a key that re-reads the highlighted setting alone. + + A full read is one paced round trip per setting — minutes, on a node with every + section — so checking whether one value took, or refreshing the one row that timed + out, must not cost all of them. The key is ``^R``, the chord the app already spends on + *retry* (chat re-sends an unacknowledged message with it): here too it asks the mesh + the same question again, for the one thing under the cursor. It has to be a chord, + because this list filters as you type and every bare letter is spoken for. + + The footer names it, and the F-key lane lights its ``Read`` chip, only on a readable + setting row — never on an action row, where there is nothing to read. + """ + + def _readable_key(self) -> str | None: + """The highlighted row's setting key, when it is a setting the node can be asked.""" + current = self._current_choice() + if current is None or not isinstance(current.value, str): + return None + spec = get_setting(current.value) + return spec.key if spec is not None and spec.readable else None + + @property + def footer_hint(self) -> str: # type: ignore[override] + """The list's own hint, plus the read atom while a readable setting is highlighted.""" + base = super().footer_hint + return _splice_hint(base, READ_ONE_HINT) if self._readable_key() else base + + @property + def fkey_lane(self): + """The list's lane with ``Read`` on F3 — dim on a row there is nothing to read. + + F1/F2 are this grouped list's section jumps and F4/F5 the pager; F3 is the slot a + select list spends on its own verb. Dim rather than empty on an action row: reading + is a thing on this screen, just not for the row the cursor is on. + """ + from .tui.fkeys import FPair + + lane = list(super().fkey_lane) + lane[2] = FPair("Read", "retry", enabled=self._readable_key() is not None) + return lane + + def handle(self, action: str, data: str = "") -> None: + """Ask for the highlighted setting's value, or behave as any select list does.""" + if action == "retry": + key = self._readable_key() + if key is not None: + self.resolve(ReadOne(key)) + return + super().handle(action, data) + async def open_repeater_admin(ctx: AppContext) -> dict[str, Any] | None: """Run the repeater-admin flow: pick a node, log in, and administer it. @@ -178,11 +256,11 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict """Run the editor loop for one logged-in node. One screen for the whole session, its rows refreshed in place after every action: they - carry the cache's ``current → new`` values and their ages, and the title counts what is - staged, so the content moves under a highlight that stays where the reader put it — - typed filter included. Every sub-prompt floats over it, and Esc leaves the node. + carry the cache's ``current → new`` values, and the title counts what is staged, so the + content moves under a highlight that stays where the reader put it — typed filter + included. Every sub-prompt floats over it, and Esc leaves the node. """ - from .tui import CANCEL, SelectScreen + from .tui import CANCEL session = ctx.ui.session @@ -191,7 +269,7 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict cache = ctx.remote_store.settings(node) title, items = _menu_items(node, cache, pending) - menu = SelectScreen( + menu = AdminMenu( title, items, footer_hint="↑↓ move · type to filter · Enter select · Esc back", @@ -206,10 +284,14 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict if pending and not await confirm_discard(ctx, len(pending), verb="sending"): continue return {"node": node.name, "applied": applied} - if choice == _APPLY: + if isinstance(choice, ReadOne): + spec = get_setting(choice.key) + if spec is not None: + await read_settings(ctx, device, node, [spec]) + elif choice == _APPLY: applied += await _apply(ctx, device, node, pending) elif choice == _READ: - await _read_all(ctx, device, node) + await read_settings(ctx, device, node, REPEATER_SETTINGS) elif choice == _CLI: await _command_line(ctx, device, node) elif choice == _ADVERT: @@ -246,9 +328,14 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict danger=True, ) else: # a setting key - await _stage_setting(ctx, str(choice), cache, pending) + spec = get_setting(str(choice)) + if spec is not None and not spec.writable: + # A read-only fact has nothing to stage; asking again is all Enter can do. + await read_settings(ctx, device, node, [spec]) + else: + await _stage_setting(ctx, str(choice), cache, pending) # A read or an apply rewrites the cache the rows are drawn from; re-read it so - # the values and their ages are the ones the action just produced. + # the values are the ones the action just produced. cache = ctx.remote_store.settings(node) title, items = _menu_items(node, cache, pending) menu.replace_items(items, title=title) @@ -289,7 +376,7 @@ def _menu_items(node: Contact, cache: dict, pending: dict[str, str]) -> tuple[st # every mark padded out to it — otherwise Read settings and Command line start their # labels a column left of the rows under them. actions = [ - ("↻", "Read settings", "Fetch every value from the node, one paced get", _READ), + ("↻", "Read settings", "Fetch every value from the node, one paced read", _READ), ("⌨", "Command line…", "Talk to the node's CLI directly", _CLI), ("📡", "Send advert…", "Have the node announce itself now", _ADVERT), ("🕒", "Sync clock…", "Set the node's clock over the mesh", _CLOCK), @@ -313,19 +400,25 @@ def _menu_items(node: Contact, cache: dict, pending: dict[str, str]) -> tuple[st def _value_text(spec: RemoteSetting, cache: dict, pending: dict[str, str]) -> Text: - """One setting's VALUE lane: cached value (with its age), and any staged arrow.""" + """One setting's VALUE lane: what the node last said, and any staged arrow. + + Four states, each its own word: the value; ``empty`` for a string the node holds blank; + ``n/a`` when the node's firmware answered that it has no such setting; ``?`` when it was + never read. No age: the lane is the value, and a stamp beside it only crowded it. + """ cached = cache.get(spec.key) if not spec.readable: value = Text("write-only", style="faint") elif cached is None: value = Text("?", style="muted") + elif not cached.supported: + value = Text("n/a", style="muted") + elif cached.value == "": + value = Text("empty", style="muted") else: - value = Text(cached.value) - age = _format_age(_age_seconds(cached.read_at)) - if age != "now": - value.append(f" ·{age}", style="faint") + value = Text(spec.display(cached.value)) if spec.key in pending: - value.append(f" → {pending[spec.key]}", style="warn") + value.append(f" → {spec.display(pending[spec.key])}", style="warn") return value @@ -334,13 +427,12 @@ def _value_text(spec: RemoteSetting, cache: dict, pending: dict[str, str]) -> Te async def _stage_setting(ctx: AppContext, key: str, cache: dict, pending: dict[str, str]) -> None: """Prompt for one setting's new value and stage it (nothing is sent yet).""" - from ..core.remote_config import get_setting, validate_value - spec = get_setting(key) if spec is None or not spec.writable: # pragma: no cover - menu offers only real keys return cached = cache.get(key) - current = pending.get(key, cached.value if cached is not None else "") + known = cached.value if cached is not None and cached.supported else None + current = pending.get(key, known or "") if spec.kind == "bool": picked = await ctx.ui.dialog( @@ -353,43 +445,73 @@ async def _stage_setting(ctx: AppContext, key: str, cache: dict, pending: dict[s if picked is None: return value = str(picked) + elif spec.kind == "enum": + items = [ + Choice( + title=option.label + + (f" — {option.help}" if option.help else "") + + (" (current)" if option.value == current else ""), + value=option.value, + ) + for option in spec.options + ] + picked = await ctx.ui.select( + spec.label, + items, + prompt=spec.help, + default=current if any(o.value == current for o in spec.options) else None, + ) + if picked is None: + return + value = str(picked) else: - hint = "" - if spec.minimum is not None and spec.maximum is not None: - hint = f"Allowed: {spec.minimum:g} – {spec.maximum:g}" - elif spec.minimum is not None: - hint = f"Allowed: ≥ {spec.minimum:g}" - if spec.unit: - hint = f"{hint} ({spec.unit})" if hint else f"In {spec.unit}." raw = await ctx.ui.text( spec.label, prompt=spec.help, default=str(current), validate=lambda t: validate_value(spec, t), - help_text=hint, + help_text=range_hint(spec), ) if raw is None: return - value = raw.strip() + value = normalize_value(spec, raw) - if cached is not None and value == cached.value: + if value == known: pending.pop(key, None) # back to what the node last said — nothing to send else: pending[key] = value -async def _apply(ctx: AppContext, device: Device, node: Contact, pending: dict[str, str]) -> int: - """Send every staged ``set`` command, paced, under an abortable progress dialog. +def _known_values(ctx: AppContext, node: Contact) -> dict[str, str]: + """The node's last-read values, for restating a composite's unstaged fields.""" + return { + key: cached.value + for key, cached in ctx.remote_store.settings(node).items() + if cached.supported + } - Each confirmed value folds straight into the per-node cache; a rejected or - unanswered set stays staged so it can be retried (or unstaged) rather than being - silently dropped. Records one ``runs`` row for the batch. + +def _remark(reply: str, value: str) -> str: + """What a successful write's reply adds beyond ``OK`` (``reboot to apply``), or ``""``.""" + remark = re.sub(r"^ok\b[\s,:-]*", "", reply.strip(), flags=re.IGNORECASE) + return "" if remark.lower() in ("", value.lower()) else remark + + +async def _apply(ctx: AppContext, device: Device, node: Contact, pending: dict[str, str]) -> int: + """Send every staged value, paced, under an abortable progress dialog. + + Staged values go out as :func:`~meshterm.core.remote_config.write_plan` groups them: + one command per setting, except the radio's four fields, which travel as one + ``set radio``. That command restates every field, so a radio field staged while its + siblings were never read first reads them — one paced ``get radio`` — rather than + guessing a frequency. Each confirmed value folds straight into the per-node cache (and + stales any other spelling of the same firmware value); a rejected or unanswered write + stays staged so it can be retried (or unstaged) rather than being silently dropped. + Records one ``runs`` row for the batch. Returns: How many settings the node accepted. """ - from ..core.remote_config import get_setting - session = ctx.ui.session run_id = ctx.repo.start_run( "repeater-admin", @@ -401,30 +523,56 @@ async def _apply(ctx: AppContext, device: Device, node: Contact, pending: dict[s async def work(dialog: TracingDialog) -> None: nonlocal applied - total = len(pending) - for i, (key, value) in enumerate(sorted(pending.items()), start=1): - spec = get_setting(key) - assert spec is not None - dialog.status = f"set {key} · {i}/{total}" + first = True + + async def send(command: str, status: str) -> str | None: + nonlocal first + if not first: # every transmission after the first waits out the cooldown + await asyncio.sleep(ctx.preferences.trace_cooldown_s) + first = False + dialog.status = status session.invalidate() - reply = await device.send_remote_command( - node, spec.set_command(value), timeout=_REPLY_TIMEOUT_S - ) - if reply is not None and not reply_is_error(reply): - ctx.remote_store.remember_setting(node, key, value) - pending.pop(key, None) - applied += 1 - outcomes.append(Text.assemble(("✓ ", "ok"), f"{spec.label} = {value}")) - elif reply is None: + return await device.send_remote_command(node, command, timeout=_REPLY_TIMEOUT_S) + + for command in composite_reads(pending, _known_values(ctx, node)): + fills = [s for s in REPEATER_SETTINGS if s.get_command == command] + reply = await send(command, command) + if reply is not None: + remember_reply(ctx, node, fills, reply) + + writes = write_plan(pending, _known_values(ctx, node)) + for i, write in enumerate(writes, start=1): + staged = [s for s in REPEATER_SETTINGS if s.key in write.values and s.key in pending] + names = ", ".join(f"{s.label} = {s.display(write.values[s.key])}" for s in staged) + if write.missing: + unread = ", ".join(s.label for s in map(get_setting, write.missing) if s) outcomes.append( - Text.assemble(("? ", "warn"), f"{spec.label} — no reply (still staged)") + Text.assemble( + ("✗ ", "err"), f"{names} — {unread} couldn't be read (still staged)" + ) ) + continue + verb = " ".join(write.command.split()[:2]) # never a secret's value on screen + reply = await send(write.command, f"{verb} · {i}/{len(writes)}") + if reply is not None and not reply_is_error(reply): + for key, value in write.values.items(): + ctx.remote_store.remember_setting(node, key, value) + spec = get_setting(key) + for other in spec.overlaps if spec is not None else (): + ctx.remote_store.forget_setting(node, other) + for spec in staged: + pending.pop(spec.key, None) + applied += len(staged) + remark = _remark(reply, write.values[staged[0].key]) if staged else "" + outcomes.append( + Text.assemble(("✓ ", "ok"), names, (f" — {remark}" if remark else "", "muted")) + ) + elif reply is None: + outcomes.append(Text.assemble(("? ", "warn"), f"{names} — no reply (still staged)")) else: outcomes.append( - Text.assemble(("✗ ", "err"), f"{spec.label} — {reply.strip()} (still staged)") + Text.assemble(("✗ ", "err"), f"{names} — {reply.strip()} (still staged)") ) - if i < total: - await asyncio.sleep(ctx.preferences.trace_cooldown_s) aborted = await _run_under_dialog(ctx, f"Applying — {node.name}", work) ctx.repo.finish_run( @@ -444,36 +592,78 @@ async def _apply(ctx: AppContext, device: Device, node: Contact, pending: dict[s return applied -async def _read_all(ctx: AppContext, device: Device, node: Contact) -> None: - """Refresh every readable setting from the node, one paced ``get`` at a time. +def remember_reply(ctx: AppContext, node: Contact, fills: list[RemoteSetting], reply: str) -> int: + """Fold one read's reply into the cache for every setting it answers. - Values that parse land in the cache (and on screen); firmware that doesn't know a - key just leaves that row unknown. Abort keeps everything already read. + An error reply is the firmware saying it has no such setting, and is remembered as + that (the row reads ``n/a``). A reply that isn't an error but doesn't parse leaves the + cache alone: a phrasing we don't understand is not evidence the setting is missing. + + Returns: + How many settings got a value. + """ + if reply_is_error(reply): + for spec in fills: + ctx.remote_store.remember_unsupported(node, spec.key) + return 0 + got = 0 + for spec in fills: + value = parse_reply_value(spec, reply) + if value is not None: + ctx.remote_store.remember_setting(node, spec.key, value) + got += 1 + return got + + +async def read_settings( + ctx: AppContext, device: Device, node: Contact, specs: Iterable[RemoteSetting] +) -> None: + """Refresh ``specs`` from the node, one paced read at a time. + + The four radio fields share one ``get radio`` (see + :func:`~meshterm.core.remote_config.read_plan`), so a full read asks each question once. + Values that parse land in the cache (and on screen), a setting the firmware lacks reads + ``n/a``, and abort keeps everything already read. Reads the node never answered are + listed afterwards, because their rows go on showing what they last said and would + otherwise pass for fresh. """ session = ctx.ui.session - specs = [s for cat, ss in settings_by_category() for s in ss if s.readable] + plan = read_plan(specs) run_id = ctx.repo.start_run( "repeater-admin", {"node": node.name, "mode": "read"}, ctx.profile_name ) read = 0 + unanswered: list[str] = [] async def work(dialog: TracingDialog) -> None: nonlocal read - for i, spec in enumerate(specs, start=1): - dialog.status = f"get {spec.key} · {i}/{len(specs)}" + for i, (command, fills) in enumerate(plan, start=1): + dialog.status = f"{command} · {i}/{len(plan)}" session.invalidate() - reply = await device.send_remote_command( - node, spec.get_command, timeout=_REPLY_TIMEOUT_S - ) - value = parse_reply_value(spec, reply) - if value is not None: - ctx.remote_store.remember_setting(node, spec.key, value) - read += 1 - if i < len(specs): + reply = await device.send_remote_command(node, command, timeout=_REPLY_TIMEOUT_S) + if reply is None: + unanswered.extend(spec.label for spec in fills) + else: + read += remember_reply(ctx, node, fills, reply) + if i < len(plan): await asyncio.sleep(ctx.preferences.trace_cooldown_s) aborted = await _run_under_dialog(ctx, f"Reading — {node.name}", work) - ctx.repo.finish_run(run_id, "error" if aborted else "ok", {"read": read, "asked": len(specs)}) + asked = sum(len(fills) for _command, fills in plan) + ctx.repo.finish_run( + run_id, + "error" if aborted else "ok", + {"read": read, "asked": asked, "unanswered": len(unanswered)}, + ) + if unanswered and not aborted: + await session.message_dialog( + Text( + f"No reply from {node.name} for: {', '.join(unanswered)}. " + "Those rows still show what they last said.", + style="warn", + ), + title=f"Read — {node.name}", + ) async def _run_under_dialog(ctx: AppContext, title: str, work) -> bool: diff --git a/tests/test_repeater_admin.py b/tests/test_repeater_admin.py index d526036..039908e 100644 --- a/tests/test_repeater_admin.py +++ b/tests/test_repeater_admin.py @@ -1,13 +1,15 @@ """Tests for repeater admin. -The settings catalog, the per-node store, the simulated remote CLI, and the -command-line screen's readline behavior. +The settings catalog (checked against the firmware's own CLI), the per-node store, the +simulated remote CLI, the editor's read/apply round trips, and the command-line screen's +readline behavior. """ from __future__ import annotations import asyncio import io +from datetime import timedelta from pathlib import Path import pytest @@ -18,19 +20,27 @@ from meshterm.core.admin_store import AdminStore from meshterm.core.config import Settings from meshterm.core.connection import MockDevice from meshterm.core.device_store import DeviceStore -from meshterm.core.models import Contact +from meshterm.core.models import Contact, utcnow from meshterm.core.remote_config import ( REPEATER_SETTINGS, + composite_reads, get_setting, known_commands, + normalize_value, parse_reply_value, + range_hint, + read_plan, + reply_is_error, validate_value, + write_plan, ) -from meshterm.core.remote_store import HISTORY_CAP, RemoteStore +from meshterm.core.remote_store import HISTORY_CAP, CachedValue, RemoteStore from meshterm.persistence.repository import Repository +from meshterm.ui import repeater_admin from meshterm.ui.remote_cli import RemoteCliScreen -from meshterm.ui.repeater_admin import open_repeater_admin +from meshterm.ui.repeater_admin import AdminMenu, ReadOne, open_repeater_admin from meshterm.ui.surface import TuiUi +from meshterm.ui.trace_screen import TracingDialog from meshterm.ui.tui.prompt import TextScreen from meshterm.ui.tui.screen import CANCEL from meshterm.ui.tui.select import SelectScreen @@ -38,6 +48,50 @@ from meshterm.ui.tui.session import TuiSession NODE = Contact(name="Yagi-Repeater", public_key="a1" * 32, key_prefix="a1b2c3d4") +#: Every key MeshCore's ``CommonCLI.cpp`` (``handleSetCmd``) lets an admin write over the +#: mesh — ``radio`` standing for its four fields. ``prv.key`` and ``freq`` are left out: the +#: firmware takes those from its serial console only. ``extra.sf`` is LR2021-only. +FIRMWARE_SET_KEYS = { + "name", + "owner.info", + "lat", + "lon", + "radio", + "tx", + "radio.rxgain", + "radio.fem.rxgain", + "radio.fem.txgain", + "cad", + "int.thresh", + "agc.reset.interval", + "repeat", + "txdelay", + "direct.txdelay", + "rxdelay", + "dutycycle", + "af", + "loop.detect", + "path.hash.mode", + "multi.acks", + "flood.max", + "flood.max.unscoped", + "flood.max.advert", + "advert.interval", + "flood.advert.interval", + "guest.password", + "allow.read.only", + "adc.multiplier", + "bridge.enabled", + "bridge.source", + "bridge.delay", + "bridge.baud", + "bridge.channel", + "bridge.secret", +} + +#: The settings ``handleCommand`` takes as top-level verbs rather than ``set`` keys. +FIRMWARE_VERB_SETTINGS = {"powersaving", "gps", "gps advert"} + class _FakeSession: def __init__(self) -> None: @@ -50,31 +104,126 @@ class _FakeSession: # --- the catalog ---------------------------------------------------------------------- +def test_catalog_covers_every_setting_the_firmware_takes_over_the_mesh() -> None: + """Each writable firmware key has a row, and nothing is spelled that the firmware lacks. + + Regression: the catalog was written from convention and carried ``get bw``/``sf``/``cr`` + (keys no firmware answers — the radio is read as one ``get radio``) while missing + ``path.hash.mode`` and twenty-odd others. + """ + spelled = {s.composite or s.key for s in REPEATER_SETTINGS if s.writable and not s.verb} + assert spelled == FIRMWARE_SET_KEYS + assert {s.verb for s in REPEATER_SETTINGS if s.verb} == FIRMWARE_VERB_SETTINGS + assert len({s.key for s in REPEATER_SETTINGS}) == len(REPEATER_SETTINGS) + + def test_catalog_carries_the_repeater_only_knobs() -> None: """TX delay and Direct TX delay — the reason this feature exists — are first-class.""" txdelay = get_setting("txdelay") direct = get_setting("direct.txdelay") - assert txdelay is not None and txdelay.set_command("5") == "set txdelay 5" + assert txdelay is not None and txdelay.set_command("0.50") == "set txdelay 0.50" assert direct is not None and direct.get_command == "get direct.txdelay" assert any(s.key == "af" for s in REPEATER_SETTINGS) assert any(s.key == "advert.interval" for s in REPEATER_SETTINGS) +def test_delays_are_floats_rounded_to_two_places() -> None: + """TX, Direct TX and RX delay read, validate and send as two-decimal floats. + + Regression: they were typed ``int``, so a firmware ``0.5`` showed as ``0`` and typing + ``0.5`` back was refused as "not a whole number". + """ + for key in ("txdelay", "direct.txdelay", "rxdelay"): + spec = get_setting(key) + assert spec.kind == "float" and spec.decimals == 2 + assert parse_reply_value(spec, "> 0.5") == "0.50" + assert parse_reply_value(spec, "> 1.2345678") == "1.23" + assert validate_value(spec, "0.5") is True + assert normalize_value(spec, "0.3333") == "0.33" + assert "≤ 2" in validate_value(get_setting("txdelay"), "2.5") + assert validate_value(get_setting("rxdelay"), "12.5") is True # RX delay runs to 20 + + +def test_path_hash_mode_is_an_enum_the_firmware_accepts() -> None: + """Path-hash mode is on the repeater too, offering exactly the modes ``set`` takes.""" + spec = get_setting("path.hash.mode") + assert spec is not None and spec.kind == "enum" + assert [o.value for o in spec.options] == ["0", "1", "2"] # the firmware refuses 3 + assert parse_reply_value(spec, "> 1") == "1" + assert spec.display("1") == "2-byte" + assert validate_value(spec, "2") is True + assert validate_value(spec, "3") != True # noqa: E712 - a message, not False + assert spec.set_command("2") == "set path.hash.mode 2" + + +def test_radio_fields_travel_as_one_command() -> None: + """Frequency, bandwidth, SF and CR are one ``get radio`` and one ``set radio``.""" + plan = dict(read_plan(REPEATER_SETTINGS)) + assert [s.key for s in plan["get radio"]] == ["freq", "bw", "sf", "cr"] + assert not any(command in plan for command in ("get freq", "get bw", "get sf", "get cr")) + assert len(plan) == len(REPEATER_SETTINGS) - 3 # everything else is its own read + + reply = "> 910.525,62.5,7,5" + fields = {key: parse_reply_value(get_setting(key), reply) for key in ("freq", "bw", "sf", "cr")} + assert fields == {"freq": "910.525", "bw": "62.5", "sf": "7", "cr": "5"} + + (write,) = write_plan({"sf": "9"}, fields) + assert write.command == "set radio 910.525,62.5,9,5" + assert write.values == {**fields, "sf": "9"} + + (blind,) = write_plan({"sf": "9"}, {}) # siblings never read: nothing to restate + assert blind.command == "" and set(blind.missing) == {"freq", "bw", "cr"} + assert composite_reads({"sf": "9"}, {}) == ["get radio"] + assert composite_reads({"sf": "9"}, fields) == [] + + +def test_verb_shaped_and_oddly_spelled_settings() -> None: + """Settings the firmware spells its own way read and write the way it spells them.""" + powersaving = get_setting("powersaving") + assert powersaving.get_command == "powersaving" + assert powersaving.set_command("on") == "powersaving on" + assert parse_reply_value(powersaving, "on - Immediate effect") == "on" + + gps = get_setting("gps") + assert parse_reply_value(gps, "on, deactivated, no fix, 0 sats") == "off" + assert parse_reply_value(gps, "on, active, fix, 7 sats") == "on" + assert get_setting("gps advert").set_command("share") == "gps advert share" + + assert get_setting("multi.acks").set_command("on") == "set multi.acks 1" # an atoi + assert parse_reply_value(get_setting("multi.acks"), "> 1") == "on" + assert parse_reply_value(get_setting("bridge.source"), "> logRx") == "rx" + assert parse_reply_value(get_setting("dutycycle"), "> 50.0%") == "50.0" + + +def test_advert_intervals_take_zero_as_off() -> None: + """0 turns an advert interval off; anything else must sit in the firmware's range.""" + spec = get_setting("advert.interval") + assert validate_value(spec, "0") is True + assert validate_value(spec, "120") is True + assert validate_value(spec, "30") == "Must be 0, or 60 – 240." + assert range_hint(spec) == "Allowed: 0 (off), or 60 – 240 (min)" + + def test_parse_reply_value_survives_terse_and_verbose_firmware() -> None: """Numbers are extracted from any phrasing; errors parse as unknown, not values.""" tx = get_setting("tx") - assert parse_reply_value(tx, "20") == "20" + assert parse_reply_value(tx, "> 20") == "20" assert parse_reply_value(tx, "tx: 20") == "20" assert parse_reply_value(tx, "TX power = 20 dBm") == "20" assert parse_reply_value(tx, "ERR: unknown config: tx") is None + assert parse_reply_value(tx, "??: tx") is None # handleGetCmd's own spelling assert parse_reply_value(tx, None) is None name = get_setting("name") assert parse_reply_value(name, "> Yagi") == "Yagi" assert parse_reply_value(name, "name: Yagi") == "Yagi" + # A value echo is a value, even one that reads like a refusal. + assert parse_reply_value(name, "> Unknown-Hill") == "Unknown-Hill" + assert not reply_is_error("> Unknown-Hill") + assert parse_reply_value(get_setting("owner.info"), "> ") == "" # blank is a value repeat = get_setting("repeat") - assert parse_reply_value(repeat, "on") == "on" + assert parse_reply_value(repeat, "> on") == "on" assert parse_reply_value(repeat, "repeat is off") == "off" @@ -82,7 +231,7 @@ def test_validate_value_enforces_kind_and_bounds() -> None: """Prompt validation speaks in the setting's own terms.""" sf = get_setting("sf") assert validate_value(sf, "9") is True - assert "≥ 7" in validate_value(sf, "3") + assert "≥ 5" in validate_value(sf, "3") assert "number" in validate_value(sf, "fast") assert validate_value(get_setting("repeat"), "maybe") == "Enter on or off." assert validate_value(get_setting("name"), " ") == "Enter a value." @@ -93,8 +242,11 @@ def test_known_commands_cover_catalog_and_verbs() -> None: commands = known_commands() assert "get txdelay" in commands assert "set direct.txdelay " in commands + assert "get radio" in commands and "set radio " in commands + assert "powersaving " in commands and "gps advert" in commands + assert "get path.hash.mode" in commands assert "reboot" in commands and "ver" in commands - assert "get guest.password" not in commands # write-only stays uncompletable + assert "get bw" not in commands and "set freq " not in commands # --- the store ------------------------------------------------------------------------ @@ -103,14 +255,26 @@ def test_known_commands_cover_catalog_and_verbs() -> None: def test_remote_store_caches_settings_per_node(tmp_path: Path) -> None: """Values round-trip with their read stamps, keyed per node.""" store = RemoteStore(tmp_path / "remote.json") - store.remember_setting(NODE, "txdelay", "5") + store.remember_setting(NODE, "txdelay", "0.50") cached = store.settings(NODE) - assert cached["txdelay"].value == "5" + assert cached["txdelay"].value == "0.50" assert cached["txdelay"].read_at is not None other = Contact(name="Other", public_key="b2" * 32) assert store.settings(other) == {} +def test_remote_store_tells_unsupported_from_unread(tmp_path: Path) -> None: + """A key the firmware refused is remembered as that; forgetting makes it unread again.""" + store = RemoteStore(tmp_path / "remote.json") + store.remember_unsupported(NODE, "bridge.delay") + store.remember_setting(NODE, "af", "1.00") + cached = store.settings(NODE) + assert cached["bridge.delay"].supported is False + assert cached["af"].supported is True + store.forget_setting(NODE, "af") + assert "af" not in store.settings(NODE) + + def test_remote_store_history_dedupes_and_caps(tmp_path: Path) -> None: """History appends in order, skips adjacent repeats, and stays capped.""" store = RemoteStore(tmp_path / "remote.json") @@ -135,18 +299,24 @@ async def test_mock_remote_cli_requires_login() -> None: await device.disconnect() -async def test_mock_remote_cli_round_trips_settings() -> None: - """get/set work for catalog keys; unknown keys answer with an error string.""" +async def test_mock_remote_cli_answers_like_the_firmware() -> None: + """The simulator keeps CommonCLI's spellings and reply shapes, refusals included.""" device = MockDevice() await device.connect() assert await device.admin_login(NODE, "admin") - assert await device.send_remote_command(NODE, "get txdelay") == "> 0" - assert await device.send_remote_command(NODE, "set txdelay 5") == "OK" - assert await device.send_remote_command(NODE, "get txdelay") == "> 5" + assert await device.send_remote_command(NODE, "get txdelay") == "> 0.5" + assert await device.send_remote_command(NODE, "set txdelay 1.25") == "OK" + assert await device.send_remote_command(NODE, "get txdelay") == "> 1.25" assert await device.send_remote_command(NODE, "set tx 22") == "OK" assert await device.get_remote_tx_power(NODE) == 22 # one shared TX state - reply = await device.send_remote_command(NODE, "get nonsense") - assert reply is not None and "unknown" in reply.lower() + assert await device.send_remote_command(NODE, "get tx") == "> 22" + assert await device.send_remote_command(NODE, "get radio") == "> 910.525,62.5,7,5" + refused = await device.send_remote_command(NODE, "set freq 915") + assert refused.startswith("unknown config") # serial console only + reboot = await device.send_remote_command(NODE, "set radio 915,250,10,5") + assert reboot == "OK - reboot to apply" + assert await device.send_remote_command(NODE, "get radio") == "> 915,250,10,5" + assert await device.send_remote_command(NODE, "get nonsense") == "??: nonsense" assert "simulator" in (await device.send_remote_command(NODE, "ver")) await device.disconnect() @@ -270,6 +440,137 @@ async def test_login_password_floats_over_the_node_picker(tui_ctx) -> None: assert result is None # no node was ever administered +# --- reading and applying against the simulator ---------------------------------------- + + +@pytest.fixture() +async def admin_device(monkeypatch): + """A simulator logged in to ``NODE``, recording every command, with pacing waived.""" + real_sleep = asyncio.sleep + + async def no_wait(_delay, result=None): + return await real_sleep(0, result) + + monkeypatch.setattr(asyncio, "sleep", no_wait) + device = MockDevice() + await device.connect() + assert await device.admin_login(NODE, "admin") + device.sent = [] + original = device.send_remote_command + + async def recording(node, command, *, timeout=8.0): + device.sent.append(command) + return await original(node, command, timeout=timeout) + + monkeypatch.setattr(device, "send_remote_command", recording) + yield device + await device.disconnect() + + +async def test_read_settings_reads_every_setting_asking_each_question_once( + tui_ctx, admin_device +) -> None: + """Read settings leaves every row answered — a value, or the node saying it has none. + + The radio's four fields come from one ``get radio``; nothing is asked twice; a board + without a front-end module or a bridge reads as unsupported rather than unread. + """ + await repeater_admin.read_settings(tui_ctx, admin_device, NODE, REPEATER_SETTINGS) + + sent = admin_device.sent + assert len(sent) == len(set(sent)) == len(read_plan(REPEATER_SETTINGS)) + cache = tui_ctx.remote_store.settings(NODE) + assert set(cache) == {s.key for s in REPEATER_SETTINGS} + assert cache["txdelay"].value == "0.50" and cache["direct.txdelay"].value == "0.20" + assert (cache["freq"].value, cache["bw"].value, cache["sf"].value) == ("910.525", "62.5", "7") + assert cache["path.hash.mode"].value == "0" + assert cache["dutycycle"].value == "50.0" + assert cache["gps"].value == "off" and cache["gps advert"].value == "none" + assert cache["owner.info"].value == "" and cache["owner.info"].supported + assert not cache["radio.fem.rxgain"].supported + assert not cache["bridge.delay"].supported + + +async def test_read_one_setting_sends_one_read(tui_ctx, admin_device) -> None: + """``^R``'s read asks for the highlighted setting alone — or its radio line.""" + await repeater_admin.read_settings(tui_ctx, admin_device, NODE, [get_setting("sf")]) + assert admin_device.sent == ["get radio"] + assert tui_ctx.remote_store.settings(NODE)["cr"].value == "5" # the same answer filled it + + +async def test_apply_reads_the_radio_first_then_sends_one_line(tui_ctx, admin_device) -> None: + """A radio field staged unread restates its siblings from a fresh read, never a guess.""" + ctx = tui_ctx + session = ctx.ui.session + ctx.remote_store.remember_setting(NODE, "af", "1.00") + pending = {"sf": "9", "txdelay": "1.25", "dutycycle": "40.0"} + + task = asyncio.ensure_future(repeater_admin._apply(ctx, admin_device, NODE, pending)) + summary = await _step_until( + lambda: ( + session.top + if session.top is not None and not isinstance(session.top, TracingDialog) + else None + ), + limit=5000, + ) + assert summary is not None, "the apply summary never opened" + summary.resolve(None) + applied = await task + + assert admin_device.sent == [ + "get radio", + "set radio 910.525,62.5,9,5", + "set txdelay 1.25", + "set dutycycle 40.0", + ] + assert applied == 3 and pending == {} + cache = ctx.remote_store.settings(NODE) + assert cache["sf"].value == "9" and cache["txdelay"].value == "1.25" + assert "af" not in cache # the other spelling of the duty cycle is stale now + + +# --- the editor menu ----------------------------------------------------------------- + + +def test_value_lane_shows_the_value_without_its_age() -> None: + """The value lane is the value: no age stamp, and its own word for each absence.""" + cache = { + "txdelay": CachedValue("0.50", utcnow() - timedelta(hours=3)), + "bridge.delay": CachedValue("", utcnow(), supported=False), + "guest.password": CachedValue("", utcnow()), + "path.hash.mode": CachedValue("1", utcnow()), + } + lane = repeater_admin._value_text + assert lane(get_setting("txdelay"), cache, {}).plain == "0.50" + assert lane(get_setting("bridge.delay"), cache, {}).plain == "n/a" + assert lane(get_setting("guest.password"), cache, {}).plain == "empty" + assert lane(get_setting("rxdelay"), cache, {}).plain == "?" + staged = lane(get_setting("path.hash.mode"), cache, {"path.hash.mode": "2"}) + assert staged.plain == "2-byte → 3-byte" + + +async def test_ctrl_r_reads_only_a_highlighted_setting() -> None: + """``^R`` resolves with the highlighted setting, and is named only where it would act.""" + title, items = repeater_admin._menu_items(NODE, {}, {}) + menu = AdminMenu(title, items, footer_hint="↑↓ move · type to filter · Enter select · Esc back") + loop = asyncio.get_running_loop() + + menu.future = loop.create_future() + assert menu._current_choice().value == "name" + assert menu.footer_hint.endswith("Enter select · ^R read · Esc back") + assert menu.fkey_lane[2].label == "Read" and menu.fkey_lane[2].enabled + menu.handle("retry") + assert menu.future.result() == ReadOne("name") + + menu.future = loop.create_future() + menu.handle("end") # the last action row: nothing there to read + assert "^R" not in menu.footer_hint + assert not menu.fkey_lane[2].enabled + menu.handle("retry") + assert not menu.future.done() + + # --- the command-line screen ----------------------------------------------------------- @@ -351,11 +652,10 @@ def test_admin_menu_pins_the_column_header_over_the_category() -> None: """Scrolled deep, the lane names stay overhead with the category heading under them.""" import re - from meshterm.ui.repeater_admin import _menu_items from meshterm.ui.tui import frame ansi = re.compile(r"\x1b\[[0-9;]*m") - title, items = _menu_items(NODE, {}, {}) + title, items = repeater_admin._menu_items(NODE, {}, {}) screen = SelectScreen(title, items) for _ in range(18): # down past the first categories screen.handle("down") @@ -366,41 +666,11 @@ def test_admin_menu_pins_the_column_header_over_the_category() -> None: assert above is True -def test_admin_actions_start_every_label_in_the_same_cell() -> None: - """``↻`` and ``⌨`` are one cell among two-cell siblings; the icon column absorbs it. - - The Actions rows used to write ``icon + " "``, which started *Read settings* and - *Command line…* a column left of *Send advert…* below them. - """ - from rich.cells import cell_len - - from meshterm.ui.repeater_admin import _menu_items - from meshterm.ui.tui import Choice - - _title, items = _menu_items(NODE, {}, {}) - labels = ("Read settings", "Command line…", "Send advert…", "Sync clock…", "Reboot node…") - rows = [ - item.title.plain - for item in items - if isinstance(item, Choice) - and hasattr(item.title, "plain") - and any(label in item.title.plain for label in labels) - ] - assert len(rows) == len(labels) - starts = set() - for row in rows: - label = next(label for label in labels if label in row) - starts.add(cell_len(row[: row.index(label)])) - assert len(starts) == 1, "a label starts a column early" - - def test_admin_menu_header_abbreviates_rather_than_wrapping() -> None: """Too narrow for the whole line, the last label shortens — the header stays one row.""" from rich.cells import cell_len - from meshterm.ui.repeater_admin import _menu_items - - _title, items = _menu_items(NODE, {}, {}) + _title, items = repeater_admin._menu_items(NODE, {}, {}) header = items[0] assert header.pinned full = header.text(100)