diff --git a/.claude/settings.json b/.claude/settings.json
index 495526c..33c9f72 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -17,7 +17,14 @@
"Bash(python -m pytest tests/test_tui.py -q -k \"overlay or progress\")",
"PowerShell([console]::beep\\(880,150\\); Start-Sleep -Milliseconds 60; [console]::beep\\(1175,200\\))",
"Bash(PYTHONUTF8=1 PYTHONIOENCODING=utf-8 python -m pytest tests/test_tui.py -q -k \"busy_overlay or scanner or dim_color or overlay_fade\")",
- "Bash(PYTHONUTF8=1 PYTHONIOENCODING=utf-8 python -m pytest -q)"
+ "Bash(PYTHONUTF8=1 PYTHONIOENCODING=utf-8 python -m pytest -q)",
+ "Bash(python -c ' *)",
+ "Bash(grep -v \"^$\")",
+ "Bash(PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python -c ' *)",
+ "Bash(python -m pytest tests/test_channels.py -q)",
+ "Bash(git commit -m ' *)",
+ "Bash(.venv/Scripts/python.exe -m meshterm --mock trace --target Alice --profile yagi)",
+ "Bash(echo \"=== EXIT: $? ===\")"
],
"defaultMode": "dontAsk",
"additionalDirectories": [
diff --git a/README.md b/README.md
index be8a3ab..9ef4d7d 100644
--- a/README.md
+++ b/README.md
@@ -1,54 +1,140 @@
# MeshTerm
-A modern, extensible command-line toolkit for tuning and exploring a
-[MeshCore](https://meshcore.co.uk/) mesh through a serial- or Bluetooth-connected companion
-device.
+**A full-screen terminal companion for [MeshCore](https://meshcore.co.uk/) LoRa mesh
+devices** — tune your radio, chat across the mesh, watch the network live, and keep a
+longitudinal record of everything you overhear, all from a connected serial, Bluetooth, or
+network (TCP) companion.
-MeshTerm is interactive by default (a full-screen Rich + prompt_toolkit TUI) and fully
-scriptable (every menu option is also a Typer subcommand). Every run is logged to SQLite,
-building a longitudinal history of the mesh.
+MeshTerm is interactive by default: a modern, keyboard-driven TUI built on
+[Rich](https://github.com/Textualize/rich) and
+[prompt_toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit). It is also
+fully scriptable — **every screen has a mirror `meshterm` subcommand** — so the same
+capabilities drive both an evening of exploring the mesh and a cron job. Every packet the
+radio overhears is recorded to a local SQLite database, so the longer you run it, the more
+your mesh's history is worth.
-## Features
+
+
+
+
+
-| Feature | Status | What it does |
-| --- | --- | --- |
-| **Chat** | ✅ working | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. Every message is logged to SQLite, unread counts show in the menu header, and `chat send/history/list` script the same from the CLI. Channels are picked here; edit them in `config`. |
-| **Channels** | ✅ working | Create, join, reorder, and share mesh channels — with QR codes and `meshcore://` links. |
-| **Map** | ✅ working | Mesh nodes on a pannable street map, repeaters highlighted, fed by everything the monitor has overheard. |
-| **Device config** | ✅ working | View and change every setting (name, radio, behavior, experimental), with TOML backup/restore, channels, and gated destructive ops. |
-| **Device discovery** | ✅ working | Enumerate serial *and* Bluetooth LE companions, pick one interactively, and remember the last good default. A dropped link (unplug, power-off, or BLE out-of-range) is detected live and offers to reconnect. |
-| **Node list** | ✅ working | List this node and its known contacts — recency heat-map, overheard packet counts, full public keys with the path-hash prefix highlighted. |
-| **Trace** | ✅ working | A live trace screen: pick a target, watch each trace stream in hop by hop, with running per-hop medians and reliability. |
-| **TX-power optimization** | ✅ working | Sweep a remote node's transmit power live (coarse + refine + verify), watch each level land, then decide whether to apply the winner. |
-| **Passive monitor** | ✅ working | Always-on background logger that records every overheard advert/telemetry (SNR, RSSI, location) to a longitudinal history while you use the app; live packet counts show in the menu header, the data feeds Nodes and Map, and `meshterm monitor --seconds 60` captures a bounded window from the CLI. |
+
+
+---
+
+## Why MeshTerm
+
+- **One tool, two faces.** Launch `meshterm` for a full-screen menu; pass a subcommand for
+ a scripted one-shot. The registry that builds the menu builds the CLI, so they never
+ drift apart.
+- **It remembers.** A passive monitor logs every overheard advert and telemetry frame —
+ SNR, RSSI, shared location — to SQLite from the moment the radio opens. Maps, node lists,
+ charts, and the Time Machine all read back that history.
+- **It measures.** Live trace with per-hop reliability, a coarse→refine→verify TX-power
+ sweep, and a walkable graph of how the mesh actually hangs together.
+- **It talks.** Live channel and direct messaging, store-and-forward courier delivery for
+ nodes that aren't there yet, and shareable channels as QR codes and `meshcore://` links.
+- **It connects however your companion does.** Serial (USB), Bluetooth LE, or TCP (a WiFi
+ board or a network proxy) — the discoverable transports are auto-found and picked
+ interactively, a network device is named by hand, and every kind reconnects live when a link
+ drops. No radio? A built-in simulator covers development.
+- **It works offline.** The street map caches OpenStreetMap tiles to disk and falls back to
+ a blank grid when there's no network — it never needs the internet to run.
## Install
```bash
+git clone meshterm
+cd meshterm
pip install -e ".[dev]"
```
-Python 3.10+ is required (matching the `meshcore` library).
-
-## Usage
+Python **3.10+** is required (matching the `meshcore` library). The `[dev]` extra adds
+pytest and ruff; drop it for a runtime-only install (`pip install -e .`).
```bash
-# Interactive menu (default)
+python -m pytest -q # run the test suite
+```
+
+## Quick start
+
+```bash
+# Interactive full-screen menu (auto-discovers serial + Bluetooth companions)
meshterm
-# Connect over Bluetooth instead of USB (address from `meshterm devices`)
+# Connect over Bluetooth (address from `meshterm devices`)
meshterm --ble AA:BB:CC:DD:EE:FF info
-# Scripted: every menu option is also a subcommand. A trace transmits exactly once —
-# repeaters can blacklist nodes that burst traffic — so run it again to sample more.
+# Connect over the network to a TCP companion (host[:port], port defaults to 5000)
+meshterm --tcp 192.168.1.50 info
+
+# No radio attached? Use the built-in simulator for development.
+meshterm --mock
+```
+
+## Features
+
+MeshTerm's menu is organised into four sections. Every interactive screen is listed here
+with its scripted equivalent, where one exists.
+
+### 🛰 Mesh — what's going on out there
+
+| Feature | What it does | Scripted |
+| --- | --- | --- |
+| **📊 Dashboard** | The live mesh overview: a two-hour all-packet activity chart with a pulse line, session traffic tallies by packet class, window RF health beside the radio's own live numbers, and a streaming packet feed. Repaints every second. | — |
+| **🌍 Map** | Located nodes plotted over a real OpenStreetMap street basemap rendered as Unicode braille (streets, rivers, place names). Pannable and zoomable; repeaters highlighted and drawn on top. Falls back to a blank grid offline. | `meshterm map` (one-shot render) |
+| **🌐 Mesh atlas** | The mesh's *observed shape*, walked one node at a time: an evidence graph built from trace walks, firmware routes, overheard relay chains, and repeater neighbour tables. SNR-coloured braille edges, quality bars, Enter to walk, ⌫ to backtrack, type to find any node. The map answers *where*; the atlas answers *how it hangs together*. | — |
+| **🚨 Watchtower** | A passive sentinel over the nodes you star: silence alarms when a watched node goes quiet, SNR-sag warnings when reception degrades, recovery notes when it returns, and a heads-up when a never-before-seen node appears. Runs in the background all session; unacked alerts show as a header badge. | — |
+| **📡 Send advert** | Announce this node to the mesh — a zero-hop or flood advertisement, or share this node's contact card as a QR code. | `meshterm config advert` / `config share` |
+
+### 💬 Messaging
+
+| Feature | What it does | Scripted |
+| --- | --- | --- |
+| **💬 Chat** | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. Every message is logged; unread counts show in the menu header. | `meshterm chat send / history / list` |
+| **# Channels** | Create, join, reorder, mute, and share mesh channels — with QR codes and `meshcore://` share links. | `meshterm channels list / add / join / import / share / clear` |
+| **📨 Courier** | Store-and-forward outbox for nodes that aren't reachable yet. Queue a message; it goes out (with ack tracking and polite exponential backoff) the moment the node is next heard, or at a scheduled time. | `meshterm courier queue / list / send / cancel / clear` |
+
+### ⚙ Device management
+
+| Feature | What it does | Scripted |
+| --- | --- | --- |
+| **📋 Device info** | The connected companion's identity and full radio configuration at a glance. | `meshterm info` |
+| **🔨 Device actions** | Immediate operations on the box itself: clock sync, TOML backup/restore, the identity key, reboot, and factory reset — each acting the moment it's confirmed, with destructive ops gated. | `config backup` / `restore` / `reboot` / … |
+| **🔧 Config** | View and *stage* changes to every setting (name, radio, behaviour, experimental) for review before applying, with TOML backup/restore. | `meshterm config` / `config set ` |
+| **🗼 Repeater admin** | Set up remote repeaters and room servers over the mesh: log in (remembered or prompted password), then a config-style editor speaking the node's text CLI — including repeater-only knobs (TX delay, airtime factor, advert intervals) — plus one-shot actions and a readline remote command line. | `meshterm repeater-admin ` |
+
+### 🧰 Tools — measure and explore
+
+| Feature | What it does | Scripted |
+| --- | --- | --- |
+| **☰ Nodes** | This node and its known contacts — a recency heat-map, overheard packet counts, and full public keys with the path-hash prefix highlighted. | `meshterm nodes` |
+| **🧭 Trace** | A live trace screen: pick a target and watch each trace stream in hop by hop, with running per-hop medians and reliability. Compose or force a route through specific repeaters. A trace transmits **exactly once** (repeaters can blacklist nodes that burst) — sample more by running it again. | `meshterm trace --target …` |
+| **⚡ TX-power optimization** | Sweep a remote node's transmit power live — coarse, then refine, then verify — watch each level land, and decide whether to apply the winner. | `meshterm tx-optimize --path … [--apply]` |
+| **⏳ Time machine** | Everything the recorder ever heard, as braille charts: reception volume, the median-SNR band, hour-of-day rhythm, packets and nodes per day, and first-ever arrivals — over a switchable 24h / 7d / 30d / all-time window, per node or mesh-wide. | — |
+| **🎧 Monitor** | Passive recording is always on in the app. On the CLI, capture a bounded foreground window, tailing each overheard packet and summarising when it ends. It transmits nothing — it only listens. | `meshterm monitor --seconds 60` |
+| **🔌 Device discovery** | Enumerate serial *and* Bluetooth LE companions, pick one interactively (or auto-select the only one present), add a network (TCP) companion by host:port, and remember the last good default. A dropped link is detected live and offers to reconnect. | `meshterm devices` |
+
+## CLI cookbook
+
+Every menu option is also a Typer subcommand — ideal for scripting, cron, and bots.
+
+```bash
+# Trace — a trace transmits exactly once; run it again to sample more.
meshterm trace --target Alice --profile yagi
# Force a route through specific repeaters (MeshCore-app style): comma-separated
# contact names and/or hex key prefixes, mixed freely. Blank lets the device route.
meshterm trace --target Alice --path "3d,f2,3d"
meshterm trace --target Alice --path "3d,Bravo-Repeater,f2"
+
+# Sweep and apply a remote node's TX power
meshterm tx-optimize --path "Bravo-Repeater,Alice" --samples 6 --step 3 --apply
-meshterm info
# Messaging: live chat in the menu, or scripted from the CLI
meshterm chat # interactive: pick a conversation, chat live
@@ -57,26 +143,76 @@ meshterm chat send --channel 0 "net in 5" # channel broadcast
meshterm chat history --to Alice
meshterm chat list
+# Store-and-forward: queue for a node that's offline right now
+meshterm courier queue Alice "ping me when you're back" --at 18:30
+meshterm courier list # the outbox — waiting and finished
+meshterm courier send 3 # force one delivery attempt now
+
+# Remote repeater admin (one transmission per invocation)
+meshterm repeater-admin Bravo-Repeater "get name"
+
# Device configuration: view, set, back up, restore
meshterm config # show all current settings
meshterm config set radio_sf 9 # change one setting
meshterm config backup node.toml # archive every setting to TOML
meshterm config restore node.toml --dry-run
+meshterm config advert-cadence 2 # auto-advert to neighbours every 2 h (0 = off)
+meshterm config advert-cadence 24 --flood # flood the wider mesh daily
-# No radio attached? Use the built-in simulator for development.
-meshterm --mock trace --target Alice
+# Passive capture window (records to history; transmits nothing)
+meshterm monitor --seconds 60
```
+Global options (before the subcommand): `--profile/-p`, `--port`, `--ble`, `--ble-pin`,
+`--tcp`, `--mock`, `--db`, `--json`, `--quiet/-q`.
+
+## Configuration
+
+MeshTerm runs with zero configuration — it discovers attached serial devices and nearby
+Bluetooth companions, lets you pick one, and remembers the last good default. A network (TCP)
+companion isn't discoverable, so reach it with `--tcp host:port`, a TCP profile, or the
+picker's "add a network device" prompt. Define a config file only to give your hardware stable
+aliases or tune behaviour.
+
+Copy [`config.example.toml`](config.example.toml) to `~/.meshterm/config.toml`:
+
+```toml
+default_profile = "s3"
+trace_cooldown_s = 1.0
+direct_message_soft_retries = 2 # auto-resend an unacked DM up to N extra times (0–2)
+history_days = 365 # days of overheard-packet history to keep (0 = forever)
+
+[profiles.s3]
+port = "COM5"
+baudrate = 115200
+default_tx_power = 20
+description = "XIAO ESP32-S3 + Wio SX1262 serial companion"
+
+# A Bluetooth LE companion: give it an `address` instead of a `port`.
+[profiles.handheld]
+address = "AA:BB:CC:DD:EE:FF"
+# ble_pin = "123456" # only if your device requires a pairing PIN
+description = "Pocket handheld over Bluetooth"
+
+# A network (TCP) companion: give it a `host` (and optional `tcp_port`, default 5000).
+[profiles.wifi]
+host = "192.168.1.50"
+description = "Basestation over WiFi"
+```
+
+Timestamps are stored as UTC and rendered in your local time. History older than
+`history_days` is pruned once at session start.
+
## Architecture
-MeshTerm is layered so features are added by dropping a single file in `meshterm/tools/`:
+MeshTerm is layered so a new feature is one file in `meshterm/tools/`:
```
cli.py Typer app; no subcommand -> interactive menu
context.py AppContext (console, config, repository, device) dependency container
core/ Domain: models, config + device profiles, connection abstraction (+ mock)
tools/ Pluggable "menu options"; each self-registers and gets logging for free
-services/ Algorithms (trace aggregation, tx search) — no UI
+services/ Background algorithms (monitor, trace, tx search, courier, watchtower) — no UI
persistence/ SQLite schema, repository, structured logging
ui/ Rich theme/widgets + the full-screen TUI (screens, dialogs, map, chat)
viz/ Plotly renderers -> interactive HTML
@@ -85,3 +221,49 @@ viz/ Plotly renderers -> interactive HTML
Adding a feature means subclassing `Tool`, decorating it with `@register`, and
implementing `run()`. The same registry builds both the CLI and the menu, and the base
class wraps every execution in a logged `runs` row automatically.
+
+## Development
+
+```bash
+pip install -e ".[dev]"
+python -m pytest -q # tests
+ruff check . # lint
+ruff format . # format
+```
+
+Screens are designed to stay readable at **72 columns**.
+
+## Acknowledgements & attribution
+
+MeshTerm stands on the [MeshCore](https://meshcore.co.uk/) project — its firmware and the
+`meshcore` Python companion library are what make talking to the radio possible.
+
+### Map data
+
+The street map is rendered from **© OpenStreetMap contributors** data, served as vector
+tiles by [OpenFreeMap](https://openfreemap.org/). OpenStreetMap data is available under the
+[Open Database License (ODbL)](https://www.openstreetmap.org/copyright). Tiles are decoded
+with a small built-in reader for the [Mapbox Vector Tile](https://github.com/mapbox/vector-tile-spec)
+format.
+
+### Open-source dependencies
+
+MeshTerm is built with these libraries; each is used under its own license (see the
+respective project for the authoritative terms):
+
+| Library | Role | License |
+| --- | --- | --- |
+| [meshcore](https://pypi.org/project/meshcore/) | Companion-device protocol (serial / BLE) | MIT |
+| [pycryptodome](https://www.pycryptodome.org/) | AES/HMAC for decrypting overheard channel packets | BSD-2-Clause / Public Domain |
+| [pyserial](https://github.com/pyserial/pyserial) | Serial-port enumeration and I/O | BSD-3-Clause |
+| [bleak](https://github.com/hbldh/bleak) | Bluetooth LE scanning + connection | MIT |
+| [Typer](https://typer.tiangolo.com/) | Scripted CLI (subcommands mirror the menu) | MIT |
+| [Rich](https://github.com/Textualize/rich) | Console rendering | MIT |
+| [prompt_toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) | Full-screen interactive TUI | BSD-3-Clause |
+| [Plotly](https://plotly.com/python/) | Self-contained interactive HTML charts | MIT |
+| [Segno](https://github.com/heuer/segno) | Pure-Python QR codes (channel share links) | BSD-3-Clause |
+| [tomli](https://github.com/hukkin/tomli) / [tomli-w](https://github.com/hukkin/tomli-w) | TOML config read/write | MIT |
+
+## License
+
+Copyright © 2026 Jean-Pierre Martineau.
diff --git a/config.example.toml b/config.example.toml
index 6bb375f..cb0fb95 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -1,11 +1,12 @@
# MeshTerm configuration.
# Copy to ~/.meshterm/config.toml (or pass --db / --port on the CLI).
#
-# Profiles are optional. With no profile, no --port, and no --ble, MeshTerm discovers
-# attached serial devices and nearby Bluetooth companions, lets you pick one (interactively)
-# or uses the single one present, and remembers the last device that connected as the default
-# for next time. Define profiles below only to give your hardware stable aliases
-# (e.g. --profile yagi, or --profile handheld for a Bluetooth device).
+# Profiles are optional. With no profile, no --port/--ble/--tcp, MeshTerm discovers attached
+# serial devices and nearby Bluetooth companions, lets you pick one (interactively) or uses the
+# single one present, and remembers the last device that connected as the default for next time.
+# A network (TCP) companion isn't discoverable — name it with --tcp host:port, a TCP profile, or
+# the picker's "add a network device" prompt. Define profiles below only to give your hardware
+# stable aliases (e.g. --profile yagi, --profile handheld for Bluetooth, --profile wifi for TCP).
default_profile = "s3"
trace_cooldown_s = 1.0
@@ -45,3 +46,14 @@ address = "AA:BB:CC:DD:EE:FF"
# transport = "ble"
# ble_pin = "123456" # only if your device requires a pairing PIN
description = "Pocket handheld over Bluetooth"
+
+# A network (TCP) companion — a WiFi board, or a meshcored-style proxy — reachable at a
+# host:port. Give it a `host` (and optional `tcp_port`, default 5000); a bare `host` already
+# implies TCP, so the `transport = "tcp"` line is optional. A TCP companion isn't discoverable,
+# so a profile (or --tcp host:port, or the picker's "add a network device" prompt) is how you
+# reach one.
+[profiles.wifi]
+host = "192.168.1.50"
+# tcp_port = 5000
+# transport = "tcp"
+description = "Basestation over WiFi"
diff --git a/meshterm/cli.py b/meshterm/cli.py
index 50f7ba0..b10b10a 100644
--- a/meshterm/cli.py
+++ b/meshterm/cli.py
@@ -84,6 +84,11 @@ def main_callback(
ble_pin: Optional[str] = typer.Option(
None, "--ble-pin", help="BLE pairing PIN, if the Bluetooth companion requires one"
),
+ tcp: Optional[str] = typer.Option(
+ None,
+ "--tcp",
+ help="Network address host[:port] of a TCP companion (selects the TCP transport)",
+ ),
mock: bool = typer.Option(False, "--mock", help="Use the built-in simulator"),
db_path: Optional[Path] = typer.Option(None, "--db", help="SQLite database path"),
json_output: bool = typer.Option(False, "--json", help="Machine-readable output"),
@@ -97,6 +102,7 @@ def main_callback(
port: Explicit serial port, overriding the profile.
ble: Explicit Bluetooth address, selecting the BLE transport.
ble_pin: Optional BLE pairing PIN for the Bluetooth companion.
+ tcp: Explicit network address ``host[:port]``, selecting the TCP transport.
mock: Whether to use the simulator instead of real hardware.
db_path: Override the database location.
json_output: Request machine-readable output from tools.
@@ -123,9 +129,12 @@ def main_callback(
mock=mock,
port_override=port,
ble_override=ble,
+ tcp_override=tcp,
ble_pin=ble_pin,
json_output=json_output,
- explicit_selection=profile is not None or port is not None or ble is not None,
+ explicit_selection=(
+ profile is not None or port is not None or ble is not None or tcp is not None
+ ),
)
_state = app_ctx
ctx.call_on_close(app_ctx.repo.close)
diff --git a/meshterm/context.py b/meshterm/context.py
index 2da474c..dfac492 100644
--- a/meshterm/context.py
+++ b/meshterm/context.py
@@ -65,6 +65,9 @@ class AppContext:
overriding the profile.
ble_override: Explicit Bluetooth address (from ``--ble`` or the interactive picker),
selecting the BLE transport. Takes precedence over ``port_override``.
+ tcp_override: Explicit network address ``host:port`` (from ``--tcp`` or the
+ interactive picker), selecting the TCP transport. Takes precedence over
+ ``ble_override`` and ``port_override``.
ble_pin: Optional BLE pairing PIN for the chosen Bluetooth device.
json_output: Whether tools should emit machine-readable output.
selected_device: The discovered device chosen for this session, when known, so it
@@ -87,6 +90,7 @@ class AppContext:
mock: bool = False
port_override: Optional[str] = None
ble_override: Optional[str] = None
+ tcp_override: Optional[str] = None
ble_pin: Optional[str] = None
json_output: bool = False
selected_device: Optional[DiscoveredDevice] = None
@@ -95,6 +99,7 @@ class AppContext:
_active_port: Optional[str] = field(default=None, init=False, repr=False)
_active_transport: Optional[str] = field(default=None, init=False, repr=False)
_active_address: Optional[str] = field(default=None, init=False, repr=False)
+ _active_endpoint: Optional[str] = field(default=None, init=False, repr=False)
unpair_on_exit: bool = field(default=False, init=False, repr=False)
#: Set by the config editor just before it sends a reboot command, so the session's
#: disconnect watcher can label the ensuing (expected) link drop as a reboot in
@@ -142,11 +147,11 @@ class AppContext:
"""The serial port the current connection is open on, if any (``None`` for --mock/BLE).
Set when a real *serial* connection is opened so the reconnect flow knows which OS
- port to wait on. ``None`` for the simulator and for BLE connections (which have no
+ port to wait on. ``None`` for the simulator and for BLE/TCP connections (which have no
serial port). Falls back to an explicit ``--port`` override when a connection hasn't
recorded one yet.
"""
- if self.mock or self.active_transport == "ble":
+ if self.mock or self.active_transport in ("ble", "tcp"):
return None
return self._active_port or self.port_override
@@ -162,18 +167,33 @@ class AppContext:
return None
return self._active_address or self.ble_override
+ @property
+ def active_endpoint(self) -> Optional[str]:
+ """The network ``host:port`` of the current TCP connection, if any (``None`` otherwise).
+
+ Set when a real *TCP* connection is opened, so the reconnect flow and header can name
+ the endpoint. ``None`` for the simulator and for serial/BLE connections. Falls back to
+ an explicit ``--tcp`` override when a connection hasn't recorded one yet.
+ """
+ if self.mock or self.active_transport != "tcp":
+ return None
+ return self._active_endpoint or self.tcp_override
+
@property
def active_transport(self) -> Optional[str]:
- """The transport of the current/selected connection: ``"serial"``, ``"ble"``, or ``None``.
+ """The transport of the current/selected connection: ``"serial"``, ``"ble"``, ``"tcp"``,
+ or ``None``.
``None`` for the simulator. For a real device it reflects the open connection when
one exists, otherwise the transport implied by the pending selection (an explicit
- ``--ble`` selects BLE), defaulting to serial.
+ ``--tcp`` selects TCP, ``--ble`` selects BLE), defaulting to serial.
"""
if self.mock:
return None
if self._active_transport is not None:
return self._active_transport
+ if self.tcp_override:
+ return "tcp"
return "ble" if self.ble_override else "serial"
async def link_alive(self) -> bool:
@@ -348,6 +368,9 @@ class AppContext:
self._active_transport = getattr(device, "transport", "serial")
self._active_port = getattr(device, "_port", None)
self._active_address = getattr(device, "_address", None)
+ self._active_endpoint = getattr(device, "endpoint", None) if (
+ self._active_transport == "tcp"
+ ) else None
async def device(self) -> Device:
"""Return a connected :class:`Device`, opening the connection on first use.
@@ -371,9 +394,26 @@ class AppContext:
self._active_transport = None
self._active_port = None
self._active_address = None
+ self._active_endpoint = None
await self._device.connect()
return self._device
+ # A network endpoint (an explicit ``--tcp``, a TCP profile, a device picked at startup,
+ # or the remembered TCP default) is opened directly by host:port — TCP companions
+ # aren't discoverable, so this remembered/explicit endpoint is the only way to reach one.
+ tcp_host, tcp_port = self._resolve_tcp_endpoint()
+ if tcp_host and tcp_port:
+ self._device = make_device(
+ mock=False, port=None, transport="tcp", host=tcp_host, tcp_port=tcp_port
+ )
+ self._active_transport = "tcp"
+ self._active_endpoint = f"{tcp_host}:{tcp_port}"
+ self._active_port = None
+ self._active_address = None
+ await self._device.connect()
+ await self._remember_connected()
+ return self._device
+
# A Bluetooth endpoint (an explicit ``--ble``, a BLE profile, a device picked at
# startup, or the remembered BLE default) is opened directly by address — no serial
# resolution, and no re-scan needed to reconnect to a known address.
@@ -400,6 +440,7 @@ class AppContext:
self._active_transport = "ble"
self._active_address = ble_address
self._active_port = None
+ self._active_endpoint = None
await self._device.connect()
await self._remember_connected()
return self._device
@@ -417,10 +458,54 @@ class AppContext:
self._active_transport = "serial"
self._active_port = resolution.port
self._active_address = None
+ self._active_endpoint = None
await self._device.connect()
await self._remember_connected()
return self._device
+ def _resolve_tcp_endpoint(self) -> tuple[Optional[str], Optional[int]]:
+ """Return the ``(host, port)`` to open over TCP, or ``(None, None)`` for other transports.
+
+ Resolves a network endpoint in priority order — an explicit ``--tcp``, a TCP
+ :class:`~meshterm.core.config.DeviceProfile`, then the remembered TCP default — so a
+ network companion is honored wherever a serial/Bluetooth one would be. A malformed
+ endpoint yields ``(None, None)`` (the session then falls through to the other
+ transports rather than crashing on a typo).
+ """
+ from .core.discovery import parse_tcp_endpoint
+ from .core.selection import DeviceSelectionError
+
+ # An explicit ``--tcp`` or TCP profile is authoritative — a malformed value is the
+ # user's typo, so surface the parse error as a clean, actionable message rather than
+ # silently falling through to another transport.
+ explicit_endpoint = self.tcp_override or (
+ self.profile.tcp_endpoint
+ if self.profile is not None and self.profile.is_tcp
+ else None
+ )
+ if explicit_endpoint:
+ try:
+ return parse_tcp_endpoint(explicit_endpoint)
+ except ValueError as exc:
+ raise DeviceSelectionError(str(exc)) from exc
+ # A remembered TCP default only applies when nothing else was selected explicitly, and
+ # a corrupt stored value must never crash startup — fall through to the other transports.
+ explicit_other = bool(self.port_override) or bool(self.ble_override) or (
+ self.profile is not None
+ and (bool(self.profile.port) or bool(self.profile.address))
+ )
+ if explicit_other:
+ return None, None
+ remembered = self.device_store.load()
+ if remembered is not None and remembered.is_tcp and remembered.target:
+ try:
+ host, port = parse_tcp_endpoint(remembered.target)
+ except ValueError:
+ return None, None
+ self.selected_device = None # remembered, not freshly discovered this session
+ return host, port
+ return None, None
+
def _resolve_ble_endpoint(self) -> tuple[Optional[str], Optional[str]]:
"""Return the ``(address, pin)`` to open over Bluetooth, or ``(None, None)`` for serial.
diff --git a/meshterm/core/config.py b/meshterm/core/config.py
index 556383a..754de30 100644
--- a/meshterm/core/config.py
+++ b/meshterm/core/config.py
@@ -43,9 +43,10 @@ def default_config_dir() -> Path:
class DeviceProfile:
"""Connection defaults for one physical companion device.
- A profile addresses either a serial companion (via ``port``) or a Bluetooth one (via
- ``transport = "ble"`` and ``address``). ``transport`` defaults to serial, so existing
- port-only profiles are unchanged.
+ A profile addresses a serial companion (via ``port``), a Bluetooth one (via
+ ``transport = "ble"`` and ``address``), or a network one (via ``transport = "tcp"``,
+ ``host``, and ``tcp_port``). ``transport`` defaults to serial, so existing port-only
+ profiles are unchanged.
Attributes:
name: The profile alias (e.g. ``"yagi"``).
@@ -53,9 +54,12 @@ class DeviceProfile:
baudrate: Serial baud rate.
default_tx_power: TX power to assume/restore for this device, if known.
description: Free-text note about the hardware.
- transport: ``"serial"`` (default) or ``"ble"``.
+ transport: ``"serial"`` (default), ``"ble"``, or ``"tcp"``.
address: Bluetooth address (e.g. ``AA:BB:CC:DD:EE:FF``); BLE profiles.
ble_pin: Optional BLE pairing PIN, if the Bluetooth companion requires one.
+ host: Hostname or IP of a network companion (e.g. ``"192.168.1.50"``); TCP profiles.
+ tcp_port: TCP port the network companion listens on; TCP profiles (defaults to
+ :data:`~meshterm.core.discovery.DEFAULT_TCP_PORT` when a host is given without one).
"""
name: str
@@ -66,12 +70,28 @@ class DeviceProfile:
transport: str = "serial"
address: Optional[str] = None
ble_pin: Optional[str] = None
+ host: Optional[str] = None
+ tcp_port: Optional[int] = None
@property
def is_ble(self) -> bool:
"""Whether this profile addresses a Bluetooth LE companion."""
return self.transport == "ble"
+ @property
+ def is_tcp(self) -> bool:
+ """Whether this profile addresses a network (TCP) companion."""
+ return self.transport == "tcp"
+
+ @property
+ def tcp_endpoint(self) -> Optional[str]:
+ """The ``host:port`` string for a TCP profile, or ``None`` if it isn't one / has no host."""
+ if not self.is_tcp or not self.host:
+ return None
+ from .discovery import DEFAULT_TCP_PORT
+
+ return f"{self.host}:{self.tcp_port or DEFAULT_TCP_PORT}"
+
@dataclass(slots=True)
class Settings:
@@ -161,10 +181,14 @@ class Settings:
profiles: dict[str, DeviceProfile] = {}
for pname, pdata in (data.get("profiles") or {}).items():
- # A profile with an ``address`` (or ``transport = "ble"``) is a Bluetooth device;
- # otherwise it's serial. Defaulting the transport this way keeps port-only
- # profiles working untouched while a bare ``address`` is enough to declare a BLE one.
- transport = pdata.get("transport") or ("ble" if pdata.get("address") else "serial")
+ # Infer the transport from which endpoint the profile carries when it isn't stated
+ # outright: a ``host`` means TCP, an ``address`` means BLE, otherwise serial. This
+ # keeps port-only profiles working untouched while a bare ``host``/``address`` is
+ # enough to declare a network/Bluetooth one.
+ transport = pdata.get("transport") or (
+ "tcp" if pdata.get("host") else "ble" if pdata.get("address") else "serial"
+ )
+ tcp_port = pdata.get("tcp_port")
profiles[pname] = DeviceProfile(
name=pname,
port=pdata.get("port"),
@@ -174,6 +198,8 @@ class Settings:
transport=transport,
address=pdata.get("address"),
ble_pin=pdata.get("ble_pin"),
+ host=pdata.get("host"),
+ tcp_port=int(tcp_port) if tcp_port is not None else None,
)
return cls(
diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py
index a0752a3..12aa6f5 100644
--- a/meshterm/core/connection.py
+++ b/meshterm/core/connection.py
@@ -772,12 +772,13 @@ class Device(ABC):
class MeshCoreDevice(Device):
- """A :class:`Device` backed by the ``meshcore`` companion client (serial or BLE).
+ """A :class:`Device` backed by the ``meshcore`` companion client (serial, BLE, or TCP).
- The same wrapper serves both transports: which one it opens is chosen by ``transport``
- (``"serial"`` opens ``port``; ``"ble"`` opens ``address``). Everything above the
- connection — commands, event mapping, trace parsing — is transport-agnostic, so only
- :meth:`connect` and :meth:`link_present` differ between the two.
+ The same wrapper serves every transport: which one it opens is chosen by ``transport``
+ (``"serial"`` opens ``port``; ``"ble"`` opens ``address``; ``"tcp"`` opens
+ ``host``:``tcp_port``). Everything above the connection — commands, event mapping, trace
+ parsing — is transport-agnostic, so only :meth:`connect` and :meth:`link_present` differ
+ between them.
Note:
The trace mapping here follows the documented companion protocol (trace replies
@@ -795,6 +796,8 @@ class MeshCoreDevice(Device):
address: Optional[str] = None,
pin: Optional[str] = None,
ble_device: Optional[object] = None,
+ host: Optional[str] = None,
+ tcp_port: Optional[int] = None,
) -> None:
"""Initialize the device wrapper.
@@ -806,7 +809,7 @@ class MeshCoreDevice(Device):
library default (~15s). The startup smoke test sets a short value so a
non-responsive port is rejected quickly instead of blocking on the full
default handshake window.
- transport: ``"serial"`` (default) or ``"ble"``.
+ transport: ``"serial"`` (default), ``"ble"``, or ``"tcp"``.
address: Bluetooth address (e.g. ``AA:BB:CC:DD:EE:FF``); BLE transport only.
pin: Optional BLE pairing PIN, when the peripheral requires one (BLE only).
ble_device: The ``bleak.BLEDevice`` the discovery scan already found at
@@ -815,6 +818,8 @@ class MeshCoreDevice(Device):
bare-address connect runs a fresh internal scan that intermittently misses a
slow-advertising companion, which is the main source of flaky BLE startups.
Typed ``object`` so ``bleak`` need not be imported on non-BLE paths.
+ host: Hostname or IP of a network companion; TCP transport only.
+ tcp_port: TCP port the network companion listens on; TCP transport only.
"""
self._port = port
self._baudrate = baudrate
@@ -823,6 +828,8 @@ class MeshCoreDevice(Device):
self._address = address
self._pin = pin
self._ble_device = ble_device
+ self._host = host
+ self._tcp_port = tcp_port
self._mc = None # type: ignore[var-annotated] # meshcore.MeshCore
# Serializes channel reads. The meshcore library's get_channel waits for "the next
# CHANNEL_INFO event" with no correlation to the index it asked for, and the dispatcher
@@ -836,12 +843,14 @@ class MeshCoreDevice(Device):
@property
def transport(self) -> str:
- """Which transport this device connects over (``"serial"`` or ``"ble"``)."""
+ """Which transport this device connects over (``"serial"``, ``"ble"``, or ``"tcp"``)."""
return self._transport
@property
def endpoint(self) -> Optional[str]:
- """The connection endpoint: the BLE address for BLE, else the serial port."""
+ """The connection endpoint: ``host:port`` for TCP, the BLE address, else the port."""
+ if self._transport == "tcp":
+ return f"{self._host}:{self._tcp_port}"
return self._address if self._transport == "ble" else self._port
async def connect(self) -> None: # noqa: D102 - inherited docstring
@@ -858,6 +867,17 @@ class MeshCoreDevice(Device):
if self._transport == "ble":
self._mc = await self._create_ble(MeshCore)
+ elif self._transport == "tcp":
+ try:
+ self._mc = await MeshCore.create_tcp(
+ self._host, self._tcp_port, default_timeout=self._connect_timeout
+ )
+ except (OSError, asyncio.TimeoutError) as exc:
+ # The socket couldn't be opened — host unreachable, connection refused, name
+ # not resolved, or the connect timed out. That's not a MeshCore-level failure,
+ # so translate it into a clean, actionable message (naming the host:port and
+ # the things to check) rather than letting a raw socket traceback escape.
+ raise DeviceCommandError(self._no_response_message()) from exc
else:
self._mc = await MeshCore.create_serial(
self._port, self._baudrate, default_timeout=self._connect_timeout
@@ -1255,6 +1275,13 @@ class MeshCoreDevice(Device):
"out of range, powered off, already connected to another device, or not a "
"MeshCore device."
)
+ if self._transport == "tcp":
+ where = self.endpoint or "the selected network device"
+ return (
+ f"no response from a MeshCore companion at {where}; check the host and port, "
+ "and that the device is powered on, reachable on the network, and not already "
+ "connected to another client."
+ )
return (
f"no response from a MeshCore companion on {self._port}; it may not be a "
"MeshCore device, or it may be powered off or in use by another program."
@@ -1263,10 +1290,11 @@ class MeshCoreDevice(Device):
async def link_present(self) -> bool: # noqa: D102 - inherited docstring
if self._mc is None:
return True # not connected yet / already torn down — nothing to declare lost
- if self._transport == "ble":
- # The meshcore client flips ``is_connected`` to False the moment bleak reports the
- # peripheral dropped (via its disconnect callback), so this is the BLE analogue of
- # the serial port-enumeration check — a cheap, non-transmitting liveness read.
+ if self._transport in ("ble", "tcp"):
+ # The meshcore client flips ``is_connected`` to False the moment the transport
+ # drops — bleak's disconnect callback for BLE, a broken socket for TCP — so this is
+ # the network/Bluetooth analogue of the serial port-enumeration check: a cheap,
+ # non-transmitting liveness read.
try:
return bool(self._mc.is_connected)
except Exception: # noqa: BLE001 - a status hiccup must not fake a disconnect
@@ -2952,6 +2980,8 @@ def make_device(
address: Optional[str] = None,
pin: Optional[str] = None,
ble_device: Optional[object] = None,
+ host: Optional[str] = None,
+ tcp_port: Optional[int] = None,
) -> Device:
"""Construct the appropriate :class:`Device` for the current invocation.
@@ -2961,12 +2991,14 @@ def make_device(
unless ``mock`` is set.
baudrate: Serial baud rate for a real serial device.
mock_optimal_tx: Peak TX power for the simulator.
- transport: ``"serial"`` (default) or ``"ble"``.
+ transport: ``"serial"`` (default), ``"ble"``, or ``"tcp"``.
address: Bluetooth address for the BLE transport. Required when ``transport="ble"``.
pin: Optional BLE pairing PIN (BLE only).
ble_device: The scanned ``bleak.BLEDevice`` for ``address``, when this session's
discovery produced one (BLE only) — lets the connect skip re-discovering the
peripheral by address (see :class:`MeshCoreDevice`).
+ host: Hostname/IP for the TCP transport. Required when ``transport="tcp"``.
+ tcp_port: TCP port for the TCP transport. Required when ``transport="tcp"``.
Returns:
A connected-on-enter :class:`Device` instance.
@@ -2983,6 +3015,13 @@ def make_device(
"or use --mock."
)
return MeshCoreDevice(transport="ble", address=address, pin=pin, ble_device=ble_device)
+ if transport == "tcp":
+ if not host or not tcp_port:
+ raise ValueError(
+ "No network address configured. Pass --tcp host:port, set a TCP profile, "
+ "pick a device at startup, or use --mock."
+ )
+ return MeshCoreDevice(transport="tcp", host=host, tcp_port=tcp_port)
if not port:
raise ValueError(
"No serial port configured. Pass --port, set a profile, or use --mock."
@@ -2998,6 +3037,11 @@ _PROBE_TIMEOUT_SERIAL_S = 6.0
#: involves a link-layer connection and GATT service discovery before the identity reply.
_PROBE_TIMEOUT_BLE_S = 20.0
+#: Handshake window (seconds) for probing a TCP companion. Between serial and BLE: a TCP
+#: connect is a quick socket open, but an unreachable host can sit in the OS connect backoff,
+#: so the window allows for that before the endpoint is written off as absent.
+_PROBE_TIMEOUT_TCP_S = 10.0
+
async def probe_device(
device: "DiscoveredDevice", *, baudrate: int = 115200, pin: Optional[str] = None
@@ -3042,6 +3086,14 @@ async def probe_device(
# through it skips the by-address re-discovery that makes BLE startups flaky.
ble_device=device.ble_device,
)
+ elif device.is_tcp:
+ timeout = _PROBE_TIMEOUT_TCP_S
+ probe = MeshCoreDevice(
+ transport="tcp",
+ host=device.host,
+ tcp_port=device.tcp_port,
+ connect_timeout=timeout,
+ )
else:
timeout = _PROBE_TIMEOUT_SERIAL_S
probe = MeshCoreDevice(
diff --git a/meshterm/core/device_store.py b/meshterm/core/device_store.py
index 5b94711..e847673 100644
--- a/meshterm/core/device_store.py
+++ b/meshterm/core/device_store.py
@@ -20,7 +20,12 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Optional
-from .discovery import TRANSPORT_BLE, TRANSPORT_SERIAL, DiscoveredDevice
+from .discovery import (
+ TRANSPORT_BLE,
+ TRANSPORT_SERIAL,
+ TRANSPORT_TCP,
+ DiscoveredDevice,
+)
from .models import utcnow
@@ -31,11 +36,11 @@ class RememberedDevice:
Attributes:
stable_id: The device's :attr:`DiscoveredDevice.stable_id` at connect time.
port: The serial port it was last seen on (informational; may have changed). Blank
- for a BLE device.
+ for a BLE/TCP device.
label: A friendly label for display in prompts and tables.
last_connected: ISO-8601 timestamp of the last successful connection.
node_name: The device's own mesh node name, learned at connect time (may be empty).
- transport: ``"serial"`` or ``"ble"`` — how this device was last reached.
+ transport: ``"serial"``, ``"ble"``, or ``"tcp"`` — how this device was last reached.
address: The Bluetooth address, for a BLE device (blank otherwise), so it can be
reconnected directly without re-scanning.
hardware_model: The firmware's own model string (e.g. ``"Seeed Tracker T1000-E"``),
@@ -43,6 +48,10 @@ class RememberedDevice:
the model — a BLE companion advertises none — so it's remembered here to fill the
hardware column even when the device is merely attached, not connected. May be empty
for a serial device confirmed by an older firmware that predates the query.
+ host: The network host, for a TCP device (blank otherwise), so it can be reconnected
+ directly. A TCP companion isn't discoverable, so this remembered endpoint is the
+ *only* way it reappears in the picker.
+ tcp_port: The TCP port, for a TCP device (0 otherwise).
"""
stable_id: str
@@ -53,15 +62,25 @@ class RememberedDevice:
transport: str = TRANSPORT_SERIAL
address: str = ""
hardware_model: str = ""
+ host: str = ""
+ tcp_port: int = 0
@property
def is_ble(self) -> bool:
"""Whether this remembered device was reached over Bluetooth LE."""
return self.transport == TRANSPORT_BLE
+ @property
+ def is_tcp(self) -> bool:
+ """Whether this remembered device was reached over a TCP network connection."""
+ return self.transport == TRANSPORT_TCP
+
@property
def target(self) -> str:
- """The connection target: the BLE address for a BLE device, else the serial port."""
+ """The connection target: ``host:port`` for TCP, the BLE address for Bluetooth, else
+ the serial port."""
+ if self.is_tcp:
+ return f"{self.host}:{self.tcp_port}"
return self.address or self.port if self.is_ble else self.port
def matches(self, device: DiscoveredDevice) -> bool:
@@ -127,8 +146,10 @@ class DeviceStore:
transport=entry.get("transport", TRANSPORT_SERIAL),
address=entry.get("address", ""),
hardware_model=entry.get("hardware_model", ""),
+ host=entry.get("host", ""),
+ tcp_port=int(entry.get("tcp_port", 0) or 0),
)
- except (KeyError, TypeError):
+ except (KeyError, TypeError, ValueError):
return None
def load(self) -> Optional[RememberedDevice]:
@@ -185,10 +206,40 @@ class DeviceStore:
transport=device.transport,
address=device.address or "",
hardware_model=hardware_model,
+ host=device.host or "",
+ tcp_port=device.tcp_port or 0,
)
self._write(registry, device.stable_id)
- def _write(self, registry: dict[str, RememberedDevice], last: str) -> None:
+ def forget(self, stable_id: str) -> bool:
+ """Drop a remembered device from the registry.
+
+ The inverse of :meth:`remember`: removes the record keyed by ``stable_id`` so the
+ device is no longer listed as a confirmed companion. Used by the device picker's
+ Delete action to prune a network (TCP) companion the user no longer wants — a TCP
+ device is listed *only* from its remembered endpoint, so forgetting it is what makes
+ it leave the picker. If the forgotten device was the most-recently-connected default,
+ that pointer is handed to the newest surviving record (or cleared when none remain),
+ so the next startup still preselects a sensible device.
+
+ Args:
+ stable_id: The :attr:`RememberedDevice.stable_id` of the device to forget.
+
+ Returns:
+ ``True`` if a record was removed, ``False`` if none matched.
+ """
+ registry, last = self._read()
+ if stable_id not in registry:
+ return False
+ del registry[stable_id]
+ if last == stable_id:
+ last = max(
+ registry, key=lambda k: registry[k].last_connected, default=None
+ )
+ self._write(registry, last)
+ return True
+
+ def _write(self, registry: dict[str, RememberedDevice], last: Optional[str]) -> None:
"""Persist the registry, marking ``last`` as the most recently connected device."""
self._path.parent.mkdir(parents=True, exist_ok=True)
payload = {
@@ -202,6 +253,8 @@ class DeviceStore:
"transport": record.transport,
"address": record.address,
"hardware_model": record.hardware_model,
+ "host": record.host,
+ "tcp_port": record.tcp_port,
}
for stable_id, record in registry.items()
},
diff --git a/meshterm/core/discovery.py b/meshterm/core/discovery.py
index aee9b56..eeb8c73 100644
--- a/meshterm/core/discovery.py
+++ b/meshterm/core/discovery.py
@@ -1,6 +1,6 @@
-"""Companion-device discovery across transports (serial + Bluetooth LE).
+"""Companion-device discovery across transports (serial + Bluetooth LE + TCP).
-Discovery enumerates two kinds of companion:
+Discovery enumerates the companion kinds that can be *found* automatically:
* **Serial**: USB serial ports via ``pyserial``, flagging the ones whose USB vendor ID
matches hardware commonly used for LoRa companion devices (ESP32/nRF boards and their
@@ -10,6 +10,14 @@ Discovery enumerates two kinds of companion:
Unlike a bare serial adapter, a BLE advert that names itself MeshCore is a strong signal,
so scanned devices are always treated as likely companions.
+A **TCP** companion — a MeshCore device reachable at a network ``host:port`` (a WiFi board,
+or a ``meshcored``-style proxy) — has no discovery: it is not attached and does not
+advertise, so there is nothing to scan for. It is instead named explicitly (``--tcp``, a
+``transport = "tcp"`` profile, or the picker's "add a network device" prompt) and, once
+confirmed, remembered like any other companion. :func:`tcp_device` builds the
+:class:`DiscoveredDevice` for such an endpoint so the rest of the pipeline (selection,
+remembering, the picker) treats it uniformly.
+
This module has no UI and no persistent state; it only reads what is currently attached or
in range. The companion connection itself still goes through
:class:`~meshterm.core.connection.MeshCoreDevice`, which the ``transport`` field selects.
@@ -26,6 +34,11 @@ _log = logging.getLogger(__name__)
#: Transport discriminators for a :class:`DiscoveredDevice` (also stored/remembered as-is).
TRANSPORT_SERIAL = "serial"
TRANSPORT_BLE = "ble"
+TRANSPORT_TCP = "tcp"
+
+#: Default TCP port assumed when a network companion is named as a bare host with no port.
+#: 5000 is the conventional MeshCore companion-over-TCP / ``meshcored`` listen port.
+DEFAULT_TCP_PORT = 5000
#: BLE advertisements from a MeshCore companion begin with this name prefix; the scan filters
#: to it so unrelated Bluetooth gadgets (headphones, watches, beacons) never clutter the list.
@@ -64,12 +77,12 @@ class DiscoveredDevice:
"""A companion device found on the system, with transport metadata.
A serial device carries its USB metadata; a Bluetooth LE device carries its BLE
- ``address`` and advertised ``name`` instead (its ``port`` is left blank). The
- ``transport`` field says which, and :attr:`target` returns the identifier used to
- open a connection regardless of kind.
+ ``address`` and advertised ``name`` instead (its ``port`` is left blank); a TCP device
+ carries a network ``host`` and ``tcp_port``. The ``transport`` field says which, and
+ :attr:`target` returns the identifier used to open a connection regardless of kind.
Attributes:
- port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``); ``""`` for BLE.
+ port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``); ``""`` for BLE/TCP.
description: Human-readable description reported by the OS/driver/advert.
hwid: Raw hardware id string from ``pyserial`` (VID/PID/serial blob); serial only.
vid: USB vendor ID, if the port is a USB device.
@@ -77,7 +90,7 @@ class DiscoveredDevice:
serial_number: USB serial number, if exposed by the device.
manufacturer: USB manufacturer string, if available.
product: USB product string, if available.
- transport: ``"serial"`` or ``"ble"`` — which connection layer opens this device.
+ transport: ``"serial"``, ``"ble"``, or ``"tcp"`` — the connection layer for this device.
address: Bluetooth address for a BLE device (e.g. ``AA:BB:CC:DD:EE:FF``).
name: Advertised BLE local name (e.g. ``"MeshCore-Basestation"``); BLE only.
ble_device: The live ``bleak.BLEDevice`` the scan produced; BLE only, and only for
@@ -87,6 +100,8 @@ class DiscoveredDevice:
a fresh internal scan, which on Windows intermittently misses a
slow-advertising companion. Typed ``object`` so ``bleak`` stays optional; never
persisted.
+ host: Hostname or IP of a TCP companion (e.g. ``"192.168.1.50"``); TCP only.
+ tcp_port: TCP port the companion listens on (e.g. ``5000``); TCP only.
"""
port: str = ""
@@ -101,28 +116,40 @@ class DiscoveredDevice:
address: Optional[str] = None
name: Optional[str] = None
ble_device: Optional[object] = None
+ host: Optional[str] = None
+ tcp_port: Optional[int] = None
@property
def is_ble(self) -> bool:
"""Whether this device is reached over Bluetooth LE rather than a serial port."""
return self.transport == TRANSPORT_BLE
+ @property
+ def is_tcp(self) -> bool:
+ """Whether this device is reached over a TCP network connection."""
+ return self.transport == TRANSPORT_TCP
+
@property
def target(self) -> str:
- """The identifier a connection opens on: the BLE address, else the serial port."""
+ """The identifier a connection opens on: the network ``host:port`` for TCP, the BLE
+ address for Bluetooth, else the serial port."""
+ if self.is_tcp:
+ return f"{self.host}:{self.tcp_port}"
return self.address or self.port if self.is_ble else self.port
@property
def stable_id(self) -> str:
"""Return an identifier stable across replug/reboot.
- For BLE, the Bluetooth address (stable per adapter pairing). For serial, the USB
- serial number (survives a changed COM number), then the ``vid:pid`` pair, and
- finally the port name as a last resort.
+ For TCP, the network ``host:port``. For BLE, the Bluetooth address (stable per
+ adapter pairing). For serial, the USB serial number (survives a changed COM
+ number), then the ``vid:pid`` pair, and finally the port name as a last resort.
Returns:
A non-empty identifier string used to recognize this device later.
"""
+ if self.is_tcp:
+ return f"tcp:{self.host}:{self.tcp_port}"
if self.is_ble:
return f"ble:{(self.address or self.name or '').lower()}"
if self.serial_number:
@@ -136,12 +163,13 @@ class DiscoveredDevice:
"""How likely this device is a LoRa companion.
Returns:
- ``"board"`` for a BLE device that named itself MeshCore or a LoRa dev board's
- native USB (both strong signals), ``"bridge"`` for a generic USB-UART chip (a
- weak hint — could be anything), or ``"unknown"`` for an unrecognized adapter.
+ ``"board"`` for a BLE device that named itself MeshCore, a TCP endpoint the user
+ named explicitly, or a LoRa dev board's native USB (all strong signals),
+ ``"bridge"`` for a generic USB-UART chip (a weak hint — could be anything), or
+ ``"unknown"`` for an unrecognized adapter.
"""
- if self.is_ble:
- return "board" # a MeshCore-named BLE advert is a confident companion signal
+ if self.is_ble or self.is_tcp:
+ return "board" # a MeshCore BLE advert / a user-named TCP endpoint is confident
if self.vid in NATIVE_LORA_VIDS:
return "board"
if self.vid in UART_BRIDGE_VIDS:
@@ -157,14 +185,14 @@ class DiscoveredDevice:
def vendor_label(self) -> str:
"""The hardware maker's name for the VENDOR column, or ``""`` when unknown.
- This is deliberately *just the vendor* — the transport (USB vs Bluetooth) is a
- separate concern shown in its own TYPE column, so a BLE advert (which rarely
- exposes a maker) reports whatever manufacturer string it carries and otherwise
+ This is deliberately *just the vendor* — the transport (USB vs Bluetooth vs TCP) is a
+ separate concern shown in its own TYPE column, so a BLE advert or TCP endpoint (which
+ rarely expose a maker) reports whatever manufacturer string it carries and otherwise
stays blank rather than mislabelling the transport as a vendor. A serial port maps
its USB vendor ID to a friendly name, falling back to the driver's manufacturer
string.
"""
- if self.is_ble:
+ if self.is_ble or self.is_tcp:
return self.manufacturer or ""
if self.vid in KNOWN_LORA_VIDS:
return KNOWN_LORA_VIDS[self.vid]
@@ -177,6 +205,9 @@ class DiscoveredDevice:
The OS description often already ends with the port (Windows reports
``"USB Serial Device (COM11)"``), so the identifier is not appended a second time.
"""
+ if self.is_tcp:
+ name = self.name or self.product or self.description or "Network device"
+ return f"{name} ({self.target})"
if self.is_ble:
name = self.name or self.product or self.description or "Bluetooth device"
return f"{name} (BLE)"
@@ -187,6 +218,88 @@ class DiscoveredDevice:
return f"{name} ({self.port})"
+def parse_tcp_endpoint(text: str, *, default_port: int = DEFAULT_TCP_PORT) -> tuple[str, int]:
+ """Parse a ``host[:port]`` string into a ``(host, port)`` pair.
+
+ Accepts a bare host (``"192.168.1.50"``, ``"meshcore.local"``) — defaulting the port to
+ ``default_port`` — or an explicit ``host:port``. IPv6 literals must be bracketed
+ (``"[::1]:5000"``) so the address colons aren't mistaken for the port separator.
+
+ Args:
+ text: The user-supplied network address.
+ default_port: Port assumed when ``text`` names only a host.
+
+ Returns:
+ The ``(host, port)`` to connect to.
+
+ Raises:
+ ValueError: If the host is empty or the port isn't a valid 1–65535 integer — with a
+ message already phrased for the user.
+ """
+ raw = text.strip()
+ if not raw:
+ raise ValueError("Enter a network address, e.g. 192.168.1.50 or 192.168.1.50:5000.")
+ host, sep, port_text = _split_host_port(raw)
+ host = host.strip()
+ if not host:
+ raise ValueError("Enter a host, e.g. 192.168.1.50 or 192.168.1.50:5000.")
+ if not sep or not port_text.strip():
+ return host, default_port
+ try:
+ port = int(port_text.strip())
+ except ValueError:
+ raise ValueError(f"'{port_text.strip()}' isn't a valid port number.") from None
+ if not 1 <= port <= 65535:
+ raise ValueError("The port must be between 1 and 65535.")
+ return host, port
+
+
+def _split_host_port(raw: str) -> tuple[str, str, str]:
+ """Split ``host[:port]`` into ``(host, separator, port)``, honouring ``[ipv6]`` brackets.
+
+ A bracketed IPv6 literal keeps its colons; only a ``:port`` *after* the closing bracket
+ (or the single colon of a plain ``host:port``) is treated as the port separator.
+ """
+ if raw.startswith("["):
+ close = raw.find("]")
+ if close != -1:
+ host = raw[1:close]
+ rest = raw[close + 1 :]
+ if rest.startswith(":"):
+ return host, ":", rest[1:]
+ return host, "", ""
+ host, sep, port_text = raw.rpartition(":")
+ if not sep: # no colon at all → the whole string is the host
+ return port_text, "", ""
+ return host, sep, port_text
+
+
+def tcp_device(host: str, port: int, *, name: str = "") -> DiscoveredDevice:
+ """Build the :class:`DiscoveredDevice` for a TCP companion at ``host:port``.
+
+ TCP companions aren't scanned for, so this is how a network endpoint enters the same
+ selection/remember/picker pipeline the discovered transports use. An optional ``name``
+ (a friendly label the user typed, or a mesh node name learned on a prior connect) is
+ carried through to the picker's DEVICE column.
+
+ Args:
+ host: Hostname or IP of the companion.
+ port: TCP port it listens on.
+ name: Optional friendly name for display.
+
+ Returns:
+ A TCP :class:`DiscoveredDevice` ready to select or connect.
+ """
+ return DiscoveredDevice(
+ transport=TRANSPORT_TCP,
+ host=host,
+ tcp_port=port,
+ name=name or None,
+ description=name,
+ product=name or None,
+ )
+
+
def _sort_key(device: DiscoveredDevice) -> tuple[int, str]:
"""Sort likely companions first, then bridges, then unknown; ties by target id."""
return (_CONFIDENCE_RANK[device.confidence], device.target)
diff --git a/meshterm/core/selection.py b/meshterm/core/selection.py
index aabafc1..71b7b4d 100644
--- a/meshterm/core/selection.py
+++ b/meshterm/core/selection.py
@@ -13,7 +13,14 @@ from typing import Optional
from .config import DeviceProfile
from .device_store import RememberedDevice
-from .discovery import TRANSPORT_BLE, TRANSPORT_SERIAL, DiscoveredDevice
+from .discovery import (
+ TRANSPORT_BLE,
+ TRANSPORT_SERIAL,
+ TRANSPORT_TCP,
+ DiscoveredDevice,
+ parse_tcp_endpoint,
+ tcp_device,
+)
class DeviceSelectionError(ValueError):
@@ -35,9 +42,9 @@ class Resolution:
device: The matching discovered device, when enumeration knows it (so the caller
can remember it on a successful connection). ``None`` for an explicit
target that is not currently enumerable.
- source: Where the choice came from (``"port"``, ``"ble"``, ``"profile"``,
+ source: Where the choice came from (``"port"``, ``"ble"``, ``"tcp"``, ``"profile"``,
``"remembered"``, or ``"only"``), for logging and messaging.
- transport: ``"serial"`` or ``"ble"`` — which connection layer opens the device.
+ transport: ``"serial"``, ``"ble"``, or ``"tcp"`` — the connection layer for the device.
"""
port: str
@@ -58,6 +65,27 @@ def _find_by_target(
return next((d for d in devices if d.target == target or d.port == target), None)
+def _resolve_tcp(
+ endpoint: str, devices: list[DiscoveredDevice], source: str
+) -> "Resolution":
+ """Build a TCP :class:`Resolution` from a ``host[:port]`` string.
+
+ The endpoint is normalized (a bare host gains the default port) so the resulting target
+ matches how a remembered TCP device stores itself. A TCP companion isn't discoverable, so
+ any matching ``devices`` entry would only be a remembered one injected by the caller.
+
+ Raises:
+ DeviceSelectionError: If ``endpoint`` isn't a valid ``host[:port]``.
+ """
+ try:
+ host, port = parse_tcp_endpoint(endpoint)
+ except ValueError as exc:
+ raise DeviceSelectionError(str(exc)) from exc
+ target = f"{host}:{port}"
+ match = _find_by_target(devices, target) or tcp_device(host, port)
+ return Resolution(target, match, source, TRANSPORT_TCP)
+
+
def _format_device_list(devices: list[DiscoveredDevice]) -> str:
"""Render discovered devices as an indented, human-readable bullet list."""
if not devices:
@@ -65,7 +93,7 @@ def _format_device_list(devices: list[DiscoveredDevice]) -> str:
lines = []
for d in devices:
flag = " [likely LoRa]" if d.is_likely_lora else ""
- kind = "BLE" if d.is_ble else "serial"
+ kind = "TCP" if d.is_tcp else "BLE" if d.is_ble else "serial"
lines.append(
f" • {d.target} ({kind}) — {d.product or d.description or 'device'}{flag}"
)
@@ -78,17 +106,19 @@ def resolve_device(
*,
explicit_port: Optional[str] = None,
explicit_ble: Optional[str] = None,
+ explicit_tcp: Optional[str] = None,
profile: Optional[DeviceProfile] = None,
) -> Resolution:
"""Decide which companion to connect to without prompting.
Resolution priority:
- 1. ``explicit_ble`` (an explicit ``--ble`` Bluetooth address).
- 2. ``explicit_port`` (an explicit ``--port``).
- 3. ``profile.port`` (an explicitly chosen profile with a port).
- 4. The remembered "last known good" device, if it is currently attached/in range.
- 5. The single attached device, if exactly one is present.
+ 1. ``explicit_tcp`` (an explicit ``--tcp`` network address).
+ 2. ``explicit_ble`` (an explicit ``--ble`` Bluetooth address).
+ 3. ``explicit_port`` (an explicit ``--port``).
+ 4. A TCP profile's ``host:port``, or a serial profile's ``port``.
+ 5. The remembered "last known good" device, if it is currently attached/in range.
+ 6. The single attached device, if exactly one is present.
Otherwise a :class:`DeviceSelectionError` is raised listing the candidates.
@@ -97,14 +127,19 @@ def resolve_device(
remembered: The remembered default, if any.
explicit_port: A serial port supplied on the command line.
explicit_ble: A Bluetooth address supplied on the command line.
+ explicit_tcp: A network ``host[:port]`` supplied on the command line.
profile: A device profile supplied on the command line.
Returns:
A :class:`Resolution` naming the chosen target and transport.
Raises:
- DeviceSelectionError: If no device can be chosen unambiguously.
+ DeviceSelectionError: If no device can be chosen unambiguously, or an explicit TCP
+ endpoint could not be parsed.
"""
+ if explicit_tcp:
+ return _resolve_tcp(explicit_tcp, devices, "tcp")
+
if explicit_ble:
return Resolution(
explicit_ble, _find_by_target(devices, explicit_ble), "ble", TRANSPORT_BLE
@@ -114,6 +149,9 @@ def resolve_device(
match = _find_by_target(devices, explicit_port)
return Resolution(explicit_port, match, "port", TRANSPORT_SERIAL)
+ if profile is not None and profile.is_tcp and profile.tcp_endpoint:
+ return _resolve_tcp(profile.tcp_endpoint, devices, "profile")
+
if profile is not None and profile.port:
match = _find_by_target(devices, profile.port)
return Resolution(profile.port, match, "profile", TRANSPORT_SERIAL)
diff --git a/meshterm/tools/channels.py b/meshterm/tools/channels.py
index 181a241..5bd6d3a 100644
--- a/meshterm/tools/channels.py
+++ b/meshterm/tools/channels.py
@@ -79,6 +79,8 @@ class ChannelsTool(Tool):
return await self._cli_import(ctx, params)
if action == "share":
return await self._cli_share(ctx, params)
+ if action == "clear":
+ return await self._cli_clear(ctx, params)
return await self._cli_list(ctx)
async def _cli_list(self, ctx: AppContext) -> ToolResult:
@@ -157,6 +159,26 @@ class ChannelsTool(Tool):
self._print_share(ctx, slot.name, slot.secret)
return ToolResult(summary={"index": idx, "shared": True})
+ async def _cli_clear(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
+ """Clear a channel slot, removing 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.
+ """
+ from ..ui.channels import read_channel_slots
+
+ device = await ctx.device()
+ idx = int(params["index"])
+ slot = next((s for s in await read_channel_slots(device) if s.idx == idx), None)
+ if slot is None:
+ ctx.ui.note(f"[muted]slot {idx} is already empty[/muted]")
+ return ToolResult(summary={"index": idx, "cleared": False})
+ await device.set_channel(idx, "", None) # empty name => the slot reads as unused
+ ctx.ui.note(f"[warn]cleared channel {slot.name} on slot {idx}[/warn]")
+ return ToolResult(summary={"index": idx, "cleared": True})
+
@staticmethod
def _print_share(ctx: AppContext, name: str, secret: bytes) -> None:
"""Render a channel's QR code and share URL into the output surface."""
@@ -216,4 +238,20 @@ class ChannelsTool(Tool):
) -> None:
run_tool_command(self, {"cli_action": "share", "index": index})
+ @channels_app.command("clear", help="Clear a channel slot (removes it from the device)")
+ def _clear_cmd(
+ index: int = typer.Argument(..., help="Channel slot index"),
+ yes: bool = typer.Option(
+ False, "--yes", help="Confirm removing the channel from this slot"
+ ),
+ ) -> None:
+ if not yes:
+ typer.secho(
+ "Refusing: clearing a slot removes the channel (a private channel's "
+ "key is lost unless you have it saved). Re-run with --yes to confirm.",
+ fg="red",
+ )
+ raise typer.Exit(1)
+ run_tool_command(self, {"cli_action": "clear", "index": index})
+
app.add_typer(channels_app, name=self.name)
diff --git a/meshterm/tools/config.py b/meshterm/tools/config.py
index 1e9e1c7..fc034f7 100644
--- a/meshterm/tools/config.py
+++ b/meshterm/tools/config.py
@@ -150,6 +150,20 @@ class ConfigTool(Tool):
def _share_cmd() -> None:
run_tool_command(self, {"ops": [("share",)]})
+ @config_app.command(
+ "advert-cadence",
+ help="Set how often this node auto-advertises in the background (0 = off)",
+ )
+ def _advert_cadence_cmd(
+ hours: int = typer.Argument(
+ ..., min=0, help="Cadence in hours between background adverts (0 disables)"
+ ),
+ flood: bool = typer.Option(
+ False, "--flood", help="Set the flood cadence (else the zero-hop / direct one)"
+ ),
+ ) -> None:
+ run_tool_command(self, {"ops": [("advert_cadence", flood, hours)]})
+
@config_app.command("export-key", help="Export the private key (sensitive)")
def _export_key_cmd(
out: Optional[Path] = typer.Option(None, "--out", help="Write to file instead of stdout"),
diff --git a/meshterm/tools/courier.py b/meshterm/tools/courier.py
index e0f5d78..ff1c575 100644
--- a/meshterm/tools/courier.py
+++ b/meshterm/tools/courier.py
@@ -8,9 +8,11 @@ message goes out when its node is next heard — or at its scheduled time — as
direct message with acknowledgement tracking and polite exponential backoff, and the
outcome lights the header's Watchtower badge.
-On the CLI it stays a scriptable one-shot: ``courier [--at HH:MM]``
-queues the message (reading the contact list to address it — nothing is transmitted)
-and the next interactive session's courier delivers it.
+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.
"""
from __future__ import annotations
@@ -54,6 +56,29 @@ 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`).
+
+ Args:
+ ctx: Shared application context.
+ params: A ``cli_action`` naming the outbox action, plus its arguments.
+
+ Returns:
+ A :class:`ToolResult` describing the action's outcome.
+ """
+ action = params.get("cli_action", "queue")
+ if action == "list":
+ return await self._cli_list(ctx)
+ if action == "send":
+ return await self._cli_send(ctx, params)
+ if action == "cancel":
+ return await self._cli_cancel(ctx, params)
+ if action == "clear":
+ return await self._cli_clear(ctx)
+ return await self._cli_queue(ctx, params)
+
+ # -- CLI --------------------------------------------------------------------
+
+ async def _cli_queue(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Queue one message from the CLI (transmits nothing).
Args:
@@ -101,23 +126,146 @@ class CourierTool(Tool):
summary={"queued": message.ident, "node": contact.name, "at": params.get("at")}
)
+ async def _cli_list(self, ctx: AppContext) -> ToolResult:
+ """Print the outbox — waiting entries then finished ones — as a table.
+
+ 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).
+ """
+ from rich.table import Table
+ from rich.text import Text
+
+ from ..core.courier_store import DELIVERED, QUEUED
+ from ..core.models import utcnow
+ from ..ui.courier_screen import _local_stamp, _shorten
+ from ..ui.widgets import _age_seconds, format_ago
+
+ entries = ctx.courier_store.entries()
+ if not entries:
+ ctx.ui.note("[muted]the outbox is empty[/muted]")
+ return ToolResult(summary={"entries": 0})
+
+ table = Table(title="Courier outbox", border_style="muted", expand=False)
+ table.add_column("ID", justify="right")
+ table.add_column("STATE")
+ table.add_column("NODE")
+ table.add_column("MESSAGE")
+ table.add_column("WHEN")
+ now = utcnow()
+ for m in entries:
+ if m.status == QUEUED:
+ state = Text("⏳ waiting", style="warn")
+ if m.not_before is not None and now < m.not_before:
+ when = f"scheduled {_local_stamp(m.not_before)}"
+ else:
+ when = "when next heard"
+ elif m.status == DELIVERED:
+ state = Text("✓ delivered", style="ok")
+ when = f"delivered {format_ago(_age_seconds(m.finished or m.created))}"
+ else:
+ state = Text("✗ gave up", style="err")
+ when = f"gave up {format_ago(_age_seconds(m.finished or m.created))}"
+ table.add_row(
+ str(m.ident),
+ state,
+ Text(m.node_name, style="brand"),
+ _shorten(m.text),
+ Text(when, style="muted"),
+ )
+ ctx.ui.show(table)
+ return ToolResult(summary={"entries": len(entries)})
+
+ async def _cli_send(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
+ """Force one delivery attempt for a waiting entry, right now.
+
+ The scriptable ``Send now`` — one forced attempt through the same courier the
+ outbox screen uses, skipping the "wait until the node is heard" eligibility check.
+ """
+ ident = int(params["id"])
+ if ctx.courier_store.get(ident) is None:
+ raise DeviceCommandError(f"no outbox entry #{ident}")
+ outcome = await ctx.courier.attempt_now(ident)
+ notes = {
+ "delivered": "[ok]✓ delivered[/ok] — acknowledged by the node",
+ "no ack": "[warn]sent, but no acknowledgement[/warn] — it stays queued for retry",
+ "gave up": "[err]✗ gave up[/err] — the retry budget is spent",
+ "unknown contact": (
+ "[warn]the device's contacts don't know this node yet[/warn] — it stays queued"
+ ),
+ "busy": "[muted]another delivery is in flight — try again in a moment[/muted]",
+ "gone": "[muted]that entry is no longer waiting[/muted]",
+ }
+ ctx.ui.note(notes.get(outcome, outcome))
+ return ToolResult(summary={"id": ident, "outcome": outcome})
+
+ async def _cli_cancel(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
+ """Remove a waiting entry from the outbox (finished ones use ``clear``)."""
+ ident = int(params["id"])
+ if ctx.courier_store.cancel(ident):
+ ctx.ui.note(f"[warn]cancelled outbox entry #{ident}[/warn]")
+ return ToolResult(summary={"id": ident, "cancelled": True})
+ ctx.ui.note(f"[muted]no waiting entry #{ident} to cancel[/muted]")
+ return ToolResult(summary={"id": ident, "cancelled": False})
+
+ async def _cli_clear(self, ctx: AppContext) -> ToolResult:
+ """Drop every finished (delivered / given-up) entry, leaving the queue untouched."""
+ before = len(ctx.courier_store.entries())
+ ctx.courier_store.clear_done()
+ cleared = before - len(ctx.courier_store.entries())
+ if cleared:
+ ctx.ui.note(
+ f"[ok]cleared {cleared} finished "
+ f"entr{'y' if cleared == 1 else 'ies'}[/ok]"
+ )
+ else:
+ ctx.ui.note("[muted]no finished entries to clear[/muted]")
+ return ToolResult(summary={"cleared": cleared})
+
def register_cli(self, app: typer.Typer) -> None:
- """Register the ``courier`` subcommand.
+ """Register the ``courier`` subcommand group.
Args:
app: The Typer application.
"""
from ..cli import run_tool_command
- @app.command(name=self.name, help=self.help)
- def _courier(
+ courier_app = typer.Typer(
+ help=self.help, no_args_is_help=True, rich_markup_mode="rich"
+ )
+
+ @courier_app.command("queue", help="Queue a message for delivery when the node is next heard")
+ def _queue_cmd(
node: str = typer.Argument(..., help="The recipient contact's name"),
text: list[str] = typer.Argument(..., help="The message to queue"),
at: Optional[str] = typer.Option(
None, "--at", help="Hold until this local time (HH:MM, next occurrence)"
),
) -> None:
- tool_params: dict[str, Any] = {"node": node, "text": " ".join(text)}
+ tool_params: dict[str, Any] = {
+ "cli_action": "queue", "node": node, "text": " ".join(text)
+ }
if at is not None:
tool_params["at"] = at
run_tool_command(self, tool_params)
+
+ @courier_app.command("list", help="Show the outbox — waiting and finished entries")
+ def _list_cmd() -> None:
+ run_tool_command(self, {"cli_action": "list"})
+
+ @courier_app.command("send", help="Force one delivery attempt for a waiting entry now")
+ def _send_cmd(
+ id: int = typer.Argument(..., help="Outbox entry id (from `courier list`)"),
+ ) -> None:
+ run_tool_command(self, {"cli_action": "send", "id": id})
+
+ @courier_app.command("cancel", help="Remove a waiting entry from the outbox")
+ def _cancel_cmd(
+ id: int = typer.Argument(..., help="Outbox entry id (from `courier list`)"),
+ ) -> None:
+ run_tool_command(self, {"cli_action": "cancel", "id": id})
+
+ @courier_app.command("clear", help="Drop finished (delivered / given-up) entries")
+ def _clear_cmd() -> None:
+ run_tool_command(self, {"cli_action": "clear"})
+
+ app.add_typer(courier_app, name=self.name)
diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py
index 048ec92..4092418 100644
--- a/meshterm/ui/device_picker.py
+++ b/meshterm/ui/device_picker.py
@@ -27,9 +27,14 @@ from rich.text import Text
from .. import copyright_notice
from ..core.connection import DeviceAuthenticationError, DeviceCommandError
from ..core.device_store import DeviceStore, RememberedDevice
-from ..core.discovery import DiscoveredDevice
+from ..core.discovery import (
+ DEFAULT_TCP_PORT,
+ DiscoveredDevice,
+ parse_tcp_endpoint,
+ tcp_device,
+)
from .logo import load_logo
-from .tui import Choice, Separator
+from .tui import Choice, DeleteRequest, Separator
if TYPE_CHECKING:
from .surface import Ui
@@ -46,6 +51,10 @@ Verify = Callable[[DiscoveredDevice, Optional[str]], Awaitable[Optional[dict]]]
#: device, which the caller treats as "exit the program".
_QUIT = object()
+#: The "add a network device" row's value. Selecting it opens a host:port prompt (TCP
+#: companions aren't discoverable, so they're named by hand) and smoke-tests the result.
+_ADD_TCP = object()
+
#: TYPE-column glyphs marking how a device connects. Kept as module constants so the splash's
#: look can be retuned without touching the row-building logic. ``ᛒ`` is the *Bjarkan* rune the
#: Bluetooth logo is drawn from — rendered white on the Bluetooth blue (see the ``bluetooth``
@@ -54,6 +63,10 @@ _QUIT = object()
_BLE_ICON = "ᛒ"
_SERIAL_ICON = "🔌"
+#: TYPE-column glyph for a TCP companion — a globe, marking a device reached over the network
+#: rather than a wired or Bluetooth link. Two cells like the serial plug, so it aligns the same.
+_TCP_ICON = "🌐"
+
#: Half-block glyphs that taper the Bluetooth badge: ``▐`` fills a cell's right half (so it
#: hugs the rune's left edge) and ``▌`` its left half (hugging the right edge). Drawn in the
#: badge's blue over the terminal background, they widen the blue by half a cell on each side.
@@ -72,6 +85,8 @@ def _type_cell(device: DiscoveredDevice) -> Text:
lining up with the Bluetooth rune (which the badge's left half-block already nudges in a
cell) rather than hugging the column's left edge.
"""
+ if device.is_tcp:
+ return Text(" " + _TCP_ICON)
if not device.is_ble:
return Text(" " + _SERIAL_ICON)
cell = Text()
@@ -88,6 +103,8 @@ def _pad(text: str, width: int) -> str:
def _hardware_name(device: DiscoveredDevice) -> str:
"""The device's product name without its trailing ``(port)`` (that is its own column)."""
+ if device.is_tcp:
+ return device.name or device.product or device.description or "Network device"
if device.is_ble:
return device.name or device.product or device.description or "Bluetooth device"
name = device.product or device.description or device.vendor_label or "Serial device"
@@ -214,11 +231,17 @@ async def _smoke_test(
return None
if info is None:
- reason = (
- "It may be out of range, powered off, already connected elsewhere, or busy."
- if chosen.is_ble
- else "It may be a different kind of serial device, powered off, or busy."
- )
+ if chosen.is_tcp:
+ reason = (
+ "Check the host and port — it may be unreachable, powered off, already "
+ "connected elsewhere, or busy."
+ )
+ elif chosen.is_ble:
+ reason = (
+ "It may be out of range, powered off, already connected elsewhere, or busy."
+ )
+ else:
+ reason = "It may be a different kind of serial device, powered off, or busy."
await ui.notify_startup(
Text.from_markup(
f"[warn]{name} {where} didn't answer as a MeshCore device.[/warn]\n"
@@ -256,34 +279,26 @@ async def prompt_device(
Returns:
The chosen, confirmed :class:`DiscoveredDevice`, or ``None`` if the user chose to
- leave the picker without selecting one — by pressing Esc, choosing the Quit row, or
- having no devices to pick — which the caller treats as a request to exit.
+ leave the picker without selecting one — by pressing Esc or choosing the Quit row —
+ which the caller treats as a request to exit.
"""
- if not devices:
- await ui.notify_startup(
- Text.from_markup(
- "[warn]No companion devices detected.[/warn]\n"
- "Plug one in over USB or power on a Bluetooth companion nearby, pass "
- "[accent]--port[/accent]/[accent]--ble[/accent], or run with "
- "[accent]--mock[/accent]."
- ),
- title="Select a companion device",
- banner=load_logo(),
- footnote=copyright_notice(),
- )
- return None
-
- remembered = store.load()
- # The full registry (not just the single last device) so *every* confirmed companion can
- # be named, highlighted, and sorted to the top — keyed by stable_id.
- registry = store.load_all()
- # Preselect the remembered "last known good" device when it is currently attached.
- default = next((d for d in devices if remembered and remembered.matches(d)), None)
-
+ scanned = list(devices)
while True:
+ remembered = store.load()
+ # The full registry (not just the single last device) so *every* confirmed companion
+ # can be named, highlighted, and sorted to the top — keyed by stable_id. Reloaded each
+ # pass so an add or a removal is reflected the next time the list is drawn.
+ registry = store.load_all()
+ # A TCP companion isn't discoverable, so a previously confirmed one only reappears if we
+ # rebuild it from its remembered endpoint and fold it into the list alongside the
+ # scanned devices (the scan never produces it).
+ listed = scanned + _remembered_tcp_devices(scanned, registry)
+ # Preselect the remembered "last known good" device when it is currently attached/in range.
+ default = next((d for d in listed if remembered and remembered.matches(d)), None)
+
chosen = await ui.select_startup(
"Select a companion device",
- _build_items(devices, remembered, registry),
+ _build_items(listed, remembered, registry),
default=default,
banner=load_logo(),
footnote=copyright_notice(),
@@ -293,9 +308,23 @@ async def prompt_device(
if chosen is None or chosen is _QUIT:
return None
+ if chosen is _ADD_TCP:
+ # Name a network companion by hand and smoke-test it. On success it's returned like
+ # any picked device; on cancel/failure we loop back to the list.
+ added = await _add_network_device(ui, store, registry, verify)
+ if added is not None:
+ return added
+ continue
+
+ if isinstance(chosen, DeleteRequest):
+ # Delete was pressed on a removable (network) row: confirm, forget, and re-draw
+ # the list — the row's disappearance is the visible feedback.
+ await _remove_network_device(ui, store, registry, chosen.value)
+ continue
+
name = _display_name(chosen, registry)
- # "over Bluetooth" reads better than an address; a serial device names its port.
- where = "over Bluetooth" if chosen.is_ble else f"on {chosen.port}"
+ # A human phrase for the transport: an address/endpoint reads worse than a plain word.
+ where = _where_phrase(chosen)
# Smoke-test the choice in place (prompting for a PIN and retrying if it needs one).
# ``None`` means the smoke test failed and already showed the user why — pick again.
info = await _smoke_test(ui, chosen, name, where, verify)
@@ -310,6 +339,122 @@ async def prompt_device(
return chosen
+def _where_phrase(device: DiscoveredDevice) -> str:
+ """A human phrase for a device's transport, woven into the smoke-test spinner line."""
+ if device.is_tcp:
+ return f"at {device.target}"
+ if device.is_ble:
+ return "over Bluetooth"
+ return f"on {device.port}"
+
+
+def _remembered_tcp_devices(
+ discovered: list[DiscoveredDevice], registry: dict[str, RememberedDevice]
+) -> list[DiscoveredDevice]:
+ """Rebuild the confirmed TCP companions from the registry as :class:`DiscoveredDevice`.
+
+ TCP companions don't advertise, so the scan never finds them; this reconstructs each
+ remembered one from its stored ``host:port`` (carrying its known node name for the DEVICE
+ column) so it reappears in the picker. Any that happen to already be in ``discovered``
+ (e.g. re-run within a session) are skipped so they aren't listed twice.
+ """
+ seen = {d.stable_id for d in discovered}
+ rebuilt: list[DiscoveredDevice] = []
+ for record in registry.values():
+ if not record.is_tcp or not record.host or not record.tcp_port:
+ continue
+ device = tcp_device(record.host, record.tcp_port, name=record.node_name)
+ if device.stable_id not in seen:
+ rebuilt.append(device)
+ return rebuilt
+
+
+async def _add_network_device(
+ ui: "Ui",
+ store: DeviceStore,
+ registry: dict[str, RememberedDevice],
+ verify: Verify,
+) -> Optional[DiscoveredDevice]:
+ """Collect a ``host:port``, smoke-test the network companion there, and remember it.
+
+ A network (TCP) companion is named by hand — it isn't attached and doesn't advertise — so
+ this opens a text prompt on the splash, parses the endpoint (a bare host defaults its
+ port), and runs the same smoke test the discovered transports use. On success the device
+ is remembered forever and returned; on a cancelled prompt or a failed test the caller
+ re-opens the device list.
+
+ Args:
+ ui: The interactive surface for the prompt, spinner, and notices.
+ store: The confirmed-device registry, updated once the device answers.
+ registry: The current registry, for naming the smoke-test spinner line.
+ verify: The smoke-test callback (see :data:`Verify`).
+
+ Returns:
+ The confirmed TCP :class:`DiscoveredDevice`, or ``None`` to return to the device list.
+ """
+ def _validate(text: str) -> object:
+ try:
+ parse_tcp_endpoint(text)
+ except ValueError as exc:
+ return str(exc)
+ return True
+
+ entered = await ui.prompt_text_startup(
+ "Add a network device",
+ prompt="Enter the companion's network address:",
+ validate=_validate,
+ help_text=f"host or host:port — the port defaults to {DEFAULT_TCP_PORT}",
+ banner=load_logo(),
+ footnote=copyright_notice(),
+ )
+ if entered is None:
+ return None # cancelled → back to the device list
+ host, port = parse_tcp_endpoint(entered) # already validated above
+ device = tcp_device(host, port)
+ name = _display_name(device, registry)
+ info = await _smoke_test(ui, device, name, _where_phrase(device), verify)
+ if info is None:
+ return None # not a reachable companion — the smoke test already explained why
+ store.remember(
+ device, node_name=_node_name_from(info), hardware_model=_model_from(info)
+ )
+ return device
+
+
+async def _remove_network_device(
+ ui: "Ui",
+ store: DeviceStore,
+ registry: dict[str, RememberedDevice],
+ device: DiscoveredDevice,
+) -> None:
+ """Confirm and forget a remembered network (TCP) device, dropping it from the picker.
+
+ Removal is offered only on network rows: a TCP companion is listed solely from its
+ remembered endpoint, so forgetting it is what makes it leave the picker — a scanned serial
+ or BLE device would just reappear on the next scan. Opens a cautionary Cancel/Remove
+ confirm on the splash; on Remove the record is pruned from the store, on Cancel/Esc nothing
+ changes. Either way the caller re-opens the list, so the row's absence is the feedback.
+
+ Args:
+ ui: The interactive surface for the confirm dialog.
+ store: The confirmed-device registry to prune.
+ registry: The current registry, for naming the device in the prompt.
+ device: The network device the user asked to remove.
+ """
+ if not device.is_tcp:
+ return # defensive: only network rows opt into deletion (see _build_items)
+ name = _display_name(device, registry)
+ confirmed = await ui.confirm_startup(
+ f"Remove {name} ({device.target}) from the device list?",
+ title="Remove network device",
+ confirm_label="Remove",
+ banner=load_logo(),
+ footnote=copyright_notice(),
+ )
+ if confirmed:
+ store.forget(device.stable_id)
+
+
def _order(
devices: list[DiscoveredDevice], registry: dict[str, RememberedDevice]
) -> list[DiscoveredDevice]:
@@ -335,20 +480,30 @@ def _build_items(
The row for each device leads with its display name (the remembered node's name when
known, else the hardware name), followed by its connection target, a TYPE glyph marking
the transport, and the HARDWARE column (the remembered firmware model, else the USB
- vendor); columns are padded to a shared width so they align. Confirmed companions sort to the top (most-recent first), wear their name in white
- and a bright tag; the remembered default is starred. A trailing Quit row (like the menu's)
- lets the user exit from here.
+ vendor); columns are padded to a shared width so they align. Confirmed companions sort to
+ the top (most-recent first), wear their name in white and a bright tag; the remembered
+ default is starred. Trailing rows let the user name a network device by hand and quit here.
"""
+ if not devices:
+ # Nothing attached or in range — but a TCP companion can still be reached by hand, so
+ # show a muted note over the same action rows rather than a dead-end.
+ note = Separator(" no companion devices detected — add a network device, or quit")
+ return [note, *_action_rows()]
devices = _order(devices, registry)
known: set[str] = set(registry)
name_w = max(cell_len(_display_name(d, registry)) for d in devices)
name_w = max(name_w, len("DEVICE"))
- # The middle column holds a serial port or a BLE address; label it for whichever kinds
- # are present so a Bluetooth address never sits under a bare "PORT" heading.
- port_label = "PORT"
- if any(d.is_ble for d in devices):
- port_label = "ADDRESS" if all(d.is_ble for d in devices) else "PORT / ADDRESS"
+ # The middle column holds a serial port, a BLE address, or a TCP host:port; label it for
+ # whichever kinds are present so a non-serial endpoint never sits under a bare "PORT"
+ # heading (a BLE address and a network host:port both read as an "address").
+ has_serial = any(not d.is_ble and not d.is_tcp for d in devices)
+ has_address = any(d.is_ble or d.is_tcp for d in devices)
+ port_label = (
+ "PORT / ADDRESS" if has_serial and has_address
+ else "ADDRESS" if has_address
+ else "PORT"
+ )
port_w = max(cell_len(_where(d)) for d in devices)
port_w = max(port_w, len(port_label))
# The TYPE column holds a small transport badge (at most 3 cells); its heading is wider,
@@ -395,15 +550,37 @@ def _build_items(
if is_known:
row.append(" ")
row.append("· MeshCore device", style="ok")
+ elif device.is_tcp:
+ row.append(" ")
+ row.append("· network companion", style="muted")
elif device.is_ble:
row.append(" ")
row.append("· Bluetooth companion", style="muted")
elif device.confidence == "bridge":
row.append(" ")
row.append("· serial adapter", style="muted")
- items.append(Choice(title=row, value=device))
- # A trailing Quit row, mirroring the main menu, so exiting is an explicit choice as well
- # as an Esc away — the leading spaces line it up under the device-name column.
- items.append(Separator(" "))
- items.append(Choice(title=" Quit", value=_QUIT))
+ # Only a network device opts into Delete-to-remove: it's listed solely from its
+ # remembered endpoint, so forgetting it is the only way it leaves the picker. A scanned
+ # serial/BLE device would just reappear, so Delete stays inert on those rows.
+ items.append(Choice(title=row, value=device, deletable=device.is_tcp))
+ items.extend(_action_rows())
return items
+
+
+def _action_rows() -> list:
+ """The trailing splash rows: name a network device by hand, then quit.
+
+ A network (TCP) companion doesn't advertise and isn't attached, so it can't be scanned
+ for — the "add a network device" row opens a host:port prompt to name one. It's flagged
+ experimental (TCP companion support is still settling), with the tag in the cautionary
+ hue so it reads as a caveat rather than a description. The Quit row mirrors the main menu.
+ The leading spaces line both up under the device-name column.
+ """
+ add_row = Text()
+ add_row.append(f" {_TCP_ICON} Add a network device…")
+ add_row.append(" · experimental", style="warn")
+ return [
+ Separator(" "),
+ Choice(title=add_row, value=_ADD_TCP),
+ Choice(title=" 🚪 Quit", value=_QUIT),
+ ]
diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py
index ce89bc2..b165fd7 100644
--- a/meshterm/ui/menu.py
+++ b/meshterm/ui/menu.py
@@ -283,6 +283,7 @@ def _device_label(ctx: AppContext, cache: dict) -> tuple[str, str]:
ctx.active_transport,
ctx.active_port,
ctx.active_address,
+ ctx.active_endpoint,
)
if cache.get("key") == key:
return cache["value"]
@@ -300,6 +301,8 @@ def _device_label(ctx: AppContext, cache: dict) -> tuple[str, str]:
name = record.label
if ctx.active_transport == "ble":
where = "BLE"
+ elif ctx.active_transport == "tcp":
+ where = ctx.active_endpoint or "TCP"
else:
where = ctx.active_port or (sel.port if sel is not None else "") or ""
cache["key"], cache["value"] = key, (name, where)
@@ -551,12 +554,18 @@ async def _startup(ctx: AppContext) -> bool:
if chosen is None:
return False # the user quit at the splash — exit without opening the menu
ctx.selected_device = chosen
- if chosen.is_ble:
+ if chosen.is_tcp:
+ ctx.tcp_override = chosen.target
+ ctx.ble_override = None
+ ctx.port_override = None
+ elif chosen.is_ble:
ctx.ble_override = chosen.address
+ ctx.tcp_override = None
ctx.port_override = None
else:
ctx.port_override = chosen.port
ctx.ble_override = None
+ ctx.tcp_override = None
if probed.get("device_id") == chosen.stable_id:
ctx.adopt_device(probed["device"])
# Between the device splash and the first menu paint, resuming background listening opens
@@ -853,8 +862,9 @@ async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None:
from ..core.connection import serial_port_present
while True:
- # Serial: wait for the port to re-appear before touching the radio. BLE (and an
- # unknown/deferred serial port): skip the wait and just retry the reconnect itself.
+ # Serial: wait for the port to re-appear before touching the radio. BLE/TCP (and an
+ # unknown/deferred serial port): skip the wait and just retry the reconnect itself —
+ # ``create_ble``/``create_tcp`` connect by address/endpoint and fail fast when absent.
if ctx.active_transport == "serial":
port = ctx.active_port
if port is not None and not serial_port_present(port):
diff --git a/meshterm/ui/surface.py b/meshterm/ui/surface.py
index b07c058..5a1e922 100644
--- a/meshterm/ui/surface.py
+++ b/meshterm/ui/surface.py
@@ -136,6 +136,18 @@ class Ui:
"""Choose one item on a chromeless startup splash; ``None`` if skipped."""
raise NotImplementedError
+ async def confirm_startup(
+ self,
+ prompt: "str | Text",
+ *,
+ title: str = "",
+ confirm_label: str = "Remove",
+ banner: Any = None,
+ footnote: Optional[str] = None,
+ ) -> bool:
+ """Confirm a destructive action on the startup splash; ``True`` only if committed."""
+ raise NotImplementedError
+
async def notify_startup(
self,
renderable: RenderableType,
@@ -171,6 +183,20 @@ class Ui:
"""Ask for a Bluetooth companion's pairing PIN on the startup splash; ``None`` if cancelled."""
raise NotImplementedError
+ async def prompt_text_startup(
+ self,
+ title: str,
+ *,
+ prompt: str = "",
+ default: str = "",
+ validate: Optional[Validator] = None,
+ help_text: str = "",
+ banner: Any = None,
+ footnote: Optional[str] = None,
+ ) -> Optional[str]:
+ """Ask for a line of text on a chromeless startup splash; ``None`` if cancelled."""
+ raise NotImplementedError
+
async def reorder(self, title: str, labels: list[str]) -> list[int]:
"""Let the user rearrange rows with the arrows; return the new order of row indices."""
raise NotImplementedError
@@ -371,6 +397,18 @@ class PlainUi(Ui):
"""Unsupported in scripted CLI mode."""
raise self._no_prompt()
+ async def confirm_startup(
+ self,
+ prompt: "str | Text",
+ *,
+ title: str = "",
+ confirm_label: str = "Remove",
+ banner: Any = None,
+ footnote: Optional[str] = None,
+ ) -> bool:
+ """Unsupported in scripted CLI mode — the picker splash is interactive-only."""
+ raise self._no_prompt()
+
async def notify_startup(
self,
renderable: RenderableType,
@@ -410,6 +448,20 @@ class PlainUi(Ui):
"""
raise self._no_prompt()
+ async def prompt_text_startup(
+ self,
+ title: str,
+ *,
+ prompt: str = "",
+ default: str = "",
+ validate: Optional[Validator] = None,
+ help_text: str = "",
+ banner: Any = None,
+ footnote: Optional[str] = None,
+ ) -> Optional[str]:
+ """Unsupported in scripted CLI mode — a network endpoint comes from ``--tcp`` instead."""
+ raise self._no_prompt()
+
async def reorder(self, title: str, labels: list[str]) -> list[int]:
"""Unsupported in scripted CLI mode."""
raise self._no_prompt()
@@ -588,6 +640,24 @@ class TuiUi(Ui):
title, items, default=default, banner=banner, footnote=footnote
)
+ async def confirm_startup(
+ self,
+ prompt: "str | Text",
+ *,
+ title: str = "",
+ confirm_label: str = "Remove",
+ banner: Any = None,
+ footnote: Optional[str] = None,
+ ) -> bool:
+ """Delegate to the session's chromeless startup confirm dialog."""
+ return await self.session.confirm_startup(
+ prompt,
+ title=title,
+ confirm_label=confirm_label,
+ banner=banner,
+ footnote=footnote,
+ )
+
async def notify_startup(
self,
renderable: RenderableType,
@@ -629,6 +699,28 @@ class TuiUi(Ui):
device_name, error=error, help_text=help_text, banner=banner, footnote=footnote
)
+ async def prompt_text_startup(
+ self,
+ title: str,
+ *,
+ prompt: str = "",
+ default: str = "",
+ validate: Optional[Validator] = None,
+ help_text: str = "",
+ banner: Any = None,
+ footnote: Optional[str] = None,
+ ) -> Optional[str]:
+ """Delegate to the session's chromeless startup text dialog."""
+ return await self.session.prompt_text_startup(
+ title,
+ prompt=prompt,
+ default=default,
+ validate=validate,
+ help_text=help_text,
+ banner=banner,
+ footnote=footnote,
+ )
+
async def reorder(self, title: str, labels: list[str]) -> list[int]:
"""Delegate to the session's reorder screen."""
return await self.session.reorder(title, labels)
diff --git a/meshterm/ui/tui/__init__.py b/meshterm/ui/tui/__init__.py
index 84bf384..1af9b9f 100644
--- a/meshterm/ui/tui/__init__.py
+++ b/meshterm/ui/tui/__init__.py
@@ -24,7 +24,7 @@ from .prompt import (
TypedConfirmDialog,
)
from .screen import CANCEL, BusyScreen, Screen, ScrollScreen
-from .select import Choice, SelectScreen, Separator
+from .select import Choice, DeleteRequest, SelectScreen, Separator
from .session import TuiSession
from .spinner import Spinner
@@ -35,6 +35,7 @@ __all__ = [
"BusyScreen",
"SelectScreen",
"Choice",
+ "DeleteRequest",
"Separator",
"TextScreen",
"ConfirmScreen",
diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py
index 5ce54b0..a523726 100644
--- a/meshterm/ui/tui/frame.py
+++ b/meshterm/ui/tui/frame.py
@@ -230,7 +230,11 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str:
# wider than the terminal and never narrower than the title/hint it must show.
probe = max(10, min(cols - 6, 100))
measured = max((_ansi_width(line) for line in screen.render_body(probe)), default=10)
- inner_w = max(measured, cell_len(screen.title), cell_len(screen.footer_hint))
+ # Size to the fullest the footer can get, not this frame's — a screen whose hint grows
+ # as the highlight moves (a select's per-row "Del remove") reports that width here, so
+ # the box is reserved for it up front and never widens mid-navigation.
+ sizing_footer = getattr(screen, "sizing_footer_hint", screen.footer_hint)
+ inner_w = max(measured, cell_len(screen.title), cell_len(sizing_footer))
inner_w = max(10, min(inner_w, cols - 6))
# Pin the banner to a fixed vertical anchor that depends only on the terminal height and
diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py
index db2c4fb..b50c835 100644
--- a/meshterm/ui/tui/select.py
+++ b/meshterm/ui/tui/select.py
@@ -28,10 +28,15 @@ class Choice:
zero-argument callable resolved fresh on every repaint, so a row can track state
that changes while the list is open.
value: Value returned when the row is chosen.
+ deletable: Whether pressing Delete on this row asks to remove it. When set, Delete
+ resolves the list with a :class:`DeleteRequest` wrapping this row's value instead
+ of choosing it, so the caller can run a remove flow and re-open the list. Off by
+ default, so an ordinary list ignores Delete.
"""
title: Union[str, Text, Callable[[], Union[str, Text]]]
value: Any
+ deletable: bool = False
@property
def label(self) -> Union[str, Text]:
@@ -39,11 +44,42 @@ class Choice:
return self.title() if callable(self.title) else self.title
+@dataclass
+class DeleteRequest:
+ """A request, raised from a select list, to remove the highlighted row.
+
+ Pressing Delete on a :class:`Choice` marked ``deletable`` resolves the select with this
+ wrapper rather than the row's value itself, so the caller can tell "the user wants to
+ remove this" apart from "the user chose this" — typically running a confirm-then-forget
+ flow and re-opening the list.
+
+ Attributes:
+ value: The :attr:`Choice.value` of the row the user asked to remove.
+ """
+
+ value: Any
+
+
def _plain(label: Union[str, Text]) -> str:
"""The plain-text form of a row label, for filtering (a :class:`Text` keeps its ``plain``)."""
return label.plain if isinstance(label, Text) else label
+def _splice_hint(base: str, segment: str) -> str:
+ """Insert ``segment`` into a footer hint just before its trailing ``Esc`` clause.
+
+ Keeps the hint grammar's "Esc last" rule when a per-row hint (e.g. ``Del remove`` on a
+ deletable row) is added while the cursor sits on it: the segment lands as its own ``·``
+ atom right before the final ``· Esc …``, rather than after it. A hint with no ``Esc``
+ clause simply gains the segment at the end.
+ """
+ marker = " · Esc"
+ idx = base.rfind(marker)
+ if idx == -1:
+ return f"{base} · {segment}"
+ return f"{base[:idx]} · {segment}{base[idx:]}"
+
+
@dataclass
class Separator:
"""A non-selectable row between choices.
@@ -77,6 +113,7 @@ class SelectScreen(Screen):
prompt: str = "",
default: Any = None,
footer_hint: Optional[str] = None,
+ delete_hint: str = "",
filterable: bool = True,
wrap: bool = True,
) -> None:
@@ -90,6 +127,10 @@ class SelectScreen(Screen):
default: A choice value to pre-highlight, if present.
footer_hint: Footer key hint; defaults to one that mentions type-to-filter only
when ``filterable`` (a fixed list shouldn't advertise a filter it ignores).
+ delete_hint: A key-hint atom (e.g. ``"Del remove"``) surfaced in the footer only
+ while the highlighted row is :attr:`Choice.deletable` — so the removal key
+ advertises itself exactly when it would act, and stays hidden on rows it can't
+ touch. Empty (the default) leaves the footer fixed.
filterable: Whether typing narrows the list. Off for short, fixed lists (e.g.
the startup device picker) where type-to-filter would only get in the way.
wrap: Whether the highlight wraps around the ends (Down from the last row jumps
@@ -104,7 +145,8 @@ class SelectScreen(Screen):
if filterable
else "↑↓ move · Enter select · Esc back"
)
- self.footer_hint = footer_hint
+ self._footer_base = footer_hint
+ self._delete_hint = delete_hint
self._prompt = prompt
self._filterable = filterable
self._wrap = wrap
@@ -185,6 +227,41 @@ class SelectScreen(Screen):
else:
self._index = at_or_before[-2] if len(at_or_before) >= 2 else 0
+ def _current_choice(self) -> Optional[Choice]:
+ """The choice the highlight currently sits on, or ``None`` when the list is empty."""
+ choices = self._choices()
+ if not choices:
+ return None
+ return choices[max(0, min(self._index, len(choices) - 1))]
+
+ @property
+ def footer_hint(self) -> str:
+ """The footer key hint, gaining the :attr:`_delete_hint` atom on a deletable row.
+
+ Fixed to the base hint unless a ``delete_hint`` was supplied *and* the highlighted
+ row opted into removal — then the atom is spliced in just before the trailing ``Esc``
+ clause (see :func:`_splice_hint`), so the removal key shows up on the bottom border
+ precisely while the cursor is on a row it can act on.
+ """
+ base = self._footer_base
+ current = self._current_choice()
+ if self._delete_hint and current is not None and current.deletable:
+ return _splice_hint(base, self._delete_hint)
+ return base
+
+ @property
+ def sizing_footer_hint(self) -> str:
+ """The fullest the footer can get, for stable box sizing (see :attr:`footer_hint`).
+
+ The delete-hint atom is always folded in here, so a compositor that sizes a box to
+ the footer width (the startup splash's :func:`~meshterm.ui.tui.frame.compose_startup`)
+ reserves room for it up front — the box then never widens the moment the highlight
+ lands on a deletable row.
+ """
+ if self._delete_hint:
+ return _splice_hint(self._footer_base, self._delete_hint)
+ return self._footer_base
+
# --- rendering -----------------------------------------------------------
@property
@@ -194,9 +271,13 @@ class SelectScreen(Screen):
The widest of the prompt, title, footer, and every row (with room for the pointer),
so a short menu is a tidy popup rather than a full-width banner. The compositor still
caps this to the space available, and this is only read for a *floating* select — the
- full-screen base menu is laid out by ``compose_base`` and ignores it.
+ full-screen base menu is laid out by ``compose_base`` and ignores it. The footer is
+ measured at its fullest — with the delete-hint atom folded in — so a deletable row
+ surfacing that hint never widens the box mid-navigation.
"""
- widths = [cell_len(self.title), cell_len(self.footer_hint), cell_len(self._prompt)]
+ footer = _splice_hint(self._footer_base, self._delete_hint) if self._delete_hint \
+ else self._footer_base
+ widths = [cell_len(self.title), cell_len(footer), cell_len(self._prompt)]
for item in self._items:
label = item.title if isinstance(item, Separator) else _plain(item.label)
widths.append(cell_len(label) + 2) # + the "❯ " / " " pointer column
@@ -286,6 +367,11 @@ class SelectScreen(Screen):
elif action == "enter":
if choices:
self.resolve(choices[self._index].value)
+ elif action == "delete":
+ # Delete asks to remove the highlighted row, but only where the row opted in
+ # (e.g. a remembered network device in the picker); elsewhere it's inert.
+ if choices and choices[self._index].deletable:
+ self.resolve(DeleteRequest(choices[self._index].value))
elif action == "escape":
super().handle("escape")
elif action == "backspace" and self._filterable:
diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py
index 52cc673..00e75cc 100644
--- a/meshterm/ui/tui/session.py
+++ b/meshterm/ui/tui/session.py
@@ -330,10 +330,24 @@ class TuiSession:
Like :meth:`select`, but drawn without the header/footer status bars and centered
under ``banner`` — the startup device picker's presentation. Type-to-filter is off:
the device list is short and fixed, so stray keys never narrow it. An optional
- ``footnote`` (e.g. a copyright notice) sits muted below the box.
+ ``footnote`` (e.g. a copyright notice) sits muted below the box. When any row opts
+ into removal (a :attr:`~meshterm.ui.tui.select.Choice.deletable` row), a "Del remove"
+ atom joins the footer — but only while the highlight is actually on such a row, so the
+ removal key advertises itself exactly where it acts (see
+ :attr:`~meshterm.ui.tui.select.SelectScreen.footer_hint`).
"""
+ delete_hint = (
+ "Del remove"
+ if any(isinstance(it, Choice) and it.deletable for it in items)
+ else ""
+ )
screen = SelectScreen(
- title, items, default=default, footer_hint=footer_hint, filterable=False
+ title,
+ items,
+ default=default,
+ footer_hint=footer_hint,
+ delete_hint=delete_hint,
+ filterable=False,
)
screen.chrome = False
screen.banner = banner
@@ -341,6 +355,50 @@ class TuiSession:
result = await self.run_screen(screen)
return None if result is CANCEL else result
+ async def confirm_startup(
+ self,
+ prompt: "str | Text",
+ *,
+ title: str = "",
+ confirm_label: str = "Remove",
+ banner: Optional[Any] = None,
+ footnote: Optional[str] = None,
+ footer_hint: str = "←→ choose · Enter select · Esc cancel",
+ ) -> bool:
+ """Confirm a destructive splash action with a Cancel/verb dialog (chromeless).
+
+ The startup-splash sibling of :meth:`button_dialog`: the same platform-dialog layout
+ — the safe *Cancel* on the left and the committing verb on the right and default, so
+ Enter commits and Esc backs out — but drawn without the status bars and centered under
+ ``banner``, so it reads as part of the device-selection flow it floats over. Themed
+ cautionary (warn prompt and border), since it only ever gates a removal.
+
+ Args:
+ prompt: The question shown above the buttons.
+ title: Short heading shown in the dialog's border.
+ confirm_label: Label for the committing button (e.g. ``"Remove"``).
+ banner: Wordmark rows drawn above the box (as on the other startup splashes).
+ footnote: Muted line drawn below the box.
+ footer_hint: Footer key hint.
+
+ Returns:
+ ``True`` only when the user chose the committing button; ``False`` on Cancel/Esc.
+ """
+ screen = ButtonDialog(
+ prompt,
+ [("Cancel", False), (confirm_label, True)],
+ title=title,
+ default=1,
+ footer_hint=footer_hint,
+ prompt_style="warn",
+ border_style="warn",
+ )
+ screen.chrome = False
+ screen.banner = banner
+ screen.footnote = footnote
+ result = await self.run_screen(screen)
+ return result is True
+
async def notify_startup(
self,
renderable: RenderableType,
@@ -445,6 +503,45 @@ class TuiSession:
result = await self.run_screen(screen)
return None if result is CANCEL else result
+ async def prompt_text_startup(
+ self,
+ title: str,
+ *,
+ prompt: str = "",
+ default: str = "",
+ validate: Optional[Validator] = None,
+ help_text: str = "",
+ banner: Optional[Any] = None,
+ footnote: Optional[str] = None,
+ ) -> Optional[str]:
+ """Ask for a line of text on the chromeless startup splash (e.g. a TCP host:port).
+
+ Drawn like :meth:`prompt_pin_startup` — a bordered :class:`TextScreen` centered under
+ ``banner`` with no status bars — so entering a network address reads as part of the
+ same device-selection flow. ``validate`` blocks submission on a bad value the same way
+ the in-menu text prompt does.
+
+ Args:
+ title: Short heading shown in the dialog's border.
+ prompt: The instruction shown inside the box, above the field.
+ default: Prefilled text.
+ validate: Optional validator run on Enter; a returned string blocks submission.
+ help_text: A muted hint under the field.
+ banner: Wordmark rows drawn above the box (as on the other startup splashes).
+ footnote: Muted line drawn below the box.
+
+ Returns:
+ The entered text, or ``None`` if the user pressed Esc to cancel.
+ """
+ screen = TextScreen(
+ title, prompt=prompt, default=default, validate=validate, help_text=help_text
+ )
+ screen.chrome = False
+ screen.banner = banner
+ screen.footnote = footnote
+ result = await self.run_screen(screen)
+ return None if result is CANCEL else result
+
async def reorder(self, title: str, labels: list[str]) -> list[int]:
"""Show a drag-with-arrows reorder screen; return the final order of row indices.
diff --git a/tests/test_channels.py b/tests/test_channels.py
index 7c4b9be..304dd48 100644
--- a/tests/test_channels.py
+++ b/tests/test_channels.py
@@ -815,3 +815,21 @@ async def test_cli_import_rejects_bad_link(ctx: AppContext) -> None:
tool = ChannelsTool()
with pytest.raises(typer.BadParameter):
await tool.run(ctx, {"cli_action": "import", "index": 5, "url": "https://nope"})
+
+
+async def test_cli_clear_removes_the_channel_from_its_slot(ctx: AppContext) -> None:
+ """`clear` empties a configured slot; `list` no longer sees it."""
+ tool = ChannelsTool()
+ await tool.run(ctx, {"cli_action": "add", "index": 1, "name": "Ops", "secret": None})
+ assert any(s.idx == 1 for s in await read_channel_slots(await ctx.device()))
+
+ result = await tool.run(ctx, {"cli_action": "clear", "index": 1})
+ assert result.summary == {"index": 1, "cleared": True}
+ assert not any(s.idx == 1 for s in await read_channel_slots(await ctx.device()))
+
+
+async def test_cli_clear_of_an_empty_slot_is_a_no_op(ctx: AppContext) -> None:
+ """Clearing an already-empty slot reports nothing cleared rather than erroring."""
+ tool = ChannelsTool()
+ result = await tool.run(ctx, {"cli_action": "clear", "index": 7})
+ assert result.summary == {"index": 7, "cleared": False}
diff --git a/tests/test_config.py b/tests/test_config.py
index ffe9e9c..a851e27 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -41,3 +41,28 @@ def test_direct_message_soft_retries_clamped_to_range(tmp_path: Path) -> None:
cold = tmp_path / "cold.toml"
cold.write_text("direct_message_soft_retries = -4\n", encoding="utf-8")
assert Settings.load(cold).direct_message_soft_retries == 0
+
+
+def test_tcp_profile_inferred_and_loaded(tmp_path: Path) -> None:
+ """A profile with a ``host`` loads as a TCP profile and exposes its host:port endpoint."""
+ config = tmp_path / "config.toml"
+ config.write_text(
+ "[profiles.wifi]\n"
+ 'host = "192.168.1.50"\n'
+ "tcp_port = 6000\n",
+ encoding="utf-8",
+ )
+ profile = Settings.load(config).profiles["wifi"]
+ assert profile.is_tcp and profile.transport == "tcp"
+ assert profile.host == "192.168.1.50" and profile.tcp_port == 6000
+ assert profile.tcp_endpoint == "192.168.1.50:6000"
+
+
+def test_tcp_profile_defaults_port(tmp_path: Path) -> None:
+ """A TCP profile naming only a host takes the default port in its endpoint."""
+ config = tmp_path / "config.toml"
+ config.write_text(
+ '[profiles.wifi]\nhost = "meshcore.local"\n', encoding="utf-8"
+ )
+ profile = Settings.load(config).profiles["wifi"]
+ assert profile.is_tcp and profile.tcp_endpoint == "meshcore.local:5000"
diff --git a/tests/test_courier.py b/tests/test_courier.py
index d388168..c80328e 100644
--- a/tests/test_courier.py
+++ b/tests/test_courier.py
@@ -10,6 +10,8 @@ import logging
from datetime import timedelta
from pathlib import Path
+import pytest
+
from meshterm.core.courier_store import DONE_CAP, QUEUED, CourierStore
from meshterm.core.models import ChatMessage, Contact, utcnow
from meshterm.core.watch_store import WatchStore
@@ -210,6 +212,122 @@ async def test_attempt_now_forces_a_send(tmp_path: Path) -> None:
assert await service.attempt_now(entry.ident) == "gone" # already settled
+# --- the scripted CLI actions -------------------------------------------------------------
+
+
+class _NoteUi:
+ """A UI surface that just collects notes and shown renderables."""
+
+ def __init__(self) -> None:
+ self.notes: list[str] = []
+ self.shown: list[object] = []
+
+ def note(self, markup: str) -> None:
+ self.notes.append(markup)
+
+ def show(self, *renderables: object) -> None:
+ self.shown.extend(renderables)
+
+
+class _StubCourier:
+ """A courier service whose ``attempt_now`` returns a canned outcome."""
+
+ def __init__(self, store: CourierStore, outcome: str) -> None:
+ self._store = store
+ self._outcome = outcome
+
+ async def attempt_now(self, ident: int) -> str:
+ message = self._store.get(ident)
+ if message is None or message.status != QUEUED:
+ return "gone"
+ if self._outcome == "delivered":
+ self._store.mark_delivered(ident)
+ return self._outcome
+
+
+class _ToolCtx:
+ """Minimal context for the courier tool's scripted CLI actions (no device needed)."""
+
+ def __init__(self, tmp_path: Path, *, outcome: str = "delivered") -> None:
+ self.courier_store = CourierStore(tmp_path / "courier.json")
+ self.ui = _NoteUi()
+ self.courier = _StubCourier(self.courier_store, outcome)
+
+
+async def test_cli_list_renders_waiting_and_finished(tmp_path: Path) -> None:
+ """`courier list` shows the outbox without needing a device."""
+ from meshterm.tools.courier import CourierTool
+
+ ctx = _ToolCtx(tmp_path)
+ ctx.courier_store.queue(NODE, "YUL", "still waiting")
+ done = ctx.courier_store.queue(NODE, "YUL", "landed")
+ ctx.courier_store.mark_delivered(done.ident)
+
+ result = await CourierTool().run(ctx, {"cli_action": "list"})
+ assert result.summary == {"entries": 2}
+ assert ctx.ui.shown # a table was rendered
+
+
+async def test_cli_list_empty_notes_and_counts_zero(tmp_path: Path) -> None:
+ """An empty outbox reports zero entries and shows no table."""
+ from meshterm.tools.courier import CourierTool
+
+ ctx = _ToolCtx(tmp_path)
+ result = await CourierTool().run(ctx, {"cli_action": "list"})
+ assert result.summary == {"entries": 0}
+ assert ctx.ui.shown == []
+
+
+async def test_cli_cancel_removes_a_waiting_entry(tmp_path: Path) -> None:
+ """`courier cancel` drops a waiting entry; a second cancel is a no-op."""
+ from meshterm.tools.courier import CourierTool
+
+ ctx = _ToolCtx(tmp_path)
+ entry = ctx.courier_store.queue(NODE, "YUL", "nope")
+ tool = CourierTool()
+
+ result = await tool.run(ctx, {"cli_action": "cancel", "id": entry.ident})
+ assert result.summary == {"id": entry.ident, "cancelled": True}
+ assert ctx.courier_store.get(entry.ident) is None
+
+ again = await tool.run(ctx, {"cli_action": "cancel", "id": entry.ident})
+ assert again.summary == {"id": entry.ident, "cancelled": False}
+
+
+async def test_cli_send_forces_one_attempt(tmp_path: Path) -> None:
+ """`courier send` forces one delivery attempt and reports the outcome."""
+ from meshterm.tools.courier import CourierTool
+
+ ctx = _ToolCtx(tmp_path, outcome="delivered")
+ entry = ctx.courier_store.queue(NODE, "YUL", "hello")
+ result = await CourierTool().run(ctx, {"cli_action": "send", "id": entry.ident})
+ assert result.summary == {"id": entry.ident, "outcome": "delivered"}
+
+
+async def test_cli_send_unknown_entry_errors(tmp_path: Path) -> None:
+ """Sending a non-existent entry is a clean device-command error, not a crash."""
+ from meshterm.core.connection import DeviceCommandError
+ from meshterm.tools.courier import CourierTool
+
+ ctx = _ToolCtx(tmp_path)
+ with pytest.raises(DeviceCommandError):
+ await CourierTool().run(ctx, {"cli_action": "send", "id": 999})
+
+
+async def test_cli_clear_drops_finished_only(tmp_path: Path) -> None:
+ """`courier clear` removes finished entries and leaves the waiting queue."""
+ from meshterm.tools.courier import CourierTool
+
+ ctx = _ToolCtx(tmp_path)
+ ctx.courier_store.queue(NODE, "YUL", "still here")
+ done = ctx.courier_store.queue(NODE, "YUL", "gone soon")
+ ctx.courier_store.mark_delivered(done.ident)
+
+ result = await CourierTool().run(ctx, {"cli_action": "clear"})
+ assert result.summary == {"cleared": 1}
+ assert [m.text for m in ctx.courier_store.entries()] == ["still here"]
+
+
# --- the clock parser ---------------------------------------------------------------------
diff --git a/tests/test_disconnect.py b/tests/test_disconnect.py
index e6e856e..8499e6e 100644
--- a/tests/test_disconnect.py
+++ b/tests/test_disconnect.py
@@ -435,6 +435,57 @@ async def test_ble_profile_opens_bluetooth_transport(tmp_path: Path, monkeypatch
ctx.repo.close()
+async def test_tcp_profile_opens_network_transport(tmp_path: Path, monkeypatch) -> None:
+ """A TCP profile makes ``device()`` build a network connection by host:port."""
+ from meshterm.core import connection as conn
+ from meshterm.core.config import DeviceProfile
+
+ settings = Settings(config_dir=tmp_path, db_path=tmp_path / "tcp.db")
+ ctx = AppContext(
+ console=Console(file=io.StringIO()),
+ settings=settings,
+ repo=Repository(settings.db_path),
+ device_store=DeviceStore(tmp_path / "devices.json"),
+ admin_store=AdminStore(tmp_path / "admin.json"),
+ profile=DeviceProfile(name="wifi", transport="tcp", host="192.168.1.50", tcp_port=5000),
+ )
+
+ built: dict = {}
+
+ class _FakeTcp:
+ transport = "tcp"
+
+ def __init__(self, **kw):
+ built.update(kw)
+ self._port = None
+ self._address = None
+ self.endpoint = f"{kw.get('host')}:{kw.get('tcp_port')}"
+
+ async def connect(self):
+ pass
+
+ async def get_self_info(self):
+ return {"name": "WifiNode"}
+
+ def fake_make_device(**kw):
+ assert kw["transport"] == "tcp"
+ return _FakeTcp(**kw)
+
+ monkeypatch.setattr(conn, "make_device", fake_make_device)
+ import meshterm.context as context_mod
+
+ monkeypatch.setattr(context_mod, "make_device", fake_make_device)
+ try:
+ device = await ctx.device()
+ assert device.transport == "tcp"
+ assert built["host"] == "192.168.1.50" and built["tcp_port"] == 5000
+ assert ctx.active_transport == "tcp"
+ assert ctx.active_endpoint == "192.168.1.50:5000"
+ assert ctx.active_port is None and ctx.active_address is None
+ finally:
+ ctx.repo.close()
+
+
async def test_reconnect_leaves_idle_services_idle(tmp_path: Path) -> None:
"""Reconnect only restores what was live: idle services stay idle afterward."""
ctx = _make_ctx(tmp_path)
diff --git a/tests/test_discovery.py b/tests/test_discovery.py
index 5063365..b09f76b 100644
--- a/tests/test_discovery.py
+++ b/tests/test_discovery.py
@@ -154,6 +154,67 @@ def test_ble_and_serial_stable_ids_never_collide() -> None:
assert _ble().stable_id != DiscoveredDevice("COM5", serial_number="SN1").stable_id
+# -- TCP transport -------------------------------------------------------------
+
+
+def test_tcp_device_identity_and_labels() -> None:
+ """A TCP device reports host:port as its target, a stable tcp: id, and a network label."""
+ from meshterm.core.discovery import tcp_device
+
+ dev = tcp_device("192.168.1.50", 5000, name="WifiNode")
+ assert dev.is_tcp and dev.transport == "tcp"
+ assert dev.target == "192.168.1.50:5000" # the connection identifier is host:port
+ assert dev.stable_id == "tcp:192.168.1.50:5000"
+ assert dev.confidence == "board" and dev.is_likely_lora # a named endpoint is confident
+ assert dev.vendor_label == "" # a network endpoint exposes no maker
+ assert dev.label == "WifiNode (192.168.1.50:5000)"
+
+
+def test_tcp_stable_ids_never_collide_with_other_transports() -> None:
+ """A TCP endpoint can't map to the same remembered device as a BLE/serial one."""
+ from meshterm.core.discovery import tcp_device
+
+ tcp = tcp_device("10.0.0.5", 5000)
+ assert tcp.stable_id != _ble().stable_id
+ assert tcp.stable_id != DiscoveredDevice("COM5", serial_number="SN1").stable_id
+
+
+def test_parse_tcp_endpoint_forms() -> None:
+ """A bare host takes the default port; host:port and bracketed IPv6 parse explicitly."""
+ from meshterm.core.discovery import DEFAULT_TCP_PORT, parse_tcp_endpoint
+
+ assert parse_tcp_endpoint("192.168.1.50") == ("192.168.1.50", DEFAULT_TCP_PORT)
+ assert parse_tcp_endpoint("meshcore.local:6000") == ("meshcore.local", 6000)
+ assert parse_tcp_endpoint("[::1]:5000") == ("::1", 5000)
+ assert parse_tcp_endpoint(" 10.0.0.5 : 7000 ".replace(" ", "")) == ("10.0.0.5", 7000)
+
+
+def test_parse_tcp_endpoint_rejects_bad_values() -> None:
+ """An empty host or a non-numeric / out-of-range port raises a user-facing error."""
+ from meshterm.core.discovery import parse_tcp_endpoint
+
+ for bad in ("", " ", "host:notaport", "host:0", "host:70000"):
+ with pytest.raises(ValueError):
+ parse_tcp_endpoint(bad)
+
+
+def test_tcp_device_store_round_trip(tmp_path: Path) -> None:
+ """A remembered TCP device persists its transport, host, and port, matched by stable_id."""
+ from meshterm.core.discovery import tcp_device
+
+ store = DeviceStore(tmp_path / "devices.json")
+ dev = tcp_device("192.168.1.50", 5000, name="WifiNode")
+ store.remember(dev, node_name="WifiNode")
+
+ loaded = store.load()
+ assert loaded is not None
+ assert loaded.is_tcp and loaded.transport == "tcp"
+ assert loaded.host == "192.168.1.50" and loaded.tcp_port == 5000
+ assert loaded.target == "192.168.1.50:5000"
+ assert loaded.node_name == "WifiNode"
+ assert loaded.matches(dev)
+
+
async def test_discover_ble_filters_to_meshcore(monkeypatch: pytest.MonkeyPatch) -> None:
"""The BLE scan keeps only MeshCore-named adverts and maps them to devices."""
from types import SimpleNamespace
@@ -288,6 +349,28 @@ def test_device_store_remembers_every_confirmed_device(tmp_path: Path) -> None:
assert set(store.load_all()) == {"sn:SN1", "sn:SN2"}
+def test_device_store_forget_removes_and_reassigns_default(tmp_path: Path) -> None:
+ """``forget`` drops a record and hands the default to the newest survivor (or clears it)."""
+ store = DeviceStore(tmp_path / "devices.json")
+ first = DiscoveredDevice("COM5", serial_number="SN1", product="Wio")
+ second = DiscoveredDevice("COM6", serial_number="SN2", product="Heltec")
+ store.remember(first, node_name="Base")
+ store.remember(second, node_name="Roamer") # the newer default
+
+ # Forgetting the current default reassigns it to the remaining (older) device.
+ assert store.forget("sn:SN2") is True
+ assert set(store.load_all()) == {"sn:SN1"}
+ assert store.load().stable_id == "sn:SN1"
+
+ # Forgetting an unknown id is a no-op that reports it did nothing.
+ assert store.forget("sn:absent") is False
+
+ # Forgetting the last device empties the registry and clears the default.
+ assert store.forget("sn:SN1") is True
+ assert store.load_all() == {}
+ assert store.load() is None
+
+
def test_device_store_migrates_old_flat_format(tmp_path: Path) -> None:
"""A pre-registry flat record still reads back as a one-entry registry."""
path = tmp_path / "devices.json"
@@ -378,6 +461,36 @@ def test_ble_device_store_round_trip(tmp_path: Path) -> None:
assert loaded.matches(dev)
+def test_resolve_prefers_explicit_tcp() -> None:
+ """An explicit --tcp selects the TCP transport, normalizing a bare host's default port."""
+ res = resolve_device([], None, explicit_tcp="192.168.1.50")
+ assert res.transport == "tcp" and res.source == "tcp"
+ assert res.target == "192.168.1.50:5000" # default port applied
+ assert res.device is not None and res.device.stable_id == "tcp:192.168.1.50:5000"
+
+
+def test_resolve_tcp_wins_over_ble_and_port() -> None:
+ """--tcp outranks --ble and --port when more than one is (somehow) supplied."""
+ res = resolve_device(
+ [], None, explicit_tcp="10.0.0.5:5000", explicit_ble="AA:BB", explicit_port="COM5"
+ )
+ assert res.transport == "tcp" and res.target == "10.0.0.5:5000"
+
+
+def test_resolve_uses_tcp_profile() -> None:
+ """A TCP profile's host:port is used when no explicit override is given."""
+ profile = DeviceProfile(name="wifi", transport="tcp", host="10.0.0.9", tcp_port=6000)
+ res = resolve_device([], None, profile=profile)
+ assert res.transport == "tcp" and res.source == "profile"
+ assert res.target == "10.0.0.9:6000"
+
+
+def test_resolve_bad_tcp_endpoint_raises() -> None:
+ """A malformed --tcp value raises a clean selection error rather than a raw ValueError."""
+ with pytest.raises(DeviceSelectionError):
+ resolve_device([], None, explicit_tcp="host:notaport")
+
+
def test_resolve_ambiguous_raises(tmp_path: Path) -> None:
"""Multiple devices with no usable default raise a guidance error."""
devices = [
diff --git a/tests/test_tui.py b/tests/test_tui.py
index 2af2680..119605d 100644
--- a/tests/test_tui.py
+++ b/tests/test_tui.py
@@ -124,6 +124,36 @@ def test_select_non_filterable_ignores_typing() -> None:
assert len(screen._rows()) == 2 # nothing was filtered out
+def test_select_delete_hint_follows_the_highlight() -> None:
+ """The 'Del remove' atom shows only while the cursor sits on a deletable row."""
+ screen = SelectScreen(
+ "pick",
+ [Choice("keep", 1), Choice("drop", 2, deletable=True)],
+ footer_hint="↑↓ move · Enter select · Esc quit",
+ delete_hint="Del remove",
+ filterable=False,
+ wrap=False,
+ )
+ # On the non-deletable row, the footer is the plain base hint.
+ assert "Del remove" not in screen.footer_hint
+ screen.handle("down") # move onto the deletable row
+ # The atom appears, spliced before the trailing Esc clause (Esc stays last).
+ assert screen.footer_hint == "↑↓ move · Enter select · Del remove · Esc quit"
+ screen.handle("up") # back to the plain row
+ assert "Del remove" not in screen.footer_hint
+ # The box is always sized for the fullest footer, so it never widens on the move.
+ assert "Del remove" in screen.sizing_footer_hint
+
+
+def test_select_no_delete_hint_leaves_footer_fixed() -> None:
+ """Without a delete_hint, a deletable row doesn't touch the footer."""
+ screen = SelectScreen(
+ "pick", [Choice("drop", 1, deletable=True)], footer_hint="↑↓ move · Esc quit"
+ )
+ assert screen.footer_hint == "↑↓ move · Esc quit"
+ assert screen.sizing_footer_hint == "↑↓ move · Esc quit"
+
+
def test_select_escape_cancels() -> None:
"""Esc resolves the sentinel rather than a value."""
assert _run(_menu(), "escape") is CANCEL
@@ -784,8 +814,11 @@ def test_device_picker_builds_aligned_columns(tmp_path) -> None:
for it in captured["items"]
if isinstance(it, Choice)
]
- assert len(rows) == 3 # two devices plus a trailing Quit row (like the main menu)
- assert rows[-1].strip() == "Quit"
+ # Two devices plus the trailing action rows (add a network device, then Quit).
+ assert len(rows) == 4
+ assert "Add a network device…" in rows[-2]
+ assert rows[-2].strip().endswith("· experimental") # the row is flagged experimental
+ assert rows[-1].strip().endswith("Quit")
device_rows = rows[:2]
assert all(port in row for port, row in zip(("COM5", "/dev/ttyUSB0"), device_rows))
assert device_rows[0].index("COM5") == device_rows[1].index("/dev/ttyUSB0")
@@ -838,6 +871,153 @@ def test_device_picker_names_and_sorts_known_devices(tmp_path) -> None:
assert any(_BLE_ICON in row.plain for row in device_rows)
+def test_device_picker_reinjects_remembered_tcp_device(tmp_path) -> None:
+ """A remembered TCP companion reappears in the picker even though it can't be scanned for."""
+ from meshterm.core.device_store import DeviceStore
+ from meshterm.core.discovery import tcp_device
+ from meshterm.ui.device_picker import _TCP_ICON, prompt_device
+
+ store = DeviceStore(tmp_path / "devices.json")
+ store.remember(tcp_device("192.168.1.50", 5000), node_name="WifiNode")
+
+ captured: dict = {}
+
+ class _Ui:
+ async def select_startup(self, title, items, *, default=None, banner=None, footnote=None):
+ captured["items"] = items
+ return None # skip past the smoke test
+
+ async def _never(_device):
+ raise AssertionError("verify should not run when selection is skipped")
+
+ # Nothing discovered this session, yet the remembered network device is rebuilt into the list.
+ asyncio.run(prompt_device(_Ui(), [], store, _never))
+ rows = [it.title for it in captured["items"] if isinstance(it, Choice)]
+ device_rows = [r for r in rows if hasattr(r, "plain") and "WifiNode" in r.plain]
+ assert device_rows, "the remembered TCP device should be listed"
+ top = device_rows[0]
+ assert "192.168.1.50:5000" in top.plain # its host:port sits in the address column
+ assert _TCP_ICON in top.plain # marked with the network TYPE glyph
+
+
+def test_device_picker_adds_network_device(tmp_path) -> None:
+ """The 'add a network device' row prompts for host:port and confirms the TCP companion."""
+ from meshterm.core.device_store import DeviceStore
+ from meshterm.ui.device_picker import _ADD_TCP, prompt_device
+
+ store = DeviceStore(tmp_path / "devices.json")
+ probed: dict = {}
+
+ class _Ui:
+ async def select_startup(self, title, items, *, default=None, banner=None, footnote=None):
+ # Choose the "add a network device" action row.
+ return next(it.value for it in items if isinstance(it, Choice) and it.value is _ADD_TCP)
+
+ async def prompt_text_startup(self, title, *, prompt="", default="", validate=None,
+ help_text="", banner=None, footnote=None):
+ assert validate("192.168.1.50:5000") is True # the validator accepts a good endpoint
+ return "192.168.1.50:5000"
+
+ async def busy_startup(self, message, coro, *, title="", banner=None, footnote=None):
+ return await coro
+
+ async def verify(device, pin=None):
+ probed["target"] = device.target
+ return {"adv_name": "WifiNode"} # a genuine companion answers
+
+ chosen = asyncio.run(prompt_device(_Ui(), [], store, verify))
+ assert chosen is not None and chosen.is_tcp and chosen.target == "192.168.1.50:5000"
+ assert probed["target"] == "192.168.1.50:5000"
+ # The confirmed network device is remembered forever, with the node name it reported.
+ remembered = store.load()
+ assert remembered is not None and remembered.is_tcp and remembered.node_name == "WifiNode"
+
+
+def test_device_picker_removes_network_device_on_delete(tmp_path) -> None:
+ """Delete on a network row confirms, forgets it, and it's gone from the re-drawn list."""
+ from meshterm.core.device_store import DeviceStore
+ from meshterm.core.discovery import tcp_device
+ from meshterm.ui.device_picker import _QUIT, prompt_device
+ from meshterm.ui.tui import DeleteRequest
+
+ store = DeviceStore(tmp_path / "devices.json")
+ store.remember(tcp_device("192.168.1.50", 5000), node_name="WifiNode")
+
+ seen_rows: list[list] = []
+ confirmed_prompts: list = []
+
+ class _Ui:
+ def __init__(self) -> None:
+ self._passes = 0
+
+ async def select_startup(self, title, items, *, default=None, banner=None, footnote=None):
+ names = [it.label.plain for it in items
+ if isinstance(it, Choice) and hasattr(it.label, "plain")]
+ seen_rows.append(names)
+ self._passes += 1
+ if self._passes == 1:
+ # First pass: the network row is present and marked deletable — press Delete.
+ row = next(it for it in items if isinstance(it, Choice)
+ and getattr(it.value, "is_tcp", False))
+ assert row.deletable
+ return DeleteRequest(row.value)
+ # Second pass (after the removal): leave the picker.
+ return _QUIT
+
+ async def confirm_startup(self, prompt, *, title="", confirm_label="Remove",
+ banner=None, footnote=None):
+ confirmed_prompts.append(prompt)
+ return True # the user confirms the removal
+
+ async def _never(_device, _pin=None):
+ raise AssertionError("verify should not run when a row is deleted, not chosen")
+
+ result = asyncio.run(prompt_device(_Ui(), [], store, _never))
+ assert result is None # quit on the second pass
+ # The confirm named the device and its endpoint.
+ assert confirmed_prompts and "WifiNode" in confirmed_prompts[0]
+ assert "192.168.1.50:5000" in confirmed_prompts[0]
+ # It was there on the first draw and gone on the second, and the store forgot it.
+ assert any("WifiNode" in name for name in seen_rows[0])
+ assert not any("WifiNode" in name for name in seen_rows[1])
+ assert store.load() is None
+
+
+def test_device_picker_keeps_network_device_when_removal_cancelled(tmp_path) -> None:
+ """Cancelling the Delete confirm leaves the remembered network device untouched."""
+ from meshterm.core.device_store import DeviceStore
+ from meshterm.core.discovery import tcp_device
+ from meshterm.ui.device_picker import _QUIT, prompt_device
+ from meshterm.ui.tui import DeleteRequest
+
+ store = DeviceStore(tmp_path / "devices.json")
+ store.remember(tcp_device("192.168.1.50", 5000), node_name="WifiNode")
+
+ class _Ui:
+ def __init__(self) -> None:
+ self._passes = 0
+
+ async def select_startup(self, title, items, *, default=None, banner=None, footnote=None):
+ self._passes += 1
+ if self._passes == 1:
+ row = next(it for it in items if isinstance(it, Choice)
+ and getattr(it.value, "is_tcp", False))
+ return DeleteRequest(row.value)
+ return _QUIT
+
+ async def confirm_startup(self, prompt, *, title="", confirm_label="Remove",
+ banner=None, footnote=None):
+ return False # the user backs out (Cancel / Esc)
+
+ async def _never(_device, _pin=None):
+ raise AssertionError("verify should not run")
+
+ asyncio.run(prompt_device(_Ui(), [], store, _never))
+ # Nothing was forgotten — the device is still remembered.
+ remembered = store.load()
+ assert remembered is not None and remembered.node_name == "WifiNode"
+
+
class _PickerUi:
"""A fake splash UI that always selects the first device, then dismisses messages."""