diff --git a/docs/devices/cardputer-zero.md b/docs/devices/cardputer-zero.md index 1feced1..acaafbb 100644 --- a/docs/devices/cardputer-zero.md +++ b/docs/devices/cardputer-zero.md @@ -95,11 +95,36 @@ real size. Closing the window quits MeshTerm. ## Radios -The Cardputer Zero has no LoRa radio built in. Once MeshTerm runs on it, there will be -three ways to add one: +The Cardputer Zero has no LoRa radio built in. There are three ways to add one: | Radio | Status | | --- | --- | +| M5Stack's **Cap LoRa-1262** add-on board | Works, with no setup. MeshTerm runs the mesh node itself while it's open, the same way it does on a uConsole. | | A MeshCore companion on USB | Expected to work as on any Linux computer. | | A MeshCore companion over Bluetooth | Expected to work as on any Linux computer. | -| M5Stack's **Cap LoRa-1262** add-on board | Not wired up. Its pins on the Cardputer Zero are known, but MeshTerm still needs two setup steps it can't do yet: switching on the board's antenna chip, and freeing two of the expansion header's pins from the USB port that shares them. | + +### The Cap LoRa-1262 + +Push the Cap onto the expansion header at the back, then start MeshTerm. The device screen +lists it as **Cap LoRa-1262**, and `meshterm --spi` reaches it from the command line. + +The Cap has no MeshCore firmware of its own: it's just a radio chip. So while MeshTerm is +open, MeshTerm *is* the node, the way it is on a uConsole's AIO board. It needs the radio +library installed beside MeshTerm: + +```bash +pip install 'mesh-term[spi]' +``` + +When MeshTerm connects, it does three things the Cardputer Zero needs before the radio +answers. It switches on the power to the expansion header, which is off until something +asks for it. It makes sure two of the header's pins are connected to the radio and not to +the USB port that shares them. And it switches on the Cap's antenna path. When MeshTerm +quits, it switches the header's power back off, so the Cap doesn't drain the battery +while nothing is using it. + +A new node starts on MeshCore's US/Canada settings (910.525 MHz). Anywhere else, change +them on **Device config** before you send anything. The node's key, contacts, and channels +are kept in `~/.meshterm/radio/spidev0.1/`. + +The Cap also carries a GPS. MeshTerm doesn't read it yet. diff --git a/docs/devices/uconsole.md b/docs/devices/uconsole.md index f374da0..76fb9bc 100644 --- a/docs/devices/uconsole.md +++ b/docs/devices/uconsole.md @@ -283,6 +283,8 @@ en_pins = [27] # the AIO v2 needs this | `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]`.** | +| `leds` | `[]` | Switches the board's device tree exposes as LEDs (under `/sys/class/leds/`), each written as `"name=brightness"`. They are set before the chip is touched and put back as they were when MeshTerm lets go. The Cardputer Zero powers its expansion header this way; its Cap needs no profile, but this is what one would say: `["ext_5v_out=1", "ext_usb_gpio_fun=0"]`. | +| `pi4io_bus`, `pi4io_address`, `pi4io_high` | `-1`, `0x43`, `[]` | A PI4IOE5V6408 I/O expander that switches the radio's antenna path: its I2C bus (`-1` for none), its address, and the pins to drive high. | | `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. | | `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. | diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 1e023ff..c27305a 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -79,9 +79,13 @@ itself — it runs the node while it is connected and lets go of the radio when It needs Linux and the radio library; [the uConsole manual](../devices/uconsole.md#step-2--install-the-radio-library) shows how to install that. -**An AIO v1 needs no configuration.** Its wiring is MeshTerm's default, so whenever -`/dev/spidev1.0` exists the device screen lists it as **SPI radio**, and `meshterm --spi` -reaches it. Any other board is added with a profile that states how it is wired. +**Two boards need no configuration.** An AIO v1's wiring is MeshTerm's default, so +whenever `/dev/spidev1.0` exists the device screen lists it as **SPI radio**. M5Stack's +Cap LoRa-1262 on a Cardputer Zero ships with MeshTerm too, and is listed as **Cap +LoRa-1262** on a Cardputer Zero (see [the Cardputer Zero page](../devices/cardputer-zero.md#the-cap-lora-1262)). +Either way, `meshterm --spi` reaches it. Any other board is added with a profile that +states how it is wired, and a profile on the same `/dev/spidev*` replaces the shipped +wiring. **Why a profile, and not a prompt on the device screen.** A USB companion describes itself: plug it in and there is nothing to ask. An SPI radio says nothing about how it is wired, and diff --git a/meshterm/context.py b/meshterm/context.py index 4badcac..883e252 100644 --- a/meshterm/context.py +++ b/meshterm/context.py @@ -792,16 +792,19 @@ class AppContext: ) 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. + """The wiring for the radio on ``spidev``: a profile's, a shipped board's, 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). + from whichever SPI profile is on that node; with none, from the board MeshTerm knows + that node on when this machine is that board (the Cardputer Zero's Cap); and + otherwise the defaults are the only wiring there is. """ + from .core.spiradio import builtin_wiring + 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() + return builtin_wiring(spidev) or SpiWiring() def _resolve_ble_endpoint(self) -> tuple[str | None, str | None]: """Return the ``(address, pin)`` to open over Bluetooth, or ``(None, None)`` for serial. diff --git a/meshterm/core/config.py b/meshterm/core/config.py index 251dc65..408575f 100644 --- a/meshterm/core/config.py +++ b/meshterm/core/config.py @@ -18,6 +18,7 @@ from __future__ import annotations import os import sys +import typing from dataclasses import dataclass, field from pathlib import Path from typing import Any, ClassVar @@ -94,6 +95,20 @@ class SpiWiring: 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. + leds: Switches the kernel exposes as LEDs (``/sys/class/leds/``), each + ``"name=brightness"``, set before the chip is touched and put back as they were + when the node ends. A board whose device tree hands its power and pin-routing + switches to ``gpio-leds`` is driven through them, because that driver holds the + lines and a GPIO request for them would be refused. The Cardputer Zero's Cap + LoRa-1262 needs two: ``ext_5v_out=1`` powers the header the Cap sits on, and + ``ext_usb_gpio_fun=0`` keeps two of that header's pins on GPIO rather than USB — + at ``1`` the Cap's reset line is cut and the chip sits in reset. Empty for none. + pi4io_bus: The I2C bus of a PI4IOE5V6408 expander the board switches its radio's + RF path with, or ``-1`` (the default) for none. + pi4io_address: That expander's address: ``0x43`` with its ADDR pin low, ``0x44`` + with it high. + pi4io_high: The expander's pins (0–7) driven high before the chip is touched; every + other pin is left an input. 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. @@ -112,6 +127,10 @@ class SpiWiring: txen_pin: int = -1 rxen_pin: int = -1 en_pins: tuple[int, ...] = () + leds: tuple[str, ...] = () + pi4io_bus: int = -1 + pi4io_address: int = 0x43 + pi4io_high: tuple[int, ...] = () use_dio2_rf: bool = True use_dio3_tcxo: bool = True is_waveshare: bool = False @@ -144,6 +163,7 @@ class SpiWiring: unknown = sorted(set(table) - set(known)) if unknown: raise ValueError(f"unknown SPI wiring key(s): {', '.join(unknown)}") + hints = typing.get_type_hints(cls) values: dict[str, Any] = {} for key, raw in table.items(): default = getattr(cls(), key) @@ -152,8 +172,9 @@ class SpiWiring: elif isinstance(default, int): ok = isinstance(raw, int) and not isinstance(raw, bool) elif isinstance(default, tuple): + item = typing.get_args(hints[key])[0] # what the list holds: pins or switches ok = isinstance(raw, list) and all( - isinstance(p, int) and not isinstance(p, bool) for p in raw + isinstance(p, item) and not isinstance(p, bool) for p in raw ) raw = tuple(raw) if ok else raw else: @@ -161,6 +182,10 @@ class SpiWiring: if not ok: raise ValueError(f"SPI wiring {key} = {raw!r} is not a {type(default).__name__}") values[key] = raw + for entry in values.get("leds", ()): + name, sep, brightness = entry.partition("=") + if not (name and sep and brightness.isdigit()): + raise ValueError(f"SPI wiring leds entry {entry!r} is not name=brightness") return cls(**values) @property diff --git a/meshterm/core/radionode.py b/meshterm/core/radionode.py index 259d7c0..4e2d948 100644 --- a/meshterm/core/radionode.py +++ b/meshterm/core/radionode.py @@ -78,9 +78,10 @@ log = logging.getLogger("radionode") 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). + Kinds: ``runtime`` (the radio library is missing or too old), ``no-spi`` / ``no-gpio`` / + ``no-i2c`` (the device node doesn't exist), ``permission`` (it exists but this user + can't open it), ``busy`` (another program holds the radio's pins), ``absent`` (the board + is there but the radio on it doesn't answer), and ``failed`` (anything else). """ def __init__(self, kind: str, message: str) -> None: @@ -263,6 +264,120 @@ def _check_device(path: str, missing_kind: str, what: str) -> None: raise NodeError("permission", f"no read/write permission on {path}") +# --- the board around the chip ------------------------------------------------------------- + +#: Where the kernel puts the switches a device tree hands to ``gpio-leds``. +LEDS = Path("/sys/class/leds") + +#: How long a header that was just powered gets before anything on it is spoken to. The +#: Cap's regulator and expander are up well inside this; the chip's own reset follows anyway. +POWER_SETTLE_S = 0.1 + +#: ``I2C_SLAVE``: address the open ``/dev/i2c-*`` at one device. Refused (``EBUSY``) while a +#: kernel driver is bound to that address, which is the right answer — it is then not ours. +_I2C_SLAVE = 0x0703 + +#: The PI4IOE5V6408's registers, and the manufacturer field of its ID register (bits 7–5), +#: which is how a different chip at the same address is told apart. +_PI4IO_ID, _PI4IO_DIRECTION, _PI4IO_OUTPUT, _PI4IO_HIGH_Z = 0x01, 0x03, 0x05, 0x07 +_PI4IO_MAKER = 0b101 + + +def set_leds(entries: list[str], root: Path = LEDS) -> list[tuple[Path, str]]: + """Set each ``name=brightness`` switch, and return what each read before, to put back. + + A switch that is missing means a wiring written for another board; one this user can't + write is the ``gpio`` group the radio's pins need anyway. + """ + previous: list[tuple[Path, str]] = [] + for entry in entries: + name, _, value = entry.partition("=") + path = root / name / "brightness" + if not path.exists(): + raise NodeError("failed", f"{path} does not exist — this board has no {name} switch") + try: + before = path.read_text(encoding="ascii").strip() + path.write_text(value, encoding="ascii") + except PermissionError: + raise NodeError("permission", f"no write permission on {path}") from None + previous.append((path, before)) + return previous + + +def restore_leds(previous: list[tuple[Path, str]]) -> None: + """Put each switch back as :func:`set_leds` found it, last first (best-effort).""" + for path, before in reversed(previous): + try: + path.write_text(before, encoding="ascii") + except OSError as exc: + log.warning("could not put %s back to %s: %s", path, before, exc) + + +def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev")) -> None: + """Drive ``high``'s pins of a PI4IOE5V6408 high, as outputs, and leave the rest inputs. + + The output level is written before the direction, so a pin becomes an output already + high rather than glitching low first. The ID register is read first: on a board where + this is the radio's own expander, silence there is the radio not being attached — the + one failure worth saying in those words. + """ + path = dev / f"i2c-{bus}" + _check_device(str(path), "no-i2c", "I2C bus") + import fcntl + + mask = sum(1 << pin for pin in high) & 0xFF + fd = os.open(path, os.O_RDWR) + try: + try: + fcntl.ioctl(fd, _I2C_SLAVE, address) + except OSError as exc: + raise NodeError("busy", f"{address:#04x} on {path} is held: {exc}") from None + try: + os.write(fd, bytes([_PI4IO_ID])) + ident = os.read(fd, 1)[0] + except OSError: + raise NodeError("absent", f"nothing answers at {address:#04x} on {path}") from None + if ident >> 5 != _PI4IO_MAKER: + raise NodeError( + "absent", f"{address:#04x} on {path} is not a PI4IOE5V6408 (ID {ident:#04x})" + ) + for register, value in ( + (_PI4IO_OUTPUT, mask), + (_PI4IO_DIRECTION, mask), + (_PI4IO_HIGH_Z, 0xFF & ~mask), + ): + os.write(fd, bytes([register, value])) + finally: + os.close(fd) + log.info("PI4IO %#04x on %s: pins %s high", address, path, high) + + +def prepare_board(wiring: dict) -> list[tuple[Path, str]]: + """Switch on what the chip needs before the radio library touches it. + + The board's LED-class switches first (power, pin routing), then its RF expander, which + is only reachable once the header it sits on is powered. Returns the switches' previous + states, which the caller puts back when the node ends — including when it never got + going, so a failed start leaves the header as it found it. + """ + previous = set_leds(list(wiring.get("leds") or ()), root=LEDS) + if previous: + import time + + time.sleep(POWER_SETTLE_S) + try: + if int(wiring.get("pi4io_bus", -1)) >= 0: + drive_pi4io( + int(wiring["pi4io_bus"]), + int(wiring.get("pi4io_address", 0x43)), + list(wiring.get("pi4io_high") or ()), + ) + except BaseException: + restore_leds(previous) + raise + return previous + + def _persist_contacts(store: Any, path: Path) -> None: """Snapshot the contact list after every change, the way the firmware writes flash.""" @@ -298,7 +413,6 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non The process exit status. """ import importlib - import inspect try: rt = importlib.import_module(RUNTIME) @@ -319,6 +433,38 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non _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 board's switches go back as they were however the node ends — a radio that never + # came up included — so a failed start leaves the header as it found it. + switched = prepare_board(wiring) + try: + return await _serve( + state, + wiring, + seed, + report, + models=models, + sx1262=sx1262, + companion_mod=companion_mod, + identity_mod=identity_mod, + ) + finally: + restore_leds(switched) + + +async def _serve( # noqa: PLR0913 - the library modules run_node imported, handed on + state: Path, + wiring: dict, + seed: dict, + report, # noqa: ANN001 - (dict) -> None + *, + models: Any, + sx1262: Any, + companion_mod: Any, + identity_mod: Any, +) -> int: + """Bring the radio up on a prepared board, report ready, and serve until told to stop.""" + import inspect + # 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( diff --git a/meshterm/core/spiradio.py b/meshterm/core/spiradio.py index a896a18..f416636 100644 --- a/meshterm/core/spiradio.py +++ b/meshterm/core/spiradio.py @@ -204,14 +204,73 @@ def gpio_chip(wiring: SpiWiring) -> int: return 0 if found is None else found +#: The M5Stack Cap LoRa-1262 on a Cardputer Zero's 14-pin EXT header, confirmed on the +#: hardware and against M5's own factory test (which names the same three lines): the SX1262 +#: on the second chip select of SPI0, which it shares with the panel on the first. The Cap's +#: header is unpowered until the device tree's ``ext_5v_out`` switch is on, and two of its +#: pins (reset, interrupt) reach the chip only while ``ext_usb_gpio_fun`` routes them to GPIO +#: rather than to USB. Its PI4IOE5V6408 at 0x43 on I2C 1 enables the RF path from pin P0, +#: which Meshtastic's Cardputer variant drives the same way. DIO2 switches the antenna and +#: DIO3 feeds a 1.8 V TCXO, as on the AIO. +CARDPUTER_ZERO_CAP = SpiWiring( + bus_id=0, + cs_id=1, + reset_pin=26, + busy_pin=22, + irq_pin=23, + leds=("ext_5v_out=1", "ext_usb_gpio_fun=0"), + pi4io_bus=1, + pi4io_address=0x43, + pi4io_high=(0,), +) + + +@dataclass(frozen=True) +class BuiltinRadio: + """A radio whose wiring ships with MeshTerm, listed with no profile where its board is. + + Attributes: + name: What the device screen calls it; empty for the plain "SPI radio". + wiring: How it is wired. + marker: A path only its board has, for a radio whose ``/dev/spidev*`` node alone + would claim every Raspberry Pi with SPI switched on. Empty when the node is + telling enough on its own (the AIO's ``spidev1.0``). + """ + + name: str + wiring: SpiWiring + marker: str = "" + + def present(self) -> bool: + """Whether this machine is its board: the SPI node exists, and the marker if any.""" + return spi_present(self.wiring) and (not self.marker or os.path.exists(self.marker)) + + +#: The radios MeshTerm knows the wiring of, in the order they are listed. A profile on the +#: same SPI node wins over any of them. +BUILTIN_RADIOS = ( + BuiltinRadio("", SpiWiring()), + BuiltinRadio("Cap LoRa-1262", CARDPUTER_ZERO_CAP, marker="/sys/class/leds/ext_5v_out"), +) + + +def builtin_wiring(spidev: str) -> SpiWiring | None: + """The shipped wiring for the radio on ``spidev``, when this machine is its board.""" + for radio in BUILTIN_RADIOS: + if radio.wiring.spidev == spidev and radio.present(): + return radio.wiring + return None + + def spi_radios( profiles: Mapping[str, DeviceProfile] | None, listed: Iterable[DiscoveredDevice] = () ) -> list[DiscoveredDevice]: """The radios on this machine's own SPI bus, as devices — THE one answer to "which are here". One 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 — a radio on the bus has no node + profile; and, where no profile covers its node, one per :data:`BUILTIN_RADIOS` entry + whose board this machine is — the uConsole AIO whenever its node exists, the Cardputer + Zero's Cap on a Cardputer Zero. Nothing is probed — a radio on the bus has no node running until one is chosen — so a radio is listed exactly when there is a device node to open. The device screen and ``meshterm devices`` both list from here, so the two can never disagree about what is attached. @@ -225,13 +284,14 @@ def spi_radios( """ seen = {d.stable_id for d in listed} wirings = [(p.spi or SpiWiring(), p.name) for p in (profiles or {}).values() if p.is_spi] + wirings = [(w, name) for w, name in wirings if spi_present(w)] covered = {wiring.spidev for wiring, _name in wirings} - if SpiWiring().spidev not in covered: - wirings.append((SpiWiring(), "")) + for builtin in BUILTIN_RADIOS: + if builtin.wiring.spidev not in covered and builtin.present(): + wirings.append((builtin.wiring, builtin.name)) + covered.add(builtin.wiring.spidev) radios: list[DiscoveredDevice] = [] for wiring, name in wirings: - if not spi_present(wiring): - continue device = spi_device(wiring, name=name) if device.stable_id in seen: continue @@ -387,10 +447,18 @@ def explain(kind: str, detail: str, wiring: SpiWiring, holder: str | None = None ) if kind == "no-gpio": return f"/dev/gpiochip{gpio_chip(wiring)} does not exist — check `gpio_chip` in the profile" - if kind == "permission": + if kind == "no-i2c": return ( - f"{detail} — add yourself to the spi and gpio groups " - "(`sudo usermod -aG spi,gpio $USER`) and log in again" + f"/dev/i2c-{wiring.pi4io_bus} does not exist — enable I2C " + "(`dtparam=i2c_arm=on` in /boot/firmware/config.txt) and reboot" + ) + if kind == "absent": + return f"{detail} — is the radio attached, and seated the right way round?" + if kind == "permission": + groups = "spi,gpio,i2c" if wiring.pi4io_bus >= 0 else "spi,gpio" + return ( + f"{detail} — add yourself to the {groups.replace(',', ', ')} groups " + f"(`sudo usermod -aG {groups} $USER`) and log in again" ) if kind == "unsupported": return detail @@ -577,6 +645,10 @@ async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeP "txen_pin": wiring.txen_pin, "rxen_pin": wiring.rxen_pin, "en_pins": list(wiring.en_pins) or None, + "leds": list(wiring.leds), + "pi4io_bus": wiring.pi4io_bus, + "pi4io_address": wiring.pi4io_address, + "pi4io_high": list(wiring.pi4io_high), "use_dio2_rf": wiring.use_dio2_rf, "use_dio3_tcxo": wiring.use_dio3_tcxo, "is_waveshare": wiring.is_waveshare, diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 98db9d6..a1c6643 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -889,7 +889,8 @@ async def _startup(ctx: AppContext) -> bool: ctx.selected_device = chosen 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. + # An SPI profile names its own; a bare row is a shipped board's (the AIO's, the + # Cardputer Zero's Cap), which ``--spi`` resolves as the one radio attached. ctx.spi_override = True ctx.tcp_override = None ctx.ble_override = None diff --git a/tests/test_radionode.py b/tests/test_radionode.py index 43f3861..fb2c69a 100644 --- a/tests/test_radionode.py +++ b/tests/test_radionode.py @@ -127,6 +127,61 @@ def test_radio_kwargs_pass_only_what_the_constructor_accepts() -> None: } +def _switch(root: Path, name: str, state: str) -> Path: + """A stand-in for ``/sys/class/leds/``, reading ``state``.""" + (root / name).mkdir(parents=True) + path = root / name / "brightness" + path.write_text(state, encoding="ascii") + return path + + +def test_board_switches_are_set_and_put_back_as_found(tmp_path: Path) -> None: + """The Cap's power and pin routing go on for the node and back to how they were after.""" + power = _switch(tmp_path, "ext_5v_out", "0") + routing = _switch(tmp_path, "ext_usb_gpio_fun", "255") + previous = radionode.set_leds(["ext_5v_out=1", "ext_usb_gpio_fun=0"], root=tmp_path) + assert (power.read_text(), routing.read_text()) == ("1", "0") + radionode.restore_leds(previous) + assert (power.read_text(), routing.read_text()) == ("0", "255") + + +def test_a_missing_switch_is_a_wiring_for_another_board(tmp_path: Path) -> None: + """No such switch means the wiring describes a board this isn't — said, not ignored.""" + with pytest.raises(radionode.NodeError, match="this board has no ext_5v_out switch"): + radionode.set_leds(["ext_5v_out=1"], root=tmp_path) + + +def test_a_failed_expander_puts_the_switches_back( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A Cap that isn't there leaves the header unpowered again, not switched on for nothing.""" + power = _switch(tmp_path, "ext_5v_out", "0") + monkeypatch.setattr(radionode, "LEDS", tmp_path) + monkeypatch.setattr(radionode, "POWER_SETTLE_S", 0) + + def absent(*_args: object) -> None: + raise radionode.NodeError("absent", "nothing answers at 0x43 on /dev/i2c-1") + + monkeypatch.setattr(radionode, "drive_pi4io", absent) + wiring = {"leds": ["ext_5v_out=1"], "pi4io_bus": 1, "pi4io_high": [0]} + with pytest.raises(radionode.NodeError) as err: + radionode.prepare_board(wiring) + assert err.value.kind == "absent" + assert power.read_text() == "0" + + +def test_an_expander_on_a_missing_bus_is_named(tmp_path: Path) -> None: + """No ``/dev/i2c-N`` is its own kind, with the fix the parent knows how to say.""" + with pytest.raises(radionode.NodeError) as err: + radionode.drive_pi4io(1, 0x43, [0], dev=tmp_path) + assert err.value.kind == "no-i2c" + + +def test_a_board_with_no_switches_prepares_nothing() -> None: + """The AIO's wiring has neither, and its node starts exactly as it always did.""" + assert radionode.prepare_board({"bus_id": 1, "pi4io_bus": -1}) == [] + + 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]) diff --git a/tests/test_spiradio.py b/tests/test_spiradio.py index 3e35302..8fd8d03 100644 --- a/tests/test_spiradio.py +++ b/tests/test_spiradio.py @@ -12,6 +12,7 @@ import io import json import sys import textwrap +from dataclasses import replace from pathlib import Path import pytest @@ -58,6 +59,31 @@ def test_a_wiring_mistake_is_refused_not_ignored(table: dict, complaint: str) -> SpiWiring.from_toml(table) +def test_a_board_s_switches_and_expander_come_from_the_table() -> None: + """``leds`` holds switch strings and ``pi4io_high`` pins: each list is checked as its own.""" + wiring = SpiWiring.from_toml( + {"leds": ["ext_5v_out=1"], "pi4io_bus": 1, "pi4io_address": 0x44, "pi4io_high": [0, 3]} + ) + assert wiring == SpiWiring( + leds=("ext_5v_out=1",), pi4io_bus=1, pi4io_address=0x44, pi4io_high=(0, 3) + ) + + +@pytest.mark.parametrize( + ("table", "complaint"), + [ + ({"leds": [1]}, "leds = [1] is not a tuple"), + ({"pi4io_high": ["0"]}, "pi4io_high = ['0'] is not a tuple"), + ({"leds": ["ext_5v_out"]}, "leds entry 'ext_5v_out' is not name=brightness"), + ({"leds": ["ext_5v_out=on"]}, "leds entry 'ext_5v_out=on' is not name=brightness"), + ], +) +def test_a_malformed_switch_is_refused(table: dict, complaint: str) -> None: + """A switch the node couldn't set would fail at connect; the file is where to say so.""" + with pytest.raises(ValueError, match=complaint.replace("[", r"\[").replace("]", r"\]")): + SpiWiring.from_toml(table) + + def test_the_retired_preamble_key_is_refused_with_its_reason() -> None: """A config still carrying the old fixed preamble is told why, not left deaf.""" with pytest.raises(ValueError, match="preamble_length is no longer a wiring key"): @@ -218,6 +244,68 @@ def test_a_listed_radio_is_wired_by_the_profile_on_its_node(contexts) -> None: assert ctx.spi_wiring_for("/dev/spidev1.0") == SpiWiring() +# --- radios that need no profile ----------------------------------------------------------- + + +@pytest.fixture() +def cardputer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A machine with the Cardputer Zero's SPI node, its board marker under ``tmp_path``. + + Returns the marker, which a test removes to make the machine some other Raspberry Pi + with the same ``/dev/spidev0.1``. + """ + marker = tmp_path / "ext_5v_out" + marker.mkdir() + monkeypatch.setattr(spiradio, "spi_present", lambda w: w.spidev == "/dev/spidev0.1") + monkeypatch.setattr( + spiradio, + "BUILTIN_RADIOS", + ( + spiradio.BuiltinRadio("", SpiWiring()), + spiradio.BuiltinRadio("Cap LoRa-1262", spiradio.CARDPUTER_ZERO_CAP, marker=str(marker)), + ), + ) + return marker + + +def test_the_cardputer_cap_is_listed_with_no_profile(cardputer: Path) -> None: + """On a Cardputer Zero the Cap is a radio like the AIO: there, named, and wired.""" + radios = spiradio.spi_radios({}) + assert [(d.port, d.name) for d in radios] == [("/dev/spidev0.1", "Cap LoRa-1262")] + assert radios[0].spi == spiradio.CARDPUTER_ZERO_CAP + + +def test_a_bare_spidev_node_is_not_a_cardputer(cardputer: Path) -> None: + """``spidev0.1`` is on every Pi with SPI on; only the board's own switch says Cardputer.""" + cardputer.rmdir() + assert spiradio.spi_radios({}) == [] + assert spiradio.builtin_wiring("/dev/spidev0.1") is None + + +def test_a_profile_on_the_cap_s_node_wins(cardputer: Path) -> None: + """A profile on the same node is the owner's word about it, and replaces the shipped one.""" + mine = replace(spiradio.CARDPUTER_ZERO_CAP, use_dio3_tcxo=False) + profiles = {"cap": DeviceProfile(name="cap", transport="spi", spi=mine)} + radios = spiradio.spi_radios(profiles) + assert [(d.name, d.spi) for d in radios] == [("cap", mine)] + + +def test_the_cap_is_what_spi_and_a_remembered_node_reach(contexts, cardputer: Path) -> None: # noqa: ANN001 + """``--spi``, and a radio remembered by its node, both resolve to the Cap's wiring.""" + assert contexts(spi_override=True).resolve_spi() == spiradio.CARDPUTER_ZERO_CAP + assert contexts().spi_wiring_for("/dev/spidev0.1") == spiradio.CARDPUTER_ZERO_CAP + + +def test_the_cardputer_cap_wiring_is_the_one_the_hardware_answered_on() -> None: + """The lines M5's factory test drives, on the node the panel shares, power from the LED.""" + cap = spiradio.CARDPUTER_ZERO_CAP + assert cap.spidev == "/dev/spidev0.1" + assert (cap.reset_pin, cap.busy_pin, cap.irq_pin) == (26, 22, 23) + assert cap.leds == ("ext_5v_out=1", "ext_usb_gpio_fun=0") + assert (cap.pi4io_bus, cap.pi4io_address, cap.pi4io_high) == (1, 0x43, (0,)) + assert cap.use_dio2_rf and cap.use_dio3_tcxo + + # --- finding a Python for the node ---------------------------------------------------------