From 5be65c212991a506de3a5ed4035abb1d492e6454 Mon Sep 17 00:00:00 2001 From: Shivtej Gaikwad <91597404+ShivtejG236@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:31:27 +0000 Subject: [PATCH 1/2] Replace CSV with a binary wire protocol as the default host stream One CSV row is about 177 bytes, which is 96% of the 921600-baud link at 500 Hz. Samples are now sent as COBS-framed, CRC-16 checked binary frames of at most 103 bytes (about 56% of the link) with a sequence number. - include/wire.h: protocol v1 framing, header-only and Arduino-free - src/transport.cpp: host output behind a small interface; the CSV stream stays available as the esp32dev-csv environment - HELLO frame (board, version, git revision, rates, sensors) at boot and every 2 s; STATUS frame every second - tools/host: protocol tests run in CI, plus the golden stream generator used by the data-pipeline decoder tests - docs/wire-protocol.md: specification --- .github/workflows/build.yml | 9 +++ CHANGELOG.md | 14 ++++ README.md | 64 ++++++++++------ docs/wire-protocol.md | 95 +++++++++++++++++++++++ include/transport.h | 25 +++++++ include/version.h | 12 +++ include/wire.h | 110 +++++++++++++++++++++++++++ platformio.ini | 17 ++++- scripts/version.py | 13 ++++ src/main.cpp | 90 +++++++--------------- src/transport.cpp | 145 ++++++++++++++++++++++++++++++++++++ tools/host/test_wire.cpp | 73 ++++++++++++++++++ tools/host/wire_dump.cpp | 59 +++++++++++++++ 13 files changed, 638 insertions(+), 88 deletions(-) create mode 100644 docs/wire-protocol.md create mode 100644 include/transport.h create mode 100644 include/version.h create mode 100644 include/wire.h create mode 100644 scripts/version.py create mode 100644 src/transport.cpp create mode 100644 tools/host/test_wire.cpp create mode 100644 tools/host/wire_dump.cpp diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9e07877..c8b4e10 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -13,6 +13,15 @@ concurrency: cancel-in-progress: true jobs: + host-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Wire protocol tests + run: | + g++ -std=c++17 -Wall -Wextra -Werror -Iinclude tools/host/test_wire.cpp -o test_wire + ./test_wire + build: runs-on: ubuntu-latest steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index b5851be..d5caa6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Changed +- **Binary wire protocol (v1)** replaces CSV as the default host stream: + COBS-framed, CRC-16 checked, with sequence numbers. A sample is at most + 103 bytes instead of about 177, taking the 921600-baud link from about + 96 % to about 56 % utilisation at 500 Hz. See `docs/wire-protocol.md`. +- Host output moved out of `main.cpp` into `src/transport.cpp`. + +### Added +- `HELLO` frame announcing board, firmware version, git revision, protocol + version, sample rates and detected sensors, at boot and every 2 s. +- `STATUS` frame once per second with ring-buffer drops and samples sent. +- `esp32dev-csv` environment: the original CSV stream as a debug build. +- Host-side protocol tests (`tools/host/`), run in CI. + ### Added - MIT `LICENSE` file (the README badge already pointed at one). - CI build of the `esp32dev` environment on every push and pull request. diff --git a/README.md b/README.md index 1feb59e..5879f05 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ > **Repo 1 of 4** · 500 Hz deterministic multi-sensor data acquisition firmware for real-time navigation systems. > -> Streams fused IMU · magnetometer · barometer · GPS telemetry as timestamped CSV over UART at 921600 baud. +> Streams fused IMU · magnetometer · barometer · GPS telemetry as checksummed binary frames over UART at 921600 baud. > > ⚠️ *This repository was named `navigation-system-firmware` before moving under the `multi-sensor-navigation-system` organization from [@ShivtejG236](https://github.com/ShivtejG236).* @@ -23,7 +23,7 @@ The firmware runs two pinned FreeRTOS tasks: | Task | Core | Priority | Responsibility | |---|---|---|---| | `task_sensors` | 1 | 5 | IMU/mag/baro polling, ring-buffer producer | -| `task_serial` | 0 | 3 | GPS UART drain, CSV output, ring-buffer consumer | +| `task_serial` | 0 | 3 | GPS UART drain, host output, ring-buffer consumer | The split exists by design: `task_sensors` busy-waits at 500 Hz on Core 1 so it never misses an IMU deadline. GPS UART draining lives on Core 0 — if it ran on Core 1, the Core 1 UART ISR would starve and drop NMEA bytes. @@ -49,7 +49,7 @@ graph TD GPS["NEO-6M GPS\n1 Hz NMEA drain"] SNAP["Snapshot GPS globals\ninto SensorRow"] POP["rb_pop"] - CSV["CSV → UART0\n921600 baud"] + CSV["Binary frames → UART0\n921600 baud"] GPS --> SNAP SNAP --> POP RB --> POP @@ -103,9 +103,19 @@ Lower-rate sensors are polled sub-sampled within the 500 Hz IMU loop — no sepa --- -## CSV Format & Fault Flags +## Wire Format -The firmware prints a single header line on boot, then one row per IMU tick: +The default build sends **binary frames**: `COBS(type | body | crc16)` terminated by `0x00`. Each 500 Hz sample is at most 103 bytes (about 56 % of the 921600-baud link), carries a checksum and a sequence number, and the stream resynchronises on the next `0x00` after any corruption. The firmware identifies itself (board, version, git revision, protocol version) in a `HELLO` frame at boot and every 2 s after. + +The full specification is in [`docs/wire-protocol.md`](docs/wire-protocol.md). The host logger in [Repo 2](https://github.com/multi-sensor-navigation-system/data-pipeline) decodes the frames back into the CSV columns below. + +> The original CSV stream needed about 177 bytes per row, which is 96 % of the link at 500 Hz. It is kept as a debug build: `pio run -e esp32dev-csv`. + +--- + +## Sample Fields & Fault Flags + +Each sample carries these fields (the CSV debug build prints them as one header line on boot, then one row per IMU tick):
@@ -272,11 +282,7 @@ When a lower-rate sensor misses its sub-deadline within a 500 Hz tick, the **las ## Ring Buffer -A **128-slot lock-free SPSC ring buffer** (`RING_SIZE` must be a power of 2) decouples the sensor task from the serial task. `rb_push` / `rb_pop` use `__sync_synchronize()` memory barriers to prevent store/load reordering across the two cores — no mutex, no FreeRTOS synchronisation primitive. If the ring fills (serial output can't keep up), the producer drops the row and increments `rb_drops`. Drops are reported on `Serial` once per second: - -``` -# rb_drops=12 -``` +A **128-slot lock-free SPSC ring buffer** (`RING_SIZE` must be a power of 2) decouples the sensor task from the serial task. `rb_push` / `rb_pop` use `__sync_synchronize()` memory barriers to prevent store/load reordering across the two cores — no mutex, no FreeRTOS synchronisation primitive. If the ring fills (serial output can't keep up), the producer drops the row and increments `rb_drops`. The running count is reported once per second in the `STATUS` frame (as a `# rb_drops=12` line in the CSV debug build). Designed for SPSC (single producer, single consumer); not safe for multi-writer scenarios. @@ -287,14 +293,22 @@ Designed for SPSC (single producer, single consumer); not safe for multi-writer ``` firmware/ ├── src/ -│ └── main.cpp # All firmware logic +│ ├── main.cpp # Sensor init, the two tasks +│ └── transport.cpp # Host output: binary frames (default) or CSV ├── include/ │ ├── config.h # Pin assignments, sample rates, fault flags, ring size -│ └── sensor_row.h # SensorRow struct + lock-free ring buffer +│ ├── sensor_row.h # SensorRow struct + lock-free ring buffer +│ ├── transport.h # Host transport interface +│ ├── wire.h # Wire protocol v1: framing, CRC, COBS +│ └── version.h # Firmware version +├── scripts/ +│ └── version.py # Stamps the build with the git revision +├── tools/host/ # Host-side protocol tests + golden stream generator ├── platformio.ini # PlatformIO build config ├── sdkconfig.defaults # ESP-IDF SDK overrides (task WDT tuning) └── docs/ - └── setup.png # Schematic diagram + ├── wire-protocol.md # Wire protocol specification + └── setup.png # Schematic diagram ``` --- @@ -316,24 +330,28 @@ Managed by PlatformIO — no manual installation needed. ## Build & Flash ```bash -# Build -pio run - -# Flash + open monitor -pio run --target upload && pio device monitor --baud 921600 +# Build and flash the default (binary) firmware +pio run -e esp32dev --target upload ``` -On boot you should see sensor init messages followed by the CSV header: +The binary stream is not readable in a serial monitor; log it with the host logger from [Repo 2](https://github.com/multi-sensor-navigation-system/data-pipeline), which prints the firmware's messages and writes the CSV. + +To watch the stream by eye, flash the CSV debug build: + +```bash +pio run -e esp32dev-csv --target upload && pio device monitor --baud 921600 +``` ``` # MPU-6050 OK # QMC5883L OK # BMP280 OK # GPS UART started — waiting for fix (HDOP reported in data) +# hello board=esp32dev;fw=0.2.0;git=abc1234;imu_hz=500;... t_imu_us,t_read_start_us,... ``` -If a sensor is absent, firmware continues logging available sensors and annotates the header with a `# WARN` line. `fault_flag` will reflect which sensor is missing on every row. +If a sensor is absent, firmware continues logging available sensors and reports a `WARN` message. `fault_flag` will reflect which sensor is missing on every row. --- @@ -351,12 +369,12 @@ If a sensor is absent, firmware continues logging available sensors and annotate ```mermaid graph LR - FW["🔧 firmware\nESP32 sensor acquisition\nCSV @ 921600 baud"] + FW["🔧 firmware\nESP32 sensor acquisition\nbinary frames @ 921600 baud"] PL["📡 data-pipeline\nHost logger · serial → CSV\ncleaning & calibration"] AN["📊 analysis\nEKF · Allan variance\nvisualisation · reports"] EH["🧭 edgehard\nDead reckoning\nGPS dropout modelling"] - FW -->|"UART CSV stream"| PL + FW -->|"UART binary stream"| PL PL -->|"clean .csv files"| AN PL -->|"clean .csv files"| EH AN -. "future: model feedback" .-> EH @@ -364,7 +382,7 @@ graph LR | Repo | Role | Status | |---|---|---| -| **`firmware`** ← *(this repo, formerly navigation-system-firmware)* | ESP32 firmware — sensor acquisition & CSV streaming | ✅ Active | +| **`firmware`** ← *(this repo, formerly navigation-system-firmware)* | ESP32 firmware — sensor acquisition & binary streaming | ✅ Active | | [`data-pipeline`](https://github.com/multi-sensor-navigation-system/data-pipeline) | Host-side logger & calibration — reads serial, writes timestamped CSV | ✅ Active | | [`analysis`](#) | Offline processing — EKF, Allan variance, map visualisation, reports | 🚧 In progress | | [`edgehard`](#) | Dead reckoning — GPS dropout modelling, edge inference | 🔜 Planned | diff --git a/docs/wire-protocol.md b/docs/wire-protocol.md new file mode 100644 index 0000000..b60743d --- /dev/null +++ b/docs/wire-protocol.md @@ -0,0 +1,95 @@ +# Wire protocol v1 + +How the firmware talks to the host over UART0 (921600 baud, 8N1). + +## Why not CSV + +One CSV row is about 177 bytes. At 500 Hz that is 88.5 kB/s on a link that +carries at most 92.16 kB/s, so the UART ran about 96 % full before any +status lines, and any stall dropped rows. A binary sample frame is 103 bytes +at most (51.5 kB/s, about 56 % of the link), carries a checksum, and +resynchronises after corruption. + +The CSV stream still exists as a debug build: `pio run -e esp32dev-csv`. + +## Framing + +``` +frame = COBS( type:u8 | body | crc16:u16le ) 0x00 +``` + +- **COBS** (Consistent Overhead Byte Stuffing) removes every `0x00` from the + payload, so `0x00` only ever appears as the frame delimiter. A reader that + attaches mid-stream discards bytes up to the next `0x00` and is in sync. +- **crc16** is CRC-16/CCITT-FALSE (poly `0x1021`, init `0xFFFF`) over + `type | body`. Check value: `"123456789"` → `0x29B1`. +- All multi-byte fields are little-endian. +- A frame whose CRC fails, or whose type is unknown, is dropped; the stream + continues at the next delimiter. + +## Frame types + +| Type | Name | Body | +|---|---|---| +| `0x01` | `HELLO` | `proto:u8` then ASCII `key=value;key=value` | +| `0x02` | `SAMPLE` | 98-byte packed struct, below | +| `0x03` | `STATUS` | `rb_drops:u32`, `samples_sent:u32` | +| `0x04` | `LOG` | ASCII text (sensor init results, warnings) | + +### HELLO + +Sent once at boot, before the first sample, and repeated every 2 s so a host +can attach without resetting the board. `proto` is the protocol version (1). +Keys: + +| Key | Example | Meaning | +|---|---|---| +| `board` | `esp32dev` | Board the firmware was built for | +| `fw` | `0.2.0` | Firmware version | +| `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 | + +Hosts must ignore keys they do not know, and must refuse a `proto` they do +not support. + +### SAMPLE + +| Offset | Field | Type | Unit | +|---|---|---|---| +| 0 | `seq` | u32 | sample counter; a gap means frames were lost on the wire | +| 4 | `t_imu_us` | u64 | µs, `esp_timer_get_time()` at IMU read start | +| 12 | `proc_us` | u32 | µs spent reading all sensors for this row | +| 16 | `t_gps_us` | u64 | µs, timestamp of last parsed GPS sentence | +| 24 | `ax, ay, az` | 3 × f32 | g | +| 36 | `gx, gy, gz` | 3 × f32 | °/s | +| 48 | `mx, my, mz` | 3 × f32 | µT | +| 60 | `pressure` | f32 | hPa | +| 64 | `bmp_temp` | f32 | °C | +| 68 | `lat, lon` | 2 × f64 | degrees | +| 84 | `alt_gps` | f32 | m (MSL) | +| 88 | `hdop` | f32 | — | +| 92 | `satellites` | u8 | — | +| 93 | `fault_flag` | u8 | bitmask, see README | +| 94 | `jitter_us` | u32 | µs past the IMU deadline | + +The CSV columns map one-to-one, with `t_read_start_us = t_imu_us` and +`t_proc_end_us = t_imu_us + proc_us`. + +### STATUS + +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. + +## 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. +- `tools/host/wire_dump.cpp` emits the golden stream that the Python decoder + in `data-pipeline` is tested against. diff --git a/include/transport.h b/include/transport.h new file mode 100644 index 0000000..fde2968 --- /dev/null +++ b/include/transport.h @@ -0,0 +1,25 @@ +#pragma once +#include "sensor_row.h" +#include + +// ── HOST TRANSPORT ───────────────────────────────────── +// Everything the firmware says to the host goes through these calls. +// The default build speaks the binary wire protocol (wire.h); building +// with -DMSNS_WIRE_CSV=1 keeps the original human-readable CSV stream. +// +// Not thread-safe: call from setup() before the tasks start, and from +// task_serial afterwards. task_sensors never touches the UART. + +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". +void transport_hello(const char *sensors); + +void transport_sample(const SensorRow &row); + +// Call about once per second with the running ring-buffer drop count. +void transport_heartbeat(uint32_t rb_drops, const char *sensors); diff --git a/include/version.h b/include/version.h new file mode 100644 index 0000000..71794f0 --- /dev/null +++ b/include/version.h @@ -0,0 +1,12 @@ +#pragma once + +#define MSNS_FW_VERSION "0.2.0" + +// Injected by scripts/version.py at build time. +#ifndef MSNS_GIT_SHA +#define MSNS_GIT_SHA "unknown" +#endif + +#ifndef MSNS_BOARD_ID +#define MSNS_BOARD_ID "esp32dev" +#endif diff --git a/include/wire.h b/include/wire.h new file mode 100644 index 0000000..f96db61 --- /dev/null +++ b/include/wire.h @@ -0,0 +1,110 @@ +#pragma once +// ── WIRE PROTOCOL v1 ─────────────────────────────────── +// Framing used on the host UART. Header-only and free of Arduino +// dependencies so the same code is compiled into the host-side tests +// (tools/host/) and into the firmware. +// +// frame = COBS( type:u8 | body | crc16:u16le ) 0x00 +// crc16 = CRC-16/CCITT-FALSE over type|body +// +// COBS removes every 0x00 from the payload, so 0x00 is an unambiguous +// frame delimiter: a reader that joins mid-stream resynchronises at the +// next delimiter, and a corrupted frame costs exactly one frame. +// All multi-byte fields are little-endian (native on ESP32 and on x86/ARM +// hosts). Full specification: docs/wire-protocol.md + +#include +#include +#include + +#define WIRE_PROTO_VERSION 1 + +enum WireType : uint8_t { + WIRE_HELLO = 0x01, // proto:u8 | "key=value;key=value" (ASCII, no NUL) + WIRE_SAMPLE = 0x02, // WireSample + WIRE_STATUS = 0x03, // WireStatus + WIRE_LOG = 0x04, // ASCII text, no NUL +}; + +#pragma pack(push, 1) +struct WireSample { + uint32_t seq; // increments per sample sent; gaps = frames lost on the wire + uint64_t t_imu_us; // esp_timer_get_time() at IMU read start + uint32_t proc_us; // t_proc_end - t_imu (saturating) + uint64_t t_gps_us; // timestamp of last GPS sentence parsed + float ax, ay, az; // g + float gx, gy, gz; // °/s + float mx, my, mz; // µT + float pressure; // hPa + float bmp_temp; // °C + double lat, lon; // degrees + float alt_gps; // m (MSL) + float hdop; + uint8_t satellites; + uint8_t fault_flag; + uint32_t jitter_us; +}; + +struct WireStatus { + uint32_t rb_drops; // rows dropped because the ring buffer was full + uint32_t samples_sent; // total WIRE_SAMPLE frames written +}; +#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"); + +#define WIRE_MAX_BODY 200 +// type + body + crc, plus COBS overhead (1 byte per 254) and the delimiter. +#define WIRE_MAX_FRAME (WIRE_MAX_BODY + 3 + (WIRE_MAX_BODY + 3) / 254 + 1 + 1) + +// CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, no final XOR. +inline uint16_t wire_crc16(const uint8_t *data, size_t len) { + uint16_t crc = 0xFFFF; + for (size_t i = 0; i < len; i++) { + crc ^= (uint16_t)data[i] << 8; + for (int b = 0; b < 8; b++) + crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1); + } + return crc; +} + +// Consistent Overhead Byte Stuffing. Writes the encoded bytes (never 0x00) +// to `out` and returns their count. `out` needs len + len/254 + 1 bytes. +inline size_t wire_cobs_encode(const uint8_t *in, size_t len, uint8_t *out) { + size_t code_idx = 0, w = 1; + uint8_t code = 1; + for (size_t i = 0; i < len; i++) { + if (in[i] == 0) { + out[code_idx] = code; + code_idx = w++; + code = 1; + } else { + out[w++] = in[i]; + if (++code == 0xFF) { + out[code_idx] = code; + code_idx = w++; + code = 1; + } + } + } + out[code_idx] = code; + return w; +} + +// Build one complete frame, delimiter included. Returns the frame length, +// or 0 if the body is too large. `out` must hold WIRE_MAX_FRAME bytes. +inline size_t wire_frame(uint8_t type, const uint8_t *body, size_t len, uint8_t *out) { + if (len > WIRE_MAX_BODY) + return 0; + uint8_t raw[WIRE_MAX_BODY + 3]; + raw[0] = type; + if (len) + memcpy(raw + 1, body, len); + uint16_t crc = wire_crc16(raw, len + 1); + raw[len + 1] = (uint8_t)(crc & 0xFF); + raw[len + 2] = (uint8_t)(crc >> 8); + size_t n = wire_cobs_encode(raw, len + 3, out); + out[n++] = 0x00; + return n; +} diff --git a/platformio.ini b/platformio.ini index e82c95c..48213d5 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,6 +1,6 @@ -[env:esp32dev] +; Shared settings for every environment. +[env] platform = espressif32 -board = esp32dev framework = arduino monitor_speed = 921600 @@ -15,3 +15,16 @@ lib_deps = build_flags = -DCORE_DEBUG_LEVEL=0 + +extra_scripts = pre:scripts/version.py + +; Default build: binary wire protocol (docs/wire-protocol.md). +[env:esp32dev] +board = esp32dev + +; Debug build: the original human-readable CSV stream, for `pio device monitor`. +[env:esp32dev-csv] +board = esp32dev +build_flags = + ${env.build_flags} + -DMSNS_WIRE_CSV=1 diff --git a/scripts/version.py b/scripts/version.py new file mode 100644 index 0000000..a409ede --- /dev/null +++ b/scripts/version.py @@ -0,0 +1,13 @@ +"""PlatformIO pre-build script: stamp the firmware with the git revision.""" +import subprocess + +Import("env") # noqa: F821 (provided by PlatformIO/SCons) + +try: + sha = subprocess.check_output( + ["git", "rev-parse", "--short", "HEAD"], stderr=subprocess.DEVNULL + ).decode().strip() +except Exception: + sha = "unknown" + +env.Append(CPPDEFINES=[("MSNS_GIT_SHA", env.StringifyMacro(sha))]) # noqa: F821 diff --git a/src/main.cpp b/src/main.cpp index 3df84cb..cb41cd2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,6 +10,7 @@ #include "config.h" #include "esp_task_wdt.h" #include "sensor_row.h" +#include "transport.h" // ── GLOBALS ──────────────────────────────────────────── Adafruit_MPU6050 mpu; @@ -37,27 +38,19 @@ volatile bool gps_valid = false; volatile uint64_t gps_ts_us = 0; volatile uint32_t rb_drops = 0; -// ── CSV HEADER ───────────────────────────────────────── -static const char CSV_HEADER[] = - "t_imu_us,t_read_start_us,t_proc_end_us,t_gps_us," - "ax_g,ay_g,az_g,gx_dps,gy_dps,gz_dps," - "mx_uT,my_uT,mz_uT," - "pressure_hPa,bmp_temp_C," - "lat_deg,lon_deg,alt_gps_m,hdop,satellites," - "fault_flag,jitter_us"; +// Comma-separated list of the sensors that initialised; sent in the hello. +static char sensor_list[32] = ""; // ── FORWARD DECLS ────────────────────────────────────── void task_sensors(void* pv); void task_serial(void* pv); -void print_row(const SensorRow& r); bool init_sensors(); // ══════════════════════════════════════════════════════ // SETUP // ══════════════════════════════════════════════════════ void setup() { - Serial.begin(HOST_BAUD); - while (!Serial) delay(10); + transport_begin(); Wire.begin(PIN_SDA, PIN_SCL); Wire.setClock(I2C_FREQ_HZ); @@ -65,11 +58,15 @@ void setup() { gpsSerial.begin(GPS_BAUD, SERIAL_8N1, PIN_GPS_RX, PIN_GPS_TX); if (!init_sensors()) { - Serial.println("# WARN: some sensors missing — logging available sensors only."); + transport_log("WARN: some sensors missing — logging available sensors only."); } - // Print header once — Python logger watches for this line - Serial.println(CSV_HEADER); + snprintf(sensor_list, sizeof(sensor_list), "%s%s%sgps", + has_mpu ? "imu," : "", has_qmc ? "mag," : "", has_bmp ? "baro," : ""); + + // Identify the firmware before the first sample — the host logger + // waits for this. + transport_hello(sensor_list); // Deregister idle tasks from the task watchdog. // Our sensor task on Core 1 limits idle task runtime — without this @@ -100,14 +97,14 @@ bool init_sensors() { // MPU-6050 if (!mpu.begin()) { - Serial.println("# MPU-6050 not found"); + transport_log("MPU-6050 not found"); ok = false; } else { has_mpu = true; mpu.setAccelerometerRange(MPU6050_RANGE_4_G); mpu.setGyroRange(MPU6050_RANGE_500_DEG); mpu.setFilterBandwidth(MPU6050_BAND_44_HZ); - Serial.println("# MPU-6050 OK"); + transport_log("MPU-6050 OK"); } // QMC5883L — begin() always succeeds (no ACK check in library), @@ -115,18 +112,18 @@ bool init_sensors() { Wire.beginTransmission(0x0D); bool qmc_found = (Wire.endTransmission() == 0); if (!qmc_found) { - Serial.println("# QMC5883L not found (tried 0x0D)"); + transport_log("QMC5883L not found (tried 0x0D)"); ok = false; } else { has_qmc = true; mag.init(); mag.setMode(0x01, 0x0C, 0x10, 0x00); // continuous, 200Hz, 8G, 512 OSR - Serial.println("# QMC5883L OK"); + transport_log("QMC5883L OK"); } // BMP280 if (!bmp.begin(0x76)) { - Serial.println("# BMP280 not found (tried 0x76)"); + transport_log("BMP280 not found (tried 0x76)"); ok = false; } else { has_bmp = true; @@ -138,11 +135,11 @@ bool init_sensors() { Adafruit_BMP280::SAMPLING_X16, // (pressure) for better accuracy Adafruit_BMP280::FILTER_X16, Adafruit_BMP280::STANDBY_MS_63); - Serial.println("# BMP280 OK"); + transport_log("BMP280 OK"); } // to confirm GPS UART is alive - Serial.println("# GPS UART started — waiting for fix (HDOP reported in data)"); + transport_log("GPS UART started — waiting for fix (HDOP reported in data)"); return ok; } @@ -330,54 +327,21 @@ void task_serial(void* pv) { } while (rb_pop(&ring, row)) { - print_row(row); + transport_sample(row); } - // Report ring buffer drops once per second as a firmware comment. - // Drops indicate the serial output can't keep up with the sensor rate. - static uint64_t last_drop_report = 0; + // 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. + static uint64_t last_heartbeat = 0; uint64_t now_us = esp_timer_get_time(); - if (rb_drops > 0 && now_us - last_drop_report >= 1000000ULL) { - uint32_t drops = rb_drops; // snapshot: report a consistent value from one point in time - Serial.printf("# rb_drops=%u\n", drops); - last_drop_report = now_us; + if (now_us - last_heartbeat >= 1000000ULL) { + transport_heartbeat(rb_drops, sensor_list); + last_heartbeat = now_us; } vTaskDelay(1); } } -// ── FORMAT ROW AS CSV ────────────────────────────────── -void print_row(const SensorRow& r) { - // Using Serial.print chains avoids sprintf heap allocation. - // Format: full precision for doubles (lat/lon), 4dp for floats. - - Serial.print(r.t_imu_us); Serial.print(','); - Serial.print(r.t_read_start_us); Serial.print(','); - Serial.print(r.t_proc_end_us); Serial.print(','); - Serial.print(r.t_gps_us); Serial.print(','); - - Serial.print(r.ax, 5); Serial.print(','); - Serial.print(r.ay, 5); Serial.print(','); - Serial.print(r.az, 5); Serial.print(','); - Serial.print(r.gx, 4); Serial.print(','); - Serial.print(r.gy, 4); Serial.print(','); - Serial.print(r.gz, 4); Serial.print(','); - - Serial.print(r.mx, 4); Serial.print(','); - Serial.print(r.my, 4); Serial.print(','); - Serial.print(r.mz, 4); Serial.print(','); - - Serial.print(r.pressure, 4); Serial.print(','); - Serial.print(r.bmp_temp, 3); Serial.print(','); - - Serial.print(r.lat, 8); Serial.print(','); - Serial.print(r.lon, 8); Serial.print(','); - Serial.print(r.alt_gps, 2); Serial.print(','); - Serial.print(r.hdop, 2); Serial.print(','); - Serial.print(r.satellites); Serial.print(','); - - Serial.print(r.fault_flag); Serial.print(','); - Serial.println(r.jitter_us); -} -// Fault flags describe this sample only (not latched system faults) \ No newline at end of file +// Fault flags describe this sample only (not latched system faults) diff --git a/src/transport.cpp b/src/transport.cpp new file mode 100644 index 0000000..13f1734 --- /dev/null +++ b/src/transport.cpp @@ -0,0 +1,145 @@ +#include + +#include "config.h" +#include "transport.h" +#include "version.h" +#include "wire.h" + +static uint32_t s_samples_sent = 0; + +void transport_begin() { + // A larger TX buffer lets task_serial queue a burst of frames without + // blocking on the UART FIFO. Must be set before begin(). + Serial.setTxBufferSize(4096); + Serial.begin(HOST_BAUD); + while (!Serial) delay(10); +} + +static int format_hello(char *buf, size_t size, const char *sensors) { + return snprintf(buf, size, + "board=%s;fw=%s;git=%s;imu_hz=%d;mag_hz=%d;baro_hz=%d;gps_hz=%d;sensors=%s", + MSNS_BOARD_ID, MSNS_FW_VERSION, MSNS_GIT_SHA, + IMU_HZ, MAG_HZ, BARO_HZ, GPS_HZ, sensors); +} + +#if MSNS_WIRE_CSV +// ══════════════════════════════════════════════════════ +// CSV TRANSPORT (debug build) +// ══════════════════════════════════════════════════════ +static const char CSV_HEADER[] = + "t_imu_us,t_read_start_us,t_proc_end_us,t_gps_us," + "ax_g,ay_g,az_g,gx_dps,gy_dps,gz_dps," + "mx_uT,my_uT,mz_uT," + "pressure_hPa,bmp_temp_C," + "lat_deg,lon_deg,alt_gps_m,hdop,satellites," + "fault_flag,jitter_us"; + +void transport_log(const char *msg) { + Serial.print("# "); + Serial.println(msg); +} + +void transport_hello(const char *sensors) { + char text[160]; + format_hello(text, sizeof(text), sensors); + Serial.print("# hello "); + Serial.println(text); + // Header once — the host logger watches for this line. + Serial.println(CSV_HEADER); +} + +void transport_sample(const SensorRow &r) { + // Serial.print chains avoid sprintf heap allocation. + Serial.print(r.t_imu_us); Serial.print(','); + Serial.print(r.t_read_start_us); Serial.print(','); + Serial.print(r.t_proc_end_us); Serial.print(','); + Serial.print(r.t_gps_us); Serial.print(','); + + Serial.print(r.ax, 5); Serial.print(','); + Serial.print(r.ay, 5); Serial.print(','); + Serial.print(r.az, 5); Serial.print(','); + Serial.print(r.gx, 4); Serial.print(','); + Serial.print(r.gy, 4); Serial.print(','); + Serial.print(r.gz, 4); Serial.print(','); + + Serial.print(r.mx, 4); Serial.print(','); + Serial.print(r.my, 4); Serial.print(','); + Serial.print(r.mz, 4); Serial.print(','); + + Serial.print(r.pressure, 4); Serial.print(','); + Serial.print(r.bmp_temp, 3); Serial.print(','); + + Serial.print(r.lat, 8); Serial.print(','); + Serial.print(r.lon, 8); Serial.print(','); + Serial.print(r.alt_gps, 2); Serial.print(','); + Serial.print(r.hdop, 2); Serial.print(','); + Serial.print(r.satellites); Serial.print(','); + + Serial.print(r.fault_flag); Serial.print(','); + Serial.println(r.jitter_us); + s_samples_sent++; +} + +void transport_heartbeat(uint32_t rb_drops, const char *sensors) { + (void)sensors; + // Drops indicate the serial output can't keep up with the sensor rate. + if (rb_drops > 0) Serial.printf("# rb_drops=%u\n", rb_drops); +} + +#else +// ══════════════════════════════════════════════════════ +// BINARY TRANSPORT (default) — see wire.h +// ══════════════════════════════════════════════════════ +static uint32_t s_heartbeats = 0; + +static void send_frame(uint8_t type, const void *body, size_t len) { + uint8_t frame[WIRE_MAX_FRAME]; + size_t n = wire_frame(type, (const uint8_t *)body, len, frame); + if (n) Serial.write(frame, n); +} + +void transport_log(const char *msg) { + size_t len = strlen(msg); + if (len > WIRE_MAX_BODY) len = WIRE_MAX_BODY; + send_frame(WIRE_LOG, msg, len); +} + +void transport_hello(const char *sensors) { + char body[WIRE_MAX_BODY]; + body[0] = (char)WIRE_PROTO_VERSION; + int n = format_hello(body + 1, sizeof(body) - 1, sensors); + if (n < 0) n = 0; + if ((size_t)n > sizeof(body) - 2) n = sizeof(body) - 2; + send_frame(WIRE_HELLO, body, (size_t)n + 1); +} + +void transport_sample(const SensorRow &r) { + WireSample s; + uint64_t proc = r.t_proc_end_us - r.t_read_start_us; + s.seq = s_samples_sent++; + s.t_imu_us = r.t_imu_us; + s.proc_us = (proc > UINT32_MAX) ? UINT32_MAX : (uint32_t)proc; + s.t_gps_us = r.t_gps_us; + s.ax = r.ax; s.ay = r.ay; s.az = r.az; + s.gx = r.gx; s.gy = r.gy; s.gz = r.gz; + s.mx = r.mx; s.my = r.my; s.mz = r.mz; + s.pressure = r.pressure; + s.bmp_temp = r.bmp_temp; + s.lat = r.lat; + s.lon = r.lon; + s.alt_gps = r.alt_gps; + s.hdop = r.hdop; + s.satellites = r.satellites; + s.fault_flag = r.fault_flag; + s.jitter_us = r.jitter_us; + send_frame(WIRE_SAMPLE, &s, sizeof(s)); +} + +void transport_heartbeat(uint32_t rb_drops, const char *sensors) { + WireStatus st = {rb_drops, s_samples_sent}; + send_frame(WIRE_STATUS, &st, sizeof(st)); + // Repeat the hello every other heartbeat so a host that attaches + // mid-stream can identify the firmware without resetting the board. + if (++s_heartbeats % 2 == 0) transport_hello(sensors); +} +#endif diff --git a/tools/host/test_wire.cpp b/tools/host/test_wire.cpp new file mode 100644 index 0000000..ffd0f2a --- /dev/null +++ b/tools/host/test_wire.cpp @@ -0,0 +1,73 @@ +// Host-side tests for the wire protocol (include/wire.h). +// g++ -std=c++17 -Wall -Wextra -Werror -Iinclude tools/host/test_wire.cpp -o test_wire && ./test_wire +#include +#include +#include +#include + +#include "wire.h" + +// Reference COBS decoder, written independently of the encoder under test. +static std::vector cobs_decode(const uint8_t *in, size_t len) { + std::vector out; + size_t i = 0; + while (i < len) { + uint8_t code = in[i++]; + assert(code != 0); + for (uint8_t k = 1; k < code; k++) { + assert(i < len); + out.push_back(in[i++]); + } + if (code != 0xFF && i < len) + out.push_back(0); + } + return out; +} + +static void check_roundtrip(const std::vector &body) { + uint8_t frame[WIRE_MAX_FRAME]; + size_t n = wire_frame(WIRE_SAMPLE, body.data(), body.size(), frame); + assert(n > 0 && n <= WIRE_MAX_FRAME); + assert(frame[n - 1] == 0x00); + for (size_t i = 0; i + 1 < n; i++) + assert(frame[i] != 0x00); // the delimiter is the only zero byte + + std::vector raw = cobs_decode(frame, n - 1); + assert(raw.size() == body.size() + 3); + assert(raw[0] == WIRE_SAMPLE); + assert(memcmp(raw.data() + 1, body.data(), body.size()) == 0); + uint16_t crc = (uint16_t)(raw[raw.size() - 2] | (raw[raw.size() - 1] << 8)); + assert(crc == wire_crc16(raw.data(), raw.size() - 2)); +} + +int main() { + // Standard check value for CRC-16/CCITT-FALSE. + assert(wire_crc16((const uint8_t *)"123456789", 9) == 0x29B1); + + check_roundtrip({}); + check_roundtrip({0}); + check_roundtrip({0, 0, 0}); + check_roundtrip({1, 2, 3}); + check_roundtrip({1, 0, 2, 0, 0, 3}); + check_roundtrip(std::vector(WIRE_MAX_BODY, 0x00)); + check_roundtrip(std::vector(WIRE_MAX_BODY, 0xAB)); // no zeros: forces 0xFF code blocks + for (size_t len = 0; len <= WIRE_MAX_BODY; len++) { + std::vector body(len); + for (size_t i = 0; i < len; i++) + body[i] = (uint8_t)((i * 37 + len) % 5 == 0 ? 0 : i * 31 + len); + check_roundtrip(body); + } + + // Oversized bodies are rejected rather than truncated. + std::vector big(WIRE_MAX_BODY + 1, 1); + uint8_t frame[WIRE_MAX_FRAME]; + assert(wire_frame(WIRE_LOG, big.data(), big.size(), frame) == 0); + + // A sample frame is 103 bytes at most: 98 body + type + crc + COBS + delimiter. + WireSample s; + memset(&s, 0x11, sizeof(s)); + assert(wire_frame(WIRE_SAMPLE, (const uint8_t *)&s, sizeof(s), frame) == 103); + + puts("wire protocol: all host tests passed"); + return 0; +} diff --git a/tools/host/wire_dump.cpp b/tools/host/wire_dump.cpp new file mode 100644 index 0000000..1d4537f --- /dev/null +++ b/tools/host/wire_dump.cpp @@ -0,0 +1,59 @@ +// Emits a deterministic wire-protocol stream on stdout. The output is the +// golden fixture the host decoder (data-pipeline) is tested against, so the +// firmware encoder and the Python decoder are checked against each other. +// +// g++ -std=c++17 -Iinclude tools/host/wire_dump.cpp -o wire_dump +// ./wire_dump > golden_v1.bin +#include +#include + +#include "wire.h" + +static void emit(uint8_t type, const void *body, size_t len) { + uint8_t frame[WIRE_MAX_FRAME]; + size_t n = wire_frame(type, (const uint8_t *)body, len, frame); + fwrite(frame, 1, n, stdout); +} + +static void emit_hello() { + char body[WIRE_MAX_BODY]; + body[0] = (char)WIRE_PROTO_VERSION; + int n = snprintf(body + 1, sizeof(body) - 1, + "board=esp32dev;fw=0.2.0;git=abc1234;imu_hz=500;mag_hz=75;baro_hz=25;gps_hz=1;" + "sensors=imu,mag,baro,gps"); + emit(WIRE_HELLO, body, (size_t)n + 1); +} + +int main() { + const char *log = "MPU-6050 OK"; + emit(WIRE_LOG, log, strlen(log)); + emit_hello(); + + for (uint32_t i = 0; i < 8; i++) { + WireSample s; + memset(&s, 0, sizeof(s)); + s.seq = i; + s.t_imu_us = 5000000ULL + 2000ULL * i; + s.proc_us = 600 + i; + s.t_gps_us = 4000000ULL; + s.ax = 0.0f; // zero bytes exercise the COBS stuffing + s.ay = -0.02f; + s.az = 1.0f + 0.001f * i; + s.gx = 0.5f; s.gy = -0.25f; s.gz = 0.125f * i; + s.mx = 20.0f; s.my = -5.0f; s.mz = 38.0f; + s.pressure = 1013.25f; + s.bmp_temp = 27.5f; + s.lat = 18.5204303; + s.lon = 73.8567437; + s.alt_gps = 560.0f; + s.hdop = 1.2f; + s.satellites = 8; + s.fault_flag = (i == 3) ? 0x06 : 0x00; + s.jitter_us = 10 * i; + emit(WIRE_SAMPLE, &s, sizeof(s)); + } + + WireStatus st = {3, 8}; + emit(WIRE_STATUS, &st, sizeof(st)); + return 0; +} From 16f42325ad566894e1a78ae0b7bd53a85e28f7c1 Mon Sep 17 00:00:00 2001 From: Shivtej Gaikwad <91597404+ShivtejG236@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:34:00 +0000 Subject: [PATCH 2/2] Write a leading frame delimiter at boot Boot ROM output would otherwise be glued onto the first frame and cost it. --- docs/wire-protocol.md | 2 ++ src/transport.cpp | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/docs/wire-protocol.md b/docs/wire-protocol.md index b60743d..033fcaa 100644 --- a/docs/wire-protocol.md +++ b/docs/wire-protocol.md @@ -26,6 +26,8 @@ frame = COBS( type:u8 | body | crc16:u16le ) 0x00 - All multi-byte fields are little-endian. - A frame whose CRC fails, or whose type is unknown, is dropped; the stream continues at the next delimiter. +- Empty frames (two delimiters in a row) are ignored. The firmware writes one + `0x00` at boot so the boot ROM's output cannot corrupt the first frame. ## Frame types diff --git a/src/transport.cpp b/src/transport.cpp index 13f1734..452c35a 100644 --- a/src/transport.cpp +++ b/src/transport.cpp @@ -13,6 +13,11 @@ void transport_begin() { Serial.setTxBufferSize(4096); Serial.begin(HOST_BAUD); while (!Serial) delay(10); +#if !MSNS_WIRE_CSV + // Terminate whatever the boot ROM printed, so that noise cannot be + // glued onto the first real frame. + Serial.write((uint8_t)0x00); +#endif } static int format_hello(char *buf, size_t size, const char *sensors) {