MeshTerm drives an SPI radio itself, without the bridge service
A LoRa chip on the host's own SPI bus (the uConsole AIO) is now a transport like serial, BLE, and TCP: --spi, an SPI profile, or the picker's row for /dev/spidev1.0. MeshTerm starts a software node as a child process under whichever Python has openhop-core, talks to it over a loopback port, and ends it on disconnect; the node also exits with its parent, so the pins are free whenever MeshTerm is not running. The node keeps identity, prefs, channels, and contacts under ~/.meshterm/radio/<spidev>/, and on first use copies the bridge's identity, contacts, and radio settings so it stays the same node. Board wiring lives in a profile's spi table; radio settings are the node's own, edited on Device config. Closes #21. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
a93c331226
commit
9538bfedce
24 files changed
+2574
-166
No files matched your search
@@ -9,6 +9,26 @@ one caveat SemVer makes for a leading zero: while the major version is still `0`
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **MeshTerm drives the uConsole's LoRa radio itself, without the bridge service.** A radio
|
||||
on this machine's own SPI bus is now a connection like USB, Bluetooth, or TCP: pick
|
||||
**SPI radio** on the device screen, or run `meshterm --spi`. MeshTerm starts the node when
|
||||
it connects and ends it when it quits, so the radio's pins are free for other programs
|
||||
whenever MeshTerm is closed — even after a crash. The node keeps its identity, name,
|
||||
radio settings, channels, and contacts in `~/.meshterm/radio/`, and the first time it
|
||||
runs it takes over the bridge's identity and contacts, so it stays the node everyone
|
||||
already knows. It needs the radio library (`pipx inject mesh-term
|
||||
'openhop-core[hardware]'`); a board wired differently from the AIO v1 states its pins in
|
||||
a profile's `spi` table. The bridge is still there for a node that stays on the mesh
|
||||
while MeshTerm is closed. ([#21](https://github.com/jpmartineau/MeshTerm/issues/21))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The SPI bridge remembers its channels across restarts.** It kept them only in memory,
|
||||
so after every reboot the Channels page came up empty while mute settings, which
|
||||
MeshTerm keeps itself, survived. Update the service (menu option 2) to get the fix.
|
||||
|
||||
### Changed
|
||||
|
||||
- **MeshTerm now sends at most one automatic advert a week, and none unless you ask.** A
|
||||
|
||||
@@ -199,7 +199,7 @@ surveys kept as a historical record. The short version:
|
||||
| **[What MeshTerm does](docs/features.md)** | Every screen the menu offers, and the command that does the same job without it. |
|
||||
| [The CLI cookbook](docs/cookbook.md) | Common one-liners, by the thing you're trying to do. |
|
||||
| [Configuring MeshTerm](docs/configuration.md) | Preferences, device profiles, and everything kept under `~/.meshterm`. |
|
||||
| [MeshTerm on hardware](docs/hardware.md) | Which handheld manual is yours — the [PicoCalc](docs/picocalc.md) build, or the [uConsole](docs/uconsole.md) bridge. |
|
||||
| [MeshTerm on hardware](docs/hardware.md) | Which handheld manual is yours — the [PicoCalc](docs/picocalc.md) build, or the [uConsole](docs/uconsole.md), whose LoRa chip MeshTerm can drive directly. |
|
||||
| [How the code is laid out](docs/architecture.md) | The layering, and where a new feature goes. |
|
||||
| [CONTRIBUTING.md](CONTRIBUTING.md) | The development setup and the house rules. |
|
||||
| [CHANGELOG.md](CHANGELOG.md) | What changed, newest first. |
|
||||
@@ -229,8 +229,9 @@ meshterm specimen
|
||||
Putting MeshTerm on a handheld has its own manuals. **[MeshTerm on the
|
||||
PicoCalc](docs/picocalc.md)** takes a stock PicoCalc from the shopping list to a Linux
|
||||
handheld with a LoRa radio soldered inside; **[MeshTerm on the uConsole](docs/uconsole.md)**
|
||||
connects a uConsole's SPI LoRa board through a small bridge. The device-side scripts both
|
||||
manuals run are in [`scripts/`](scripts/); not sure which manual is yours?
|
||||
drives a uConsole's SPI LoRa board directly with `--spi`, or through a small bridge if you
|
||||
want the node on the mesh all the time. The device-side scripts both manuals run are in
|
||||
[`scripts/`](scripts/); not sure which manual is yours?
|
||||
[`docs/hardware.md`](docs/hardware.md) says.
|
||||
|
||||
## What it does
|
||||
|
||||
@@ -58,3 +58,10 @@ host = "192.168.1.50"
|
||||
# tcp_port = 5000
|
||||
# transport = "tcp"
|
||||
description = "Basestation over WiFi"
|
||||
|
||||
# A radio on this machine's own SPI bus (the uConsole AIO): MeshTerm runs its node.
|
||||
# The pins default to the AIO v1's; a `spi` table states only what differs.
|
||||
[profiles.aio]
|
||||
transport = "spi"
|
||||
# [profiles.aio.spi]
|
||||
# en_pins = [27] # the AIO v2 powers its radio from pin 27
|
||||
+1
-1
@@ -23,7 +23,7 @@ USB, Bluetooth or Wi-Fi needs none of this.
|
||||
| --- | --- |
|
||||
| **[MeshTerm on hardware](hardware.md)** | Start here — which of the two manuals below is yours, and what the device-side scripts do. |
|
||||
| [MeshTerm on the PicoCalc](picocalc.md) | A stock ClockworkPi PicoCalc to a Linux handheld with a LoRa radio soldered inside: the shopping list, the Lyra swap, Calculinux, and the radio. |
|
||||
| [MeshTerm on the uConsole](uconsole.md) | A uConsole with the hackergadgets AIO LoRa board, whose SX1262 sits on the host's own SPI bus, fronted as a companion by a small bridge. |
|
||||
| [MeshTerm on the uConsole](uconsole.md) | A uConsole with the hackergadgets AIO LoRa board, whose SX1262 sits on the host's own SPI bus — MeshTerm drives it directly with `--spi`, or a small bridge fronts it as a companion for an always-on node. |
|
||||
|
||||
## Reading the code
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ delete a line and the default takes over again.
|
||||
— 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.
|
||||
A LoRa radio on this machine's own SPI bus is listed on the picker when its device node
|
||||
exists, or reached with `--spi`; see [the uConsole manual](uconsole.md).
|
||||
Write a config file only to give your hardware stable aliases.
|
||||
|
||||
Copy [`config.example.toml`](../config.example.toml) to `~/.meshterm/config.toml`:
|
||||
@@ -46,6 +48,13 @@ description = "Pocket handheld over Bluetooth"
|
||||
[profiles.wifi]
|
||||
host = "192.168.1.50"
|
||||
description = "Basestation over WiFi"
|
||||
|
||||
# A radio on this machine's own SPI bus (the uConsole AIO): MeshTerm runs its node.
|
||||
# The pins default to the AIO v1's; a `spi` table states only what differs.
|
||||
[profiles.aio]
|
||||
transport = "spi"
|
||||
# [profiles.aio.spi]
|
||||
# en_pins = [27] # the AIO v2 powers its radio from pin 27
|
||||
```
|
||||
|
||||
Both live in `~/.meshterm`, along with everything else MeshTerm remembers: the SQLite
|
||||
|
||||
+5
-3
@@ -14,7 +14,7 @@ its own step-by-step manual, and this page only tells you which one is yours.
|
||||
| --- | --- |
|
||||
| a ClockworkPi **PicoCalc**, stock or already running Calculinux on a Luckfox Lyra, and I want MeshTerm on its own screen | **[MeshTerm on the PicoCalc](picocalc.md)** — from the shopping list to a working machine |
|
||||
| …and I want a **radio** inside it | the same manual, [Phase 3](picocalc.md#phase-3--add-the-radio) — a XIAO nRF52840 + Wio-SX1262 soldered to the Lyra's UART |
|
||||
| a ClockworkPi **uConsole** with the hackergadgets AIO board — an SX1262 on the host's own SPI bus | **[MeshTerm on the uConsole](uconsole.md)** — the bridge that fronts that chip as a companion |
|
||||
| a ClockworkPi **uConsole** with the hackergadgets AIO board — an SX1262 on the host's own SPI bus | **[MeshTerm on the uConsole](uconsole.md)** — MeshTerm drives it directly with `--spi`, or a bridge service fronts it as a companion if you want it always on |
|
||||
| a MeshCore companion on USB, BLE or Wi-Fi | nothing here — the [README](../README.md) |
|
||||
|
||||
The two targets have nothing in common but MeshTerm itself. The device-side scripts each
|
||||
@@ -28,7 +28,9 @@ script before you run it; most run as root and change the machine they run on.
|
||||
[`picocalc/`](../scripts/picocalc/) for the PicoCalc — bringing up Calculinux on the Lyra,
|
||||
building its console font, and (under [`xiao-radio/`](../scripts/picocalc/xiao-radio/))
|
||||
giving it a MeshCore radio over UART — and [`uconsole/`](../scripts/uconsole/) for the
|
||||
bridge that fronts the uConsole's SPI-attached LoRa chip as a companion. The manual is the
|
||||
always-on bridge that fronts the uConsole's SPI-attached LoRa chip as a companion (MeshTerm
|
||||
can also drive that chip directly, with no script at all — the uConsole manual covers
|
||||
both). The manual is the
|
||||
walkthrough; each script's own header says what it assumes about the machine and why each
|
||||
step is the way it is. On the Lyra, only one program may hold `/dev/ttyS1` — MeshTerm
|
||||
directly, or a pump in front of it, never both.
|
||||
@@ -46,7 +48,7 @@ directly, or a pump in front of it, never both.
|
||||
| [`xiao-radio/meshcore-uart1.patch`](../scripts/picocalc/xiao-radio/meshcore-uart1.patch) | — | The two firmware hunks: the companion on nRF52 `Serial1`, and I²C moved off the UART pads. Not upstream yet. |
|
||||
| [`xiao-radio/lyra-setup.sh`](../scripts/picocalc/xiao-radio/lyra-setup.sh) | the Lyra (root) | Boot-persistent UART1 → GP4/GP5 mux service, `dialout` membership, and a default MeshTerm serial profile for `/dev/ttyS1`. |
|
||||
| [`xiao-radio/uart1-mux.py`](../scripts/picocalc/xiao-radio/uart1-mux.py) | the Lyra (root) | The matrix-IO register poke that routes UART1 to the header pads, run once per boot by the service above. |
|
||||
| [`uconsole/meshterm-spi-bridge`](../scripts/uconsole/meshterm-spi-bridge) | the radio host (your user) | Runs a mesh node in software over an SPI-attached SX1262 (uConsole AIO, Waveshare HATs) and serves the companion protocol on `127.0.0.1:5000`. Setup menu, preflight, optional `systemd --user` service. Runs on `openhop_core` (preferred) or its predecessor `pymc_core`; see the manual for the venv it wants on a bookworm uConsole. |
|
||||
| [`uconsole/meshterm-spi-bridge`](../scripts/uconsole/meshterm-spi-bridge) | the radio host (your user) | The **always-on** option: runs a mesh node in software over an SPI-attached SX1262 (uConsole AIO, Waveshare HATs) and serves the companion protocol on `127.0.0.1:5000`, so the node stays on the mesh while MeshTerm is closed. Setup menu, preflight, optional `systemd --user` service. Runs on `openhop_core` (preferred) or its predecessor `pymc_core`; see the manual for the venv it wants on a bookworm uConsole. Most people should reach for `meshterm --spi` instead — no script, no service, MeshTerm drives the chip itself while it runs. |
|
||||
|
||||
## The regular and picocalc platforms
|
||||
|
||||
|
||||
+310
-137
@@ -2,22 +2,25 @@
|
||||
|
||||
A ClockworkPi uConsole with the hackergadgets AIO LoRa board has no companion
|
||||
microcontroller and no firmware to flash — the LoRa chip sits straight on the host's SPI
|
||||
bus. So a small bridge runs the mesh node in software on the uConsole itself and puts the
|
||||
standard MeshCore companion protocol in front of it on a local TCP port. MeshTerm then
|
||||
connects to that port like it would any network companion. By the end of this guide you'll
|
||||
have the bridge running as a background service and MeshTerm talking to it.
|
||||
bus. MeshTerm can drive it directly: it starts a mesh node as a child process the moment
|
||||
you connect, talks to it over the standard companion protocol on a loopback port, and ends
|
||||
it when you disconnect or quit. No separate service, no TCP port to remember — just
|
||||
`meshterm --spi`.
|
||||
|
||||
> ⚠ **Read this first.** This guide edits your uConsole's boot configuration, adds your
|
||||
> user to hardware groups, installs a service under your account, and then keys a LoRa
|
||||
> transmitter. It assumes you are comfortable at a Linux shell and know which frequency
|
||||
> plan and power limits apply where you live — what the radio does on air is your
|
||||
> responsibility, not the bridge's. There is a real risk of leaving the system, the radio
|
||||
> or the mesh around you in a worse state if a step goes wrong. You do this at your own
|
||||
> risk.
|
||||
If you'd rather the node stayed on the mesh while MeshTerm is closed, a small bridge can
|
||||
run it as a background service instead, fronting the same chip as a network companion.
|
||||
That's [further down](#always-on-the-bridge) — most people want the section above it.
|
||||
|
||||
> ⚠ **Read this first.** Either route edits your uConsole's boot configuration, adds your
|
||||
> user to hardware groups, and then keys a LoRa transmitter. It assumes you are comfortable
|
||||
> at a Linux shell and know which frequency plan and power limits apply where you live —
|
||||
> what the radio does on air is your responsibility, not MeshTerm's. There is a real risk
|
||||
> of leaving the system, the radio or the mesh around you in a worse state if a step goes
|
||||
> wrong. You do this at your own risk.
|
||||
>
|
||||
> **Read the whole manual through once before you start.** Which route you take in
|
||||
> Step 2 depends on your Debian release, and whether the GUI is running changes what the
|
||||
> preflight and the service will do — both are easier to get right knowing the later steps.
|
||||
> **Read the whole manual through once before you start.** Which install route you take
|
||||
> depends on how you're running MeshTerm, and that's easier to get right knowing the later
|
||||
> steps.
|
||||
>
|
||||
> This is a guide, not a prescription. Despite the author's best efforts it may contain
|
||||
> errors, and parts of it will go out of date as packages, runtimes and boards change. It
|
||||
@@ -27,15 +30,13 @@ have the bridge running as a background service and MeshTerm talking to it.
|
||||
|
||||
- [What you need](#what-you-need)
|
||||
- [Step 1 — Prepare the system](#step-1--prepare-the-system)
|
||||
- [Step 2 — Install the radio runtime](#step-2--install-the-radio-runtime)
|
||||
- [Step 3 — Get the bridge](#step-3--get-the-bridge)
|
||||
- [Step 4 — Run the preflight](#step-4--run-the-preflight)
|
||||
- [Step 5 — Run it once in the foreground](#step-5--run-it-once-in-the-foreground)
|
||||
- [Step 6 — Install it as a service](#step-6--install-it-as-a-service)
|
||||
- [Step 7 — Install MeshTerm and connect](#step-7--install-meshterm-and-connect)
|
||||
- [Updating and uninstalling](#updating-and-uninstalling)
|
||||
- [Hardware knobs](#hardware-knobs)
|
||||
- [Step 2 — Install the radio library](#step-2--install-the-radio-library)
|
||||
- [Step 3 — Install MeshTerm](#step-3--install-meshterm)
|
||||
- [Step 4 — Connect](#step-4--connect)
|
||||
- [Moving over from the bridge](#moving-over-from-the-bridge)
|
||||
- [Board wiring](#board-wiring)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Always on: the bridge](#always-on-the-bridge)
|
||||
- [What this has been tested on](#what-this-has-been-tested-on)
|
||||
|
||||
---
|
||||
@@ -47,67 +48,31 @@ have the bridge running as a background service and MeshTerm talking to it.
|
||||
| Part | Notes |
|
||||
| --- | --- |
|
||||
| ClockworkPi **uConsole** (CM4 module) | Any uConsole with a Compute Module 4. |
|
||||
| hackergadgets **AIO** expansion board | The board this guide is written for and the one we recommend: an SX1262 on SPI bus 1, plus GPS, an RTL-SDR and a USB hub you don't need here. The bridge's defaults are its wiring. |
|
||||
| hackergadgets **AIO** expansion board | The board this guide is written for and the one we recommend: an SX1262 on SPI bus 1, plus GPS, an RTL-SDR and a USB hub you don't need here. MeshTerm's SPI defaults are its wiring (AIO v1; the v2 needs one extra setting — see [Board wiring](#board-wiring)). |
|
||||
| An antenna for your region's LoRa band | Required. |
|
||||
|
||||
Installing the AIO board into the uConsole is out of scope here — follow
|
||||
[hackergadgets' own setup guide](https://hackergadgets.com/pages/hackergadgets-uconsole-rtl-sdr-lora-gps-rtc-usb-hub-all-in-one-extension-board-setup-guide)
|
||||
for that part.
|
||||
|
||||
The bridge assumes the AIO's wiring by default:
|
||||
|
||||
| Setting | Default |
|
||||
| --- | --- |
|
||||
| SPI bus | 1 |
|
||||
| Reset pin | 25 |
|
||||
| Busy pin | 24 |
|
||||
| IRQ pin | 26 |
|
||||
| TX-enable pin | none |
|
||||
| DIO2 (RF switch) | on |
|
||||
| DIO3 (TCXO) | on |
|
||||
| Frequency | 910.525 MHz |
|
||||
| TX power | 22 dBm |
|
||||
| Spreading factor | 7 |
|
||||
| Bandwidth | 62.5 kHz |
|
||||
| Coding rate | 4/5 |
|
||||
|
||||
The radio settings (frequency, spreading factor, bandwidth, coding rate) are MeshCore's
|
||||
US/Canada preset. Anywhere else, set the `MESHCORE_*` variables to your region's preset.
|
||||
Every one of these is overridable with a `MESHCORE_*` environment variable if your board or
|
||||
region differs — see [Hardware knobs](#hardware-knobs).
|
||||
|
||||
**Software:**
|
||||
|
||||
- Raspberry Pi OS / Debian **bookworm** or **trixie** on the uConsole, 64-bit.
|
||||
- Python 3 (the system one is fine — the bridge finds whichever interpreter has the radio
|
||||
library, and re-execs itself under it).
|
||||
- Raspberry Pi OS / Debian **bookworm** or **trixie** on the uConsole, 64-bit. This is
|
||||
Linux-only — driving a radio on the host's own SPI bus is not something Windows or macOS
|
||||
can do.
|
||||
- A `/dev/spidev*` node. This needs `dtoverlay=spi1-1cs` in `/boot/firmware/config.txt`.
|
||||
- `/dev/gpiochip0`, and membership of the `spi` and `gpio` groups so you can read and write
|
||||
both without root.
|
||||
- Optionally, the [`meshcore-uconsole`](https://github.com/cwill747/meshcore-uconsole)
|
||||
package (it brings the `meshcore-console` GUI and a radio runtime). Whether you can use it depends on your Debian release — see
|
||||
[Step 2](#step-2--install-the-radio-runtime).
|
||||
- The radio library, **`openhop-core[hardware]` 1.1.3 or newer** — [Step
|
||||
2](#step-2--install-the-radio-library) gets you there. It doesn't have to be in
|
||||
MeshTerm's own Python; MeshTerm looks in several places for it.
|
||||
- MeshTerm itself, on the uConsole — [Step 3](#step-3--install-meshterm).
|
||||
|
||||
The radio library that actually drives the chip was renamed in 2026: `pymc_core` became
|
||||
`openhop_core`. PyPI's `pymc-core` stopped at 1.0.12; `openhop-core` carries on from 1.1.x.
|
||||
The bridge supports both and prefers the newer one when it finds both installed.
|
||||
|
||||
**MeshTerm itself** — either:
|
||||
|
||||
- the Linux ARM64 one-file release — three lines, no Python at all:
|
||||
|
||||
```bash
|
||||
curl -fL -o meshterm https://github.com/jpmartineau/MeshTerm/releases/latest/download/meshterm-linux-arm64
|
||||
chmod +x meshterm
|
||||
./meshterm
|
||||
```
|
||||
|
||||
(That URL always fetches whichever release is newest; the
|
||||
[release page](https://github.com/jpmartineau/MeshTerm/releases/latest) has the
|
||||
version-stamped files and their checksums.) Or:
|
||||
- an install from the repository with `pipx` (Python 3.10 or newer). Plain `pip install`
|
||||
into the system Python is refused on bookworm and trixie; `pipx` (`sudo apt install pipx`)
|
||||
gives MeshTerm a virtual environment of its own.
|
||||
A node's own radio settings — frequency, bandwidth, spreading factor, coding rate, TX
|
||||
power — are not part of this setup. They're the node's, saved by the node, and you change
|
||||
them the same way you would on any companion: MeshTerm's Device config page. A brand-new
|
||||
node starts on MeshCore's US/Canada preset (910.525 MHz, 62.5 kHz, SF 7, CR 4/5, 22 dBm)
|
||||
until you change it.
|
||||
|
||||
---
|
||||
|
||||
@@ -143,12 +108,237 @@ and `spi` and `gpio` in your `groups` output.
|
||||
|
||||
---
|
||||
|
||||
## Step 2 — Install the radio runtime
|
||||
## Step 2 — Install the radio library
|
||||
|
||||
MeshTerm needs `openhop-core[hardware]` 1.1.3 or newer importable by *some* Python on the
|
||||
machine — not necessarily MeshTerm's own. It looks, in order: a `python` named in the
|
||||
profile's `spi` table; MeshTerm's own interpreter; the bridge's venv at
|
||||
`~/.local/share/meshterm-spi-bridge/venv/bin/python`; `/opt/venvs/meshcore-uconsole/bin/python`;
|
||||
then `python3` on your `PATH`. Whichever route you take below, that's the interpreter it
|
||||
lands in.
|
||||
|
||||
- **Installed MeshTerm with `pipx`?** Inject it into MeshTerm's own environment:
|
||||
|
||||
```bash
|
||||
pipx inject mesh-term 'openhop-core[hardware]'
|
||||
```
|
||||
|
||||
- **Installed with `pip`?** Pull in the `spi` extra when you install MeshTerm (see
|
||||
[Step 3](#step-3--install-meshterm)):
|
||||
|
||||
```bash
|
||||
pip install 'mesh-term[spi]'
|
||||
```
|
||||
|
||||
- **Running the one-file Linux ARM64 build?** It's a single frozen binary and can't carry
|
||||
the library, so give it a venv of its own — the same one the bridge guide uses, so it's
|
||||
shared if you ever run both:
|
||||
|
||||
```bash
|
||||
python3 -m venv ~/.local/share/meshterm-spi-bridge/venv
|
||||
~/.local/share/meshterm-spi-bridge/venv/bin/pip install "openhop-core[hardware]"
|
||||
```
|
||||
|
||||
MeshTerm finds it there automatically; no configuration needed.
|
||||
|
||||
The older `pymc_core` runtime (the library's name before 2026) is not supported for a
|
||||
direct connection — only the standalone bridge still carries the compatibility shims it
|
||||
needs.
|
||||
|
||||
---
|
||||
|
||||
## Step 3 — Install MeshTerm
|
||||
|
||||
Same as any other machine — the simplest way is the Linux ARM64 one-file release:
|
||||
|
||||
```bash
|
||||
curl -fL -o meshterm https://github.com/jpmartineau/MeshTerm/releases/latest/download/meshterm-linux-arm64
|
||||
chmod +x meshterm
|
||||
sudo mv meshterm /usr/local/bin/meshterm
|
||||
```
|
||||
|
||||
Or install it from the repository with `pipx`:
|
||||
|
||||
```bash
|
||||
sudo apt install pipx
|
||||
pipx install git+https://github.com/jpmartineau/MeshTerm
|
||||
pipx ensurepath
|
||||
pipx inject mesh-term 'openhop-core[hardware]'
|
||||
```
|
||||
|
||||
Or with `pip`, pulling in the radio library as its own extra in one line:
|
||||
|
||||
```bash
|
||||
pip install 'mesh-term[spi]'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Connect
|
||||
|
||||
```bash
|
||||
meshterm --spi
|
||||
```
|
||||
|
||||
`--spi` finds the AIO's radio at `/dev/spidev1.0` and starts a node on it. The startup
|
||||
device picker also lists it — a row reading **SPI radio (/dev/spidev1.0)** with a 📍 icon —
|
||||
whenever that device node exists, so `meshterm` with no flags gets you there too.
|
||||
|
||||
You're connected when **Device info** or the dashboard shows a node name instead of a
|
||||
connection error. MeshTerm reports the device model as **MeshTerm SPI node**, and the
|
||||
header's connection label reads **SPI**.
|
||||
|
||||
**What happens underneath.** MeshTerm starts the node when it connects and ends it when
|
||||
you disconnect or quit — including a crash: the node exits with MeshTerm, and the kernel
|
||||
frees the GPIO lines and SPI handle the moment its process does. The trade-off is the one
|
||||
this implies: **the node is off the mesh while MeshTerm is closed.** If you want it on all
|
||||
the time, that's what [the bridge](#always-on-the-bridge) is for.
|
||||
|
||||
**Where its state lives.** Each radio keeps its identity, preferences, channels and
|
||||
contacts under `~/.meshterm/radio/spidev1.0/` — `identity.key`, `prefs.json`,
|
||||
`channels.json`, `contacts.json` — plus a running log, `node.log` (the previous run's is
|
||||
kept as `node.log.1`). All of it survives a restart.
|
||||
|
||||
**A profile, if you want a name for it:**
|
||||
|
||||
```toml
|
||||
[profiles.aio]
|
||||
transport = "spi"
|
||||
```
|
||||
|
||||
```bash
|
||||
meshterm -p aio
|
||||
```
|
||||
|
||||
The AIO's wiring is the default, so this profile needs nothing beyond `transport = "spi"`.
|
||||
[Board wiring](#board-wiring) is for when yours differs.
|
||||
|
||||
---
|
||||
|
||||
## Moving over from the bridge
|
||||
|
||||
Already running the bridge? The first time you connect with `--spi` (or a profile, or the
|
||||
picker row), MeshTerm carries the bridge's node over — **copying**, never moving, so the
|
||||
bridge still works afterwards if you go back to it:
|
||||
|
||||
- the identity key — from the `meshcore-console` GUI's copy first
|
||||
(`~/.local/share/meshcore-uconsole/identity.key`), the way the bridge itself looks for
|
||||
it, else the bridge's own (`~/.local/share/meshterm-spi-bridge/identity.key`);
|
||||
- the bridge's `contacts.json`;
|
||||
- the name `uConsole`;
|
||||
- the bridge's radio settings — frequency, bandwidth, spreading factor, coding rate, TX
|
||||
power — read out of the bridge service's `MESHCORE_*` environment.
|
||||
|
||||
This only happens once, while `~/.meshterm/radio/spidev1.0/` has no `identity.key` yet — so
|
||||
your node keeps its public key, and with it its place in everyone else's contact list.
|
||||
|
||||
**Wiring is not carried over.** If your board needed `MESHCORE_EN_PINS` or another wiring
|
||||
variable for the bridge, put the equivalent in the profile's `spi` table (see
|
||||
[Board wiring](#board-wiring)) — the direct connection reads wiring from there, never from
|
||||
the bridge's environment.
|
||||
|
||||
**Stop the bridge before switching over**, since only one program may hold the radio at a
|
||||
time:
|
||||
|
||||
```bash
|
||||
systemctl --user stop meshterm-spi-bridge
|
||||
systemctl --user disable meshterm-spi-bridge # keep it stopped across reboots
|
||||
```
|
||||
|
||||
If MeshTerm sees the bridge service running, it refuses to start the node and tells you the
|
||||
same two commands.
|
||||
|
||||
---
|
||||
|
||||
## Board wiring
|
||||
|
||||
The defaults match the hackergadgets uConsole AIO **v1**, which needs no `spi` table at
|
||||
all. State only what differs, under `[profiles.<name>.spi]`:
|
||||
|
||||
```toml
|
||||
[profiles.aio2]
|
||||
transport = "spi"
|
||||
|
||||
[profiles.aio2.spi]
|
||||
en_pins = [27] # the AIO v2 needs this
|
||||
```
|
||||
|
||||
| Setting | Default | What it is |
|
||||
| --- | --- | --- |
|
||||
| `bus_id`, `cs_id` | `1`, `0` | Which SPI bus and chip-select the radio is on (`/dev/spidev<bus_id>.<cs_id>`). |
|
||||
| `cs_pin` | `-1` | A GPIO driven as chip select by hand, instead of the bus's own. |
|
||||
| `gpio_chip` | `0` | Which `/dev/gpiochip<n>` the pins below are on. |
|
||||
| `use_gpiod_backend` | `false` | Drive the pins through `gpiod` instead of `python-periphery`. |
|
||||
| `reset_pin`, `busy_pin`, `irq_pin` | `25`, `24`, `26` | The chip's reset, busy and interrupt (DIO1) lines. |
|
||||
| `txen_pin`, `rxen_pin` | `-1`, `-1` | An external RF switch's transmit/receive-enable lines, if the board has one. |
|
||||
| `en_pins` | `[]` | Power-enable lines to raise before the chip is touched. The **AIO v2 needs `[27]`.** |
|
||||
| `use_dio2_rf`, `use_dio3_tcxo` | `true`, `true` | Whether DIO2 drives the RF switch and DIO3 a TCXO (both on for the AIO). |
|
||||
| `is_waveshare` | `false` | The Waveshare HAT's wiring quirks, which the radio library knows about. |
|
||||
| `preamble_length` | `12` | LoRa preamble symbols. |
|
||||
| `python` | `""` (empty) | An interpreter to run the node under, when the one MeshTerm would find on its own isn't the one you want. Empty lets MeshTerm look. |
|
||||
|
||||
An unknown key, or one of the wrong type, stops MeshTerm at startup with the profile
|
||||
named — a misspelt pin is never silently ignored.
|
||||
|
||||
Radio settings — frequency, bandwidth, spreading factor, coding rate, TX power — are
|
||||
**not** in this table. They're the node's own, on Device config, as noted in
|
||||
[What you need](#what-you-need).
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Fix |
|
||||
| --- | --- |
|
||||
| The radio library isn't found | Follow [Step 2](#step-2--install-the-radio-library) for however you installed MeshTerm, or set `python` in the profile's `spi` table to an interpreter that has `openhop-core[hardware]`. |
|
||||
| No `/dev/spidev1.0` | Add `dtoverlay=spi1-1cs` to `/boot/firmware/config.txt` and reboot. |
|
||||
| Permission denied opening the SPI or GPIO device | `sudo usermod -aG spi,gpio $USER`, then log out and back in. |
|
||||
| "the meshterm-spi-bridge service has the radio" | Stop it: `systemctl --user stop meshterm-spi-bridge` (and `disable` it to keep it stopped). |
|
||||
| "meshcore-console has the radio open" | Close the GUI and connect again. |
|
||||
| Some other program has the radio | `sudo lsof /dev/gpiochip0` shows which; only one program may hold the radio at a time. |
|
||||
| The node starts but never answers | Check its log: `~/.meshterm/radio/spidev1.0/node.log`. |
|
||||
| An AIO v2 radio never comes up | It needs `en_pins = [27]` in the profile's `spi` table — see [Board wiring](#board-wiring). |
|
||||
|
||||
---
|
||||
|
||||
## Always on: the bridge
|
||||
|
||||
Most people should use the direct connection above. Use the bridge instead if you want the
|
||||
node reachable on the mesh **while MeshTerm is closed** — it runs as a `systemd --user`
|
||||
service, on its own, independent of whether MeshTerm is even installed. The trade-off runs
|
||||
the other way from the direct connection: once the bridge is running, it holds the radio's
|
||||
pins for good, so no other LoRa program — including a direct `meshterm --spi` — can use
|
||||
them until you stop it.
|
||||
|
||||
The bridge puts the standard MeshCore companion protocol in front of the same SPI-attached
|
||||
chip, on a local TCP port. MeshTerm then connects to that port like it would any network
|
||||
companion.
|
||||
|
||||
- [Bridge step 1 — Install the radio runtime](#bridge-step-1--install-the-radio-runtime)
|
||||
- [Bridge step 2 — Get the bridge](#bridge-step-2--get-the-bridge)
|
||||
- [Bridge step 3 — Run the preflight](#bridge-step-3--run-the-preflight)
|
||||
- [Bridge step 4 — Run it once in the foreground](#bridge-step-4--run-it-once-in-the-foreground)
|
||||
- [Bridge step 5 — Install it as a service](#bridge-step-5--install-it-as-a-service)
|
||||
- [Bridge step 6 — Connect MeshTerm to it](#bridge-step-6--connect-meshterm-to-it)
|
||||
- [Updating and uninstalling the bridge](#updating-and-uninstalling-the-bridge)
|
||||
- [Bridge hardware knobs](#bridge-hardware-knobs)
|
||||
- [Bridge troubleshooting](#bridge-troubleshooting)
|
||||
|
||||
The bridge's own wiring and radio defaults are the same AIO v1 numbers as the direct
|
||||
connection's — see the table in [Board wiring](#board-wiring) — just set through
|
||||
`MESHCORE_*` environment variables instead of a profile's `spi` table.
|
||||
|
||||
The radio library that actually drives the chip was renamed in 2026: `pymc_core` became
|
||||
`openhop_core`. PyPI's `pymc-core` stopped at 1.0.12; `openhop-core` carries on from 1.1.x.
|
||||
The bridge supports both and prefers the newer one when it finds both installed.
|
||||
|
||||
### Bridge step 1 — Install the radio runtime
|
||||
|
||||
Which route you take depends on your Debian release:
|
||||
|
||||
- **trixie**, with the `meshcore-uconsole` package (by cwill747) installed: you already
|
||||
have a working runtime (Python 3.13-based). Skip to [Step 3](#step-3--get-the-bridge).
|
||||
have a working runtime (Python 3.13-based). Skip to
|
||||
[step 2](#bridge-step-2--get-the-bridge).
|
||||
- **bookworm**: the trixie `.deb` of `meshcore-uconsole` 1.12.0 is built on Python 3.13
|
||||
and needs glibc 2.38, so it will not install on bookworm, and the APT repository offers
|
||||
nothing for bookworm. Upstream's GitHub Releases also carry a separate bookworm `.deb`
|
||||
@@ -163,12 +353,11 @@ Which route you take depends on your Debian release:
|
||||
This is also the route to take if you'd rather not install the `meshcore-uconsole` package
|
||||
at all.
|
||||
|
||||
You'll confirm which runtime the bridge actually found in [Step 4](#step-4--run-the-preflight) —
|
||||
its first check line names the interpreter and the runtime.
|
||||
You'll confirm which runtime the bridge actually found in
|
||||
[step 3](#bridge-step-3--run-the-preflight) — its first check line names the interpreter
|
||||
and the runtime.
|
||||
|
||||
---
|
||||
|
||||
## Step 3 — Get the bridge
|
||||
### Bridge step 2 — Get the bridge
|
||||
|
||||
`scripts/uconsole/meshterm-spi-bridge` is a single, self-contained Python file — no install step of
|
||||
its own. Either clone the MeshTerm repo:
|
||||
@@ -191,9 +380,7 @@ Make it executable:
|
||||
chmod +x meshterm-spi-bridge
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Run the preflight
|
||||
### Bridge step 3 — Run the preflight
|
||||
|
||||
```bash
|
||||
./meshterm-spi-bridge --check
|
||||
@@ -204,16 +391,14 @@ what to do if it fails:
|
||||
|
||||
| Check | Meaning if it fails | Fix |
|
||||
| --- | --- | --- |
|
||||
| `node runtime` | Neither `openhop_core` nor `pymc_core` is importable by any interpreter the bridge tried. | Build the venv from [Step 2](#step-2--install-the-radio-runtime), or set `MESHTERM_PYMC_PYTHON` to a python that has one. |
|
||||
| `node runtime` | Neither `openhop_core` nor `pymc_core` is importable by any interpreter the bridge tried. | Build the venv from [step 1](#bridge-step-1--install-the-radio-runtime), or set `MESHTERM_PYMC_PYTHON` to a python that has one. |
|
||||
| `SPI device` | No `/dev/spidev*` node exists, or it exists but you can't read/write it. | No node at all: add `dtoverlay=spi1-1cs` to `/boot/firmware/config.txt` and reboot. Node present but no permission: `sudo usermod -aG spi $USER`, then log out and back in. |
|
||||
| `GPIO chip` | `/dev/gpiochip0` is missing or not read/write for you. | `sudo usermod -aG gpio $USER`, then log out and back in. |
|
||||
| `bridge service` / `radio in use` / `port 5000 busy` / `radio is free` | Tells you whether something already holds the radio: the bridge's own boot service, a running `meshcore-console`, or something else already listening on the TCP port. | Only one program may use the radio at a time — see [Step 7](#step-7--install-meshterm-and-connect). If `meshcore-console` is running, close it before running the bridge. |
|
||||
| `bridge service` / `radio in use` / `port 5000 busy` / `radio is free` | Tells you whether something already holds the radio: the bridge's own boot service, a running `meshcore-console`, or something else already listening on the TCP port. | Only one program may use the radio at a time — see [step 6](#bridge-step-6--connect-meshterm-to-it). If `meshcore-console` is running, close it before running the bridge. |
|
||||
|
||||
If the first three checks all pass, you're ready to run it.
|
||||
|
||||
---
|
||||
|
||||
## Step 5 — Run it once in the foreground
|
||||
### Bridge step 4 — Run it once in the foreground
|
||||
|
||||
```bash
|
||||
./meshterm-spi-bridge --run
|
||||
@@ -222,7 +407,7 @@ If the first three checks all pass, you're ready to run it.
|
||||
This runs the preflight again and prints it. Before it starts the bridge, it asks whether
|
||||
to add a `bridge` profile to your MeshTerm config
|
||||
(`` Add a 'bridge' profile to /home/you/.meshterm/config.toml so you can just run `meshterm`? [y/N] ``).
|
||||
Either answer is fine; Step 6 asks again if you say no. Then it starts the bridge in this
|
||||
Either answer is fine; step 5 asks again if you say no. Then it starts the bridge in this
|
||||
terminal. A healthy startup logs something like:
|
||||
|
||||
```
|
||||
@@ -237,8 +422,8 @@ READY — connect with: meshterm --tcp 127.0.0.1:5000
|
||||
The `radio config` line lists every setting as `key=value`, so the one above is
|
||||
shortened; yours is longer.
|
||||
|
||||
Once MeshTerm is installed ([Step 7](#step-7--install-meshterm-and-connect)), you can test
|
||||
the bridge this way: leave it running, and in another terminal on the same machine run:
|
||||
You can test the bridge this way: leave it running, and in another terminal on the same
|
||||
machine run:
|
||||
|
||||
```bash
|
||||
meshterm --tcp 127.0.0.1:5000
|
||||
@@ -246,9 +431,7 @@ meshterm --tcp 127.0.0.1:5000
|
||||
|
||||
Back in the bridge's terminal, press **Ctrl+C** to stop it.
|
||||
|
||||
---
|
||||
|
||||
## Step 6 — Install it as a service
|
||||
### Bridge step 5 — Install it as a service
|
||||
|
||||
Run the bridge with no flags to get the interactive menu:
|
||||
|
||||
@@ -271,7 +454,7 @@ sudo loginctl enable-linger $USER
|
||||
```
|
||||
|
||||
It also offers to add a `[profiles.bridge]` block to your MeshTerm `config.toml` — say yes,
|
||||
it's the profile you'll use in [Step 7](#step-7--install-meshterm-and-connect).
|
||||
it's the profile you'll use next.
|
||||
|
||||
Check on it any time:
|
||||
|
||||
@@ -282,27 +465,13 @@ journalctl --user -u meshterm-spi-bridge.service -f
|
||||
|
||||
Menu option **4) Show status** prints the same information from inside the script.
|
||||
|
||||
---
|
||||
### Bridge step 6 — Connect MeshTerm to it
|
||||
|
||||
## Step 7 — Install MeshTerm and connect
|
||||
Install MeshTerm on the uConsole the same way as [Step 3](#step-3--install-meshterm)
|
||||
above — the bridge doesn't need the `spi` extra or `openhop-core[hardware]` in MeshTerm's
|
||||
own Python, since the bridge is the one running the node.
|
||||
|
||||
Install MeshTerm on the uConsole. The simplest way is the Linux ARM64 one-file release:
|
||||
|
||||
```bash
|
||||
curl -fL -o meshterm https://github.com/jpmartineau/MeshTerm/releases/latest/download/meshterm-linux-arm64
|
||||
chmod +x meshterm
|
||||
sudo mv meshterm /usr/local/bin/meshterm
|
||||
```
|
||||
|
||||
Or install it from the repository with `pipx`:
|
||||
|
||||
```bash
|
||||
sudo apt install pipx
|
||||
pipx install git+https://github.com/jpmartineau/MeshTerm
|
||||
pipx ensurepath
|
||||
```
|
||||
|
||||
If you accepted the profile in Step 5 or 6, `~/.meshterm/config.toml` now has this block
|
||||
If you accepted the profile in step 4 or 5, `~/.meshterm/config.toml` now has this block
|
||||
(the bridge always writes to that path, even if you set `MESHTERM_HOME`):
|
||||
|
||||
```toml
|
||||
@@ -326,23 +495,24 @@ meshterm --tcp 127.0.0.1:5000
|
||||
|
||||
You're connected when **Device info** or the dashboard shows a node name (`uConsole` by
|
||||
default) instead of a connection error. MeshTerm reports the device model as
|
||||
`pyMC-spi-bridge` — that's how you tell a bridged node from a real companion.
|
||||
`pyMC-spi-bridge` — that's how you tell a bridged node from a real companion or a direct
|
||||
SPI connection.
|
||||
|
||||
**Identity.** If the `meshcore-console` GUI's package is present, the bridge loads *that*
|
||||
package's identity key, so MeshTerm and the GUI share the same public key. Contacts and
|
||||
radio settings are the bridge's own: it keeps contacts in
|
||||
`~/.local/share/meshterm-spi-bridge/contacts.json`, and builds its radio settings from the
|
||||
`MESHCORE_*` variables and its defaults, never from the GUI's saved settings. Set the
|
||||
`MESHCORE_*` variables to match what the GUI uses. On a library-only install, the bridge mints and keeps its own identity key
|
||||
under `~/.local/share/meshterm-spi-bridge/identity.key`.
|
||||
`~/.local/share/meshterm-spi-bridge/contacts.json`, its channels in
|
||||
`~/.local/share/meshterm-spi-bridge/channels.json` (both survive a restart), and builds its
|
||||
radio settings from the `MESHCORE_*` variables and its defaults, never from the GUI's saved
|
||||
settings. Set the `MESHCORE_*` variables to match what the GUI uses. On a library-only
|
||||
install, the bridge mints and keeps its own identity key under
|
||||
`~/.local/share/meshterm-spi-bridge/identity.key`.
|
||||
|
||||
**Only one program may use the radio at a time.** Never run the bridge and the
|
||||
`meshcore-console` GUI at the same time — whichever started second will fail to open the
|
||||
radio.
|
||||
radio. The same goes for a direct `meshterm --spi` connection while the bridge is running.
|
||||
|
||||
---
|
||||
|
||||
## Updating and uninstalling
|
||||
### Updating and uninstalling the bridge
|
||||
|
||||
To update, pull or re-download `meshterm-spi-bridge` and reinstall the service (menu option
|
||||
2 again — it overwrites the copy in `~/.local/bin/`). The running service keeps the old
|
||||
@@ -353,17 +523,16 @@ systemctl --user restart meshterm-spi-bridge.service
|
||||
```
|
||||
|
||||
Option 2 also rewrites the unit file, so any `Environment=` lines you added to it by hand
|
||||
are lost. Put them in a drop-in instead, as [Hardware knobs](#hardware-knobs) shows.
|
||||
are lost. Put them in a drop-in instead, as [Bridge hardware knobs](#bridge-hardware-knobs)
|
||||
shows.
|
||||
|
||||
To remove the bridge, run the menu and choose **3) Uninstall the service**. This stops and
|
||||
removes the `systemd --user` unit and the installed script copy. It does **not** touch
|
||||
`meshcore-console`, the radio library, your node identity, or your saved contacts — those
|
||||
stay put. If you'd added `[profiles.bridge]` to your MeshTerm config, it tells you to remove
|
||||
that block by hand if you no longer want it.
|
||||
`meshcore-console`, the radio library, your node identity, or your saved contacts and
|
||||
channels — those stay put. If you'd added `[profiles.bridge]` to your MeshTerm config, it
|
||||
tells you to remove that block by hand if you no longer want it.
|
||||
|
||||
---
|
||||
|
||||
## Hardware knobs
|
||||
### Bridge hardware knobs
|
||||
|
||||
The pin defaults match the hackergadgets uConsole AIO v1, which needs none of these. The
|
||||
**AIO v2 needs `MESHCORE_EN_PINS=27`**, whether or not the `meshcore-console` package is
|
||||
@@ -403,13 +572,11 @@ that package's documentation) and ignores the GUI's saved presets. On a library-
|
||||
install the table above is the whole of it. Either way, an AIO v2 without
|
||||
`MESHCORE_EN_PINS=27` will not power its radio.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
### Bridge troubleshooting
|
||||
|
||||
| Symptom | Check |
|
||||
| --- | --- |
|
||||
| `node runtime` fails in the preflight | Did you build the venv in [Step 2](#step-2--install-the-radio-runtime)? Is `MESHTERM_PYMC_PYTHON` pointing at the right interpreter, if set? |
|
||||
| `node runtime` fails in the preflight | Did you build the venv in [step 1](#bridge-step-1--install-the-radio-runtime)? Is `MESHTERM_PYMC_PYTHON` pointing at the right interpreter, if set? |
|
||||
| `SPI device` shows "no /dev/spidev* found" | Is `dtoverlay=spi1-1cs` in `/boot/firmware/config.txt`? Did you reboot after adding it? |
|
||||
| `SPI device` or `GPIO chip` shows a permission error | Are you in the `spi` and `gpio` groups (`groups`)? Did you log out and back in after `usermod`? |
|
||||
| Preflight warns `radio in use meshcore-console is running:` | Close the GUI before running or installing the bridge. |
|
||||
@@ -423,14 +590,20 @@ install the table above is the whole of it. Either way, an AIO v2 without
|
||||
|
||||
## What this has been tested on
|
||||
|
||||
This has been verified on a bookworm uConsole with `openhop-core` 1.1.3: the radio comes up,
|
||||
contacts are restored across a restart, and `info` and `contacts` answer correctly over the
|
||||
TCP connection. The older `pymc-core` 1.0.x path, with all three of the bridge's
|
||||
compatibility shims active, has been exercised in full, including traces and the live feed.
|
||||
MeshTerm's test suite does not cover the bridge.
|
||||
**The direct connection** has been tested against the real radio library
|
||||
(`openhop-core`) with a simulated radio; it has **not yet been verified on uConsole
|
||||
hardware**.
|
||||
|
||||
**The bridge** has been verified on a bookworm uConsole with `openhop-core` 1.1.3: the
|
||||
radio comes up, contacts are restored across a restart, and `info` and `contacts` answer
|
||||
correctly over the TCP connection. The older `pymc-core` 1.0.x path, with all three of the
|
||||
bridge's compatibility shims active, has been exercised in full, including traces and the
|
||||
live feed. MeshTerm's test suite does not cover the bridge.
|
||||
|
||||
What has not been confirmed:
|
||||
|
||||
- **The direct connection on real hardware** — everything above has only run against a
|
||||
simulated radio under the real library.
|
||||
- **The bridge under `openhop_core` beyond `info` and `contacts`.** Startup, identity,
|
||||
contact restore and those two reads were exercised; a trace, a message and the live feed
|
||||
under the new runtime were not, though the library's own trace push is what the bridge
|
||||
|
||||
@@ -21,7 +21,7 @@ I wanted something I could run from my computer. I wanted it to run on Windows,
|
||||
In addition to a generic terminal setup, I wanted it to run on two devices I had lying around in my nerdcave.
|
||||
|
||||
### ClockworkPi uConsole
|
||||
MeshTerm is compatible with the **HackerGadgets AIO board (v1 or v2)**. The **AIO** board has just a raw LoRa radio, meaning it can't run MeshCore firmware. MeshTerm includes a script to run the mesh node in software, and expose it using a TCP port which MeshTerm can connect to.
|
||||
MeshTerm is compatible with the **HackerGadgets AIO board (v1 or v2)**. The **AIO** board has just a raw LoRa radio, meaning it can't run MeshCore firmware. MeshTerm can run the mesh node in software itself, straight over the board's SPI bus, for as long as MeshTerm is running — no separate service needed. If you'd rather the node stayed on the mesh while MeshTerm is closed, an optional bridge service can run it all the time instead.
|
||||
|
||||
MeshTerm feels right at home on the **uConsole**. Running MeshTerm on it makes it feel like a piece of gear straight out of a William Gibson novel.
|
||||
|
||||
|
||||
+18
-4
@@ -179,6 +179,11 @@ def main_callback(
|
||||
"--tcp",
|
||||
help="Network address host[:port] of a TCP companion (selects the TCP transport)",
|
||||
),
|
||||
spi: bool = typer.Option(
|
||||
False,
|
||||
"--spi",
|
||||
help="Run a node on the LoRa radio on this machine's SPI bus (selects the SPI transport)",
|
||||
),
|
||||
mock: bool = typer.Option(False, "--mock", help="Use the built-in simulator"),
|
||||
db_path: Path | None = typer.Option(
|
||||
None, "--db", help="SQLite database path (--mock records to meshterm-mock.db)"
|
||||
@@ -204,6 +209,7 @@ def main_callback(
|
||||
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.
|
||||
spi: Select the radio on this machine's SPI bus, whose node MeshTerm runs itself.
|
||||
mock: Whether to use the simulator instead of real hardware.
|
||||
db_path: Override the database location. Without it, a ``--mock`` run records to
|
||||
the simulator's own database rather than the real history.
|
||||
@@ -229,13 +235,20 @@ def main_callback(
|
||||
active = without_emoji(active)
|
||||
set_platform(active)
|
||||
|
||||
if mock and (port or ble or tcp):
|
||||
named_radios = [
|
||||
flag
|
||||
for flag, given in (("--port", port), ("--ble", ble), ("--tcp", tcp), ("--spi", spi))
|
||||
if given
|
||||
]
|
||||
if spi and len(named_radios) > 1:
|
||||
# The SPI radio is on this machine and every other flag names a radio that isn't.
|
||||
raise typer.BadParameter(f"--spi and {named_radios[0]} name different devices; pass one")
|
||||
if mock and named_radios:
|
||||
# One flag says "pretend", the other names one exact radio, and `--mock` used to
|
||||
# win silently — so a scheduled `--port COM7 --mock info` reported on a simulator
|
||||
# while reading as though it had reached the radio. Two contradictory claims about
|
||||
# which device to talk to is a bad command line, not a precedence question.
|
||||
named = "--port" if port else ("--ble" if ble else "--tcp")
|
||||
raise typer.BadParameter(f"--mock and {named} name different devices; pass one")
|
||||
raise typer.BadParameter(f"--mock and {named_radios[0]} name different devices; pass one")
|
||||
|
||||
settings = Settings.load()
|
||||
if db_path is not None:
|
||||
@@ -304,13 +317,14 @@ def main_callback(
|
||||
port_override=port,
|
||||
ble_override=ble,
|
||||
tcp_override=tcp,
|
||||
spi_override=spi,
|
||||
ble_pin=ble_pin,
|
||||
output=OutputFormat.JSON if json_output else OutputFormat.PLAIN,
|
||||
# Whether a tool may stop and ask, which is a different question from what its
|
||||
# output looks like. A pipe on stdin means nobody is there to answer.
|
||||
interactive=_stdin_is_a_person(),
|
||||
explicit_selection=(
|
||||
profile is not None or port is not None or ble is not None or tcp is not None
|
||||
profile is not None or port is not None or ble is not None or tcp is not None or spi
|
||||
),
|
||||
)
|
||||
_state = app_ctx
|
||||
|
||||
+71
-6
@@ -16,7 +16,7 @@ from rich.console import Console
|
||||
from .core.admin_store import AdminStore
|
||||
from .core.advert_store import AdvertStore
|
||||
from .core.channel_store import ChannelStore
|
||||
from .core.config import DeviceProfile, Settings
|
||||
from .core.config import DeviceProfile, Settings, SpiWiring
|
||||
from .core.connection import Device, make_device
|
||||
from .core.contact_store import ContactStore
|
||||
from .core.courier_store import CourierStore
|
||||
@@ -129,6 +129,7 @@ class AppContext:
|
||||
port_override: str | None = None
|
||||
ble_override: str | None = None
|
||||
tcp_override: str | None = None
|
||||
spi_override: bool = False
|
||||
ble_pin: str | None = None
|
||||
output: OutputFormat = OutputFormat.PLAIN
|
||||
interactive: bool = True
|
||||
@@ -210,7 +211,7 @@ class AppContext:
|
||||
serial port). Falls back to an explicit ``--port`` override when a connection hasn't
|
||||
recorded one yet.
|
||||
"""
|
||||
if self.mock or self.active_transport in ("ble", "tcp"):
|
||||
if self.mock or self.active_transport in ("ble", "tcp", "spi"):
|
||||
return None
|
||||
return self._active_port or self.port_override
|
||||
|
||||
@@ -242,15 +243,17 @@ class AppContext:
|
||||
def active_transport(self) -> str | None:
|
||||
"""Which transport the current or selected connection uses.
|
||||
|
||||
One of ``"serial"``, ``"ble"``, ``"tcp"``, or ``None`` for the simulator. For a
|
||||
real device it reflects the open connection when one exists, otherwise the
|
||||
One of ``"serial"``, ``"ble"``, ``"tcp"``, ``"spi"``, or ``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 ``--tcp`` selects TCP,
|
||||
``--ble`` selects BLE), defaulting to serial.
|
||||
``--ble`` selects BLE, ``--spi`` the SPI radio), defaulting to serial.
|
||||
"""
|
||||
if self.mock:
|
||||
return None
|
||||
if self._active_transport is not None:
|
||||
return self._active_transport
|
||||
if self.spi_override or (self.profile is not None and self.profile.is_spi):
|
||||
return "spi"
|
||||
if self.tcp_override:
|
||||
return "tcp"
|
||||
return "ble" if self.ble_override else "serial"
|
||||
@@ -520,6 +523,27 @@ class AppContext:
|
||||
await self._open("the simulator")
|
||||
return self._device
|
||||
|
||||
# A radio on the host's own SPI bus (``--spi``, an SPI profile, or the remembered
|
||||
# default) has nothing to find: MeshTerm starts the node that answers on it.
|
||||
spi = self._resolve_spi()
|
||||
if spi is not None:
|
||||
from .core.spiradio import state_dir
|
||||
|
||||
self._device = make_device(
|
||||
mock=False,
|
||||
port=None,
|
||||
transport="spi",
|
||||
spi=spi,
|
||||
state=state_dir(self.settings.config_dir, spi),
|
||||
)
|
||||
self._active_transport = "spi"
|
||||
self._active_endpoint = spi.spidev
|
||||
self._active_port = None
|
||||
self._active_address = None
|
||||
await self._open(f"SPI radio {spi.spidev}")
|
||||
await self._settle_connection()
|
||||
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.
|
||||
@@ -615,8 +639,10 @@ class AppContext:
|
||||
explicit_other = (
|
||||
bool(self.port_override)
|
||||
or bool(self.ble_override)
|
||||
or self.spi_override
|
||||
or (
|
||||
self.profile is not None and (bool(self.profile.port) or bool(self.profile.address))
|
||||
self.profile is not None
|
||||
and (bool(self.profile.port) or bool(self.profile.address) or self.profile.is_spi)
|
||||
)
|
||||
)
|
||||
if explicit_other:
|
||||
@@ -631,6 +657,45 @@ class AppContext:
|
||||
return host, port
|
||||
return None, None
|
||||
|
||||
def _resolve_spi(self) -> SpiWiring | None:
|
||||
"""The wiring of the SPI radio to open, or ``None`` when another transport is meant.
|
||||
|
||||
In priority order: an SPI profile, the radio picked on the startup splash, ``--spi``
|
||||
(the first SPI profile's wiring, else the AIO's), then the remembered default when it
|
||||
was an SPI radio and nothing else was named. Anything else named explicitly — a port,
|
||||
an address, a host, another kind of profile — means this session is not about the SPI
|
||||
radio.
|
||||
"""
|
||||
if self.profile is not None and self.profile.is_spi:
|
||||
return self.profile.spi or SpiWiring()
|
||||
chosen = self.selected_device
|
||||
if chosen is not None and chosen.is_spi:
|
||||
return chosen.spi or self.spi_wiring_for(chosen.port) # type: ignore[return-value]
|
||||
if self.spi_override:
|
||||
return next(
|
||||
(p.spi or SpiWiring() for p in self.settings.profiles.values() if p.is_spi),
|
||||
SpiWiring(),
|
||||
)
|
||||
if self.port_override or self.ble_override or self.tcp_override or self.profile:
|
||||
return None
|
||||
remembered = self.device_store.load()
|
||||
if remembered is None or remembered.transport != "spi" or not remembered.target:
|
||||
return None
|
||||
self.selected_device = None # remembered, not freshly discovered this session
|
||||
return self.spi_wiring_for(remembered.target)
|
||||
|
||||
def spi_wiring_for(self, spidev: str) -> SpiWiring:
|
||||
"""The wiring for the radio on ``spidev``: a profile's that names it, else the AIO's.
|
||||
|
||||
A remembered or listed SPI radio is known by its device node alone, so its pins come
|
||||
from whichever SPI profile is on that node; with none, the defaults are the only
|
||||
wiring there is (and the right one for the board they describe).
|
||||
"""
|
||||
for profile in self.settings.profiles.values():
|
||||
if profile.is_spi and (profile.spi or SpiWiring()).spidev == spidev:
|
||||
return profile.spi or SpiWiring()
|
||||
return SpiWiring()
|
||||
|
||||
def _resolve_ble_endpoint(self) -> tuple[str | None, str | None]:
|
||||
"""Return the ``(address, pin)`` to open over Bluetooth, or ``(None, None)`` for serial.
|
||||
|
||||
|
||||
+110
-1
@@ -67,6 +67,94 @@ def default_config_dir() -> Path:
|
||||
return Path.home() / ".meshterm"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SpiWiring:
|
||||
"""How a LoRa chip on the host's SPI bus is wired, for a ``transport = "spi"`` profile.
|
||||
|
||||
The defaults are the hackergadgets uConsole AIO v1's wiring, so that board needs no
|
||||
``[profiles.<name>.spi]`` table at all; any other board states only what differs. These
|
||||
are facts about the *board*, which is why they live in ``config.toml`` with the profile
|
||||
and not among the radio's settings: the frequency, bandwidth and power are the node's
|
||||
own, saved by the node and edited on Device config like any companion's.
|
||||
|
||||
Attributes:
|
||||
bus_id: SPI bus (``/dev/spidev<bus_id>.<cs_id>``).
|
||||
cs_id: SPI chip-select device on that bus.
|
||||
cs_pin: A GPIO driven as chip select by hand, or ``-1`` for the bus's own.
|
||||
gpio_chip: Which ``/dev/gpiochip<n>`` the pins below are on.
|
||||
use_gpiod_backend: Drive the pins through ``gpiod`` instead of ``python-periphery``.
|
||||
reset_pin: The chip's reset line.
|
||||
busy_pin: The chip's busy line.
|
||||
irq_pin: The chip's interrupt line (DIO1).
|
||||
txen_pin: A transmit-enable line for an external RF switch, or ``-1``.
|
||||
rxen_pin: A receive-enable line for an external RF switch, or ``-1``.
|
||||
en_pins: Power-enable lines raised before the chip is touched (the AIO v2 wants
|
||||
``[27]``); empty for none.
|
||||
use_dio2_rf: Whether DIO2 drives the RF switch.
|
||||
use_dio3_tcxo: Whether DIO3 powers a TCXO.
|
||||
is_waveshare: The Waveshare HAT's wiring quirks, which the radio library knows.
|
||||
preamble_length: LoRa preamble symbols.
|
||||
python: An interpreter to run the node under, when the one MeshTerm would find
|
||||
is not the one you want. Empty to let MeshTerm look.
|
||||
"""
|
||||
|
||||
bus_id: int = 1
|
||||
cs_id: int = 0
|
||||
cs_pin: int = -1
|
||||
gpio_chip: int = 0
|
||||
use_gpiod_backend: bool = False
|
||||
reset_pin: int = 25
|
||||
busy_pin: int = 24
|
||||
irq_pin: int = 26
|
||||
txen_pin: int = -1
|
||||
rxen_pin: int = -1
|
||||
en_pins: tuple[int, ...] = ()
|
||||
use_dio2_rf: bool = True
|
||||
use_dio3_tcxo: bool = True
|
||||
is_waveshare: bool = False
|
||||
preamble_length: int = 12
|
||||
python: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, table: dict[str, Any]) -> SpiWiring:
|
||||
"""Build the wiring from a ``[profiles.<name>.spi]`` table, defaults for the rest.
|
||||
|
||||
A key this dataclass doesn't know is refused rather than ignored: a misspelt
|
||||
``irq_pn = 22`` would otherwise leave the default in force and a deaf radio with
|
||||
nothing to say why.
|
||||
|
||||
Raises:
|
||||
ValueError: On an unknown key or a value of the wrong type.
|
||||
"""
|
||||
known = {f.name: f for f in cls.__dataclass_fields__.values()}
|
||||
unknown = sorted(set(table) - set(known))
|
||||
if unknown:
|
||||
raise ValueError(f"unknown SPI wiring key(s): {', '.join(unknown)}")
|
||||
values: dict[str, Any] = {}
|
||||
for key, raw in table.items():
|
||||
default = getattr(cls(), key)
|
||||
if isinstance(default, bool):
|
||||
ok = isinstance(raw, bool)
|
||||
elif isinstance(default, int):
|
||||
ok = isinstance(raw, int) and not isinstance(raw, bool)
|
||||
elif isinstance(default, tuple):
|
||||
ok = isinstance(raw, list) and all(
|
||||
isinstance(p, int) and not isinstance(p, bool) for p in raw
|
||||
)
|
||||
raw = tuple(raw) if ok else raw
|
||||
else:
|
||||
ok = isinstance(raw, str)
|
||||
if not ok:
|
||||
raise ValueError(f"SPI wiring {key} = {raw!r} is not a {type(default).__name__}")
|
||||
values[key] = raw
|
||||
return cls(**values)
|
||||
|
||||
@property
|
||||
def spidev(self) -> str:
|
||||
"""The SPI device node this wiring opens."""
|
||||
return f"/dev/spidev{self.bus_id}.{self.cs_id}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DeviceProfile:
|
||||
"""Connection defaults for one physical companion device.
|
||||
@@ -88,6 +176,8 @@ class DeviceProfile:
|
||||
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).
|
||||
spi: How the radio is wired, for ``transport = "spi"`` — a LoRa chip on the host's
|
||||
own SPI bus, run by a node MeshTerm starts itself (:mod:`meshterm.core.spiradio`).
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -100,6 +190,12 @@ class DeviceProfile:
|
||||
ble_pin: str | None = None
|
||||
host: str | None = None
|
||||
tcp_port: int | None = None
|
||||
spi: SpiWiring | None = None
|
||||
|
||||
@property
|
||||
def is_spi(self) -> bool:
|
||||
"""Whether this profile addresses a radio on the host's own SPI bus."""
|
||||
return self.transport == "spi"
|
||||
|
||||
@property
|
||||
def is_ble(self) -> bool:
|
||||
@@ -191,9 +287,21 @@ class Settings:
|
||||
# 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"
|
||||
"spi"
|
||||
if "spi" in pdata
|
||||
else "tcp"
|
||||
if pdata.get("host")
|
||||
else "ble"
|
||||
if pdata.get("address")
|
||||
else "serial"
|
||||
)
|
||||
tcp_port = pdata.get("tcp_port")
|
||||
spi = None
|
||||
if transport == "spi":
|
||||
try:
|
||||
spi = SpiWiring.from_toml(pdata.get("spi") or {})
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"[profiles.{pname}.spi]: {exc}") from exc
|
||||
profiles[pname] = DeviceProfile(
|
||||
name=pname,
|
||||
port=pdata.get("port"),
|
||||
@@ -205,6 +313,7 @@ class Settings:
|
||||
ble_pin=pdata.get("ble_pin"),
|
||||
host=pdata.get("host"),
|
||||
tcp_port=int(tcp_port) if tcp_port is not None else None,
|
||||
spi=spi,
|
||||
)
|
||||
|
||||
return cls(
|
||||
|
||||
@@ -22,6 +22,7 @@ from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from . import transmit_gate
|
||||
@@ -45,6 +46,7 @@ from .models import (
|
||||
from .tracing import path_hash_flags, trace_timeout
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .config import SpiWiring
|
||||
from .discovery import DiscoveredDevice
|
||||
|
||||
#: Module logger; enable DEBUG on ``meshterm.core.connection`` to trace the message pump.
|
||||
@@ -4033,6 +4035,8 @@ def make_device(
|
||||
ble_device: object | None = None,
|
||||
host: str | None = None,
|
||||
tcp_port: int | None = None,
|
||||
spi: SpiWiring | None = None,
|
||||
state: Path | None = None,
|
||||
) -> Device:
|
||||
"""Construct the appropriate :class:`Device` for the current invocation.
|
||||
|
||||
@@ -4042,7 +4046,7 @@ 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), ``"ble"``, or ``"tcp"``.
|
||||
transport: ``"serial"`` (default), ``"ble"``, ``"tcp"``, or ``"spi"``.
|
||||
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
|
||||
@@ -4050,6 +4054,9 @@ def make_device(
|
||||
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"``.
|
||||
spi: How the radio is wired, for the SPI transport. Required when ``transport="spi"``.
|
||||
state: The SPI radio's state directory (see :func:`meshterm.core.spiradio.state_dir`).
|
||||
Required when ``transport="spi"``.
|
||||
|
||||
Returns:
|
||||
A connected-on-enter :class:`Device` instance.
|
||||
@@ -4073,6 +4080,14 @@ def make_device(
|
||||
"pick a device at startup, or use --mock."
|
||||
)
|
||||
return MeshCoreDevice(transport="tcp", host=host, tcp_port=tcp_port)
|
||||
if transport == "spi":
|
||||
if spi is None or state is None:
|
||||
raise ValueError(
|
||||
"No SPI radio configured. Pass --spi, set an SPI profile, or use --mock."
|
||||
)
|
||||
from .spiradio import SpiRadioDevice # imports this module, so not at the top
|
||||
|
||||
return SpiRadioDevice(spi, state)
|
||||
if not port:
|
||||
raise ValueError("No serial port configured. Pass --port, set a profile, or use --mock.")
|
||||
return MeshCoreDevice(port=port, baudrate=baudrate)
|
||||
@@ -4093,7 +4108,11 @@ _PROBE_TIMEOUT_TCP_S = 10.0
|
||||
|
||||
|
||||
async def probe_device(
|
||||
device: DiscoveredDevice, *, baudrate: int = 115200, pin: str | None = None
|
||||
device: DiscoveredDevice,
|
||||
*,
|
||||
baudrate: int = 115200,
|
||||
pin: str | None = None,
|
||||
spi_state: Path | None = None,
|
||||
) -> tuple[MeshCoreDevice, dict] | None:
|
||||
"""Open a discovered device, confirm a MeshCore companion answers, and keep it connected.
|
||||
|
||||
@@ -4113,6 +4132,8 @@ async def probe_device(
|
||||
device: The discovered device to probe (serial or BLE).
|
||||
baudrate: Serial baud rate (serial transport only).
|
||||
pin: Optional BLE pairing PIN (BLE transport only).
|
||||
spi_state: The radio's state directory (SPI transport only) — probing an SPI radio
|
||||
starts its node, and the node needs somewhere to keep its identity.
|
||||
|
||||
Returns:
|
||||
``(device, self_info)`` with a connected :class:`MeshCoreDevice` on success (the
|
||||
@@ -4143,6 +4164,16 @@ async def probe_device(
|
||||
tcp_port=device.tcp_port,
|
||||
connect_timeout=timeout,
|
||||
)
|
||||
elif device.is_spi:
|
||||
from .config import SpiWiring
|
||||
from .spiradio import READY_TIMEOUT_S, SpiRadioDevice
|
||||
|
||||
if spi_state is None:
|
||||
raise ValueError("probing an SPI radio needs its state directory")
|
||||
# The window covers starting the node, not just the handshake: the radio library's
|
||||
# import and the chip's bring-up come first, and a board this small is slow at both.
|
||||
timeout = READY_TIMEOUT_S
|
||||
probe = SpiRadioDevice(device.spi or SpiWiring(), spi_state) # type: ignore[arg-type]
|
||||
else:
|
||||
timeout = _PROBE_TIMEOUT_SERIAL_S
|
||||
probe = MeshCoreDevice(port=device.port, baudrate=baudrate, connect_timeout=timeout)
|
||||
|
||||
@@ -36,6 +36,9 @@ _log = logging.getLogger(__name__)
|
||||
TRANSPORT_SERIAL = "serial"
|
||||
TRANSPORT_BLE = "ble"
|
||||
TRANSPORT_TCP = "tcp"
|
||||
#: A LoRa chip on the host's own SPI bus, run by a node MeshTerm starts itself
|
||||
#: (:mod:`meshterm.core.spiradio`). Found by its ``/dev/spidev*`` node, like a serial port.
|
||||
TRANSPORT_SPI = "spi"
|
||||
#: The built-in simulator, as a device inventory reports it under ``--mock``. Never
|
||||
#: discovered — there is nothing to find — but a session that promised no real hardware
|
||||
#: still has exactly one device, and this is what it is called.
|
||||
@@ -127,7 +130,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"``, ``"ble"``, or ``"tcp"`` — the connection layer for this device.
|
||||
transport: ``"serial"``, ``"ble"``, ``"tcp"``, or ``"spi"`` — the connection layer.
|
||||
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
|
||||
@@ -139,6 +142,10 @@ class DiscoveredDevice:
|
||||
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.
|
||||
spi: The :class:`~meshterm.core.config.SpiWiring` of a radio on the host's SPI bus;
|
||||
SPI only. Its ``port`` is the SPI device node (``/dev/spidev1.0``), which is what
|
||||
such a radio is named and remembered by. Typed ``object`` to keep this module
|
||||
free of the config import.
|
||||
"""
|
||||
|
||||
port: str = ""
|
||||
@@ -155,6 +162,12 @@ class DiscoveredDevice:
|
||||
ble_device: object | None = None
|
||||
host: str | None = None
|
||||
tcp_port: int | None = None
|
||||
spi: object | None = None
|
||||
|
||||
@property
|
||||
def is_spi(self) -> bool:
|
||||
"""Whether this device is a radio on the host's own SPI bus, run by MeshTerm's node."""
|
||||
return self.transport == TRANSPORT_SPI
|
||||
|
||||
@property
|
||||
def is_ble(self) -> bool:
|
||||
@@ -194,6 +207,8 @@ class DiscoveredDevice:
|
||||
return f"tcp:{self.host}:{self.tcp_port}"
|
||||
if self.transport == TRANSPORT_MOCK:
|
||||
return "mock:simulator"
|
||||
if self.is_spi:
|
||||
return f"spi:{self.port}"
|
||||
if self.is_ble:
|
||||
return f"ble:{(self.address or self.name or '').lower()}"
|
||||
if self.serial_number:
|
||||
@@ -212,8 +227,8 @@ class DiscoveredDevice:
|
||||
``"bridge"`` for a generic USB-UART chip (a weak hint — could be anything), or
|
||||
``"unknown"`` for an unrecognized adapter.
|
||||
"""
|
||||
if self.is_ble or self.is_tcp:
|
||||
return "board" # a MeshCore BLE advert / a user-named TCP endpoint is confident
|
||||
if self.is_ble or self.is_tcp or self.is_spi:
|
||||
return "board" # a MeshCore advert / a named endpoint / a wired radio is confident
|
||||
if self.vid in NATIVE_LORA_VIDS:
|
||||
return "board"
|
||||
if self.vid in UART_BRIDGE_VIDS:
|
||||
@@ -236,7 +251,7 @@ class DiscoveredDevice:
|
||||
its USB vendor ID to a friendly name, falling back to the driver's manufacturer
|
||||
string.
|
||||
"""
|
||||
if self.is_ble or self.is_tcp:
|
||||
if self.is_ble or self.is_tcp or self.is_spi:
|
||||
return self.manufacturer or ""
|
||||
if self.vid in KNOWN_LORA_VIDS:
|
||||
return KNOWN_LORA_VIDS[self.vid]
|
||||
@@ -255,6 +270,8 @@ class DiscoveredDevice:
|
||||
if self.is_ble:
|
||||
name = self.name or self.product or self.description or "Bluetooth device"
|
||||
return f"{name} (BLE)"
|
||||
if self.is_spi:
|
||||
return f"{self.name or 'SPI radio'} ({self.port})"
|
||||
name = self.product or self.description or self.vendor_label or "Serial device"
|
||||
suffix = f"({self.port})"
|
||||
if name.endswith(suffix): # avoid "… (COM11) (COM11)"
|
||||
@@ -529,3 +546,27 @@ async def discover_all(
|
||||
# (USB serial number vs BLE address), so no cross-transport dedup is needed here.
|
||||
ble_devices = await discover_ble_devices(ble_timeout)
|
||||
return serial + ble_devices
|
||||
|
||||
|
||||
def spi_device(wiring: object, *, name: str = "") -> DiscoveredDevice:
|
||||
"""Build the :class:`DiscoveredDevice` for a radio on the host's own SPI bus.
|
||||
|
||||
Such a radio is "found" the way a serial port is — its ``/dev/spidev*`` node exists —
|
||||
but nothing answers on it until MeshTerm starts a node, so it is listed from its wiring
|
||||
(a profile's, or the AIO's defaults) rather than probed.
|
||||
|
||||
Args:
|
||||
wiring: The radio's :class:`~meshterm.core.config.SpiWiring`.
|
||||
name: Optional friendly name for display (a profile's description, a node name).
|
||||
|
||||
Returns:
|
||||
An SPI :class:`DiscoveredDevice` ready to select or connect.
|
||||
"""
|
||||
return DiscoveredDevice(
|
||||
transport=TRANSPORT_SPI,
|
||||
port=wiring.spidev, # type: ignore[attr-defined]
|
||||
spi=wiring,
|
||||
name=name or None,
|
||||
description=name or "SPI radio",
|
||||
product=name or None,
|
||||
)
|
||||
@@ -0,0 +1,504 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The software MeshCore node MeshTerm runs on a radio wired straight to the host.
|
||||
|
||||
A board like the uConsole's AIO puts an SX1262 on the host's SPI bus with no
|
||||
microcontroller and no firmware in front of it, so there is no companion to talk to until
|
||||
something runs one. This file is that something: MeshTerm starts it as a **child process**
|
||||
when it connects (:mod:`meshterm.core.spiradio` is the parent's half), talks to it over the
|
||||
standard companion protocol on a loopback port like any network companion, and ends it when
|
||||
it disconnects — so the radio's pins are held exactly as long as MeshTerm is using them.
|
||||
|
||||
**Self-contained on purpose.** Nothing here imports MeshTerm. The radio library
|
||||
(``openhop_core``) is an optional install that often lives in a different interpreter than
|
||||
MeshTerm's — the one-file build cannot import it at all, and on a uConsole it usually sits
|
||||
in its own venv — so the parent runs *this file* by path under whichever Python has the
|
||||
library. Standard library plus ``openhop_core``, and nothing else, is the contract that
|
||||
makes that work; ``tests/test_radionode.py`` holds it.
|
||||
|
||||
**What firmware would remember, this remembers.** The library keeps preferences, channels
|
||||
and contacts in memory only, which is why a node run this way used to come up with no
|
||||
channels after every restart. Everything a firmware companion keeps in flash is kept in the
|
||||
state directory the parent names instead:
|
||||
|
||||
================= =============================================================
|
||||
``identity.key`` the node's private seed — its identity on the mesh
|
||||
``prefs.json`` name, radio settings, TX power, position, the other prefs
|
||||
``channels.json`` the channel table, slot by slot
|
||||
``contacts.json`` the contact list
|
||||
================= =============================================================
|
||||
|
||||
**Talking to the parent.** The parent reads exactly one JSON line from this process's
|
||||
stdout: ``{"event": "ready", "port": …, "public_key": …}`` once the frame server is
|
||||
listening, or ``{"event": "error", "kind": …, "message": …}`` if the radio could not be
|
||||
opened. The library prints its own diagnostics to stdout, so the real stdout is set aside
|
||||
for that one line and everything else is sent to stderr, which the parent keeps as the
|
||||
node's log.
|
||||
|
||||
**Letting go of the radio.** GPIO lines requested through the character device and an open
|
||||
``spidev`` are the kernel's to release, and it releases them when the process ends however
|
||||
it ends. The work is making sure the process *does* end with its parent: it exits when its
|
||||
stdin reaches end-of-file (the parent closing it, or the parent dying and the kernel closing
|
||||
it), and on Linux it also asks for ``SIGTERM`` the moment its parent goes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import dataclasses
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
#: The radio library this node runs on. ``pymc_core`` (its name before 2026) is not
|
||||
#: supported here: it needs three shims that ``openhop_core`` made unnecessary, and the
|
||||
#: standalone bridge still carries them for anyone on it.
|
||||
RUNTIME = "openhop_core"
|
||||
|
||||
#: How many times ``radio.begin()`` is tried when a GPIO line is busy, and the pause before
|
||||
#: each retry. A node that just exited released its lines as it went, so the retries are for
|
||||
#: a line some *other* program is letting go of — not for waiting out a program that holds it.
|
||||
BEGIN_ATTEMPTS = 3
|
||||
BEGIN_BACKOFF_S = 1.5
|
||||
|
||||
#: The model string the frame server reports, which MeshTerm shows as the device model.
|
||||
DEVICE_MODEL = "MeshTerm SPI node"
|
||||
|
||||
log = logging.getLogger("radionode")
|
||||
|
||||
|
||||
# --- errors the parent is told about -------------------------------------------------------
|
||||
|
||||
|
||||
class NodeError(Exception):
|
||||
"""A failure to bring the node up, with the ``kind`` the parent words its message by.
|
||||
|
||||
Kinds: ``runtime`` (the radio library is missing or too old), ``no-spi`` / ``no-gpio``
|
||||
(the device node doesn't exist), ``permission`` (it exists but this user can't open it),
|
||||
``busy`` (another program holds the radio's pins), and ``failed`` (anything else).
|
||||
"""
|
||||
|
||||
def __init__(self, kind: str, message: str) -> None:
|
||||
"""Carry ``message`` as the error text and ``kind`` as its classification."""
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
|
||||
|
||||
class _Recent(logging.Handler):
|
||||
"""Keeps the library's recent error lines, to tell *why* ``radio.begin()`` gave up.
|
||||
|
||||
The GPIO manager answers a busy or forbidden pin by logging the reason and calling
|
||||
``sys.exit``, so the reason exists only as a log line; this is where it is read back.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(level=logging.WARNING)
|
||||
self.lines: list[str] = []
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
self.lines.append(record.getMessage())
|
||||
del self.lines[:-20]
|
||||
|
||||
|
||||
def classify_begin_failure(lines: list[str]) -> str:
|
||||
"""The error kind a failed ``radio.begin()`` amounts to, from the library's log lines."""
|
||||
text = " ".join(lines).lower()
|
||||
if "already in use" in text or "resource busy" in text:
|
||||
return "busy"
|
||||
if "permission denied" in text:
|
||||
return "permission"
|
||||
return "failed"
|
||||
|
||||
|
||||
# --- the state directory -------------------------------------------------------------------
|
||||
|
||||
|
||||
def _write_json(path: Path, value: Any) -> None:
|
||||
"""Replace ``path`` with ``value`` as JSON in one rename (a crash keeps the old file)."""
|
||||
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
||||
tmp.write_text(json.dumps(value, indent=2), encoding="utf-8")
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def _read_json(path: Path) -> Any:
|
||||
"""``path`` parsed as JSON, or ``None`` when it is missing or unreadable."""
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def load_identity_seed(state: Path, mint) -> bytes: # noqa: ANN001 - () -> bytes
|
||||
"""The node's private seed from ``identity.key``, minting and saving one if there is none.
|
||||
|
||||
Args:
|
||||
state: The node's state directory.
|
||||
mint: Makes a fresh seed (the library's key generator) when none is saved yet.
|
||||
"""
|
||||
path = state / "identity.key"
|
||||
try:
|
||||
seed = path.read_bytes()
|
||||
except OSError:
|
||||
seed = b""
|
||||
if seed:
|
||||
return seed
|
||||
seed = bytes(mint())
|
||||
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
||||
tmp.write_bytes(seed)
|
||||
try:
|
||||
os.chmod(tmp, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
tmp.replace(path)
|
||||
log.info("minted a new node identity at %s", path)
|
||||
return seed
|
||||
|
||||
|
||||
def prefs_to_json(prefs: Any) -> dict:
|
||||
"""A ``NodePrefs`` as JSON-safe fields (``bytes`` as hex), for ``prefs.json``."""
|
||||
out = {}
|
||||
for field in dataclasses.fields(prefs):
|
||||
value = getattr(prefs, field.name)
|
||||
out[field.name] = value.hex() if isinstance(value, (bytes, bytearray)) else value
|
||||
return out
|
||||
|
||||
|
||||
def apply_saved_prefs(prefs: Any, saved: Any) -> None:
|
||||
"""Load ``prefs.json`` into a ``NodePrefs`` in place, field by field.
|
||||
|
||||
Only fields the library's ``NodePrefs`` still declares are taken, each coerced to the
|
||||
type its default has, so a field the library dropped is ignored and a hand-edited value
|
||||
of the wrong type is skipped rather than carried into the radio.
|
||||
"""
|
||||
if not isinstance(saved, dict):
|
||||
return
|
||||
for field in dataclasses.fields(prefs):
|
||||
if field.name not in saved:
|
||||
continue
|
||||
current = getattr(prefs, field.name)
|
||||
raw = saved[field.name]
|
||||
try:
|
||||
if isinstance(current, (bytes, bytearray)):
|
||||
value: Any = bytes.fromhex(str(raw))
|
||||
elif isinstance(current, bool):
|
||||
value = bool(raw)
|
||||
elif isinstance(current, int):
|
||||
value = int(raw)
|
||||
elif isinstance(current, float):
|
||||
value = float(raw)
|
||||
else:
|
||||
value = str(raw)
|
||||
except (TypeError, ValueError):
|
||||
log.warning("prefs.json: ignoring %s=%r", field.name, raw)
|
||||
continue
|
||||
setattr(prefs, field.name, value)
|
||||
|
||||
|
||||
def channels_to_json(store: Any) -> list[dict]:
|
||||
"""The channel table as ``[{"idx", "name", "secret"}]`` in slot order."""
|
||||
out = []
|
||||
for idx in range(store.max_channels):
|
||||
channel = store.get(idx)
|
||||
if channel is not None and channel.name:
|
||||
out.append({"idx": idx, "name": channel.name, "secret": bytes(channel.secret).hex()})
|
||||
return out
|
||||
|
||||
|
||||
def saved_channels(saved: Any) -> list[tuple[int, str, bytes]]:
|
||||
"""``channels.json`` as ``(idx, name, secret)`` triples, skipping malformed entries."""
|
||||
out = []
|
||||
for entry in saved if isinstance(saved, list) else []:
|
||||
try:
|
||||
out.append((int(entry["idx"]), str(entry["name"]), bytes.fromhex(entry["secret"])))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
return [c for c in out if c[1]]
|
||||
|
||||
|
||||
# --- the node ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def radio_kwargs(signature_params, wiring: dict, prefs: Any) -> dict: # noqa: ANN001
|
||||
"""The ``SX1262Radio`` constructor arguments: the board's wiring plus the saved radio.
|
||||
|
||||
Passes only what this library version's constructor accepts, so a knob it lacks is
|
||||
dropped instead of refusing the call. ``None`` means "not set" and is never passed.
|
||||
"""
|
||||
wanted = dict(wiring)
|
||||
wanted.update(
|
||||
frequency=prefs.frequency_hz,
|
||||
bandwidth=prefs.bandwidth_hz,
|
||||
spreading_factor=prefs.spreading_factor,
|
||||
coding_rate=prefs.coding_rate,
|
||||
tx_power=prefs.tx_power_dbm,
|
||||
)
|
||||
return {k: v for k, v in wanted.items() if k in signature_params and v is not None}
|
||||
|
||||
|
||||
def _check_device(path: str, missing_kind: str, what: str) -> None:
|
||||
"""Refuse early, with the right kind, when a device node is absent or unopenable."""
|
||||
if not os.path.exists(path):
|
||||
raise NodeError(missing_kind, f"{path} does not exist — is the {what} enabled?")
|
||||
if not os.access(path, os.R_OK | os.W_OK):
|
||||
raise NodeError("permission", f"no read/write permission on {path}")
|
||||
|
||||
|
||||
def _persist_contacts(store: Any, path: Path) -> None:
|
||||
"""Snapshot the contact list after every change, the way the firmware writes flash."""
|
||||
|
||||
def save() -> None:
|
||||
try:
|
||||
_write_json(path, store.to_dicts())
|
||||
except Exception as exc: # noqa: BLE001 - a failed snapshot must not stop the node
|
||||
log.warning("could not save contacts: %s", exc)
|
||||
|
||||
for name in ("add", "add_or_overwrite", "update", "remove", "clear"):
|
||||
original = getattr(store, name, None)
|
||||
if original is None:
|
||||
continue
|
||||
|
||||
def wrapped(*args, _original=original, **kwargs): # noqa: ANN002, ANN003, ANN202
|
||||
result = _original(*args, **kwargs)
|
||||
save()
|
||||
return result
|
||||
|
||||
setattr(store, name, wrapped)
|
||||
store.save_snapshot = save
|
||||
|
||||
|
||||
async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> None
|
||||
"""Bring the node up, report ready, and serve until told to stop.
|
||||
|
||||
Args:
|
||||
config: ``state_dir``, ``wiring`` (the board's pins and switches) and ``seed``
|
||||
(name and radio settings for a node with no ``prefs.json`` yet).
|
||||
report: Sends the one status line to the parent.
|
||||
|
||||
Returns:
|
||||
The process exit status.
|
||||
"""
|
||||
import importlib
|
||||
import inspect
|
||||
|
||||
try:
|
||||
rt = importlib.import_module(RUNTIME)
|
||||
companion_mod = importlib.import_module(f"{RUNTIME}.companion")
|
||||
models = importlib.import_module(f"{RUNTIME}.companion.models")
|
||||
identity_mod = importlib.import_module(f"{RUNTIME}.protocol.identity")
|
||||
sx1262 = importlib.import_module(f"{RUNTIME}.hardware.sx1262_wrapper")
|
||||
except ImportError as exc:
|
||||
raise NodeError("runtime", f"{RUNTIME} is not importable here ({exc})") from exc
|
||||
log.info("node runtime %s %s (%s)", RUNTIME, getattr(rt, "__version__", "?"), sys.executable)
|
||||
|
||||
state = Path(config["state_dir"])
|
||||
state.mkdir(parents=True, exist_ok=True)
|
||||
wiring = dict(config.get("wiring") or {})
|
||||
seed = dict(config.get("seed") or {})
|
||||
|
||||
bus, cs = int(wiring.get("bus_id", 0)), int(wiring.get("cs_id", 0))
|
||||
_check_device(f"/dev/spidev{bus}.{cs}", "no-spi", "SPI overlay")
|
||||
_check_device(f"/dev/gpiochip{int(wiring.get('gpio_chip', 0))}", "no-gpio", "GPIO chip")
|
||||
|
||||
# The saved preferences decide the radio the chip is brought up on; the seed only fills
|
||||
# in a node that has never saved any.
|
||||
prefs = models.NodePrefs(
|
||||
node_name=seed.get("node_name", "MeshTerm"),
|
||||
tx_power_dbm=seed.get("tx_power_dbm", 22),
|
||||
frequency_hz=seed.get("frequency_hz", 910_525_000),
|
||||
bandwidth_hz=seed.get("bandwidth_hz", 62_500),
|
||||
spreading_factor=seed.get("spreading_factor", 7),
|
||||
coding_rate=seed.get("coding_rate", 5),
|
||||
)
|
||||
apply_saved_prefs(prefs, _read_json(state / "prefs.json"))
|
||||
|
||||
SX1262Radio = sx1262.SX1262Radio
|
||||
kwargs = radio_kwargs(inspect.signature(SX1262Radio.__init__).parameters, wiring, prefs)
|
||||
log.info("radio config %s", " ".join(f"{k}={v}" for k, v in kwargs.items()))
|
||||
radio = SX1262Radio(**kwargs)
|
||||
|
||||
recent = _Recent()
|
||||
logging.getLogger().addHandler(recent)
|
||||
for attempt in range(BEGIN_ATTEMPTS):
|
||||
recent.lines.clear()
|
||||
try:
|
||||
if radio.begin():
|
||||
break
|
||||
kind = classify_begin_failure(recent.lines)
|
||||
except SystemExit: # the GPIO manager's answer to a busy or forbidden pin
|
||||
kind = classify_begin_failure(recent.lines)
|
||||
except Exception as exc: # noqa: BLE001 - reported to the parent, not raised
|
||||
recent.lines.append(str(exc))
|
||||
kind = classify_begin_failure(recent.lines)
|
||||
try:
|
||||
radio.cleanup()
|
||||
except Exception: # noqa: BLE001, S110 - best-effort release before retrying
|
||||
pass
|
||||
if kind != "busy" or attempt == BEGIN_ATTEMPTS - 1:
|
||||
detail = recent.lines[-1] if recent.lines else "radio.begin() failed"
|
||||
raise NodeError(kind, detail)
|
||||
await asyncio.sleep(BEGIN_BACKOFF_S * (attempt + 1))
|
||||
logging.getLogger().removeHandler(recent)
|
||||
log.info("radio ready")
|
||||
|
||||
try:
|
||||
seed_bytes = load_identity_seed(
|
||||
state, lambda: identity_mod.LocalIdentity().get_signing_key_bytes()
|
||||
)
|
||||
identity = identity_mod.LocalIdentity(seed_bytes)
|
||||
node = _persistent_companion(companion_mod.CompanionRadio, state)(
|
||||
radio,
|
||||
identity,
|
||||
node_name=prefs.node_name,
|
||||
radio_config={
|
||||
"frequency": prefs.frequency_hz,
|
||||
"bandwidth": prefs.bandwidth_hz,
|
||||
"spreading_factor": prefs.spreading_factor,
|
||||
"coding_rate": prefs.coding_rate,
|
||||
"tx_power": prefs.tx_power_dbm,
|
||||
},
|
||||
)
|
||||
apply_saved_prefs(node.prefs, prefs_to_json(prefs))
|
||||
|
||||
for idx, name, secret in saved_channels(_read_json(state / "channels.json")):
|
||||
node.set_channel(idx, name, secret)
|
||||
contacts = _read_json(state / "contacts.json")
|
||||
if isinstance(contacts, list):
|
||||
node.contacts.load_from_dicts(contacts)
|
||||
log.info("restored %d contact(s)", node.contacts.get_count())
|
||||
_persist_contacts(node.contacts, state / "contacts.json")
|
||||
node.add_push_callback(
|
||||
"channel_updated",
|
||||
lambda _idx, _channel: _write_json(
|
||||
state / "channels.json", channels_to_json(node.channels)
|
||||
),
|
||||
)
|
||||
|
||||
await node.start()
|
||||
public_key = node.get_public_key()
|
||||
server = companion_mod.CompanionFrameServer(
|
||||
bridge=node,
|
||||
companion_hash=f"{public_key[0]:02x}",
|
||||
port=0,
|
||||
bind_address="127.0.0.1",
|
||||
local_hash=public_key[0],
|
||||
device_model=DEVICE_MODEL,
|
||||
client_idle_timeout_sec=None,
|
||||
)
|
||||
await server.start()
|
||||
# The one push the library's frame server doesn't subscribe to: every overheard frame
|
||||
# with its SNR/RSSI, which MeshTerm's live feed is built from.
|
||||
node.add_push_callback("rx_log_data", server.push_rx_raw)
|
||||
port = server._server.sockets[0].getsockname()[1]
|
||||
except Exception:
|
||||
radio.cleanup()
|
||||
raise
|
||||
|
||||
log.info("node %s… listening on 127.0.0.1:%d", public_key.hex()[:16], port)
|
||||
report({"event": "ready", "port": port, "public_key": public_key.hex()})
|
||||
|
||||
try:
|
||||
await _until_told_to_stop()
|
||||
finally:
|
||||
log.info("shutting down")
|
||||
for step in (server.stop, node.stop):
|
||||
try:
|
||||
await step()
|
||||
except Exception as exc: # noqa: BLE001 - keep going: the radio still needs freeing
|
||||
log.warning("shutdown step failed: %s", exc)
|
||||
node.contacts.save_snapshot()
|
||||
radio.cleanup()
|
||||
return 0
|
||||
|
||||
|
||||
def _persistent_companion(base: type, state: Path) -> type:
|
||||
"""``CompanionRadio`` with its preferences written to ``prefs.json`` on every change.
|
||||
|
||||
``_save_prefs`` is the library's own hook for exactly this ("subclasses that need
|
||||
persistence … should override this method"), called after every preference setter.
|
||||
"""
|
||||
|
||||
class PersistentCompanion(base): # type: ignore[misc, valid-type]
|
||||
def _save_prefs(self) -> None:
|
||||
try:
|
||||
_write_json(state / "prefs.json", prefs_to_json(self.prefs))
|
||||
except Exception as exc: # noqa: BLE001 - a failed save must not fail the setter
|
||||
log.warning("could not save prefs: %s", exc)
|
||||
|
||||
return PersistentCompanion
|
||||
|
||||
|
||||
async def _until_told_to_stop() -> None:
|
||||
"""Wait for stdin to close or a SIGTERM/SIGINT — the parent's two ways of saying stop."""
|
||||
loop = asyncio.get_running_loop()
|
||||
stop = asyncio.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
try:
|
||||
loop.add_signal_handler(sig, stop.set)
|
||||
except (NotImplementedError, RuntimeError):
|
||||
pass
|
||||
|
||||
def watch_stdin() -> None:
|
||||
try:
|
||||
while sys.stdin.buffer.read(4096):
|
||||
pass
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
loop.call_soon_threadsafe(stop.set)
|
||||
|
||||
threading.Thread(target=watch_stdin, name="parent-watch", daemon=True).start()
|
||||
await stop.wait()
|
||||
|
||||
|
||||
def _die_with_parent() -> None:
|
||||
"""On Linux, have the kernel send SIGTERM when the parent exits (best-effort)."""
|
||||
if not sys.platform.startswith("linux"):
|
||||
return
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
PR_SET_PDEATHSIG = 1
|
||||
ctypes.CDLL("libc.so.6", use_errno=True).prctl(PR_SET_PDEATHSIG, signal.SIGTERM)
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Entry point: ``python radionode.py --config '<json>'``."""
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--config", required=True, help="the node's configuration, as JSON")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
# One line on the real stdout is the parent's; everything else goes to stderr.
|
||||
status = os.fdopen(os.dup(1), "w", encoding="utf-8")
|
||||
os.dup2(2, 1)
|
||||
sys.stdout = sys.stderr
|
||||
|
||||
def report(message: dict) -> None:
|
||||
status.write(json.dumps(message) + "\n")
|
||||
status.flush()
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
stream=sys.stderr,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
_die_with_parent()
|
||||
try:
|
||||
return asyncio.run(run_node(json.loads(args.config), report))
|
||||
except NodeError as exc:
|
||||
log.error("%s: %s", exc.kind, exc)
|
||||
report({"event": "error", "kind": exc.kind, "message": str(exc)})
|
||||
return 1
|
||||
except Exception as exc: # noqa: BLE001 - the parent gets a sentence, the log the trace
|
||||
log.exception("node failed")
|
||||
report({"event": "error", "kind": "failed", "message": str(exc)})
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,595 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""A LoRa radio on the host's own SPI bus, driven by a node MeshTerm runs only while it runs.
|
||||
|
||||
Some boards — the uConsole's AIO is the one this was built for — put the radio chip straight
|
||||
on the host's SPI bus, with no microcontroller and so no companion firmware to talk to. A
|
||||
software node has to run somewhere. The standalone ``meshterm-spi-bridge`` service runs one
|
||||
all the time, which keeps the node on the mesh while MeshTerm is closed but holds the radio's
|
||||
pins for good, so no other LoRa program can use them until the service is stopped.
|
||||
|
||||
This is the other shape: **MeshTerm runs the node itself, for exactly as long as it is
|
||||
connected.** :class:`SpiRadioDevice` starts the node (:mod:`meshterm.core.radionode`) as a
|
||||
child process when it connects, talks to it over the ordinary companion protocol on a
|
||||
loopback port — so every feature works exactly as it does against a network companion — and
|
||||
ends it when it disconnects. The pins go back when MeshTerm quits, and also when it crashes:
|
||||
the node exits with its parent (see :mod:`~meshterm.core.radionode`), and the kernel frees a
|
||||
process's GPIO lines and SPI handle when it exits.
|
||||
|
||||
**Why a child process and not a library call.** The radio library (``openhop-core``) is an
|
||||
optional install, deliberately not something every desktop MeshTerm carries, and the
|
||||
one-file build can't import it at all. So the node runs under whichever Python *has* the
|
||||
library (:func:`find_runtime`): MeshTerm's own when it was installed with the ``spi``
|
||||
extra, the bridge's venv, or the ``meshcore-uconsole`` package's. A separate process also
|
||||
keeps the node's radio timing off the event loop that draws the screen.
|
||||
|
||||
**One radio, one identity.** A node's state — its identity key, preferences, channels and
|
||||
contacts — lives under ``<config_dir>/radio/<spidev>/``, keyed by the SPI device rather than
|
||||
by a profile name, so reaching the same radio from the picker one day and from a profile the
|
||||
next is still the same node. The first time a radio is used, the bridge's identity and
|
||||
contacts are copied in (:func:`import_bridge_state`) so an existing node keeps its key, and
|
||||
with it its place in everyone else's contact list.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .config import SpiWiring
|
||||
from .connection import DeviceCommandError, MeshCoreDevice
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
#: The radio library the node needs, as ``pip`` spells it — what every "install it" hint says.
|
||||
RUNTIME_PACKAGE = "openhop-core[hardware]"
|
||||
|
||||
#: How long a starting node gets to report ready. It imports the radio library, brings the
|
||||
#: chip up (retrying a busy pin a few times) and starts listening; on a PicoCalc-class board
|
||||
#: the import alone is several seconds.
|
||||
READY_TIMEOUT_S = 60.0
|
||||
|
||||
#: How long a node gets to shut down on its own after its stdin closes, before it is sent
|
||||
#: SIGTERM, and then again before SIGKILL. Its own shutdown saves contacts and frees the
|
||||
#: radio; the signals are for a node that has stopped answering.
|
||||
STOP_GRACE_S = 8.0
|
||||
TERM_GRACE_S = 3.0
|
||||
|
||||
#: What the node is seeded with the first time a radio is used and it has no preferences of
|
||||
#: its own: MeshCore's US/Canada preset at the AIO's 22 dBm. Afterwards the node's saved
|
||||
#: settings rule, edited on Device config like any companion's.
|
||||
DEFAULT_SEED: dict[str, object] = {
|
||||
"frequency_hz": 910_525_000,
|
||||
"bandwidth_hz": 62_500,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 5,
|
||||
"tx_power_dbm": 22,
|
||||
}
|
||||
|
||||
#: The standalone bridge's service name and the directory it keeps its state in.
|
||||
BRIDGE_SERVICE = "meshterm-spi-bridge.service"
|
||||
BRIDGE_NAME = "meshterm-spi-bridge"
|
||||
|
||||
#: ``MESHCORE_*`` variables the bridge reads, mapped to the node preference each seeds.
|
||||
_BRIDGE_RADIO_ENV = {
|
||||
"MESHCORE_FREQUENCY": "frequency_hz",
|
||||
"MESHCORE_BANDWIDTH": "bandwidth_hz",
|
||||
"MESHCORE_SPREADING_FACTOR": "spreading_factor",
|
||||
"MESHCORE_CODING_RATE": "coding_rate",
|
||||
"MESHCORE_TX_POWER": "tx_power_dbm",
|
||||
}
|
||||
|
||||
|
||||
class SpiRadioError(DeviceCommandError):
|
||||
"""The node could not be started, worded for the person who has to fix it.
|
||||
|
||||
A :class:`~meshterm.core.connection.DeviceCommandError`, because that is what the
|
||||
startup picker and the connect path pass through as an *actionable* failure — shown
|
||||
with its remedy — rather than folding it into "didn't answer".
|
||||
|
||||
Attributes:
|
||||
kind: What went wrong — ``unsupported``, ``runtime``, ``no-spi``, ``no-gpio``,
|
||||
``permission``, ``busy``, or ``failed`` (see :func:`explain`).
|
||||
"""
|
||||
|
||||
def __init__(self, kind: str, message: str) -> None:
|
||||
"""Carry ``message`` as the error text and ``kind`` as its classification."""
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
|
||||
|
||||
# --- where things are ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def node_script() -> Path:
|
||||
"""The node's source file, which is run by path under another interpreter.
|
||||
|
||||
It sits beside this module in a checkout and in an install, and the one-file build
|
||||
ships it as a data file at the same relative place (``packaging/meshterm.spec``).
|
||||
"""
|
||||
return Path(__file__).with_name("radionode.py")
|
||||
|
||||
|
||||
def state_dir(config_dir: Path, wiring: SpiWiring) -> Path:
|
||||
"""Where the node on ``wiring``'s SPI device keeps its identity, settings and lists."""
|
||||
return config_dir / "radio" / Path(wiring.spidev).name
|
||||
|
||||
|
||||
def _on_linux() -> bool:
|
||||
"""Whether this is Linux, the one place a radio on the SPI bus can be driven from."""
|
||||
return sys.platform.startswith("linux")
|
||||
|
||||
|
||||
def _xdg_data_home() -> Path:
|
||||
"""``$XDG_DATA_HOME``, or ``~/.local/share`` where it is unset."""
|
||||
raw = os.environ.get("XDG_DATA_HOME", "").strip()
|
||||
return Path(raw) if raw else Path.home() / ".local" / "share"
|
||||
|
||||
|
||||
def spi_present(wiring: SpiWiring) -> bool:
|
||||
"""Whether ``wiring``'s SPI device node exists on this machine (Linux only)."""
|
||||
return _on_linux() and os.path.exists(wiring.spidev)
|
||||
|
||||
|
||||
# --- finding a Python with the radio library -----------------------------------------------
|
||||
|
||||
#: Each interpreter probed this session: path -> whether it can import the radio library.
|
||||
_probed: dict[str, bool] = {}
|
||||
|
||||
|
||||
def _runtime_candidates(wiring: SpiWiring) -> list[str]:
|
||||
"""Interpreters worth probing for the radio library, most specific first."""
|
||||
candidates: list[str] = []
|
||||
if wiring.python:
|
||||
candidates.append(os.path.expanduser(wiring.python))
|
||||
if not getattr(sys, "frozen", False):
|
||||
candidates.append(sys.executable) # MeshTerm's own, installed with the ``spi`` extra
|
||||
data = _xdg_data_home()
|
||||
candidates += [
|
||||
str(data / BRIDGE_NAME / "venv" / "bin" / "python"),
|
||||
"/opt/venvs/meshcore-uconsole/bin/python",
|
||||
]
|
||||
system = shutil.which("python3")
|
||||
if system:
|
||||
candidates.append(system)
|
||||
seen: set[str] = set()
|
||||
return [c for c in candidates if c and not (c in seen or seen.add(c))]
|
||||
|
||||
|
||||
def _can_import_runtime(python: str) -> bool:
|
||||
"""Whether ``python`` can import ``openhop_core`` (one short subprocess, then cached)."""
|
||||
if python in _probed:
|
||||
return _probed[python]
|
||||
ok = False
|
||||
if os.path.exists(python):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[python, "-c", "import openhop_core"],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
env=child_env(),
|
||||
timeout=30,
|
||||
check=False,
|
||||
)
|
||||
ok = result.returncode == 0
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
ok = False
|
||||
_probed[python] = ok
|
||||
return ok
|
||||
|
||||
|
||||
def find_runtime(wiring: SpiWiring) -> str:
|
||||
"""An interpreter that can run the node, or raise :class:`SpiRadioError` (``runtime``).
|
||||
|
||||
A ``python`` named in the wiring is the only candidate when it is set — naming one is a
|
||||
decision, and quietly falling back past it would hide that it doesn't work.
|
||||
"""
|
||||
candidates = _runtime_candidates(wiring)
|
||||
if wiring.python:
|
||||
candidates = candidates[:1]
|
||||
for python in candidates:
|
||||
if _can_import_runtime(python):
|
||||
return python
|
||||
if wiring.python:
|
||||
raise SpiRadioError("runtime", f"{wiring.python} cannot import openhop_core")
|
||||
raise SpiRadioError("runtime", "no Python on this machine has the radio library")
|
||||
|
||||
|
||||
def child_env() -> dict[str, str]:
|
||||
"""The environment for a program MeshTerm starts, minus what a frozen build injected.
|
||||
|
||||
The one-file build's bootloader leaves its own variables behind (``_PYI_*``,
|
||||
``_MEIPASS2``) and points ``LD_LIBRARY_PATH`` at its unpacked libraries; another Python
|
||||
started with those loads MeshTerm's bundled copies of libssl and friends instead of its
|
||||
own. PyInstaller keeps the original under ``LD_LIBRARY_PATH_ORIG``, which is put back.
|
||||
"""
|
||||
env = {k: v for k, v in os.environ.items() if not (k.startswith("_PYI") or k == "_MEIPASS2")}
|
||||
if getattr(sys, "frozen", False):
|
||||
original = env.pop("LD_LIBRARY_PATH_ORIG", None)
|
||||
if original is not None:
|
||||
env["LD_LIBRARY_PATH"] = original
|
||||
else:
|
||||
env.pop("LD_LIBRARY_PATH", None)
|
||||
env["PYTHONUNBUFFERED"] = "1"
|
||||
return env
|
||||
|
||||
|
||||
# --- who else has the radio ----------------------------------------------------------------
|
||||
|
||||
|
||||
def radio_holder() -> str | None:
|
||||
"""Name the program already holding the radio, when it is one we know how to stop.
|
||||
|
||||
Asked before starting the node, because the node's own answer to a held pin is a bare
|
||||
"busy" after several seconds of retries, and the two usual holders each have a one-line
|
||||
fix worth saying instead.
|
||||
"""
|
||||
if not _on_linux():
|
||||
return None
|
||||
systemctl = shutil.which("systemctl")
|
||||
if systemctl:
|
||||
try:
|
||||
active = subprocess.run(
|
||||
[systemctl, "--user", "is-active", "--quiet", BRIDGE_SERVICE],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
if active.returncode == 0:
|
||||
return "bridge"
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
for cmdline in Path("/proc").glob("[0-9]*/cmdline"):
|
||||
try:
|
||||
argv = cmdline.read_bytes().split(b"\0")
|
||||
except OSError:
|
||||
continue
|
||||
if any(os.path.basename(a) == b"meshcore-console" for a in argv[:3]):
|
||||
return "console"
|
||||
return None
|
||||
|
||||
|
||||
def explain(kind: str, detail: str, wiring: SpiWiring, holder: str | None = None) -> str:
|
||||
"""The sentence a failed start is reported with: what is wrong and what to do about it."""
|
||||
if kind == "busy" or holder:
|
||||
if holder == "bridge":
|
||||
return (
|
||||
f"the {BRIDGE_NAME} service has the radio — stop it with "
|
||||
f"`systemctl --user stop {BRIDGE_NAME}` (and `disable` it to keep it stopped)"
|
||||
)
|
||||
if holder == "console":
|
||||
return "meshcore-console has the radio open — close it and connect again"
|
||||
return (
|
||||
"another program has the radio's pins "
|
||||
f"(`sudo lsof /dev/gpiochip{wiring.gpio_chip}` shows which)"
|
||||
)
|
||||
if kind == "runtime":
|
||||
return (
|
||||
f"{detail}. Install it with `pipx inject mesh-term '{RUNTIME_PACKAGE}'`, or into a "
|
||||
"venv of its own and name that venv's python as `python` in the profile's spi table"
|
||||
)
|
||||
if kind == "no-spi":
|
||||
return (
|
||||
f"{wiring.spidev} does not exist — enable SPI (on a uConsole, add "
|
||||
"`dtoverlay=spi1-1cs` to /boot/firmware/config.txt) and reboot"
|
||||
)
|
||||
if kind == "no-gpio":
|
||||
return f"/dev/gpiochip{wiring.gpio_chip} does not exist — check `gpio_chip` in the profile"
|
||||
if kind == "permission":
|
||||
return (
|
||||
f"{detail} — add yourself to the spi and gpio groups "
|
||||
"(`sudo usermod -aG spi,gpio $USER`) and log in again"
|
||||
)
|
||||
if kind == "unsupported":
|
||||
return detail
|
||||
return f"the radio node failed: {detail}"
|
||||
|
||||
|
||||
# --- first use: carrying over the bridge's node --------------------------------------------
|
||||
|
||||
|
||||
def _bridge_radio_seed() -> dict[str, int]:
|
||||
"""The radio settings the bridge service runs with, from its unit's environment.
|
||||
|
||||
The bridge takes its frequency, preset and power from ``MESHCORE_*`` variables, usually
|
||||
set in a drop-in; a node that inherits the bridge's identity should come up on the same
|
||||
channel of air, not on the default preset. Empty when there is no such service.
|
||||
"""
|
||||
systemctl = shutil.which("systemctl")
|
||||
if not systemctl:
|
||||
return {}
|
||||
try:
|
||||
shown = subprocess.run(
|
||||
[systemctl, "--user", "show", "--property=Environment", BRIDGE_SERVICE],
|
||||
stdin=subprocess.DEVNULL,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return {}
|
||||
seed: dict[str, int] = {}
|
||||
for word in shown.stdout.removeprefix("Environment=").split():
|
||||
name, _, value = word.partition("=")
|
||||
if name in _BRIDGE_RADIO_ENV:
|
||||
try:
|
||||
seed[_BRIDGE_RADIO_ENV[name]] = int(value)
|
||||
except ValueError:
|
||||
continue
|
||||
return seed
|
||||
|
||||
|
||||
def import_bridge_state(state: Path) -> list[str]:
|
||||
"""Copy the bridge's node into a radio's state directory the first time it is used.
|
||||
|
||||
Runs only while the state directory has no identity yet, and copies rather than moves, so
|
||||
the bridge still works for anyone who goes back to it. The identity is looked for where
|
||||
the bridge itself looks, in its order: the ``meshcore-uconsole`` GUI's key first (the
|
||||
bridge shares it), then the bridge's own. Contacts come from the bridge's snapshot, whose
|
||||
records are the radio library's own contact dicts, so they load unchanged. Radio settings
|
||||
are seeded from the service's environment, and the node keeps the bridge's name.
|
||||
|
||||
Args:
|
||||
state: The radio's state directory.
|
||||
|
||||
Returns:
|
||||
What was carried over, for the log — empty when nothing was.
|
||||
"""
|
||||
if (state / "identity.key").exists():
|
||||
return []
|
||||
data = _xdg_data_home()
|
||||
bridge = data / BRIDGE_NAME
|
||||
carried: list[str] = []
|
||||
for key in (data / "meshcore-uconsole" / "identity.key", bridge / "identity.key"):
|
||||
if key.is_file():
|
||||
state.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(key, state / "identity.key")
|
||||
os.chmod(state / "identity.key", 0o600)
|
||||
carried.append(f"identity from {key}")
|
||||
break
|
||||
if not carried:
|
||||
return []
|
||||
contacts = bridge / "contacts.json"
|
||||
if contacts.is_file() and not (state / "contacts.json").exists():
|
||||
shutil.copyfile(contacts, state / "contacts.json")
|
||||
carried.append(f"contacts from {contacts}")
|
||||
if not (state / "prefs.json").exists():
|
||||
prefs: dict[str, object] = {"node_name": "uConsole", **_bridge_radio_seed()}
|
||||
(state / "prefs.json").write_text(json.dumps(prefs, indent=2), encoding="utf-8")
|
||||
carried.append("the bridge's name and radio settings")
|
||||
return carried
|
||||
|
||||
|
||||
# --- the node process ----------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class NodeProcess:
|
||||
"""One running node: the child process and the loopback port it serves on.
|
||||
|
||||
Attributes:
|
||||
process: The child.
|
||||
port: The loopback TCP port its frame server listens on.
|
||||
public_key: The node's public key, hex, as it reported it.
|
||||
log_path: Where its stderr goes.
|
||||
"""
|
||||
|
||||
process: asyncio.subprocess.Process
|
||||
port: int
|
||||
public_key: str
|
||||
log_path: Path
|
||||
|
||||
@property
|
||||
def alive(self) -> bool:
|
||||
"""Whether the child is still running."""
|
||||
return self.process.returncode is None
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""End the node and wait for it: close its stdin, then SIGTERM, then SIGKILL.
|
||||
|
||||
Closing stdin is the polite request — the node saves its contacts and frees the radio
|
||||
on the way out. The signals are for a node that has stopped listening, and each wait
|
||||
is bounded so a wedged child can never hold up a quit.
|
||||
"""
|
||||
proc = self.process
|
||||
if proc.returncode is not None:
|
||||
return
|
||||
if proc.stdin is not None:
|
||||
proc.stdin.close()
|
||||
for grace, escalate in ((STOP_GRACE_S, proc.terminate), (TERM_GRACE_S, proc.kill)):
|
||||
try:
|
||||
await asyncio.wait_for(proc.wait(), timeout=grace)
|
||||
return
|
||||
except asyncio.TimeoutError:
|
||||
try:
|
||||
escalate()
|
||||
except ProcessLookupError:
|
||||
return
|
||||
await proc.wait()
|
||||
|
||||
|
||||
def _rotate(log_path: Path) -> None:
|
||||
"""Keep the previous run's node log beside this one's, and no more."""
|
||||
if log_path.exists():
|
||||
try:
|
||||
log_path.replace(log_path.with_suffix(".log.1"))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeProcess:
|
||||
"""Start the node on ``wiring``'s radio and wait until it is listening.
|
||||
|
||||
Args:
|
||||
wiring: How the radio is wired.
|
||||
state: The radio's state directory.
|
||||
node_name: The name a brand-new node advertises until it is renamed.
|
||||
|
||||
Returns:
|
||||
The running node.
|
||||
|
||||
Raises:
|
||||
SpiRadioError: If it can't be started, with the reason already worded.
|
||||
"""
|
||||
if not _on_linux():
|
||||
raise SpiRadioError("unsupported", "a radio on the SPI bus needs Linux")
|
||||
# Each of these runs a short subprocess or two; none of them belongs on the event loop
|
||||
# that is drawing the "connecting" card.
|
||||
holder = await asyncio.to_thread(radio_holder)
|
||||
if holder:
|
||||
raise SpiRadioError("busy", explain("busy", "", wiring, holder))
|
||||
try:
|
||||
python = await asyncio.to_thread(find_runtime, wiring)
|
||||
except SpiRadioError as exc:
|
||||
raise SpiRadioError(exc.kind, explain(exc.kind, str(exc), wiring)) from None
|
||||
|
||||
state.mkdir(parents=True, exist_ok=True)
|
||||
for line in await asyncio.to_thread(import_bridge_state, state):
|
||||
_log.info("spi radio: carried over %s", line)
|
||||
config = {
|
||||
"state_dir": str(state),
|
||||
"wiring": {
|
||||
"bus_id": wiring.bus_id,
|
||||
"cs_id": wiring.cs_id,
|
||||
"cs_pin": wiring.cs_pin,
|
||||
"gpio_chip": wiring.gpio_chip,
|
||||
"use_gpiod_backend": wiring.use_gpiod_backend,
|
||||
"reset_pin": wiring.reset_pin,
|
||||
"busy_pin": wiring.busy_pin,
|
||||
"irq_pin": wiring.irq_pin,
|
||||
"txen_pin": wiring.txen_pin,
|
||||
"rxen_pin": wiring.rxen_pin,
|
||||
"en_pins": list(wiring.en_pins) or None,
|
||||
"use_dio2_rf": wiring.use_dio2_rf,
|
||||
"use_dio3_tcxo": wiring.use_dio3_tcxo,
|
||||
"is_waveshare": wiring.is_waveshare,
|
||||
"preamble_length": wiring.preamble_length,
|
||||
},
|
||||
"seed": {"node_name": node_name, **DEFAULT_SEED},
|
||||
}
|
||||
log_path = state / "node.log"
|
||||
_rotate(log_path)
|
||||
_log.info("spi radio: starting the node under %s (log %s)", python, log_path)
|
||||
with log_path.open("wb") as log_file:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
python,
|
||||
str(node_script()),
|
||||
"--config",
|
||||
json.dumps(config),
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=log_file,
|
||||
env=child_env(),
|
||||
start_new_session=True, # ^C in the terminal is MeshTerm's to handle, not the node's
|
||||
)
|
||||
node = NodeProcess(process=proc, port=0, public_key="", log_path=log_path)
|
||||
try:
|
||||
line = await asyncio.wait_for(proc.stdout.readline(), timeout=READY_TIMEOUT_S)
|
||||
except asyncio.CancelledError:
|
||||
proc.kill() # abandoned mid-start (a probe's own deadline): nothing may keep the radio
|
||||
raise
|
||||
except asyncio.TimeoutError:
|
||||
await node.stop()
|
||||
detail = f"it did not start within {READY_TIMEOUT_S:.0f}s (see {log_path})"
|
||||
raise SpiRadioError("failed", explain("failed", detail, wiring)) from None
|
||||
try:
|
||||
status = json.loads(line) if line else {}
|
||||
except ValueError:
|
||||
status = {}
|
||||
if status.get("event") != "ready":
|
||||
await node.stop()
|
||||
kind = str(status.get("kind") or "failed")
|
||||
detail = str(status.get("message") or f"it exited without a word (see {log_path})")
|
||||
holder = await asyncio.to_thread(radio_holder) if kind == "busy" else None
|
||||
raise SpiRadioError(kind, explain(kind, detail, wiring, holder))
|
||||
node.port = int(status["port"])
|
||||
node.public_key = str(status.get("public_key") or "")
|
||||
_log.info("spi radio: node %s… ready on 127.0.0.1:%d", node.public_key[:16], node.port)
|
||||
return node
|
||||
|
||||
|
||||
# --- the device ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SpiRadioDevice(MeshCoreDevice):
|
||||
"""A companion connection to a node MeshTerm starts on the host's own radio.
|
||||
|
||||
Underneath it is exactly a network companion on ``127.0.0.1`` — every command, event
|
||||
and trace goes through :class:`MeshCoreDevice`'s TCP path unchanged — with the node's
|
||||
lifetime tied to the connection's: :meth:`connect` starts it, :meth:`disconnect` ends
|
||||
it, and a reconnect (which disconnects and builds a fresh device) starts a fresh one.
|
||||
"""
|
||||
|
||||
def __init__(self, wiring: SpiWiring, state: Path, *, node_name: str = "MeshTerm") -> None:
|
||||
"""Prepare the device; nothing is started until :meth:`connect`.
|
||||
|
||||
Args:
|
||||
wiring: How the radio is wired.
|
||||
state: The radio's state directory (see :func:`state_dir`).
|
||||
node_name: The name a brand-new node advertises until it is renamed.
|
||||
"""
|
||||
super().__init__(transport="tcp", host="127.0.0.1", tcp_port=0)
|
||||
self._wiring = wiring
|
||||
self._state = state
|
||||
self._node_name = node_name
|
||||
self._node: NodeProcess | None = None
|
||||
|
||||
@property
|
||||
def transport(self) -> str:
|
||||
"""``"spi"`` — the loopback socket underneath is an implementation detail."""
|
||||
return "spi"
|
||||
|
||||
@property
|
||||
def endpoint(self) -> str:
|
||||
"""The SPI device the radio is on, which is how the radio is named and remembered."""
|
||||
return self._wiring.spidev
|
||||
|
||||
@property
|
||||
def wiring(self) -> SpiWiring:
|
||||
"""How the radio this device drives is wired."""
|
||||
return self._wiring
|
||||
|
||||
async def connect(self) -> None: # noqa: D102 - inherited docstring
|
||||
if self._mc is not None:
|
||||
return
|
||||
if self._node is None or not self._node.alive:
|
||||
self._node = await start_node(self._wiring, self._state, node_name=self._node_name)
|
||||
self._tcp_port = self._node.port
|
||||
try:
|
||||
await super().connect()
|
||||
except BaseException:
|
||||
await self._stop_node()
|
||||
raise
|
||||
|
||||
async def link_present(self) -> bool: # noqa: D102 - inherited docstring
|
||||
if self._node is not None and not self._node.alive:
|
||||
return False # the node died, so the radio is gone whatever the socket says
|
||||
return await super().link_present()
|
||||
|
||||
async def disconnect(self) -> None: # noqa: D102 - inherited docstring
|
||||
try:
|
||||
await super().disconnect()
|
||||
finally:
|
||||
await self._stop_node()
|
||||
|
||||
async def _stop_node(self) -> None:
|
||||
"""End the node, if one is running, and forget it."""
|
||||
node, self._node = self._node, None
|
||||
if node is not None:
|
||||
await node.stop()
|
||||
|
||||
def _no_response_message(self) -> str:
|
||||
"""The node started but never answered as a companion: point at its log."""
|
||||
where = self._node.log_path if self._node is not None else self._state / "node.log"
|
||||
return f"the radio node on {self._wiring.spidev} did not answer; its log is {where}"
|
||||
@@ -35,7 +35,7 @@ from typing import TYPE_CHECKING
|
||||
from rich.cells import cell_len
|
||||
from rich.text import Text
|
||||
|
||||
from ..core.config import DeviceProfile
|
||||
from ..core.config import DeviceProfile, SpiWiring
|
||||
from ..core.connection import DeviceAuthenticationError, DeviceCommandError
|
||||
from ..core.device_store import DeviceStore, RememberedDevice
|
||||
from ..core.discovery import (
|
||||
@@ -45,8 +45,10 @@ from ..core.discovery import (
|
||||
discover_devices,
|
||||
parse_tcp_endpoint,
|
||||
serial_device,
|
||||
spi_device,
|
||||
tcp_device,
|
||||
)
|
||||
from ..core.spiradio import spi_present
|
||||
from ..platforms import get_platform
|
||||
from .logo import load_logo
|
||||
from .menus import Lane, align_icons, column_header, fit_cells
|
||||
@@ -90,6 +92,10 @@ _SERIAL_ICON = "🔌"
|
||||
#: rather than a wired or Bluetooth link. Two cells like the serial plug, so it aligns the same.
|
||||
_TCP_ICON = "🌐"
|
||||
|
||||
#: TYPE-column glyph for a radio on the host's own SPI bus — a pin, because the radio is
|
||||
#: right here, on this machine. Two cells, aligning with the plug and the globe.
|
||||
_SPI_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.
|
||||
@@ -110,6 +116,8 @@ def _type_cell(device: DiscoveredDevice) -> Text:
|
||||
"""
|
||||
if device.is_tcp:
|
||||
return Text(" " + _TCP_ICON)
|
||||
if device.is_spi:
|
||||
return Text(" " + _SPI_ICON)
|
||||
if not device.is_ble:
|
||||
return Text(" " + _SERIAL_ICON)
|
||||
cell = Text()
|
||||
@@ -130,6 +138,8 @@ def _hardware_name(device: DiscoveredDevice) -> str:
|
||||
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"
|
||||
if device.is_spi:
|
||||
return device.name or "SPI radio"
|
||||
name = device.product or device.description or device.vendor_label or "Serial device"
|
||||
suffix = f"({device.port})"
|
||||
if name.endswith(suffix):
|
||||
@@ -281,6 +291,11 @@ async def _smoke_test(
|
||||
"Check the host and port — it may be unreachable, powered off, already "
|
||||
"connected elsewhere, or busy."
|
||||
)
|
||||
elif chosen.is_spi:
|
||||
reason = (
|
||||
"Its node started but never answered — its log is node.log in "
|
||||
"MeshTerm's radio folder."
|
||||
)
|
||||
elif chosen.is_ble:
|
||||
reason = (
|
||||
"It may be out of range, powered off, already connected elsewhere, or busy."
|
||||
@@ -385,6 +400,9 @@ async def prompt_device(
|
||||
# produced by the scan, so fold those in too — after the scanned set, so a port
|
||||
# pyserial *does* enumerate keeps its richer scanned row rather than the bare profile.
|
||||
listed += _profile_serial_devices(listed, profiles)
|
||||
# A radio on the SPI bus answers nothing until MeshTerm starts its node, so it is
|
||||
# listed from the device node's presence, the way a serial port is.
|
||||
listed += _spi_devices(listed, profiles)
|
||||
# Devices the user has told this splash to stop showing (h). Read each pass, so a
|
||||
# row hidden a moment ago is gone the next time the list is drawn — which is the
|
||||
# only feedback hiding needs.
|
||||
@@ -678,6 +696,42 @@ def _profile_serial_devices(
|
||||
return rebuilt
|
||||
|
||||
|
||||
def _spi_devices(
|
||||
listed: list[DiscoveredDevice],
|
||||
profiles: Mapping[str, DeviceProfile] | None,
|
||||
) -> list[DiscoveredDevice]:
|
||||
"""The radios on this machine's own SPI bus, as picker rows.
|
||||
|
||||
One row per ``transport = "spi"`` profile whose ``/dev/spidev*`` node exists, named by
|
||||
the profile; and, where no profile covers it, one for the uConsole AIO's device node when
|
||||
it exists, wired with the defaults. Nothing is probed to list them — a radio on the bus
|
||||
has no node running until one is chosen — so a row appears exactly when there is a device
|
||||
node to open. A device node already listed is not listed twice.
|
||||
|
||||
Args:
|
||||
listed: The devices already gathered, for de-duplication.
|
||||
profiles: The configured profiles, or ``None`` when none are loaded.
|
||||
|
||||
Returns:
|
||||
One SPI :class:`DiscoveredDevice` per radio not already listed.
|
||||
"""
|
||||
seen = {d.stable_id for d in listed}
|
||||
rows: list[DiscoveredDevice] = []
|
||||
wirings = [(p.spi or SpiWiring(), p.name) for p in (profiles or {}).values() if p.is_spi]
|
||||
covered = {wiring.spidev for wiring, _name in wirings}
|
||||
if SpiWiring().spidev not in covered:
|
||||
wirings.append((SpiWiring(), ""))
|
||||
for wiring, name in wirings:
|
||||
if not spi_present(wiring):
|
||||
continue
|
||||
device = spi_device(wiring, name=name)
|
||||
if device.stable_id in seen:
|
||||
continue
|
||||
seen.add(device.stable_id)
|
||||
rows.append(device)
|
||||
return rows
|
||||
|
||||
|
||||
async def _add_network_device(
|
||||
ui: Ui,
|
||||
store: DeviceStore,
|
||||
|
||||
+17
-2
@@ -363,6 +363,8 @@ def _device_label(ctx: AppContext, cache: dict) -> tuple[str, str]:
|
||||
where = "BLE"
|
||||
elif ctx.active_transport == "tcp":
|
||||
where = ctx.active_endpoint or "TCP"
|
||||
elif ctx.active_transport == "spi":
|
||||
where = "SPI"
|
||||
else:
|
||||
where = ctx.active_port or (sel.port if sel is not None else "") or ""
|
||||
cache["key"], cache["value"] = key, (name, where)
|
||||
@@ -730,6 +732,7 @@ async def _startup(ctx: AppContext) -> bool:
|
||||
if not (ctx.mock or ctx.explicit_selection):
|
||||
from ..core.connection import probe_device
|
||||
from ..core.discovery import DiscoveredDevice, discover_all
|
||||
from ..core.spiradio import state_dir
|
||||
from .device_picker import prompt_device
|
||||
from .logo import load_logo
|
||||
|
||||
@@ -750,7 +753,12 @@ async def _startup(ctx: AppContext) -> bool:
|
||||
# ``pin`` is what the picker's PIN dialog collected on a retry; fall back to any
|
||||
# ``--ble-pin`` supplied on the CLI for the first attempt.
|
||||
used = pin if pin is not None else ctx.ble_pin
|
||||
result = await probe_device(device, baudrate=baudrate, pin=used)
|
||||
spi_state = (
|
||||
state_dir(ctx.settings.config_dir, device.spi or ctx.spi_wiring_for(device.port))
|
||||
if device.is_spi
|
||||
else None
|
||||
)
|
||||
result = await probe_device(device, baudrate=baudrate, pin=used, spi_state=spi_state)
|
||||
if result is None:
|
||||
return None
|
||||
connection, info = result
|
||||
@@ -770,7 +778,14 @@ 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_tcp:
|
||||
if chosen.is_spi:
|
||||
# A reconnect rebuilds the device from the context, so it has to know which radio.
|
||||
# An SPI profile names its own; a bare row is the AIO's, which ``--spi`` resolves.
|
||||
ctx.spi_override = True
|
||||
ctx.tcp_override = None
|
||||
ctx.ble_override = None
|
||||
ctx.port_override = None
|
||||
elif chosen.is_tcp:
|
||||
ctx.tcp_override = chosen.target
|
||||
ctx.ble_override = None
|
||||
ctx.port_override = None
|
||||
|
||||
@@ -700,6 +700,7 @@ _GLYPH_MAP: dict[str, str] = {
|
||||
"🎧": "≈", # monitor — listening to the waveform
|
||||
"🗼": "▲", # repeater admin — the repeater mark itself
|
||||
"🔌": "~", # serial port — the cable
|
||||
"📍": "╨", # a radio on the host's SPI bus — the antenna on its board
|
||||
"👤": "%", # a person (two-circle silhouette)
|
||||
"👥": "%", # contacts — people
|
||||
"👋": "", # a wave in prose — the words carry it
|
||||
|
||||
@@ -39,6 +39,10 @@ third_party_notices = notices.write_third_party_notices(
|
||||
# the bundle exactly as it does in a checkout.
|
||||
datas = [
|
||||
("../meshterm/assets", "meshterm/assets"),
|
||||
# The SPI radio's node is run by path under *another* Python — the one with the radio
|
||||
# library, which this build doesn't carry — so it has to exist as a source file, beside
|
||||
# where `spiradio.node_script()` looks for it, not only as bytecode in the archive.
|
||||
("../meshterm/core/radionode.py", "meshterm/core"),
|
||||
# A one-file build is a *copy* of MeshTerm, and Apache-2.0 §4(a)/(d) want MeshTerm's
|
||||
# own LICENSE and NOTICE distributed with every copy — not folded into the app's own
|
||||
# assets, but sitting at the bundle root the way they sit at the repository root.
|
||||
|
||||
@@ -59,6 +59,14 @@ dev = [
|
||||
# not a gate: 0.16 formats Python inside Markdown and 0.15 does not, so an
|
||||
# unpinned `ruff>=0.4` had CI and a laptop disagreeing about a clean tree.
|
||||
"ruff>=0.16.6,<0.17",
|
||||
# The SPI radio's node, run for real in tests/test_radionode_live.py on a fake radio.
|
||||
# The bare library is pure Python everywhere; only the `hardware` extra is Linux-bound.
|
||||
"openhop-core>=1.1.3",
|
||||
]
|
||||
# A LoRa chip on this machine's own SPI bus (the uConsole AIO), driven by a node MeshTerm
|
||||
# runs itself — see meshterm/core/spiradio.py. Linux only, and nowhere else worth carrying.
|
||||
spi = [
|
||||
"openhop-core[hardware]>=1.1.3",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Repo-side tools. None of these ship in the wheel.
|
||||
|---|---|
|
||||
| `basemap-doctor.py` | Why a user's map has no basemap — certificates, DNS, proxy, or colour depth |
|
||||
| `picocalc/` | Calculinux device setup: console font, palette, Wi-Fi; `xiao-radio/` is the XIAO radio kit (firmware build, flashing, UART setup) |
|
||||
| `uconsole/` | The uConsole SPI bridge service |
|
||||
| `uconsole/` | The uConsole's always-on SPI bridge service (MeshTerm can also drive that radio directly, with no script at all — see `docs/uconsole.md`) |
|
||||
|
||||
## basemap-doctor.py
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The software node MeshTerm runs on an SPI radio (``meshterm/core/radionode.py``).
|
||||
|
||||
Two kinds of test. The first holds the node's contract with its parent and with the
|
||||
interpreter it runs under — it imports nothing from MeshTerm, reports one status line, and
|
||||
reads its state files back defensively. The second runs the node for real, on the actual
|
||||
radio library with a fake radio underneath, and talks to it through MeshTerm's own
|
||||
companion client: that is the only way to prove the thing this file exists for, which is
|
||||
that a channel written through MeshTerm is still there after the node restarts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import dataclasses
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from meshterm.core import radionode
|
||||
|
||||
NODE_SOURCE = Path(radionode.__file__)
|
||||
|
||||
|
||||
# --- the contract --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_node_imports_only_the_standard_library_and_the_radio_library() -> None:
|
||||
"""The node runs under *another* Python, by path, so it can import nothing of ours."""
|
||||
tree = ast.parse(NODE_SOURCE.read_text(encoding="utf-8"))
|
||||
names: set[str] = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
names |= {alias.name.split(".")[0] for alias in node.names}
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
assert node.level == 0, "a relative import only works inside the package"
|
||||
names.add((node.module or "").split(".")[0])
|
||||
foreign = {n for n in names if n not in sys.stdlib_module_names and n != "__future__"}
|
||||
assert foreign == set(), f"the node imports {sorted(foreign)}"
|
||||
# And the radio library only by name, at run time — importing it at the top would make
|
||||
# a missing library an ImportError traceback instead of the "runtime" report.
|
||||
assert radionode.RUNTIME == "openhop_core"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("lines", "kind"),
|
||||
[
|
||||
(["GPIO pin 25 is already in use by another process: [Errno 16]"], "busy"),
|
||||
(["Failed to setup: Device or resource busy"], "busy"),
|
||||
(["Permission denied for GPIO pin 24: ..."], "permission"),
|
||||
(["radio.begin() returned False"], "failed"),
|
||||
([], "failed"),
|
||||
],
|
||||
)
|
||||
def test_a_failed_begin_is_classified_by_what_the_library_logged(
|
||||
lines: list[str], kind: str
|
||||
) -> None:
|
||||
"""The library says why a pin failed only in a log line, so that is what is read."""
|
||||
assert radionode.classify_begin_failure(lines) == kind
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class _Prefs:
|
||||
"""A stand-in for the library's ``NodePrefs``: one field of each type it has."""
|
||||
|
||||
node_name: str = "pyMC"
|
||||
tx_power_dbm: int = 20
|
||||
latitude: float = 0.0
|
||||
default_scope_key: bytes = b""
|
||||
|
||||
|
||||
def test_prefs_round_trip_through_json() -> None:
|
||||
"""Every field type ``NodePrefs`` has comes back from ``prefs.json`` as it went in."""
|
||||
prefs = _Prefs(node_name="Lakeside", tx_power_dbm=17, latitude=45.5, default_scope_key=b"\x01")
|
||||
saved = json.loads(json.dumps(radionode.prefs_to_json(prefs)))
|
||||
loaded = _Prefs()
|
||||
radionode.apply_saved_prefs(loaded, saved)
|
||||
assert loaded == prefs
|
||||
|
||||
|
||||
def test_saved_prefs_take_only_known_fields_of_the_right_type() -> None:
|
||||
"""A retired field is ignored, and a hand-edited wrong value never reaches the radio."""
|
||||
prefs = _Prefs()
|
||||
radionode.apply_saved_prefs(
|
||||
prefs, {"node_name": "Ridge", "tx_power_dbm": "loud", "retired_knob": 3, "latitude": 1}
|
||||
)
|
||||
assert prefs == _Prefs(node_name="Ridge", latitude=1.0)
|
||||
radionode.apply_saved_prefs(prefs, ["not", "a", "dict"]) # a corrupt file: no change
|
||||
assert prefs.node_name == "Ridge"
|
||||
|
||||
|
||||
def test_saved_channels_skip_what_cannot_be_a_channel() -> None:
|
||||
"""A malformed or cleared entry in ``channels.json`` is skipped, never restored."""
|
||||
entries = [
|
||||
{"idx": 0, "name": "Public", "secret": "00" * 16},
|
||||
{"idx": 1, "name": "", "secret": "00" * 16}, # a cleared slot is not a channel
|
||||
{"idx": "two", "name": "Bad", "secret": "00"},
|
||||
{"idx": 3, "name": "Hex", "secret": "zz"},
|
||||
"garbage",
|
||||
]
|
||||
assert radionode.saved_channels(entries) == [(0, "Public", bytes(16))]
|
||||
assert radionode.saved_channels(None) == []
|
||||
|
||||
|
||||
def test_radio_kwargs_pass_only_what_the_constructor_accepts() -> None:
|
||||
"""An older library missing a knob gets the call without it, not a refusal."""
|
||||
accepted = {"bus_id", "reset_pin", "en_pins", "frequency", "tx_power"}
|
||||
wiring = {"bus_id": 1, "reset_pin": 25, "en_pins": None, "gpio_chip": 0}
|
||||
prefs = type(
|
||||
"P",
|
||||
(),
|
||||
{
|
||||
"frequency_hz": 869_525_000,
|
||||
"bandwidth_hz": 250_000,
|
||||
"spreading_factor": 11,
|
||||
"coding_rate": 5,
|
||||
"tx_power_dbm": 14,
|
||||
},
|
||||
)()
|
||||
assert radionode.radio_kwargs(accepted, wiring, prefs) == {
|
||||
"bus_id": 1,
|
||||
"reset_pin": 25,
|
||||
"frequency": 869_525_000,
|
||||
"tx_power": 14,
|
||||
}
|
||||
|
||||
|
||||
def test_an_identity_is_minted_once_and_then_kept(tmp_path: Path) -> None:
|
||||
"""A node's key is made the first time and read back every time after."""
|
||||
minted = iter([b"\x11" * 32, b"\x22" * 32])
|
||||
first = radionode.load_identity_seed(tmp_path, lambda: next(minted))
|
||||
again = radionode.load_identity_seed(tmp_path, lambda: next(minted))
|
||||
assert first == again == b"\x11" * 32
|
||||
assert (tmp_path / "identity.key").read_bytes() == first
|
||||
@@ -0,0 +1,181 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The SPI radio's node, run for real: the radio library with a fake radio underneath.
|
||||
|
||||
MeshTerm's own companion client talks to it over the loopback port exactly as it would on a
|
||||
uConsole. This is the only way to prove what the node exists for — that a channel written
|
||||
through MeshTerm is still there after the node restarts, which is the bug the node's state
|
||||
directory ended. Skipped where ``openhop_core`` isn't installed (it is in the dev extra).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from meshterm.core import radionode
|
||||
|
||||
openhop_core = pytest.importorskip("openhop_core")
|
||||
|
||||
|
||||
class _FakeRadio:
|
||||
"""Just enough of an SX1262 for the node to come up and sit listening."""
|
||||
|
||||
instances: list[_FakeRadio] = []
|
||||
|
||||
def __init__(self, **kwargs: object) -> None:
|
||||
self.kwargs = kwargs
|
||||
self.cleaned = False
|
||||
_FakeRadio.instances.append(self)
|
||||
|
||||
def begin(self) -> bool:
|
||||
return True
|
||||
|
||||
def cleanup(self) -> None:
|
||||
self.cleaned = True
|
||||
|
||||
async def send(self, data: bytes) -> None:
|
||||
return None
|
||||
|
||||
async def wait_for_rx(self) -> bytes:
|
||||
await asyncio.Event().wait()
|
||||
return b""
|
||||
|
||||
def set_rx_callback(self, callback: object) -> None:
|
||||
return None
|
||||
|
||||
def configure_radio(self, **kwargs: object) -> bool:
|
||||
self.kwargs.update(kwargs)
|
||||
return True
|
||||
|
||||
def set_tx_power(self, power: int) -> bool:
|
||||
self.kwargs["tx_power"] = power
|
||||
return True
|
||||
|
||||
def sleep(self) -> None:
|
||||
return None
|
||||
|
||||
def get_last_rssi(self) -> int:
|
||||
return -90
|
||||
|
||||
def get_last_snr(self) -> float:
|
||||
return 5.0
|
||||
|
||||
|
||||
def _fake_init(self, bus_id=1, reset_pin=25, frequency=0, tx_power=0, **kwargs): # noqa: ANN001, ANN202
|
||||
_FakeRadio.__init__(
|
||||
self, bus_id=bus_id, reset_pin=reset_pin, frequency=frequency, tx_power=tx_power, **kwargs
|
||||
)
|
||||
|
||||
|
||||
class _Node:
|
||||
"""One run of the node in this process, stopped on request instead of by stdin."""
|
||||
|
||||
def __init__(self, monkeypatch: pytest.MonkeyPatch, state: Path) -> None:
|
||||
import openhop_core.hardware.sx1262_wrapper as sx1262
|
||||
|
||||
fake = type("SX1262Radio", (_FakeRadio,), {"__init__": _fake_init})
|
||||
monkeypatch.setattr(sx1262, "SX1262Radio", fake)
|
||||
monkeypatch.setattr(radionode, "_check_device", lambda *a: None)
|
||||
self.stop = asyncio.Event()
|
||||
|
||||
async def until_stopped() -> None:
|
||||
await self.stop.wait()
|
||||
|
||||
monkeypatch.setattr(radionode, "_until_told_to_stop", until_stopped)
|
||||
self.state = state
|
||||
self.status: dict = {}
|
||||
self.task: asyncio.Task | None = None
|
||||
|
||||
async def __aenter__(self) -> int:
|
||||
ready = asyncio.Event()
|
||||
|
||||
def report(message: dict) -> None:
|
||||
self.status = message
|
||||
ready.set()
|
||||
|
||||
config = {"state_dir": str(self.state), "wiring": {"bus_id": 1}, "seed": {}}
|
||||
self.task = asyncio.create_task(radionode.run_node(config, report))
|
||||
waiter = asyncio.create_task(ready.wait())
|
||||
await asyncio.wait({self.task, waiter}, timeout=20, return_when=asyncio.FIRST_COMPLETED)
|
||||
if self.task.done():
|
||||
self.task.result() # surface the node's own failure
|
||||
assert self.status.get("event") == "ready", self.status
|
||||
return int(self.status["port"])
|
||||
|
||||
async def __aexit__(self, *exc: object) -> None:
|
||||
self.stop.set()
|
||||
assert self.task is not None
|
||||
assert await asyncio.wait_for(self.task, timeout=20) == 0
|
||||
|
||||
|
||||
async def _client(port: int): # noqa: ANN202
|
||||
from meshterm.core.connection import MeshCoreDevice
|
||||
|
||||
device = MeshCoreDevice(transport="tcp", host="127.0.0.1", tcp_port=port)
|
||||
await device.connect()
|
||||
return device
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channels_name_and_radio_survive_a_restart(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The bug this node was built to end: a channel added through MeshTerm is forgotten."""
|
||||
secret = bytes(range(16))
|
||||
async with _Node(monkeypatch, tmp_path) as port:
|
||||
device = await _client(port)
|
||||
try:
|
||||
await device.set_channel(2, "Lakeside ops", secret)
|
||||
await device.set_name("Lakeside")
|
||||
await device.set_radio(869.525, 250.0, 11, 5)
|
||||
finally:
|
||||
await device.disconnect()
|
||||
assert _FakeRadio.instances[-1].cleaned, "the radio must be released on the way out"
|
||||
|
||||
async with _Node(monkeypatch, tmp_path) as port:
|
||||
device = await _client(port)
|
||||
try:
|
||||
channel = await device.get_channel(2)
|
||||
info = await device.get_self_info()
|
||||
finally:
|
||||
await device.disconnect()
|
||||
assert channel is not None and channel.get("channel_name") == "Lakeside ops"
|
||||
assert bytes(channel.get("channel_secret") or b"")[:16] == secret
|
||||
assert info.get("name") == "Lakeside"
|
||||
# The chip is brought up on the saved radio, not the seed.
|
||||
assert _FakeRadio.instances[-1].kwargs["frequency"] == 869_525_000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_cleared_channel_stays_cleared(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Clearing a slot through MeshTerm removes it from what the node restores."""
|
||||
async with _Node(monkeypatch, tmp_path) as port:
|
||||
device = await _client(port)
|
||||
try:
|
||||
await device.set_channel(1, "#gone", bytes(16))
|
||||
await device.set_channel(1, "", None)
|
||||
finally:
|
||||
await device.disconnect()
|
||||
saved = json.loads((tmp_path / "channels.json").read_text(encoding="utf-8"))
|
||||
assert [c["idx"] for c in saved] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_identity_is_the_same_node_after_a_restart(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The node comes back with the key it had, so it is still the same contact to everyone."""
|
||||
keys = []
|
||||
for _ in range(2):
|
||||
async with _Node(monkeypatch, tmp_path) as port:
|
||||
device = await _client(port)
|
||||
try:
|
||||
keys.append((await device.get_self_info()).get("public_key"))
|
||||
finally:
|
||||
await device.disconnect()
|
||||
assert keys[0] and keys[0] == keys[1]
|
||||
@@ -0,0 +1,438 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""MeshTerm's half of the SPI radio: wiring, finding the node's Python, and its lifetime.
|
||||
|
||||
The node itself is :mod:`tests.test_radionode`. Here a stand-in node script plays its part —
|
||||
one status line on stdout, then wait for stdin to close — so the protocol between the two
|
||||
processes, the error wording and the shutdown ladder are exercised on any platform.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from rich.console import Console
|
||||
|
||||
from meshterm.context import AppContext
|
||||
from meshterm.core import spiradio
|
||||
from meshterm.core.admin_store import AdminStore
|
||||
from meshterm.core.config import DeviceProfile, Settings, SpiWiring
|
||||
from meshterm.core.device_store import DeviceStore
|
||||
from meshterm.core.discovery import TRANSPORT_SPI, spi_device
|
||||
from meshterm.persistence.repository import Repository
|
||||
|
||||
# --- wiring --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_default_wiring_is_the_uconsole_aio() -> None:
|
||||
"""A profile with no ``spi`` table is the AIO v1, which is what the defaults describe."""
|
||||
wiring = SpiWiring()
|
||||
assert (wiring.bus_id, wiring.reset_pin, wiring.busy_pin, wiring.irq_pin) == (1, 25, 24, 26)
|
||||
assert wiring.use_dio2_rf and wiring.use_dio3_tcxo and wiring.en_pins == ()
|
||||
assert wiring.spidev == "/dev/spidev1.0"
|
||||
|
||||
|
||||
def test_a_wiring_table_states_only_what_differs() -> None:
|
||||
"""The AIO v2's one difference is its power-enable pin; nothing else moves."""
|
||||
wiring = SpiWiring.from_toml({"en_pins": [27]})
|
||||
assert wiring == SpiWiring(en_pins=(27,))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("table", "complaint"),
|
||||
[
|
||||
({"irq_pn": 22}, "unknown SPI wiring key(s): irq_pn"),
|
||||
({"reset_pin": "25"}, "reset_pin = '25' is not a int"),
|
||||
({"use_dio2_rf": 1}, "use_dio2_rf = 1 is not a bool"),
|
||||
({"en_pins": 27}, "en_pins = 27 is not a tuple"),
|
||||
({"busy_pin": True}, "busy_pin = True is not a int"),
|
||||
],
|
||||
)
|
||||
def test_a_wiring_mistake_is_refused_not_ignored(table: dict, complaint: str) -> None:
|
||||
"""A misspelt pin would otherwise leave a default in force and a deaf radio."""
|
||||
with pytest.raises(ValueError, match=complaint.replace("(", r"\(").replace(")", r"\)")):
|
||||
SpiWiring.from_toml(table)
|
||||
|
||||
|
||||
def test_a_profile_with_an_spi_table_is_an_spi_profile(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The ``spi`` table implies the transport, the way ``host`` implies TCP."""
|
||||
monkeypatch.setenv("MESHTERM_HOME", str(tmp_path))
|
||||
(tmp_path / "config.toml").write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[profiles.aio2.spi]
|
||||
en_pins = [27]
|
||||
|
||||
[profiles.aio]
|
||||
transport = "spi"
|
||||
"""
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
profiles = Settings.load().profiles
|
||||
assert profiles["aio2"].is_spi and profiles["aio2"].spi == SpiWiring(en_pins=(27,))
|
||||
assert profiles["aio"].is_spi and profiles["aio"].spi == SpiWiring()
|
||||
|
||||
|
||||
def test_a_bad_wiring_table_names_its_profile(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A wiring error is reported against the profile it is in, not as a bare key."""
|
||||
monkeypatch.setenv("MESHTERM_HOME", str(tmp_path))
|
||||
(tmp_path / "config.toml").write_text("[profiles.aio.spi]\nirq = 1\n", encoding="utf-8")
|
||||
with pytest.raises(ValueError, match=r"\[profiles\.aio\.spi\]"):
|
||||
Settings.load()
|
||||
|
||||
|
||||
def test_state_lives_under_the_spi_device_not_the_profile(tmp_path: Path) -> None:
|
||||
"""One radio is one node however it was reached, so its key is filed by device node."""
|
||||
assert spiradio.state_dir(tmp_path, SpiWiring()) == tmp_path / "radio" / "spidev1.0"
|
||||
assert spiradio.state_dir(tmp_path, SpiWiring(bus_id=0, cs_id=1)).name == "spidev0.1"
|
||||
|
||||
|
||||
def test_an_spi_radio_lists_like_a_device_on_its_node() -> None:
|
||||
"""The picker row is named by the device node, which is also its remembered identity."""
|
||||
device = spi_device(SpiWiring(), name="aio")
|
||||
assert device.transport == TRANSPORT_SPI and device.is_spi
|
||||
assert device.target == "/dev/spidev1.0"
|
||||
assert device.stable_id == "spi:/dev/spidev1.0"
|
||||
assert device.label == "aio (/dev/spidev1.0)"
|
||||
assert spi_device(SpiWiring()).label == "SPI radio (/dev/spidev1.0)"
|
||||
|
||||
|
||||
# --- choosing the radio --------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def contexts(tmp_path: Path): # noqa: ANN201 - a factory fixture
|
||||
"""Build contexts over a scratch config directory, closing their databases after."""
|
||||
made: list[AppContext] = []
|
||||
|
||||
def make(**kwargs: object) -> AppContext:
|
||||
profiles = kwargs.pop("profiles", {})
|
||||
settings = Settings(
|
||||
config_dir=tmp_path,
|
||||
db_path=tmp_path / "spi.db",
|
||||
profiles=profiles, # type: ignore[arg-type]
|
||||
)
|
||||
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"),
|
||||
**kwargs, # type: ignore[arg-type]
|
||||
)
|
||||
made.append(ctx)
|
||||
return ctx
|
||||
|
||||
yield make
|
||||
for ctx in made:
|
||||
ctx.repo.close()
|
||||
|
||||
|
||||
def test_spi_flag_takes_the_spi_profile_wiring(contexts) -> None: # noqa: ANN001
|
||||
"""``--spi`` means the radio on this machine, wired as its profile says when there is one."""
|
||||
wired = SpiWiring(en_pins=(27,))
|
||||
profiles = {"aio2": DeviceProfile(name="aio2", transport="spi", spi=wired)}
|
||||
assert contexts(spi_override=True, profiles=profiles)._resolve_spi() == wired
|
||||
assert contexts(spi_override=True)._resolve_spi() == SpiWiring()
|
||||
assert contexts(spi_override=True).active_transport == "spi"
|
||||
|
||||
|
||||
def test_another_named_radio_is_not_the_spi_radio(contexts) -> None: # noqa: ANN001
|
||||
"""A port, an address or a host named outright means the session is about that radio."""
|
||||
for override in (
|
||||
{"port_override": "COM7"},
|
||||
{"tcp_override": "10.0.0.2"},
|
||||
{"ble_override": "AA"},
|
||||
):
|
||||
assert contexts(**override)._resolve_spi() is None
|
||||
|
||||
|
||||
def test_a_listed_radio_is_wired_by_the_profile_on_its_node(contexts) -> None: # noqa: ANN001
|
||||
"""A remembered or listed radio is known by its node, and its pins come from that."""
|
||||
other = SpiWiring(bus_id=0, reset_pin=17)
|
||||
profiles = {"hat": DeviceProfile(name="hat", transport="spi", spi=other)}
|
||||
ctx = contexts(profiles=profiles)
|
||||
assert ctx.spi_wiring_for("/dev/spidev0.0") == other
|
||||
assert ctx.spi_wiring_for("/dev/spidev1.0") == SpiWiring()
|
||||
|
||||
|
||||
# --- finding a Python for the node ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_named_python_is_the_only_candidate(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Naming an interpreter is a decision; falling back past it would hide that it fails."""
|
||||
probed: list[str] = []
|
||||
monkeypatch.setattr(spiradio, "_can_import_runtime", lambda p: probed.append(p) or False)
|
||||
with pytest.raises(spiradio.SpiRadioError) as err:
|
||||
spiradio.find_runtime(SpiWiring(python="/opt/radio/bin/python"))
|
||||
assert err.value.kind == "runtime"
|
||||
assert probed == ["/opt/radio/bin/python"]
|
||||
|
||||
|
||||
def test_the_first_python_with_the_library_wins(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Candidates are tried in order, and the search stops at the first that can import it."""
|
||||
monkeypatch.setattr(spiradio, "_runtime_candidates", lambda w: ["/a", "/b", "/c"])
|
||||
monkeypatch.setattr(spiradio, "_can_import_runtime", lambda p: p != "/a")
|
||||
assert spiradio.find_runtime(SpiWiring()) == "/b"
|
||||
|
||||
|
||||
def test_a_frozen_build_hands_the_node_a_clean_environment(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Another Python must load its own libraries, not the one-file build's unpacked copies."""
|
||||
monkeypatch.setattr(sys, "frozen", True, raising=False)
|
||||
monkeypatch.setenv("_PYI_APPLICATION_HOME_DIR", "/tmp/_MEI1")
|
||||
monkeypatch.setenv("_MEIPASS2", "/tmp/_MEI1")
|
||||
monkeypatch.setenv("LD_LIBRARY_PATH", "/tmp/_MEI1")
|
||||
monkeypatch.setenv("LD_LIBRARY_PATH_ORIG", "/usr/local/lib")
|
||||
env = spiradio.child_env()
|
||||
assert "_MEIPASS2" not in env and not any(k.startswith("_PYI") for k in env)
|
||||
assert env["LD_LIBRARY_PATH"] == "/usr/local/lib"
|
||||
assert "LD_LIBRARY_PATH_ORIG" not in env
|
||||
monkeypatch.delenv("LD_LIBRARY_PATH_ORIG")
|
||||
assert "LD_LIBRARY_PATH" not in spiradio.child_env()
|
||||
|
||||
|
||||
# --- first use: the bridge's node carries over ---------------------------------------------
|
||||
|
||||
|
||||
def _bridge_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""An XDG data home holding a bridge's state, with the service's radio settings stubbed."""
|
||||
data = tmp_path / "share"
|
||||
monkeypatch.setenv("XDG_DATA_HOME", str(data))
|
||||
monkeypatch.setattr(spiradio, "_bridge_radio_seed", lambda: {"frequency_hz": 869_525_000})
|
||||
bridge = data / "meshterm-spi-bridge"
|
||||
bridge.mkdir(parents=True)
|
||||
(bridge / "identity.key").write_bytes(b"\xbb" * 32)
|
||||
(bridge / "contacts.json").write_text('[{"public_key": "ab", "name": "Ridge"}]')
|
||||
return data
|
||||
|
||||
|
||||
def test_the_bridge_node_carries_over_the_first_time(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Identity, contacts, name and radio: the node is the one everybody already knows."""
|
||||
_bridge_home(tmp_path, monkeypatch)
|
||||
state = tmp_path / "radio" / "spidev1.0"
|
||||
carried = spiradio.import_bridge_state(state)
|
||||
assert len(carried) == 3
|
||||
assert (state / "identity.key").read_bytes() == b"\xbb" * 32
|
||||
assert json.loads((state / "contacts.json").read_text())[0]["name"] == "Ridge"
|
||||
prefs = json.loads((state / "prefs.json").read_text())
|
||||
assert prefs == {"node_name": "uConsole", "frequency_hz": 869_525_000}
|
||||
assert spiradio.import_bridge_state(state) == [], "never twice: the node has its own now"
|
||||
|
||||
|
||||
def test_the_gui_key_wins_over_the_bridge_own(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The bridge shares the meshcore-uconsole GUI's key when there is one, so that is it."""
|
||||
data = _bridge_home(tmp_path, monkeypatch)
|
||||
(data / "meshcore-uconsole").mkdir()
|
||||
(data / "meshcore-uconsole" / "identity.key").write_bytes(b"\xcc" * 32)
|
||||
state = tmp_path / "radio" / "spidev1.0"
|
||||
spiradio.import_bridge_state(state)
|
||||
assert (state / "identity.key").read_bytes() == b"\xcc" * 32
|
||||
|
||||
|
||||
def test_no_bridge_means_nothing_carried(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Without a key to inherit the node mints its own, and nothing else is copied either."""
|
||||
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "empty"))
|
||||
state = tmp_path / "radio" / "spidev1.0"
|
||||
assert spiradio.import_bridge_state(state) == []
|
||||
assert not state.exists()
|
||||
|
||||
|
||||
# --- the error a person reads --------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kind", "holder", "says"),
|
||||
[
|
||||
("busy", "bridge", "systemctl --user stop meshterm-spi-bridge"),
|
||||
("busy", "console", "meshcore-console has the radio open"),
|
||||
("busy", None, "sudo lsof /dev/gpiochip0"),
|
||||
("runtime", None, "pipx inject mesh-term 'openhop-core[hardware]'"),
|
||||
("no-spi", None, "dtoverlay=spi1-1cs"),
|
||||
("permission", None, "sudo usermod -aG spi,gpio $USER"),
|
||||
],
|
||||
)
|
||||
def test_every_failure_says_what_to_do(kind: str, holder: str | None, says: str) -> None:
|
||||
"""Each way the node can fail to start comes with the command that fixes it."""
|
||||
assert says in spiradio.explain(kind, "detail", SpiWiring(), holder)
|
||||
|
||||
|
||||
# --- the node process ----------------------------------------------------------------------
|
||||
|
||||
_READY = """
|
||||
import json, sys
|
||||
print(json.dumps({"event": "ready", "port": 4321, "public_key": "ab" * 32}), flush=True)
|
||||
sys.stdin.buffer.read()
|
||||
"""
|
||||
|
||||
_REFUSES = """
|
||||
import json
|
||||
message = "no access to /dev/spidev1.0"
|
||||
print(json.dumps({"event": "error", "kind": "permission", "message": message}))
|
||||
"""
|
||||
|
||||
_SILENT = "import sys\nsys.exit(3)\n"
|
||||
|
||||
_DEAF = """
|
||||
import json, time
|
||||
print(json.dumps({"event": "ready", "port": 4321}), flush=True)
|
||||
while True:
|
||||
time.sleep(1)
|
||||
"""
|
||||
|
||||
|
||||
def _node(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source: str) -> None:
|
||||
"""Stand ``source`` in for the node script, run by this interpreter on "Linux"."""
|
||||
script = tmp_path / "node.py"
|
||||
script.write_text(source, encoding="utf-8")
|
||||
monkeypatch.setattr(spiradio, "node_script", lambda: script)
|
||||
monkeypatch.setattr(spiradio, "_on_linux", lambda: True)
|
||||
monkeypatch.setattr(spiradio, "radio_holder", lambda: None)
|
||||
monkeypatch.setattr(spiradio, "find_runtime", lambda wiring: sys.executable)
|
||||
monkeypatch.setattr(spiradio, "_bridge_radio_seed", dict)
|
||||
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "no-bridge"))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_ready_node_reports_its_port_and_leaves_when_asked(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The node's one line is its port; closing its stdin is all it takes to end it."""
|
||||
_node(monkeypatch, tmp_path, _READY)
|
||||
node = await spiradio.start_node(SpiWiring(), tmp_path / "state", node_name="Test")
|
||||
assert (node.port, node.public_key) == (4321, "ab" * 32) and node.alive
|
||||
await node.stop()
|
||||
assert not node.alive and node.process.returncode == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_refusal_arrives_as_its_kind_with_the_fix(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The node's error line becomes an actionable error, not "didn't answer"."""
|
||||
_node(monkeypatch, tmp_path, _REFUSES)
|
||||
with pytest.raises(spiradio.SpiRadioError) as err:
|
||||
await spiradio.start_node(SpiWiring(), tmp_path / "state", node_name="Test")
|
||||
assert err.value.kind == "permission"
|
||||
assert "usermod -aG spi,gpio" in str(err.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_node_that_dies_silently_points_at_its_log(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""With nothing said, the log is the one place the reason can be."""
|
||||
_node(monkeypatch, tmp_path, _SILENT)
|
||||
with pytest.raises(spiradio.SpiRadioError) as err:
|
||||
await spiradio.start_node(SpiWiring(), tmp_path / "state", node_name="Test")
|
||||
assert err.value.kind == "failed" and "node.log" in str(err.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_node_deaf_to_its_stdin_is_ended_anyway(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A wedged node never holds the radio past a quit: the signals end it."""
|
||||
_node(monkeypatch, tmp_path, _DEAF)
|
||||
monkeypatch.setattr(spiradio, "STOP_GRACE_S", 0.3)
|
||||
node = await spiradio.start_node(SpiWiring(), tmp_path / "state", node_name="Test")
|
||||
await node.stop()
|
||||
assert not node.alive
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_known_holder_is_named_before_any_node_starts(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The bridge service holding the radio is said at once, with how to stop it."""
|
||||
_node(monkeypatch, tmp_path, _READY)
|
||||
monkeypatch.setattr(spiradio, "radio_holder", lambda: "bridge")
|
||||
with pytest.raises(spiradio.SpiRadioError, match="systemctl --user stop"):
|
||||
await spiradio.start_node(SpiWiring(), tmp_path / "state", node_name="Test")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_only_linux_drives_an_spi_radio(tmp_path: Path) -> None:
|
||||
"""Anywhere else the radio can't be there, and the reason is the platform."""
|
||||
if sys.platform.startswith("linux"):
|
||||
pytest.skip("this is Linux")
|
||||
with pytest.raises(spiradio.SpiRadioError) as err:
|
||||
await spiradio.start_node(SpiWiring(), tmp_path, node_name="Test")
|
||||
assert err.value.kind == "unsupported"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_device_ends_its_node_when_the_connection_fails(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A node whose companion never answers must not be left holding the radio."""
|
||||
_node(monkeypatch, tmp_path, _READY)
|
||||
started: list[spiradio.NodeProcess] = []
|
||||
real_start = spiradio.start_node
|
||||
|
||||
async def start(*args: object, **kwargs: object) -> spiradio.NodeProcess:
|
||||
node = await real_start(*args, **kwargs) # type: ignore[arg-type]
|
||||
started.append(node)
|
||||
return node
|
||||
|
||||
async def no_companion(self: object) -> None:
|
||||
raise spiradio.DeviceCommandError("no answer")
|
||||
|
||||
monkeypatch.setattr(spiradio, "start_node", start)
|
||||
monkeypatch.setattr(spiradio.MeshCoreDevice, "connect", no_companion)
|
||||
device = spiradio.SpiRadioDevice(SpiWiring(), tmp_path / "state")
|
||||
assert device.transport == "spi" and device.endpoint == "/dev/spidev1.0"
|
||||
with pytest.raises(spiradio.DeviceCommandError):
|
||||
await device.connect()
|
||||
assert started and not started[0].alive
|
||||
|
||||
|
||||
# --- where it shows up ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_picker_lists_each_radio_whose_device_node_exists(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A profile's radio by its name; the AIO's node on its own when no profile covers it."""
|
||||
from meshterm.ui import device_picker
|
||||
|
||||
present = {"/dev/spidev1.0", "/dev/spidev0.0"}
|
||||
monkeypatch.setattr(device_picker, "spi_present", lambda w: w.spidev in present)
|
||||
hat = SpiWiring(bus_id=0, reset_pin=17)
|
||||
profiles = {
|
||||
"hat": DeviceProfile(name="hat", transport="spi", spi=hat),
|
||||
"gone": DeviceProfile(name="gone", transport="spi", spi=SpiWiring(bus_id=3)),
|
||||
}
|
||||
rows = device_picker._spi_devices([], profiles)
|
||||
assert [(r.port, r.name) for r in rows] == [("/dev/spidev0.0", "hat"), ("/dev/spidev1.0", None)]
|
||||
# A profile on the AIO's own node takes that row instead of a nameless one.
|
||||
profiles["aio"] = DeviceProfile(name="aio", transport="spi")
|
||||
rows = device_picker._spi_devices([], profiles)
|
||||
assert [r.name for r in rows] == ["hat", "aio"]
|
||||
# And a radio already in the list is not listed twice.
|
||||
assert device_picker._spi_devices(rows, profiles) == []
|
||||
|
||||
|
||||
def test_spi_and_another_radio_on_one_command_line_is_a_usage_error() -> None:
|
||||
"""The SPI radio is on this machine, and every other flag names one that isn't."""
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from meshterm.cli import app
|
||||
|
||||
result = CliRunner().invoke(app, ["--spi", "--port", "COM7", "info"])
|
||||
assert result.exit_code == 2
|
||||
assert "--spi and --port name different devices" in result.output
|
||||
Reference in new issue
Block a user