Docstrings and comments of meshterm/tools are in ASD-STE100
The same rewrite as for the core package. No help= string, epilog, or other UX text changed. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5fc224476c
commit
6b90e0505b
26 files changed
+2001
-1819
No files matched your search
@@ -1,8 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Pluggable tools (menu options / CLI subcommands).
|
||||
"""Tools that plug in: the menu items and the CLI subcommands.
|
||||
|
||||
Importing this package eagerly imports every tool module so that each one's ``@register``
|
||||
decorator populates the shared registry. New features only need to add a module here.
|
||||
When this package is imported, it imports each tool module immediately. Thus the
|
||||
``@register`` decorator of each module adds its tools to the shared registry. A new feature
|
||||
must only add a module here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,9 +17,10 @@ __all__ = ["Tool", "all_tools", "get_tool", "register", "load_all_tools"]
|
||||
|
||||
|
||||
def load_all_tools() -> None:
|
||||
"""Import every sibling module so its tools self-register.
|
||||
"""Import each sibling module, so that its tools add themselves to the registry.
|
||||
|
||||
Modules whose names start with an underscore (and ``base``) are skipped.
|
||||
This function does not import the modules whose names start with an underscore, or
|
||||
``base``.
|
||||
"""
|
||||
package = __name__
|
||||
for mod in pkgutil.iter_modules(__path__):
|
||||
@@ -27,5 +29,5 @@ def load_all_tools() -> None:
|
||||
importlib.import_module(f"{package}.{mod.name}")
|
||||
|
||||
|
||||
# Populate the registry on import so the CLI and menu see every tool.
|
||||
# Fill the registry when the package is imported, so that the CLI and the menu get each tool.
|
||||
load_all_tools()
|
||||
+63
-61
@@ -1,21 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The About MeshTerm tools: the four written pages in the menu's last section.
|
||||
"""The About MeshTerm tools: the four written pages in the last section of the menu.
|
||||
|
||||
*About MeshTerm*, *About the author*, *Join Discord*, *Support MeshTerm* — in that
|
||||
order, which is the order a stranger asks the questions in: what is this, who made it,
|
||||
where is everyone, how do I help. They share the *This app* section with Preferences,
|
||||
which leads it: the section is the app's own, and the one row that *changes*
|
||||
MeshTerm sits above the four that describe it.
|
||||
Each is a page rather than a feature: it reads nothing, transmits nothing, and needs no
|
||||
device, so it opens straight to its screen (see :mod:`meshterm.ui.about`) instead of
|
||||
prompting for anything first.
|
||||
The pages are "About MeshTerm", "About the author", "Join Discord", and "Support
|
||||
MeshTerm", in that order. A new user asks the questions in the same order: what is this,
|
||||
who made it, where are the other users, and how can I help. The pages share the "This
|
||||
app" section with Preferences, which is first in it. The section belongs to the app
|
||||
itself, and the only row that changes MeshTerm is above the four rows that describe it.
|
||||
Each item is a page, not a feature. It reads nothing, it transmits nothing, and it does
|
||||
not use a device. Thus it opens directly to its screen (refer to :mod:`meshterm.ui.about`),
|
||||
and it does not ask for anything first.
|
||||
|
||||
Each also keeps a CLI face — ``meshterm about``, ``meshterm about-author``,
|
||||
``meshterm discord``, ``meshterm support`` — printing the same page to the terminal, so
|
||||
the answers are reachable from a shell without launching the full-screen session.
|
||||
Each page also has a CLI face (``meshterm about``, ``meshterm about-author``,
|
||||
``meshterm discord``, ``meshterm support``) that prints the same page to the terminal.
|
||||
Thus a user can get the answers from a shell without the full-screen session.
|
||||
|
||||
The pages themselves are written in markdown under ``meshterm/assets/pages`` (see
|
||||
:mod:`meshterm.ui.about`); nothing here knows what any of them say.
|
||||
The pages are written in markdown in ``meshterm/assets/pages`` (refer to
|
||||
:mod:`meshterm.ui.about`). Nothing in this module knows the content of a page.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,34 +31,34 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class _AboutTool(Tool):
|
||||
"""Shared behaviour for the four About pages: open the screen, or print the page.
|
||||
"""The shared behaviour of the four About pages: open the screen, or print the page.
|
||||
|
||||
The pages differ only in their title, icon, and content, so everything else — the
|
||||
menu-only screen open, the printing CLI face, the run row — lives here once. A
|
||||
subclass supplies :meth:`page`, and nothing more.
|
||||
The pages are different only in their title, icon, and content. Thus all the other
|
||||
parts (the screen that opens only in the menu, the CLI face that prints, the run row)
|
||||
are in this class, one time. A subclass gives :meth:`page`, and nothing more.
|
||||
"""
|
||||
|
||||
category = "This app"
|
||||
|
||||
@staticmethod
|
||||
def page() -> MarkdownDoc:
|
||||
"""Build this page's content.
|
||||
"""Build the content of this page.
|
||||
|
||||
Overridden by each page. Subclasses import their builder *inside* the override
|
||||
rather than at module scope: the registry imports every tool module at startup
|
||||
(see :func:`~meshterm.tools.load_all_tools`), and a page's content is only ever
|
||||
wanted once someone actually opens it.
|
||||
Each page overrides this method. A subclass imports its builder in the override,
|
||||
not at module scope. The reason is that the registry imports each tool module at
|
||||
startup (refer to :func:`~meshterm.tools.load_all_tools`), but the content of a
|
||||
page is necessary only when a user opens it.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Open the page; returning ``None`` completes the invocation with no run row.
|
||||
"""Open the page. The return value ``None`` completes the run with no run row.
|
||||
|
||||
The page transmits nothing and stores nothing, so — like the Trophy case and the
|
||||
mesh walk — it lives here rather than in :meth:`run`, and logs no run of its own.
|
||||
The page transmits nothing and stores nothing. Thus, as with the Trophy case and
|
||||
the mesh walk, it opens here, not in :meth:`run`, and it logs no run of its own.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -69,18 +69,18 @@ class _AboutTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""State the page — only reachable from the CLI (the menu opens the screen).
|
||||
"""Give the page. Only the CLI comes to this method (the menu opens the screen).
|
||||
|
||||
Without its scannable codes: a QR is a second rendering of a link the page already
|
||||
prints, drawn for a phone pointed at a screen, and redirected into a file it is a
|
||||
block of block characters around nothing new.
|
||||
The page has no QR codes here. A QR code is a second rendering of a link that the
|
||||
page already prints. It is drawn for a phone that points at a screen. In a
|
||||
redirected file, it is only a mass of block characters, with no new information.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused beyond the injected ``_run_id``.
|
||||
ctx: The shared application context.
|
||||
params: Not used, except for the injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` naming the page that was shown.
|
||||
A :class:`ToolResult` that names the page that was shown.
|
||||
"""
|
||||
return ToolResult(
|
||||
summary={"page": self.name},
|
||||
@@ -90,13 +90,13 @@ class _AboutTool(Tool):
|
||||
|
||||
@register
|
||||
class AboutMeshTermTool(_AboutTool):
|
||||
"""What MeshTerm is, where it came from, and the terms it ships under."""
|
||||
"""What MeshTerm is, where it came from, and the terms under which it is distributed."""
|
||||
|
||||
name = "about"
|
||||
title = "About MeshTerm"
|
||||
icon = "📖"
|
||||
help = "What this is, and the terms it ships under"
|
||||
order = 10 # the question a stranger asks first
|
||||
order = 10 # the first question of a new user
|
||||
|
||||
@staticmethod
|
||||
def page() -> MarkdownDoc:
|
||||
@@ -108,13 +108,13 @@ class AboutMeshTermTool(_AboutTool):
|
||||
|
||||
@register
|
||||
class AboutAuthorTool(_AboutTool):
|
||||
"""The person behind MeshTerm, on the mesh and off it."""
|
||||
"""The person who made MeshTerm, on the mesh and off the mesh."""
|
||||
|
||||
name = "about-author"
|
||||
title = "About the author"
|
||||
icon = "👤"
|
||||
help = "The person behind MeshTerm, on and off the mesh"
|
||||
order = 20 # who made the thing you just read about
|
||||
order = 20 # who made the app that the previous page describes
|
||||
|
||||
@staticmethod
|
||||
def page() -> MarkdownDoc:
|
||||
@@ -126,13 +126,13 @@ class AboutAuthorTool(_AboutTool):
|
||||
|
||||
@register
|
||||
class JoinDiscordTool(_AboutTool):
|
||||
"""The community server: one invite link, and a QR of it for a phone to read."""
|
||||
"""The community server: one invite link, and its QR code for a phone to read."""
|
||||
|
||||
name = "discord"
|
||||
title = "Join Discord"
|
||||
icon = "🔗"
|
||||
help = "The invite link to the MeshTerm community server"
|
||||
order = 25 # where everyone else is, once you know what this is and who made it
|
||||
order = 25 # where the other users are, after the user knows what this is and who made it
|
||||
|
||||
@staticmethod
|
||||
def page() -> MarkdownDoc:
|
||||
@@ -144,13 +144,13 @@ class JoinDiscordTool(_AboutTool):
|
||||
|
||||
@register
|
||||
class SupportProjectTool(_AboutTool):
|
||||
"""What keeps MeshTerm going, and the ways — paid and unpaid — to help it along."""
|
||||
"""What MeshTerm needs to continue, and the paid and unpaid ways to help it."""
|
||||
|
||||
name = "support"
|
||||
title = "Support MeshTerm"
|
||||
icon = "💰"
|
||||
help = "What keeps MeshTerm going, and how to help"
|
||||
order = 30 # the ask, and only once the pages before it have earned it
|
||||
order = 30 # the request for help, only after the pages before it earned it
|
||||
|
||||
@staticmethod
|
||||
def page() -> MarkdownDoc:
|
||||
@@ -161,20 +161,21 @@ class SupportProjectTool(_AboutTool):
|
||||
|
||||
|
||||
def _written_page(name: str, title: str, doc: MarkdownDoc) -> Facts:
|
||||
"""One prose page, stated once for both faces.
|
||||
"""One prose page, given one time for both faces.
|
||||
|
||||
**Wrapped**, and that is the one deliberate exception to "no line wrapping". The rule
|
||||
exists so a *record* is never split across two lines with its fields landing under the
|
||||
wrong headings; a paragraph has no records and no headings, and left unwrapped these
|
||||
four pages print as single six-hundred-cell lines no terminal can read. So the page is
|
||||
drawn on a console :data:`~meshterm.ui.script.PAGE_WIDTH` cells wide — a fixed width,
|
||||
not the terminal's, so the same paragraph reads the same piped, redirected, or shipped
|
||||
as the document's ``text``.
|
||||
The page is **wrapped**. This is the only exception, on purpose, to the "no line
|
||||
wrapping" rule. The rule makes sure that a record is never divided across two lines,
|
||||
with its fields under the wrong headings. A paragraph has no records and no headings.
|
||||
Without a wrap, these four pages print as lines of six hundred cells, and in a
|
||||
terminal, nobody can read such a line. Thus the page is drawn on a console that is
|
||||
:data:`~meshterm.ui.script.PAGE_WIDTH` cells wide. This is a fixed width, not the width
|
||||
of the terminal. Thus the same paragraph looks the same in a pipe, in a redirected
|
||||
file, or in the ``text`` of the document.
|
||||
|
||||
``links`` is the one machine-actionable thing on a page of prose, and the one thing the
|
||||
menu bothers to draw a QR of. ``text`` is the page's plain rendering rather than a fold
|
||||
of the markdown into nested JSON: a structured markdown tree would be a second
|
||||
rendering, not data, and nothing would consume it.
|
||||
``links`` is the only part of a prose page that a program can use, and the only part
|
||||
that the menu draws as a QR code. ``text`` is the plain rendering of the page, not the
|
||||
markdown changed into nested JSON. A structured markdown tree is a second rendering,
|
||||
not data, and no program uses one.
|
||||
"""
|
||||
from .. import __version__
|
||||
from ..ui import fields
|
||||
@@ -193,8 +194,8 @@ def _written_page(name: str, title: str, doc: MarkdownDoc) -> Facts:
|
||||
values={
|
||||
"page": name,
|
||||
"title": title,
|
||||
# Duplicated from the package on purpose: a page's own facts are part of its
|
||||
# content, and this is the version its `{version}` placeholder resolved to.
|
||||
# A copy of the package value, on purpose. The facts of a page are part of its
|
||||
# content, and this is the version that its `{version}` placeholder became.
|
||||
"version": __version__,
|
||||
"text": text,
|
||||
"links": _links(text),
|
||||
@@ -205,7 +206,7 @@ def _written_page(name: str, title: str, doc: MarkdownDoc) -> Facts:
|
||||
|
||||
|
||||
def _rendered_page(doc: MarkdownDoc) -> str:
|
||||
"""The page as plain text, folded to the fixed page width."""
|
||||
"""The page as plain text, wrapped at the fixed page width."""
|
||||
import io
|
||||
|
||||
from rich.console import Console
|
||||
@@ -225,11 +226,12 @@ def _rendered_page(doc: MarkdownDoc) -> str:
|
||||
|
||||
|
||||
def _links(text: str) -> list[str]:
|
||||
"""Every URL the page carries, in document order, de-duplicated.
|
||||
"""All the URLs on the page, in document order, and each URL one time.
|
||||
|
||||
Read off the rendered page rather than the markdown source, so a link written as a
|
||||
reference and a link written inline both count once and both read as what the reader
|
||||
sees. Trailing punctuation is not part of a URL and is trimmed.
|
||||
The function reads the URLs from the rendered page, not from the markdown source.
|
||||
Thus a reference link and an inline link both count one time, and both are the text
|
||||
that the user sees. Punctuation at the end is not part of a URL, so the function
|
||||
removes it.
|
||||
"""
|
||||
import re
|
||||
|
||||
|
||||
+22
-22
@@ -1,14 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``advert`` tool: announce this node to the mesh, straight from the main menu.
|
||||
"""The ``advert`` tool: announce this node to the mesh, directly from the main menu.
|
||||
|
||||
Opens the Send advert flow (see :func:`meshterm.ui.config_editor.send_advert`) — a
|
||||
zero-hop or flood advertisement, or this node's shareable contact card as a QR code.
|
||||
A ``popup`` tool: the flow's prompts and result float over the still-pushed main menu
|
||||
as modal dialogs (the quit-dialog pattern), so the everyday action stays a quick
|
||||
in-place popup rather than a screen change.
|
||||
The tool opens the Send advert flow (refer to :func:`meshterm.ui.config_editor.send_advert`):
|
||||
a zero-hop or flood advert, or the contact card of this node as a QR code to share. It is
|
||||
a ``popup`` tool. The prompts and the result of the flow float as modal dialogs over the
|
||||
main menu, which stays pushed (the pattern of the quit dialog). Thus this everyday action
|
||||
stays a quick dialog in place, not a change of screen.
|
||||
|
||||
Menu-only: the scripted equivalents are ``config advert`` and ``config share``, so no
|
||||
duplicate subcommand is registered here.
|
||||
Menu only: the scripted equivalents are ``config advert`` and ``config share``, so this
|
||||
module registers no duplicate subcommand.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,19 +30,19 @@ class SendAdvertTool(Tool):
|
||||
icon = "📡"
|
||||
help = "Announce this node — zero-hop, flood, or QR"
|
||||
category = "This node"
|
||||
order = 40 # your own node announcing itself: a device action, not a view
|
||||
popup = True # dialog-sized: float over the menu instead of replacing it
|
||||
order = 40 # our node announces itself: a device action, not a screen
|
||||
popup = True # dialog-sized: float over the menu, and do not replace it
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the interactive advert flow; there are never parameters to collect.
|
||||
"""Run the interactive advert flow. It has no parameters to collect.
|
||||
|
||||
The flow presents its own result (the sent-advert note or the contact-card
|
||||
view) before returning, so by the time the user backs out there is nothing
|
||||
left for :meth:`run` to do — returning ``None`` tells the menu the invocation
|
||||
is complete (the same pattern as the Device config page).
|
||||
The flow shows its own result (the note about the sent advert, or the contact
|
||||
card) before it returns. Thus, when the user leaves, :meth:`run` has nothing more
|
||||
to do. The return value ``None`` tells the menu that the run is complete (the
|
||||
same pattern as the Device config page).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -53,20 +53,20 @@ class SendAdvertTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Nothing runs here: the advert is sent inside :meth:`prompt_params`.
|
||||
"""Nothing runs here: the advert is sent in :meth:`prompt_params`.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
An empty :class:`ToolResult` (only reachable from a scripted call).
|
||||
An empty :class:`ToolResult` (only a scripted call comes here).
|
||||
"""
|
||||
return ToolResult(summary={})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — ``config advert`` / ``config share`` cover scripting.
|
||||
"""Register no CLI command: ``config advert`` and ``config share`` are for scripts.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
+114
-101
@@ -1,10 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The tool plugin contract and registry.
|
||||
"""The contract and the registry of the tool plugins.
|
||||
|
||||
A *tool* is one menu option / CLI subcommand. Subclass :class:`Tool`, decorate it with
|
||||
:func:`register`, and implement :meth:`Tool.run`. The same registry drives both the
|
||||
interactive menu and the Typer CLI, and :meth:`Tool.execute` wraps every invocation in a
|
||||
logged ``runs`` row, so new tools get persistence and logging for free.
|
||||
A *tool* is one menu item and one CLI subcommand. To make a tool, subclass :class:`Tool`,
|
||||
decorate it with :func:`register`, and implement :meth:`Tool.run`. The same registry
|
||||
controls the interactive menu and the Typer CLI. :meth:`Tool.execute` puts each run of a
|
||||
tool in a logged ``runs`` row. Thus a new tool gets storage and logging with no more
|
||||
work.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +16,7 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
from ..core import exitcodes
|
||||
|
||||
if TYPE_CHECKING: # avoid importing typer/context at module load for fast startup
|
||||
if TYPE_CHECKING: # do not import typer or the context at module load, for a fast start
|
||||
import typer
|
||||
|
||||
from ..context import AppContext
|
||||
@@ -24,34 +25,36 @@ if TYPE_CHECKING: # avoid importing typer/context at module load for fast start
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ToolResult:
|
||||
"""The outcome of a tool execution.
|
||||
"""The result of a run of a tool.
|
||||
|
||||
Attributes:
|
||||
summary: JSON-serializable summary persisted to the run record.
|
||||
message: Optional human-readable closing message. The *menu's* closing line — a
|
||||
scripted run does not print it (see
|
||||
summary: A summary that can be serialized to JSON. It is stored in the record of
|
||||
the run.
|
||||
message: An optional closing message for a person. It is the closing line of the
|
||||
*menu*. A scripted run does not print it (refer to
|
||||
:func:`~meshterm.cli._execute_and_render`), because on the command line it
|
||||
restates the output above it and the exit status below it.
|
||||
artifacts: Paths to any files produced (e.g. generated visualizations).
|
||||
exit_code: The status a scripted run should exit with — see
|
||||
:mod:`meshterm.core.exitcodes`. Left at ``OK`` by everything that worked;
|
||||
set to ``NO_RESULT`` by a tool that ran fine and found nothing to report, so
|
||||
a caller can tell an empty mesh from a full one without counting lines. A
|
||||
*failure* is raised, not returned, so this never carries one.
|
||||
report: **The answer**, as data (see :mod:`meshterm.ui.report`). A scripted run
|
||||
states it here and the CLI boundary hands it to a renderer, exactly as it
|
||||
already does with ``exit_code`` — the tool says what happened, and something
|
||||
else turns that into bytes or into a process status. It used to be printed
|
||||
instead, which meant the answer was gone by the time anything could ask for it
|
||||
in another format, which is why ``--json`` reached two commands and stopped.
|
||||
repeats the output above it and the exit status below it.
|
||||
artifacts: The paths of the files that the tool made (for example, generated
|
||||
visualizations).
|
||||
exit_code: The status with which a scripted run must exit. Refer to
|
||||
:mod:`meshterm.core.exitcodes`. A tool that worked keeps ``OK``. A tool that
|
||||
ran correctly and found nothing to report sets ``NO_RESULT``. Thus a caller
|
||||
can tell an empty mesh from a full one, and does not have to count lines. A
|
||||
*failure* is raised, not returned, so this value never holds one.
|
||||
report: **The answer**, as data (refer to :mod:`meshterm.ui.report`). A scripted
|
||||
run puts it here, and the CLI boundary gives it to a renderer. The boundary
|
||||
does the same with ``exit_code``: the tool says what occurred, and other code
|
||||
changes that into bytes or into a process status. Before, the tool printed
|
||||
the answer instead. Then the answer was gone before anything could ask for it
|
||||
in another format. That is why ``--json`` got to two commands and stopped.
|
||||
|
||||
``None`` for the menu path and for a feature with no scripted face at all (the
|
||||
map, the dashboard), which keep working unchanged.
|
||||
``None`` for the menu path, and for a feature that has no scripted face (the
|
||||
map, the dashboard). These continue to work with no change.
|
||||
|
||||
Not folded into ``summary``: that is the *run log's* record of what this
|
||||
invocation did, written to the ``runs`` table on every execution including a
|
||||
menu run. Putting a five-hour ``monitor`` capture in SQLite would be the price
|
||||
of one field fewer.
|
||||
It is not part of ``summary``. ``summary`` is the record in the *run log* of
|
||||
what this run did, and each run writes it to the ``runs`` table, also a menu
|
||||
run. If ``report`` is part of it, a five-hour ``monitor`` capture goes into
|
||||
SQLite. That is the cost of one field fewer.
|
||||
"""
|
||||
|
||||
summary: dict[str, Any] = field(default_factory=dict)
|
||||
@@ -62,27 +65,31 @@ class ToolResult:
|
||||
|
||||
|
||||
class Tool(ABC):
|
||||
"""Base class for all MeshTerm features.
|
||||
"""The base class for all MeshTerm features.
|
||||
|
||||
Class Attributes:
|
||||
name: CLI identifier (kebab-case), unique across tools.
|
||||
title: Display name shown as the interactive menu item and on the tool's result
|
||||
window. Capitalized, and kept identical to the screen the item opens so the
|
||||
menu never promises one name and delivers another. Falls back to ``name``.
|
||||
help: One-line description shown in the menu and ``--help`` (no trailing period).
|
||||
icon: Emoji drawn before the title in the interactive menu (and only there — the
|
||||
result window keeps the plain title). Single-codepoint, emoji-presentation
|
||||
glyphs only, so the two-cell width holds across terminals (see
|
||||
:mod:`meshterm.ui.tui.emoji_width`).
|
||||
category: Grouping label used to organize the interactive menu.
|
||||
order: Sort key within a category (lower sorts first).
|
||||
menu_visible: Whether the tool appears in the interactive menu. Set ``False`` for
|
||||
CLI-only tools (e.g. startup-time diagnostics with no place in a connected
|
||||
session); such tools still register a CLI subcommand as usual.
|
||||
popup: Whether the menu stays pushed while this tool runs, so the tool's prompts
|
||||
and result float over it as modal popups (the quit-dialog pattern) instead of
|
||||
replacing the screen. For quick dialog-sized tools; a tool that pushes its
|
||||
own full screen keeps the default.
|
||||
name: The CLI identifier (kebab-case). It is unique among the tools.
|
||||
title: The name that the interactive menu item and the result screen of the tool
|
||||
show. It starts with a capital letter. It is the same as the name of the
|
||||
screen that the item opens, so that the menu never shows one name and opens
|
||||
another. If it is empty, ``name`` is used.
|
||||
help: The one-line description in the menu and in ``--help`` (with no period at
|
||||
the end).
|
||||
icon: The emoji that the interactive menu draws before the title (only there:
|
||||
the result screen keeps the plain title). Use only glyphs of one code point
|
||||
with emoji presentation, so that the width of two cells is the same on all
|
||||
terminals (refer to :mod:`meshterm.ui.tui.emoji_width`).
|
||||
category: The group label that organizes the interactive menu.
|
||||
order: The sort key in a category (a lower value comes first).
|
||||
menu_visible: Whether the tool is in the interactive menu. Set ``False`` for a
|
||||
tool that is only for the CLI (for example, diagnostics at startup, which
|
||||
have no place in a connected session). Such a tool registers a CLI
|
||||
subcommand as usual.
|
||||
popup: Whether the menu stays pushed while this tool runs. Then the prompts and
|
||||
the result of the tool float over the menu as modal dialogs (the pattern of
|
||||
the quit dialog), and do not replace the screen. This is for quick tools of
|
||||
the size of a dialog. A tool that pushes its own full screen keeps the
|
||||
default.
|
||||
"""
|
||||
|
||||
name: str = ""
|
||||
@@ -96,39 +103,40 @@ class Tool(ABC):
|
||||
|
||||
@abstractmethod
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Execute the tool's work.
|
||||
"""Do the work of the tool.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context (console, device, repository, ...).
|
||||
params: Validated parameters for this invocation.
|
||||
ctx: The shared application context (console, device, repository, and other
|
||||
items).
|
||||
params: The validated parameters for this run.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` describing the outcome.
|
||||
A :class:`ToolResult` that describes the result.
|
||||
"""
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any]:
|
||||
"""Interactively gather parameters for the menu.
|
||||
"""Ask the user for the parameters of a menu run.
|
||||
|
||||
The default implementation requires no parameters. Tools override this to ask
|
||||
the user through :attr:`AppContext.ui` — a dialog or a select list in the menu, and
|
||||
nothing at all on the CLI, where the arguments came off the command line.
|
||||
The default implementation has no parameters. A tool overrides this method to ask
|
||||
the user through :attr:`AppContext.ui`: a dialog or a select list in the menu.
|
||||
On the CLI, it asks nothing, because the arguments came from the command line.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
A parameter dict compatible with :meth:`run`.
|
||||
A dict of parameters that :meth:`run` accepts.
|
||||
"""
|
||||
return {}
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register this tool as a Typer subcommand.
|
||||
|
||||
The default registers a no-argument command. Tools with parameters override this
|
||||
to declare typed options, then delegate to :meth:`execute`.
|
||||
The default registers a command with no arguments. A tool with parameters
|
||||
overrides this method to declare typed options, and then calls :meth:`execute`.
|
||||
|
||||
Args:
|
||||
app: The Typer application to add the command to.
|
||||
app: The Typer application that gets the command.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
@@ -137,20 +145,20 @@ class Tool(ABC):
|
||||
run_tool_command(self, {})
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run the tool wrapped in run-logging and error capture.
|
||||
"""Run the tool, with a log of the run and a capture of its errors.
|
||||
|
||||
Opens a ``runs`` row before execution and closes it with the final status and
|
||||
summary afterward, regardless of success.
|
||||
This method opens a ``runs`` row before the run. After the run, it closes the row
|
||||
with the final status and the summary, also when the run failed.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Parameters for this invocation.
|
||||
ctx: The shared application context.
|
||||
params: The parameters for this run.
|
||||
|
||||
Returns:
|
||||
The :class:`ToolResult` from :meth:`run`.
|
||||
|
||||
Raises:
|
||||
Exception: Re-raises any error from :meth:`run` after recording it.
|
||||
Exception: Each error from :meth:`run`, raised again after it is stored.
|
||||
"""
|
||||
import typer
|
||||
|
||||
@@ -168,24 +176,27 @@ class Tool(ABC):
|
||||
DeviceConfigError,
|
||||
DeviceCommandError,
|
||||
PreferenceError,
|
||||
# A tool rejecting one of its own arguments (an unresolvable `--to`) raises
|
||||
# what the parser would have. It is a usage error, not a fault.
|
||||
# When a tool refuses one of its own arguments (a `--to` that it cannot
|
||||
# resolve), it raises the same error as the parser. It is a usage error, not a
|
||||
# fault.
|
||||
typer.BadParameter,
|
||||
typer.Abort,
|
||||
typer.Exit,
|
||||
) as exc:
|
||||
# Expected user-facing condition (no/ambiguous device, a bad config or
|
||||
# preference value, a bad argument, or a transient command failure): record it
|
||||
# but don't dump a traceback; callers print the message cleanly.
|
||||
# An expected condition for the user (no device or an ambiguous device, a bad
|
||||
# config or preference value, a bad argument, or a temporary failure of a
|
||||
# command). Store it, but do not write a traceback. The callers print the
|
||||
# message cleanly.
|
||||
ctx.repo.finish_run(run_id, "error", {"error": str(exc)})
|
||||
ctx.log.debug("run %s aborted: %s", run_id, exc)
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - we record then re-raise
|
||||
except Exception as exc: # noqa: BLE001 - we store it, then raise it again
|
||||
ctx.repo.finish_run(run_id, "error", {"error": str(exc)})
|
||||
if is_connection_lost(exc):
|
||||
# The radio was unplugged or powered off mid-command. Every layer above
|
||||
# already knows how to say that in one line; a stack of serial internals
|
||||
# describes how the driver found out, which is not the same question.
|
||||
# The device was disconnected or switched off during a command. Each
|
||||
# layer above knows how to say that in one line. A stack of serial
|
||||
# internals tells how the driver found the problem, and that is a
|
||||
# different question.
|
||||
ctx.log.warning("run %s lost the device connection: %s", run_id, exc)
|
||||
else:
|
||||
ctx.log.exception("run %s failed: %s", run_id, exc)
|
||||
@@ -197,20 +208,22 @@ class Tool(ABC):
|
||||
|
||||
_REGISTRY: dict[str, Tool] = {}
|
||||
|
||||
#: Explicit menu ordering for tool categories. The menu asks "What would you like to
|
||||
#: do?", so its sections answer that: each names a *doing*, not a subject, and holds
|
||||
#: everything that shares it. Message leads (the everyday features, plus the book you
|
||||
#: pick a recipient from), then Watch (what the mesh is doing, what it did, what to be
|
||||
#: told about), Explore (where the nodes are, how they reach each other, and the boards
|
||||
#: that score the walking), then the two owners a setting can belong to — This node, the
|
||||
#: radio in your hand, and Other nodes, someone else's over the mesh.
|
||||
#: The explicit order of the tool categories in the menu. The menu asks "What would you
|
||||
#: like to do?", so its sections answer that question. Each section names an *activity*,
|
||||
#: not a subject, and holds all the items for that activity. Message is first (the
|
||||
#: features for each day, and the list from which you select a recipient). Then come Watch
|
||||
#: (what the mesh does, what it did, and what to get notifications about) and Explore
|
||||
#: (where the nodes are, how they get to each other, and the boards that score the walks).
|
||||
#: Then come the two owners of a setting: This node (the radio in your hand) and Other
|
||||
#: nodes (the radio of another person, over the mesh).
|
||||
#:
|
||||
#: This app closes the list as the third and last *owner*, after the radio in your hand and
|
||||
#: someone else's over the mesh: the program in front of you. It holds the one thing that
|
||||
#: changes how MeshTerm behaves (Preferences) and the four pages that say what MeshTerm is
|
||||
#: — questions none of the doings above can hold, and which nothing on the mesh can answer.
|
||||
#: It sits last because a reader who has run out of things to do is who goes looking for it.
|
||||
#: Categories not listed here sort last, alphabetically, so a new category still appears.
|
||||
#: This app ends the list as the third and last *owner*, after the radio in your hand and
|
||||
#: the radio of another person over the mesh: it is the program in front of you. It holds
|
||||
#: the one item that changes how MeshTerm behaves (Preferences), and the four pages that
|
||||
#: say what MeshTerm is. These are questions that no activity above can hold, and that
|
||||
#: nothing on the mesh can answer. This app is last because the user who has nothing more
|
||||
#: to do is the user who looks for it. Categories that are not in this list come last, in
|
||||
#: alphabetical order. Thus a new category is always in the menu.
|
||||
_CATEGORY_ORDER = [
|
||||
"Message",
|
||||
"Watch",
|
||||
@@ -222,7 +235,7 @@ _CATEGORY_ORDER = [
|
||||
|
||||
|
||||
def _category_rank(category: str) -> int:
|
||||
"""Return a category's sort rank (its position in ``_CATEGORY_ORDER``, else last)."""
|
||||
"""Return the sort rank of a category (its position in ``_CATEGORY_ORDER``, or last)."""
|
||||
try:
|
||||
return _CATEGORY_ORDER.index(category)
|
||||
except ValueError:
|
||||
@@ -230,16 +243,16 @@ def _category_rank(category: str) -> int:
|
||||
|
||||
|
||||
def register(cls: type[Tool]) -> type[Tool]:
|
||||
"""Class decorator that instantiates a tool and adds it to the registry.
|
||||
"""A class decorator that makes an instance of a tool and adds it to the registry.
|
||||
|
||||
Args:
|
||||
cls: The :class:`Tool` subclass to register.
|
||||
|
||||
Returns:
|
||||
The unchanged class (so the decorator is transparent).
|
||||
The class with no change (thus the decorator is transparent).
|
||||
|
||||
Raises:
|
||||
ValueError: If the tool has no ``name`` or the name is already registered.
|
||||
ValueError: If the tool has no ``name``, or if the name is already registered.
|
||||
"""
|
||||
instance = cls()
|
||||
if not instance.name:
|
||||
@@ -251,14 +264,14 @@ def register(cls: type[Tool]) -> type[Tool]:
|
||||
|
||||
|
||||
def all_tools() -> list[Tool]:
|
||||
"""Return all registered tools sorted by category rank, then order, then name.
|
||||
"""Return all the registered tools, sorted by category rank, then order, then name.
|
||||
|
||||
Categories are ordered by :data:`_CATEGORY_ORDER` (Mesh first), so the first-class
|
||||
Chat and Channels tools lead the menu; within a category, ``order`` then ``name`` break
|
||||
ties.
|
||||
:data:`_CATEGORY_ORDER` sets the order of the categories (Mesh first). Thus the main
|
||||
tools, Chat and Channels, come first in the menu. In a category, ``order`` and then
|
||||
``name`` decide a tie.
|
||||
|
||||
Returns:
|
||||
The registered tool instances in stable menu order.
|
||||
The registered tool instances, in a stable menu order.
|
||||
"""
|
||||
return sorted(
|
||||
_REGISTRY.values(),
|
||||
@@ -267,12 +280,12 @@ def all_tools() -> list[Tool]:
|
||||
|
||||
|
||||
def get_tool(name: str) -> Tool | None:
|
||||
"""Look up a registered tool by name.
|
||||
"""Find a registered tool by its name.
|
||||
|
||||
Args:
|
||||
name: The tool's ``name``.
|
||||
name: The ``name`` of the tool.
|
||||
|
||||
Returns:
|
||||
The tool instance, or ``None`` if not registered.
|
||||
The tool instance, or ``None`` if no tool has that name.
|
||||
"""
|
||||
return _REGISTRY.get(name)
|
||||
+81
-72
@@ -1,14 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``channels`` tool: create, join, and manage mesh channels.
|
||||
|
||||
Interactively it opens a full-screen channel manager (see :mod:`meshterm.ui.channels`) — a
|
||||
first-class, phone-app-style experience for creating private channels, adding public ``#``
|
||||
channels, joining with a key, importing a scanned ``meshcore://`` link, and sharing any
|
||||
channel as a QR code. On the CLI it exposes ``list``, ``add``, ``join``, ``import``,
|
||||
``share``, ``clear`` and ``scope`` subcommands for scripted use.
|
||||
In the menu, the tool opens a full-screen channel manager (refer to
|
||||
:mod:`meshterm.ui.channels`). The manager is a complete feature, similar to a phone app.
|
||||
With it, the user can create a private channel, add a public ``#`` channel, join a channel
|
||||
with a key, import a scanned ``meshcore://`` link, and share any channel as a QR code. On
|
||||
the CLI, the tool gives the ``list``, ``add``, ``join``, ``import``, ``share``, ``clear``,
|
||||
and ``scope`` subcommands for use in scripts.
|
||||
|
||||
Channels are also *listed* by the ``chat`` tool for picking a conversation; this tool owns
|
||||
everything to do with configuring the slots themselves.
|
||||
The ``chat`` tool also lists the channels, so that the user can select a conversation. But
|
||||
this tool owns all the configuration of the slots.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -49,11 +50,11 @@ class ChannelsTool(Tool):
|
||||
"""Open the channel manager (menu) or run a scripted action (CLI).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: A ``cli_action`` with its arguments (CLI), or empty for the menu.
|
||||
ctx: The shared application context.
|
||||
params: A ``cli_action`` and its arguments (CLI), or empty for the menu.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` recording what happened (the menu path shows nothing).
|
||||
A :class:`ToolResult` that holds what occurred. The menu path shows nothing.
|
||||
"""
|
||||
action = params.get("cli_action")
|
||||
if action is not None:
|
||||
@@ -61,16 +62,16 @@ class ChannelsTool(Tool):
|
||||
|
||||
from ..ui.channels import manage_channels
|
||||
|
||||
# No message: the manager acknowledged its work on the way out, which meant telling
|
||||
# the reader that changes they had just watched land were applied. The count still
|
||||
# goes to the run log through ``summary``, which is the record of what an invocation
|
||||
# did rather than anything shown.
|
||||
# No message. The manager once acknowledged its work when the user left it. That
|
||||
# told the user that the changes were applied, but the user saw them occur already.
|
||||
# The count still goes to the run log through ``summary``. ``summary`` is the
|
||||
# record of what a run did, not a thing that the screen shows.
|
||||
return ToolResult(summary={"changes": await manage_channels(ctx)})
|
||||
|
||||
# -- CLI --------------------------------------------------------------------
|
||||
|
||||
async def _run_cli(self, ctx: AppContext, action: str, params: dict[str, Any]) -> ToolResult:
|
||||
"""Dispatch a scripted CLI action."""
|
||||
"""Run the handler for a scripted CLI action."""
|
||||
if action == "add":
|
||||
return await self._cli_add(ctx, params)
|
||||
if action == "join":
|
||||
@@ -98,13 +99,13 @@ class ChannelsTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_add(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Add a public, private-random, or explicitly-keyed channel on a slot."""
|
||||
"""Add a channel on a slot: public, private with a random key, or with a given key."""
|
||||
from ..ui.channels import write_channel
|
||||
|
||||
device = await ctx.device()
|
||||
idx = int(params["index"])
|
||||
name = str(params["name"])
|
||||
if name.startswith("#"): # public: firmware derives the key from the name
|
||||
if name.startswith("#"): # public: the firmware derives the key from the name
|
||||
await write_channel(ctx, device, idx, name, None)
|
||||
secret = derive_secret(name)
|
||||
else:
|
||||
@@ -117,7 +118,7 @@ class ChannelsTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_join(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Join a channel from a name and an explicit key."""
|
||||
"""Join a channel with a name and a given key."""
|
||||
from ..ui.channels import write_channel
|
||||
|
||||
device = await ctx.device()
|
||||
@@ -147,11 +148,11 @@ class ChannelsTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_share(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Print a channel's share link, with its QR code in the menu.
|
||||
"""Print the share link of a channel. In the menu, also show its QR code.
|
||||
|
||||
The one command that names a channel's key deliberately, so it is the one place
|
||||
the secret and the share URL leave the app at all — every other channel document
|
||||
carries the identity and stops there.
|
||||
This is the only command that shows the key of a channel on purpose. Thus it is
|
||||
the only place where the secret and the share URL go out of the app. Each other
|
||||
channel document holds the identity of the channel and nothing more.
|
||||
"""
|
||||
from ..core.channel_probe import read_channel_slots
|
||||
|
||||
@@ -171,12 +172,13 @@ class ChannelsTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_clear(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Clear a channel slot, removing the channel from the device.
|
||||
"""Clear a channel slot. This removes the channel from the device.
|
||||
|
||||
The scriptable face of the channel manager's *Clear this slot*: an empty name
|
||||
makes the firmware read the slot as unused. The ``--yes`` gate lives on the CLI
|
||||
command (a private channel's key is lost with the slot unless it's saved
|
||||
elsewhere), mirroring the interactive flow's danger confirmation.
|
||||
This is the script form of "Clear this slot" in the channel manager. An empty
|
||||
name makes the firmware read the slot as unused. The ``--yes`` gate is on the CLI
|
||||
command, because the key of a private channel is lost with the slot if it is not
|
||||
saved in a different place. The gate is the same as the danger confirmation of
|
||||
the interactive flow.
|
||||
"""
|
||||
from ..core.channel_probe import read_channel_slots
|
||||
from ..ui.channels import write_channel
|
||||
@@ -190,27 +192,28 @@ class ChannelsTool(Tool):
|
||||
report=(_cleared(idx, False),),
|
||||
exit_code=exitcodes.NO_RESULT,
|
||||
)
|
||||
await write_channel(ctx, device, idx, "", None) # empty name => the slot reads as unused
|
||||
await write_channel(ctx, device, idx, "", None) # an empty name marks the slot as unused
|
||||
return ToolResult(
|
||||
summary={"index": idx, "cleared": True},
|
||||
report=(_cleared(idx, True),),
|
||||
)
|
||||
|
||||
async def _cli_scope(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Read, set or clear the region a channel's messages are sent under.
|
||||
"""Read, set, or clear the scope of a channel: the region its messages are sent in.
|
||||
|
||||
The scriptable face of the detail page's *Send scope…*. The scope is MeshTerm's to
|
||||
keep (the firmware has none per channel; the send sets the companion's session
|
||||
scope around each message), so setting one writes nothing to the radio — the slot
|
||||
is read only to learn which channel is in it, since the scope is keyed by the
|
||||
channel's identity and follows it to any slot.
|
||||
This is the script form of "Send scope…" on the detail page. MeshTerm keeps the
|
||||
scope, because the firmware has no scope for each channel. When MeshTerm sends a
|
||||
message, it sets the session scope of the companion around that message. Thus,
|
||||
when this command sets a scope, it writes nothing to the device. It reads the slot
|
||||
only to find which channel is in it, because the scope is keyed by the identity of
|
||||
the channel. The scope follows the channel to any slot.
|
||||
|
||||
With no region, the plain face prints the scope alone, the way ``config get`` prints
|
||||
one value — and a channel with none prints ``-`` and exits 0: "no scope, so the
|
||||
device default" is an answer about a channel that is there, not an empty result. A
|
||||
set or a clear prints nothing, and the document always carries the channel and its
|
||||
scope (``null`` for none). Only an empty slot, with no channel to answer about,
|
||||
exits 5.
|
||||
With no region, the plain face prints only the scope, as ``config get`` prints one
|
||||
value. A channel with no scope prints ``-`` and exits 0, because "no scope, so the
|
||||
device default" is an answer about a channel that exists. It is not an empty
|
||||
result. A set or a clear prints nothing. The document always holds the channel and
|
||||
its scope (``null`` for no scope). Only an empty slot exits 5, because it has no
|
||||
channel to answer about.
|
||||
"""
|
||||
from ..core.channel_probe import read_channel_slots
|
||||
|
||||
@@ -220,8 +223,9 @@ class ChannelsTool(Tool):
|
||||
region = params.get("region")
|
||||
if slot is None:
|
||||
if region is not None or params.get("clear"):
|
||||
# A write names a channel that isn't there: a bad argument, not an empty
|
||||
# answer — exit 5 would tell a script the scope was set and read back empty.
|
||||
# A write names a channel that does not exist. That is a bad argument, not an
|
||||
# empty answer. Exit 5 tells a script that the scope was set and then read
|
||||
# back as empty, which is false.
|
||||
import typer
|
||||
|
||||
raise typer.BadParameter(f"slot {idx} is empty; there is no channel to scope")
|
||||
@@ -244,12 +248,12 @@ class ChannelsTool(Tool):
|
||||
|
||||
@staticmethod
|
||||
async def _show_qr(ctx: AppContext, name: str, url: str) -> None:
|
||||
"""Draw a channel's share link as a QR code — in the menu, and only there.
|
||||
"""Draw the share link of a channel as a QR code, only in the menu.
|
||||
|
||||
The QR is for a phone pointed at the screen, and there it takes the whole screen
|
||||
(:func:`~meshterm.ui.qr.share_screen`). Piped into a file it is a block of block
|
||||
characters wrapped around the one thing that is actually the answer, so a scripted
|
||||
run states the link and nothing else.
|
||||
The QR code is for a phone that points at the screen. There, the code fills the
|
||||
whole screen (:func:`~meshterm.ui.qr.share_screen`). In a file (through a pipe),
|
||||
the code is only a mass of block characters around the link, and the link is the
|
||||
real answer. Thus a scripted run prints the link and nothing else.
|
||||
"""
|
||||
from ..ui.qr import share_screen
|
||||
from ..ui.surface import TuiUi
|
||||
@@ -314,8 +318,9 @@ class ChannelsTool(Tool):
|
||||
),
|
||||
) -> None:
|
||||
if not yes:
|
||||
# A usage error, in the parser's own words and under its own status — not a
|
||||
# red line printed onto whatever is reading this command's output.
|
||||
# A usage error, in the words of the parser and with its exit status. It is
|
||||
# not a red line printed into the program that reads the output of this
|
||||
# command.
|
||||
raise typer.BadParameter(
|
||||
"clearing a slot removes the channel (a private channel's key is lost "
|
||||
"unless you have it saved). Re-run with --yes to confirm."
|
||||
@@ -349,14 +354,16 @@ class ChannelsTool(Tool):
|
||||
|
||||
|
||||
def _channel_listing(slots: list, store: object | None = None) -> Listing:
|
||||
"""The configured slots, one record each.
|
||||
"""The configured slots, one record for each slot.
|
||||
|
||||
The one listing whose record *is* a shared shape rather than carrying one: a row that
|
||||
nested its only field under a ``channel`` key would make ``jq '.[].channel.name'``
|
||||
out of a listing whose every column is already the channel.
|
||||
This is the only listing whose record is a shared shape itself, instead of a record
|
||||
that holds one. Each column of this listing is already the channel. If each row put
|
||||
its only field under a ``channel`` key, a query must be ``jq '.[].channel.name'``
|
||||
for no reason.
|
||||
|
||||
``SCOPE`` is the region the channel's messages are sent under (``-`` and ``null`` for
|
||||
the device default), read from the region store the send path reads.
|
||||
``SCOPE`` is the region that the messages of the channel are sent in (``-`` and
|
||||
``null`` for the device default). The value comes from the region store, which the
|
||||
send path also reads.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import Listing
|
||||
@@ -389,15 +396,15 @@ def _channel_listing(slots: list, store: object | None = None) -> Listing:
|
||||
def _scoped(
|
||||
idx: int, name: str | None, secret: bytes | None, scope: str | None, *, changed: bool
|
||||
) -> Facts:
|
||||
"""What ``channels scope`` read or set: the channel and the region it sends into.
|
||||
"""What ``channels scope`` read or set: the channel and the region that it sends into.
|
||||
|
||||
Args:
|
||||
idx: The slot index.
|
||||
name: The channel name, or ``None`` for a slot that turned out to be empty.
|
||||
name: The channel name, or ``None`` if the slot is empty.
|
||||
secret: The 16-byte key, or ``None`` for an empty slot.
|
||||
scope: The channel's scope now, or ``None`` for the device default.
|
||||
changed: Whether this run set or cleared it — then the plain face is silent, the
|
||||
way every write's is; a read prints the scope alone.
|
||||
scope: The current scope of the channel, or ``None`` for the device default.
|
||||
changed: Whether this run set or cleared the scope. If it did, the plain face
|
||||
prints nothing, as for each write. A read prints only the scope.
|
||||
|
||||
Returns:
|
||||
The facts block.
|
||||
@@ -410,10 +417,11 @@ def _scoped(
|
||||
if name is not None and secret is not None:
|
||||
public = is_public_channel(name, secret)
|
||||
channel = ChannelRef(slot=idx, name=name, public=public, hash=channel_hash(secret))
|
||||
# A channel with no scope answers `-` plain (and `null` in the document): "the device
|
||||
# default" is an answer about a channel that is there, where the bare form's usual
|
||||
# silence for an absent value would leave only the exit status to say it. An empty
|
||||
# slot has no channel to answer about, so it keeps that silence (and its exit 5).
|
||||
# A channel with no scope prints `-` on the plain face (and `null` in the document).
|
||||
# "The device default" is an answer about a channel that exists. Usually the bare form
|
||||
# prints nothing for an absent value, and then only the exit status can give this
|
||||
# answer. An empty slot has no channel to answer about, so it keeps that silence (and
|
||||
# its exit 5).
|
||||
value = Rendered(scope, scope or script.NONE) if channel is not None else None
|
||||
return Facts(
|
||||
key="channel",
|
||||
@@ -425,17 +433,18 @@ def _scoped(
|
||||
|
||||
|
||||
def _written(idx: int, name: str | None, secret: bytes | None, *, shown: bool = True) -> Facts:
|
||||
"""What a slot now holds, after ``add``, ``join``, ``import`` or ``share``.
|
||||
"""What a slot holds now, after ``add``, ``join``, ``import``, or ``share``.
|
||||
|
||||
All four write or read the same thing and all four know the key they wrote, so all
|
||||
four state the same shape. The plain face prints the share URL alone where the caller
|
||||
asked to be given something to pass on (``add``, ``share``) and nothing at all where
|
||||
it did not (``join``, ``import``): those two were handed the key, and reading it back
|
||||
to them is not an answer.
|
||||
All four commands write or read the same thing, and all four know the key that they
|
||||
wrote. Thus all four give the same shape. The plain face prints only the share URL
|
||||
when the caller asked for something to give to other persons (``add``, ``share``). It
|
||||
prints nothing when the caller did not ask for it (``join``, ``import``). The caller
|
||||
gave the key to these two commands, and to read the key back to the caller is not an
|
||||
answer.
|
||||
|
||||
Args:
|
||||
idx: The slot index.
|
||||
name: The channel name, or ``None`` for a slot that turned out to be empty.
|
||||
name: The channel name, or ``None`` if the slot is empty.
|
||||
secret: The 16-byte key, or ``None`` for an empty slot.
|
||||
shown: Whether the plain face prints the URL.
|
||||
|
||||
@@ -468,7 +477,7 @@ def _written(idx: int, name: str | None, secret: bytes | None, *, shown: bool =
|
||||
|
||||
|
||||
def _cleared(idx: int, cleared: bool) -> Facts:
|
||||
"""What ``channels clear`` did — nothing plain, since the status already said it."""
|
||||
"""What ``channels clear`` did. The plain face prints nothing, because the status said it."""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Facts
|
||||
|
||||
|
||||
+372
-333
File diff suppressed because it is too large.
Load diff
+155
-146
@@ -1,13 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``config`` tool: every device setting, and the operations on the box itself.
|
||||
"""The ``config`` tool: each device setting, and the operations on the device itself.
|
||||
|
||||
Interactively it opens the Device config page (see :mod:`meshterm.ui.config_editor`) —
|
||||
settings staged and applied in place, with the clock, backup/restore, the identity key,
|
||||
reboot and factory reset as actions below them. On the CLI it exposes generic key/value
|
||||
subcommands plus backup/restore, channels, custom vars, and a ``--yes``-gated set of
|
||||
destructive operations. Everything funnels through :func:`apply_ops`: the page's Apply and
|
||||
its actions, :meth:`ConfigTool.run` for the scripted commands, and the standalone ``advert``
|
||||
tool's sends all run through the one executor.
|
||||
In the menu, it opens the Device config page (refer to :mod:`meshterm.ui.config_editor`).
|
||||
There, the settings are staged and applied in place, and the clock, backup and restore,
|
||||
the identity key, reboot, and factory reset are actions below them. On the CLI, it has
|
||||
generic key and value subcommands, and also backup and restore, channels, custom
|
||||
variables, and a set of destructive operations that must have ``--yes``. All of these go
|
||||
through :func:`apply_ops`. The Apply and the actions of the page, :meth:`ConfigTool.run`
|
||||
for the scripted commands, and the sends of the standalone ``advert`` tool all run
|
||||
through the one executor.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,7 +39,7 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class ConfigTool(Tool):
|
||||
"""View and edit the connected device's full configuration."""
|
||||
"""Show and edit all the settings of the connected device."""
|
||||
|
||||
name = "config"
|
||||
title = "Device config"
|
||||
@@ -48,14 +49,14 @@ class ConfigTool(Tool):
|
||||
order = 20
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the Device config page; there are never parameters to collect.
|
||||
"""Run the Device config page. There are never parameters to collect.
|
||||
|
||||
The page applies what is staged and runs its actions itself, logging a ``runs`` row
|
||||
for each Apply (the same pattern as ``repeater-admin``), so by the time the reader
|
||||
backs out there is nothing left for :meth:`run` to do.
|
||||
The page itself applies the staged values and runs its actions, and logs a ``runs``
|
||||
row for each Apply (the same pattern as ``repeater-admin``). Thus, when the user
|
||||
leaves, :meth:`run` has nothing more to do.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -66,14 +67,14 @@ class ConfigTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Execute a list of configuration operations against the device.
|
||||
"""Do a list of setting operations on the device.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``ops`` — a list of operation tuples (see module docstring).
|
||||
ctx: The shared application context.
|
||||
params: ``ops``: a list of operation tuples (refer to the module docstring).
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing how many values changed.
|
||||
A :class:`ToolResult` with a summary of how many values changed.
|
||||
"""
|
||||
device = await ctx.device()
|
||||
ops: list[tuple] = list(params.get("ops") or [])
|
||||
@@ -104,7 +105,7 @@ class ConfigTool(Tool):
|
||||
|
||||
@config_app.callback(invoke_without_command=True)
|
||||
def _root(ctx: typer.Context) -> None:
|
||||
"""Show the configuration when no subcommand is given."""
|
||||
"""Show all the current settings when no subcommand is given."""
|
||||
if ctx.invoked_subcommand is None:
|
||||
run_tool_command(self, {"ops": [("show",)]})
|
||||
|
||||
@@ -196,30 +197,30 @@ class ConfigTool(Tool):
|
||||
app.add_typer(config_app, name=self.name)
|
||||
|
||||
|
||||
# -- op execution (shared by the tool and the interactive editor) -------------
|
||||
# -- op execution (the tool and the interactive editor share it) --------------
|
||||
|
||||
|
||||
async def apply_ops(
|
||||
ctx: AppContext, device: Device, snapshot: dict, ops: list[tuple]
|
||||
) -> tuple[int, list[str], Report]:
|
||||
"""Execute a list of configuration operation tuples against ``device``.
|
||||
"""Do a list of setting operation tuples on ``device``.
|
||||
|
||||
This is the single executor for every config operation, used by :meth:`ConfigTool.run`
|
||||
(the scripted commands) and by the Device config page — its Apply, one staged value at a
|
||||
time, and its actions (reboot, backup/restore, key management, factory reset), which run
|
||||
immediately rather than staging.
|
||||
This is the only executor for all the setting operations. :meth:`ConfigTool.run` (the
|
||||
scripted commands) uses it, and the Device config page uses it too: for its Apply, one
|
||||
staged value at a time, and for its actions (reboot, backup and restore, key
|
||||
management, factory reset). The actions run immediately, and are not staged.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context (for console output).
|
||||
device: The connected device to act on.
|
||||
snapshot: The current device snapshot; updated in place as settings change so
|
||||
coupled commands rebuild from current values.
|
||||
ops: Operation tuples (see the module docstring).
|
||||
ctx: The shared application context (for console output).
|
||||
device: The connected device on which to do the operations.
|
||||
snapshot: The current device snapshot. It is changed in place when settings
|
||||
change, so that coupled commands are made again from the current values.
|
||||
ops: The operation tuples (refer to the module docstring).
|
||||
|
||||
Returns:
|
||||
A ``(changes, artifacts, report)`` triple: the number of value changes applied,
|
||||
any file paths produced, and the blocks stating what happened (empty for the
|
||||
menu, which shows its own acknowledgements).
|
||||
A ``(changes, artifacts, report)`` triple: the number of applied value changes,
|
||||
the paths of the files that were made, and the blocks that state what occurred
|
||||
(empty for the menu, which shows its own acknowledgements).
|
||||
"""
|
||||
changes = 0
|
||||
artifacts: list[str] = []
|
||||
@@ -232,10 +233,10 @@ async def apply_ops(
|
||||
if block is not None:
|
||||
report.append(block)
|
||||
elif kind == "get":
|
||||
# The bare value, nothing else: the caller named the key, so repeating it back
|
||||
# is one more thing for `$(meshterm config get name)` to strip off. The same
|
||||
# shape `sysctl -n` and `git config --get` print. The document keeps the key,
|
||||
# the type and an enum's label, none of which the bare form has room for.
|
||||
# Only the bare value. The caller named the key, so if the output repeats it,
|
||||
# `$(meshterm config get name)` must remove one more thing. `sysctl -n` and
|
||||
# `git config --get` print the same shape. The document keeps the key, the type,
|
||||
# and the label of an enum, and the bare form has space for none of them.
|
||||
spec = get_spec(op[1])
|
||||
report.append(_one_setting(spec, spec.getter(snapshot)))
|
||||
elif kind == "set":
|
||||
@@ -265,9 +266,10 @@ async def apply_ops(
|
||||
elif kind == "advert":
|
||||
flood = len(op) > 1 and bool(op[1])
|
||||
await device.send_advert(flood)
|
||||
# A flood advert, however it was asked for, restarts this device's week: the
|
||||
# weekly one only ever goes out a full week after the last (see
|
||||
# AdvertScheduler). A zero-hop reaches only the neighbours, and resets nothing.
|
||||
# A flood advert, however it was requested, starts the week of this device again.
|
||||
# The weekly advert goes out only a full week after the last one (refer to
|
||||
# AdvertScheduler). A zero-hop advert gets only to the neighbours, and resets
|
||||
# nothing.
|
||||
public_key = str(snapshot.get("public_key") or "")
|
||||
if flood and public_key:
|
||||
ctx.advert_store.mark_flood(public_key)
|
||||
@@ -277,8 +279,8 @@ async def apply_ops(
|
||||
elif kind == "share":
|
||||
report.append(await _share_contact(ctx, snapshot))
|
||||
elif kind == "sync_clock":
|
||||
# The same step the on-connect service runs in the background
|
||||
# (:mod:`meshterm.services.clock_sync`); here it is acknowledged and reported.
|
||||
# The same step that the on-connect service runs in the background
|
||||
# (:mod:`meshterm.services.clock_sync`). Here, it is acknowledged and reported.
|
||||
done = await set_clock(device)
|
||||
if done.written:
|
||||
ctx.ui.ack(f"[ok]✓[/ok] device clock set to [brand]{done.stamp}[/brand]")
|
||||
@@ -293,8 +295,8 @@ async def apply_ops(
|
||||
"clock",
|
||||
changes=int(done.written),
|
||||
set_at=done.set_at,
|
||||
# What the clock was off by *before* the set: the fact worth logging,
|
||||
# and the one this command destroys by succeeding.
|
||||
# The clock error *before* the set. That is the fact to log, and when
|
||||
# this command succeeds, it removes that fact.
|
||||
drift_s=done.drift_s,
|
||||
)
|
||||
)
|
||||
@@ -303,8 +305,9 @@ async def apply_ops(
|
||||
ctx.ui.ack("[warn]device rebooting[/warn]")
|
||||
report.append(_acted("reboot", rebooted=True))
|
||||
if ctx.active_transport is not None:
|
||||
# Run from the menu's command line, this hands off to the reconnect dialog
|
||||
# as the config editor's reboot does; a scripted run has no watcher to wake.
|
||||
# When this runs from the command line of the menu, it gives control to the
|
||||
# reconnect dialog, as the reboot of the config editor does. A scripted run
|
||||
# has no watcher to wake.
|
||||
ctx.announce_reboot()
|
||||
elif kind == "export_key":
|
||||
report.append(await _export_key(ctx, device, op[1] if len(op) > 1 else None, artifacts))
|
||||
@@ -317,20 +320,21 @@ async def apply_ops(
|
||||
await device.factory_reset()
|
||||
ctx.ui.ack("[err]device factory-reset[/err]")
|
||||
report.append(_acted("factory_reset", factory_reset=True))
|
||||
else: # pragma: no cover - guarded by the call sites that build ops
|
||||
else: # pragma: no cover - the call sites that make ops prevent this
|
||||
raise DeviceCommandError(f"unknown config operation: {kind}")
|
||||
if applied:
|
||||
report.append(_applied(applied))
|
||||
# Drop any session-cached facts these ops may have changed, so the next screen re-reads
|
||||
# the truth rather than a stale copy (see meshterm.services.device_state.DeviceState). A
|
||||
# reboot/reconnect resets the whole cache on its own; these cover the in-place edits.
|
||||
# Remove the facts in the session cache that these ops can have changed. Thus the next
|
||||
# screen reads the true values again, not an old copy (refer to
|
||||
# meshterm.services.device_state.DeviceState). A reboot or a reconnect resets the full
|
||||
# cache itself. These lines are for the edits in place.
|
||||
kinds = {op[0] for op in ops}
|
||||
_WHOLESALE = {"restore", "import_key", "factory_reset"}
|
||||
if kinds & _WHOLESALE:
|
||||
ctx.devstate.reset()
|
||||
else:
|
||||
if "set" in kinds:
|
||||
ctx.devstate.invalidate_config() # self-info fields + path-hash mode
|
||||
ctx.devstate.invalidate_config() # the self-info fields and the path hash mode
|
||||
if "set_channel" in kinds:
|
||||
ctx.devstate.invalidate_channels()
|
||||
return changes, artifacts, tuple(report)
|
||||
@@ -339,24 +343,25 @@ async def apply_ops(
|
||||
async def _apply_setting(
|
||||
ctx: AppContext, device: Device, key: str, raw: Any, snapshot: dict
|
||||
) -> dict[str, Any]:
|
||||
"""Parse, apply and record one setting; keep ``snapshot`` consistent.
|
||||
"""Parse, apply, and store one setting, and keep ``snapshot`` consistent.
|
||||
|
||||
The local snapshot is updated with the new value so a later coupled change in the
|
||||
same batch (e.g. another radio field) is rebuilt from current values.
|
||||
The local snapshot gets the new value. Thus a later coupled change in the same batch
|
||||
(for example, another radio field) is made again from the current values.
|
||||
|
||||
Returns:
|
||||
The change, as ``{"key", "previous", "value"}``. The *previous* value is read off
|
||||
the snapshot before it is overwritten: a caller managing a machine's configuration
|
||||
wants to know what moved, and it is gone the moment this returns.
|
||||
The change, as ``{"key", "previous", "value"}``. The *previous* value is read from
|
||||
the snapshot before it is overwritten. A caller that manages the settings of a
|
||||
machine wants to know what changed, and the old value is gone when this function
|
||||
returns.
|
||||
"""
|
||||
spec = get_spec(key)
|
||||
value = parse_value(spec, raw, snapshot)
|
||||
previous = spec.getter(snapshot)
|
||||
await spec.apply(device, value, snapshot)
|
||||
snapshot[key] = value
|
||||
# Remember what we set, keyed by the device's own public key, so a forgetful device (a
|
||||
# firmware-less radio bridge) can be offered its settings back on the next connect (see
|
||||
# meshterm.core.settings_store). Provenance-gated: only values changed through MeshTerm.
|
||||
# Keep what we set, keyed by the public key of the device. Thus a device that forgets
|
||||
# (a radio bridge with no firmware) can get its settings back at the next connect (refer
|
||||
# to meshterm.core.settings_store). Only the values that MeshTerm changed are kept.
|
||||
if ctx.settings_store is not None:
|
||||
ctx.settings_store.remember(str(snapshot.get("public_key") or ""), key, value)
|
||||
if key == "flood_scope":
|
||||
@@ -366,21 +371,21 @@ async def _apply_setting(
|
||||
|
||||
|
||||
def learn_default_scope(ctx: AppContext, snapshot: dict) -> None:
|
||||
"""Take in the default flood scope a config read or write has just seen.
|
||||
"""Keep the default flood scope that a settings read or a settings write got.
|
||||
|
||||
Two things want it. The region store learns the name (source ``default``): it is the
|
||||
region this station's own plain floods carry, so it is the first name any of them will
|
||||
be resolved against. And the session cache holds it (``devstate``), since a channel with
|
||||
no scope of its own records its messages as sent under the default, and this saves that
|
||||
record a round trip.
|
||||
Two parts of MeshTerm use it. The region store learns the name (source ``default``).
|
||||
It is the region that the plain floods of our node have, so it is the first name
|
||||
against which any of them is resolved. The session cache (``devstate``) also keeps
|
||||
it, because a channel with no scope of its own stores its messages as sent under the
|
||||
default. Thus that store does not have to do a round trip.
|
||||
|
||||
A snapshot whose read of the default failed (firmware before 1.15) carries no
|
||||
``flood_scope`` key at all, and teaches nothing.
|
||||
A snapshot whose read of the default failed (firmware before 1.15) has no
|
||||
``flood_scope`` key, and gives nothing to learn.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
snapshot: A :func:`~meshterm.core.device_config.build_snapshot` result, or one an
|
||||
apply has just updated.
|
||||
ctx: The shared application context.
|
||||
snapshot: A :func:`~meshterm.core.device_config.build_snapshot` result, or a
|
||||
snapshot that an apply has changed.
|
||||
"""
|
||||
if "flood_scope" not in snapshot:
|
||||
return
|
||||
@@ -396,17 +401,17 @@ def learn_default_scope(ctx: AppContext, snapshot: dict) -> None:
|
||||
|
||||
|
||||
async def _show(ctx: AppContext, device: Device, snapshot: dict) -> Listing | None:
|
||||
"""Print every current setting, plus any custom variables.
|
||||
"""Print each current setting, and the custom variables, if there are any.
|
||||
|
||||
The menu shows the annotated table; a scripted run gets one ``key value`` line per
|
||||
setting, keyed exactly as ``config get`` and ``config set`` name them, so a line read
|
||||
out of ``show`` can be typed straight back in. The labels and descriptions the table
|
||||
carries are for a reader choosing a setting, and this reader has already chosen.
|
||||
The menu shows the table with notes. A scripted run gets one ``key value`` line for
|
||||
each setting, with the key exactly as ``config get`` and ``config set`` name it. Thus
|
||||
a line from ``show`` can be typed back in directly. The labels and descriptions in the
|
||||
table help a user who selects a setting, but this user already selected.
|
||||
|
||||
The pairing PIN stays concealed here, as it is in the table: this is the whole-device
|
||||
dump, the thing that gets redirected into a file and pasted into a bug report, and the
|
||||
PIN is the one value on it that lets someone else's phone onto the radio.
|
||||
``config get device_pin`` names it deliberately.
|
||||
The pairing PIN stays hidden here, as it is in the table. This is the dump of the full
|
||||
device: a person redirects it into a file and pastes it into a bug report. The PIN is
|
||||
the one value in it that lets the phone of another person connect to the radio.
|
||||
``config get device_pin`` names it on purpose.
|
||||
"""
|
||||
from ..ui import fields, script
|
||||
from ..ui.config_editor import PIN_KEY, conceal, config_table
|
||||
@@ -428,17 +433,17 @@ async def _show(ctx: AppContext, device: Device, snapshot: dict) -> Listing | No
|
||||
rows.append(
|
||||
{
|
||||
"key": spec.key,
|
||||
# A masked PIN is *withheld*, which is not a value: the document says
|
||||
# so with `redacted` and writes `null`, rather than shipping six
|
||||
# bullets a consumer would have to recognise as a mask.
|
||||
# A masked PIN is *withheld*, and that is not a value. The document says
|
||||
# so with `redacted` and writes `null`. It does not send six bullets
|
||||
# that a consumer must recognize as a mask.
|
||||
"value": fields.Rendered(None if redacted else value, masked),
|
||||
"type": spec.value_type,
|
||||
"label": (spec.choices or {}).get(value) if spec.value_type == "enum" else None,
|
||||
"redacted": redacted,
|
||||
}
|
||||
)
|
||||
# Custom variables are experimental firmware fields with no spec, so they are namespaced
|
||||
# rather than mixed in — a reader can tell which lines `config set` will take.
|
||||
# Custom variables are experimental firmware fields with no spec. Thus they have their
|
||||
# own namespace, and are not mixed in. A user can tell which lines `config set` accepts.
|
||||
rows.extend(
|
||||
{
|
||||
"key": f"custom.{key}",
|
||||
@@ -453,26 +458,27 @@ async def _show(ctx: AppContext, device: Device, snapshot: dict) -> Listing | No
|
||||
key="settings",
|
||||
columns=_setting_columns(),
|
||||
rows=rows,
|
||||
# An array to a parser and a `sysctl -a` block to a reader: a header line over two
|
||||
# columns whose keys *are* the answer would be furniture.
|
||||
# An array for a parser, and a `sysctl -a` block for a person. A header line above
|
||||
# two columns whose keys *are* the answer adds nothing.
|
||||
headed=False,
|
||||
)
|
||||
|
||||
|
||||
def _script_value(spec: SettingSpec, value: Any) -> str:
|
||||
"""A setting's value in the form ``config set`` accepts back.
|
||||
"""The value of a setting, in the form that ``config set`` accepts back.
|
||||
|
||||
:func:`~meshterm.core.device_config.format_value` writes for a reader choosing a
|
||||
setting: an enum reads ``0 (off)``, an unset string reads ``(not set)``, an unreported
|
||||
one reads ``?``. None of those three survive a round trip —
|
||||
:func:`~meshterm.core.device_config.parse_value` wants a bare integer for an enum, and
|
||||
would take the words ``(not set)`` as the literal value of a string. So the scripted
|
||||
dump prints what can be typed back: the enum's number, the empty string as ``""``, and
|
||||
:data:`~meshterm.ui.script.NONE` for a value the firmware never reported (which is an
|
||||
absence, not a value, and is the one line ``config set`` should not be handed back).
|
||||
:func:`~meshterm.core.device_config.format_value` writes for a user who selects a
|
||||
setting. An enum shows as ``0 (off)``, a string with no value shows as ``(not set)``,
|
||||
and a value that the device did not report shows as ``?``. None of those three can go
|
||||
in and come back out unchanged. :func:`~meshterm.core.device_config.parse_value` must
|
||||
have a bare integer for an enum, and takes the words ``(not set)`` as the literal value
|
||||
of a string. Thus the scripted dump prints what can be typed back: the number of the
|
||||
enum, the empty string as ``""``, and :data:`~meshterm.ui.script.NONE` for a value
|
||||
that the firmware never reported. That last one is an absence, not a value, and it is
|
||||
the one line that must not go back to ``config set``.
|
||||
|
||||
Args:
|
||||
spec: The setting the value belongs to.
|
||||
spec: The setting of the value.
|
||||
value: Its current value, or ``None`` when the device did not report it.
|
||||
|
||||
Returns:
|
||||
@@ -490,13 +496,13 @@ def _script_value(spec: SettingSpec, value: Any) -> str:
|
||||
|
||||
|
||||
async def _share_contact(ctx: AppContext, snapshot: dict) -> Facts:
|
||||
"""State this node's contact card — with the QR code drawn in the menu, full-frame.
|
||||
"""State the contact card of this node, with the QR code drawn on the full frame in the menu.
|
||||
|
||||
The QR is for a phone pointed at the screen, and there it takes the whole screen
|
||||
(:func:`~meshterm.ui.qr.share_screen`). Redirected into a file it is a block of
|
||||
block characters around the one thing that is the answer, so a scripted run states the
|
||||
link by itself. There is no machine face for the code either, and never will be: it is
|
||||
a second rendering of ``url``.
|
||||
The QR code is for a phone that points at the screen, and there it fills the screen
|
||||
(:func:`~meshterm.ui.qr.share_screen`). In a redirected file, it is a block of block
|
||||
characters around the one thing that is the answer. Thus a scripted run states only
|
||||
the link. There is also no machine face for the code, and there never will be one,
|
||||
because it is a second rendering of ``url``.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.config_editor import contact_share_url
|
||||
@@ -527,11 +533,12 @@ async def _share_contact(ctx: AppContext, snapshot: dict) -> Facts:
|
||||
|
||||
|
||||
async def _backup(device: Device, snapshot: dict, path: Path) -> tuple[Path, dict[str, int]]:
|
||||
"""Write a TOML backup of the current configuration.
|
||||
"""Write a TOML backup of the current settings.
|
||||
|
||||
Returns:
|
||||
The path written and how much went into it, counted the way the file counts —
|
||||
a setting the firmware never reported is not in the backup and is not in the tally.
|
||||
The path of the written file, and how much went into it, counted in the same way
|
||||
as the file counts. A setting that the firmware never reported is not in the
|
||||
backup, and is not in the count.
|
||||
"""
|
||||
from ..core.device_config import DEVICE_SETTINGS
|
||||
|
||||
@@ -549,15 +556,16 @@ async def _backup(device: Device, snapshot: dict, path: Path) -> tuple[Path, dic
|
||||
async def _restore(
|
||||
ctx: AppContext, device: Device, snapshot: dict, path: Path, dry_run: bool
|
||||
) -> tuple[int, list[Block]]:
|
||||
"""Apply (or preview) a backup file against the current configuration.
|
||||
"""Apply (or preview) a backup file over the current settings.
|
||||
|
||||
The plan is the answer on a dry run and a record on a real one, so the same listing
|
||||
serves both — drawn for a reader only when nothing was changed, since a run that *did*
|
||||
change things already said so, setting by setting, on stderr.
|
||||
On a dry run, the plan is the answer. On a real run, it is a record. Thus the same
|
||||
listing is for the two runs. It is drawn for a person only when nothing changed,
|
||||
because a run that *did* change settings already said so on stderr, one setting at a
|
||||
time.
|
||||
|
||||
Returns:
|
||||
The number of changes applied (always ``0`` for a dry run), and the blocks stating
|
||||
what was planned or done.
|
||||
The number of applied changes (always ``0`` for a dry run), and the blocks that
|
||||
state what was planned or done.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Facts, Listing
|
||||
@@ -617,16 +625,16 @@ async def _restore(
|
||||
async def _export_key(
|
||||
ctx: AppContext, device: Device, out: Path | None, artifacts: list[str]
|
||||
) -> Facts:
|
||||
"""Export the private key, to a file if ``out`` is given, else as the answer itself.
|
||||
"""Export the private key: to a file if ``out`` is given, or else as the answer itself.
|
||||
|
||||
Either way the plain face prints **one bare line** — the key, or the path it was
|
||||
written to — because ``config export-key > key.hex`` is expected to hold the key and
|
||||
nothing else, and a caller that asked for a file wants the name of it. The warning
|
||||
that comes with either belongs beside it on screen, not in the file, so it goes to
|
||||
stderr with every other acknowledgement.
|
||||
In the two cases, the plain face prints **one bare line**: the key, or the path of the
|
||||
file that holds it. The reason: ``config export-key > key.hex`` must hold the key and
|
||||
nothing else, and a caller that asked for a file wants its name. The warning that
|
||||
comes with each of them must be next to it on the screen, not in the file. Thus it
|
||||
goes to stderr with all the other acknowledgements.
|
||||
|
||||
This document carries a private key when one was asked for. That is what the command
|
||||
is, exactly as on the plain face, and no extra gate is introduced here.
|
||||
This document holds a private key when the caller asked for one. That is the purpose
|
||||
of the command, the same as on the plain face, and this function adds no more gate.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import BARE, Facts
|
||||
@@ -654,12 +662,12 @@ async def _export_key(
|
||||
|
||||
|
||||
async def _read_channels(device: Device) -> list[dict]:
|
||||
"""Probe channel slots and return the configured ones."""
|
||||
"""Probe the channel slots, and return the configured slots."""
|
||||
channels: list[dict] = []
|
||||
for idx in range(CHANNEL_SLOT_PROBE_CAP):
|
||||
try:
|
||||
ch = await device.get_channel(idx)
|
||||
except Exception: # noqa: BLE001 - firmware may not support channel reads
|
||||
except Exception: # noqa: BLE001 - the firmware may not support channel reads
|
||||
break
|
||||
if ch:
|
||||
channels.append(ch)
|
||||
@@ -667,27 +675,27 @@ async def _read_channels(device: Device) -> list[dict]:
|
||||
|
||||
|
||||
def _require_yes(yes: bool, what: str) -> None:
|
||||
"""Abort a destructive CLI command unless ``--yes`` was passed.
|
||||
"""Stop a destructive CLI command, unless the user gave ``--yes``.
|
||||
|
||||
Raised as a :class:`typer.BadParameter` rather than printed and exited: a missing
|
||||
confirmation *is* a usage error, so it belongs on stderr in the parser's own words and
|
||||
under the parser's own status (see :mod:`meshterm.core.exitcodes`). Printing it in red
|
||||
on stdout put a colour, and a sentence that is not the command's answer, into whatever
|
||||
was reading the command's answer.
|
||||
This function raises a :class:`typer.BadParameter`, and does not print and exit. A
|
||||
missing confirmation *is* a usage error. Thus it must go to stderr, in the words of the
|
||||
parser, and with the status of the parser (refer to :mod:`meshterm.core.exitcodes`).
|
||||
Before, the function printed it in red on stdout. That put a colour, and a sentence
|
||||
that is not the answer of the command, into the program that read the answer.
|
||||
|
||||
Args:
|
||||
yes: Whether the user passed ``--yes``.
|
||||
what: Human-readable description of the consequence.
|
||||
yes: Whether the user gave ``--yes``.
|
||||
what: A description of the result, for a person.
|
||||
|
||||
Raises:
|
||||
typer.BadParameter: If confirmation was not given.
|
||||
typer.BadParameter: If the user did not confirm.
|
||||
"""
|
||||
if not yes:
|
||||
raise typer.BadParameter(f"{what}. Re-run with --yes to confirm.")
|
||||
|
||||
|
||||
def _setting_columns() -> tuple:
|
||||
"""One setting row's columns, shared by ``config show`` and ``config get``."""
|
||||
"""The columns of one setting row, shared by ``config show`` and ``config get``."""
|
||||
from ..ui import fields
|
||||
|
||||
return (
|
||||
@@ -700,11 +708,11 @@ def _setting_columns() -> tuple:
|
||||
|
||||
|
||||
def _one_setting(spec: SettingSpec, value: Any) -> Facts:
|
||||
"""One setting: the bare value plain, the whole object in the document.
|
||||
"""One setting: the bare value on the plain face, and the full object in the document.
|
||||
|
||||
``config get device_pin`` is the one place the PIN is named deliberately, so it is
|
||||
**not** redacted here — the caller asked for that key by name, which is a different
|
||||
act from dumping every setting into a file.
|
||||
``config get device_pin`` is the one place where the caller names the PIN on purpose.
|
||||
Thus it is **not** redacted here. The caller asked for that key by name, and that is a
|
||||
different act from a dump of all the settings into a file.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import BARE, Facts
|
||||
@@ -725,10 +733,10 @@ def _one_setting(spec: SettingSpec, value: Any) -> Facts:
|
||||
|
||||
|
||||
def _applied(applied: list[dict[str, Any]]) -> Facts:
|
||||
"""What a ``set`` changed — nothing plain, a record for whoever is logging it.
|
||||
"""What a ``set`` changed: nothing on the plain face, and a record for a program that logs it.
|
||||
|
||||
The exit status is the plain answer and the acknowledgement on stderr is the reassurance;
|
||||
neither is something a script can read back later to find out *what moved*.
|
||||
The exit status is the plain answer, and the acknowledgement on stderr tells the user
|
||||
that all is well. A script cannot read either of them later to find *what changed*.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Column, Facts
|
||||
@@ -766,10 +774,10 @@ def _channel_written(idx: int, name: str, secret: bytes | None) -> Facts:
|
||||
|
||||
|
||||
def _backed_up(written: Path, counts: dict[str, int]) -> Facts:
|
||||
"""What ``config backup`` wrote, and how much of it.
|
||||
"""What ``config backup`` wrote, and how much.
|
||||
|
||||
The plain face prints the path bare — it is what the caller keeps, and what the thing
|
||||
that ran the command reads next.
|
||||
The plain face prints only the path. The caller keeps the path, and the program that
|
||||
ran the command reads it next.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import BARE, Facts
|
||||
@@ -789,11 +797,12 @@ def _backed_up(written: Path, counts: dict[str, int]) -> Facts:
|
||||
|
||||
|
||||
def _acted(key: str, **facts: Any) -> Facts:
|
||||
"""An action, stated as data: nothing plain, a document for whoever wanted a record.
|
||||
"""An action, stated as data: nothing on the plain face, and a document for a record.
|
||||
|
||||
Every one of these prints nothing on the plain face today and should keep doing so —
|
||||
``config advert`` says all it has to say in its exit status. But "prints nothing" is an
|
||||
answer a person can act on and a program cannot, so the machine face gets the fact.
|
||||
Each of these actions prints nothing on the plain face now, and must continue to print
|
||||
nothing. ``config advert`` says all that it has to say in its exit status. But "prints
|
||||
nothing" is an answer on which a person can act, and a program cannot. Thus the
|
||||
machine face gets the fact.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Column, Facts
|
||||
|
||||
+48
-43
@@ -1,9 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``contacts`` tool: list the contacts this node knows about.
|
||||
"""The ``contacts`` tool: list the contacts that this node knows.
|
||||
|
||||
The menu opens the sortable Contacts screen, which leads with our own node; the CLI
|
||||
prints the contact list alone, because our own node is not a contact — ``meshterm info``
|
||||
reports it, in far more detail than a row could hold.
|
||||
The menu opens the Contacts screen, which you can sort and which starts with our node.
|
||||
The CLI prints only the contact list, because our node is not a contact.
|
||||
``meshterm info`` reports our node, with much more detail than a row can hold.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,58 +24,61 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class ContactsTool(Tool):
|
||||
"""List this node and its known contacts, each with its path-hash prefix."""
|
||||
"""List this node and its known contacts, each with its hash."""
|
||||
|
||||
name = "contacts"
|
||||
title = "Contacts"
|
||||
icon = "👥"
|
||||
help = "Known contacts — last heard, packets, type"
|
||||
category = "Message"
|
||||
order = 40 # the address book the three above pick their recipient from
|
||||
order = 40 # the address book from which the three tools above select a recipient
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Query the device and render the contacts list.
|
||||
"""Query the device and render the contact list.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing the number of known contacts.
|
||||
A :class:`ToolResult` with a summary of the number of known contacts.
|
||||
"""
|
||||
from ..ui.surface import TuiUi
|
||||
from ..ui.widgets import ContactsSort, ordered_contacts
|
||||
|
||||
# Read through the session cache: on a busy node the contacts table is a slow
|
||||
# round-trip, and re-fetching it (plus self-info) on every menu visit is a chief cause
|
||||
# of sluggish navigation. The cache holds them for the session and refreshes contacts
|
||||
# in the background (see :class:`~meshterm.services.device_state.DeviceState`).
|
||||
# Read through the session cache. On a busy node, the contacts table is a slow
|
||||
# round trip. If MeshTerm reads it again (and the self info) at each visit to the
|
||||
# menu, that is a main cause of slow navigation. The cache keeps them for the session
|
||||
# and reads the contacts again in the background (refer to
|
||||
# :class:`~meshterm.services.device_state.DeviceState`).
|
||||
info = await ctx.devstate.self_info()
|
||||
contacts = await ctx.devstate.contacts()
|
||||
|
||||
# The path-hash prefix — the leading slice of a key a forced path addresses — is
|
||||
# ``mode + 1`` bytes wide; highlight it in every key. The mode is an optional read,
|
||||
# so fall back to no highlighting when the firmware doesn't report it.
|
||||
# The hash (the first part of a key, which a forced path uses as the address) is
|
||||
# ``mode + 1`` bytes wide. Light it in each key. The mode is an optional read. Thus
|
||||
# if the firmware does not report it, light nothing.
|
||||
try:
|
||||
mode = await ctx.devstate.path_hash_mode()
|
||||
except Exception: # noqa: BLE001 - optional read; absence just skips highlighting
|
||||
except Exception: # noqa: BLE001 - an optional read. If it is absent, nothing is lit.
|
||||
mode = None
|
||||
prefix_bytes = (mode + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0
|
||||
|
||||
# Overheard-packet tallies from background monitoring, keyed by node hash; a
|
||||
# contact we've never passively overheard simply has no entry.
|
||||
# The counts of overheard packets from the background monitor, keyed by node hash.
|
||||
# A contact that we never overheard passively has no entry.
|
||||
counts = {n.node: n.count for n in ctx.repo.heard_nodes() if n.node}
|
||||
|
||||
self_name = str(info.get("name") or "this node")
|
||||
self_key = str(info.get("public_key") or "")
|
||||
# Opens most-recently-heard first: the list's job is "who's out there right now",
|
||||
# and a freshest-first order answers that on sight — an A→Z roll call doesn't. The
|
||||
# Ctrl+arrows re-sort from there (and ``--sort`` picks the CLI's order).
|
||||
# The list opens with the most recently heard node first. The list must answer "who
|
||||
# is out there now", and an order with the newest first answers that immediately.
|
||||
# A list from A to Z does not. Then the Ctrl+arrows sort the list again (and
|
||||
# ``--sort`` sets the order of the CLI).
|
||||
sort_name = str(params.get("sort") or "heard")
|
||||
|
||||
# In the menu, hand the list to the interactive screen so the Ctrl+arrows re-sort it
|
||||
# live — its ring spans the shared contact list's four columns (hash included); on the
|
||||
# scripted CLI, print the plain listing once in the requested order.
|
||||
# In the menu, give the list to the interactive screen, so that the Ctrl+arrows sort
|
||||
# it again while it is open. Their ring goes through the four columns of the shared
|
||||
# contact list (also the hash). On the scripted CLI, print the plain listing one
|
||||
# time, in the requested order.
|
||||
if isinstance(ctx.ui, TuiUi):
|
||||
from ..ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING
|
||||
from ..ui.contacts_screen import open_contacts
|
||||
@@ -107,10 +110,10 @@ class ContactsTool(Tool):
|
||||
"heard", "--sort", "-s", help="Order contacts by: heard, name, packets"
|
||||
),
|
||||
) -> None:
|
||||
# `ContactsSort.from_name` falls back to the first column for an unknown name,
|
||||
# deliberately, so a saved preference written by an older build cannot wedge
|
||||
# the menu's list. On the command line the same silence hides a typo: the
|
||||
# caller asked for one order and got another, with nothing said.
|
||||
# For an unknown name, `ContactsSort.from_name` uses the first column. This is
|
||||
# on purpose, so that a saved preference from an older build cannot block the
|
||||
# list of the menu. On the command line, the same silence hides a typing error:
|
||||
# the caller asked for one order and got another, and nothing said so.
|
||||
if sort not in ContactsSort.names():
|
||||
choices = ", ".join(ContactsSort.names())
|
||||
raise typer.BadParameter(f"--sort must be one of: {choices} (got {sort!r})")
|
||||
@@ -118,21 +121,23 @@ class ContactsTool(Tool):
|
||||
|
||||
|
||||
def _listing(contacts: list[Contact], counts: dict[str, int], prefix_bytes: int) -> Listing:
|
||||
"""The contact list, stated once for both faces.
|
||||
"""The contact list, stated one time for the two faces.
|
||||
|
||||
``TYPE`` is the node's advertised role in words, where the menu draws a coloured glyph:
|
||||
a monochrome ``▲`` would need a legend and the CLI has no legends. ``HEARD`` is a
|
||||
relative age, because "recently?" is the question this listing is opened to answer.
|
||||
``HASH`` is the token ``--path`` and ``--to`` take — it used to have to be sliced out
|
||||
of ``KEY`` by hand — and ``LOCATION`` is a fact the model has always carried and no
|
||||
column had room for. ``KEY`` stays full and last, so it runs off the right harmlessly
|
||||
and is never elided: a truncated key is not something a caller can hand back.
|
||||
``TYPE`` is the advertised role of the node, in words. The menu draws a coloured glyph
|
||||
there, but a monochrome ``▲`` must have a legend, and the CLI has no legends.
|
||||
``HEARD`` is a relative age, because the user opens this listing to ask "recently?".
|
||||
``HASH`` is the token that ``--path`` and ``--to`` accept. Before, the user had to cut
|
||||
it out of ``KEY`` by hand. ``LOCATION`` is a fact that the model always had, but no
|
||||
column had space for it. ``KEY`` stays full and last. Thus it goes off the right side
|
||||
with no harm and is never cut: a caller cannot give a truncated key back to a command.
|
||||
|
||||
Args:
|
||||
contacts: The contacts, already in the requested order.
|
||||
counts: Overheard-packet tallies keyed by node id (from passive monitoring).
|
||||
prefix_bytes: The device's path-hash width, which is what makes ``HASH`` the
|
||||
token a forced path addresses this node by rather than an arbitrary slice.
|
||||
counts: The counts of overheard packets, keyed by node id (from the passive
|
||||
monitor).
|
||||
prefix_bytes: The path hash width of the device. Because of it, ``HASH`` is the
|
||||
token by which a forced path addresses this node, not a random part of the
|
||||
key.
|
||||
|
||||
Returns:
|
||||
The listing.
|
||||
@@ -171,7 +176,7 @@ def _listing(contacts: list[Contact], counts: dict[str, int], prefix_bytes: int)
|
||||
fields.position(),
|
||||
),
|
||||
rows=rows,
|
||||
# The node's four lanes are not contiguous: what a reader scans for — who, what,
|
||||
# how recently, how much — comes first, and the two long hex fields go right.
|
||||
# The four lanes of the node are not together. What the user looks for (who, what,
|
||||
# how recently, how much) comes first, and the two long hex fields go to the right.
|
||||
order=("NAME", "TYPE", "HEARD", "PKTS", "HASH", "LOCATION", "KEY"),
|
||||
)
|
||||
+75
-67
@@ -1,19 +1,24 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``courier`` tool: store-and-forward messaging for contacts that aren't there yet.
|
||||
"""The ``courier`` tool: store-and-forward messages for contacts that MeshTerm cannot reach yet.
|
||||
|
||||
Interactively it opens the outbox screen (see :mod:`meshterm.ui.courier_screen`):
|
||||
queued messages with their live state, the queueing flow (recipient → message →
|
||||
when), forced sends, and the delivered/given-up history. Delivery runs in the
|
||||
background for the whole session (see :mod:`meshterm.services.courier`): a queued
|
||||
message goes out when its contact is next heard — or at its scheduled time — as a normal
|
||||
direct message with acknowledgement tracking and polite exponential backoff, and the
|
||||
outcome lights the header's Watchtower badge.
|
||||
In the menu, the tool opens the outbox screen (refer to :mod:`meshterm.ui.courier_screen`).
|
||||
The screen shows the queued messages with their live state, the flow to queue a message
|
||||
(recipient → message → when), forced sends, and the history of the messages that were
|
||||
delivered or that the courier gave up. Delivery runs in the background for the whole
|
||||
session (refer to :mod:`meshterm.services.courier`). A queued message goes out when
|
||||
MeshTerm next hears its contact, or at its scheduled time. It goes as a normal direct
|
||||
message, with acknowledgement tracking and a polite exponential backoff. The result lights
|
||||
the Watchtower badge in the header.
|
||||
|
||||
On the CLI the same outbox is scriptable through subcommands: ``queue`` adds a message
|
||||
(reading the contact list to address it — nothing is transmitted) for the next
|
||||
interactive session's courier to deliver, ``send`` forces one delivery attempt right now,
|
||||
and ``list`` / ``cancel`` / ``clear`` inspect and prune the outbox — the scriptable face
|
||||
of the outbox screen's own Send-now, Cancel, and Clear-finished actions.
|
||||
On the CLI, subcommands give script access to the same outbox:
|
||||
|
||||
- ``queue`` adds a message for the courier of the next interactive session to deliver. It
|
||||
reads the contact list to address the message, but it transmits nothing.
|
||||
- ``send`` forces one delivery try now.
|
||||
- ``list``, ``cancel``, and ``clear`` examine the outbox and remove entries from it.
|
||||
|
||||
These subcommands are the script form of the Send-now, Cancel, and Clear-finished actions
|
||||
of the outbox screen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -33,24 +38,24 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class CourierTool(Tool):
|
||||
"""Queue messages for offline contacts; they go out when the contact is next heard."""
|
||||
"""Queue messages for offline contacts. A message goes out when its contact is next heard."""
|
||||
|
||||
name = "courier"
|
||||
title = "Courier"
|
||||
icon = "📨"
|
||||
help = "Outbox that delivers when a contact is heard"
|
||||
category = "Message"
|
||||
order = 30 # after Chat and Channels: the same conversations, minus the waiting around
|
||||
order = 30 # after Chat and Channels: the same conversations, but without the wait
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the outbox screen; there are never parameters to collect.
|
||||
"""Run the outbox screen. It has no parameters to collect.
|
||||
|
||||
The screen presents everything itself and returns when dismissed, so
|
||||
returning ``None`` tells the menu the invocation is complete (the same
|
||||
The screen shows all its content itself, and it returns when the user leaves it.
|
||||
Thus the return value ``None`` tells the menu that the run is complete (the same
|
||||
pattern as the ``dashboard`` tool).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -61,14 +66,14 @@ class CourierTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Dispatch a scripted CLI action (the menu path lives in :meth:`prompt_params`).
|
||||
"""Run the handler for a scripted CLI action (the menu path is :meth:`prompt_params`).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: A ``cli_action`` naming the outbox action, plus its arguments.
|
||||
ctx: The shared application context.
|
||||
params: A ``cli_action`` that names the outbox action, and its arguments.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` describing the action's outcome.
|
||||
A :class:`ToolResult` that gives the result of the action.
|
||||
"""
|
||||
action = params.get("cli_action", "queue")
|
||||
if action == "list":
|
||||
@@ -84,15 +89,15 @@ class CourierTool(Tool):
|
||||
# -- CLI --------------------------------------------------------------------
|
||||
|
||||
async def _cli_queue(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Queue one message from the CLI (transmits nothing).
|
||||
"""Queue one message from the CLI. This transmits nothing.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``contact`` (contact name), ``text`` (the message body), and an
|
||||
optional local ``at`` clock time (``HH:MM``, next occurrence).
|
||||
ctx: The shared application context.
|
||||
params: ``contact`` (the contact name), ``text`` (the message body), and an
|
||||
optional local clock time ``at`` (``HH:MM``, the next occurrence).
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` describing the queued entry.
|
||||
A :class:`ToolResult` that describes the queued entry.
|
||||
"""
|
||||
from ..ui.courier_screen import parse_clock
|
||||
from ..ui.watchtower_screen import contact_watch_key
|
||||
@@ -102,8 +107,8 @@ class CourierTool(Tool):
|
||||
name = str(params["contact"])
|
||||
needle = name.casefold()
|
||||
contact = next((c for c in contacts if c.name.casefold() == needle), None)
|
||||
# The named contact, not the radio: nothing is queued and nothing is sent, so
|
||||
# these are bad arguments (2) rather than device failures (4).
|
||||
# The problem is the named contact, not the device. Nothing is queued and nothing
|
||||
# is sent, so these are bad arguments (2) instead of device failures (4).
|
||||
if contact is None:
|
||||
raise typer.BadParameter(f"unknown contact: {name!r}")
|
||||
key = contact_watch_key(contact)
|
||||
@@ -135,10 +140,11 @@ class CourierTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_list(self, ctx: AppContext) -> ToolResult:
|
||||
"""State the outbox — waiting entries then finished ones.
|
||||
"""Give the outbox: first the waiting entries, then the finished entries.
|
||||
|
||||
A read-only view over the stored outbox: it needs no device, so it works the same
|
||||
whether or not a radio is attached (the scriptable face of the outbox screen).
|
||||
This is a read-only listing of the stored outbox. It does not use the device, so it
|
||||
works the same when a device is connected and when it is not. It is the script
|
||||
form of the outbox screen.
|
||||
"""
|
||||
entries = ctx.courier_store.entries()
|
||||
return ToolResult(
|
||||
@@ -148,16 +154,17 @@ class CourierTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_send(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Force one delivery attempt for a waiting entry, right now.
|
||||
"""Try one forced delivery of a waiting entry, now.
|
||||
|
||||
The scriptable ``Send now`` — one forced attempt through the same courier the
|
||||
outbox screen uses, skipping the "wait until the contact is heard" eligibility check.
|
||||
This is the script form of ``Send now``. It tries one forced delivery through the
|
||||
same courier that the outbox screen uses. It does not do the eligibility check
|
||||
("wait until the contact is heard").
|
||||
"""
|
||||
ident = int(params["id"])
|
||||
if ctx.courier_store.get(ident) is None:
|
||||
# A bad argument, not a device failure: the outbox is a local file, nothing was
|
||||
# transmitted, and no retry will make an id exist. Exit 4 told a caller to try
|
||||
# again; exit 2 tells it to fix the command, which is the truth.
|
||||
# A bad argument, not a device failure. The outbox is a local file, nothing was
|
||||
# transmitted, and no retry can make an id exist. Exit 4 told a caller to try
|
||||
# again. Exit 2 tells it to correct the command, and that is the true answer.
|
||||
raise typer.BadParameter(f"no outbox entry #{ident} (see `courier list`)")
|
||||
outcome = await ctx.courier.attempt_now(ident)
|
||||
notes = {
|
||||
@@ -177,7 +184,7 @@ class CourierTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_cancel(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Remove a waiting entry from the outbox (finished ones use ``clear``)."""
|
||||
"""Remove a waiting entry from the outbox (for a finished entry, use ``clear``)."""
|
||||
ident = int(params["id"])
|
||||
if ctx.courier_store.cancel(ident):
|
||||
ctx.ui.ack(f"[warn]cancelled outbox entry #{ident}[/warn]")
|
||||
@@ -193,7 +200,7 @@ class CourierTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_clear(self, ctx: AppContext) -> ToolResult:
|
||||
"""Drop every finished (delivered / given-up) entry, leaving the queue untouched."""
|
||||
"""Remove each finished entry (delivered or given up), and keep the queue as it is."""
|
||||
before = len(ctx.courier_store.entries())
|
||||
ctx.courier_store.clear_done()
|
||||
cleared = before - len(ctx.courier_store.entries())
|
||||
@@ -260,12 +267,13 @@ class CourierTool(Tool):
|
||||
|
||||
|
||||
def _recipient(name: str | None, node_key: str | None) -> object:
|
||||
"""The outbox's addressee as the shared node shape.
|
||||
"""The addressee of the outbox entry, as the shared node shape.
|
||||
|
||||
The outbox stores a name and the 12-hex id it addresses, so three of the five fields
|
||||
are honestly ``null`` — and the id goes in ``hash`` rather than ``key``, because that
|
||||
is what it is. A key is the full value and is never truncated by this app's choosing;
|
||||
calling a six-byte prefix one would hand a caller something ``--to`` cannot take.
|
||||
The outbox stores a name and the key prefix (12 hex digits) that it addresses. Thus
|
||||
three of the five fields are correctly ``null``. The key prefix goes in ``hash``
|
||||
instead of ``key``, because it is a short id, not a full key. A key is the full value,
|
||||
and MeshTerm never truncates a key by its own choice. If MeshTerm calls a six-byte
|
||||
prefix a key, it gives a caller a value that ``--to`` cannot accept.
|
||||
"""
|
||||
from ..ui.fields import NodeRef
|
||||
|
||||
@@ -275,10 +283,10 @@ def _recipient(name: str | None, node_key: str | None) -> object:
|
||||
def _queued(message: QueuedMessage, name: str, not_before: object) -> Facts:
|
||||
"""What ``courier queue`` put in the outbox.
|
||||
|
||||
The plain face prints the **id and nothing else**, because the id is the one fact a
|
||||
caller has to keep — it is what ``send`` and ``cancel`` take — and everything else on
|
||||
the line is what they just typed. The document carries the rest, because a caller
|
||||
logging the queue has no other record of it.
|
||||
The plain face prints **only the id**, because the id is the only fact that a caller
|
||||
must keep: ``send`` and ``cancel`` take it. All the other data on the line is what the
|
||||
caller typed. The document holds the rest, because a caller that logs the queue has no
|
||||
other record of it.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import Facts
|
||||
@@ -301,13 +309,13 @@ def _queued(message: QueuedMessage, name: str, not_before: object) -> Facts:
|
||||
|
||||
|
||||
def _outbox(entries: list) -> Listing:
|
||||
"""The outbox, waiting entries then finished ones.
|
||||
"""The outbox: first the waiting entries, then the finished entries.
|
||||
|
||||
The deliberate asymmetry between the two time columns: ``SCHEDULED`` is an
|
||||
*appointment* the caller set with ``--at``, so it stays a wall-clock instant, and
|
||||
``FINISHED`` is an age, because "how long ago did it go" is what anyone reading a
|
||||
delivered row wants. The mixed widths are the price of both columns being right, and
|
||||
``--absolute`` makes them uniform for anyone who dislikes it.
|
||||
The two time columns are different on purpose. ``SCHEDULED`` is an appointment that
|
||||
the caller set with ``--at``, so it stays a wall-clock instant. ``FINISHED`` is an
|
||||
age, because a person who reads a delivered row wants to know how long ago it went.
|
||||
Thus the two columns have different widths, but both columns are correct.
|
||||
``--absolute`` makes them the same for a person who does not like the difference.
|
||||
"""
|
||||
from ..core.courier_store import DELIVERED, QUEUED
|
||||
from ..ui import fields
|
||||
@@ -326,11 +334,11 @@ def _outbox(entries: list) -> Listing:
|
||||
"id": m.ident,
|
||||
"state": state,
|
||||
"node": _recipient(m.node_name, m.node_key),
|
||||
# An entry with no scheduled time goes as soon as the contact is heard,
|
||||
# which is not a time and so is not one here either.
|
||||
# An entry with no scheduled time goes when the contact is next heard. That
|
||||
# is not a time, so this field has no time either.
|
||||
"scheduled_at": m.not_before,
|
||||
"finished_at": m.finished,
|
||||
# Not shortened the way the outbox screen shortens it: nothing wraps here.
|
||||
# Not shortened as the outbox screen shortens it, because nothing wraps here.
|
||||
"text": m.text,
|
||||
}
|
||||
)
|
||||
@@ -349,11 +357,11 @@ def _outbox(entries: list) -> Listing:
|
||||
|
||||
|
||||
def _attempted(ident: int, outcome: str) -> Facts:
|
||||
"""What one forced delivery attempt came to.
|
||||
"""The result of one forced delivery try.
|
||||
|
||||
``outcome`` is one of the closed set the help lists, kept verbatim — spaces and all —
|
||||
so both faces say the same word and a script matching ``no ack`` matches what a person
|
||||
reads.
|
||||
``outcome`` is one value of the closed set that the help gives. It is kept exactly,
|
||||
with its spaces. Thus both faces show the same word, and a script that matches
|
||||
``no ack`` matches the text that a person reads.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import Facts
|
||||
@@ -366,11 +374,11 @@ def _attempted(ident: int, outcome: str) -> Facts:
|
||||
|
||||
|
||||
def _did(*facts: tuple[str, object]) -> Facts:
|
||||
"""An acknowledgement as data: nothing plain, a document for whoever is logging.
|
||||
"""An acknowledgement as data: nothing on the plain face, and a document for a log.
|
||||
|
||||
``cancel`` and ``clear`` say everything they have to say in their exit status, which
|
||||
is the right plain answer — but a caller that wants to record *what* was cancelled has
|
||||
nowhere to read it, and that is what the document is for.
|
||||
``cancel`` and ``clear`` give all their information in their exit status, and that is
|
||||
the correct plain answer. But a caller that wants to store what was cancelled has no
|
||||
other place to read it. The document is for that caller.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Facts
|
||||
|
||||
+23
-22
@@ -1,16 +1,17 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``dashboard`` tool: the live mesh overview, at the top of the Watch section.
|
||||
"""The ``dashboard`` tool: the live overview of the mesh, at the top of the Watch section.
|
||||
|
||||
Opens the full-screen dashboard (see :mod:`meshterm.ui.dashboard_screen`): the two-hour
|
||||
all-packet activity chart with its pulse line, the session's traffic tallies by packet
|
||||
class, and the window's RF health beside the radio's own live numbers. (The per-packet
|
||||
stream is the Live feed tool, right below.) It leads the Watch section because it answers
|
||||
the section's first question — *what's going on out there?* — before any specific tool
|
||||
is reached for.
|
||||
The tool opens the full-screen dashboard (refer to :mod:`meshterm.ui.dashboard_screen`).
|
||||
It shows the activity chart of all packets for two hours with its pulse line, the traffic
|
||||
counts of the session for each packet class, and the RF health of the window next to the
|
||||
live numbers of the radio itself. (The stream of each packet is the Live feed tool,
|
||||
directly below.) The dashboard is first in the Watch section, because it answers the
|
||||
first question of the section (what occurs on the mesh now?) before the user goes to a
|
||||
specific tool.
|
||||
|
||||
Menu-only: the dashboard is inherently live (it rides the event hub and repaints every
|
||||
second), so there is no scripted one-shot to register — the ``monitor`` and ``contacts``
|
||||
subcommands cover scripted inspection.
|
||||
Menu only: the dashboard is always live (it uses the event hub and paints again each
|
||||
second). Thus there is no scripted one-shot command to register. The ``monitor`` and
|
||||
``contacts`` subcommands are the script commands to examine the mesh.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,24 +26,24 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
@register
|
||||
class DashboardTool(Tool):
|
||||
"""Watch everything going on on the mesh: activity, traffic, RF health."""
|
||||
"""Watch all that occurs on the mesh: activity, traffic, RF health."""
|
||||
|
||||
name = "dashboard"
|
||||
title = "Dashboard"
|
||||
icon = "📊"
|
||||
help = "The mesh live — activity, traffic, RF health"
|
||||
category = "Watch"
|
||||
order = 10 # the section's overview, above the tools it summarizes
|
||||
order = 10 # the overview of the section, above the tools that it summarizes
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the live dashboard; there are never parameters to collect.
|
||||
"""Run the live dashboard. It has no parameters to collect.
|
||||
|
||||
The screen presents everything itself and returns when dismissed, so
|
||||
returning ``None`` tells the menu the invocation is complete (the same
|
||||
The screen shows all its content itself, and it returns when the user leaves it.
|
||||
Thus the return value ``None`` tells the menu that the run is complete (the same
|
||||
pattern as the ``advert`` tool).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -53,20 +54,20 @@ class DashboardTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Nothing runs here: the dashboard lives inside :meth:`prompt_params`.
|
||||
"""Nothing runs here: the dashboard is in :meth:`prompt_params`.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
An empty :class:`ToolResult` (only reachable from a scripted call).
|
||||
An empty :class:`ToolResult` (only a scripted call comes here).
|
||||
"""
|
||||
return ToolResult(summary={})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — the dashboard is a live, menu-only screen.
|
||||
"""Register no CLI command, because the dashboard is a live screen for the menu only.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
+66
-56
@@ -1,13 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``devices`` tool: enumerate attached serial, SPI, and in-range Bluetooth companions.
|
||||
"""The ``devices`` tool: list the connected serial, SPI, and in-range Bluetooth companions.
|
||||
|
||||
Discovery never opens the radio — it only lists what is attached or advertising. This is a
|
||||
CLI-only, read-only inventory (``menu_visible = False``): by the time the interactive menu is
|
||||
up a device is already selected, so the listing has no job there — it belongs on the command
|
||||
line as a startup-time "which port/address is my radio?" diagnostic. It marks devices already
|
||||
confirmed as MeshCore companions (and the active one). Selecting a companion is a startup-only
|
||||
concern: pass ``--port`` or ``--ble`` on the CLI (remembered after it connects), or pick from
|
||||
the prompt shown when the menu launches (which smoke-tests the choice before confirming it).
|
||||
Discovery never opens the device. It only lists the devices that are connected or that
|
||||
send a BLE advertisement. This tool is a read-only inventory, for the CLI only
|
||||
(``menu_visible = False``). When the interactive menu opens, a device is already selected,
|
||||
so the listing has no purpose there. It is a diagnostic on the command line at startup,
|
||||
for the question "which port/address is my radio?". It marks the devices that MeshTerm
|
||||
already confirmed as MeshCore companions, and it marks the active device. The user selects
|
||||
a companion only at startup. Give ``--port`` or ``--ble`` on the CLI (MeshTerm remembers
|
||||
it after it connects), or select from the prompt that shows when the menu starts. That
|
||||
prompt does a smoke test of the selection before it confirms it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,16 +34,16 @@ from .base import Tool, ToolResult, register
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from ..ui.report import Listing
|
||||
|
||||
#: The ``MESHCORE`` verdict per discovery confidence tier, for devices we have *not* yet
|
||||
#: confirmed. The USB vendor ID is only a hint — a native-USB board or a bare bridge chip
|
||||
#: is a "maybe", never a "yes" — so nothing is billed as MeshCore until a connection proves
|
||||
#: it.
|
||||
#: The ``MESHCORE`` verdict for each discovery confidence tier, for the devices that
|
||||
#: MeshTerm did not confirm yet. The USB vendor ID is only a hint: a native-USB board or a
|
||||
#: bare bridge chip is a "maybe", never a "yes". Thus no device is called MeshCore until a
|
||||
#: connection proves it.
|
||||
_MAYBE: dict[str, str] = {"board": "maybe", "bridge": "maybe", "unknown": "no"}
|
||||
|
||||
|
||||
@register
|
||||
class DevicesTool(Tool):
|
||||
"""List attached serial, SPI, and in-range Bluetooth companions; mark likely and active."""
|
||||
"""List the serial, SPI, and in-range Bluetooth companions, and mark likely and active ones."""
|
||||
|
||||
name = "devices"
|
||||
title = "Devices"
|
||||
@@ -51,21 +53,22 @@ class DevicesTool(Tool):
|
||||
menu_visible = False # CLI-only: a startup diagnostic with no place in a connected session
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Enumerate attached and advertising devices, and state them as a listing.
|
||||
"""Find the connected devices and the devices that send BLE advertisements, as a listing.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused beyond the menu's selection bookkeeping.
|
||||
ctx: The shared application context.
|
||||
params: Not used, except for the selection bookkeeping of the menu.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing how many devices were found.
|
||||
A :class:`ToolResult` with the number of devices found.
|
||||
"""
|
||||
if ctx.mock:
|
||||
# `--mock` promises a session with no real hardware, and a scan is the one
|
||||
# thing this tool does — it walked the serial ports and switched the Bluetooth
|
||||
# radio on regardless, which is a promise broken on the first command a
|
||||
# stranger without a radio would try. So under --mock the simulator *is* the
|
||||
# inventory: one row, and nothing on the machine touched.
|
||||
# `--mock` promises a session with no real hardware, and a scan is the only
|
||||
# thing that this tool does. Before, the tool examined the serial ports and
|
||||
# switched the Bluetooth radio on, also with `--mock`. Thus a new user without
|
||||
# a companion saw that promise broken on the first command that they tried.
|
||||
# Now, with --mock, the simulator is the inventory: one row, and the tool does
|
||||
# not touch the machine.
|
||||
devices = [
|
||||
DiscoveredDevice(
|
||||
transport=TRANSPORT_MOCK,
|
||||
@@ -76,9 +79,10 @@ class DevicesTool(Tool):
|
||||
else:
|
||||
scan_ble = params.get("ble", True)
|
||||
devices = await discover_all(ble=scan_ble) if scan_ble else discover_devices()
|
||||
# A radio on the SPI bus is attached the way a serial port is, but nothing
|
||||
# enumerates it: it is listed from its device node, as the device screen lists it
|
||||
# — and the port its board's GPS answers on is listed as part of it, not beside it.
|
||||
# A radio on the SPI bus is connected as a serial port is, but nothing lists it
|
||||
# automatically. Thus the tool lists it from its device file, as the device
|
||||
# screen lists it. The port on which the GPS of its board answers is listed as
|
||||
# part of the radio, not next to it.
|
||||
devices = without_radio_ports(devices, ctx.settings.profiles)
|
||||
devices += spi_radios(ctx.settings.profiles, devices)
|
||||
known = ctx.device_store.load_all()
|
||||
@@ -91,7 +95,7 @@ class DevicesTool(Tool):
|
||||
else None
|
||||
)
|
||||
except DeviceSelectionError:
|
||||
spi = None # an ambiguous --spi: the listing is how the reader finds out which
|
||||
spi = None # an ambiguous --spi: the listing shows the user which one
|
||||
|
||||
active_target = (
|
||||
ctx.ble_override
|
||||
@@ -100,10 +104,11 @@ class DevicesTool(Tool):
|
||||
or (active.target if active else None)
|
||||
)
|
||||
|
||||
# A refused Bluetooth scan is not the same as a quiet one, and the difference is
|
||||
# invisible in the listing — both simply lack BLE rows. Say so whether or not
|
||||
# anything else was found: a serial board being present does not make a companion
|
||||
# the reader expected over Bluetooth any less missing.
|
||||
# A refused Bluetooth scan is not the same as a scan that found nothing. The
|
||||
# listing does not show the difference, because both have no BLE rows. Thus tell
|
||||
# the user, also if the scan found other devices. A serial board that is present
|
||||
# does not change the fact that a companion that the user expected over Bluetooth
|
||||
# is missing.
|
||||
blocked = ble_unavailable_reason()
|
||||
if blocked:
|
||||
from ..ui import script
|
||||
@@ -113,11 +118,12 @@ class DevicesTool(Tool):
|
||||
)
|
||||
|
||||
if not devices:
|
||||
# Not an error: the scan ran and found nothing. Said on stderr so a caller
|
||||
# redirecting stdout still hears it, and reported as NO_RESULT so a script can
|
||||
# branch on it without matching prose. The empty listing still reaches the
|
||||
# machine face as `[]`, which is a document a consumer can read — where an
|
||||
# empty stdout is a parse error it would have to tell apart from a real one.
|
||||
# Not an error: the scan ran and found nothing. The message goes to stderr, so
|
||||
# that a caller that redirects stdout still gets it. The exit status is
|
||||
# NO_RESULT, so that a script can branch on it without a match on the text.
|
||||
# The empty listing still goes to the machine face as `[]`, which is a document
|
||||
# that a consumer can read. An empty stdout is a parse error, and the consumer
|
||||
# must then tell it apart from a real parse error.
|
||||
from ..ui import script
|
||||
|
||||
script.stderr_console().print(
|
||||
@@ -127,13 +133,13 @@ class DevicesTool(Tool):
|
||||
return ToolResult(
|
||||
summary={"count": len(devices)},
|
||||
report=(_listing(devices, known, remembered, active_target),),
|
||||
# Changed from the 0 this used to return under --json: a rendering flag has no
|
||||
# business changing the report, and the plain path has always said 5 here.
|
||||
# Before, this returned 0 with --json. We changed it, because a rendering flag
|
||||
# must not change the report, and the plain path always gave 5 here.
|
||||
exit_code=exitcodes.OK if devices else exitcodes.NO_RESULT,
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``devices`` subcommand (inventory only; no connection).
|
||||
"""Register the ``devices`` subcommand (only an inventory, with no connection).
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
@@ -143,8 +149,8 @@ class DevicesTool(Tool):
|
||||
@app.command(
|
||||
name=self.name,
|
||||
help=self.help,
|
||||
# The listing used to close with a line explaining its own markers and how to
|
||||
# act on a row. That is help, and this is where help goes.
|
||||
# Before, the listing ended with a line that explained its markers and how to
|
||||
# use a row. That text is help, and help goes here.
|
||||
epilog="Select a device with --port TARGET or --ble TARGET, using the "
|
||||
"TARGET column verbatim; an SPI radio with --spi, or -p and its profile.",
|
||||
)
|
||||
@@ -157,24 +163,28 @@ class DevicesTool(Tool):
|
||||
|
||||
|
||||
def _listing(devices: list, known: dict, remembered: object, active_target: str | None) -> Listing:
|
||||
"""The device inventory, stated once for both faces.
|
||||
"""The device inventory, given one time for both faces.
|
||||
|
||||
``TARGET`` leads because it is the field a caller acts on — it is what ``--port`` and
|
||||
``--ble`` take, verbatim. The menu's two markers become columns of their own
|
||||
(``ACTIVE``, and ``MESHCORE`` for the confirmed star), because a glyph in a margin is
|
||||
something to look at rather than something to test.
|
||||
``TARGET`` is first, because a caller uses that field: ``--port`` and ``--ble`` take it
|
||||
exactly as it is. The two markers of the menu become columns (``ACTIVE``, and
|
||||
``MESHCORE`` for the confirmed star), because a person can look at a glyph in a
|
||||
margin, but a program cannot test it.
|
||||
|
||||
``MESHCORE`` is three-valued and stays that way: ``yes`` only once a connection has
|
||||
proved the device speaks the protocol, ``maybe`` for a USB vendor ID that suggests a
|
||||
LoRa board or a bridge chip, ``no`` for anything else. A vendor ID is a hint, and the
|
||||
column would be lying if it rounded one up — which is why the machine face carries the
|
||||
same three words rather than the boolean it used to.
|
||||
``MESHCORE`` has three values, and it keeps them:
|
||||
|
||||
- ``yes`` only after a connection proved that the device uses the protocol.
|
||||
- ``maybe`` for a USB vendor ID that suggests a LoRa board or a bridge chip.
|
||||
- ``no`` for all other devices.
|
||||
|
||||
A vendor ID is a hint. If the column changes a hint to ``yes``, the column gives false
|
||||
information. For this reason, the machine face has the same three words, and not
|
||||
the boolean that it had before.
|
||||
|
||||
Args:
|
||||
devices: The discovered devices.
|
||||
known: Remembered device records, keyed by stable id.
|
||||
known: The remembered device records, keyed by stable id.
|
||||
remembered: The remembered default device, if there is one.
|
||||
active_target: The target this invocation is (or would be) using.
|
||||
active_target: The target that this run uses (or would use).
|
||||
|
||||
Returns:
|
||||
The listing.
|
||||
@@ -207,15 +217,15 @@ def _listing(devices: list, known: dict, remembered: object, active_target: str
|
||||
columns=(
|
||||
fields.word("target", "TARGET"),
|
||||
fields.word("transport", "TRANSPORT"),
|
||||
# The two halves `target` is one of, kept apart for a caller that has to know
|
||||
# which transport it is holding without parsing the target for a colon.
|
||||
# The two possible forms of `target`, kept separate. Thus a caller knows which
|
||||
# transport it has, and it does not have to parse the target for a colon.
|
||||
fields.hidden("port"),
|
||||
fields.hidden("address"),
|
||||
fields.name("label", "NAME"),
|
||||
fields.name("hardware", "HARDWARE"),
|
||||
fields.word("meshcore", "MESHCORE"),
|
||||
# What the "maybe" was derived from. A person reading the column has the
|
||||
# vendor label beside it and can see for themselves; a program cannot.
|
||||
# The source of the "maybe". A person who reads the column sees the vendor
|
||||
# label next to it, but a program cannot.
|
||||
fields.hidden("confidence"),
|
||||
fields.word("serial_number", "SERIAL"),
|
||||
fields.hidden("stable_id"),
|
||||
|
||||
+141
-129
@@ -1,31 +1,33 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``diagnostics`` tool: everything a bug report needs, in one block worth pasting.
|
||||
"""The ``diagnostics`` tool: all that is necessary for a bug report, in one block to paste.
|
||||
|
||||
A report that opens with "it crashed" costs two or three round trips before anyone knows
|
||||
which MeshTerm, which OS, which terminal, which radio — and the person who hit the bug is
|
||||
usually the one least able to answer, because half of it is resolved at boot and never
|
||||
shown. This states all of it at once.
|
||||
If a report starts with "it crashed", two or three questions and answers are necessary
|
||||
before anyone knows which MeshTerm, which OS, which terminal, and which radio. The person
|
||||
who found the bug is usually the person who can answer least, because MeshTerm finds half
|
||||
of these facts at boot and never shows them. This tool states all of them at one time.
|
||||
|
||||
**What it deliberately does not say.** The block is designed to be pasted in public by
|
||||
somebody who has not read it, so nothing that identifies a person or unlocks anything may
|
||||
be in it: no pairing PIN, no admin password, no channel secret, no private key, no
|
||||
position, and no contact's name or key. The mesh is described in **aggregate** — how many
|
||||
rows of each kind, and the span of time they cover — which is the half that explains a bug
|
||||
(a database with four observations and one with four hundred thousand fail differently)
|
||||
without naming anyone the reporter talks to. :func:`~meshterm.core.hostinfo.host` and
|
||||
:meth:`~meshterm.persistence.repository.Repository.table_counts` hold that line on their
|
||||
own side, so it cannot be crossed here by accident.
|
||||
**What it does not say, on purpose.** The block is made for a person who pastes it in
|
||||
public and did not read it. Thus it must not contain anything that identifies a person or
|
||||
unlocks anything: no pairing PIN, no admin password, no channel secret, no private key, no
|
||||
position, and no name or key of a contact. The block describes the mesh only in
|
||||
**totals**: how many rows of each type, and the span of time that they cover. That half
|
||||
explains a bug (a database with four observations and one with four hundred thousand fail
|
||||
in different ways), and it names nobody that the reporter talks to.
|
||||
:func:`~meshterm.core.hostinfo.host` and
|
||||
:meth:`~meshterm.persistence.repository.Repository.table_counts` keep that limit on their
|
||||
own side. Thus this module cannot go past it by accident.
|
||||
|
||||
**One report, three faces**, which is the whole reason this is a report and not a
|
||||
``print``: the menu draws it as a written page (see :mod:`meshterm.ui.diagnostics`) and
|
||||
saves it as markdown, ``meshterm diagnostics`` prints the same facts as aligned records for
|
||||
anyone who would rather redirect than read, and ``--json`` hands them to whatever files the
|
||||
issue. The document face is the one that leaves this machine, so it is the one written in
|
||||
the format an issue tracker already renders.
|
||||
**One report, three faces.** That is the only reason why this is a report and not a
|
||||
``print``. The menu draws it as a written page (refer to :mod:`meshterm.ui.diagnostics`)
|
||||
and saves it as markdown. ``meshterm diagnostics`` prints the same facts as aligned
|
||||
records, for a person who wants to redirect them and not read them. ``--json`` gives
|
||||
them to the program that files the issue. The document face is the face that leaves this
|
||||
machine. Thus it is written in a format that an issue tracker already renders.
|
||||
|
||||
The device is asked but never required. A report about a radio that will not connect is
|
||||
exactly the report that most needs to be filed, so a failure to reach it becomes a fact in
|
||||
the block (``connected``/``error``) rather than an error that replaces it.
|
||||
The tool asks the device, but the device is not necessary. A report about a radio that
|
||||
does not connect is the report that it is most necessary to file. Thus, when the tool
|
||||
cannot get to the device, that failure becomes a fact in the block (``connected`` and
|
||||
``error``), and not an error that replaces the block.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -41,32 +43,33 @@ from .base import Tool, ToolResult, register
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from ..ui.report import Report
|
||||
|
||||
#: What the saved file is called, in the config directory beside the log it sits next to
|
||||
#: in a bug report. Named for the app rather than just ``diagnostics.md`` because the one
|
||||
#: thing that happens to this file is being moved somewhere else and attached, and by then
|
||||
#: the directory it came from is no longer saying what it is.
|
||||
#: The name of the saved file, in the config directory, next to the log that it goes with
|
||||
#: in a bug report. The name includes the app name, and is not only ``diagnostics.md``.
|
||||
#: The reason: the only thing that occurs to this file is that a person moves it to a
|
||||
#: different place and attaches it. Then the directory that it came from no longer tells
|
||||
#: what it is.
|
||||
DIAGNOSTICS_FILENAME = "meshterm-diagnostics.md"
|
||||
|
||||
|
||||
@register
|
||||
class DiagnosticsTool(Tool):
|
||||
"""What MeshTerm, this machine, this terminal and this radio actually are."""
|
||||
"""What MeshTerm, this machine, this terminal, and this radio are."""
|
||||
|
||||
name = "diagnostics"
|
||||
title = "Diagnostics"
|
||||
icon = "🩺"
|
||||
help = "Version, host, terminal, and device facts for a bug report"
|
||||
category = "This app"
|
||||
order = 7 # after Preferences (the row that changes MeshTerm), before the pages
|
||||
order = 7 # after Preferences (the row that changes MeshTerm), and before the pages
|
||||
|
||||
def register_cli(self, app: Any) -> None:
|
||||
"""Register the command, with the one option that turns the answer into a file.
|
||||
"""Register the command, with the one option that changes the answer into a file.
|
||||
|
||||
``--out`` is spelled the way ``config export-key --out`` already spells it, rather
|
||||
than inventing a second word for writing an answer to a path. Plain redirection
|
||||
still works and is not replaced by it — what the option adds is a file whose
|
||||
columns are laid out at full width instead of at whatever the terminal happened to
|
||||
be, which is the difference between a readable attachment and a folded one.
|
||||
``--out`` has the same spelling as ``config export-key --out``. We did not make a
|
||||
second word to write an answer to a path. Plain redirection continues to work, and
|
||||
the option does not replace it. The option adds a file whose columns have the full
|
||||
width, and not the width that the terminal had at that time. That is the
|
||||
difference between an attachment that a person can read and a folded one.
|
||||
"""
|
||||
import typer
|
||||
|
||||
@@ -81,18 +84,18 @@ class DiagnosticsTool(Tool):
|
||||
run_tool_command(self, {"out": out})
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Open the page in the menu; returning ``None`` completes with no run row.
|
||||
"""Open the page in the menu. The return value ``None`` ends with no run row.
|
||||
|
||||
The same shape the About pages use — and the same screen, since the page *is* one:
|
||||
the menu's whole interaction is the reading of it, and a run row recording that
|
||||
somebody looked at their own version number would be a line in the log for every
|
||||
glance. Saving from the page is likewise not a run.
|
||||
The About pages use the same shape, and the same screen, because this page is a
|
||||
written page too. In the menu, the user only reads it. If a run row stores that a
|
||||
person looked at their own version number, the log gets a line for each look. A
|
||||
save from the page is also not a run.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None`` in the menu; the CLI never reaches this.
|
||||
Always ``None`` in the menu. The CLI never gets to this method.
|
||||
"""
|
||||
from ..ui.diagnostics import open_diagnostics_page
|
||||
|
||||
@@ -101,18 +104,18 @@ class DiagnosticsTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""State the diagnostics, or write them to a file — only reachable from the CLI.
|
||||
"""State the diagnostics, or write them to a file. Only the CLI gets to this method.
|
||||
|
||||
With ``--out`` the answer *becomes the path*, the same trade ``config export-key``
|
||||
makes: a caller who asked for a file wants to be told where it is, not handed the
|
||||
contents they just redirected into it.
|
||||
With ``--out``, the answer *is the path*. ``config export-key`` makes the same
|
||||
choice. A caller who asked for a file wants to know where it is. The caller does
|
||||
not want to get again the contents that it sent into that file.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``out`` — a destination path, or ``None`` to print the block.
|
||||
ctx: The shared application context.
|
||||
params: ``out``: a destination path, or ``None`` to print the block.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` carrying the block, or the path it was written to.
|
||||
A :class:`ToolResult` that holds the block, or the path of the written file.
|
||||
"""
|
||||
report = await build_report(ctx)
|
||||
out = params.get("out")
|
||||
@@ -129,23 +132,24 @@ class DiagnosticsTool(Tool):
|
||||
|
||||
|
||||
async def build_report(ctx: AppContext) -> Report:
|
||||
"""Gather every diagnostic fact, as the report both faces render.
|
||||
"""Collect all the diagnostic facts, as the report that the two faces render.
|
||||
|
||||
Seven blocks in the order a reader needs them: what this program is, what it is running
|
||||
on, what it is drawing into, what radio it found, how much history it has, what that
|
||||
history is made of, and what has been changed from the defaults. Each carries a
|
||||
``caption``, which is what the markdown face turns into the page's ``##`` landmarks.
|
||||
Seven blocks, in the order that is most useful to the user: what this program is, the
|
||||
machine it runs on, the terminal it draws into, the radio it found, how much history it
|
||||
has, what that history contains, and what is changed from the defaults. Each block has
|
||||
a ``caption``. The markdown face changes the captions into the ``##`` landmarks of the
|
||||
page.
|
||||
|
||||
The five :class:`~meshterm.ui.report.Facts` blocks merge into one flat JSON object and
|
||||
the two :class:`~meshterm.ui.report.Listing` blocks keep a key of their own — which is
|
||||
also why the table counts are a listing, since a table named after a fact would
|
||||
otherwise be able to collide with it.
|
||||
The five :class:`~meshterm.ui.report.Facts` blocks merge into one flat JSON object.
|
||||
The two :class:`~meshterm.ui.report.Listing` blocks each keep their own key. That is
|
||||
also why the table counts are a listing: if they were facts, a table with the same name
|
||||
as a fact could collide with it.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
The seven-block report.
|
||||
The report of seven blocks.
|
||||
"""
|
||||
return (
|
||||
_app_facts(),
|
||||
@@ -159,36 +163,41 @@ async def build_report(ctx: AppContext) -> Report:
|
||||
|
||||
|
||||
def markdown_source(report: Report, *, when: datetime | None = None) -> str:
|
||||
"""The whole block as a markdown document — the page's source, and the file's contents.
|
||||
"""The full block as a markdown document: the source of the page, and the file contents.
|
||||
|
||||
Markdown because both places this goes already speak it: the menu draws it through
|
||||
:func:`~meshterm.ui.markdown.render_markdown`, the same renderer behind the About
|
||||
pages, so the page gets real ``##`` landmarks that pin as it scrolls and that its
|
||||
section jumps step by; and an issue tracker renders it as written, with no fence and
|
||||
no apology. The command line keeps its aligned records — that face is a stream a
|
||||
person greps, and headings are furniture on it.
|
||||
It is markdown because the two places where this text goes already use markdown. The
|
||||
menu draws it through :func:`~meshterm.ui.markdown.render_markdown`, the same renderer
|
||||
as the About pages. Thus the page gets real ``##`` landmarks, which pin while the page
|
||||
scrolls and which the section jumps go to. An issue tracker renders it as it is
|
||||
written, with no fence and no apology. The command line keeps its aligned records,
|
||||
because that face is a stream that a person searches with grep, and headings only add
|
||||
clutter to it.
|
||||
|
||||
Args:
|
||||
report: The blocks to write out.
|
||||
when: The moment to stamp in the colophon (defaults to now, local). Injectable so
|
||||
the same report can be rendered twice and compared.
|
||||
report: The blocks to write.
|
||||
when: The time to put in the colophon (the default is now, in local time). A
|
||||
caller can give it, so that the same report can be rendered two times and
|
||||
compared.
|
||||
|
||||
Returns:
|
||||
Markdown source, ready for :func:`~meshterm.ui.markdown.render_markdown` or a file.
|
||||
The markdown source, ready for :func:`~meshterm.ui.markdown.render_markdown` or
|
||||
for a file.
|
||||
"""
|
||||
from .. import __version__
|
||||
from ..ui.renderers import markdown_blocks
|
||||
|
||||
stamp = (when or datetime.now().astimezone()).strftime("%Y-%m-%d %H:%M")
|
||||
return (
|
||||
# The `#` title carries what the frame around it cannot — which is the same reason
|
||||
# `about.md` has one and the other three written pages do not. The screen is already
|
||||
# headed "Diagnostics"; repeating that would spend the page's first line saying
|
||||
# nothing, while the version belongs at the top of a file somebody will open later.
|
||||
# Emphasis makes it the muted qualifier beside the name.
|
||||
# The `#` title holds what the frame around it cannot hold. For the same reason,
|
||||
# `about.md` has one and the other three written pages do not. The screen already
|
||||
# has the heading "Diagnostics". If the title repeats it, the first line of the
|
||||
# page says nothing. But the version must be at the top of a file that a
|
||||
# person will open later. The emphasis makes the version the muted qualifier next
|
||||
# to the name.
|
||||
f"# MeshTerm diagnostics *v{__version__}*\n\n"
|
||||
# The standfirst sits flush and muted under the title, and says the one thing a
|
||||
# reader needs before reading any of it: this is safe to hand over.
|
||||
# The standfirst is flush and muted under the title. It says the one thing that the
|
||||
# user must know before the user reads the rest: it is safe to give this text to
|
||||
# other persons.
|
||||
"Everything a bug report opens with. Nothing here is private.\n\n"
|
||||
f"{markdown_blocks(report)}\n\n"
|
||||
"---\n\n"
|
||||
@@ -197,21 +206,22 @@ def markdown_source(report: Report, *, when: datetime | None = None) -> str:
|
||||
|
||||
|
||||
def default_path(ctx: AppContext) -> Path:
|
||||
"""Where the page saves when nobody named a place: beside the log, in the config dir.
|
||||
"""Where the page saves when no place is given: next to the log, in the config directory.
|
||||
|
||||
The config directory rather than the working directory, which in the menu is wherever
|
||||
the reader happened to launch from and is not somewhere they can be told to look. It
|
||||
is also where the log already lives, so "send me both" names one folder.
|
||||
It is the config directory, not the working directory. In the menu, the working
|
||||
directory is the directory from which the user started MeshTerm, and nobody can tell
|
||||
the user where that is. The log is also in the config directory, so "send me both"
|
||||
names one folder.
|
||||
"""
|
||||
return ctx.settings.config_dir / DIAGNOSTICS_FILENAME
|
||||
|
||||
|
||||
def write_markdown(source: str, path: Path | str) -> Path:
|
||||
"""Write a markdown document to ``path``, creating its directory.
|
||||
"""Write a markdown document to ``path``, and make its directory.
|
||||
|
||||
**Always markdown**, whatever face the run was printing. This file exists to be
|
||||
attached to an issue and read there, and an issue tracker renders markdown; anyone who
|
||||
wants the machine face can redirect ``--json`` and already has a better name for that
|
||||
**Always markdown**, whatever face the run printed. This file is for an attachment to
|
||||
an issue, where people read it, and an issue tracker renders markdown. A person who
|
||||
wants the machine face can redirect ``--json``, and already has a better name for that
|
||||
file than this one.
|
||||
|
||||
Args:
|
||||
@@ -219,10 +229,10 @@ def write_markdown(source: str, path: Path | str) -> Path:
|
||||
path: The destination.
|
||||
|
||||
Returns:
|
||||
The path written.
|
||||
The path of the written file.
|
||||
|
||||
Raises:
|
||||
OSError: If the directory cannot be made or the file cannot be written.
|
||||
OSError: If the directory cannot be made, or if the file cannot be written.
|
||||
"""
|
||||
written = Path(path)
|
||||
written.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -231,7 +241,7 @@ def write_markdown(source: str, path: Path | str) -> Path:
|
||||
|
||||
|
||||
def _written_to(written: Path) -> Any:
|
||||
"""The answer a ``--out`` run gives: the path, alone on the plain face."""
|
||||
"""The answer of a ``--out`` run: only the path, on the plain face."""
|
||||
from ..ui import fields
|
||||
from ..ui.report import BARE, Facts
|
||||
|
||||
@@ -245,7 +255,7 @@ def _written_to(written: Path) -> Any:
|
||||
|
||||
|
||||
def _app_facts() -> Any:
|
||||
"""What this program is: version, how it was installed, and where it keeps things."""
|
||||
"""What this program is: the version, how it was installed, and where it keeps data."""
|
||||
from .. import __version__
|
||||
from ..core import hostinfo
|
||||
from ..ui import fields
|
||||
@@ -263,7 +273,7 @@ def _app_facts() -> Any:
|
||||
|
||||
|
||||
def _host_facts() -> Any:
|
||||
"""The machine underneath: which OS, which build, which processor, which Python."""
|
||||
"""The machine below MeshTerm: which OS, which build, which processor, which Python."""
|
||||
from ..core import hostinfo
|
||||
from ..ui import fields
|
||||
from ..ui.report import Facts
|
||||
@@ -288,13 +298,14 @@ def _host_facts() -> Any:
|
||||
|
||||
|
||||
def _terminal_facts() -> Any:
|
||||
"""The terminal, and every verdict about it resolved once at boot.
|
||||
"""The terminal, and each decision about it that MeshTerm made one time at boot.
|
||||
|
||||
Its own section rather than more host facts, because these are what a "it looks wrong"
|
||||
report is actually about, and a reader skimming for them should not have to pass the
|
||||
processor architecture on the way. Whether icons draw, whether the path widget's
|
||||
separators draw, which platform flavour resolved and *why* — each is decided from the
|
||||
environment before the first frame and none of it is visible on any screen.
|
||||
These facts have their own section, and are not more host facts. The reason: a report
|
||||
of "it looks wrong" is about these facts. A user who looks quickly for them must not
|
||||
have to read the processor architecture first. Whether icons draw, whether the
|
||||
separators of the path widget draw, which platform flavour resolved, and *why*:
|
||||
MeshTerm decides each of these from the environment before the first frame, and no
|
||||
screen shows them.
|
||||
"""
|
||||
from ..core import hostinfo
|
||||
from ..platforms import get_platform
|
||||
@@ -330,24 +341,25 @@ def _terminal_facts() -> Any:
|
||||
"platform": get_platform().name,
|
||||
"icons": emoji.supported,
|
||||
"icons_source": emoji.source,
|
||||
# The face, and which terminal it was read from — an unidentified terminal
|
||||
# (or an ssh session, where the font lives on the far client) has no answer,
|
||||
# and saying so is worth more than naming a font nobody here can see.
|
||||
# The font face, and the terminal from which it was read. A terminal that is not
|
||||
# identified (or an ssh session, where the font is on the far client) has no
|
||||
# answer. To say so is better than to name a font that nobody here can see.
|
||||
"font": f"{font.face} ({font.source})" if font else None,
|
||||
# Level and source together: `none (font:windows-terminal)` is a measurement
|
||||
# and `unknown (ssh)` is an admission, and they lead somewhere different.
|
||||
# The level and the source together. `none (font:windows-terminal)` is a
|
||||
# measurement and `unknown (ssh)` says that MeshTerm does not know. They lead
|
||||
# to different places.
|
||||
"powerline": f"{powerline.level} ({powerline.source})",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _device_facts(ctx: AppContext) -> Any:
|
||||
"""The radio: what it is, how it is attached, and what its link is set to.
|
||||
"""The radio: what it is, how it is connected, and the settings of its link.
|
||||
|
||||
Best-effort by design. Every value here is ``None`` on a machine whose radio is
|
||||
unplugged, asleep, or refusing to pair — and ``connected: false`` with the failure's
|
||||
own words in ``error`` is a better first line for that bug report than a command that
|
||||
refused to produce one.
|
||||
This function does what it can, on purpose. Each value here is ``None`` on a machine
|
||||
whose radio is disconnected, asleep, or does not pair. For that bug report,
|
||||
``connected: false`` with the words of the failure in ``error`` is a better first line
|
||||
than a command that did not make a report.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import Facts
|
||||
@@ -387,7 +399,7 @@ async def _device_facts(ctx: AppContext) -> Any:
|
||||
radio_cr=snapshot.get("radio_cr"),
|
||||
tx_power_dbm=snapshot.get("tx_power"),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - any failure to reach the radio is the fact
|
||||
except Exception as exc: # noqa: BLE001 - each failure to get to the radio is the fact
|
||||
values["error"] = str(exc) or exc.__class__.__name__
|
||||
|
||||
return Facts(
|
||||
@@ -412,11 +424,11 @@ async def _device_facts(ctx: AppContext) -> Any:
|
||||
|
||||
|
||||
def _mesh_facts(ctx: AppContext) -> Any:
|
||||
"""How much history this install holds, and where it holds it.
|
||||
"""How much history this installation holds, and where it holds it.
|
||||
|
||||
Counts and a span, never a row. The span is the fact that sizes every other number
|
||||
here: a thousand observations over two years and a thousand in an afternoon describe
|
||||
two different installs, and only one of them has a radio worth suspecting.
|
||||
Counts and a span, never a row. The span gives the scale of each other number here.
|
||||
A thousand observations in two years and a thousand in an afternoon describe two
|
||||
different installations, and only one of them has a radio that is possibly faulty.
|
||||
"""
|
||||
from ..core.preferences import current
|
||||
from ..persistence.logging import log_path
|
||||
@@ -442,8 +454,8 @@ def _mesh_facts(ctx: AppContext) -> Any:
|
||||
"config_dir": ctx.settings.config_dir,
|
||||
"db_size_kb": _size_kb(db_path),
|
||||
"log_level": preferences.log_level,
|
||||
# How much the log holds, so a maintainer asking for it knows what they are
|
||||
# asking for — and so a file still at zero says the level never let it write.
|
||||
# How much the log holds. Thus a maintainer who asks for it knows what to expect.
|
||||
# Also, a file that is still at zero shows that the level never let it write.
|
||||
"log_size_kb": _size_kb(log_path(ctx.settings.config_dir)),
|
||||
"runs_failed": ctx.repo.failed_run_count(),
|
||||
"first_heard": first,
|
||||
@@ -453,12 +465,12 @@ def _mesh_facts(ctx: AppContext) -> Any:
|
||||
|
||||
|
||||
def _table_listing(ctx: AppContext) -> Any:
|
||||
"""Every table in the database and how many rows it holds.
|
||||
"""Each table in the database, and how many rows it holds.
|
||||
|
||||
A listing rather than more facts, for two reasons. The keys are discovered from the
|
||||
schema rather than declared, so a table named after a fact could otherwise collide
|
||||
with it in the merged JSON object; and this genuinely is a set of records — one per
|
||||
table — which is the shape a reader and a parser both already know.
|
||||
A listing, and not more facts, for two reasons. First, the keys come from the schema,
|
||||
and are not declared. Thus, if they were facts, a table with the same name as a fact
|
||||
could collide with it in the merged JSON object. Second, this is in fact a set of
|
||||
records (one for each table), and a person and a parser both already know that shape.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import Column, Listing
|
||||
@@ -473,11 +485,11 @@ def _table_listing(ctx: AppContext) -> Any:
|
||||
|
||||
|
||||
def _preference_listing(ctx: AppContext) -> Any:
|
||||
"""The preferences that differ from their defaults — the whole list, and only those.
|
||||
"""The preferences that are not at their defaults: all of them, and only those.
|
||||
|
||||
An override is the only part of the preference set that can explain anything: the
|
||||
defaults are in the source, the same for everyone, and dumping all forty would bury
|
||||
the two the reporter actually changed.
|
||||
An override is the only part of the preferences that can explain something. The
|
||||
defaults are in the source, and they are the same for all users. If the list shows
|
||||
all forty preferences, the two that the reporter changed are hard to find.
|
||||
"""
|
||||
from ..core.preferences import current
|
||||
from ..ui import fields
|
||||
@@ -496,14 +508,14 @@ def _preference_listing(ctx: AppContext) -> Any:
|
||||
|
||||
|
||||
def _rows_lane() -> Any:
|
||||
"""The row-count lane: right-aligned, because a column of magnitudes only compares aligned."""
|
||||
"""The lane of row counts: right-aligned, because only aligned numbers are easy to compare."""
|
||||
from ..ui.report import Lane
|
||||
|
||||
return Lane(header="ROWS", render=lambda v: str(v if v is not None else 0), align="right")
|
||||
|
||||
|
||||
def _size_kb(path: Any) -> int | None:
|
||||
"""A file's size in whole kilobytes, or ``None`` when it is not there to measure."""
|
||||
"""The size of a file in whole kilobytes, or ``None`` when there is no file to measure."""
|
||||
if path is None:
|
||||
return None
|
||||
try:
|
||||
@@ -513,18 +525,18 @@ def _size_kb(path: Any) -> int | None:
|
||||
|
||||
|
||||
async def _snapshot(ctx: AppContext, device: Any) -> dict:
|
||||
"""The device's settings snapshot, or an empty one when the read fails."""
|
||||
"""The snapshot of the device settings, or an empty snapshot when the read fails."""
|
||||
from ..ui.config_editor import cached_snapshot
|
||||
|
||||
try:
|
||||
return await cached_snapshot(ctx, device)
|
||||
except Exception: # noqa: BLE001 - a settings read that fails leaves the radio facts blank
|
||||
except Exception: # noqa: BLE001 - if the settings read fails, the radio facts stay blank
|
||||
return {}
|
||||
|
||||
|
||||
async def _device_info(device: Any) -> dict:
|
||||
"""The device's self-description, or an empty one when the firmware does not answer."""
|
||||
"""The self-description of the device, or an empty one when the firmware does not answer."""
|
||||
try:
|
||||
return await device.get_device_info() or {}
|
||||
except Exception: # noqa: BLE001 - firmware predating the query contributes nothing
|
||||
except Exception: # noqa: BLE001 - firmware older than the query gives nothing
|
||||
return {}
|
||||
+58
-54
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``info`` tool: show the connected companion device's identity and radio config."""
|
||||
"""The ``info`` tool: show the identity and the radio settings of the connected device."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,9 +23,9 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class InfoTool(Tool):
|
||||
"""Display device identity and radio configuration.
|
||||
"""Show the identity and the radio settings of the device.
|
||||
|
||||
The known-contacts list lives in the separate ``nodes`` tool.
|
||||
The list of known contacts is in the separate ``nodes`` tool.
|
||||
"""
|
||||
|
||||
name = "info"
|
||||
@@ -33,17 +33,17 @@ class InfoTool(Tool):
|
||||
icon = "📋"
|
||||
help = "Show device status, identity, and radio config"
|
||||
category = "This node"
|
||||
order = 10 # what it is, before anything that changes it
|
||||
order = 10 # what it is, before the tools that change it
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Query the device and render its live status plus its full configuration.
|
||||
"""Query the device, and render its live status and all its settings.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing the device name.
|
||||
A :class:`ToolResult` with the device name in its summary.
|
||||
"""
|
||||
from rich.console import Group
|
||||
|
||||
@@ -52,10 +52,10 @@ class InfoTool(Tool):
|
||||
device = await ctx.device()
|
||||
snapshot = await cached_snapshot(ctx, device)
|
||||
|
||||
# On the CLI this is the *status* report and nothing else: how the radio is doing
|
||||
# right now, one fact per line. What it is set to is `config show`'s answer, in
|
||||
# the very keys `config get`/`config set` take, so printing the settings here as
|
||||
# well would be the same table twice under two different spellings.
|
||||
# On the CLI, this is only the status report: the current condition of the device,
|
||||
# one fact on each line. The settings are the answer of `config show`, with the
|
||||
# same keys that `config get` and `config set` take. If this command also prints
|
||||
# the settings, the same table shows two times, with two different spellings.
|
||||
session = getattr(ctx.ui, "session", None)
|
||||
if session is None:
|
||||
return ToolResult(
|
||||
@@ -66,16 +66,17 @@ class InfoTool(Tool):
|
||||
from ..ui.device_info_screen import DeviceInfoScreen
|
||||
|
||||
custom = await device.get_custom_vars()
|
||||
# A live status panel (role, firmware, battery, clock, radio/packet statistics)
|
||||
# above every current setting with a short explanation of each. The panel is read
|
||||
# once; only the table differs between the two states, and it is cheap to rebuild.
|
||||
# A live status panel (role, firmware, battery, clock, radio and packet statistics)
|
||||
# above all the current settings, each with a short explanation. The panel is read
|
||||
# one time. Only the table is different between the two states, and it is fast to
|
||||
# build again.
|
||||
panel = await _status_panel(device, snapshot)
|
||||
|
||||
def page(reveal_pin: bool) -> Group:
|
||||
return Group(panel, Text(""), config_table(snapshot, custom, reveal_pin=reveal_pin))
|
||||
|
||||
# The page is its own screen because it has a key of its own: the pairing PIN is
|
||||
# masked until ``p`` uncovers it.
|
||||
# The page is a separate screen, because it has its own keyboard key: the pairing
|
||||
# PIN is masked until ``p`` shows it.
|
||||
await session.run_screen(
|
||||
DeviceInfoScreen(session, page, title=self.title, conceals=has_pin(snapshot))
|
||||
)
|
||||
@@ -98,18 +99,19 @@ class InfoTool(Tool):
|
||||
|
||||
|
||||
async def _read_status(device: Device) -> dict[str, Any]:
|
||||
"""Read every live status value the firmware will answer for, best-effort.
|
||||
"""Read each live status value that the firmware gives, as a best effort.
|
||||
|
||||
The one place the device is asked. Both faces build from what it returns: the menu's
|
||||
panel composes prose rows out of these values, the CLI prints them one fact per line
|
||||
(see :func:`_status_panel` and :func:`status_facts`). Every read is optional —
|
||||
firmware predating a query simply contributes nothing — so this works on any device.
|
||||
This is the only place that asks the device. Both faces use what it returns: the panel
|
||||
of the menu makes prose rows from these values, and the CLI prints them one fact on
|
||||
each line (refer to :func:`_status_panel` and :func:`status_facts`). Each read is
|
||||
optional, because firmware that is older than a query gives nothing for it. Thus this
|
||||
function works on any device.
|
||||
|
||||
Args:
|
||||
device: The connected device to query.
|
||||
|
||||
Returns:
|
||||
The merged raw readings: ``info``, ``battery``, ``stats`` and ``clock``.
|
||||
The merged raw readings: ``info``, ``battery``, ``stats``, and ``clock``.
|
||||
"""
|
||||
return {
|
||||
"info": await _try(device.get_device_info) or {},
|
||||
@@ -122,16 +124,17 @@ async def _read_status(device: Device) -> dict[str, Any]:
|
||||
async def _status_panel(device: Device, snapshot: dict) -> Panel:
|
||||
"""Build the live status panel: role, firmware, battery, clock, and statistics.
|
||||
|
||||
The menu's face of :func:`_read_status` — each row a short phrase rather than an
|
||||
This is the menu face of :func:`_read_status`. Each row is a short phrase, not an
|
||||
atomic value, because a person reads "-110 dBm noise floor · last RSSI -62 dBm" in one
|
||||
go where a script wants the three numbers apart.
|
||||
step. A script wants the three numbers separately.
|
||||
|
||||
Args:
|
||||
device: The connected device to query.
|
||||
snapshot: The already-built settings snapshot (for role and identity fields).
|
||||
snapshot: The settings snapshot that is already built (for the role and identity
|
||||
fields).
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Panel` of label/value status rows.
|
||||
A Rich :class:`Panel` of status rows, each with a label and a value.
|
||||
"""
|
||||
rows: list[tuple[str, Text]] = []
|
||||
readings = await _read_status(device)
|
||||
@@ -191,34 +194,35 @@ async def _status_panel(device: Device, snapshot: dict) -> Panel:
|
||||
|
||||
|
||||
def _firmware(info: dict) -> str:
|
||||
"""The firmware version and build joined, or ``""`` when neither was reported."""
|
||||
"""The firmware version and build, joined, or ``""`` if the device reported neither."""
|
||||
return " ".join(str(info[k]) for k in ("ver", "fw_build") if info.get(k))
|
||||
|
||||
|
||||
async def status_facts(device: Device, snapshot: dict) -> Facts:
|
||||
"""The device's live status as one set of facts.
|
||||
"""The live status of the device, as one set of facts.
|
||||
|
||||
The CLI's face of :func:`_read_status`. Where the panel writes a phrase per row, this
|
||||
writes one value per key and puts the unit *in the key* — ``battery_v``, ``uptime_s``,
|
||||
``noise_floor_dbm`` — so nothing has to be pulled back out of prose. A number never
|
||||
carries a unit in its value, on either face.
|
||||
This is the CLI face of :func:`_read_status`. The panel writes a phrase in each row,
|
||||
but this function writes one value for each key. It puts the unit in the key
|
||||
(``battery_v``, ``uptime_s``, ``noise_floor_dbm``), so that no program must get the
|
||||
number out of prose. On both faces, a number never has a unit in its value.
|
||||
|
||||
The three second-valued readings and the clock drift carry a **gloss** beside the
|
||||
figure: ``uptime_s 93784 (1d 2h)``. This is the one key/value block that may, and
|
||||
the reason is that it is the one with no ``get`` and no ``set`` behind it — there is no
|
||||
round trip to protect, the key still says what the number counts, and ``93784`` is a
|
||||
reading nobody can hold in their head. The document carries the number alone, having
|
||||
nowhere useful to put a phrase.
|
||||
The three readings in seconds and the clock drift have a **gloss** next to the number:
|
||||
``uptime_s 93784 (1d 2h)``. This is the only key/value block that can have a gloss.
|
||||
The reason is that it is the only block with no ``get`` and no ``set`` behind it. Thus
|
||||
there is no round trip to protect, the key still tells what the number counts, and
|
||||
``93784`` is a value that no person can easily understand. The document holds only the
|
||||
number, because it has no useful place for a phrase.
|
||||
|
||||
A reading the firmware did not answer for is **left out** of the plain block rather
|
||||
than dashed: these are optional queries, and a missing key says "this device does not
|
||||
report it" where a dash would claim it reported nothing. The document keeps the key and
|
||||
writes ``null`` — see :attr:`~meshterm.ui.report.Facts.omit_absent` for why the two
|
||||
faces disagree here on purpose.
|
||||
If the firmware gave no answer for a reading, the plain block **leaves out** that
|
||||
reading, and it does not show a dash. These are optional queries. A missing key says
|
||||
"this device does not report it", but a dash says that it reported nothing. The
|
||||
document keeps the key and writes ``null``. Refer to
|
||||
:attr:`~meshterm.ui.report.Facts.omit_absent` for the reason why the two faces are
|
||||
different here on purpose.
|
||||
|
||||
Args:
|
||||
device: The connected device to query.
|
||||
snapshot: The already-built settings snapshot (for role and identity).
|
||||
snapshot: The settings snapshot that is already built (for the role and identity).
|
||||
|
||||
Returns:
|
||||
The facts block.
|
||||
@@ -233,8 +237,8 @@ async def status_facts(device: Device, snapshot: dict) -> Facts:
|
||||
adv_type = snapshot.get("adv_type")
|
||||
clock = readings["clock"]
|
||||
values: dict[str, Any] = {
|
||||
# Identity first: which radio this is. Everything it *can be set to* is
|
||||
# `config show`'s answer, not this one.
|
||||
# The identity is first: which device this is. All the values that it can be set
|
||||
# to are the answer of `config show`, not of this command.
|
||||
"name": snapshot.get("name"),
|
||||
"public_key": str(snapshot.get("public_key") or "").lower() or None,
|
||||
"role": node_type_label(adv_type),
|
||||
@@ -286,7 +290,7 @@ async def status_facts(device: Device, snapshot: dict) -> Facts:
|
||||
|
||||
|
||||
def _glossed(key: str, gloss: Callable[[int], str]) -> Column:
|
||||
"""A seconds reading printed as its own number with a readable span beside it."""
|
||||
"""A reading in seconds, printed as its number with a readable duration next to it."""
|
||||
from ..ui import script
|
||||
from ..ui.report import Column, Lane
|
||||
|
||||
@@ -299,14 +303,14 @@ def _glossed(key: str, gloss: Callable[[int], str]) -> Column:
|
||||
|
||||
|
||||
def _span_gloss(seconds: int) -> str:
|
||||
"""``93784`` → ``1d 2h``: the figure a person can hold in their head."""
|
||||
"""``93784`` → ``1d 2h``: a value that a person can easily understand."""
|
||||
from ..ui import script
|
||||
|
||||
return script.duration(seconds)
|
||||
|
||||
|
||||
def _drift_gloss(seconds: int) -> str:
|
||||
"""The device clock's error, in the direction a reader would say it."""
|
||||
"""The error of the device clock, in the words that a person uses (fast or slow)."""
|
||||
from ..ui import script
|
||||
|
||||
if abs(seconds) < 2:
|
||||
@@ -315,15 +319,15 @@ def _drift_gloss(seconds: int) -> str:
|
||||
|
||||
|
||||
async def _try(read) -> Any | None:
|
||||
"""Await a device read, returning ``None`` when the firmware doesn't support it."""
|
||||
"""Await a device read. Return ``None`` if the firmware does not support it."""
|
||||
try:
|
||||
return await read()
|
||||
except Exception: # noqa: BLE001 - optional read; absence is acceptable
|
||||
except Exception: # noqa: BLE001 - an optional read. If it is absent, that is acceptable.
|
||||
return None
|
||||
|
||||
|
||||
def _drift(device_epoch: int) -> str:
|
||||
"""Describe the device clock's drift against this computer's clock."""
|
||||
"""Describe the drift of the device clock, compared with the clock of this computer."""
|
||||
drift = device_epoch - int(time.time())
|
||||
if abs(drift) < 2:
|
||||
return "(in sync)"
|
||||
@@ -332,7 +336,7 @@ def _drift(device_epoch: int) -> str:
|
||||
|
||||
|
||||
def _uptime(secs: int) -> str:
|
||||
"""Render an uptime as ``3d 2h 41m`` (seconds shown only under a minute)."""
|
||||
"""Render an uptime as ``3d 2h 41m`` (the seconds show only below one minute)."""
|
||||
if secs < 60:
|
||||
return f"{secs} s"
|
||||
days, rem = divmod(secs, 86400)
|
||||
|
||||
+22
-22
@@ -1,16 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``livefeed`` tool: every packet as it arrives, right under the dashboard.
|
||||
"""The ``livefeed`` tool: each packet when it arrives, directly below the dashboard.
|
||||
|
||||
Opens the full-screen live feed (see :mod:`meshterm.ui.livefeed_screen`): the
|
||||
streaming packet list that used to be the dashboard's bottom panel, promoted to its
|
||||
own menu entry — newest first, every class, Enter opening any row in the shared
|
||||
packet viewer. It sits directly under the dashboard because the two split one
|
||||
question between them: the dashboard summarizes *what's going on out there*, the
|
||||
feed shows every individual packet behind those numbers.
|
||||
The tool opens the full-screen live feed (refer to :mod:`meshterm.ui.livefeed_screen`).
|
||||
This is the streaming packet list that was the bottom panel of the dashboard before. Now
|
||||
it has its own menu entry. It shows the newest packets first and all the classes, and
|
||||
Enter opens any row in the shared packet viewer. It is directly below the dashboard,
|
||||
because the two tools share one question. The dashboard summarizes what occurs on the
|
||||
mesh, and the feed shows each packet behind those numbers.
|
||||
|
||||
Menu-only: the feed is inherently live (it rides the event hub and repaints every
|
||||
second), so there is no scripted one-shot to register — the ``monitor`` subcommand
|
||||
covers scripted packet-watching.
|
||||
Menu only: the feed is always live (it uses the event hub and paints again each second).
|
||||
Thus there is no scripted one-shot command to register. The ``monitor`` subcommand is the
|
||||
script command to watch packets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,24 +25,24 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
@register
|
||||
class LiveFeedTool(Tool):
|
||||
"""Watch every packet stream in, newest first, and open any in the viewer."""
|
||||
"""Watch each packet as it arrives, newest first, and open any packet in the viewer."""
|
||||
|
||||
name = "livefeed"
|
||||
title = "Live feed"
|
||||
icon = "📰"
|
||||
help = "Every packet as it arrives, newest first"
|
||||
category = "Watch"
|
||||
order = 20 # right under the dashboard it was promoted out of
|
||||
order = 20 # directly below the dashboard, which it came out of
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the live feed; there are never parameters to collect.
|
||||
"""Run the live feed. It has no parameters to collect.
|
||||
|
||||
The screen presents everything itself and returns when dismissed, so
|
||||
returning ``None`` tells the menu the invocation is complete (the same
|
||||
The screen shows all its content itself, and it returns when the user leaves it.
|
||||
Thus the return value ``None`` tells the menu that the run is complete (the same
|
||||
pattern as the ``dashboard`` tool).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -53,20 +53,20 @@ class LiveFeedTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Nothing runs here: the feed lives inside :meth:`prompt_params`.
|
||||
"""Nothing runs here: the feed is in :meth:`prompt_params`.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
An empty :class:`ToolResult` (only reachable from a scripted call).
|
||||
An empty :class:`ToolResult` (only a scripted call comes here).
|
||||
"""
|
||||
return ToolResult(summary={})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — the feed is a live, menu-only screen.
|
||||
"""Register no CLI command, because the feed is a live screen for the menu only.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
+38
-35
@@ -1,17 +1,18 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``map`` tool: plot the mesh's located nodes on an OpenStreetMap terminal map.
|
||||
"""The ``map`` tool: plot the located nodes of the mesh on an OpenStreetMap terminal map.
|
||||
|
||||
Nodes that share their location in adverts are collected from the passive-monitor history
|
||||
(:meth:`~meshterm.persistence.repository.Repository.heard_nodes`), our own node is added when
|
||||
its position is known, and everything is drawn over a real street basemap rendered as Unicode
|
||||
braille (streets, rivers, place names — the same terminal-map idea as ``mapscii``).
|
||||
The tool collects the nodes that share their location in adverts from the passive-monitor
|
||||
history (:meth:`~meshterm.persistence.repository.Repository.heard_nodes`). It adds our node
|
||||
when its position is known. Then it draws all the nodes over a real street basemap,
|
||||
rendered as Unicode braille (streets, rivers, place names). This is the same terminal-map
|
||||
idea as ``mapscii``.
|
||||
|
||||
Menu-only: it opens a full-screen, pannable/zoomable map (see
|
||||
:mod:`meshterm.ui.map_screen`) and registers no CLI subcommand, because a map is a picture
|
||||
and the scripted CLI deals in facts (see :meth:`MapTool.register_cli`). Repeaters are
|
||||
prioritised over ordinary nodes: a distinct marker, drawn on top. The basemap is
|
||||
best-effort — with no network (and no cached tiles) the nodes are plotted on a blank grid
|
||||
instead, and the tool still works offline.
|
||||
Menu only: the tool opens a full-screen map that the user can pan and zoom (refer to
|
||||
:mod:`meshterm.ui.map_screen`). It registers no CLI subcommand, because a map is a picture,
|
||||
and the scripted CLI gives facts (refer to :meth:`MapTool.register_cli`). Repeaters have
|
||||
priority over ordinary nodes: they have a different marker, drawn on top. The basemap is a
|
||||
best effort. With no network (and no cached tiles), the tool plots the nodes on a blank
|
||||
grid, and it still works offline.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,15 +27,15 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
|
||||
def _fraction(ctx: AppContext, params: dict[str, Any]) -> float:
|
||||
"""How much of the mesh a map opens framed on: the flag if one was passed, else the preference.
|
||||
"""The fraction of the mesh that a new map frames: the flag if given, else the preference.
|
||||
|
||||
``--fraction`` is resolved here rather than as the Typer option's default because the
|
||||
options are declared at CLI *registration* time — before a context, and so before the
|
||||
preferences file has been read.
|
||||
``--fraction`` is resolved here, not as the default of the Typer option, because the
|
||||
options are declared when the CLI is registered. That occurs before a context exists,
|
||||
and thus before MeshTerm reads the preferences file.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: This invocation's parameters.
|
||||
ctx: The shared application context.
|
||||
params: The parameters of this run.
|
||||
|
||||
Returns:
|
||||
The fraction to frame.
|
||||
@@ -49,7 +50,7 @@ if TYPE_CHECKING:
|
||||
|
||||
@register
|
||||
class MapTool(Tool):
|
||||
"""Show the mesh's location-sharing nodes on a braille OpenStreetMap map."""
|
||||
"""Show the nodes of the mesh that share a location on a braille OpenStreetMap map."""
|
||||
|
||||
name = "map"
|
||||
title = "Map"
|
||||
@@ -59,16 +60,18 @@ class MapTool(Tool):
|
||||
order = 10
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Gather the located nodes and open the interactive map.
|
||||
"""Collect the located nodes and open the interactive map.
|
||||
|
||||
Menu-only (see :meth:`register_cli`), so there is one path through here.
|
||||
The tool is for the menu only (refer to :meth:`register_cli`), so this method has
|
||||
one path.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Optional ``fraction`` — how much of the mesh to open framed on.
|
||||
ctx: The shared application context.
|
||||
params: An optional ``fraction``: the part of the mesh to frame when the map
|
||||
opens.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing how many nodes were plotted.
|
||||
A :class:`ToolResult` with the number of plotted nodes.
|
||||
"""
|
||||
from ..ui.map_screen import open_map
|
||||
|
||||
@@ -93,25 +96,25 @@ class MapTool(Tool):
|
||||
},
|
||||
)
|
||||
|
||||
# -- marker gathering -------------------------------------------------------
|
||||
# -- the markers ------------------------------------------------------------
|
||||
|
||||
async def _gather(self, ctx: AppContext) -> list[MapMarker]:
|
||||
"""Collect every located node to plot (see :func:`gather_markers`)."""
|
||||
"""Collect each located node to plot (refer to :func:`gather_markers`)."""
|
||||
return await gather_markers(ctx)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — a map is a picture, and pictures are menu-only.
|
||||
"""Register no CLI command, because a map is a picture, and pictures are menu only.
|
||||
|
||||
Every other feature has a scripted face because its answer is a set of facts a
|
||||
script can act on. A map's answer is a *drawing*: braille cells whose meaning is
|
||||
their position on a grid and whose nodes are told apart by colour, which is
|
||||
exactly what the scripted CLI does not have (see :mod:`meshterm.ui.script`). A
|
||||
one-shot render there would be an unparseable block of glyphs, and stripping its
|
||||
colour to match the rest of the CLI would make it unreadable as well.
|
||||
Each other feature has a scripted face, because its answer is a set of facts that
|
||||
a script can use. The answer of a map is a drawing. Its braille cells get their
|
||||
meaning from their position on a grid, and colour tells its nodes apart. The
|
||||
scripted CLI does not have these (refer to :mod:`meshterm.ui.script`). A one-shot
|
||||
render on the CLI is a block of glyphs that no program can parse. If the render
|
||||
has no colour, as the rest of the CLI, a person cannot read it either.
|
||||
|
||||
The located nodes themselves are still scriptable — ``meshterm contacts`` lists
|
||||
every one of them, coordinates included.
|
||||
A script can still get the located nodes: ``meshterm contacts`` lists each of
|
||||
them, with their coordinates.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
+72
-66
@@ -1,19 +1,19 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``monitor`` tool: a bounded foreground capture of what the mesh is saying.
|
||||
"""The ``monitor`` tool: a foreground capture of the mesh traffic, for a limited time.
|
||||
|
||||
Passive monitoring records every advert and telemetry frame the companion overhears —
|
||||
with SNR, RSSI, and any shared location — to the database, building the longitudinal
|
||||
history that the map's packet counts and the nodes list read back. It transmits nothing;
|
||||
it only listens.
|
||||
Passive monitoring stores each advert and telemetry packet that the companion hears in the
|
||||
database, with its SNR, its RSSI, and any shared location. Over time, this makes the
|
||||
history that the packet counts of the map and the nodes list read. The tool transmits
|
||||
nothing. It only listens.
|
||||
|
||||
Recording is always on: the session-wide
|
||||
:class:`~meshterm.services.event_hub.EventHub` overhears every packet, and
|
||||
:class:`~meshterm.services.monitor_service.MonitorService` (``ctx.monitor``) writes them
|
||||
to history as one of its subscribers, from the moment the radio opens. In the menu the
|
||||
live packet counters show in the persistent header and the accumulated data surfaces
|
||||
through Nodes and Map, so there is no separate screen here — this tool is CLI-only:
|
||||
``meshterm monitor --seconds 60`` tails each overheard packet to the console and
|
||||
summarizes the window when it ends.
|
||||
MeshTerm always stores this history. The session-wide
|
||||
:class:`~meshterm.services.event_hub.EventHub` receives each packet, and
|
||||
:class:`~meshterm.services.monitor_service.MonitorService` (``ctx.monitor``) is one of its
|
||||
subscribers. From the time that the connection to the device opens, the service writes
|
||||
the packets to the history. In the menu, the live packet counters show in the header,
|
||||
which is always visible, and the stored data shows on Nodes and Map. Thus this tool has no
|
||||
screen, and it is CLI only. ``meshterm monitor --seconds 60`` prints each heard packet to
|
||||
the console, and it gives a summary of the window when the window ends.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,7 +37,7 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class MonitorTool(Tool):
|
||||
"""Capture overheard packets in the foreground for a bounded window (CLI only)."""
|
||||
"""Capture heard packets in the foreground for a limited time window (CLI only)."""
|
||||
|
||||
name = "monitor"
|
||||
title = "Monitor"
|
||||
@@ -45,18 +45,18 @@ class MonitorTool(Tool):
|
||||
help = "Capture overheard packets live for a while and summarize them"
|
||||
category = "Watch"
|
||||
order = 50
|
||||
menu_visible = False # recording is always on; in the menu the header/Nodes/Map show it
|
||||
menu_visible = False # always stored. In the menu, the header, Nodes, and Map show it
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run directly, without a logged ``runs`` row.
|
||||
|
||||
The capture's observations are recorded under the monitor service's own
|
||||
``monitor`` run, so wrapping this invocation in a second run row (as the base
|
||||
:meth:`Tool.execute` would) would double-log the session.
|
||||
The monitor service stores the observations of the capture under its own
|
||||
``monitor`` run. The base :meth:`Tool.execute` puts each run in a run row. A second
|
||||
run row for this run logs the session two times.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Parameters for this invocation.
|
||||
ctx: The shared application context.
|
||||
params: The parameters for this run.
|
||||
|
||||
Returns:
|
||||
The :class:`ToolResult` from :meth:`run`.
|
||||
@@ -64,29 +64,30 @@ class MonitorTool(Tool):
|
||||
return await self.run(ctx, params)
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Record overheard packets in the foreground for a bounded window.
|
||||
"""Store heard packets in the foreground for a limited time window.
|
||||
|
||||
Connects the device, ensures history recording and the event hub are running,
|
||||
and tails each overheard packet to the console until the window ends (or the
|
||||
user interrupts). Observations are persisted by the monitor service exactly as
|
||||
in an interactive session; this adds a live console view and a window-scoped
|
||||
heard-node summary on top.
|
||||
The method connects the device, and it makes sure that the history storage and
|
||||
the event hub run. Then it prints each heard packet to the console until the
|
||||
window ends (or until the user interrupts it). The monitor service stores the
|
||||
observations exactly as in an interactive session. This method adds a live
|
||||
console output, and a summary of the nodes that were heard in the window.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``seconds`` — how long to capture (``0``/``None`` = until Ctrl-C).
|
||||
ctx: The shared application context.
|
||||
params: ``seconds``: the duration of the capture (``0`` or ``None`` = until
|
||||
Ctrl-C).
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the window's packet and node counts.
|
||||
A :class:`ToolResult` with the packet count and the node count of the window.
|
||||
"""
|
||||
from ..ui import script
|
||||
|
||||
seconds = int(params.get("seconds") or 0)
|
||||
await ctx.device() # surface connection problems before announcing the capture
|
||||
await ctx.monitor.start() # register history recording before the hub pumps
|
||||
await ctx.device() # show a connection problem before the capture is announced
|
||||
await ctx.monitor.start() # register history storage before the hub sends events
|
||||
await ctx.events.start()
|
||||
# The announcement is about the run, not part of its answer, so it goes to stderr
|
||||
# and stays out of `meshterm monitor -s 60 > packets.txt`.
|
||||
# The announcement is about the run, and it is not part of the answer. Thus it goes
|
||||
# to stderr, and it stays out of `meshterm monitor -s 60 > packets.txt`.
|
||||
script.stderr_console().print(
|
||||
"monitoring" + (f" for {seconds}s" if seconds else " — press Ctrl-C to stop"),
|
||||
style="muted",
|
||||
@@ -112,8 +113,9 @@ class MonitorTool(Tool):
|
||||
"snr_db": obs.snr,
|
||||
"rssi_dbm": obs.rssi,
|
||||
"position": _position(obs.lat, obs.lon),
|
||||
# The region a flood was sent into, resolved against the names known
|
||||
# right now; a direct frame (or a class with no route) has none.
|
||||
# The region that a flood was sent into, found from the region names
|
||||
# that are known now. A direct packet (or a class with no route) has
|
||||
# no region.
|
||||
"scope": ctx.region_store.scope_of(obs.raw),
|
||||
"path": _relays(obs.path),
|
||||
}
|
||||
@@ -125,7 +127,7 @@ class MonitorTool(Tool):
|
||||
if seconds:
|
||||
await asyncio.sleep(seconds)
|
||||
else:
|
||||
await asyncio.Event().wait() # until Ctrl-C / cancellation
|
||||
await asyncio.Event().wait() # until Ctrl-C or cancellation
|
||||
except (KeyboardInterrupt, asyncio.CancelledError): # pragma: no cover - interactive
|
||||
pass
|
||||
finally:
|
||||
@@ -137,8 +139,9 @@ class MonitorTool(Tool):
|
||||
by_node.setdefault(obs.node, []).append(obs)
|
||||
nodes = [HeardNode.from_observations(node, group) for node, group in by_node.items()]
|
||||
nodes.sort(key=lambda n: n.last_seen, reverse=True)
|
||||
# The window is over, so its facts are worth saying — on stderr, where everything
|
||||
# about a run goes, keeping the packets a caller redirected the run for on their own.
|
||||
# The window is over, so its facts are useful. They go to stderr, where all the
|
||||
# information about a run goes. Thus the packets, which are the reason that the
|
||||
# caller redirected the output, stay alone on stdout.
|
||||
script.stderr_console().print(
|
||||
f"captured {len(seen)} packet{'' if len(seen) == 1 else 's'} "
|
||||
f"from {len(nodes)} node{'' if len(nodes) == 1 else 's'}"
|
||||
@@ -153,7 +156,7 @@ class MonitorTool(Tool):
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``monitor`` subcommand (the bounded foreground capture).
|
||||
"""Register the ``monitor`` subcommand (the foreground capture for a limited time).
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
@@ -170,17 +173,18 @@ class MonitorTool(Tool):
|
||||
|
||||
|
||||
def _position(lat: float | None, lon: float | None) -> Position | None:
|
||||
"""A reception's shared position, or ``None`` where the packet carried none."""
|
||||
"""The shared position of a reception, or ``None`` if the packet had no position."""
|
||||
return Position(lat, lon) if lat is not None and lon is not None else None
|
||||
|
||||
|
||||
def _relays(path: str | None) -> list[str] | None:
|
||||
"""A packet's relay chain as hashes, in propagation order.
|
||||
"""The relay chain of a packet as hashes, in the order that the packet went through.
|
||||
|
||||
Hashes rather than the shared node shape, and that is the honest answer: nothing
|
||||
resolves a relay to a node at reception time, so a node object per hop would be four
|
||||
``null``s wrapped round a hash. ``[]`` is a direct reception (zero hops); ``None``
|
||||
means the packet class carries no path at all, which is a different fact.
|
||||
The function returns hashes instead of the shared node shape, and that is the correct
|
||||
answer. At reception time, nothing finds the node for a relay. Thus a node object for
|
||||
each hop has only four ``null`` values around a hash. ``[]`` is a direct reception
|
||||
(zero hops). ``None`` means that the packet class has no path, which is a different
|
||||
fact.
|
||||
"""
|
||||
if path is None:
|
||||
return None
|
||||
@@ -188,14 +192,14 @@ def _relays(path: str | None) -> list[str] | None:
|
||||
|
||||
|
||||
def _live_packets() -> Listing:
|
||||
"""The shape the live capture streams: one record per packet, as it lands.
|
||||
"""The shape that the live capture streams: one record for each packet, when it arrives.
|
||||
|
||||
``TIME`` is absolute where a listing's times are ages, and for the reason the whole
|
||||
rule turns on: every row of a live tail would read ``now``. ``SCOPE`` says which region
|
||||
a flood was sent into (:func:`~meshterm.ui.fields.scope`), ``null`` in the document for
|
||||
a frame that has none. The **name goes last**, so
|
||||
the one field with no width cannot push a lane — which is what finally let the two
|
||||
streams have columns at all, and with them the quoting could go.
|
||||
``TIME`` is an absolute time, but the times of a listing are usually ages. The reason
|
||||
is the base of that rule: in a live output, an age shows ``now`` in each row. ``SCOPE``
|
||||
gives the region that a flood was sent into (:func:`~meshterm.ui.fields.scope`). In
|
||||
the document, it is ``null`` for a packet that has no scope. The **name goes last**,
|
||||
so the only field with no width cannot push a lane. This change finally let the two
|
||||
streams have columns, and with the columns, the quoting was no longer necessary.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
@@ -215,16 +219,17 @@ def _live_packets() -> Listing:
|
||||
columns=(
|
||||
pin(fields.instant("observed_at", "TIME"), 25),
|
||||
node,
|
||||
# The packet class, which the plain stream has never had room for. New
|
||||
# surface: the simulator does not exercise every class, so a consumer should
|
||||
# treat an unfamiliar word as a word rather than an error.
|
||||
# The packet class. The plain stream never had space for it. This field is new,
|
||||
# and the simulator does not make each class. Thus a consumer must read an
|
||||
# unfamiliar word as a word, not as an error.
|
||||
fields.hidden("kind"),
|
||||
pin(fields.snr("snr_db", "SNR_DB"), 6),
|
||||
pin(fields.decimal("rssi_dbm", "RSSI_DBM", ".0f"), 8),
|
||||
pin(fields.position(), 19),
|
||||
# The flood's scope — a region name, ``unknown`` or ``unscoped``, ``-`` for a
|
||||
# frame with none. Pinned to hold the two words whole; a long region name
|
||||
# overruns and pushes the row right, which is why NAME still goes last.
|
||||
# The scope of the flood: a region name, ``unknown``, or ``unscoped``, and ``-``
|
||||
# for a packet with no scope. The width is pinned to hold the two words
|
||||
# complete. A long region name overruns and pushes the row to the right, so
|
||||
# NAME still goes last.
|
||||
pin(fields.scope(), 10),
|
||||
fields.hidden("path"),
|
||||
),
|
||||
@@ -233,18 +238,19 @@ def _live_packets() -> Listing:
|
||||
|
||||
|
||||
def _heard(heard: list[HeardNode]) -> Listing:
|
||||
"""The capture window's per-node summary: what each node did over the whole window.
|
||||
"""A summary of the capture window for each node: what the node did in the whole window.
|
||||
|
||||
The aggregate the live stream cannot give — a count, a median, a best — one record per
|
||||
node heard, most recently heard first.
|
||||
The summary gives the aggregates that the live stream cannot give (a count, a median,
|
||||
a best value). It has one record for each heard node, and the most recently heard
|
||||
node is first.
|
||||
|
||||
Drawn **for a person only**. Every figure in it is computable from the records that
|
||||
scrolled past above it, and emitting it as a second *shape* of line in the middle of an
|
||||
otherwise homogeneous NDJSON stream would cost every consumer a discriminator it would
|
||||
never otherwise need.
|
||||
It is drawn **for a person only**. A program can calculate each value in it from the
|
||||
records above it. The NDJSON stream has lines of only one shape. If the summary was a
|
||||
second shape of line in that stream, each consumer must have a discriminator, which
|
||||
no consumer needs for the other lines.
|
||||
|
||||
Args:
|
||||
heard: Aggregated per-node statistics for the window.
|
||||
heard: The aggregated statistics of each node for the window.
|
||||
|
||||
Returns:
|
||||
The listing.
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``preferences`` tool: how MeshTerm itself behaves.
|
||||
"""The ``preferences`` tool: the behaviour of MeshTerm itself.
|
||||
|
||||
Interactively it opens the Preferences page (see :mod:`meshterm.ui.preferences`), which
|
||||
stages changes and hands them back here to write. On the CLI it exposes the same
|
||||
preferences as ``show`` / ``get`` / ``set`` / ``reset``, so a value can be changed from a
|
||||
shell — or from a script setting a machine up — without launching the full-screen session.
|
||||
In the menu, the tool opens the Preferences page (refer to :mod:`meshterm.ui.preferences`).
|
||||
The page stages the changes and returns them to this tool, which writes them. On the CLI,
|
||||
the tool gives the same preferences through ``show``, ``get``, ``set``, and ``reset``.
|
||||
Thus a user can change a value from a shell, and a script can change it when it sets up a
|
||||
machine, without the full-screen session.
|
||||
|
||||
Everything funnels through :meth:`PreferencesTool.run`, which applies a list of operations
|
||||
and saves the file once at the end: one write per invocation, whether it came from the page
|
||||
staging eleven changes or from a single ``preferences set``.
|
||||
All changes go through :meth:`PreferencesTool.run`. It applies a list of operations and
|
||||
saves the file one time at the end. Thus each run writes the file one time. This is true
|
||||
for eleven changes that the page staged, and for one ``preferences set``.
|
||||
|
||||
This is deliberately the *app's* tool, not the radio's. It reads nothing from the
|
||||
companion, transmits nothing, and works with no device attached at all — which is why it
|
||||
leads the **This app** section (the third owner, after this node and other nodes) rather
|
||||
than sitting beside Device config.
|
||||
This tool is the tool of the app, not of the device, on purpose. It reads nothing from the
|
||||
companion, it transmits nothing, and it works with no device connected. For this reason,
|
||||
it is the first row of the **This app** section (the third owner, after this node and
|
||||
other nodes), and it is not next to Device config.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,24 +40,24 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class PreferencesTool(Tool):
|
||||
"""View and change MeshTerm's own preferences, saved to ``preferences.toml``."""
|
||||
"""Show and change the preferences of MeshTerm, which are saved to ``preferences.toml``."""
|
||||
|
||||
name = "preferences"
|
||||
title = "Preferences"
|
||||
icon = "⚙"
|
||||
help = "How MeshTerm behaves — startup, sending, history, …"
|
||||
category = "This app"
|
||||
order = 5 # leads the section: the one row there that changes MeshTerm, not describes it
|
||||
order = 5 # first in the section. Its row changes MeshTerm, and the other rows describe it
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Open the Preferences page and collect the changes it staged.
|
||||
"""Open the Preferences page and collect the changes that it staged.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
``{"ops": [("set", key, value), …]}`` to write, or ``None`` if the reader left
|
||||
with nothing staged.
|
||||
``{"ops": [("set", key, value), …]}`` to write, or ``None`` if the user left
|
||||
with no staged changes.
|
||||
"""
|
||||
from ..ui.preferences import edit_preferences
|
||||
|
||||
@@ -66,22 +67,22 @@ class PreferencesTool(Tool):
|
||||
return {"ops": [("set", key, value) for key, value in staged.items()]}
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Apply a list of preference operations, saving the file once if anything changed.
|
||||
"""Apply a list of preference operations. If a value changed, save the file one time.
|
||||
|
||||
Operations are ``("show",)``, ``("get", key)``, ``("set", key, value)``, and
|
||||
``("reset",)``. They run in order, so a scripted ``set`` after a ``reset`` lands on
|
||||
top of the defaults rather than under them.
|
||||
The operations are ``("show",)``, ``("get", key)``, ``("set", key, value)``, and
|
||||
``("reset",)``. They run in order. Thus a scripted ``set`` after a ``reset``
|
||||
changes the value from its default, and the ``reset`` does not remove that change.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``ops`` — the operations to perform.
|
||||
ctx: The shared application context.
|
||||
params: ``ops``: the operations to do.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` counting the preferences changed.
|
||||
A :class:`ToolResult` with the number of changed preferences.
|
||||
|
||||
Raises:
|
||||
PreferenceError: If a key is unknown or a value fails its spec — reported
|
||||
cleanly by the CLI rather than as a traceback.
|
||||
PreferenceError: If a key is unknown, or if a value does not agree with its
|
||||
spec. The CLI reports this as a clear error, not as a traceback.
|
||||
"""
|
||||
from ..services import consolefont
|
||||
from ..ui.preferences import preferences_table
|
||||
@@ -101,9 +102,9 @@ class PreferencesTool(Tool):
|
||||
else:
|
||||
ctx.ui.show(preferences_table(prefs, ctx.console.width))
|
||||
elif action == "get":
|
||||
# The bare value and nothing else — the caller named the key, and
|
||||
# whether it is overridden is what `show`'s DEFAULT lane answers. The
|
||||
# document keeps both, since a parser has no lane to read them off.
|
||||
# Only the bare value, because the caller named the key. The DEFAULT lane
|
||||
# of `show` tells if the value is overridden. The document keeps both,
|
||||
# because a parser has no lane to read them from.
|
||||
spec = get_spec(op[1])
|
||||
if scripted:
|
||||
blocks.append(_one(prefs, spec))
|
||||
@@ -128,16 +129,18 @@ class PreferencesTool(Tool):
|
||||
if changes:
|
||||
prefs.save()
|
||||
if any(c["key"] == "weekly_flood_advert" for c in applied):
|
||||
# Switching the weekly advert on starts its week rather than sending, so the
|
||||
# instant is recorded as it happens — from the page and a shell alike — and
|
||||
# not whenever the scheduler next looks (see meshterm.core.advert_store).
|
||||
# When the user switches the weekly advert on, its week starts, but nothing is
|
||||
# sent. Thus MeshTerm stores the instant when it occurs (from the page and from
|
||||
# a shell), and not when the scheduler next looks (refer to
|
||||
# meshterm.core.advert_store).
|
||||
ctx.advert_store.set_enabled(bool(prefs.weekly_flood_advert))
|
||||
if not scripted and any(c["key"] == consolefont.PREFERENCE_KEY for c in applied):
|
||||
# The one preference whose effect is outside the app: the console's font is
|
||||
# the console's, so it takes hold now rather than next launch. The kernel
|
||||
# sends SIGWINCH on a VT font change, so prompt_toolkit repaints the whole
|
||||
# frame at the new row count by itself. Menu-only — a scripted run was typed
|
||||
# into a console it does not own (see meshterm.services.consolefont).
|
||||
# The only preference that has an effect outside the app. The font belongs to
|
||||
# the console, so the change occurs now, not at the next start. The kernel
|
||||
# sends SIGWINCH when the font of a VT changes. Thus prompt_toolkit paints the
|
||||
# whole frame again at the new row count by itself. This occurs only in the
|
||||
# menu, because a user typed a scripted run into a console that the run does
|
||||
# not own (refer to meshterm.services.consolefont).
|
||||
consolefont.apply(prefs.get(consolefont.PREFERENCE_KEY))
|
||||
if scripted and any(op[0] in ("set", "reset") for op in ops):
|
||||
blocks.append(_written(applied, prefs))
|
||||
@@ -203,20 +206,20 @@ __all__ = ["PreferencesTool", "PreferenceError"]
|
||||
|
||||
|
||||
def _script_value(spec: PrefSpec, value: Any) -> str:
|
||||
"""A preference's value in the form ``preferences set`` accepts back.
|
||||
"""The value of a preference, in the form that ``preferences set`` accepts.
|
||||
|
||||
:func:`~meshterm.core.preferences.format_value` writes for the page: a number carries
|
||||
its unit (``5 s``), so a bare figure in the VALUE lane still says what it counts. That
|
||||
unit is exactly what :func:`~meshterm.core.preferences.parse_value` will not take
|
||||
back, so the scripted dump drops it. Booleans keep ``on``/``off`` and an enum keeps
|
||||
its own key, both of which do round-trip.
|
||||
:func:`~meshterm.core.preferences.format_value` writes for the page: a number has its
|
||||
unit (``5 s``), so that a bare number in the VALUE lane tells what it counts. But
|
||||
:func:`~meshterm.core.preferences.parse_value` does not accept that unit, so the
|
||||
scripted output removes it. A boolean keeps ``on`` or ``off``, and an enum keeps its
|
||||
own key. Both of these round-trip.
|
||||
|
||||
Args:
|
||||
spec: The preference the value belongs to.
|
||||
spec: The preference that the value is for.
|
||||
value: Its current value.
|
||||
|
||||
Returns:
|
||||
The scripted rendering.
|
||||
The value as text for a script.
|
||||
"""
|
||||
if spec.value_type == "bool":
|
||||
return "on" if value else "off"
|
||||
@@ -228,9 +231,10 @@ def _script_value(spec: PrefSpec, value: Any) -> str:
|
||||
def _row(prefs: Preferences, spec: PrefSpec) -> dict[str, Any]:
|
||||
"""One preference as a report row, in the shared setting shape.
|
||||
|
||||
``overridden`` is the fact the plain face makes a reader derive by comparing two
|
||||
columns; a document that carried the same two numbers and left the comparison to the
|
||||
consumer would be handing over homework it has the answer to.
|
||||
On the plain face, the user compares two columns to find if a value is overridden.
|
||||
``overridden`` gives this fact directly. If a document gives the same two numbers and
|
||||
lets the consumer compare them, the consumer must do work for which the document
|
||||
already has the answer.
|
||||
"""
|
||||
from ..ui.fields import Rendered
|
||||
|
||||
@@ -239,8 +243,8 @@ def _row(prefs: Preferences, spec: PrefSpec) -> dict[str, Any]:
|
||||
"key": spec.key,
|
||||
"value": Rendered(value, _script_value(spec, value)),
|
||||
"type": spec.value_type,
|
||||
# The reader's word for an enum's own key — never what `set` takes, which is the
|
||||
# key itself and rides in `value`.
|
||||
# The word that the user sees for the key of an enum. It is never what `set` takes:
|
||||
# `set` takes the key itself, which is in `value`.
|
||||
"label": (spec.choices or {}).get(value) if spec.value_type == "enum" else None,
|
||||
"redacted": False,
|
||||
"default": Rendered(spec.default, _script_value(spec, spec.default)),
|
||||
@@ -250,7 +254,7 @@ def _row(prefs: Preferences, spec: PrefSpec) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _columns() -> tuple:
|
||||
"""The preference row's columns, shared by ``show`` and ``get``."""
|
||||
"""The columns of a preference row, which ``show`` and ``get`` share."""
|
||||
from ..ui import fields
|
||||
|
||||
return (
|
||||
@@ -266,13 +270,13 @@ def _columns() -> tuple:
|
||||
|
||||
|
||||
def _listing(prefs: Preferences) -> Listing:
|
||||
"""Every preference, its value, its built-in default, and what it is for.
|
||||
"""Each preference, with its value, its built-in default, and its purpose.
|
||||
|
||||
``DESCRIPTION`` comes straight from :attr:`PrefSpec.help` — the text is already
|
||||
written, one short line each, and as the *last* column it can never disturb an
|
||||
alignment or wrap. It used to be cut for parser hygiene, which is a bargain the plain
|
||||
face no longer has to make: a listing is read by a person now, and a person choosing a
|
||||
preference is exactly who that sentence was written for.
|
||||
``DESCRIPTION`` comes directly from :attr:`PrefSpec.help`. That text is already
|
||||
written, with one short line for each preference. Because it is the last column, it
|
||||
can never break an alignment or cause a wrap. Before, the listing removed it, to keep
|
||||
the output clean for a parser. The plain face does not have to do that now: a person
|
||||
reads the listing, and the sentence was written for a person who selects a preference.
|
||||
|
||||
Args:
|
||||
prefs: The preference set to report.
|
||||
@@ -291,7 +295,7 @@ def _listing(prefs: Preferences) -> Listing:
|
||||
|
||||
|
||||
def _one(prefs: Preferences, spec: PrefSpec) -> Facts:
|
||||
"""One preference: the bare value plain, the whole setting object in the document."""
|
||||
"""One preference: the bare value on the plain face, the full setting object in the document."""
|
||||
from ..ui.report import BARE, Facts
|
||||
|
||||
return Facts(
|
||||
@@ -304,11 +308,11 @@ def _one(prefs: Preferences, spec: PrefSpec) -> Facts:
|
||||
|
||||
|
||||
def _written(applied: list[dict[str, Any]], prefs: Preferences) -> Facts:
|
||||
"""What ``set`` or ``reset`` changed — nothing plain, a record for whoever wants one.
|
||||
"""What ``set`` or ``reset`` changed: nothing on the plain face, and a record for a log.
|
||||
|
||||
The plain face says it in the exit status and in the acknowledgement on stderr, which
|
||||
is the whole answer for a person. A caller managing a machine's configuration wants to
|
||||
know *what moved*, and had no way to ask.
|
||||
The plain face gives the result in the exit status and in the acknowledgement on
|
||||
stderr. For a person, that is the whole answer. A caller that manages the setup of a
|
||||
machine wants to know what changed, and before, it had no way to ask.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Column, Facts
|
||||
|
||||
+62
-60
@@ -1,15 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The Trophy case tool: the record-setting walks the trace tools have turned up.
|
||||
"""The Trophy case tool: the record-setting walks that the trace tools found.
|
||||
|
||||
The menu face opens the browser (:mod:`meshterm.ui.records_screen`): every discipline's
|
||||
records — longest distance, farthest node, most nodes (with and without revisits),
|
||||
weakest surviving link, biggest loop — each under its own description, opened for their
|
||||
full stats, re-walked in Trace path, or deleted. Records are *earned* on the trace
|
||||
screens, where every walk that comes home is scored and offered to the boards (see
|
||||
:mod:`meshterm.services.records`); this tool never transmits.
|
||||
The menu face opens the browser (:mod:`meshterm.ui.records_screen`). It shows the records
|
||||
of each discipline: longest distance, farthest node, most nodes (with and without
|
||||
revisits), weakest link that survived, and biggest loop. Each discipline has its own
|
||||
description. The user can open a record to see all its stats, walk it again in Trace
|
||||
path, or delete it. The records are earned on the trace screens: each walk that comes
|
||||
back is scored and offered to the boards (refer to :mod:`meshterm.services.records`). This
|
||||
tool never transmits.
|
||||
|
||||
The CLI face prints the stored boards: ``meshterm records`` reads the tables so a script
|
||||
(or a curious shell) can see the standings without a device attached.
|
||||
The CLI face prints the stored boards. ``meshterm records`` reads the tables, so that a
|
||||
script (or a user at a shell) can see the standings without a connected device.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,7 +27,7 @@ from ..services.records import CATEGORIES, CATEGORY_BY_ID, Category
|
||||
from ..ui.script import NONE
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
#: The hash widths a record can be set at: MeshCore's path hashes are 1, 2 or 4 bytes.
|
||||
#: The hash widths at which a record can be set: MeshCore path hashes are 1, 2, or 4 bytes.
|
||||
WIDTHS = (1, 2, 4)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
@@ -37,24 +38,24 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class TrophyCaseTool(Tool):
|
||||
"""The record-setting mesh walks the trace tools scored, browsed or listed."""
|
||||
"""The record-setting mesh walks that the trace tools scored, to browse or to list."""
|
||||
|
||||
name = "records"
|
||||
title = "Trophy case"
|
||||
icon = "🏆"
|
||||
help = "Record-setting walks, scored from every trace"
|
||||
category = "Explore"
|
||||
order = 40 # what the two walks above it score into
|
||||
order = 40 # the two walks above it put their scores here
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Open the browser; returning ``None`` completes the invocation with no run row.
|
||||
"""Open the browser. The return value ``None`` completes the run with no run row.
|
||||
|
||||
The screen reads stored records and transmits nothing (and logs no rows of its
|
||||
own), so it lives in :meth:`prompt_params` and needs no logged run — the mesh walk /
|
||||
dashboard pattern.
|
||||
The screen reads stored records and transmits nothing (and it logs no rows of its
|
||||
own). Thus it is in :meth:`prompt_params`, and it does not need a logged run. The
|
||||
mesh walk and the dashboard use the same pattern.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -65,11 +66,11 @@ class TrophyCaseTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Print the stored boards — only reachable from a scripted call (never transmits).
|
||||
"""Print the stored boards. Only a scripted call comes here (this never transmits).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``category``/``width`` filters and the injected ``_run_id``.
|
||||
ctx: The shared application context.
|
||||
params: The ``category`` and ``width`` filters, and the injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the record count.
|
||||
@@ -83,12 +84,12 @@ class TrophyCaseTool(Tool):
|
||||
def _show_records(
|
||||
self, ctx: AppContext, *, category: str | None, width: int | None
|
||||
) -> ToolResult:
|
||||
"""State the stored record boards (no device, no transmissions).
|
||||
"""Give the stored record boards (with no device, and with no transmission).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
category: Only this category id, or ``None`` for every discipline.
|
||||
width: Only this hash width, or ``None`` for every width.
|
||||
ctx: The shared application context.
|
||||
category: Only this category id, or ``None`` for all the disciplines.
|
||||
width: Only this hash width, or ``None`` for all the widths.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the record count.
|
||||
@@ -98,8 +99,8 @@ class TrophyCaseTool(Tool):
|
||||
from ..ui.report import Listing
|
||||
|
||||
wanted = [CATEGORY_BY_ID[category]] if category in CATEGORY_BY_ID else CATEGORIES
|
||||
# Names come from stored history alone — no contacts, because this command reads
|
||||
# the database and must work with no radio attached at all.
|
||||
# The names come only from the stored history, not from the contacts, because this
|
||||
# command reads the database. It must work with no device connected.
|
||||
resolve = trace_runner.make_node_resolver(None, ctx.repo.node_names())
|
||||
|
||||
rows: list[dict] = []
|
||||
@@ -125,19 +126,19 @@ class TrophyCaseTool(Tool):
|
||||
key="records",
|
||||
columns=(
|
||||
fields.word("category", "CATEGORY"),
|
||||
# The contract's word for the concept. The plain heading stays WIDTH,
|
||||
# which is what a column of 1/2/4 reads as.
|
||||
# The word of the contract for this concept. The plain heading stays
|
||||
# WIDTH, because a column of 1, 2, or 4 reads as a width.
|
||||
fields.integer("hash_bytes", "WIDTH"),
|
||||
_score_column(),
|
||||
fields.word("unit", "UNIT"),
|
||||
# `>=273.0` is not a number, and a consumer comparing scores must be able
|
||||
# to see the qualifier without string-matching a prefix off its own data.
|
||||
# `>=273.0` is not a number. A consumer that compares scores must see the
|
||||
# qualifier without a string match on a prefix of its own data.
|
||||
fields.hidden("lower_bound"),
|
||||
fields.when("recorded_at", "RECORDED"),
|
||||
fields.word("version", "VERSION"),
|
||||
# The transmitted spec, hop-aligned with the route beside it. It has no
|
||||
# column — a route line already runs off the right — but it is what a
|
||||
# caller re-walks with, so the document carries it.
|
||||
# The transmitted spec, aligned hop for hop with the route next to it. It
|
||||
# has no column, because a route line already goes past the right edge.
|
||||
# But a caller uses it to walk the path again, so the document holds it.
|
||||
fields.hidden("path"),
|
||||
fields.route(),
|
||||
),
|
||||
@@ -152,7 +153,7 @@ class TrophyCaseTool(Tool):
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``records`` subcommand (read-only record listing).
|
||||
"""Register the ``records`` subcommand (a read-only listing of the records).
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
@@ -177,9 +178,9 @@ class TrophyCaseTool(Tool):
|
||||
) -> None:
|
||||
tool_params: dict[str, Any] = {}
|
||||
if category:
|
||||
# An unknown id used to select *every* discipline, so a misspelled
|
||||
# `--category long_hual` came back as "no records" — exit 5, which is
|
||||
# exactly what a real empty result looks like. A closed set refuses.
|
||||
# Before, an unknown id selected all the disciplines. Thus a misspelled
|
||||
# `--category long_hual` returned "no records" with exit 5, which is the
|
||||
# same as a real empty result. A closed set refuses an unknown id.
|
||||
if category not in CATEGORY_BY_ID:
|
||||
choices = ", ".join(CATEGORY_BY_ID)
|
||||
raise typer.BadParameter(
|
||||
@@ -187,9 +188,9 @@ class TrophyCaseTool(Tool):
|
||||
)
|
||||
tool_params["category"] = category
|
||||
if width is not None:
|
||||
# The same closed set as --category, for the same reason: `--width 3`
|
||||
# found nothing and exited 5, indistinguishable from an empty database,
|
||||
# and `--width 0` was falsy and so quietly listed every width.
|
||||
# A closed set, as for --category, for the same reason. `--width 3` found
|
||||
# nothing and exited 5, which was the same as an empty database. And
|
||||
# `--width 0` was falsy, so it listed all the widths with no warning.
|
||||
if width not in WIDTHS:
|
||||
choices = ", ".join(map(str, WIDTHS))
|
||||
raise typer.BadParameter(f"--width must be one of: {choices} (got {width})")
|
||||
@@ -199,17 +200,17 @@ class TrophyCaseTool(Tool):
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Score:
|
||||
"""A record's score, and the one thing about it a bare number cannot carry.
|
||||
"""The score of a record, and the one fact about it that a bare number cannot hold.
|
||||
|
||||
``format_score`` writes ``273.0 km`` for a reader; the unit is its own column here so
|
||||
the ``SCORE`` column is one comparable number per row. What has to travel *with* the
|
||||
number is the ``>=`` on a Longest-distance walk whose kilometre total is incomplete —
|
||||
some hop on it has no known position, so the distance is a floor rather than a
|
||||
measurement, and dropping the qualifier would turn a lower bound into a claim.
|
||||
``format_score`` writes ``273.0 km`` for a person. Here the unit has its own column,
|
||||
so that the ``SCORE`` column has one comparable number in each row. But one thing must
|
||||
stay with the number: the ``>=`` on a Longest-distance walk whose kilometre total is
|
||||
not complete. A hop on that walk has no known position, so the distance is a minimum,
|
||||
not a measurement. Without the qualifier, a lower bound becomes a claim.
|
||||
|
||||
The plain face wears the prefix; the document keeps the number a number and says
|
||||
``lower_bound`` beside it, because a consumer comparing scores cannot be asked to
|
||||
string-match a prefix off the front of its own data.
|
||||
The plain face shows the prefix. The document keeps the number as a number, and it
|
||||
gives ``lower_bound`` next to it. The reason is that a consumer that compares scores
|
||||
must not have to match a prefix at the start of its own data.
|
||||
"""
|
||||
|
||||
value: float
|
||||
@@ -218,7 +219,7 @@ class _Score:
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
"""The score as the SCORE column prints it, qualifier and all."""
|
||||
"""The score as the SCORE column prints it, with the qualifier."""
|
||||
if self.category.unit == "nodes":
|
||||
drawn = str(int(self.value))
|
||||
elif self.category.unit == "dB":
|
||||
@@ -229,7 +230,7 @@ class _Score:
|
||||
|
||||
|
||||
def _score_column() -> Column:
|
||||
"""The SCORE column: the qualified figure plain, the bare number in the document."""
|
||||
"""The SCORE column: the qualified number on the plain face, the bare number in a document."""
|
||||
from ..ui.report import Column, Lane
|
||||
|
||||
return Column(
|
||||
@@ -246,22 +247,23 @@ def _score_column() -> Column:
|
||||
|
||||
|
||||
def _route(record: DiscoveredPath, resolve: Callable[[str], str | None]) -> list[NodeRef]:
|
||||
"""A record's walk as the shared route shape.
|
||||
"""The walk of a record, as the shared route shape.
|
||||
|
||||
Each hop is named where history knows the node and carries the hash it was actually
|
||||
transmitted at — the spec's own hop, at this record's width — so the line can be read
|
||||
against the ``path`` a re-walk would take. Where the two lists disagree in length the
|
||||
node id stands in, which is the only identity that hop has.
|
||||
Each hop has a name if the history knows the node. Each hop also has the hash with
|
||||
which it was transmitted (the hop of the spec itself, at the width of this record).
|
||||
Thus a person can compare the line with the ``path`` that a new walk uses. If the
|
||||
two lists have different lengths, the node id is used instead. That id is the only
|
||||
identity that the hop has.
|
||||
|
||||
Our own node never appears in a record's walk: a discovery is scored on what it
|
||||
reached, and the two ends of it are somebody else's.
|
||||
Our node is never in the walk of a record. A discovery is scored on what it reached,
|
||||
and its two ends are the nodes of other persons.
|
||||
|
||||
Args:
|
||||
record: The record whose walk to render.
|
||||
resolve: Maps a node id to a friendly name, or ``None`` when unknown.
|
||||
resolve: Gives the friendly name of a node id, or ``None`` if the name is unknown.
|
||||
|
||||
Returns:
|
||||
The hops in propagation order.
|
||||
The hops, in the order that the packet went through them.
|
||||
"""
|
||||
from ..ui.fields import NodeRef
|
||||
|
||||
|
||||
+30
-25
@@ -1,23 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``regions`` command: ask a repeater which regions it relays floods for.
|
||||
"""The ``regions`` command: ask a repeater for which regions it relays floods.
|
||||
|
||||
``meshterm regions <repeater>`` sends the anonymous regions request (firmware 1.12+, no
|
||||
login) and prints the answer — the regions it relays scoped floods for, and whether it also
|
||||
relays unscoped ones. One request, one transmission, per invocation: the repeater
|
||||
rate-limits the question, and nothing here retries it.
|
||||
``meshterm regions <repeater>`` sends the anonymous regions request (firmware 1.12 or
|
||||
later, no login) and prints the answer. The answer gives the regions for which the
|
||||
repeater relays scoped floods, and it tells if the repeater also relays unscoped floods.
|
||||
Each run sends one request, which is one transmission. The repeater limits the rate of
|
||||
this question, and nothing here tries it again.
|
||||
|
||||
It is a command-line face only. In the menu the same question lives on a repeater's node
|
||||
page (*Ask which regions it carries*), beside the answer it last gave, so there is no menu
|
||||
row for it here.
|
||||
This tool has only a command-line face. In the menu, the same question is on the node page
|
||||
of a repeater ("Ask which regions it carries"), next to the last answer of that repeater.
|
||||
Thus the menu has no row for this tool.
|
||||
|
||||
The answer is learned into the region store either way, exactly as the node page learns it,
|
||||
so a scoped flood heard afterwards can be traced back to a region this repeater named.
|
||||
In both cases, MeshTerm adds the answer to the region store, exactly as the node page does.
|
||||
Thus MeshTerm can trace a scoped flood that it hears later back to a region that this
|
||||
repeater named.
|
||||
|
||||
Exit status, per the CLI's rules: ``0`` when it answered with anything (unscoped floods
|
||||
alone are an answer), ``5`` when it answered and named nothing at all — it relays no floods
|
||||
— ``2`` for a contact that does not exist or is known not to be a repeater (nothing was
|
||||
sent), and ``4`` when it never answered, which is what a repeater out of direct reach does:
|
||||
the request is only answered when it arrives from a neighbour or over a known route.
|
||||
The exit status, by the rules of the CLI:
|
||||
|
||||
- ``0`` if the repeater answered with any value (only unscoped floods is also an answer).
|
||||
- ``5`` if it answered and named nothing (it relays no floods).
|
||||
- ``2`` for a contact that does not exist, or that is known not to be a repeater (nothing
|
||||
was sent).
|
||||
- ``4`` if it never answered. A repeater that is out of direct reach does this, because it
|
||||
answers the request only when the request comes from a neighbour or over a known route.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -52,16 +57,16 @@ class RegionsTool(Tool):
|
||||
"""Send the regions request to one repeater and report its answer.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``node``, the repeater's contact name.
|
||||
ctx: The shared application context.
|
||||
params: ``node``: the contact name of the repeater.
|
||||
|
||||
Returns:
|
||||
The answer as a report; ``NO_RESULT`` when it named nothing.
|
||||
The answer as a report. ``NO_RESULT`` if the repeater named nothing.
|
||||
|
||||
Raises:
|
||||
typer.BadParameter: For an unknown contact, or one known not to be a repeater —
|
||||
both decided before anything is sent.
|
||||
DeviceCommandError: When the repeater never answered.
|
||||
typer.BadParameter: For an unknown contact, or for a contact that is known not
|
||||
to be a repeater. The method finds both before it sends anything.
|
||||
DeviceCommandError: If the repeater never answered.
|
||||
"""
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
@@ -102,11 +107,11 @@ class RegionsTool(Tool):
|
||||
|
||||
|
||||
def _answer(node: Contact, unscoped: bool, regions: list[str]) -> Facts:
|
||||
"""The repeater's answer, stated once for both faces.
|
||||
"""The answer of the repeater, given one time for both faces.
|
||||
|
||||
Three facts: who answered, whether it relays unscoped floods, and the regions it relays
|
||||
scoped floods for — the wildcard kept out of that list, since it names no region (see
|
||||
:func:`~meshterm.ui.fields.regions`).
|
||||
Three facts: which node answered, if it relays unscoped floods, and the regions for
|
||||
which it relays scoped floods. That list does not include the wildcard, because the
|
||||
wildcard names no region (refer to :func:`~meshterm.ui.fields.regions`).
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.fields import NodeRef
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``repeater-admin`` tool: set up remote repeaters and room servers over the mesh.
|
||||
|
||||
Interactively it opens the repeater-admin flow (see :mod:`meshterm.ui.repeater_admin`):
|
||||
pick a node (credentialed ones lead the list), log in with a remembered or prompted
|
||||
password, and land in a device-configuration-style editor speaking the node's text CLI —
|
||||
including the repeater-only knobs the local editor never had (TX delay, Direct TX delay,
|
||||
airtime factor, advert intervals) — plus one-shot actions (advert, clock sync, password,
|
||||
reboot) and the readline-style remote command line.
|
||||
In the menu, the tool opens the repeater-admin flow (refer to
|
||||
:mod:`meshterm.ui.repeater_admin`):
|
||||
|
||||
On the CLI it stays a scriptable one-shot: ``repeater-admin <node> <command…>`` logs in
|
||||
(remembered password, or ``--password``) and prints the node's reply — one transmission
|
||||
per invocation, the trace tool's rule.
|
||||
1. The user selects a node. The nodes with stored credentials are first in the list.
|
||||
2. The user logs in with a remembered password, or with a password that a prompt asks
|
||||
for.
|
||||
3. The user goes to an editor similar to Device config, which uses the text CLI of the
|
||||
node. The editor includes the settings that only a repeater has, which the local
|
||||
editor never had (TX delay, Direct TX delay, airtime factor, advert intervals). It also
|
||||
has one-shot actions (advert, clock sync, password, reboot) and a remote command line
|
||||
similar to readline.
|
||||
|
||||
On the CLI, the tool stays a one-shot command for scripts. ``repeater-admin <node>
|
||||
<command…>`` logs in (with the remembered password, or with ``--password``) and prints the
|
||||
reply of the node. Each run does one transmission, which is the rule of the trace tool.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,23 +36,23 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class RepeaterAdminTool(Tool):
|
||||
"""Configure a remote repeater/room server: settings, actions, and its raw CLI."""
|
||||
"""Configure a remote repeater or room server: settings, actions, and its raw CLI."""
|
||||
|
||||
name = "repeater-admin"
|
||||
title = "Repeater admin"
|
||||
icon = "🗼"
|
||||
help = "Run a remote repeater — settings and actions"
|
||||
category = "Other nodes"
|
||||
order = 10 # the remote sibling of the local config tools
|
||||
order = 10 # the remote equivalent of the local config tools
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the interactive flow; there are never parameters to collect.
|
||||
"""Run the interactive flow. It has no parameters to collect.
|
||||
|
||||
The flow presents everything itself (the same pattern as ``config``),
|
||||
so returning ``None`` tells the menu the invocation is complete.
|
||||
The flow shows all its content itself (the same pattern as ``config``). Thus the
|
||||
return value ``None`` tells the menu that the run is complete.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -61,21 +66,21 @@ class RepeaterAdminTool(Tool):
|
||||
"""Send one CLI command to a remote node and print its reply (scripted path).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``node`` (contact name), ``command`` (the CLI text), and an
|
||||
optional ``password`` overriding the remembered one.
|
||||
ctx: The shared application context.
|
||||
params: ``node`` (the contact name), ``command`` (the CLI text), and an
|
||||
optional ``password`` that replaces the remembered password.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` carrying the node's reply (or its absence).
|
||||
A :class:`ToolResult` with the reply of the node (or with no reply).
|
||||
"""
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
name = str(params["node"])
|
||||
node = next((c for c in contacts if c.name == name), None)
|
||||
# Both of these are the *argument* being wrong, and nothing has gone out over
|
||||
# the air when either fires — so they are usage errors (2), not device failures
|
||||
# (4), whose promise to a caller is that a retry is worth trying. `tx-optimize`
|
||||
# already answered the identical question this way for the identical condition.
|
||||
# In both cases, the argument is wrong, and nothing went out on the air. Thus they
|
||||
# are usage errors (2), not device failures (4). A device failure tells a caller
|
||||
# that a retry can help. `tx-optimize` already gave the same answer for the same
|
||||
# condition.
|
||||
if node is None:
|
||||
raise typer.BadParameter(f"unknown contact: {name!r}")
|
||||
|
||||
@@ -103,8 +108,9 @@ class RepeaterAdminTool(Tool):
|
||||
return ToolResult(
|
||||
report=(_answered(node, command, reply),),
|
||||
summary={"node": name, "command": command, "replied": reply is not None},
|
||||
# Silence is not failure — the command may well have landed — but there is
|
||||
# nothing to report, and a script waiting on output should know which it got.
|
||||
# No reply is not a failure, because the command possibly arrived. But there is
|
||||
# nothing to report, and a script that waits for output must know which result
|
||||
# it got.
|
||||
exit_code=exitcodes.OK if reply is not None else exitcodes.NO_RESULT,
|
||||
)
|
||||
|
||||
@@ -131,16 +137,16 @@ class RepeaterAdminTool(Tool):
|
||||
|
||||
|
||||
def _answered(node: Contact, command: str, reply: str | None) -> Facts:
|
||||
"""What a remote node said back.
|
||||
"""The reply of a remote node.
|
||||
|
||||
``reply`` is the node's own text, whole and verbatim — the plain face prints it bare
|
||||
(as text and never as markup, so a reply holding a square bracket is a reply holding a
|
||||
square bracket), and the document carries it raw, multi-line where the node sent
|
||||
several lines.
|
||||
``reply`` is the text of the node, complete and exact. The plain face prints it bare,
|
||||
as text and never as markup. Thus a square bracket in a reply stays a square bracket.
|
||||
The document holds it raw, with more than one line if the node sent more than one
|
||||
line.
|
||||
|
||||
It is deliberately **not parsed**. MeshTerm does not know the remote node's CLI
|
||||
grammar, and a document that pretended to would be inventing structure a consumer
|
||||
would then depend on.
|
||||
On purpose, it is **not parsed**. MeshTerm does not know the CLI grammar of the remote
|
||||
node. If the document parses it, the document invents a structure, and a consumer
|
||||
then depends on that structure.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.fields import NodeRef
|
||||
|
||||
+39
-37
@@ -1,13 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``rooms`` tool: the room servers your radio knows, and joining them.
|
||||
"""The ``rooms`` tool: the room servers that your device knows, and how to join them.
|
||||
|
||||
Interactively it opens the Rooms page (see :mod:`meshterm.ui.rooms`) — every room server
|
||||
the radio knows, joined ones first, each with a page to join it, log in again, open its
|
||||
board, or forget it. On the CLI it exposes ``list``, ``join`` and ``forget``.
|
||||
In the menu, the tool opens the Rooms page (refer to :mod:`meshterm.ui.rooms`). The page
|
||||
lists each room server that the device knows, with the joined rooms first. Each room has a
|
||||
page where the user can join it, log in again, open its board, or forget it. On the CLI,
|
||||
the tool gives ``list``, ``join``, and ``forget``.
|
||||
|
||||
A room's board is *read* in Chat, the way a channel's messages are; this tool owns
|
||||
everything to do with getting in, as the ``channels`` tool owns everything to do with
|
||||
configuring a slot.
|
||||
The user reads the board of a room in Chat, as for the messages of a channel. This tool
|
||||
owns all the steps to get in, as the ``channels`` tool owns all the configuration of a
|
||||
slot.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,24 +29,24 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
|
||||
@register
|
||||
class RoomsTool(Tool):
|
||||
"""Join room servers, and keep track of the ones you have."""
|
||||
"""Join room servers, and keep a list of the rooms that you joined."""
|
||||
|
||||
name = "rooms"
|
||||
title = "Rooms"
|
||||
icon = "📌"
|
||||
help = "Join room servers' message boards"
|
||||
category = "Message"
|
||||
order = 25 # beside Channels: the other half of what Chat lists
|
||||
order = 25 # next to Channels: the other half of the items that Chat lists
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Open the Rooms page (menu) or run a scripted action (CLI).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: A ``cli_action`` with its arguments (CLI), or empty for the menu.
|
||||
ctx: The shared application context.
|
||||
params: A ``cli_action`` and its arguments (CLI), or empty for the menu.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` recording what happened (the menu path shows nothing).
|
||||
A :class:`ToolResult` that holds what occurred. The menu path shows nothing.
|
||||
"""
|
||||
action = params.get("cli_action")
|
||||
if action == "join":
|
||||
@@ -62,12 +63,12 @@ class RoomsTool(Tool):
|
||||
# -- CLI --------------------------------------------------------------------
|
||||
|
||||
async def _rooms(self, ctx: AppContext) -> list[Contact]:
|
||||
"""Every room server the radio knows, as the session's contact cache holds it."""
|
||||
"""Each room server that the device knows, as the contact cache of the session has it."""
|
||||
await ctx.device()
|
||||
return [c for c in await ctx.devstate.contacts() if c.is_room]
|
||||
|
||||
async def _room(self, ctx: AppContext, needle: str) -> Contact:
|
||||
"""The room server a name or key prefix names — a usage error for anything else."""
|
||||
"""The room server for a name or a key prefix. Any other value is a usage error."""
|
||||
folded = needle.casefold()
|
||||
contacts = await ctx.devstate.contacts()
|
||||
for contact in contacts:
|
||||
@@ -79,7 +80,7 @@ class RoomsTool(Tool):
|
||||
raise typer.BadParameter(f"no room server matches {needle!r}")
|
||||
|
||||
async def _cli_list(self, ctx: AppContext) -> ToolResult:
|
||||
"""List every room server the radio knows: joined, access, heard, posts, unread."""
|
||||
"""List each room server that the device knows: joined, access, heard, posts, unread."""
|
||||
rooms = await self._rooms(ctx)
|
||||
peers = [_peer(r) for r in rooms]
|
||||
lasts = ctx.repo.last_chat_messages(rooms=peers)
|
||||
@@ -105,19 +106,20 @@ class RoomsTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_join(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Log in to a room server — one exchange — and print the access it granted.
|
||||
"""Log in to a room server (one exchange), and print the access that it gave.
|
||||
|
||||
The password is ``--password``, else the one MeshTerm remembers for the room (its
|
||||
admin password, then its room password); one that works is remembered, exactly as
|
||||
the Rooms page remembers it. ``--flood`` forgets the route the radio learned to the
|
||||
room first, the way round a route gone stale. The room then sends every post the
|
||||
radio hasn't seen, one at a time — they wait on the radio for whatever reads it next
|
||||
(``chat listen``, the menu), and ``chat history`` has them from then on.
|
||||
The password is ``--password``. If there is no ``--password``, it is the password
|
||||
that MeshTerm remembers for the room (its admin password, then its room password).
|
||||
MeshTerm remembers a password that works, exactly as the Rooms page remembers it.
|
||||
``--flood`` first forgets the route to the room that the device learned. This is
|
||||
the solution for a stale route. Then the room sends each post that the device did
|
||||
not receive yet, one at a time. The posts wait on the device for the next program
|
||||
that reads it (``chat listen``, the menu). After that, ``chat history`` has them.
|
||||
|
||||
A room never says no: a wrong password gets no reply at all. So silence is a
|
||||
failure here (exit 4), explained in the Rooms page's own words — how the login went
|
||||
out, when the room was last heard, and whether this password has worked before —
|
||||
and whatever password was remembered is kept.
|
||||
A room never says no: a wrong password gets no reply. Thus no reply is a failure
|
||||
here (exit 4). The error message uses the words of the Rooms page: how the login
|
||||
went out, when the room was last heard, and if this password worked before.
|
||||
MeshTerm keeps the remembered password, if there is one.
|
||||
"""
|
||||
from ..core.connection import DeviceCommandError
|
||||
from ..ui.rooms import silence_explanation, valid_password
|
||||
@@ -147,7 +149,7 @@ class RoomsTool(Tool):
|
||||
)
|
||||
|
||||
async def _cli_forget(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Stop logging in to a room and forget its password; its stored posts are kept."""
|
||||
"""Do not log in to a room again, and forget its password. Its stored posts stay."""
|
||||
room = await self._room(ctx, str(params["room"]))
|
||||
was = ctx.rooms.joined(room)
|
||||
ctx.rooms.forget(room)
|
||||
@@ -199,7 +201,7 @@ class RoomsTool(Tool):
|
||||
|
||||
|
||||
def _peer(room: Contact) -> str:
|
||||
"""The room's key as its conversation stores it."""
|
||||
"""The key prefix of the room, as its conversation stores it."""
|
||||
return (room.key_prefix or room.public_key[:12] or "").lower()
|
||||
|
||||
|
||||
@@ -216,11 +218,11 @@ def _node(room: Contact) -> NodeRef:
|
||||
|
||||
|
||||
def _listing(records: list[dict]) -> Listing:
|
||||
"""``rooms list``: one room per record, joined ones first.
|
||||
"""``rooms list``: one room in each record, with the joined rooms first.
|
||||
|
||||
``ACCESS`` is ``-`` for a room not joined (the document's ``joined`` says so outright);
|
||||
``HEARD`` is when the room was last heard on the air, the one column that says whether
|
||||
a login has any chance of reaching it.
|
||||
``ACCESS`` is ``-`` for a room that is not joined (``joined`` in the document says this
|
||||
directly). ``HEARD`` is the time when the room was last heard on the air. It is the
|
||||
only column that shows if a login can possibly get to the room.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import Listing
|
||||
@@ -241,11 +243,11 @@ def _listing(records: list[dict]) -> Listing:
|
||||
|
||||
|
||||
def _joined(room: Contact, access: str, flood: bool | None) -> Facts:
|
||||
"""What ``rooms join`` won: the access a room granted, bare — the one fact asked for.
|
||||
"""What ``rooms join`` got: only the access that a room gave, the one fact asked for.
|
||||
|
||||
The room and how the login went out ride in the document; the plain face prints the
|
||||
access word alone (``member``, ``admin`` or ``read-only``), which is what a script
|
||||
deciding whether it may post branches on.
|
||||
The room, and how the login went out, are in the document. The plain face prints only
|
||||
the access word (``member``, ``admin``, or ``read-only``). A script uses this word to
|
||||
decide if it can post.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import BARE, Facts
|
||||
@@ -268,7 +270,7 @@ def _joined(room: Contact, access: str, flood: bool | None) -> Facts:
|
||||
|
||||
|
||||
def _forgotten(room: Contact, was: bool) -> Facts:
|
||||
"""What ``rooms forget`` did: silent on the plain face, the room and the fact in JSON."""
|
||||
"""What ``rooms forget`` did: nothing on the plain face, the room and the fact in JSON."""
|
||||
from ..ui import fields
|
||||
from ..ui.report import SILENT, Facts
|
||||
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``timemachine`` tool: explore everything the recorder ever heard.
|
||||
"""The ``timemachine`` tool: explore all that the recorder ever heard.
|
||||
|
||||
Opens the Time Machine (see :mod:`meshterm.ui.timemachine_screen`): pick the whole mesh
|
||||
or any node ever observed and read its history as braille charts — reception volume,
|
||||
the median-SNR band, the hour-of-day rhythm, packets and nodes per day, first-ever
|
||||
arrivals — over a switchable 24 h / 7 d / 30 d / all-time window. The passive monitor
|
||||
has been writing this history since the first session; this is where it pays off.
|
||||
The tool opens the Time Machine (refer to :mod:`meshterm.ui.timemachine_screen`). The
|
||||
user selects the whole mesh, or any node that MeshTerm ever heard, and reads its history
|
||||
as braille charts: the reception volume, the median-SNR band, the rhythm by hour of the
|
||||
day, the packets and nodes for each day, and the first arrivals. The time window is 24 h,
|
||||
7 d, 30 d, or all the time, and the user can change it. The passive monitor writes this
|
||||
history, and it started in the first session. This tool is where that history becomes
|
||||
useful.
|
||||
|
||||
Menu-only: the explorer is interactive by nature (subjects, windows, scrolling); the
|
||||
``monitor`` and ``nodes`` subcommands remain the scripted views over the same data.
|
||||
Menu only: the explorer is interactive (subjects, time windows, scroll). The ``monitor``
|
||||
and ``nodes`` subcommands stay the scripted listings of the same data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,24 +25,24 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
@register
|
||||
class TimeMachineTool(Tool):
|
||||
"""Read the mesh's recorded past: per-node timelines, daily volumes, arrivals."""
|
||||
"""Read the stored history of the mesh: node timelines, daily volumes, arrivals."""
|
||||
|
||||
name = "timemachine"
|
||||
title = "Time machine"
|
||||
icon = "⏳"
|
||||
help = "Recorded history — timelines, rhythms, arrivals"
|
||||
category = "Watch"
|
||||
order = 40 # the past tense of the Dashboard above it
|
||||
order = 40 # the Dashboard above it, but for the past
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the explorer; there are never parameters to collect.
|
||||
"""Run the explorer. It has no parameters to collect.
|
||||
|
||||
The screen presents everything itself and returns when dismissed, so
|
||||
returning ``None`` tells the menu the invocation is complete (the same
|
||||
The screen shows all its content itself, and it returns when the user leaves it.
|
||||
Thus the return value ``None`` tells the menu that the run is complete (the same
|
||||
pattern as the ``dashboard`` tool).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -51,20 +53,20 @@ class TimeMachineTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Nothing runs here: the Time Machine lives inside :meth:`prompt_params`.
|
||||
"""Nothing runs here: the Time Machine is in :meth:`prompt_params`.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
An empty :class:`ToolResult` (only reachable from a scripted call).
|
||||
An empty :class:`ToolResult` (only a scripted call comes here).
|
||||
"""
|
||||
return ToolResult(summary={})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — the Time Machine is an interactive explorer.
|
||||
"""Register no CLI command, because the Time Machine is an interactive explorer.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
+177
-163
@@ -1,28 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The trace tools: path traces, live in the menu, one-shot on the CLI.
|
||||
"""The trace tools: path traces, live in the menu, and a single run on the CLI.
|
||||
|
||||
A trace is one walked path — the protocol has no destination field, so "target" is
|
||||
purely a UX notion — and the menu splits the feature along exactly that line:
|
||||
A trace is one walked path. The protocol has no destination field, so "target" is only
|
||||
a UX concept. The menu divides the feature at exactly that line:
|
||||
|
||||
* **Trace target** (``trace``): *can I reach this node?* Pick a target from a
|
||||
recency-ordered list; the live screen composes/explores symmetric routes that turn
|
||||
at the target and come home over the mirrored hops. The list stays pushed underneath
|
||||
for the whole visit, so Esc from a walk lands back on the row that launched it —
|
||||
freshly re-sorted by what was just traced — and the next node is one Enter away.
|
||||
* **Trace path** (``trace-path``): *how far can a route I build carry?* No target and
|
||||
no picker — the whole walk is composed hop by hop and only has to end within our
|
||||
own earshot. Traces record under the ``(path)`` sentinel, keeping composed walks
|
||||
out of the target picker's history.
|
||||
* **Trace target** (``trace``): *can I get to this node?* Select a target from a list in
|
||||
the order of recency. The live screen composes and explores symmetric routes that turn
|
||||
at the target and come back over the mirrored hops. The list stays pushed below for
|
||||
the full visit. Thus Esc from a walk goes back to the row that started it (sorted
|
||||
again by the last trace), and the next node is one Enter away.
|
||||
* **Trace path** (``trace-path``): *how far can a route that I make go?* No target and
|
||||
no picker. The user composes the full walk hop by hop, and it must only end at a node
|
||||
that our node can hear. The traces are stored under the ``(path)`` sentinel, so the
|
||||
composed walks stay out of the history of the target picker.
|
||||
|
||||
Both open the live trace screen (:mod:`meshterm.ui.trace_screen`) armed but idle:
|
||||
nothing transmits until Trace is committed, which runs the chosen sample count
|
||||
(1–8 traces, paced between transmissions — repeaters penalize, and can blacklist,
|
||||
nodes that burst traffic, so multi-trace runs always sleep a cooldown between sends).
|
||||
On the CLI each stays a scriptable one-shot: run one trace, print the route and
|
||||
per-hop SNR, exit.
|
||||
Both tools open the live trace screen (:mod:`meshterm.ui.trace_screen`) ready but idle.
|
||||
Nothing transmits until the user starts Trace, which runs the selected sample count
|
||||
(1–8 traces, with a pause between transmissions). Repeaters penalize, and can
|
||||
blacklist, nodes that transmit in bursts. Thus a run of more than one trace always
|
||||
waits a cooldown between sends. On the CLI, each tool stays a scriptable single run:
|
||||
run one trace, print the route and the SNR of each hop, and exit.
|
||||
|
||||
Both front ends persist identically: one ``runs`` row per trace, recorded under it, so
|
||||
stored history reads the same no matter where it came from.
|
||||
The two front ends store the same data: one ``runs`` row for each trace, with the trace
|
||||
stored under it. Thus the stored history is the same, wherever it came from.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -48,47 +48,48 @@ from .base import Tool, ToolResult, register
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from ..ui.contactlist import ContactListScreen, ContactRow
|
||||
|
||||
#: The characters a stored trace target must consist of to be treated as a hex key
|
||||
#: prefix when folding it back to a contact name in the target picker.
|
||||
#: The characters that a stored trace target must contain, and only these, to be a hex key
|
||||
#: prefix when the target picker folds it back to a contact name.
|
||||
_HEX_DIGITS = frozenset("0123456789abcdef")
|
||||
|
||||
|
||||
@register
|
||||
class TraceTool(Tool):
|
||||
"""Trace the path to a target and watch per-hop SNR, live or scripted."""
|
||||
"""Trace the path to a target and watch the SNR of each hop, live or scripted."""
|
||||
|
||||
name = "trace"
|
||||
title = "Trace target"
|
||||
icon = "🎯"
|
||||
help = "Trace a target and watch per-hop SNR"
|
||||
category = "Explore"
|
||||
order = 30 # see a node above, walk to it here
|
||||
order = 30 # find a node with the tool above, and walk to it here
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Nothing to gather here — the target picker lives inside :meth:`run`.
|
||||
"""Nothing to collect here. The target picker is in :meth:`run`.
|
||||
|
||||
The pick and the screen it opens share the contacts read and the routing width,
|
||||
and the live path skips the base class's run row (see :meth:`execute`), so the
|
||||
whole entry flow sits in :meth:`_run_live` rather than half of it here.
|
||||
The selection and the screen that it opens share the read of the contacts and the
|
||||
routing width. Also, the live path does not use the run row of the base class
|
||||
(refer to :meth:`execute`). Thus the full entry flow is in :meth:`_run_live`, and
|
||||
not half of it here.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
``{"live": True}`` — the menu's marker for the interactive path.
|
||||
``{"live": True}``: the marker of the menu for the interactive path.
|
||||
"""
|
||||
return {"live": True}
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run — without the outer run row on the live path.
|
||||
"""Run, with no outer run row on the live path.
|
||||
|
||||
The live screen opens one ``runs`` row *per trace* (matching what a scripted
|
||||
invocation records), so wrapping the whole screen session in another row would
|
||||
double-log it. Scripted runs keep the base class's logging.
|
||||
The live screen opens one ``runs`` row *for each trace* (the same row that a
|
||||
scripted run stores). If another row goes around the full screen session, the log
|
||||
has each trace two times. Scripted runs keep the logging of the base class.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Parameters for this invocation.
|
||||
ctx: The shared application context.
|
||||
params: The parameters for this run.
|
||||
|
||||
Returns:
|
||||
The :class:`ToolResult` from :meth:`run`.
|
||||
@@ -98,16 +99,16 @@ class TraceTool(Tool):
|
||||
return await super().execute(ctx, params)
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Open the live screen (menu) or run one persisted trace (CLI).
|
||||
"""Open the live screen (menu), or run one stored trace (CLI).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``live`` from the menu (the target is picked on the screen); or
|
||||
``target`` (str), optional ``path``, and the injected ``_run_id``
|
||||
from the CLI.
|
||||
ctx: The shared application context.
|
||||
params: ``live`` from the menu (the user selects the target on the screen).
|
||||
Or, from the CLI: ``target`` (str), the optional ``path``, and the
|
||||
injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the trace's outcome.
|
||||
A :class:`ToolResult` with the result of the trace.
|
||||
"""
|
||||
if params.get("live"):
|
||||
return await self._run_live(ctx)
|
||||
@@ -116,26 +117,27 @@ class TraceTool(Tool):
|
||||
# -- interactive (menu) -------------------------------------------------------
|
||||
|
||||
async def _run_live(self, ctx: AppContext) -> ToolResult:
|
||||
"""Ask for the target in a popup, then run the live screen over the menu.
|
||||
"""Ask for the target in a dialog, then run the live screen over the menu.
|
||||
|
||||
The picker is a *question*, not a place: a floating list over the menu, gone the
|
||||
moment a target is picked, so the trace screen opens straight over the menu and
|
||||
Esc from it lands there. It used to stay pushed as a hub under the trace screen —
|
||||
Esc out of a trace landed back on the list, which read as two places where the
|
||||
trace is the whole visit; tracing another node is opening the tool again.
|
||||
The picker is a *question*, not a place. It is a floating list over the menu, and
|
||||
it closes immediately when the user selects a target. Thus the trace screen opens
|
||||
directly over the menu, and Esc from it goes back there. Before, the picker stayed
|
||||
pushed as a hub under the trace screen, and Esc from a trace went back to the
|
||||
list. That looked like two places, but the trace is the full visit. To trace
|
||||
another node, the user opens the tool again.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` counting the screen opened and the traces run.
|
||||
A :class:`ToolResult` that counts the opened screen and the traces that ran.
|
||||
"""
|
||||
from ..ui.trace_screen import open_trace
|
||||
from ..ui.tui.screen import CANCEL
|
||||
|
||||
picker = await self._build_picker(ctx)
|
||||
if picker is None:
|
||||
# Nothing to list (or no full-screen session): the target is typed instead.
|
||||
# Nothing to list (or no full-screen session): the user types the target.
|
||||
target = await self._prompt_target(ctx)
|
||||
else:
|
||||
chosen = await ctx.ui.session.run_dialog(picker)
|
||||
@@ -145,39 +147,41 @@ class TraceTool(Tool):
|
||||
return ToolResult(summary={"sessions": 1, "traces": await open_trace(ctx, target)})
|
||||
|
||||
async def _prompt_target(self, ctx: AppContext) -> str | None:
|
||||
"""Ask for a target by hand — the way in when there is no list to pick from.
|
||||
"""Ask the user to type a target: the way in when there is no list to select from.
|
||||
|
||||
Reached with no known contacts at all (an empty list would be nothing to pick from)
|
||||
and on any surface without a full-screen session. It is also the only way to trace a
|
||||
bare key prefix for a node the device doesn't carry as a contact. A question like
|
||||
the list it stands in for, so it floats over the menu rather than filling the frame.
|
||||
MeshTerm comes here when there are no known contacts (an empty list gives nothing
|
||||
to select), and on each surface that has no full-screen session. It is also the
|
||||
only way to trace a bare key prefix of a node that the device does not have as a
|
||||
contact. It is a question, the same as the list that it replaces. Thus it floats
|
||||
over the menu, and does not fill the frame.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
The typed target, or ``None`` if it was left blank or cancelled.
|
||||
The typed target, or ``None`` if the user left it blank or cancelled it.
|
||||
"""
|
||||
entered = await ctx.ui.text("Target node (name or key prefix):", floating=True)
|
||||
return entered.strip() if entered else None
|
||||
|
||||
async def _build_picker(self, ctx: AppContext) -> ContactListScreen | None:
|
||||
"""Build the trace-target picker, or ``None`` when there is no list to draw.
|
||||
"""Make the trace target picker, or return ``None`` when there is no list to draw.
|
||||
|
||||
The same ``NAME · TRACED · HEARD · PKTS · KEY`` lanes, Ctrl+arrow sort ring, and
|
||||
type-to-filter the Contacts screen and the courier recipient draw — but with every
|
||||
node type listed (a trace answers *can I reach this node?* for a repeater or room
|
||||
just as for a companion) and an extra ``TRACED`` lane: how long ago each node was
|
||||
last traced. The list opens sorted by ``TRACED`` descending, so the most recently
|
||||
traced node leads and never-traced ones gather at the bottom. Enter commits the
|
||||
highlighted node as the target.
|
||||
It has the same ``NAME · TRACED · HEARD · PKTS · KEY`` lanes, Ctrl+arrow sort ring,
|
||||
and type-to-filter as the Contacts screen and the courier recipient. But it lists
|
||||
all the node types (a trace answers *can I get to this node?* for a repeater or a
|
||||
room, the same as for a companion). It also has one more lane, ``TRACED``: how
|
||||
long ago each node was last traced. The list opens sorted by ``TRACED``, in
|
||||
descending order. Thus the most recently traced node comes first, and the nodes
|
||||
that were never traced are at the bottom. Enter commits the highlighted node as
|
||||
the target.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
The picker, or ``None`` when there is nothing to list — see
|
||||
:meth:`_prompt_target`.
|
||||
The picker, or ``None`` when there is nothing to list (refer to
|
||||
:meth:`_prompt_target`).
|
||||
"""
|
||||
from ..ui.contactlist import (
|
||||
TRACE_LANES,
|
||||
@@ -188,9 +192,10 @@ class TraceTool(Tool):
|
||||
from ..ui.surface import TuiUi
|
||||
from ..ui.widgets import ContactsSort
|
||||
|
||||
# Through the session cache: this picker runs on every Trace open, and the contacts
|
||||
# table is a slow round-trip on a busy node — re-reading it here (in front of the
|
||||
# already-cached trace screen) is what kept opening Trace feeling like a stall. See
|
||||
# Read through the session cache. This picker runs each time that Trace opens, and
|
||||
# the contacts table is a slow round trip on a busy node. When MeshTerm read it
|
||||
# again here (before the trace screen, which is already cached), Trace seemed to
|
||||
# stop each time it opened. Refer to
|
||||
# :class:`~meshterm.services.device_state.DeviceState`.
|
||||
contacts = await ctx.devstate.contacts()
|
||||
if not contacts or not isinstance(ctx.ui, TuiUi):
|
||||
@@ -204,26 +209,27 @@ class TraceTool(Tool):
|
||||
footer_hint="↑↓ move · ^←→↑↓ sort · type to filter · Enter select · Esc back",
|
||||
lanes=TRACE_LANES,
|
||||
)
|
||||
# The contact list is a full-screen page everywhere else; here it is a question
|
||||
# asked on the way in, so it floats over the menu like every other lead-in pick.
|
||||
# In all other places, the contact list is a full-screen page. Here it is a
|
||||
# question before the screen opens, so it floats over the menu, the same as each
|
||||
# other selection before a tool.
|
||||
picker.floating = True
|
||||
return picker
|
||||
|
||||
@staticmethod
|
||||
def _picker_rows(ctx: AppContext, contacts: list[Contact]) -> list[ContactRow]:
|
||||
"""The picker's lane data for ``contacts``, read fresh from stored history.
|
||||
"""The lane data of the picker for ``contacts``, read again from the stored history.
|
||||
|
||||
Both the ``TRACED`` ages and the packet counts come from the repository, so this is
|
||||
cheap enough to redo every time a trace hands the picker back — which is what keeps
|
||||
the lane the list is *sorted* by honest about the walk that just happened.
|
||||
The ``TRACED`` ages and the packet counts both come from the repository. Thus it
|
||||
costs little to do this again each time that a trace returns to the picker. That
|
||||
keeps the lane by which the list is *sorted* correct for the last walk.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
contacts: The device's contacts, as listed.
|
||||
ctx: The shared application context.
|
||||
contacts: The contacts of the device, as listed.
|
||||
|
||||
Returns:
|
||||
One :class:`~meshterm.ui.contactlist.ContactRow` per contact, in the order
|
||||
given (the screen sorts them).
|
||||
One :class:`~meshterm.ui.contactlist.ContactRow` for each contact, in the given
|
||||
order (the screen sorts them).
|
||||
"""
|
||||
from ..ui.contactlist import ContactRow
|
||||
from ..ui.widgets import contact_packets
|
||||
@@ -246,18 +252,18 @@ class TraceTool(Tool):
|
||||
# -- scripted (CLI) -------------------------------------------------------------
|
||||
|
||||
async def _run_cli(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run one trace, persist it, and print the route and per-hop summary.
|
||||
"""Run one trace, store it, and print the route and the summary of each hop.
|
||||
|
||||
One transmission per invocation is a hard rule on the CLI — repeaters
|
||||
penalize (and can blacklist) nodes that burst traffic — so scripted sampling
|
||||
means invoking again (with your own pacing between runs).
|
||||
On the CLI, one transmission for each run is a strict rule, because repeaters
|
||||
penalize (and can blacklist) nodes that transmit in bursts. Thus, to take more
|
||||
samples in a script, run the command again (with your own pause between runs).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``target`` (str), optional ``path``, and the injected ``_run_id``.
|
||||
ctx: The shared application context.
|
||||
params: ``target`` (str), the optional ``path``, and the injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the trace's outcome.
|
||||
A :class:`ToolResult` with the result of the trace.
|
||||
"""
|
||||
return await _trace_once_cli(
|
||||
ctx, params["_run_id"], target=params["target"], path_spec=params.get("path")
|
||||
@@ -279,9 +285,10 @@ class TraceTool(Tool):
|
||||
path: str | None = typer.Option(
|
||||
None,
|
||||
"--path",
|
||||
# No ``-p`` short form: ``-p`` is the global ``--profile``, and
|
||||
# ``_globals_first`` lifts a group option ahead of the subcommand wherever it
|
||||
# is typed — so a leaf ``-p`` could never reach this option, only shadow it.
|
||||
# No ``-p`` short form. ``-p`` is the global ``--profile``, and
|
||||
# ``_globals_first`` moves a group option in front of the subcommand, at any
|
||||
# position where it is typed. Thus a leaf ``-p`` can never get to this option.
|
||||
# It can only hide it.
|
||||
help="Force a route: comma-separated contact names/hex prefixes (e.g. 3d,f2,3d)",
|
||||
),
|
||||
) -> None:
|
||||
@@ -293,7 +300,7 @@ class TraceTool(Tool):
|
||||
|
||||
@register
|
||||
class TracePathTool(Tool):
|
||||
"""Walk a hand-composed route — no target — and see how far it carries."""
|
||||
"""Walk a route that you compose by hand (no target), and see how far it goes."""
|
||||
|
||||
name = "trace-path"
|
||||
title = "Trace path"
|
||||
@@ -303,22 +310,22 @@ class TracePathTool(Tool):
|
||||
order = 32
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""No parameters to gather — a path walk has no target to pick.
|
||||
"""No parameters to collect, because a path walk has no target to select.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
``{"live": True}`` — the route itself is composed on the screen.
|
||||
``{"live": True}``. The user composes the route itself on the screen.
|
||||
"""
|
||||
return {"live": True}
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run — without the outer run row on the live path (see :class:`TraceTool`).
|
||||
"""Run, with no outer run row on the live path (refer to :class:`TraceTool`).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Parameters for this invocation.
|
||||
ctx: The shared application context.
|
||||
params: The parameters for this run.
|
||||
|
||||
Returns:
|
||||
The :class:`ToolResult` from :meth:`run`.
|
||||
@@ -328,15 +335,15 @@ class TracePathTool(Tool):
|
||||
return await super().execute(ctx, params)
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Open the live path-walk screen (menu) or run one persisted trace (CLI).
|
||||
"""Open the live path walk screen (menu), or run one stored trace (CLI).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``live`` from the menu; or ``path`` (str, required) and the
|
||||
injected ``_run_id`` from the CLI.
|
||||
ctx: The shared application context.
|
||||
params: ``live`` from the menu. Or, from the CLI: ``path`` (str, necessary)
|
||||
and the injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the walk's outcome.
|
||||
A :class:`ToolResult` with the result of the walk.
|
||||
"""
|
||||
if params.get("live"):
|
||||
from ..ui.trace_screen import open_trace_path
|
||||
@@ -363,9 +370,10 @@ class TracePathTool(Tool):
|
||||
path: str = typer.Option(
|
||||
...,
|
||||
"--path",
|
||||
# No ``-p`` short form: ``-p`` is the global ``--profile``, and
|
||||
# ``_globals_first`` lifts a group option ahead of the subcommand wherever it
|
||||
# is typed — so a leaf ``-p`` could never reach this option, only shadow it.
|
||||
# No ``-p`` short form. ``-p`` is the global ``--profile``, and
|
||||
# ``_globals_first`` moves a group option in front of the subcommand, at any
|
||||
# position where it is typed. Thus a leaf ``-p`` can never get to this option.
|
||||
# It can only hide it.
|
||||
help="The whole walk: comma-separated contact names/hex prefixes "
|
||||
"(must end within earshot of this node)",
|
||||
),
|
||||
@@ -376,42 +384,45 @@ class TracePathTool(Tool):
|
||||
async def _trace_once_cli(
|
||||
ctx: AppContext, run_id: int, *, target: str, path_spec: str | None
|
||||
) -> ToolResult:
|
||||
"""Run one persisted trace and print the route and per-hop summary (CLI body).
|
||||
"""Run one stored trace, and print the route and the summary of each hop (CLI body).
|
||||
|
||||
Shared by both scripted trace commands: ``trace`` passes its target (path
|
||||
optional — the device routes without one), ``trace-path`` passes the
|
||||
:data:`~meshterm.core.models.PATH_TRACE_TARGET` sentinel with a required path.
|
||||
The two scripted trace commands share this function. ``trace`` gives its target (the
|
||||
path is optional, because the device can route without one). ``trace-path`` gives the
|
||||
:data:`~meshterm.core.models.PATH_TRACE_TARGET` sentinel and a necessary path.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
run_id: The already-open run row to record under.
|
||||
target: The label the trace persists under.
|
||||
path_spec: The forced route as typed (names/hex, comma-separated), if any.
|
||||
ctx: The shared application context.
|
||||
run_id: The run row, already open, under which to store the trace.
|
||||
target: The label under which the trace is stored.
|
||||
path_spec: The forced route as typed (names or hex, with commas between them), if
|
||||
there is one.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the trace's outcome.
|
||||
A :class:`ToolResult` with the result of the trace.
|
||||
"""
|
||||
from ..ui.surface import TuiUi
|
||||
|
||||
is_walk = target == PATH_TRACE_TARGET
|
||||
device = await ctx.device()
|
||||
|
||||
# Our own device's name labels both endpoints of the path (first hop's origin,
|
||||
# last hop's destination); fall back to a neutral label if it's unavailable.
|
||||
# The name of our device is the label of the two ends of the path (the origin of the
|
||||
# first hop, and the destination of the last hop). If the name is not available, use a
|
||||
# neutral label.
|
||||
self_info = await device.get_self_info()
|
||||
device_label = str(self_info.get("name") or LOCAL_DEVICE_LABEL)
|
||||
# Our own public key, so the route's endpoints (us) carry a hash like every
|
||||
# other hop, addressed at the same path-hash width.
|
||||
# Our own public key. Thus the ends of the route (our node) have a hash, the same as
|
||||
# each other hop, at the same path hash width.
|
||||
device_hash = str(self_info.get("public_key") or "") or None
|
||||
|
||||
# Resolve repeater hashes in the results to contact names where we know them,
|
||||
# so the tables read as names instead of opaque hex prefixes.
|
||||
# Resolve the repeater hashes in the results to contact names, when we know them. Thus
|
||||
# the tables show names, not hex prefixes that tell nothing.
|
||||
contacts = await device.get_contacts()
|
||||
resolve = trace_runner.make_node_resolver(contacts)
|
||||
|
||||
# Resolve an optional forced path (names/hex) to the hex string the radio wants.
|
||||
# Leaving it blank is fully supported for a *target* trace: the device reuses the
|
||||
# route it already learned (or floods if it has none). A path walk always has one.
|
||||
# Resolve an optional forced path (names or hex) to the hex string that the radio
|
||||
# accepts. A blank path is fully supported for a *target* trace: the device uses again
|
||||
# the route that it already learned (or floods if it has no route). A path walk always
|
||||
# has a path.
|
||||
path: str | None = None
|
||||
if path_spec:
|
||||
path = trace_runner.parse_trace_path(path_spec, contacts)
|
||||
@@ -424,8 +435,8 @@ async def _trace_once_cli(
|
||||
|
||||
stats = TraceStats.from_traces(target, [result])
|
||||
if isinstance(ctx.ui, TuiUi):
|
||||
# The stats panel renders route + per-hop readings for the single trace (its
|
||||
# medians collapse to the readings themselves).
|
||||
# The stats panel renders the route and the readings of each hop for the single
|
||||
# trace (its medians are the same as the readings themselves).
|
||||
ctx.ui.show(
|
||||
stats_panel(
|
||||
stats,
|
||||
@@ -459,9 +470,9 @@ async def _trace_once_cli(
|
||||
message = f"[ok]✓[/ok] traced [brand]{target}[/brand]{via}"
|
||||
else:
|
||||
message = f"[err]✗[/err] no reply from [brand]{target}[/brand]{via}"
|
||||
# A trace that never came home is not a failure of the command — the radio did
|
||||
# transmit and the walk did run. It is a walk with nothing to report, which is what
|
||||
# NO_RESULT says, and it is the answer a script most often branches on.
|
||||
# A trace that never came back is not a failure of the command: the radio transmitted,
|
||||
# and the walk ran. It is a walk with nothing to report, which is what NO_RESULT says.
|
||||
# It is also the answer on which a script most often branches.
|
||||
return ToolResult(
|
||||
summary=summary,
|
||||
message=message,
|
||||
@@ -478,30 +489,32 @@ def _trace_report(
|
||||
resolve: Any,
|
||||
device_hash: str | None,
|
||||
) -> tuple:
|
||||
"""State one trace: the walk's outcome, then its per-hop readings.
|
||||
"""State one trace: the result of the walk, then the readings of each hop.
|
||||
|
||||
Two blocks. The first is what the walk *did* — one fact per line, ``route`` among them
|
||||
as a drawn line, every node named and carrying the hash it was addressed by. The
|
||||
second is a record per hop, and it names its two ends by that same **hash** rather than
|
||||
repeating the names: the route line above is where the names are, and the hash is what
|
||||
joins the two blocks (it is what carries a node's identity here, the way its colour
|
||||
does on a screen). The document embeds the whole node at both ends instead, because a
|
||||
structural join needs no key and each edge should be readable on its own.
|
||||
Two blocks. The first block is what the walk *did*: one fact on each line. ``route``
|
||||
is one of these facts, as a drawn line, and each node in it has a name and the hash by
|
||||
which it was addressed. The second block has a record for each hop. It names the two
|
||||
ends of a hop by that same **hash**, and does not repeat the names. The names are in
|
||||
the route line above, and the hash joins the two blocks (here, the hash shows the
|
||||
identity of a node, as its colour does on a screen). The document puts the full node
|
||||
at the two ends instead, because a structural join does not use a key, and each edge
|
||||
must be readable alone.
|
||||
|
||||
Our own node is a hop like any other, named and hashed. The menu draws it as ``★``
|
||||
because a reader never has to be told which node is theirs; this line is as often read
|
||||
out of a file by somebody who was not at the prompt when it ran.
|
||||
Our node is a hop like any other, with a name and a hash. The menu draws it as ``★``,
|
||||
because the user never has to be told which node is theirs. But this line is often
|
||||
read from a file by a person who was not at the prompt when it ran.
|
||||
|
||||
Args:
|
||||
result: The trace that ran.
|
||||
target: The label it was addressed to.
|
||||
target: The label to which it was addressed.
|
||||
path: The forced route as hex, or ``None`` when the device routed it.
|
||||
device_label: Our own node's name, at both ends of the walk.
|
||||
resolve: Maps a hop hash to a friendly name when known.
|
||||
device_hash: Our own public key, so our ends carry a hash like every other hop.
|
||||
device_label: The name of our node, at the two ends of the walk.
|
||||
resolve: Maps a hop hash to a friendly name, when the name is known.
|
||||
device_hash: Our own public key, so that our ends have a hash, the same as each
|
||||
other hop.
|
||||
|
||||
Returns:
|
||||
The report's blocks.
|
||||
The blocks of the report.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.fields import NodeRef
|
||||
@@ -510,14 +523,14 @@ def _trace_report(
|
||||
hash_bytes = result.path_hash_bytes
|
||||
|
||||
def short(value: str | None) -> str | None:
|
||||
"""A hash at the width this trace addressed nodes by."""
|
||||
"""A hash, at the width with which this trace addressed the nodes."""
|
||||
if not value:
|
||||
return None
|
||||
raw = value.lower().removeprefix("0x")
|
||||
return raw[: hash_bytes * 2] if hash_bytes else raw
|
||||
|
||||
def node(label: str) -> NodeRef:
|
||||
"""One end of a hop as the shared node shape."""
|
||||
"""One end of a hop, in the shared node shape."""
|
||||
if not label or label == device_label:
|
||||
return NodeRef(name=device_label, hash=short(device_hash), is_self=True)
|
||||
return NodeRef(name=resolve(label) or None, hash=short(label))
|
||||
@@ -536,11 +549,11 @@ def _trace_report(
|
||||
fields.integer("hops", "hops"),
|
||||
fields.snr("min_snr_db", "min_snr_db"),
|
||||
fields.decimal("rtt_ms", "rtt_ms", ".0f"),
|
||||
# New surface on the machine face: the model has always carried the TX power
|
||||
# the walk ran at, and the plain facts block has no room for it.
|
||||
# A new field on the machine face. The model always had the TX power at which
|
||||
# the walk ran, and the plain facts block has no space for it.
|
||||
fields.hidden("tx_dbm"),
|
||||
# What `hash` means on this walk's nodes, so a consumer can join two traces
|
||||
# that addressed the same node at different widths.
|
||||
# What `hash` means on the nodes of this walk. Thus a consumer can join two
|
||||
# traces that addressed the same node at different widths.
|
||||
fields.hidden("hash_bytes"),
|
||||
fields.route("route", "route"),
|
||||
),
|
||||
@@ -580,22 +593,23 @@ def _trace_report(
|
||||
def _last_traced_by_name(
|
||||
contacts: list[Contact], traced: dict[str, datetime]
|
||||
) -> dict[str, datetime]:
|
||||
"""Map each contact's name to when that node was last traced.
|
||||
"""Map the name of each contact to the time when that node was last traced.
|
||||
|
||||
The Trace picker's ``TRACED`` lane and default sort read this. Stored trace targets are
|
||||
filed exactly as the user addressed them — a contact name one day, a raw hex key prefix
|
||||
another — so each target is folded onto the contact it names (by name, case-insensitively,
|
||||
or as a prefix of a contact's public key) and the *latest* trace time wins, so a node
|
||||
traced under both spellings still shows one honest "last traced" age. This is the inverse
|
||||
of the picker's old recent-targets fold, kept per-contact rather than as a name list.
|
||||
The ``TRACED`` lane and the default sort of the Trace picker read this map. The stored
|
||||
trace targets are filed exactly as the user addressed them: a contact name one day, a
|
||||
raw hex key prefix on another day. Thus each target is folded onto the contact that it
|
||||
names (by name, case-insensitive, or as a prefix of the public key of a contact). The
|
||||
*latest* trace time wins. Thus a node that was traced under the two spellings still
|
||||
shows one correct "last traced" age. This is the inverse of the old fold of recent
|
||||
targets in the picker, kept for each contact, not as a list of names.
|
||||
|
||||
Args:
|
||||
contacts: The device's current contacts.
|
||||
contacts: The current contacts of the device.
|
||||
traced: ``target → last-traced time`` from
|
||||
:meth:`~meshterm.persistence.repository.Repository.target_last_traced`.
|
||||
|
||||
Returns:
|
||||
``contact name → last-traced time`` for every contact the history can place.
|
||||
``contact name → last-traced time`` for each contact that the history can find.
|
||||
"""
|
||||
by_fold = {c.name.casefold(): c.name for c in contacts}
|
||||
out: dict[str, datetime] = {}
|
||||
@@ -611,8 +625,8 @@ def _last_traced_by_name(
|
||||
note(named, when)
|
||||
continue
|
||||
needle = target.lower().removeprefix("0x")
|
||||
# Only fold plausible key prefixes (≥2 bytes of hex) — a short hex-looking *name*
|
||||
# like "ace" must not be mistaken for an address.
|
||||
# Fold only possible key prefixes (≥2 bytes of hex). A short *name* that looks like
|
||||
# hex, such as "ace", must not be mistaken for an address.
|
||||
if len(needle) >= 4 and all(ch in _HEX_DIGITS for ch in needle):
|
||||
for contact in contacts:
|
||||
if (contact.public_key or "").lower().startswith(needle):
|
||||
|
||||
+153
-134
@@ -1,19 +1,25 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``tx-optimize`` tool: tune a remote node's TX power for the best signal at a target.
|
||||
"""The ``tx-optimize`` tool: tune the TX power of a remote node for the best signal at a target.
|
||||
|
||||
You force a path (just like ``trace``) ending at the **target** node where SNR is
|
||||
measured. The node one hop *before* the target — one you hold admin rights on — is the
|
||||
node whose transmit power gets swept and tuned. Admin passwords are remembered between
|
||||
runs.
|
||||
You force a path (the same as for ``trace``) that ends at the **target** node, where
|
||||
MeshTerm measures the SNR. The node one hop *before* the target is the node whose transmit
|
||||
power MeshTerm sweeps and tunes. You must have admin rights on that node. MeshTerm keeps
|
||||
the admin passwords from one run to the next.
|
||||
|
||||
In the interactive menu one two-step dialog chooses the link — the node to tune
|
||||
(repeaters you hold credentials for lead the list), then the target whose reception is
|
||||
optimized — and the live sweep screen (:mod:`meshterm.ui.tx_screen`) takes it from
|
||||
there, armed but idle: route, range, step, and samples are adjusted in place, nothing
|
||||
transmits until Sweep is committed, levels land in a bar chart as they are measured, and
|
||||
the apply decision is made *after* the sweep, over the evidence. On the CLI it stays a
|
||||
scriptable one-shot with the full flag set (``--path``, range, step, samples,
|
||||
``--apply``), and progress streams like a trace.
|
||||
In the interactive menu, one dialog with two steps selects the link. First, it selects
|
||||
the node to tune (the repeaters for which you have credentials come first in the list).
|
||||
Then it selects the target whose reception MeshTerm optimizes. Then the live sweep screen
|
||||
(:mod:`meshterm.ui.tx_screen`) continues. It is ready, but it does nothing yet:
|
||||
|
||||
- You adjust the route, the range, the step, and the samples on the screen.
|
||||
- Nothing transmits until you start Sweep.
|
||||
- The levels go into a bar chart as MeshTerm measures them.
|
||||
- You decide whether to apply the result *after* the sweep, when you can see the
|
||||
evidence.
|
||||
|
||||
On the CLI, the tool stays a scriptable single run with the full set of flags
|
||||
(``--path``, range, step, samples, ``--apply``), and it streams its progress as a trace
|
||||
does.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,47 +36,48 @@ from ..services import trace_runner, tx_optimizer
|
||||
from ..ui.widgets import tx_opt_summary, tx_opt_table
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
#: Trace count per TX level — kept to single digits so the radio's duty cycle stays sane
|
||||
#: and the per-level sweep finishes in reasonable time.
|
||||
#: The number of traces for each TX level. It stays below 10, so that the duty cycle of the
|
||||
#: radio stays in safe limits and the sweep of each level ends in a reasonable time.
|
||||
MAX_SAMPLES = 9
|
||||
|
||||
|
||||
@register
|
||||
class TxOptimizeTool(Tool):
|
||||
"""Tune a remote node's TX power for the strongest, most reliable signal at a target."""
|
||||
"""Tune the TX power of a remote node for the strongest, most reliable signal at a target."""
|
||||
|
||||
name = "tx-optimize"
|
||||
title = "TX optimize"
|
||||
icon = "📶"
|
||||
help = "Tune a remote node's TX power for a target"
|
||||
category = "Other nodes"
|
||||
order = 20 # like Repeater admin: a remote radio, changed over the mesh
|
||||
order = 20 # the same as Repeater admin: a remote radio, changed over the mesh
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Nothing to gather here — the link is picked inside :meth:`run`.
|
||||
"""Nothing to collect here. The user selects the link in :meth:`run`.
|
||||
|
||||
The two picks are one stepped dialog, and the sweep screen opens the moment it
|
||||
closes; keeping them together in :meth:`_run_live` keeps the contacts read (the one
|
||||
slow thing on the way in) shared between the dialog's rows and the sweep's resolver.
|
||||
The two selections are one dialog with steps, and the sweep screen opens
|
||||
immediately when that dialog closes. :meth:`_run_live` keeps them together. Thus the
|
||||
dialog rows and the resolver of the sweep share one read of the contacts (the only
|
||||
slow step before the screen opens).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
``{"live": True}`` — the menu's marker for the interactive path.
|
||||
``{"live": True}``: the marker of the menu for the interactive path.
|
||||
"""
|
||||
return {"live": True}
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run — without the outer run row on the live path.
|
||||
"""Run, with no outer run row on the live path.
|
||||
|
||||
The live screen opens its own ``runs`` row for the sweep (matching what a
|
||||
scripted invocation records), so wrapping the screen session in another row
|
||||
would double-log it. Scripted runs keep the base class's logging.
|
||||
The live screen opens its own ``runs`` row for the sweep (the same row that a
|
||||
scripted run stores). If another row goes around the screen session, the log has
|
||||
the sweep two times. Scripted runs keep the logging of the base class.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Parameters for this invocation.
|
||||
ctx: The shared application context.
|
||||
params: The parameters for this run.
|
||||
|
||||
Returns:
|
||||
The :class:`ToolResult` from :meth:`run`.
|
||||
@@ -80,16 +87,17 @@ class TxOptimizeTool(Tool):
|
||||
return await super().execute(ctx, params)
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Open the live sweep (menu) or run the scripted optimization (CLI).
|
||||
"""Open the live sweep (menu), or run the scripted optimization (CLI).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``live`` from the menu (both nodes are picked in one dialog); or ``path``,
|
||||
``samples``, ``tx_min``, ``tx_max``, ``step``, ``apply``, optional
|
||||
``password``/``viz``, and the injected ``_run_id`` from the CLI.
|
||||
ctx: The shared application context.
|
||||
params: ``live`` from the menu (the user selects the two nodes in one dialog).
|
||||
Or, from the CLI: ``path``, ``samples``, ``tx_min``, ``tx_max``, ``step``,
|
||||
``apply``, the optional ``password`` and ``viz``, and the injected
|
||||
``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the optimum and any chart path.
|
||||
A :class:`ToolResult` with the optimum and the chart path, if there is one.
|
||||
"""
|
||||
if params.get("live"):
|
||||
return await self._run_live(ctx)
|
||||
@@ -98,36 +106,38 @@ class TxOptimizeTool(Tool):
|
||||
# -- interactive (menu) ---------------------------------------------------------
|
||||
|
||||
async def _run_live(self, ctx: AppContext) -> ToolResult:
|
||||
"""Pick the link in one stepped dialog, then run the sweep screen over the menu.
|
||||
"""Select the link in one dialog with steps, then run the sweep screen over the menu.
|
||||
|
||||
The two picks — the node to tune, then the node to measure at — are one floating
|
||||
list that turns its page (:func:`~meshterm.ui.menus.run_wizard`): Esc on the
|
||||
second step turns back to the first with the picked node still highlighted, Esc
|
||||
on the first leaves. The dialog is gone before the sweep screen opens, so Esc from
|
||||
the sweep lands on the main menu: the link was a question on the way in, not a
|
||||
place to come back to. It used to be two pickers, each kept pushed under the
|
||||
sweep as a hub — three frames deep for a sweep, and two popups stacked on the way
|
||||
in, which read as two places rather than one question in two parts.
|
||||
The two selections (first the node to tune, then the node at which to measure) are
|
||||
one floating list that turns its page (:func:`~meshterm.ui.menus.run_wizard`).
|
||||
Esc on the second step turns back to the first step, and the selected node stays
|
||||
highlighted. Esc on the first step leaves. The dialog closes before the sweep screen
|
||||
opens, so Esc from the sweep goes to the main menu. The link was a question before
|
||||
the screen, not a place to come back to. Before, there were two pickers, and each
|
||||
stayed pushed under the sweep as a hub. That put the sweep three frames deep, and
|
||||
put two dialogs on top of each other before it. They looked like two places, not
|
||||
one question in two parts.
|
||||
|
||||
No login here: the screen logs in inside the first Sweep commit, so backing
|
||||
out of an idle screen never touched the radio beyond the contact reads.
|
||||
There is no login here. The screen logs in when the user starts the first Sweep.
|
||||
Thus, if the user leaves an idle screen, MeshTerm did nothing with the radio but
|
||||
read the contacts.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` echoing the sweep's recorded summary.
|
||||
A :class:`ToolResult` that repeats the stored summary of the sweep.
|
||||
"""
|
||||
from ..ui.admin_picker import admin_picker_rows
|
||||
from ..ui.menus import WizardPage, run_wizard
|
||||
from ..ui.surface import TuiUi
|
||||
from ..ui.tx_screen import open_tx_optimize
|
||||
|
||||
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
|
||||
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - only the menu calls this
|
||||
raise RuntimeError("the live TX sweep is only available in the menu")
|
||||
|
||||
# Through the session cache: this entry flow runs on every open, and the contacts
|
||||
# table is a slow read on a busy node (see
|
||||
# Read through the session cache. This entry flow runs each time the tool opens, and
|
||||
# the contacts table is a slow read on a busy node (refer to
|
||||
# :class:`~meshterm.services.device_state.DeviceState`).
|
||||
contacts = await ctx.devstate.contacts()
|
||||
items, candidates = admin_picker_rows(ctx, contacts)
|
||||
@@ -151,8 +161,8 @@ class TxOptimizeTool(Tool):
|
||||
admin = admin_of(values)
|
||||
targets = _target_items(contacts, admin)
|
||||
if not targets:
|
||||
# The tuned node is the only contact there is: a typed hex key prefix is the
|
||||
# only way to name the target, floated over the dialog's first page.
|
||||
# The tuned node is the only contact. Thus a typed hex key prefix is the only
|
||||
# way to name the target. Its prompt floats over the first page of the dialog.
|
||||
return ctx.ui.session.text(
|
||||
"TX optimize — measure at · step 2 of 2",
|
||||
prompt=f"Hex key prefix of the node that hears {admin.name}:",
|
||||
@@ -167,7 +177,7 @@ class TxOptimizeTool(Tool):
|
||||
)
|
||||
|
||||
answers = await run_wizard(ctx.ui.session, [node_page, target_page])
|
||||
if answers is None: # Esc on the first step — out to the menu
|
||||
if answers is None: # Esc on the first step: back to the menu
|
||||
return ToolResult(summary={})
|
||||
admin_node = admin_of(answers)
|
||||
target = str(answers[1]).strip()
|
||||
@@ -180,7 +190,7 @@ class TxOptimizeTool(Tool):
|
||||
target_hash = target_contact.public_key or target_contact.key_prefix
|
||||
else:
|
||||
target_label = target
|
||||
target_hash = target # a typed hex prefix stands for itself
|
||||
target_hash = target # a typed hex prefix is its own hash
|
||||
|
||||
summary = await open_tx_optimize(
|
||||
ctx,
|
||||
@@ -191,17 +201,19 @@ class TxOptimizeTool(Tool):
|
||||
return ToolResult(summary=summary)
|
||||
|
||||
async def _login(self, ctx: AppContext, admin_node: Contact, params: dict[str, Any]) -> None:
|
||||
"""Authenticate against the admin node, remembering a working password.
|
||||
"""Log in to the admin node, and keep a password that works.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
admin_node: The node we're about to tune.
|
||||
params: Tool params (may carry an explicit ``password`` on the CLI).
|
||||
ctx: The shared application context.
|
||||
admin_node: The node that we will tune.
|
||||
params: The tool parameters (on the CLI, they can hold an explicit
|
||||
``password``).
|
||||
|
||||
Raises:
|
||||
DeviceCommandError: If the node rejected the login (the stored password, now
|
||||
known bad, is forgotten so the next run asks fresh) — or if it never
|
||||
answered, in which case the password is untested and is kept.
|
||||
DeviceCommandError: If the node refused the login. MeshTerm then forgets the
|
||||
stored password, because it is known to be bad, and the next run asks
|
||||
again. Also if the node never answered. Then the password is not tested,
|
||||
and MeshTerm keeps it.
|
||||
"""
|
||||
device = await ctx.device()
|
||||
password = await self._resolve_password(ctx, admin_node, params)
|
||||
@@ -221,15 +233,15 @@ class TxOptimizeTool(Tool):
|
||||
# -- scripted (CLI) ---------------------------------------------------------------
|
||||
|
||||
async def _run_cli(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Resolve the link, log in, sweep TX power, render results, and apply the winner.
|
||||
"""Resolve the link, log in, sweep the TX power, render the results, and apply the best.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``path``, ``samples``, ``tx_min``, ``tx_max``, ``step``, ``apply``,
|
||||
optional ``password``/``viz``, and the injected ``_run_id``.
|
||||
ctx: The shared application context.
|
||||
params: ``path``, ``samples``, ``tx_min``, ``tx_max``, ``step``, ``apply``, the
|
||||
optional ``password`` and ``viz``, and the injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the optimum and any chart path.
|
||||
A :class:`ToolResult` with the optimum and the chart path, if there is one.
|
||||
"""
|
||||
from ..ui.surface import TuiUi
|
||||
|
||||
@@ -237,8 +249,8 @@ class TxOptimizeTool(Tool):
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
|
||||
# Resolve the forced path to hashes, then pull out the target (last hop) and the
|
||||
# admin node we tune (the hop before it).
|
||||
# Resolve the forced path to hashes. Then get the target (the last hop) and the admin
|
||||
# node that we tune (the hop before the target).
|
||||
path = trace_runner.parse_trace_path(params["path"], contacts)
|
||||
admin_node, target_label = _resolve_link(path, contacts)
|
||||
|
||||
@@ -286,8 +298,9 @@ class TxOptimizeTool(Tool):
|
||||
persist_trace=lambda t: ctx.repo.record_trace(run_id, t),
|
||||
)
|
||||
|
||||
# No trace got through at any TX level: nothing was tuned, the node was left at
|
||||
# its original power. Usually a wrong/unreachable path rather than a weak link.
|
||||
# No trace got through at any TX level. Thus nothing was tuned, and the node stays
|
||||
# at its original power. Usually the cause is a path that is wrong or that cannot be
|
||||
# reached, not a weak link.
|
||||
no_result = result.best_snr is None
|
||||
if result.applied:
|
||||
ctx.log.info("set TX power %s on %s", result.best_tx, admin_node.name)
|
||||
@@ -316,8 +329,8 @@ class TxOptimizeTool(Tool):
|
||||
|
||||
return ToolResult(
|
||||
report=report,
|
||||
# No level got a trace through, so nothing was measured and nothing was tuned:
|
||||
# the sweep ran and has nothing to report.
|
||||
# No level got a trace through. Thus nothing was measured and nothing was tuned.
|
||||
# The sweep ran and has nothing to report.
|
||||
exit_code=exitcodes.NO_RESULT if no_result else exitcodes.OK,
|
||||
summary={
|
||||
"target": result.target,
|
||||
@@ -336,27 +349,28 @@ class TxOptimizeTool(Tool):
|
||||
async def _resolve_password(
|
||||
self, ctx: AppContext, admin_node: Contact, params: dict[str, Any]
|
||||
) -> str:
|
||||
"""Find the admin password: explicit flag, remembered, or an interactive prompt.
|
||||
"""Find the admin password: from the flag, from the store, or from a prompt.
|
||||
|
||||
The question this asks is **"is anyone there to answer?"**, and it used to ask
|
||||
``--json`` instead — a flag about what the output looks like, which cannot answer
|
||||
it and answered it wrong in both directions: with the flag a piped run failed
|
||||
cleanly, and without it a scheduled run on a terminal sat waiting for a password
|
||||
nobody was going to type. ``ctx.interactive`` reads stdin, which is where the
|
||||
answer actually is.
|
||||
The question that this method asks is **"is a person there to answer?"**. Before,
|
||||
it asked ``--json`` instead. That flag is about the look of the output, so it
|
||||
cannot answer the question, and its answer was wrong in both directions. With the
|
||||
flag, a piped run failed cleanly. Without it, a scheduled run on a terminal waited
|
||||
for a password, but no person was there to type it. ``ctx.interactive`` reads stdin,
|
||||
which is where the answer is.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
admin_node: The node we're about to log in to.
|
||||
params: Tool params (may carry an explicit ``password``).
|
||||
ctx: The shared application context.
|
||||
admin_node: The node that we will log in to.
|
||||
params: The tool parameters (they can hold an explicit ``password``).
|
||||
|
||||
Returns:
|
||||
The password to log in with.
|
||||
The password for the login.
|
||||
|
||||
Raises:
|
||||
typer.BadParameter: If no password is available and nobody can be asked for
|
||||
one. A usage error rather than a device failure: nothing was transmitted,
|
||||
and no retry helps until the command line carries the password.
|
||||
typer.BadParameter: If no password is available and MeshTerm cannot ask
|
||||
anyone for one. This is a usage error, not a device failure: nothing was
|
||||
transmitted, and a retry cannot help until the command line has the
|
||||
password.
|
||||
"""
|
||||
password = params.get("password") or ctx.admin_store.get(admin_node)
|
||||
if password:
|
||||
@@ -366,8 +380,8 @@ class TxOptimizeTool(Tool):
|
||||
f"no admin password for {admin_node.name!r}; pass --password or run once "
|
||||
"interactively to store it."
|
||||
)
|
||||
# This resolver only runs on the scripted CLI path (the menu logs in inside the pushed
|
||||
# sweep screen), so the surface here is PlainUi — no screen stack, no floating.
|
||||
# This resolver runs only on the scripted CLI path (the menu logs in from the pushed
|
||||
# sweep screen). Thus the surface here is PlainUi: no screen stack, no floating.
|
||||
entered = await ctx.ui.text(f"Admin password for {admin_node.name}:", password=True)
|
||||
if not entered:
|
||||
raise typer.BadParameter("an admin password is required to tune a remote node.")
|
||||
@@ -386,9 +400,10 @@ class TxOptimizeTool(Tool):
|
||||
path: str = typer.Option(
|
||||
...,
|
||||
"--path",
|
||||
# No ``-p`` short form: ``-p`` is the global ``--profile``, and
|
||||
# ``_globals_first`` lifts a group option ahead of the subcommand wherever it
|
||||
# is typed — so a leaf ``-p`` could never reach this option, only shadow it.
|
||||
# No ``-p`` short form. ``-p`` is the global ``--profile``, and
|
||||
# ``_globals_first`` moves a group option in front of the subcommand, at any
|
||||
# position where it is typed. Thus a leaf ``-p`` can never get to this option.
|
||||
# It can only hide it.
|
||||
help="Forced path ending at the target (e.g. 'Repeater,Target' or '3d,f2')",
|
||||
),
|
||||
samples: int = typer.Option(3, "--samples", "-n", help="Traces per TX level"),
|
||||
@@ -416,23 +431,24 @@ class TxOptimizeTool(Tool):
|
||||
|
||||
|
||||
def _resolve_link(path: str, contacts: list[Contact]) -> tuple[Contact, str]:
|
||||
"""Split a forced path into the admin node we tune and the target's display label.
|
||||
"""Divide a forced path into the admin node that we tune and the label of the target.
|
||||
|
||||
Args:
|
||||
path: The comma-separated hash path (output of ``parse_trace_path``).
|
||||
contacts: Known contacts, used to map hashes back to names/keys.
|
||||
path: The hash path, with commas between the hops (the output of
|
||||
``parse_trace_path``).
|
||||
contacts: The known contacts. They change hashes back into names and keys.
|
||||
|
||||
Returns:
|
||||
``(admin_node, target_label)`` — the second-to-last hop as a full
|
||||
:class:`Contact` (needed for login), and a friendly name for the last hop.
|
||||
``(admin_node, target_label)``: the second-to-last hop as a full :class:`Contact`
|
||||
(it is necessary for the login), and a friendly name for the last hop.
|
||||
|
||||
Raises:
|
||||
typer.BadParameter: If the path has fewer than two hops — the argument is what is
|
||||
wrong and nothing was transmitted, so that is a usage error (exit 2), not a
|
||||
device failure.
|
||||
DeviceCommandError: If the admin hop can't be matched to a known contact carrying a
|
||||
public key. That one *is* about the mesh: the path is well formed and we simply
|
||||
have not heard from the node it names.
|
||||
typer.BadParameter: If the path has fewer than two hops. The argument is wrong and
|
||||
nothing was transmitted. Thus that is a usage error (exit 2), not a device
|
||||
failure.
|
||||
DeviceCommandError: If no known contact with a public key matches the admin hop.
|
||||
That error *is* about the mesh: the path is correct, but we have not heard
|
||||
from the node that it names.
|
||||
"""
|
||||
hops = [h for h in path.split(",") if h]
|
||||
if len(hops) < 2:
|
||||
@@ -451,14 +467,14 @@ def _resolve_link(path: str, contacts: list[Contact]) -> tuple[Contact, str]:
|
||||
|
||||
|
||||
def _contact_for_hash(hash_hex: str, contacts: list[Contact]) -> Contact | None:
|
||||
"""Return the contact whose key matches a path-hop hash, if any.
|
||||
"""Return the contact whose key matches the hash of a path hop, if there is one.
|
||||
|
||||
Args:
|
||||
hash_hex: A path hop hash (a leading slice of the node's public key).
|
||||
contacts: Known contacts to match against.
|
||||
hash_hex: The hash of a path hop (the first part of the public key of the node).
|
||||
contacts: The known contacts to compare with.
|
||||
|
||||
Returns:
|
||||
The matching :class:`Contact`, or ``None``.
|
||||
The :class:`Contact` that matches, or ``None``.
|
||||
"""
|
||||
needle = hash_hex.lower().removeprefix("0x")
|
||||
for c in contacts:
|
||||
@@ -472,18 +488,20 @@ def _contact_for_hash(hash_hex: str, contacts: list[Contact]) -> Contact | None:
|
||||
|
||||
|
||||
def _target_items(contacts: list[Contact], admin: Contact) -> list:
|
||||
"""The *measure at* list's rows, ordered by how recently each node was heard.
|
||||
"""The rows of the *measure at* list, in the order of how recently each node was heard.
|
||||
|
||||
Rows carry the contact's **name** as their value, since a typed hex prefix stands in the
|
||||
same place (see :meth:`TxOptimizeTool._run_live`). Empty when the tuned node is the only
|
||||
contact there is — the caller falls back to a typed prefix.
|
||||
The value of each row is the **name** of the contact, because a typed hex prefix can
|
||||
go in the same place (refer to :meth:`TxOptimizeTool._run_live`). The list is empty
|
||||
when the tuned node is the only contact. Then the caller asks for a typed prefix.
|
||||
|
||||
Args:
|
||||
contacts: The device's known contacts.
|
||||
admin: The already-picked tuned node (excluded — it can't measure itself).
|
||||
contacts: The known contacts of the device.
|
||||
admin: The tuned node, which the user already selected. It is not in the list,
|
||||
because it cannot measure itself.
|
||||
|
||||
Returns:
|
||||
One :class:`~meshterm.ui.tui.select.Choice` per other contact, freshest first.
|
||||
One :class:`~meshterm.ui.tui.select.Choice` for each other contact, the most
|
||||
recently heard first.
|
||||
"""
|
||||
from rich.text import Text
|
||||
|
||||
@@ -492,9 +510,10 @@ def _target_items(contacts: list[Contact], admin: Contact) -> list:
|
||||
from ..ui.widgets import DEFAULT_GLYPH, NODE_GLYPHS
|
||||
|
||||
def row(contact: Contact) -> Any:
|
||||
# The type mark keeps its own fixed hue; the *name* takes the node's key-derived
|
||||
# colour like every other list of nodes (a style on the Text itself would be the
|
||||
# row's base and would paint the name the type's colour too).
|
||||
# The type mark keeps its own fixed hue. The *name* gets the hue of the node, which
|
||||
# comes from its key, the same as in each other list of nodes. (A style on the
|
||||
# Text itself becomes the base of the row, and then the name also gets the colour
|
||||
# of the type.)
|
||||
glyph, glyph_style = NODE_GLYPHS.get(contact.node_type, DEFAULT_GLYPH)
|
||||
label = Text()
|
||||
label.append(f"{glyph} ", style=glyph_style)
|
||||
@@ -517,10 +536,10 @@ def _fmt_snr(snr: float | None) -> str:
|
||||
"""Format an optional SNR for the progress description.
|
||||
|
||||
Args:
|
||||
snr: SNR in dB, or ``None``.
|
||||
snr: The SNR in dB, or ``None``.
|
||||
|
||||
Returns:
|
||||
A short fixed-width string like ``+5.1`` or `` n/a``.
|
||||
A short string with a fixed width, for example ``+5.1`` or `` n/a``.
|
||||
"""
|
||||
return f"{snr:+.1f}" if snr is not None else " n/a"
|
||||
|
||||
@@ -528,33 +547,33 @@ def _fmt_snr(snr: float | None) -> str:
|
||||
def _sweep_report(
|
||||
result: TxOptResult, path: str, admin_node: Contact, contacts: list[Contact]
|
||||
) -> tuple:
|
||||
"""State a TX sweep: the outcome, then every level measured.
|
||||
"""State a TX sweep: the result, then each measured level.
|
||||
|
||||
The winner comes first, because it is what the command was asked for and what a caller
|
||||
acts on; the per-level records follow, so the choice can be checked against the
|
||||
measurements it was made from. The menu's ``★`` on the winning row has no column here
|
||||
— ``optimal_tx_dbm`` above the table already names it, and a mark is something to look
|
||||
at rather than something to test.
|
||||
The best level comes first, because the command was asked for it, and a caller acts
|
||||
on it. The records of each level come after it, so that a person can compare the
|
||||
choice with the measurements that it came from. The ``★`` that the menu puts on the
|
||||
best row has no column here. ``optimal_tx_dbm`` above the table already names that
|
||||
level, and a mark is a thing to look at, not a thing to test.
|
||||
|
||||
The two nodes become the shared node shape, and here that matters more than anywhere
|
||||
else: on the plain line they are told apart by nothing but their names, and a caller
|
||||
correlating a sweep with a trace has no key to join on.
|
||||
The two nodes use the shared node shape. Here that is more important than in other
|
||||
places. On the plain line, only their names tell them apart. Without the shape, a
|
||||
caller who compares a sweep with a trace has no key to join them on.
|
||||
|
||||
Args:
|
||||
result: The completed sweep.
|
||||
path: The forced route the traces walked, as hex hops.
|
||||
path: The forced route that the traces went through, as hex hops.
|
||||
admin_node: The node whose TX power was tuned.
|
||||
contacts: The contact list, for placing the target by name.
|
||||
contacts: The contact list, to find the target by its name.
|
||||
|
||||
Returns:
|
||||
The report's blocks.
|
||||
The blocks of the report.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.fields import NodeRef
|
||||
from ..ui.report import Facts, Listing
|
||||
|
||||
def node(name: str) -> NodeRef | None:
|
||||
"""One end of the tuned link as the shared node shape."""
|
||||
"""One end of the tuned link, in the shared node shape."""
|
||||
contact = next((c for c in contacts if c.name == name), None)
|
||||
if contact is None:
|
||||
return NodeRef(name=name) if name else None
|
||||
@@ -583,8 +602,8 @@ def _sweep_report(
|
||||
"path": path,
|
||||
"optimal_tx_dbm": result.best_tx,
|
||||
"target_snr_db": result.best_snr,
|
||||
# A fraction in [0, 1], not a formatted "1.00": the plain column rounds for
|
||||
# the eye and the document keeps the number a number.
|
||||
# A fraction in [0, 1], not a formatted "1.00". The plain column rounds it so
|
||||
# that it is easy to read, and the document keeps the number as a number.
|
||||
"reliability": result.best_success_rate,
|
||||
"previous_tx_dbm": result.original_tx,
|
||||
"applied": result.applied,
|
||||
|
||||
+27
-27
@@ -1,17 +1,17 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``walk`` tool: the mesh's observed shape, explored one node at a time.
|
||||
"""The ``walk`` tool: the observed shape of the mesh, explored one node at a time.
|
||||
|
||||
Opens the full-screen Mesh walk (see :mod:`meshterm.ui.walk_screen`): a walkable
|
||||
browser over the evidence graph — trace walks, firmware routes, overheard relay
|
||||
chains, repeater neighbour tables. One node holds the focus, its neighbourhood draws
|
||||
as SNR-coloured braille edges on a small clean canvas, and its links list beneath as
|
||||
rows with quality bars and evidence; Enter walks the graph, ⌫ backtracks along the
|
||||
breadcrumb trail, and typing finds any node (islands included). The geographic map
|
||||
answers *where* the mesh is; the walk answers *how it hangs together*.
|
||||
The tool opens the full-screen Mesh walk (refer to :mod:`meshterm.ui.walk_screen`). It is
|
||||
a browser in which the user walks over the evidence graph: trace walks, firmware routes,
|
||||
heard relay chains, and repeater neighbour tables. One node has the focus. Its
|
||||
neighbourhood draws as SNR-coloured braille edges on a small clean canvas, and its links
|
||||
show below it as rows with quality bars and evidence. Enter walks the graph, ⌫ goes back
|
||||
along the breadcrumb trail, and typed text finds any node (also the islands). The
|
||||
geographic map tells where the mesh is. The walk tells how the nodes of the mesh connect.
|
||||
|
||||
Menu-only: the walk is an interactive reading of stored evidence (and transmits
|
||||
nothing), so there is no scripted one-shot to register — ``trace``-family commands
|
||||
already print path evidence in scripted runs.
|
||||
Menu only: with the walk, the user examines stored evidence interactively (and the walk
|
||||
transmits nothing). Thus there is no scripted one-shot command to register. The commands
|
||||
of the ``trace`` family already print path evidence in scripted runs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,29 +26,29 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
@register
|
||||
class WalkTool(Tool):
|
||||
"""See how the mesh hangs together: the observed link graph, walkable."""
|
||||
"""See how the nodes of the mesh connect: the observed link graph, which the user walks."""
|
||||
|
||||
name = "walk"
|
||||
title = "Mesh walk"
|
||||
# A single-codepoint emoji (like every other tool icon), not a VS16 sequence: the
|
||||
# emoji-width calibration strips VS16 on terminals that render it narrow, which would
|
||||
# A single-codepoint emoji (as all the other tool icons are), not a VS16 sequence. On a
|
||||
# terminal that renders VS16 narrow, the emoji-width calibration removes VS16. Thus it can
|
||||
# measure a 🕸️ one cell short of how it paints and drift this row's help text right of
|
||||
# the column the others align to. The wireframe globe reads as the logical topology,
|
||||
# the geographic map's 🌍 counterpart.
|
||||
# the column to which the other rows align. The wireframe globe shows the logical
|
||||
# topology. It is the equivalent of the 🌍 of the geographic map.
|
||||
icon = "🌐"
|
||||
help = "Walk the observed topology — links and SNR"
|
||||
category = "Explore"
|
||||
order = 20 # beside Map: the logical shape next to the geographic one
|
||||
order = 20 # next to Map: the logical shape next to the geographic shape
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the walk; there are never parameters to collect.
|
||||
"""Run the walk. It has no parameters to collect.
|
||||
|
||||
The screen presents everything itself and returns when dismissed, so
|
||||
returning ``None`` tells the menu the invocation is complete (the same
|
||||
The screen shows all its content itself, and it returns when the user leaves it.
|
||||
Thus the return value ``None`` tells the menu that the run is complete (the same
|
||||
pattern as the ``dashboard`` tool).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -59,20 +59,20 @@ class WalkTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Nothing runs here: the walk lives inside :meth:`prompt_params`.
|
||||
"""Nothing runs here: the walk is in :meth:`prompt_params`.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
An empty :class:`ToolResult` (only reachable from a scripted call).
|
||||
An empty :class:`ToolResult` (only a scripted call comes here).
|
||||
"""
|
||||
return ToolResult(summary={})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — the walk is an interactive, menu-only screen.
|
||||
"""Register no CLI command, because the walk is an interactive screen for the menu only.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
@@ -1,16 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The ``watchtower`` tool: a passive sentinel over the nodes you care about.
|
||||
"""The ``watchtower`` tool: a passive sentinel for the nodes that are important to you.
|
||||
|
||||
Opens the Watchtower screen (see :mod:`meshterm.ui.watchtower_screen`): the alert log
|
||||
with acknowledge/clear, the watchlist, and per-node rules. The rules themselves run in
|
||||
the background for the whole session (see :mod:`meshterm.services.watchtower`) — a
|
||||
silence alarm when a starred node goes quiet, an SNR-sag warning when its receptions
|
||||
degrade, a recovery note when it returns, and a mesh-wide heads-up when a never-before-
|
||||
seen node appears. Unacknowledged alerts show as the ``▲ n`` badge in the header, so
|
||||
nothing here needs to be open to be on duty.
|
||||
The tool opens the Watchtower screen (refer to :mod:`meshterm.ui.watchtower_screen`): the
|
||||
alert log with acknowledge and clear, the watchlist, and the rules for each node. The
|
||||
rules run in the background for the whole session (refer to
|
||||
:mod:`meshterm.services.watchtower`):
|
||||
|
||||
Menu-only: the sentinel is inherently a live, session-long service; scripted runs can
|
||||
read the same history through ``monitor``/``nodes``.
|
||||
- A silence alarm when MeshTerm no longer hears a starred node.
|
||||
- An SNR-sag warning when the receptions of the node become weaker.
|
||||
- A recovery note when the node comes back.
|
||||
- A notice for the whole mesh when a node appears that MeshTerm never heard before.
|
||||
|
||||
The header shows the alerts that are not acknowledged as the ``▲ n`` badge. Thus this
|
||||
screen does not have to be open for the watch to work.
|
||||
|
||||
Menu only: the sentinel is always a live service for the whole session. Scripted runs can
|
||||
read the same history through ``monitor`` and ``nodes``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,24 +30,24 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
@register
|
||||
class WatchtowerTool(Tool):
|
||||
"""Watch starred nodes: silence alarms, SNR sag, new-node sightings."""
|
||||
"""Watch starred nodes: silence alarms, SNR sag, and new nodes that are heard."""
|
||||
|
||||
name = "watchtower"
|
||||
title = "Watchtower"
|
||||
icon = "🚨"
|
||||
help = "Alerts on watched nodes — silence, SNR sag"
|
||||
category = "Watch"
|
||||
order = 30 # after the live views: the section's always-on alerting eye
|
||||
order = 30 # after the live screens: the alerts of the section, which are always on
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
|
||||
"""Run the Watchtower screen; there are never parameters to collect.
|
||||
"""Run the Watchtower screen. It has no parameters to collect.
|
||||
|
||||
The screen presents everything itself and returns when dismissed, so
|
||||
returning ``None`` tells the menu the invocation is complete (the same
|
||||
The screen shows all its content itself, and it returns when the user leaves it.
|
||||
Thus the return value ``None`` tells the menu that the run is complete (the same
|
||||
pattern as the ``dashboard`` tool).
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
Always ``None``.
|
||||
@@ -53,20 +58,20 @@ class WatchtowerTool(Tool):
|
||||
return None
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Nothing runs here: the Watchtower lives inside :meth:`prompt_params`.
|
||||
"""Nothing runs here: the Watchtower is in :meth:`prompt_params`.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Unused.
|
||||
ctx: The shared application context.
|
||||
params: Not used.
|
||||
|
||||
Returns:
|
||||
An empty :class:`ToolResult` (only reachable from a scripted call).
|
||||
An empty :class:`ToolResult` (only a scripted call comes here).
|
||||
"""
|
||||
return ToolResult(summary={})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register no CLI command — the Watchtower is a live, menu-only feature.
|
||||
"""Register no CLI command, because the Watchtower is a live feature for the menu only.
|
||||
|
||||
Args:
|
||||
app: The Typer application (untouched).
|
||||
app: The Typer application (not changed).
|
||||
"""
|
||||
Reference in new issue
Block a user