The Clock drift page can sync all managed clocks at once
The Managed nodes section ends on "Sync their clocks…" when a managed repeater or room server is out of sync or has no sample. One confirm, then each node in turn: a cancellable transmit-cooldown wait, a quiet login with its stored password, and "clock sync"; one summary names each result. "Adverts refused" moves to the end of the page. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b4ea549fb0
commit
5d20fe49b5
6 files changed
+254
-19
No files matched your search
@@ -28,7 +28,7 @@ This page lists each interactive screen with its scripted equivalent, where one
|
||||
| **📊 Dashboard** | The live overview of the mesh. It has a two-hour chart of the activity of all packets with a pulse line, the traffic counts of the session for each packet class, and window RF health next to the live numbers of the radio. The screen updates each second. | none |
|
||||
| **📰 Live feed** | Each packet as it arrives, newest first. A row shows the time, the type of the packet (its parsed payload class), and what the packet is about. For an advert, that is the node. For a channel text, it is the channel. For a direct message or a request, it is sender → recipient. For a trace, it is the tag. The row also shows the reception quality and, for a scoped flood, the region of the flood. Press Enter to open a row in the packet viewer, with its route graph. | none |
|
||||
| **🚨 Watchtower** | A passive watcher of the nodes that you star. It gives a silence alarm when a watched node goes quiet. It warns you when the SNR of a node gets worse, and it tells you when the node returns. It also tells you when a node is heard for the first time. It runs in the background during the whole session. Alerts that you did not acknowledge show as a badge in the header. | none |
|
||||
| **🕒 Clock drift** | How far the clock of each node is from yours. A node with a wrong clock puts wrong times on what it sends, and only its owner can set it. The page starts with a histogram of all the offsets, from the clocks behind yours, through the clocks in sync, to the clocks ahead. Then it lists your managed nodes (the nodes whose admin password MeshTerm stores), each one always, because you can set these clocks yourself. Then each other node whose clock is out of sync, the largest offset first. Press Enter to open the node page. In a chat, a message from a wrong clock shows the time when it arrived, with a `?` mark. | `meshterm clocks` |
|
||||
| **🕒 Clock drift** | How far the clock of each node is from yours. A node with a wrong clock puts wrong times on what it sends, and only its owner can set it. The page starts with a histogram of all the offsets, from the clocks behind yours, through the clocks in sync, to the clocks ahead. Then it lists your managed nodes (the nodes whose admin password MeshTerm stores), each one always, because you can set these clocks yourself. When a managed repeater or room server is out of sync, `Sync their clocks…` sets each of them in turn, with a pause between them. Then each other node whose clock is out of sync, the largest offset first. Press Enter to open the node page. In a chat, a message from a wrong clock shows the time when it arrived, with a `?` mark. | `meshterm clocks` |
|
||||
| **⏳ Time machine** | Everything that the recorder ever heard, as braille charts: reception volume, the median-SNR band, the rhythm of the hours of the day, packets and nodes for each day, and first-ever arrivals. You can switch the time window between 24h, 7d, 30d, and all time. On the PicoCalc, the windows stop at 30d. You can look at one node or at the whole mesh. | none |
|
||||
| **🎧 Monitor** | The app always records passively. On the command line, this command captures a window of a fixed length in the foreground. It shows each overheard packet as it arrives, and it gives a summary at the end. It transmits nothing. It only listens. | `meshterm monitor --seconds 60` |
|
||||
|
||||
|
||||
@@ -170,8 +170,9 @@ async def clock_rows(ctx: AppContext) -> list[ClockRow]:
|
||||
|
||||
async def _open_page(ctx: AppContext, rows: list[ClockRow], tolerance: float) -> None:
|
||||
"""Run the Clock drift page. Enter opens the node page, and Esc comes back to the row."""
|
||||
from ..ui.clocks_screen import clock_drift_screen
|
||||
from ..ui.clocks_screen import SYNC_ALL, clock_drift_screen, clocks_to_sync
|
||||
from ..ui.node_detail_screen import open_node_detail
|
||||
from ..ui.repeater_admin import sync_clocks
|
||||
from ..ui.surface import TuiUi
|
||||
from ..ui.tui.screen import CANCEL
|
||||
|
||||
@@ -183,6 +184,11 @@ async def _open_page(ctx: AppContext, rows: list[ClockRow], tolerance: float) ->
|
||||
chosen = await visit.result()
|
||||
if chosen is CANCEL or chosen is None:
|
||||
return
|
||||
if chosen == SYNC_ALL:
|
||||
# The page stays as it is: an offset changes only when a new advert of the
|
||||
# node arrives, so there is nothing to draw again now.
|
||||
await sync_clocks(ctx, clocks_to_sync(rows, tolerance))
|
||||
continue
|
||||
# The page opens to look. The verbs that manage a contact belong to the
|
||||
# Contacts list, and this page is not that list.
|
||||
await open_node_detail(ctx, chosen, manage=False)
|
||||
|
||||
@@ -15,15 +15,19 @@ The page reads the clock samples of the last ``clock_report_days`` (refer to
|
||||
user can set (JP, 2026-11-03). A managed node with no sample in the window shows its
|
||||
newest offset from all the history, or ``no sample``. A repeater sends no message, so
|
||||
its adverts are its only samples, and a new install has none yet.
|
||||
* **Adverts refused**: the contacts whose adverts the device drops, because their clocks
|
||||
were once ahead (refer to
|
||||
:attr:`~meshterm.core.models.Contact.adverts_refused_until`), with the date until which
|
||||
it drops them. The node page of each one has the repair.
|
||||
When a managed repeater or room server is out of sync, or has no sample, the section
|
||||
ends on ``Sync their clocks…``: one confirm, then each clock in turn, with the
|
||||
transmit cooldown between the nodes (refer to
|
||||
:func:`~meshterm.ui.repeater_admin.sync_clocks`).
|
||||
* **Out of sync**: each other node past the tolerance, the largest offset first. Enter
|
||||
opens the node page.
|
||||
* **Senders with no key**: the channel senders whose name resolves to no single key. Their
|
||||
samples count in the histogram, and their names are page text in the grey of an unknown
|
||||
node. There is no node page to open for a name.
|
||||
* **Adverts refused**, last (JP, 2026-11-03): the contacts whose adverts the device drops,
|
||||
because their clocks were once ahead (refer to
|
||||
:attr:`~meshterm.core.models.Contact.adverts_refused_until`), with the date until which
|
||||
it drops them. The node page of each one has the repair.
|
||||
|
||||
Each section has a header line under its heading, which pins with the heading while the
|
||||
section scrolls. When most clocks are off in the same direction, the fault is probably
|
||||
@@ -39,9 +43,10 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from rich.text import Text
|
||||
|
||||
from ..core.models import NODE_TYPE_REPEATER, NODE_TYPE_ROOM
|
||||
from ..services.clock_offsets import ClockOffset
|
||||
from .braillechart import meter
|
||||
from .menus import fit_cells, section_heading
|
||||
from .menus import fit_cells, marked_label, section_heading
|
||||
from .theme import name_style
|
||||
from .tui import Choice, Separator
|
||||
from .tui.select import SelectScreen
|
||||
@@ -74,6 +79,10 @@ _OWN_CLOCK_MIN_NODES = 5
|
||||
#: The share of the keyed nodes that must be off in one direction to blame our clock.
|
||||
_OWN_CLOCK_SHARE = 0.6
|
||||
|
||||
#: The value of the bulk ``Sync their clocks…`` row of the Managed nodes section. Each
|
||||
#: other row resolves with its contact.
|
||||
SYNC_ALL = "sync-all"
|
||||
|
||||
#: The footer hint. Enter opens the node page of the highlighted row.
|
||||
_HINT = "↑↓ move · Enter open · type to filter · Esc back"
|
||||
|
||||
@@ -367,17 +376,16 @@ def clock_drift_screen(rows: Sequence[ClockRow], *, tolerance_s: float) -> Selec
|
||||
items.append(section_heading("Managed nodes"))
|
||||
items.append(Separator(_node_header))
|
||||
items += node_rows(managed)
|
||||
|
||||
# The contacts whose adverts the device refuses, because their clocks were once ahead
|
||||
# (refer to Contact.adverts_refused_until). Their node page has the repair.
|
||||
refused = sorted(
|
||||
(r for r in rows if r.contact is not None and r.contact.adverts_refused_until),
|
||||
key=lambda r: r.label.casefold(),
|
||||
)
|
||||
if refused:
|
||||
items.append(section_heading("Adverts refused"))
|
||||
items.append(Separator(_refused_header))
|
||||
items += [Choice(lambda w, r=r: _refused_text(r, w), r.contact) for r in refused]
|
||||
# The bulk action ends the section, as the maintenance rows end the Contacts list.
|
||||
# It shows only when a clock needs it. It is a list of its own, with its own icon
|
||||
# column, so a blank seam goes on each side of it: the node rows above and below
|
||||
# have one-cell type marks, and its clock is two cells. The heading that follows
|
||||
# adds no second blank line under a blank one.
|
||||
due = clocks_to_sync(rows, tolerance_s)
|
||||
if due:
|
||||
label = marked_label("🕒", "Sync their clocks…", "")
|
||||
label.append(f" · {len(due)} {'node' if len(due) == 1 else 'nodes'}", "muted")
|
||||
items += [Separator(" "), Choice(title=label, value=SYNC_ALL), Separator(" ")]
|
||||
|
||||
others = _by_size([r for r in off if not r.managed and r.contact is not None])
|
||||
items.append(section_heading("Out of sync"))
|
||||
@@ -392,4 +400,40 @@ def clock_drift_screen(rows: Sequence[ClockRow], *, tolerance_s: float) -> Selec
|
||||
items.append(section_heading("Senders with no key"))
|
||||
items.append(Separator(_node_header))
|
||||
items += [Separator(lambda w, r=r: _name_line(r, tolerance_s, w)) for r in nameless]
|
||||
|
||||
# The contacts whose adverts the device refuses, because their clocks were once ahead
|
||||
# (refer to Contact.adverts_refused_until). Their node page has the repair. Last on the
|
||||
# page (JP, 2026-11-03): a rare state of the device, not a reading of the clocks.
|
||||
refused = sorted(
|
||||
(r for r in rows if r.contact is not None and r.contact.adverts_refused_until),
|
||||
key=lambda r: r.label.casefold(),
|
||||
)
|
||||
if refused:
|
||||
items.append(section_heading("Adverts refused"))
|
||||
items.append(Separator(_refused_header))
|
||||
items += [Choice(lambda w, r=r: _refused_text(r, w), r.contact) for r in refused]
|
||||
return SelectScreen(title, items, footer_hint=_HINT)
|
||||
|
||||
|
||||
def clocks_to_sync(rows: Sequence[ClockRow], tolerance_s: float) -> list[Contact]:
|
||||
"""The managed nodes whose clocks the bulk ``Sync their clocks…`` sets.
|
||||
|
||||
Only a repeater or a room server has the ``clock sync`` command. Of those, the ones
|
||||
whose clock is out of sync, or not known (no sample): a correct clock needs no
|
||||
transmission.
|
||||
|
||||
Args:
|
||||
rows: The rows of the page.
|
||||
tolerance_s: The ``clock_tolerance_s`` preference.
|
||||
|
||||
Returns:
|
||||
The contacts, in the order of the page.
|
||||
"""
|
||||
return [
|
||||
r.contact
|
||||
for r in _by_size(rows)
|
||||
if r.managed
|
||||
and r.contact is not None
|
||||
and r.node_type in (NODE_TYPE_REPEATER, NODE_TYPE_ROOM)
|
||||
and (r.offset is None or r.out_of_sync(tolerance_s))
|
||||
]
|
||||
@@ -1106,6 +1106,92 @@ async def sync_clock(ctx: AppContext, node: Contact) -> None:
|
||||
)
|
||||
|
||||
|
||||
async def sync_clocks(ctx: AppContext, nodes: list[Contact]) -> None:
|
||||
"""Set the clocks of several managed nodes from ours, one node at a time.
|
||||
|
||||
This is the bulk ``Sync their clocks…`` of the Clock drift page. One confirm for the
|
||||
whole list, then for each node a login with its stored password and the ``clock sync``
|
||||
command. MeshTerm never sends a burst: before each node it waits for the transmit
|
||||
cooldown (refer to :func:`~meshterm.ui.cooldown.wait_for_cooldown`), whose countdown the
|
||||
user can cancel. A cancel stops the run, and the summary says which nodes got their
|
||||
clocks.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context (the interactive menu must be running).
|
||||
nodes: The managed repeaters and room servers to set.
|
||||
"""
|
||||
from .cooldown import wait_for_cooldown
|
||||
|
||||
if not nodes:
|
||||
return
|
||||
names = ", ".join(node.name for node in nodes)
|
||||
choice = await ctx.ui.dialog(
|
||||
f"Set the clocks of {len(nodes)} managed nodes from this companion's time? "
|
||||
f"MeshTerm logs in to each one and sends one command, with a pause between "
|
||||
f"transmissions. ({names})",
|
||||
[("Cancel", None), ("Sync", "go")],
|
||||
title="Sync clocks",
|
||||
default=1,
|
||||
)
|
||||
if choice != "go":
|
||||
return
|
||||
device = await ctx.device()
|
||||
results: list[tuple[Contact, bool, str]] = []
|
||||
for node in nodes:
|
||||
# One wait for each node, before its login. The login and the command are one
|
||||
# exchange with one node, as on the admin page, and the command marks the
|
||||
# transmit clock that the wait of the next node reads.
|
||||
if not await wait_for_cooldown(ctx, action=f"Sync clock — {node.name}"):
|
||||
break
|
||||
ok, reason = await _quiet_login(ctx, device, node)
|
||||
if ok:
|
||||
async with ctx.ui.busy_overlay():
|
||||
reply = await device.send_remote_command(
|
||||
node, "clock sync", timeout=_REPLY_TIMEOUT_S
|
||||
)
|
||||
if reply is None:
|
||||
ok, reason = False, "no reply — the command may still have landed"
|
||||
else:
|
||||
ok, reason = not reply_is_error(reply), reply.strip()
|
||||
results.append((node, ok, reason))
|
||||
body = Text()
|
||||
for node, ok, reason in results:
|
||||
if body.plain:
|
||||
body.append("\n")
|
||||
body.append("✓ " if ok else "✗ ", style="ok" if ok else "err")
|
||||
body.append(node.name)
|
||||
body.append(f" · {reason}", style="muted")
|
||||
skipped = len(nodes) - len(results)
|
||||
if skipped:
|
||||
body.append(f"\n{skipped} not done: the run was cancelled", style="warn")
|
||||
await ctx.ui.session.message_dialog(body, title="Sync clocks")
|
||||
|
||||
|
||||
async def _quiet_login(ctx: AppContext, device: Device, node: Contact) -> tuple[bool, str]:
|
||||
"""Log in to a managed node with its stored password, with no dialog.
|
||||
|
||||
The bulk sync reports each failure in one summary, not one dialog for each node. The
|
||||
password rules are those of :func:`_login`: a refused password is forgotten, and a
|
||||
silence keeps it.
|
||||
|
||||
Returns:
|
||||
``(True, "")`` when the session opened, else ``(False, the reason)``.
|
||||
"""
|
||||
from ..core.models import LoginResult
|
||||
|
||||
password = ctx.admin_store.get(node)
|
||||
if password is None:
|
||||
return False, "no stored password"
|
||||
async with ctx.ui.busy_overlay():
|
||||
outcome = await device.admin_login(node, password)
|
||||
ctx.admin_store.record(node, password, outcome)
|
||||
if outcome is LoginResult.REFUSED:
|
||||
return False, "the login was refused; the saved password was cleared"
|
||||
if not outcome:
|
||||
return False, "no reply to the login"
|
||||
return True, ""
|
||||
|
||||
|
||||
async def _change_password(ctx: AppContext, device: Device, node: Contact) -> None:
|
||||
"""Change the admin password of the node (and remember the new password if it succeeds)."""
|
||||
new = await ctx.ui.text(
|
||||
|
||||
@@ -190,3 +190,102 @@ def test_clock_rows_name_their_nodes_and_mark_the_managed_ones(tmp_path: Path) -
|
||||
listing = _listing(rows, TOLERANCE)
|
||||
assert listing.rows[-1]["offset_s"] is None and listing.rows[-1]["managed"]
|
||||
repo.close()
|
||||
|
||||
|
||||
# -- the bulk clock sync ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def _managed(name: str, offset_s: float | None, node_type: int | None = NODE_TYPE_REPEATER): # noqa: ANN202
|
||||
key = (name.encode().hex() * 32)[:64]
|
||||
contact = Contact(name=name, public_key=key, node_type=node_type)
|
||||
offset = None if offset_s is None else ClockOffset(key[:12], True, offset_s, 3, utcnow())
|
||||
return ClockRow(offset, name, key, node_type, True, contact)
|
||||
|
||||
|
||||
def test_the_bulk_row_ends_the_managed_section_when_a_clock_needs_it() -> None:
|
||||
"""A repeater out of sync and one with no sample are due. A correct clock is not.
|
||||
|
||||
A managed companion has no ``clock sync`` command, so it is never due.
|
||||
"""
|
||||
from meshterm.ui.clocks_screen import SYNC_ALL, clocks_to_sync
|
||||
|
||||
rows = [
|
||||
_managed("Fine", 10),
|
||||
_managed("Behind", -7200),
|
||||
_managed("Unknown", None),
|
||||
_managed("Phone", -7200, node_type=None),
|
||||
]
|
||||
assert [c.name for c in clocks_to_sync(rows, TOLERANCE)] == ["Behind", "Unknown"]
|
||||
screen = clock_drift_screen(rows, tolerance_s=TOLERANCE)
|
||||
text = plain("\n".join(screen.render_body(72)))
|
||||
assert "Sync their clocks… · 2 nodes" in text
|
||||
assert text.index("Sync their clocks") < text.index("Out of sync")
|
||||
assert any(getattr(item, "value", None) == SYNC_ALL for item in screen._items)
|
||||
|
||||
in_sync = clock_drift_screen([_managed("Fine", 10)], tolerance_s=TOLERANCE)
|
||||
assert "Sync their clocks" not in plain("\n".join(in_sync.render_body(72)))
|
||||
|
||||
|
||||
class _Ui:
|
||||
"""The UI of the bulk sync: the confirm, the busy overlay, and the summary."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.summary = None
|
||||
self.session = self
|
||||
|
||||
async def dialog(self, prompt, buttons, **kw): # noqa: ANN001, ANN003, ANN201
|
||||
return "go"
|
||||
|
||||
def busy_overlay(self): # noqa: ANN201
|
||||
return _AsyncNull()
|
||||
|
||||
async def message_dialog(self, body, **kw): # noqa: ANN001, ANN003, ANN201
|
||||
self.summary = body.plain
|
||||
|
||||
|
||||
class _AsyncNull:
|
||||
async def __aenter__(self) -> None:
|
||||
return None
|
||||
|
||||
async def __aexit__(self, *exc) -> None: # noqa: ANN002
|
||||
return None
|
||||
|
||||
|
||||
class _Device:
|
||||
"""Two nodes: one accepts the login and the command, one never answers the login."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.commands: list[str] = []
|
||||
|
||||
async def admin_login(self, node, password): # noqa: ANN001, ANN201
|
||||
from meshterm.core.models import LoginResult
|
||||
|
||||
return LoginResult.ACCEPTED if node.name == "Behind" else LoginResult.NO_REPLY
|
||||
|
||||
async def send_remote_command(self, node, command, timeout): # noqa: ANN001, ANN201
|
||||
self.commands.append(f"{node.name}: {command}")
|
||||
return "OK - clock set"
|
||||
|
||||
|
||||
def test_the_bulk_sync_sets_each_clock_and_sums_up(tmp_path: Path, monkeypatch) -> None: # noqa: ANN001
|
||||
"""One confirm, then each node in turn. The summary names each result."""
|
||||
from meshterm.core import transmit_gate
|
||||
from meshterm.ui.repeater_admin import sync_clocks
|
||||
|
||||
monkeypatch.setattr(transmit_gate, "remaining", lambda **kw: 0.0) # no countdown here
|
||||
behind, silent = _managed("Behind", -7200).contact, _managed("Silent", None).contact
|
||||
admin = AdminStore(tmp_path / "admin.json")
|
||||
admin.remember(behind, "secret")
|
||||
admin.remember(silent, "secret")
|
||||
device = _Device()
|
||||
ui = _Ui()
|
||||
|
||||
async def get_device(): # noqa: ANN202
|
||||
return device
|
||||
|
||||
ctx = type("Ctx", (), {"ui": ui, "admin_store": admin, "device": staticmethod(get_device)})
|
||||
asyncio.run(sync_clocks(ctx, [behind, silent]))
|
||||
assert device.commands == ["Behind: clock sync"] # no command after a silent login
|
||||
assert "✓ Behind" in ui.summary and "OK - clock set" in ui.summary
|
||||
assert "✗ Silent" in ui.summary and "no reply to the login" in ui.summary
|
||||
assert admin.get(silent) == "secret" # a silence keeps the password
|
||||
@@ -175,4 +175,4 @@ def test_the_page_lists_the_contacts_whose_adverts_are_refused() -> None:
|
||||
text = plain("\n".join(screen.render_body(72)))
|
||||
assert "Adverts refused" in text
|
||||
assert f"{until.astimezone():%Y-%m-%d}" in text
|
||||
assert text.index("All clocks") < text.index("Adverts refused")
|
||||
assert text.index("Out of sync") < text.index("Adverts refused") # the last section
|
||||
Reference in new issue
Block a user