From 338b5678def94f4b3cf37f6dd01624c2cc48178d Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 22 Nov 2026 23:18:44 -0500 Subject: [PATCH] MeshTerm drives the older Cap LoRa868 as well as the Cap LoRa-1262 A user on a Cardputer Zero could not connect his Cap. MeshTerm stopped at "nothing answers at 0x43 on /dev/i2c-1". His Cap is the Cap LoRa868, which M5Stack made before the Cap LoRa-1262. The two boards carry the same SX1262 on the same pins of the same header, and the same GNSS at the same speed. The newer board adds an antenna switch, and the chip at 0x43 that turns the switch on. The older board has no switch, so it has no such chip. MeshTerm asked for one on every Cardputer Zero. A wiring now says whether its expander is required. pi4io_required is true by default, so every other board keeps the rule that an expander which does not answer is an absent board. The Cap sets it to false. An absent expander is then the other revision of the board, and the node must prove that before it accepts it. After the radio starts, the node reads the version register of the chip and requires the name of an SX126x. A bus with nothing on it reads as all ones or all zeros, and the library can start on such a bus, so a Cap that is absent or badly seated still reports that no radio answered. The read of the expander also tells its failures apart now. Only the errors that mean "nobody is at this address" count as absent. A bus error or a refused read is a failure of its own, and never becomes the older board quietly. The two boards come from M5Stack's own pages, and from two other Cardputer Zero applications that drive both. The pins, the TCXO, and DIO2 are the same everywhere, and they agree with the wiring MeshTerm already had. One thing is open. The device screen names the row "Cap LoRa-1262" before anything is connected, because nothing can know which Cap is attached until the node runs. Co-Authored-By: Claude Opus 5 --- docs/devices/cardputer-zero.md | 40 +++++++++++ docs/devices/uconsole.md | 1 + meshterm/core/config.py | 7 ++ meshterm/core/radionode.py | 127 ++++++++++++++++++++++++++++++--- meshterm/core/spiradio.py | 8 ++- tests/test_radionode.py | 88 ++++++++++++++++++++++- 6 files changed, 258 insertions(+), 13 deletions(-) diff --git a/docs/devices/cardputer-zero.md b/docs/devices/cardputer-zero.md index f32c7a7..17332ec 100644 --- a/docs/devices/cardputer-zero.md +++ b/docs/devices/cardputer-zero.md @@ -180,6 +180,7 @@ The Cardputer Zero has no LoRa radio built in. You can add one in three ways: | Radio | Status | | --- | --- | | **Cap LoRa-1262** add-on board from M5Stack | Works, with no setup. MeshTerm runs the mesh node itself while it is open, as it does on a uConsole. | +| **Cap LoRa868**, the earlier add-on board | Works, with no setup. It is the same radio with no antenna switch (refer to [The older Cap LoRa868](#the-older-cap-lora868)). | | 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. | @@ -227,6 +228,45 @@ A new node starts with the US/Canada settings of MeshCore (910.525 MHz). In othe change the settings on **Device config** before you send anything. MeshTerm keeps the key, the contacts, and the channels of the node in `~/.meshterm/radio/spidev0.1/`. +#### The older Cap LoRa868 + +M5Stack made an earlier LoRa Cap, the **Cap LoRa868**. MeshTerm works with it as well, +and you do nothing to make it work. + +The two Caps are almost the same board. Each one has an SX1262 radio and a GNSS +receiver, on the same pins of the same 14-pin header. The newer Cap LoRa-1262 adds an +antenna switch, and a small chip at I2C address `0x43` that turns that switch on. The +older Cap has no antenna switch, so it has no such chip. + +MeshTerm finds out which Cap you have each time it connects: + +1. It powers the header. +2. It looks for the switch chip at `0x43`, for one second. +3. If the chip answers, the Cap is a Cap LoRa-1262, and MeshTerm turns the antenna + switch on. +4. If nothing answers, MeshTerm starts the radio and asks the radio what it is. An + SX1262 that gives its name is the older Cap, and MeshTerm continues. + +Step 4 is the reason why a Cap that is absent, or that is not pushed fully onto the +header, is still reported as absent. Only a radio that answers for itself is accepted. + +#### If MeshTerm says that it cannot find the radio + +Two messages are possible, and they mean different things. + +**"Nothing answers at 0x43 on /dev/i2c-1"** comes from a profile of your own that +requires the switch chip. MeshTerm's own wiring for the Cap does not require it. Set +`pi4io_required = false` in your profile, or remove the `pi4io_bus` line from it (refer +to [Board wiring](uconsole.md#board-wiring)). + +**"No SX126x answered on the SPI bus"** means that no radio answered. Turn the Cardputer +Zero off, push the Cap fully onto the header at the back, and check that no row of pins +is left over at either end. Then turn it on again. Never add or remove a Cap while the +device is on. + +The node writes what it did to `~/.meshterm/radio/spidev0.1/node.log`. That file names +the wiring it used and the answer it got from the bus. Send it with a problem report. + #### The Cap's GPS The Cap also has a GPS. MeshTerm can use it to keep the position of your node current. The diff --git a/docs/devices/uconsole.md b/docs/devices/uconsole.md index 736903e..fc98991 100644 --- a/docs/devices/uconsole.md +++ b/docs/devices/uconsole.md @@ -318,6 +318,7 @@ en_pins = [27] # the AIO v2 needs this | `en_pins` | `[]` | The power-enable lines that go high before MeshTerm touches the chip. The **AIO v2 needs `[27]`.** | | `leds` | `[]` | Switches that the device tree of the board shows as LEDs (under `/sys/class/leds/`). Write each one as `"name=brightness"`. MeshTerm sets them before it touches the chip. It puts them back as they were when it releases the radio. The Cardputer Zero powers its expansion header in this way. Its Cap needs no profile, but this is what you would write: `["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 antenna path of the radio. These are its I2C bus (`-1` for none), its address, and the pins that go high. | +| `pi4io_required` | `true` | Whether the radio works only with that expander. `false` says that the board has two revisions, one with the expander and one without it. An expander that does not answer is then the revision without it, and MeshTerm continues after the radio itself answers. The Cap of the Cardputer Zero is set this way. | | `use_dio2_rf`, `use_dio3_tcxo` | `true`, `true` | If DIO2 drives the RF switch, and if DIO3 drives a TCXO (both are on for the AIO). | | `is_waveshare` | `false` | The wiring quirks of the Waveshare HAT, which the radio library knows. | | `python` | `""` (empty) | An interpreter to run the node under. Use it when the interpreter that MeshTerm finds is not the one that you want. If it is empty, MeshTerm looks for one. | diff --git a/meshterm/core/config.py b/meshterm/core/config.py index 5edadce..125545a 100644 --- a/meshterm/core/config.py +++ b/meshterm/core/config.py @@ -114,6 +114,12 @@ class SpiWiring: ``0x44`` when it is high. pi4io_high: The pins of the expander (0–7) that MeshTerm drives high before it touches the chip. Each other pin stays an input. + pi4io_required: Whether the radio works only with that expander. ``True``, the + default, makes an expander that does not answer an absent board. Set it to + ``False`` on a board that has two revisions, one with the expander and one + without it. A board that does not answer at that address is then the revision + without it, and MeshTerm continues. The Cap LoRa868 of the Cardputer Zero is + that revision of the Cap LoRa-1262. use_dio2_rf: Whether DIO2 drives the RF switch. use_dio3_tcxo: Whether DIO3 powers a TCXO. is_waveshare: The wiring quirks of the Waveshare HAT, which the radio library @@ -144,6 +150,7 @@ class SpiWiring: pi4io_bus: int = -1 pi4io_address: int = 0x43 pi4io_high: tuple[int, ...] = () + pi4io_required: bool = True use_dio2_rf: bool = True use_dio3_tcxo: bool = True is_waveshare: bool = False diff --git a/meshterm/core/radionode.py b/meshterm/core/radionode.py index b452137..8746b8c 100644 --- a/meshterm/core/radionode.py +++ b/meshterm/core/radionode.py @@ -58,6 +58,7 @@ from __future__ import annotations import argparse import asyncio import dataclasses +import errno import functools import json import logging @@ -314,6 +315,16 @@ PI4IO_RETRY_S = 0.05 #: because then the device is not ours to use. _I2C_SLAVE = 0x0703 +#: The errors of a read that mean that nothing is at the address: the kernel found no +#: device there, or the device did not acknowledge. Each other error is a fault of the bus +#: or of this process, and must never read as an absent board. ENXIO and EREMOTEIO are the +#: two that a Linux I2C adapter gives for an address that nobody answers. EREMOTEIO is on +#: Linux alone, and this file is imported on each platform, so its number stands in where +#: the module does not have the name. +_ABSENT_ERRNOS = frozenset( + {errno.ENXIO, errno.ENODEV, errno.ETIMEDOUT, getattr(errno, "EREMOTEIO", 121)} +) + #: The registers of the PI4IOE5V6408, and the manufacturer field of its ID register (bits #: 7–5). This field tells a different chip at the same address apart from it. _PI4IO_ID, _PI4IO_DIRECTION, _PI4IO_OUTPUT, _PI4IO_HIGH_Z = 0x01, 0x03, 0x05, 0x07 @@ -380,6 +391,10 @@ def _expander_id(fd: int, address: int, path: Path) -> int: os.write(fd, bytes([_PI4IO_ID])) return os.read(fd, 1)[0] except OSError as exc: + if exc.errno not in _ABSENT_ERRNOS: + raise NodeError( + "failed", f"{address:#04x} on {path} could not be read: {exc}" + ) from exc if time.monotonic() >= deadline: log.warning( "no answer at %#04x on %s after %.1fs: %s", address, path, PI4IO_WAIT_S, exc @@ -388,7 +403,14 @@ def _expander_id(fd: int, address: int, path: Path) -> int: time.sleep(PI4IO_RETRY_S) -def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev")) -> None: +def drive_pi4io( + bus: int, + address: int, + high: list[int], + dev: Path = Path("/dev"), + *, + required: bool = True, +) -> bool: """Drive the ``high`` pins of a PI4IOE5V6408 high as outputs, and keep the rest as inputs. The function writes the output level before the direction. Thus a pin becomes an @@ -396,6 +418,26 @@ def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev" register first. On a board where this is the expander of the radio itself, no answer there means that the radio is not attached. That is the one failure that the message must give in those words. + + A board that has two revisions is the exception (``required=False``). There an absent + expander is the revision that has none, and the node continues without it. The node + then proves that a radio is on the bus (refer to :func:`confirm_sx126x`), because + "no expander" and "no board at all" are the same thing at this point. + + Args: + bus: The I2C bus of the expander. + address: Its address. + high: The pins that go high. + dev: The directory of the device files, for the tests. + required: Whether an absent expander is a failure. + + Returns: + Whether the expander answered. + + Raises: + NodeError: ``no-i2c`` or ``permission`` for the bus, ``busy`` when a driver holds + the address, ``failed`` when the bus itself failed, and ``absent`` when nothing + answered and ``required`` is set. """ path = dev / f"i2c-{bus}" _check_device(str(path), "no-i2c", "I2C bus") @@ -408,7 +450,15 @@ def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev" fcntl.ioctl(fd, _I2C_SLAVE, address) except OSError as exc: raise NodeError("busy", f"{address:#04x} on {path} is held: {exc}") from None - ident = _expander_id(fd, address, path) + try: + ident = _expander_id(fd, address, path) + except NodeError as exc: + if exc.kind != "absent" or required: + raise + log.info( + "nothing at %#04x on %s: this board is the revision with no expander", address, path + ) + return False if ident >> 5 != _PI4IO_MAKER: raise NodeError( "absent", f"{address:#04x} on {path} is not a PI4IOE5V6408 (ID {ident:#04x})" @@ -422,31 +472,81 @@ def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev" finally: os.close(fd) log.info("PI4IO %#04x on %s: pins %s high", address, path, high) + return True -def prepare_board(wiring: dict) -> list[tuple[Path, str]]: +#: The register where an SX126x holds its version string, how many bytes of it to read, +#: and the first bytes of what the string must be. A bus with no chip on it reads as all +#: ones or all zeros, and neither starts with these letters. +_VERSION_REGISTER, _VERSION_LENGTH, _SX126X = 0x0320, 16, b"SX126" + + +def confirm_sx126x(lora: Any) -> None: + """Refuse a radio that did not answer with the version string of an SX126x. + + This is for a board whose expander did not answer (refer to :func:`drive_pi4io`). + There, "this revision has no expander" and "no board is attached" look the same, and + only the chip can tell them apart. The library can start on a bus with nothing on it, + so the answer must come from the silicon. + + Args: + lora: The chip of the started radio. + + Raises: + NodeError: ``absent``, when the chip did not answer, or answered as something else. + """ + try: + signature = bytes(lora.readRegister(_VERSION_REGISTER, _VERSION_LENGTH)) + except Exception as exc: # noqa: BLE001 - any failure here means that nothing answered + raise NodeError("absent", f"the radio did not answer a register read ({exc})") from None + if not signature.startswith(_SX126X): + log.warning("the version register reads %r, which is not an SX126x", signature) + raise NodeError("absent", "no SX126x answered on the SPI bus") + name = signature.split(bytes(1))[0].decode("ascii", "replace") + log.info("the chip reports itself as %s", name) + + +@dataclasses.dataclass(frozen=True) +class PreparedBoard: + """What :func:`prepare_board` switched on, and what it found there. + + Attributes: + switches: The LED-class switches that it set, each with the value that it had + before. :func:`restore_leds` puts them back. + expander: ``True`` when the expander of the board answered, ``False`` when the + wiring permits an absent one and none answered, and ``None`` when this wiring + has no expander at all. + """ + + switches: list[tuple[Path, str]] + expander: bool | None + + +def prepare_board(wiring: dict) -> PreparedBoard: """Switch on the parts that the chip must have before the radio library uses it. First the LED-class switches of the board (power, pin routing), then its RF expander. The node can get to the expander only after the header that it is on has power. The - function returns the previous states of the switches. The caller puts them back when - the node ends, also when the node did not start. Thus a failed start leaves the header - as it was. + function returns what it switched, and whether the expander answered. The caller puts + the switches back when the node ends, also when the node did not start. Thus a failed + start leaves the header as it was. """ previous = set_leds(list(wiring.get("leds") or ()), root=LEDS) if previous: time.sleep(POWER_SETTLE_S) + expander: bool | None = None try: if int(wiring.get("pi4io_bus", -1)) >= 0: - drive_pi4io( + expander = drive_pi4io( int(wiring["pi4io_bus"]), int(wiring.get("pi4io_address", 0x43)), list(wiring.get("pi4io_high") or ()), + required=bool(wiring.get("pi4io_required", True)), ) except BaseException: restore_leds(previous) raise - return previous + return PreparedBoard(switches=previous, expander=expander) # --- the GPS beside the chip --------------------------------------------------------------- @@ -739,13 +839,14 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non # The switches of the board go back to how they were, in any way that the node ends, # also when the radio did not start. Thus a failed start leaves the header as it was. - switched = prepare_board(wiring) + board = prepare_board(wiring) try: return await _serve( state, wiring, seed, report, + expander=board.expander, model=str(config.get("model") or DEVICE_MODEL), models=models, sx1262=sx1262, @@ -753,7 +854,7 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non identity_mod=identity_mod, ) finally: - restore_leds(switched) + restore_leds(board.switches) async def _serve( # noqa: PLR0913 - the library modules run_node imported, handed on @@ -762,6 +863,7 @@ async def _serve( # noqa: PLR0913 - the library modules run_node imported, hand seed: dict, report, # noqa: ANN001 - (dict) -> None *, + expander: bool | None, model: str, models: Any, sx1262: Any, @@ -818,6 +920,11 @@ async def _serve( # noqa: PLR0913 - the library modules run_node imported, hand logging.getLogger().removeHandler(recent) log.info("radio ready") + # The expander of this board did not answer, and the wiring permits that. Before the + # node accepts the board as the revision that has none, the chip itself must answer. + if expander is False: + confirm_sx126x(radio.lora) + try: seed_bytes = load_identity_seed( state, lambda: identity_mod.LocalIdentity().get_signing_key_bytes() diff --git a/meshterm/core/spiradio.py b/meshterm/core/spiradio.py index e2c0d56..90e0f6c 100644 --- a/meshterm/core/spiradio.py +++ b/meshterm/core/spiradio.py @@ -226,7 +226,11 @@ def gpio_chip(wiring: SpiWiring) -> int: #: The header of the Cap has no power until the ``ext_5v_out`` switch of the device tree is #: on. Two of its pins (reset, interrupt) get to the chip only while ``ext_usb_gpio_fun`` #: routes them to GPIO, not to USB. Its PI4IOE5V6408 at 0x43 on I2C 1 turns on the RF path -#: from pin P0. The Cardputer variant of Meshtastic drives that pin in the same way. DIO2 +#: from pin P0. The older Cap LoRa868 has the same radio on the same pins, and no expander +#: at all, because it has no antenna switch to turn on. For this reason the expander of +#: this board is not required: a Cap that does not answer at 0x43 is the older one, and the +#: node proves that a radio is there before it accepts that. +#: The Cardputer variant of Meshtastic drives that pin in the same way. DIO2 #: switches the antenna and DIO3 supplies a 1.8 V TCXO, as on the AIO. Its GPS talks NMEA #: at 115200 on the UART of the header, which is the ``serial0`` of the Pi (``/dev/ttyS0`` #: on the Zero). The GPS gets its power from ``ext_5v_out``, as the radio does. Thus it @@ -241,6 +245,7 @@ CARDPUTER_ZERO_CAP = SpiWiring( pi4io_bus=1, pi4io_address=0x43, pi4io_high=(0,), + pi4io_required=False, gps_port="/dev/serial0", gps_baud=115200, ) @@ -819,6 +824,7 @@ async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeP "pi4io_bus": wiring.pi4io_bus, "pi4io_address": wiring.pi4io_address, "pi4io_high": list(wiring.pi4io_high), + "pi4io_required": wiring.pi4io_required, "use_dio2_rf": wiring.use_dio2_rf, "use_dio3_tcxo": wiring.use_dio3_tcxo, "is_waveshare": wiring.is_waveshare, diff --git a/tests/test_radionode.py b/tests/test_radionode.py index 548f998..5aa5b59 100644 --- a/tests/test_radionode.py +++ b/tests/test_radionode.py @@ -166,7 +166,7 @@ def test_a_failed_expander_puts_the_switches_back( monkeypatch.setattr(radionode, "LEDS", tmp_path) monkeypatch.setattr(radionode, "POWER_SETTLE_S", 0) - def absent(*_args: object) -> None: + def absent(*_args: object, **_kwargs: object) -> None: raise radionode.NodeError("absent", "nothing answers at 0x43 on /dev/i2c-1") monkeypatch.setattr(radionode, "drive_pi4io", absent) @@ -177,6 +177,89 @@ def test_a_failed_expander_puts_the_switches_back( assert power.read_text() == "0" +def test_a_board_whose_expander_is_optional_starts_without_one( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The Cap LoRa868 is the Cap LoRa-1262 with no antenna switch. It keeps the power on.""" + power = _switch(tmp_path, "ext_5v_out", "0") + monkeypatch.setattr(radionode, "LEDS", tmp_path) + monkeypatch.setattr(radionode, "POWER_SETTLE_S", 0) + asked: dict[str, object] = {} + + def nothing_there(*args: object, required: bool = True) -> bool: + asked["required"] = required + return False + + monkeypatch.setattr(radionode, "drive_pi4io", nothing_there) + wiring = { + "leds": ["ext_5v_out=1"], + "pi4io_bus": 1, + "pi4io_high": [0], + "pi4io_required": False, + } + board = radionode.prepare_board(wiring) + assert asked["required"] is False, "the wiring decides, not the function" + assert board.expander is False, "the node knows that it is the board with no expander" + assert power.read_text() == "1", "the header keeps its power, because the radio is there" + radionode.restore_leds(board.switches) + assert power.read_text() == "0" + + +def test_a_broken_bus_is_not_an_absent_board(monkeypatch: pytest.MonkeyPatch) -> None: + """Only "nobody answered" is an absent board. Each other error of the bus is a failure.""" + real_write = os.write + + def write(fd: int, data: bytes) -> int: + if fd != _BUS_FD: + return real_write(fd, data) + raise OSError(5, "Input/output error") + + monkeypatch.setattr(os, "write", write) + with pytest.raises(radionode.NodeError) as err: + radionode._expander_id(_BUS_FD, 0x43, Path("/dev/i2c-1")) + assert err.value.kind == "failed", "a broken bus must never read as a board that is not there" + + +class _VersionChip: + """A started radio that answers a register read with ``answer``.""" + + def __init__(self, answer: bytes) -> None: + self.answer = answer + + def readRegister(self, address: int, count: int) -> tuple[int, ...]: # noqa: N802 + """The spelling of the radio library. It returns the bytes at ``address``.""" + assert (address, count) == (0x0320, 16) + return tuple(self.answer.ljust(count, bytes(1))[:count]) + + +def test_the_chip_says_that_it_is_an_sx126x() -> None: + """A board with no expander is accepted only after the chip answers with its own name.""" + radionode.confirm_sx126x(_VersionChip(b"SX1262 V2D")) + + +@pytest.mark.parametrize( + "answer", [bytes(16), bytes([0xFF] * 16), b"NOTARADIO"], ids=["zeros", "ones", "other"] +) +def test_a_bus_with_nothing_on_it_is_not_a_board(answer: bytes) -> None: + """An empty bus reads as all ones or all zeros. The library can start on it.""" + with pytest.raises(radionode.NodeError) as err: + radionode.confirm_sx126x(_VersionChip(answer)) + assert err.value.kind == "absent" + + +def test_a_chip_that_cannot_be_read_is_not_a_board() -> None: + """A read that fails is the same answer as a read of nothing: no board is attached.""" + + class _Dead: + def readRegister(self, address: int, count: int) -> tuple[int, ...]: # noqa: N802 + """Fail as a chip that is not there fails.""" + raise OSError(5, "Input/output error") + + with pytest.raises(radionode.NodeError) as err: + radionode.confirm_sx126x(_Dead()) + assert err.value.kind == "absent" + + def test_an_expander_on_a_missing_bus_is_named(tmp_path: Path) -> None: """A missing ``/dev/i2c-N`` is its own kind, and the parent knows the correction for it.""" with pytest.raises(radionode.NodeError) as err: @@ -239,7 +322,8 @@ def test_an_expander_that_never_answers_is_absent_and_the_log_says_why( def test_a_board_with_no_switches_prepares_nothing() -> None: """The wiring of the AIO has neither, and its node starts the same as it always did.""" - assert radionode.prepare_board({"bus_id": 1, "pi4io_bus": -1}) == [] + board = radionode.prepare_board({"bus_id": 1, "pi4io_bus": -1}) + assert (board.switches, board.expander) == ([], None) def test_an_identity_is_minted_once_and_then_kept(tmp_path: Path) -> None: