Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<chip>.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`.
Expand Down
5 changes: 5 additions & 0 deletions docs/boards.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
55 changes: 52 additions & 3 deletions docs/wire-protocol.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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

Expand All @@ -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.
Expand Down Expand Up @@ -84,14 +97,50 @@ 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/<chip>.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
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.
9 changes: 9 additions & 0 deletions include/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@
#define GPS_UART_NUM 2
#endif

// Allowed-pin masks for user-chosen pins (bit n = GPIO n), generated from
// chips/<chip>.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

Expand Down
24 changes: 24 additions & 0 deletions include/device_config.h
Original file line number Diff line number Diff line change
@@ -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();
66 changes: 66 additions & 0 deletions include/pin_config.h
Original file line number Diff line number Diff line change
@@ -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/<chip>.json and the board manifest
// (scripts/boards.py: pin_masks). Bit n set = GPIO n may be used.

#include <stdint.h>

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;
}
14 changes: 12 additions & 2 deletions include/transport.h
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#pragma once
#include "pin_config.h"
#include "sensor_row.h"
#include <stdint.h>

Expand All @@ -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.
Expand Down
80 changes: 80 additions & 0 deletions include/wire.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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;
}
};
2 changes: 1 addition & 1 deletion scripts/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading