diff --git a/meshterm/core/radionode.py b/meshterm/core/radionode.py index ed2f103..b452137 100644 --- a/meshterm/core/radionode.py +++ b/meshterm/core/radionode.py @@ -300,6 +300,15 @@ LEDS = Path("/sys/class/leds") #: the chip does its own reset after this. POWER_SETTLE_S = 0.1 +#: How long the expander of a board gets to answer, after the header is powered on, and +#: before MeshTerm says that no board is attached. The first read comes after +#: :data:`POWER_SETTLE_S`, which is sufficient on the boards that we have. A board with a +#: slower power rail answers a moment later, and that must not read as an absent board. +#: :data:`PI4IO_RETRY_S` is the time between two tries, which is short, because a board +#: that is ready answers at once. +PI4IO_WAIT_S = 1.0 +PI4IO_RETRY_S = 0.05 + #: ``I2C_SLAVE``: point the open ``/dev/i2c-*`` at one device. The kernel refuses it #: (``EBUSY``) while a kernel driver is bound to that address. This is the correct answer, #: because then the device is not ours to use. @@ -342,6 +351,43 @@ def restore_leds(previous: list[tuple[Path, str]]) -> None: log.warning("could not put %s back to %s: %s", path, before, exc) +def _expander_id(fd: int, address: int, path: Path) -> int: + """Read the ID register of the expander at ``address``, and try again until it answers. + + The caller powers the header of the board a short time before this read. A board whose + power rail is slower than :data:`POWER_SETTLE_S` refuses the first read and answers + correctly a moment later. For this reason the function tries again until + :data:`PI4IO_WAIT_S` is spent, and calls the board absent only then. + + The log line carries the error of the last try. The sentence that the user reads cannot + carry it, because a refused address and a broken bus are the same thing to that user. + They are not the same thing to us, and only the log can tell them apart afterwards. + + Args: + fd: The open bus, already pointed at the address. + address: The address of the expander, for the message. + path: The bus device file, for the message. + + Returns: + The byte in the ID register. + + Raises: + NodeError: ``absent``, when nothing answered in the time above. + """ + deadline = time.monotonic() + PI4IO_WAIT_S + while True: + try: + os.write(fd, bytes([_PI4IO_ID])) + return os.read(fd, 1)[0] + except OSError as exc: + if time.monotonic() >= deadline: + log.warning( + "no answer at %#04x on %s after %.1fs: %s", address, path, PI4IO_WAIT_S, exc + ) + raise NodeError("absent", f"nothing answers at {address:#04x} on {path}") from None + time.sleep(PI4IO_RETRY_S) + + def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev")) -> None: """Drive the ``high`` pins of a PI4IOE5V6408 high as outputs, and keep the rest as inputs. @@ -362,11 +408,7 @@ 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 - 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 + ident = _expander_id(fd, address, path) if ident >> 5 != _PI4IO_MAKER: raise NodeError( "absent", f"{address:#04x} on {path} is not a PI4IOE5V6408 (ID {ident:#04x})" @@ -687,6 +729,10 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non wiring = dict(config.get("wiring") or {}) seed = dict(config.get("seed") or {}) + # The log must say which wiring the node used. A board problem is reported with this + # file, and the wiring can come from a profile that the reporter wrote. + log.info("node wiring: %s", json.dumps(wiring, sort_keys=True)) + 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") diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 2b7b11d..bba7402 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -63,7 +63,7 @@ from ..core.discovery import ( tcp_device, ) from ..core.spiradio import spi_radios, without_radio_ports -from ..persistence.logging import log_file_for +from ..persistence.logging import get_logger, log_file_for from .logo import load_logo from .menus import Lane, align_icons, column_header from .tui import Choice, DeleteRequest, KeyRequest, Separator @@ -332,7 +332,10 @@ async def _smoke_test( continue except DeviceCommandError as exc: # A different failure that the user can act on (not a PIN). Show its remedy, then - # go back to the list. + # go back to the list. The log keeps the failure also when the dialog says all + # that the log would say, because a user who reports a problem sends the log file, + # and the dialog is gone long before that. + get_logger().warning("%s did not connect (%s): %s", name, type(exc).__name__, exc) notice = connect_failure_text(exc) notice.append("\nChoose another device.") await ui.notify_startup(notice, title="Can't connect yet", banner=load_logo()) diff --git a/tests/test_radionode.py b/tests/test_radionode.py index 1c1f6ce..548f998 100644 --- a/tests/test_radionode.py +++ b/tests/test_radionode.py @@ -16,6 +16,7 @@ import ast import asyncio import dataclasses import json +import logging import os import sys from pathlib import Path @@ -183,6 +184,59 @@ def test_an_expander_on_a_missing_bus_is_named(tmp_path: Path) -> None: assert err.value.kind == "no-i2c" +#: A number that stands for the open I2C bus in the two tests below. The tests put their +#: own ``os.write`` and ``os.read`` in front of the real ones, and those answer for this +#: number alone. Each other file in the process, the capture of pytest included, goes +#: through to the real function. +_BUS_FD = 9001 + + +def test_a_slow_expander_gets_more_than_one_try(monkeypatch: pytest.MonkeyPatch) -> None: + """A board whose power rail is slow answers a later read, and is attached after all.""" + real_write, real_read = os.write, os.read + tries: list[bytes] = [] + + def write(fd: int, data: bytes) -> int: + if fd != _BUS_FD: + return real_write(fd, data) + tries.append(data) + return len(data) + + def read(fd: int, count: int) -> bytes: + if fd != _BUS_FD: + return real_read(fd, count) + if len(tries) < 3: + raise OSError(121, "Remote I/O error") + return bytes([0xA2]) + + monkeypatch.setattr(os, "write", write) + monkeypatch.setattr(os, "read", read) + monkeypatch.setattr(radionode, "PI4IO_RETRY_S", 0) + assert radionode._expander_id(_BUS_FD, 0x43, Path("/dev/i2c-1")) == 0xA2 + assert len(tries) == 3, "it read the ID register again until the board answered" + + +def test_an_expander_that_never_answers_is_absent_and_the_log_says_why( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The user reads that nothing is there. Only the log says what the bus answered.""" + real_write = os.write + + def write(fd: int, data: bytes) -> int: + if fd != _BUS_FD: + return real_write(fd, data) + raise OSError(121, "Remote I/O error") + + monkeypatch.setattr(os, "write", write) + monkeypatch.setattr(radionode, "PI4IO_WAIT_S", 0) + with caplog.at_level(logging.WARNING, logger="radionode"): + with pytest.raises(radionode.NodeError) as err: + radionode._expander_id(_BUS_FD, 0x43, Path("/dev/i2c-1")) + assert err.value.kind == "absent" + assert "nothing answers at 0x43" in str(err.value), "the sentence of the user is unchanged" + assert "Remote I/O error" in caplog.text, "the log keeps the error of the bus" + + 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}) == []