diff --git a/meshterm/ui/contactlist.py b/meshterm/ui/contactlist.py index 79bcd37..c2d819f 100644 --- a/meshterm/ui/contactlist.py +++ b/meshterm/ui/contactlist.py @@ -52,9 +52,9 @@ from typing import TYPE_CHECKING, Any from rich.cells import cell_len from rich.text import Text -from .marks import LOCK_ICON, MANAGED_ICON, SELF_MARK +from .marks import LOCK_ICON, MANAGED_ICON, SELF_MARK, UNKNOWN_MARK from .menus import fit_cells -from .theme import glyph, name_style +from .theme import glyph, name_style, snr_style from .tui.select import Choice, SelectScreen, Separator from .widgets import ( DEFAULT_GLYPH, @@ -115,9 +115,16 @@ class ContactLane: field: The :class:`ContactRow` attribute that holds the value of the lane. kind: ``"age"`` for a datetime drawn as a relative age in the colour of the recency heat, ``"count"`` for an integer count drawn muted (a faint ``—`` - when ``None``), or ``"text"`` for a string drawn on the left (a faint ``—`` - when ``None``). A ``text`` lane has no fixed width: the list sizes it to its - widest value (refer to :func:`_sized`), and :attr:`width` is the minimum. + when ``None``), ``"snr"`` for a signal reading drawn in the SNR scale of the + app (a muted ``—`` when ``None``), or ``"text"`` for a string drawn on the + left (a faint ``—`` when ``None``). A ``text`` lane has no fixed width: the + list sizes it to its widest value (refer to :func:`_sized`), and + :attr:`width` is the minimum. + absent: What an ``age`` lane draws when it has no value. ``"never"`` is the usual + word, and it is a *fact*: MeshTerm never heard the node. A lane whose source + can leave the age out without that meaning says so with ``"—"`` instead + (:data:`NEIGHBOUR_HEARD_LANE`: the remote node hears the neighbour, and it did + not say when). """ column: str @@ -125,6 +132,7 @@ class ContactLane: width: int field: str kind: str = "age" + absent: str = "never" #: How long ago MeshTerm last heard the node: the lane that each list of *live* contacts has. @@ -148,6 +156,18 @@ ARCHIVED_LANE = ContactLane("archived", "ARCHIVED", 8, "archived_at") #: Archived list it is the first lane, after the name (JP, 2026-11-03). PLACE_LANE = ContactLane("place", "PLACE", 5, "place", kind="text") +#: The signal-to-noise ratio that a **remote** node measured when it received from this +#: one: the first lane of the neighbour table of a repeater. It is not our own reading, and +#: the title of that dialog names the node whose reading it is. +SNR_LANE = ContactLane("snr", "SNR", 5, "snr", kind="snr") + +#: How long ago a **remote** node last heard this one: the second lane of its neighbour +#: table. It is drawn exactly as ``HEARD`` is, with the recency heat, because it is the same +#: question (how long ago did this node receive from that one) asked at the other end of the +#: link. A node that gave no age for an entry shows ``—``, which is not ``never``: it hears +#: the neighbour, and it did not say when. +NEIGHBOUR_HEARD_LANE = ContactLane("heard", "HEARD", 5, "heard_by_node", absent="—") + #: The middle lanes of the usual contact list: ``NAME · HEARD · PKTS · KEY``. DEFAULT_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE) @@ -157,6 +177,11 @@ CONTACTS_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE, PLACE_LANE) #: The middle lanes of the Trace-target picker, which puts ``TRACED`` before the usual two. TRACE_LANES: tuple[ContactLane, ...] = (TRACED_LANE, HEARD_LANE, PKTS_LANE) +#: The middle lanes of the neighbour table of a repeater: ``NAME · SNR · HEARD · KEY``. +#: Both middle lanes are the readings of the *remote* node, so there is no ``PKTS`` lane: +#: our own packet count would be the one number on the row that is not its measurement. +NEIGHBOUR_LANES: tuple[ContactLane, ...] = (SNR_LANE, NEIGHBOUR_HEARD_LANE) + #: The middle lanes of the Archived list: ``NAME · PLACE · ARCHIVED · KEY``. There is no #: ``HEARD`` and no ``PKTS``. An archived contact is not on the device, so this screen is not #: about what the contact still transmits. It is about where the contact is, and when it @@ -229,6 +254,19 @@ TRACE_SORT_OPENS_ASCENDING: dict[str, bool] = { "hash": True, } +#: The sort ring of the neighbour table of a repeater: ``NAME · SNR · HEARD · KEY``, the +#: same as :data:`NEIGHBOUR_LANES`. It opens on ``snr`` *descending*, so the strongest link +#: is first: the strongest neighbours say where the node sits in the mesh. An entry with no +#: reading has ``-inf``, so it collects at the weak end in both directions (refer to +#: :func:`_ordered`). +NEIGHBOUR_SORT_COLUMNS: tuple[str, ...] = ("name", "snr", "heard", "hash") +NEIGHBOUR_SORT_OPENS_ASCENDING: dict[str, bool] = { + "name": True, + "snr": False, + "heard": True, + "hash": True, +} + #: The sort ring of the Archived list: ``NAME · PLACE · ARCHIVED · KEY``, the same as #: :data:`ARCHIVED_LANES`. ``archived`` opens *ascending* on the age of the lane, so the #: most recently archived contacts come first. This screen answers the question "what did @@ -286,11 +324,22 @@ class ContactRow: archived_at: When this contact was archived and removed from the device (aware UTC). It fills the ``ARCHIVED`` lane (:data:`ARCHIVED_LANES`). Lists without that lane ignore it. + snr: The signal reading that a remote node measured for this one, in dB. It fills + the ``SNR`` lane (:data:`NEIGHBOUR_LANES`). ``None`` renders a muted ``—``. + Lists that do not declare the lane ignore it. + heard_by_node: When a remote node last heard this one (aware UTC). It fills the + ``HEARD`` lane of a neighbour table (:data:`NEIGHBOUR_LANES`), in the colour of + the recency heat. ``None`` renders a muted ``—``. Lists that do not declare the + lane ignore it. locked: Whether the contact is locked, so that it cannot be archived. A padlock then starts the row, on the left of the type glyph. ``False`` draws nothing there. managed: Whether the contact is a managed node: MeshTerm stores its admin password. The ``🔑`` then goes in the same column, after a padlock. + unknown: Whether nothing can place this node: it is not a contact of the device, + and no stored advert names it. The row then starts with the ``○`` unknown mark + in place of a type mark, because a type mark would be a claim about a node + that nobody identified. ``False`` keeps the mark of :attr:`node_type`. you: Whether this is our node. Our node gets the ``★`` marker, the pure-white ``you`` name style with a muted ``(you)`` tag, and faint ``—`` heard and packet lanes (MeshTerm never hears our node). Its row is pinned above the sorted @@ -305,9 +354,12 @@ class ContactRow: count: int | None = None last_traced: datetime | None = None archived_at: datetime | None = None + snr: float | None = None + heard_by_node: datetime | None = None place: str | None = None locked: bool = False managed: bool = False + unknown: bool = False you: bool = False @@ -401,10 +453,12 @@ def _lane_cell(row: ContactRow, lane: ContactLane) -> Text: An ``age`` lane draws the relative age in the column form (:func:`format_age`), in the colour of the recency heat. Thus a new value is bright and an old value is grey, the - same for each event that the lane measures. A ``count`` lane draws the count muted, or + same for each event that the lane measures. An age lane with no value draws the word of + its :attr:`~ContactLane.absent`. A ``count`` lane draws the count muted, or a faint ``—`` where there is nothing to count. It clamps the count, so that a very - large count cannot make the column wider. A ``text`` lane draws its string on the left, - padded to the lane, or a faint ``—`` where there is none. + large count cannot make the column wider. An ``snr`` lane draws the reading signed, to + one decimal, in the SNR scale that each other surface of the app uses. A ``text`` lane + draws its string on the left, padded to the lane, or a faint ``—`` where there is none. """ value = getattr(row, lane.field, None) if lane.kind == "text": @@ -415,7 +469,13 @@ def _lane_cell(row: ContactRow, lane: ContactLane) -> Text: if value is None: return Text(f"{'—':>{lane.width}}", style="faint") return Text(f"{min(value, 99999):>{lane.width}}", style="muted") + if lane.kind == "snr": + if value is None: + return Text(f"{'—':>{lane.width}}", style="muted") + return Text(f"{value:+.1f}".rjust(lane.width), style=snr_style(float(value))) secs = age_seconds(value) + if secs is None: + return Text(f"{lane.absent:>{lane.width}}", style=_recency_style(None)) return Text(f"{format_age(secs):>{lane.width}}", style=_recency_style(secs)) @@ -503,7 +563,9 @@ def _lane( """ if row.you: return _you_lane(row, name_w, prefix_bytes, hash_w, lanes, lock_w) - mark, mark_style = NODE_GLYPHS.get(row.node_type, DEFAULT_GLYPH) + mark, mark_style = ( + UNKNOWN_MARK if row.unknown else NODE_GLYPHS.get(row.node_type, DEFAULT_GLYPH) + ) text = Text(_lock_cell(row, lock_w), no_wrap=True, overflow="ellipsis") text.append(mark, style=mark_style) text.append(" ") @@ -536,11 +598,11 @@ def _ordered( The two fixed columns sort on their own values: name A→Z, and ``hash`` by the displayed key (ascending = ``0`` → ``f``). Each other column is a declared :class:`ContactLane`, - and sorts by the metric of the lane. A ``count`` lane sorts by its count, and an ``age`` - lane sorts by *age in seconds*. Thus ascending puts the newest first, and a row with no - value at all collects at the old end in both directions. Because of this property, - ``heard``, ``traced``, and ``archived`` behave the same, and no line of code names any - of them. + and sorts by the metric of the lane. A ``count`` lane sorts by its count, an ``snr`` + lane by its reading, and an ``age`` lane by *age in seconds*. Thus ascending puts the + newest first, and a row with no value at all collects at the old end in both + directions. Because of this property, ``heard``, ``traced``, and ``archived`` behave + the same, and no line of code names any of them. A pre-sort by name, ascending, is the stable tiebreak. Thus two contacts with the same metric keep an A→Z order in both directions, and do not change places with the primary @@ -569,6 +631,11 @@ def _ordered( return (0, str(value).casefold()) if value else (1, "") if lane.kind == "count": return value or 0 + if lane.kind == "snr": + # A reading that the node did not give is the weakest value there is, so it + # collects at the weak end in both directions, as a node that was never heard + # does in an age column. + return value if value is not None else float("-inf") secs = age_seconds(value) return secs if secs is not None else float("inf") diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index c0fa1de..312656b 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -42,14 +42,14 @@ from __future__ import annotations import asyncio import re -from collections.abc import Iterable +from collections.abc import Iterable, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any from rich.cells import cell_len from rich.text import Text -from ..core.models import Contact +from ..core.models import Contact, NeighbourInfo from ..core.remote_config import ( DISCOVERED_CATEGORY, NEVER_STORED, @@ -70,6 +70,13 @@ from ..core.remote_config import ( validate_value, write_plan, ) +from .contactlist import ( + NEIGHBOUR_LANES, + NEIGHBOUR_SORT_COLUMNS, + NEIGHBOUR_SORT_OPENS_ASCENDING, + ContactListScreen, + ContactRow, +) from .menus import ( PICK_LOCATION_HELP, PICK_LOCATION_LABEL, @@ -84,9 +91,10 @@ from .menus import ( section_heading, ) from .trace_screen import TracingDialog -from .tui import Choice, Separator +from .tui import CANCEL, Choice, Separator from .tui.select import DeleteRequest, SelectScreen, splice_hint from .tui.spinner import Spinner, spinner_interval +from .widgets import ContactsSort, _key_id if TYPE_CHECKING: from ..context import AppContext @@ -107,6 +115,7 @@ _CLOCK = "__clock__" _PASSWORD = "__password__" _REBOOT = "__reboot__" _REGIONS = "__regions__" +_NEIGHBOURS = "__neighbours__" _APPLY = "__apply__" _CANCEL = "__cancel__" @@ -398,6 +407,8 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict from .region_editor import open_region_editor await open_region_editor(ctx, device, node) + elif choice == _NEIGHBOURS: + await _neighbours(ctx, device, node) elif choice == _ADVERT: await _simple_action( ctx, @@ -518,6 +529,7 @@ def _menu_items(node: Contact, cache: dict, pending: dict[str, str]) -> tuple[st ("↻", "Read settings", "Fetch every value from the node, one paced read", _READ), ("⌨", "Command line…", "Talk to the node's CLI directly", _CLI), ("🔖", "Regions…", "Which scoped floods it relays", _REGIONS), + ("⚡", "Neighbours…", "The nodes it hears directly, and how well", _NEIGHBOURS), ("📡", "Send advert…", "Have the node announce itself now", _ADVERT), ("🕒", "Sync clock…", "Set the node's clock over the mesh", _CLOCK), ("🔐", "Admin password…", "Change the node's admin password", _PASSWORD), @@ -1020,6 +1032,169 @@ async def _run_under_dialog(ctx: AppContext, title: str, work) -> bool: return aborted +# --- the neighbour table ---------------------------------------------------------- + + +def neighbours_picker( + node: Contact, + entries: Sequence[NeighbourInfo], + *, + contacts: list[Contact], + prefix_bytes: int, +) -> ContactListScreen: + """Build the neighbour table of a node as the shared contact list, floated as a dialog. + + It is the Trace-target picker in a different subject: the same lane layout, the same + Ctrl+arrow sort ring, the same type-to-filter, the same node hues, type marks, and key + lane. Only the two middle lanes differ, because here the readings belong to the + *remote* node and not to us. ``SNR`` is what that node measured, and ``HEARD`` is how + long ago it last received from the neighbour (refer to + :data:`~meshterm.ui.contactlist.NEIGHBOUR_LANES`). The list opens on ``SNR``, with the + strongest link first. + + A neighbour that the device holds as a contact carries that contact, so Enter opens the + node page that the Contacts list opens. A neighbour that nothing can name gets a + contact built from its key prefix, so the row still opens. The page then shows what the + stored history knows about that key, which is the question that a reader has about a + node that their own radio never heard. + + Args: + node: The node that gave the table. Its name is the subject of the title. + entries: The table as the node gave it. + contacts: The contacts of the device, to name each key prefix. + prefix_bytes: The width in bytes of the hash that the routing of the mesh + addresses, to light at the start of each key. + + Returns: + The floating picker. Each row resolves with the :class:`Contact` of its neighbour. + """ + picker = ContactListScreen( + f"Neighbours — {node.name}", + rows=[_neighbour_row(entry, contacts) for entry in entries], + prefix_bytes=prefix_bytes, + sort=ContactsSort.from_name("snr", NEIGHBOUR_SORT_COLUMNS, NEIGHBOUR_SORT_OPENS_ASCENDING), + lanes=NEIGHBOUR_LANES, + ) + # The table is an answer that the admin page asked for, not a page of its own. Thus it + # floats over that page, exactly as the Trace-target picker floats over the menu. + picker.floating = True + return picker + + +def _neighbour_row(entry: NeighbourInfo, contacts: list[Contact]) -> ContactRow: + """One row of the neighbour table: its contact if the device has one, or else a stub. + + The node gives a key prefix, so the match is by prefix in the two directions (the + device can hold a contact that is itself only a prefix). With no match, the row carries + a contact of that prefix alone. It has no name, so the list draws the key prefix in the + grey of an unidentified node, after the ``○`` unknown type mark. + """ + key = entry.node.lower().removeprefix("0x") + found = next( + ( + c + for c in contacts + for held in ((c.public_key or c.key_prefix or "").lower().removeprefix("0x"),) + if held and (held.startswith(key) or key.startswith(held)) + ), + None, + ) + contact = found or Contact(name="", key_prefix=key) + return ContactRow( + value=contact, + name=found.name if found and found.name else None, + key=contact.public_key or contact.key_prefix or key, + node_type=contact.node_type, + snr=entry.snr, + heard_by_node=entry.heard_at, + unknown=found is None, + ) + + +async def _neighbours(ctx: AppContext, device: Device, node: Contact) -> None: + """Ask the node for its neighbour table, keep the snapshot, and open it as a list. + + The neighbour table is what the node hears for itself: one entry for each node whose + packets reach it directly. It is a second point of view on the mesh, and it shows + links, and whole nodes, that our own radio never received anything from. + + The admin session of this page is already open, so this sends no login. The firmware + gives the table in pages of approximately 25 entries, so the fetch can take some + seconds. Thus it runs under the same spinner dialog with Abort that the reads use. The + snapshot goes to the repository, where it becomes evidence for the topology that the + mesh walk, the path composer, and the trace scenarios read. Thus a fetch from this page + helps the same screens as a fetch from the path composer of the trace. + + The list is a hub: it stays pushed while a node page opens above it. Thus Esc from that + page lands on the same list, at the same row, in the same sort. + + Args: + ctx: The shared application context. + device: The connected companion. + node: The repeater or room server, which this page is already logged in to. + """ + from .node_detail_screen import open_node_detail + + session = ctx.ui.session + title = f"Neighbours — {node.name}" + run_id = ctx.repo.start_run( + "repeater-admin", {"node": node.name, "mode": "neighbours"}, ctx.profile_name + ) + entries: list[NeighbourInfo] = [] + done = False + + async def work(dialog: TracingDialog) -> None: + nonlocal entries, done + dialog.status = f"asking {node.name} for its neighbours…" + session.invalidate() + entries = await device.fetch_neighbours(node) + done = True + + aborted = await _run_under_dialog(ctx, title, work) + if aborted or not done: + # A failure already showed its own dialog (refer to _run_under_dialog). A second + # dialog with an empty list would say the node answered, and it did not. + ctx.repo.finish_run(run_id, "error", {"error": "aborted" if aborted else "no reply"}) + return + # The snapshot is keyed by the node, so a node with no key at all stores nothing. + # (A managed node always has one, because the login addresses it.) + node_id = _key_id(node.public_key or node.key_prefix or "") + if node_id: + ctx.repo.record_neighbours(run_id, node_id, entries) + ctx.repo.finish_run(run_id, "ok", {"node": node.name, "neighbours": len(entries)}) + + if not entries: + # Checked on real firmware: an empty table is a normal answer. A repeater forgets + # its neighbours when it reboots, and it learns them again from the adverts that + # arrive. An empty list to sort and filter is a worse answer than a sentence. + await session.message_dialog( + Text( + "no neighbours — it learns them again from the adverts it hears", + style="muted", + ), + title=title, + ) + return + + try: + contacts = await ctx.devstate.contacts() + except Exception: # noqa: BLE001 - the key prefixes alone still make a usable list + contacts = [] + try: + prefix_bytes = int(await ctx.devstate.routing_prefix_bytes()) + except Exception: # noqa: BLE001 - an optional read. Without it, nothing is lit. + prefix_bytes = 0 + picker = neighbours_picker(node, entries, contacts=contacts, prefix_bytes=prefix_bytes) + async with session.stay(picker) as visit: + while True: + chosen = await visit.result() + if chosen is CANCEL or chosen is None: + return + # To look, not to manage: the verbs that remove a contact belong to the list + # that the contact is in, and this list is the table of another node. + await open_node_detail(ctx, chosen, manage=False, lock=True) + + # --- one-shot actions ------------------------------------------------------------ diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 4c9a550..0fa2a30 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -102,7 +102,7 @@ from meshterm.ui.path_composer import PathComposerScreen from meshterm.ui.preferences import _menu_items as _preference_items from meshterm.ui.records_screen import RecordScreen, WalkVertex from meshterm.ui.remote_cli import RemoteCliScreen -from meshterm.ui.repeater_admin import AdminMenu +from meshterm.ui.repeater_admin import AdminMenu, neighbours_picker from meshterm.ui.repeater_admin import _menu_items as _admin_menu_items from meshterm.ui.theme import name_style from meshterm.ui.timemachine_screen import TimeMachineScreen @@ -1862,6 +1862,33 @@ def _repeater_admin(cols: int, rows: int) -> Screen: return AdminMenu(title, items, footer_hint="↑↓ move · type to filter · Enter select · Esc back") +def _repeater_neighbours(cols: int, rows: int) -> Screen: + """The neighbour table of a repeater, floated as the Trace-target picker is. + + It has the widest shapes that the list can draw: a long name, a node that nothing can + name (which reads as its grey key prefix, after the unknown type mark), and an entry + for which the node gave neither a reading nor an age. + """ + from datetime import timedelta + + from meshterm.core.models import NeighbourInfo + + hub = Contact(name="Hilltop-Repeater", public_key=_HUB_KEY, key_prefix="3d63c6429436") + now = utcnow() + entries = [ + NeighbourInfo("a1b2c3d4", 7.5, now - timedelta(minutes=12)), + NeighbourInfo("b7c80912", 2.0, now - timedelta(days=9)), + NeighbourInfo("c3d4e5f6", -4.25, now - timedelta(hours=3)), + NeighbourInfo("ffee0011", None, None), + ] + contacts = [ + Contact(name="Mont-Royal", public_key="a1b2c3d4" + "1" * 56, node_type=NODE_TYPE_REPEATER), + Contact(name="A Rather Long Node Name", public_key="b7c80912" + "2" * 56), + Contact(name="Chalet-Sensor", public_key="c3d4e5f6" + "3" * 56, node_type=NODE_TYPE_SENSOR), + ] + return neighbours_picker(hub, entries, contacts=contacts, prefix_bytes=1) + + def _preferences(cols: int, rows: int) -> Screen: """The Preferences page when it is widest. @@ -2205,6 +2232,7 @@ _ENTRIES: list[_Entry] = [ _Entry("config_editor_revealed", _config_editor_revealed), _Entry("repeater_admin", _repeater_admin), _Entry("region_editor", _region_editor), + _Entry("repeater_neighbours", _repeater_neighbours), _Entry("preferences", _preferences), _Entry("preferences-weekly-advert", _preferences_weekly_advert), _Entry("cooldown_countdown", _cooldown_countdown),