From 8b1ccf5938da5c8006bdfb4c281aa9605aa4923c Mon Sep 17 00:00:00 2001 From: Shivtej Gaikwad <91597404+ShivtejG236@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:58:58 +0530 Subject: [PATCH] Store sensor pins per device and accept pin commands from the host Each physical board can now keep its own pin assignment in non-volatile storage. The host sends SET_PINS or RESET_PINS using the existing framing; the firmware checks the request against allowed-pin masks generated from the pin rules, stores it, answers with an ACK frame and restarts to apply it. An assignment that fails the check is never stored, and the UART0 pins are always blocked, so the host link cannot be cut. HELLO gains id (the chip's factory MAC), pins and pin_src. These are new keys and new frame types, so the protocol version stays 1. The release manifest now carries each board's default pins and pin rules for host tools. --- .github/workflows/build.yml | 4 ++ CHANGELOG.md | 9 +++ docs/boards.md | 5 ++ docs/wire-protocol.md | 55 +++++++++++++++++- include/config.h | 9 +++ include/device_config.h | 24 ++++++++ include/pin_config.h | 66 ++++++++++++++++++++++ include/transport.h | 14 ++++- include/wire.h | 80 +++++++++++++++++++++++++++ scripts/board.py | 2 +- scripts/boards.py | 25 +++++++++ src/device_config.cpp | 68 +++++++++++++++++++++++ src/main.cpp | 12 +++- src/transport.cpp | 64 ++++++++++++++++++++- tools/host/test_pins.cpp | 107 ++++++++++++++++++++++++++++++++++++ tools/release.py | 3 + tools/test_pin_rules.py | 24 ++++++++ 17 files changed, 560 insertions(+), 11 deletions(-) create mode 100644 include/device_config.h create mode 100644 include/pin_config.h create mode 100644 src/device_config.cpp create mode 100644 tools/host/test_pins.cpp diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6624e41..37325e1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,6 +21,10 @@ jobs: run: | g++ -std=c++17 -Wall -Wextra -Werror -Iinclude tools/host/test_wire.cpp -o test_wire ./test_wire + - name: Command and pin-check tests + run: | + g++ -std=c++17 -Wall -Wextra -Werror -Iinclude tools/host/test_pins.cpp -o test_pins + ./test_pins - name: Board manifests run: python3 tools/check_boards.py - name: Pin rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 203dcbb..1673709 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - Host output moved out of `main.cpp` into `src/transport.cpp`. ### Added +- **Per-device pin settings.** Each physical board can store its own sensor + pins: the host sends `SET_PINS` / `RESET_PINS`, the firmware checks the + request against the pin rules, stores it, answers with `ACK` and restarts. + `HELLO` now carries the chip's unique `id`, the `pins` in use and + `pin_src`. See `docs/wire-protocol.md`. +- **Pin rules** (`chips/.json`): which GPIOs may carry a sensor signal + on each chip, with the reason for every blocked pin. Enforced on board + manifests, compiled into the firmware as allowed-pin masks, and published + per board in the release `manifest.json`. - **Web flasher** (`web/index.html`, built by `tools/release.py --site`): flash any released board from Chrome or Edge with no install. Deployed to GitHub Pages by the release workflow when `PAGES_DEPLOY=true`. diff --git a/docs/boards.md b/docs/boards.md index 542f4d6..9084009 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -45,6 +45,11 @@ against those rules plus the board's `reserved` list and returns every problem it finds. Manifests that break a rule fail `tools/check_boards.py` and the build. +The same rules are compiled into the firmware as two bit masks, so a pin +change requested by the host (`SET_PINS`, see `docs/wire-protocol.md`) is +checked on the device as well, and they are published per board in the +release `manifest.json` (`pins`, `pin_rules`) for host tools. + Strapping pins are blocked outright, including the ones that are safe with a pull-up, so that no allowed assignment can stop a board from booting or flashing. diff --git a/docs/wire-protocol.md b/docs/wire-protocol.md index 033fcaa..2cd54d8 100644 --- a/docs/wire-protocol.md +++ b/docs/wire-protocol.md @@ -1,6 +1,8 @@ # Wire protocol v1 -How the firmware talks to the host over UART0 (921600 baud, 8N1). +How the firmware and the host talk over UART0 (921600 baud, 8N1). Most +traffic is device to host; the host can send a small set of commands using +the same framing. ## Why not CSV @@ -37,6 +39,14 @@ frame = COBS( type:u8 | body | crc16:u16le ) 0x00 | `0x02` | `SAMPLE` | 98-byte packed struct, below | | `0x03` | `STATUS` | `rb_drops:u32`, `samples_sent:u32` | | `0x04` | `LOG` | ASCII text (sensor init results, warnings) | +| `0x05` | `ACK` | `cmd:u8`, `status:u8`, `signal:u8` — the answer to a command | + +Host to device: + +| Type | Name | Body | +|---|---|---| +| `0x10` | `SET_PINS` | `sda:u8`, `scl:u8`, `gps_rx:u8`, `gps_tx:u8` (GPIO numbers) | +| `0x11` | `RESET_PINS` | empty | ### HELLO @@ -51,6 +61,9 @@ Keys: | `git` | `abc1234` | Git revision of the build | | `imu_hz`, `mag_hz`, `baro_hz`, `gps_hz` | `500` | Configured sample rates | | `sensors` | `imu,mag,baro,gps` | Sensors that initialised | +| `id` | `7cdfa1e2b3c4` | Unique id of this chip: its factory MAC address, 12 hex digits | +| `pins` | `21,22,16,17` | GPIOs in use, in the order `sda,scl,gps_rx,gps_tx` | +| `pin_src` | `default` or `stored` | Whether the pins are the board defaults or were set on this device | Hosts must ignore keys they do not know, and must refuse a `proto` they do not support. @@ -84,6 +97,40 @@ Sent once per second. `rb_drops` counts rows the sensor task dropped because the ring buffer was full (the UART could not keep up). `samples_sent` is the total number of `SAMPLE` frames written. +## Commands + +Each physical board can keep its own pin assignment. The pins are stored in +the chip's non-volatile storage, survive a firmware update, and are lost +only by a full flash erase. + +- `SET_PINS` asks the device to use the given GPIOs. The device checks them + against the pin rules built into its firmware (`chips/.json` plus + the board's reserved pins). It never stores an assignment that fails. +- `RESET_PINS` forgets the stored pins; the board defaults apply again. +- The device answers every command with one `ACK`. On `status = 0` it then + restarts, and the next `HELLO` shows the pins now in use. +- Frames longer than 16 body bytes, and frames whose CRC fails, are dropped + without an answer. A host should retry if no `ACK` arrives within 1 s. +- The CSV debug build takes no commands. + +`ACK.status`: + +| Value | Meaning | +|---|---| +| 0 | Done. The device restarts to apply it | +| 1 | The command body has the wrong length | +| 2 | A GPIO does not exist on this chip, or is blocked or reserved | +| 3 | A signal that must be driven was put on an input-only GPIO | +| 4 | Two signals were put on the same GPIO | +| 5 | The setting could not be written | +| 6 | Unknown command | + +`ACK.signal` names the first signal the status refers to (`0` sda, `1` scl, +`2` gps_rx, `3` gps_tx), or `0xFF` if it refers to none. + +The UART0 pins are always blocked, so no pin assignment can cut the host +link: a board with wrong pins still answers `RESET_PINS`. + ## Versioning `proto` changes whenever an existing frame's layout changes. Adding a new @@ -91,7 +138,9 @@ frame type or a new HELLO key does not change it. ## Reference implementation and tests -- Encoder: `include/wire.h` (header-only, no Arduino dependencies). -- Host tests: `tools/host/test_wire.cpp`, run in CI. +- Encoder and command receiver: `include/wire.h`; pin check: + `include/pin_config.h` (both header-only, no Arduino dependencies). +- Host tests: `tools/host/test_wire.cpp` and `tools/host/test_pins.cpp`, + run in CI. - `tools/host/wire_dump.cpp` emits the golden stream that the Python decoder in `data-pipeline` is tested against. diff --git a/include/config.h b/include/config.h index 6dbc0d1..3f98ae2 100644 --- a/include/config.h +++ b/include/config.h @@ -19,6 +19,15 @@ #define GPS_UART_NUM 2 #endif +// Allowed-pin masks for user-chosen pins (bit n = GPIO n), generated from +// chips/.json and the board manifest. See include/pin_config.h. +#ifndef MSNS_PIN_MASK_OUT +#define MSNS_PIN_MASK_OUT 0x30eef6010ULL +#endif +#ifndef MSNS_PIN_MASK_IN +#define MSNS_PIN_MASK_IN 0xff0eef6010ULL +#endif + // ── I²C ──────────────────────────────────────────────── #define I2C_FREQ_HZ 400000 diff --git a/include/device_config.h b/include/device_config.h new file mode 100644 index 0000000..262ae0f --- /dev/null +++ b/include/device_config.h @@ -0,0 +1,24 @@ +#pragma once +#include "pin_config.h" + +// ── PER-DEVICE SETTINGS ──────────────────────────────── +// Settings that belong to one physical board, kept in the chip's +// non-volatile storage so they survive a firmware update. + +// Unique id of this chip: the factory MAC address as 12 lowercase hex +// digits, in the order esptool prints it. +const char *device_id(); + +// Pins in use: the stored ones if present and still allowed by this +// build's rules, otherwise the board manifest defaults. Call once at boot. +PinConfig device_pins_load(); + +// True if device_pins_load() returned stored pins rather than defaults. +bool device_pins_stored(); + +// Check and store. Returns PIN_OK only if the pins were written; they take +// effect at the next boot. `signal` receives the offending signal, if any. +PinStatus device_pins_save(const PinConfig &pins, uint8_t *signal); + +// Forget the stored pins. Returns PIN_OK or PIN_ERR_STORAGE. +PinStatus device_pins_clear(); diff --git a/include/pin_config.h b/include/pin_config.h new file mode 100644 index 0000000..21dc5f0 --- /dev/null +++ b/include/pin_config.h @@ -0,0 +1,66 @@ +#pragma once +// ── PIN CONFIGURATION ────────────────────────────────── +// Which GPIO carries each sensor signal on this particular board, and the +// check that decides whether an assignment is allowed. Header-only and free +// of Arduino dependencies so the host tests compile the same code. +// +// The allowed-pin masks come from chips/.json and the board manifest +// (scripts/boards.py: pin_masks). Bit n set = GPIO n may be used. + +#include + +struct PinConfig { + uint8_t sda; + uint8_t scl; + uint8_t gps_rx; + uint8_t gps_tx; +}; + +// Order of the signals in a SET_PINS command and in the HELLO `pins` key. +enum PinSignal : uint8_t { + PIN_SIG_SDA = 0, + PIN_SIG_SCL = 1, + PIN_SIG_GPS_RX = 2, + PIN_SIG_GPS_TX = 3, + PIN_SIG_COUNT = 4, + PIN_SIG_NONE = 0xFF, +}; + +// Also the `status` byte of an ACK frame (docs/wire-protocol.md). +enum PinStatus : uint8_t { + PIN_OK = 0, + PIN_ERR_LENGTH = 1, // command body has the wrong size + PIN_ERR_NOT_ALLOWED = 2, // GPIO does not exist, or is blocked or reserved + PIN_ERR_INPUT_ONLY = 3, // signal needs an output, GPIO can only read + PIN_ERR_SHARED = 4, // two signals on one GPIO + PIN_ERR_STORAGE = 5, // could not write the setting + PIN_ERR_UNKNOWN = 6, // unknown command +}; + +// Check an assignment. `out_mask`: GPIOs that can drive a signal. +// `in_mask`: GPIOs that can read one (a superset of out_mask). On failure +// `*signal` is the first offending signal. +inline PinStatus pincfg_check(const PinConfig &c, uint64_t out_mask, uint64_t in_mask, + uint8_t *signal = nullptr) { + const uint8_t pin[PIN_SIG_COUNT] = {c.sda, c.scl, c.gps_rx, c.gps_tx}; + PinStatus status = PIN_OK; + uint8_t at = PIN_SIG_NONE; + for (uint8_t i = 0; i < PIN_SIG_COUNT && status == PIN_OK; i++) { + bool can_read = pin[i] < 64 && ((in_mask >> pin[i]) & 1); + bool can_drive = pin[i] < 64 && ((out_mask >> pin[i]) & 1); + if (!can_read) { + status = PIN_ERR_NOT_ALLOWED; + } else if (i != PIN_SIG_GPS_RX && !can_drive) { + status = PIN_ERR_INPUT_ONLY; // only gps_rx may sit on an input-only GPIO + } else { + for (uint8_t k = 0; k < i; k++) + if (pin[k] == pin[i]) + status = PIN_ERR_SHARED; + } + if (status != PIN_OK) + at = i; + } + if (signal) + *signal = at; + return status; +} diff --git a/include/transport.h b/include/transport.h index fde2968..6a2abf8 100644 --- a/include/transport.h +++ b/include/transport.h @@ -1,4 +1,5 @@ #pragma once +#include "pin_config.h" #include "sensor_row.h" #include @@ -15,10 +16,19 @@ void transport_begin(); // Free-text message (sensor init results, warnings). void transport_log(const char *msg); -// Identify the firmware. `sensors` is a comma-separated list of the -// sensors that initialised, e.g. "imu,mag,baro,gps". +// Tell the transport which pins are in use, for the hello. Call once, +// before the first transport_hello(). +void transport_set_pins(const PinConfig &pins, bool stored); + +// Identify the firmware and this device. `sensors` is a comma-separated +// list of the sensors that initialised, e.g. "imu,mag,baro,gps". void transport_hello(const char *sensors); +// Read and act on commands from the host (binary transport only). A pin +// change that is accepted is stored, acknowledged, and applied by +// restarting, so this call may not return. +void transport_poll(); + void transport_sample(const SensorRow &row); // Call about once per second with the running ring-buffer drop count. diff --git a/include/wire.h b/include/wire.h index f96db61..87ec6f5 100644 --- a/include/wire.h +++ b/include/wire.h @@ -24,6 +24,11 @@ enum WireType : uint8_t { WIRE_SAMPLE = 0x02, // WireSample WIRE_STATUS = 0x03, // WireStatus WIRE_LOG = 0x04, // ASCII text, no NUL + WIRE_ACK = 0x05, // WireAck: the answer to a command + + // Host → device commands. Same framing as everything else. + WIRE_CMD_SET_PINS = 0x10, // sda:u8 | scl:u8 | gps_rx:u8 | gps_tx:u8 + WIRE_CMD_RESET_PINS = 0x11, // empty: forget the stored pins }; #pragma pack(push, 1) @@ -49,10 +54,17 @@ struct WireStatus { uint32_t rb_drops; // rows dropped because the ring buffer was full uint32_t samples_sent; // total WIRE_SAMPLE frames written }; + +struct WireAck { + uint8_t cmd; // the command type being answered + uint8_t status; // PinStatus: 0 = done, the device restarts to apply it + uint8_t signal; // PinSignal the status refers to, 0xFF if none +}; #pragma pack(pop) static_assert(sizeof(WireSample) == 98, "WireSample layout is part of the wire protocol"); static_assert(sizeof(WireStatus) == 8, "WireStatus layout is part of the wire protocol"); +static_assert(sizeof(WireAck) == 3, "WireAck layout is part of the wire protocol"); #define WIRE_MAX_BODY 200 // type + body + crc, plus COBS overhead (1 byte per 254) and the delimiter. @@ -108,3 +120,71 @@ inline size_t wire_frame(uint8_t type, const uint8_t *body, size_t len, uint8_t out[n++] = 0x00; return n; } + +// ── RECEIVING (host → device commands) ───────────────── + +// Inverse of wire_cobs_encode. Returns the decoded length, or -1 if the +// input is malformed or does not fit in `cap`. +inline int wire_cobs_decode(const uint8_t *in, size_t len, uint8_t *out, size_t cap) { + size_t r = 0, w = 0; + while (r < len) { + uint8_t code = in[r++]; + if (code == 0) + return -1; + for (uint8_t k = 1; k < code; k++) { + if (r >= len || w >= cap || in[r] == 0) + return -1; + out[w++] = in[r++]; + } + if (code != 0xFF && r < len) { + if (w >= cap) + return -1; + out[w++] = 0; + } + } + return (int)w; +} + +// Commands are tiny; anything longer than this is not for us. +#define WIRE_RX_MAX_BODY 16 +#define WIRE_RX_MAX_FRAME (WIRE_RX_MAX_BODY + 3 + 1) + +// Collects bytes up to each 0x00 delimiter and hands back one checked +// command at a time. Oversized or corrupt frames are dropped whole. +struct WireReceiver { + uint8_t buf[WIRE_RX_MAX_FRAME]; + uint8_t len = 0; + bool overflow = false; + uint8_t body[WIRE_RX_MAX_BODY]; + uint8_t body_len = 0; + uint8_t type = 0; + + // Feed one received byte. Returns true when `type`, `body` and + // `body_len` hold a complete frame whose CRC is correct. + bool feed(uint8_t byte) { + if (byte != 0x00) { + if (len < sizeof(buf)) + buf[len++] = byte; + else + overflow = true; + return false; + } + bool ok = false; + uint8_t raw[WIRE_RX_MAX_BODY + 3]; + if (!overflow && len > 0) { + int n = wire_cobs_decode(buf, len, raw, sizeof(raw)); + if (n >= 3) { + uint16_t crc = (uint16_t)(raw[n - 2] | (raw[n - 1] << 8)); + if (crc == wire_crc16(raw, (size_t)n - 2)) { + type = raw[0]; + body_len = (uint8_t)(n - 3); + memcpy(body, raw + 1, body_len); + ok = true; + } + } + } + len = 0; + overflow = false; + return ok; + } +}; diff --git a/scripts/board.py b/scripts/board.py index c785e3e..9eb0207 100644 --- a/scripts/board.py +++ b/scripts/board.py @@ -11,7 +11,7 @@ board = boards.load(board_id) for name, value in boards.defines(board).items(): - if isinstance(value, str): + if name == "MSNS_BOARD_ID": # the only string; the rest are numeric literals value = env.StringifyMacro(value) # noqa: F821 env.Append(CPPDEFINES=[(name, value)]) # noqa: F821 diff --git a/scripts/boards.py b/scripts/boards.py index 9f954e8..5794df4 100644 --- a/scripts/boards.py +++ b/scripts/boards.py @@ -94,10 +94,35 @@ def load_all() -> list[dict]: return [load(p.stem) for p in sorted(BOARDS_DIR.glob("*.json"))] +def pin_masks(chip: dict, reserved=None) -> tuple[int, int]: + """(out_mask, in_mask) for the firmware's own check: bit n set means + GPIO n may drive a signal / may read one. Mirrors pin_errors().""" + usable = {g for g in chip["gpio"] if str(g) not in chip["blocked"] and str(g) not in (reserved or {})} + if any(g > 63 for g in usable): + raise BoardError(f"{chip['chip']}: GPIO numbers above 63 do not fit the pin mask") + in_mask = sum(1 << g for g in usable) + out_mask = sum(1 << g for g in usable - set(chip["input_only"])) + return out_mask, in_mask + + +def pin_rules(board: dict) -> dict: + """The chip's rules with this board's reserved pins folded in: what a + host needs to validate a user's pin choice and give the reason.""" + chip = load_chip(board["chip"]) + return { + "gpio": chip["gpio"], + "input_only": chip["input_only"], + "blocked": {**chip["blocked"], **{g: f"reserved on this board: {why}" for g, why in board.get("reserved", {}).items()}}, + } + + def defines(board: dict) -> dict: """C preprocessor definitions that config.h and version.h pick up.""" pins = board["pins"] + out_mask, in_mask = pin_masks(load_chip(board["chip"]), board.get("reserved")) return { + "MSNS_PIN_MASK_OUT": f"{out_mask:#x}ULL", + "MSNS_PIN_MASK_IN": f"{in_mask:#x}ULL", "MSNS_BOARD_ID": board["id"], "PIN_SDA": pins["sda"], "PIN_SCL": pins["scl"], diff --git a/src/device_config.cpp b/src/device_config.cpp new file mode 100644 index 0000000..2351596 --- /dev/null +++ b/src/device_config.cpp @@ -0,0 +1,68 @@ +#include +#include + +#include "config.h" +#include "device_config.h" + +static const char NVS_NAMESPACE[] = "msns"; +static const char NVS_KEY_PINS[] = "pins"; + +static const PinConfig DEFAULT_PINS = {PIN_SDA, PIN_SCL, PIN_GPS_RX, PIN_GPS_TX}; +static bool s_stored = false; + +const char *device_id() { + static char id[13] = ""; + if (!id[0]) { + // getEfuseMac() packs the first MAC octet into the lowest byte. + uint64_t mac = ESP.getEfuseMac(); + for (int i = 0; i < 6; i++) + snprintf(id + 2 * i, 3, "%02x", (unsigned)((mac >> (8 * i)) & 0xFF)); + } + return id; +} + +PinConfig device_pins_load() { + PinConfig pins = DEFAULT_PINS; + s_stored = false; + + Preferences prefs; + if (prefs.begin(NVS_NAMESPACE, true)) { + uint8_t raw[PIN_SIG_COUNT]; + if (prefs.getBytesLength(NVS_KEY_PINS) == sizeof(raw) && + prefs.getBytes(NVS_KEY_PINS, raw, sizeof(raw)) == sizeof(raw)) { + PinConfig stored = {raw[0], raw[1], raw[2], raw[3]}; + // Checked again here: the rules may be stricter in this build + // than in the one that stored the pins. + if (pincfg_check(stored, MSNS_PIN_MASK_OUT, MSNS_PIN_MASK_IN) == PIN_OK) { + pins = stored; + s_stored = true; + } + } + prefs.end(); + } + return pins; +} + +bool device_pins_stored() { return s_stored; } + +PinStatus device_pins_save(const PinConfig &pins, uint8_t *signal) { + PinStatus status = pincfg_check(pins, MSNS_PIN_MASK_OUT, MSNS_PIN_MASK_IN, signal); + if (status != PIN_OK) return status; + + const uint8_t raw[PIN_SIG_COUNT] = {pins.sda, pins.scl, pins.gps_rx, pins.gps_tx}; + Preferences prefs; + if (!prefs.begin(NVS_NAMESPACE, false)) return PIN_ERR_STORAGE; + size_t written = prefs.putBytes(NVS_KEY_PINS, raw, sizeof(raw)); + prefs.end(); + return written == sizeof(raw) ? PIN_OK : PIN_ERR_STORAGE; +} + +PinStatus device_pins_clear() { + Preferences prefs; + if (!prefs.begin(NVS_NAMESPACE, false)) return PIN_ERR_STORAGE; + // remove() reports false when the key was never set; that is still "cleared". + if (prefs.isKey(NVS_KEY_PINS)) prefs.remove(NVS_KEY_PINS); + bool gone = !prefs.isKey(NVS_KEY_PINS); + prefs.end(); + return gone ? PIN_OK : PIN_ERR_STORAGE; +} diff --git a/src/main.cpp b/src/main.cpp index cb41cd2..82efb68 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,6 +8,7 @@ #include #include "config.h" +#include "device_config.h" #include "esp_task_wdt.h" #include "sensor_row.h" #include "transport.h" @@ -52,10 +53,14 @@ bool init_sensors(); void setup() { transport_begin(); - Wire.begin(PIN_SDA, PIN_SCL); + // This board's own pins if it has any stored, else the manifest defaults. + const PinConfig pins = device_pins_load(); + transport_set_pins(pins, device_pins_stored()); + + Wire.begin(pins.sda, pins.scl); Wire.setClock(I2C_FREQ_HZ); - gpsSerial.begin(GPS_BAUD, SERIAL_8N1, PIN_GPS_RX, PIN_GPS_TX); + gpsSerial.begin(GPS_BAUD, SERIAL_8N1, pins.gps_rx, pins.gps_tx); if (!init_sensors()) { transport_log("WARN: some sensors missing — logging available sensors only."); @@ -330,6 +335,9 @@ void task_serial(void* pv) { transport_sample(row); } + // Commands from the host (pin changes). + transport_poll(); + // Heartbeat once per second: reports ring buffer drops (the serial // output not keeping up with the sensor rate) and, on the binary // transport, re-announces the firmware identity. diff --git a/src/transport.cpp b/src/transport.cpp index 452c35a..f2939f9 100644 --- a/src/transport.cpp +++ b/src/transport.cpp @@ -1,11 +1,19 @@ #include #include "config.h" +#include "device_config.h" #include "transport.h" #include "version.h" #include "wire.h" static uint32_t s_samples_sent = 0; +static PinConfig s_pins = {PIN_SDA, PIN_SCL, PIN_GPS_RX, PIN_GPS_TX}; +static bool s_pins_stored = false; + +void transport_set_pins(const PinConfig &pins, bool stored) { + s_pins = pins; + s_pins_stored = stored; +} void transport_begin() { // A larger TX buffer lets task_serial queue a burst of frames without @@ -21,10 +29,14 @@ void transport_begin() { } static int format_hello(char *buf, size_t size, const char *sensors) { + // `pins` is sda,scl,gps_rx,gps_tx (the PinSignal order). return snprintf(buf, size, - "board=%s;fw=%s;git=%s;imu_hz=%d;mag_hz=%d;baro_hz=%d;gps_hz=%d;sensors=%s", + "board=%s;fw=%s;git=%s;imu_hz=%d;mag_hz=%d;baro_hz=%d;gps_hz=%d;sensors=%s;" + "id=%s;pins=%u,%u,%u,%u;pin_src=%s", MSNS_BOARD_ID, MSNS_FW_VERSION, MSNS_GIT_SHA, - IMU_HZ, MAG_HZ, BARO_HZ, GPS_HZ, sensors); + IMU_HZ, MAG_HZ, BARO_HZ, GPS_HZ, sensors, + device_id(), s_pins.sda, s_pins.scl, s_pins.gps_rx, s_pins.gps_tx, + s_pins_stored ? "stored" : "default"); } #if MSNS_WIRE_CSV @@ -45,7 +57,7 @@ void transport_log(const char *msg) { } void transport_hello(const char *sensors) { - char text[160]; + char text[WIRE_MAX_BODY]; format_hello(text, sizeof(text), sensors); Serial.print("# hello "); Serial.println(text); @@ -91,6 +103,9 @@ void transport_heartbeat(uint32_t rb_drops, const char *sensors) { if (rb_drops > 0) Serial.printf("# rb_drops=%u\n", rb_drops); } +// The CSV build is a read-only debug stream; it takes no commands. +void transport_poll() {} + #else // ══════════════════════════════════════════════════════ // BINARY TRANSPORT (default) — see wire.h @@ -147,4 +162,47 @@ void transport_heartbeat(uint32_t rb_drops, const char *sensors) { // mid-stream can identify the firmware without resetting the board. if (++s_heartbeats % 2 == 0) transport_hello(sensors); } + +static void send_ack(uint8_t cmd, PinStatus status, uint8_t signal) { + WireAck ack = {cmd, (uint8_t)status, signal}; + send_frame(WIRE_ACK, &ack, sizeof(ack)); +} + +// Pins are read once at boot, so an accepted change is applied by +// restarting. The acknowledgement is flushed first so the host sees it. +static void restart_to_apply() { + Serial.flush(); + delay(50); + ESP.restart(); +} + +static void handle_command(const WireReceiver &rx) { + uint8_t signal = PIN_SIG_NONE; + PinStatus status; + switch (rx.type) { + case WIRE_CMD_SET_PINS: + if (rx.body_len != PIN_SIG_COUNT) { + status = PIN_ERR_LENGTH; + } else { + PinConfig pins = {rx.body[0], rx.body[1], rx.body[2], rx.body[3]}; + status = device_pins_save(pins, &signal); + } + break; + case WIRE_CMD_RESET_PINS: + status = rx.body_len == 0 ? device_pins_clear() : PIN_ERR_LENGTH; + break; + default: + status = PIN_ERR_UNKNOWN; + break; + } + send_ack(rx.type, status, signal); + if (status == PIN_OK) restart_to_apply(); +} + +void transport_poll() { + static WireReceiver rx; + while (Serial.available()) { + if (rx.feed((uint8_t)Serial.read())) handle_command(rx); + } +} #endif diff --git a/tools/host/test_pins.cpp b/tools/host/test_pins.cpp new file mode 100644 index 0000000..c6f8ec2 --- /dev/null +++ b/tools/host/test_pins.cpp @@ -0,0 +1,107 @@ +// Host-side tests for command receiving (wire.h) and the pin check +// (pin_config.h). +// g++ -std=c++17 -Wall -Wextra -Werror -Iinclude tools/host/test_pins.cpp -o test_pins && ./test_pins +#include +#include +#include +#include + +#include "config.h" +#include "pin_config.h" +#include "wire.h" + +static std::vector frame_of(uint8_t type, const std::vector &body) { + uint8_t frame[WIRE_MAX_FRAME]; + size_t n = wire_frame(type, body.data(), body.size(), frame); + assert(n > 0); + return std::vector(frame, frame + n); +} + +// Feed bytes; return how many complete frames came out, keeping the last. +static int feed_all(WireReceiver &rx, const std::vector &bytes) { + int frames = 0; + for (uint8_t b : bytes) + if (rx.feed(b)) + frames++; + return frames; +} + +static void test_receiver() { + WireReceiver rx; + + // A command round-trips through the encoder and the receiver. + assert(feed_all(rx, frame_of(WIRE_CMD_SET_PINS, {21, 22, 16, 17})) == 1); + assert(rx.type == WIRE_CMD_SET_PINS && rx.body_len == 4); + assert(rx.body[0] == 21 && rx.body[1] == 22 && rx.body[2] == 16 && rx.body[3] == 17); + + // Zero bytes in the body survive the stuffing; an empty body works. + assert(feed_all(rx, frame_of(WIRE_CMD_SET_PINS, {0, 0, 4, 0})) == 1); + assert(rx.body_len == 4 && rx.body[0] == 0 && rx.body[2] == 4 && rx.body[3] == 0); + assert(feed_all(rx, frame_of(WIRE_CMD_RESET_PINS, {})) == 1); + assert(rx.type == WIRE_CMD_RESET_PINS && rx.body_len == 0); + + // Every body size the receiver accepts. + for (size_t len = 0; len <= WIRE_RX_MAX_BODY; len++) { + std::vector body(len); + for (size_t i = 0; i < len; i++) + body[i] = (uint8_t)(i % 3 == 0 ? 0 : 0xF0 + i); + assert(feed_all(rx, frame_of(0x7E, body)) == 1); + assert(rx.type == 0x7E && rx.body_len == len); + assert(memcmp(rx.body, body.data(), len) == 0); + } + + // Any single corrupted byte is rejected, and the next frame still parses. + std::vector good = frame_of(WIRE_CMD_SET_PINS, {21, 22, 16, 17}); + for (size_t i = 0; i + 1 < good.size(); i++) { + std::vector bad = good; + bad[i] ^= 0x55; + if (bad[i] == 0) + continue; // that would split the frame instead of corrupting it + assert(feed_all(rx, bad) == 0); + assert(feed_all(rx, good) == 1); + } + + // Oversized frames are dropped whole and do not disturb what follows. + assert(feed_all(rx, frame_of(WIRE_LOG, std::vector(WIRE_RX_MAX_BODY + 1, 7))) == 0); + assert(feed_all(rx, frame_of(WIRE_LOG, std::vector(WIRE_MAX_BODY, 7))) == 0); + assert(feed_all(rx, good) == 1); + + // Noise, empty frames and a mid-frame start are ignored. + assert(feed_all(rx, {0, 0, 0}) == 0); + assert(feed_all(rx, {0x41, 0x54, 0x0D, 0x0A, 0}) == 0); + std::vector tail(good.begin() + 2, good.end()); + assert(feed_all(rx, tail) == 0); + assert(feed_all(rx, good) == 1); +} + +static void test_pin_check() { + // The esp32dev masks from config.h (no -D given to this build). + const uint64_t OUT = MSNS_PIN_MASK_OUT, IN = MSNS_PIN_MASK_IN; + uint8_t sig = 0; + + assert(pincfg_check({21, 22, 16, 17}, OUT, IN, &sig) == PIN_OK && sig == PIN_SIG_NONE); + assert(pincfg_check({21, 22, 34, 17}, OUT, IN) == PIN_OK); // gps_rx may be input-only + + assert(pincfg_check({6, 22, 16, 17}, OUT, IN, &sig) == PIN_ERR_NOT_ALLOWED && sig == PIN_SIG_SDA); // flash + assert(pincfg_check({21, 12, 16, 17}, OUT, IN, &sig) == PIN_ERR_NOT_ALLOWED && sig == PIN_SIG_SCL); // strapping + assert(pincfg_check({21, 22, 3, 17}, OUT, IN, &sig) == PIN_ERR_NOT_ALLOWED && sig == PIN_SIG_GPS_RX); // host link + assert(pincfg_check({21, 22, 16, 24}, OUT, IN, &sig) == PIN_ERR_NOT_ALLOWED && sig == PIN_SIG_GPS_TX); // no such GPIO + assert(pincfg_check({21, 22, 16, 64}, OUT, IN) == PIN_ERR_NOT_ALLOWED); // beyond the mask + assert(pincfg_check({21, 22, 16, 255}, OUT, IN) == PIN_ERR_NOT_ALLOWED); + + assert(pincfg_check({34, 22, 16, 17}, OUT, IN, &sig) == PIN_ERR_INPUT_ONLY && sig == PIN_SIG_SDA); + assert(pincfg_check({21, 22, 16, 35}, OUT, IN, &sig) == PIN_ERR_INPUT_ONLY && sig == PIN_SIG_GPS_TX); + + assert(pincfg_check({21, 21, 16, 17}, OUT, IN, &sig) == PIN_ERR_SHARED && sig == PIN_SIG_SCL); + assert(pincfg_check({21, 22, 16, 21}, OUT, IN, &sig) == PIN_ERR_SHARED && sig == PIN_SIG_GPS_TX); + + // With nothing allowed, nothing passes. + assert(pincfg_check({21, 22, 16, 17}, 0, 0) == PIN_ERR_NOT_ALLOWED); +} + +int main() { + test_receiver(); + test_pin_check(); + puts("commands and pin check: all host tests passed"); + return 0; +} diff --git a/tools/release.py b/tools/release.py index cf2fc2e..f010b3f 100644 --- a/tools/release.py +++ b/tools/release.py @@ -123,6 +123,9 @@ def main() -> int: "sha256": hashlib.sha256(image.read_bytes()).hexdigest(), "size": image.stat().st_size, "offset": "0x0", + # What a host needs to offer a pin choice and explain a refusal. + "pins": board["pins"], + "pin_rules": boards.pin_rules(board), } print(f" {image.name} {manifest['boards'][board['id']]['sha256'][:16]}…") diff --git a/tools/test_pin_rules.py b/tools/test_pin_rules.py index db53c2f..174548e 100644 --- a/tools/test_pin_rules.py +++ b/tools/test_pin_rules.py @@ -50,6 +50,30 @@ def main() -> int: chip = boards.load_chip(board["chip"]) assert boards.pin_errors(board["pins"], board["gps_uart"], chip, board.get("reserved")) == [], board["id"] + # The masks compiled into the firmware allow exactly what pin_errors allows. + for board in boards.load_all(): + chip = boards.load_chip(board["chip"]) + reserved = board.get("reserved") + out_mask, in_mask = boards.pin_masks(chip, reserved) + assert out_mask & ~in_mask == 0, board["id"] + free = [g for g in range(64) if (out_mask >> g) & 1] + for gpio in range(64): + a, b, c = [g for g in free if g != gpio][:3] # three other pins known to be fine + as_output = {"sda": gpio, "scl": a, "gps_rx": b, "gps_tx": c} + as_input = {"sda": a, "scl": b, "gps_rx": gpio, "gps_tx": c} + uart = board["gps_uart"] + assert (boards.pin_errors(as_output, uart, chip, reserved) == []) == bool((out_mask >> gpio) & 1), (board["id"], gpio) + assert (boards.pin_errors(as_input, uart, chip, reserved) == []) == bool((in_mask >> gpio) & 1), (board["id"], gpio) + + # config.h's fallback masks (builds made outside PlatformIO) are the esp32dev ones. + config = (boards.ROOT / "include" / "config.h").read_text() + esp32dev = boards.defines(boards.load("esp32dev")) + for name in ("MSNS_PIN_MASK_OUT", "MSNS_PIN_MASK_IN"): + assert f"#define {name} {esp32dev[name]}" in config, name + + rules = boards.pin_rules(boards.load("esp32-s3-devkitc-1")) + assert "35" in rules["blocked"] and "19" in rules["blocked"] + print("pin rules OK") return 0