Skip to content
Merged
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
9 changes: 9 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
64 changes: 41 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).*

Expand All @@ -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.

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


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

Expand All @@ -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
```

---
Expand All @@ -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.

---

Expand All @@ -351,20 +369,20 @@ 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
```

| 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 |
Expand Down
97 changes: 97 additions & 0 deletions docs/wire-protocol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# 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.
- 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

| 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.
25 changes: 25 additions & 0 deletions include/transport.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#pragma once
#include "sensor_row.h"
#include <stdint.h>

// ── 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);
12 changes: 12 additions & 0 deletions include/version.h
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading