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
19 changes: 12 additions & 7 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ jobs:
run: |
g++ -std=c++17 -Wall -Wextra -Werror -Iinclude tools/host/test_wire.cpp -o test_wire
./test_wire
- name: Board manifests
run: python3 tools/check_boards.py

build:
runs-on: ubuntu-latest
Expand All @@ -33,12 +35,15 @@ jobs:
with:
path: ~/.platformio
key: pio-${{ hashFiles('platformio.ini') }}
- run: pip install platformio
- run: pio run
- run: pip install platformio "esptool>=5"
- name: Build every environment
run: pio run
- name: Assemble release images (dry run)
run: |
version="$(sed -nE 's/^#define MSNS_FW_VERSION "(.*)"/\1/p' include/version.h)"
python tools/release.py --tag "v${version}" --out dist
cat dist/manifest.json
- uses: actions/upload-artifact@v4
with:
name: firmware-esp32dev
path: |
.pio/build/esp32dev/firmware.bin
.pio/build/esp32dev/bootloader.bin
.pio/build/esp32dev/partitions.bin
name: firmware-images
path: dist/
34 changes: 11 additions & 23 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
name: Release

# Pushing a tag like v0.1.0 builds the firmware and publishes a GitHub
# Release with a single merged image that can be flashed at offset 0x0:
# esptool.py --chip esp32 write_flash 0x0 msns-firmware-esp32dev-v0.1.0.bin
# Pushing a tag like v0.2.0 builds every board and publishes a GitHub Release
# holding one merged image per board plus manifest.json. The tag must match
# MSNS_FW_VERSION in include/version.h.
#
# Flash with navkit: nav flash
# Or by hand: esptool --chip esp32 write-flash 0x0 msns-firmware-esp32dev-v0.2.0.bin

on:
push:
Expand All @@ -14,31 +17,16 @@ permissions:
jobs:
release:
runs-on: ubuntu-latest
env:
BOARD: esp32dev
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install platformio "esptool<5"
- run: pio run -e "$BOARD"
- name: Merge into one flashable image
run: |
out="msns-firmware-${BOARD}-${GITHUB_REF_NAME}.bin"
build=".pio/build/${BOARD}"
boot_app0="$HOME/.platformio/packages/framework-arduinoespressif32/tools/partitions/boot_app0.bin"
esptool.py --chip esp32 merge_bin -o "$out" \
--flash_mode dio --flash_freq 40m --flash_size 4MB \
0x1000 "$build/bootloader.bin" \
0x8000 "$build/partitions.bin" \
0xe000 "$boot_app0" \
0x10000 "$build/firmware.bin"
sha256sum "$out" > "$out.sha256"
echo "IMAGE=$out" >> "$GITHUB_ENV"
- run: pip install platformio "esptool>=5"
- run: python3 tools/check_boards.py
- run: pio run
- run: python tools/release.py --tag "$GITHUB_REF_NAME" --out dist
- name: Publish release
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release create "$GITHUB_REF_NAME" "$IMAGE" "$IMAGE.sha256" \
--title "$GITHUB_REF_NAME" --generate-notes
run: gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --generate-notes
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.pio
.vscode
.DS_Store
dist/
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ 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
- **Board manifests** (`targets/<id>.json`): pins, flash layout and status
per board, applied to the build by `scripts/board.py`. Adding a board is
one JSON file and one PlatformIO environment. See `docs/boards.md`.
- `esp32-s3-devkitc-1` board (builds in CI; not yet run on hardware).
- `tools/release.py`: one merged image per board plus `manifest.json`
(version, git revision, protocol version, SHA-256 per image), published
by the release workflow and read by `nav flash`.
- `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.
Expand Down
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ Data flow is single-producer (Core 1) → single-consumer (Core 0) via a lock-fr

All three I²C devices share the same bus at 400 kHz fast-mode.

Pins are set per board. Supported boards and how to add one: [`docs/boards.md`](docs/boards.md).

---

## Sample Rates
Expand Down Expand Up @@ -301,13 +303,20 @@ firmware/
│ ├── transport.h # Host transport interface
│ ├── wire.h # Wire protocol v1: framing, CRC, COBS
│ └── version.h # Firmware version
├── targets/ # One manifest per supported board (pins, flash layout, status)
├── scripts/
│ └── version.py # Stamps the build with the git revision
├── tools/host/ # Host-side protocol tests + golden stream generator
│ ├── version.py # Stamps the build with the git revision
│ ├── board.py # Applies the board manifest to the build
│ └── boards.py # Manifest loading and validation
├── tools/
│ ├── host/ # Host-side protocol tests + golden stream generator
│ ├── check_boards.py # CI check: manifests ↔ PlatformIO environments
│ └── release.py # Merges release images and writes manifest.json
├── platformio.ini # PlatformIO build config
├── sdkconfig.defaults # ESP-IDF SDK overrides (task WDT tuning)
└── docs/
├── wire-protocol.md # Wire protocol specification
├── boards.md # Supported boards, adding a board
└── setup.png # Schematic diagram
```

Expand All @@ -334,6 +343,8 @@ Managed by PlatformIO — no manual installation needed.
pio run -e esp32dev --target upload
```

Replace `esp32dev` with another board id from [`docs/boards.md`](docs/boards.md) to build for it. Released images can be flashed without PlatformIO: `nav flash` from [Repo 2](https://github.com/multi-sensor-navigation-system/data-pipeline) detects the board and downloads the right one.

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

Each supported board is described by one manifest, `targets/<id>.json`, and
one PlatformIO environment with the same name. The manifest is the single
source for the pins, the flash layout and the board's status; the build, the
release images, `nav flash` and the firmware's `HELLO` frame all read from it.

| Board id | Board | Chip | Status |
|---|---|---|---|
| `esp32dev` | ESP32 DevKit (ESP32-WROOM-32) | ESP32 | tested |
| `esp32-s3-devkitc-1` | ESP32-S3 DevKitC-1 | ESP32-S3 | builds in CI, not yet run on hardware |

## Manifest

```json
{
"id": "esp32dev",
"name": "ESP32 DevKit (ESP32-WROOM-32)",
"chip": "esp32",
"status": "tested",
"pins": { "sda": 21, "scl": 22, "gps_rx": 16, "gps_tx": 17 },
"gps_uart": 2,
"flash": { "mode": "dio", "freq": "40m", "size": "4MB", "bootloader_offset": "0x1000" }
}
```

| Field | Meaning |
|---|---|
| `id` | Board id. Must equal the file name and the PlatformIO environment name |
| `name` | Human-readable name shown by `nav flash` and the web flasher |
| `chip` | esptool chip id (`esp32`, `esp32s3`, …). `nav flash` matches it against the detected chip |
| `status` | Free text. Say honestly whether the board has been run on hardware |
| `pins` | GPIO numbers for the shared I²C bus and the GPS UART |
| `gps_uart` | Hardware UART used for the GPS. UART0 is the host link and cannot be used |
| `flash` | Parameters for merging the release image. `bootloader_offset` is `0x1000` on the ESP32 and `0x0` on the ESP32-S3/C3 |

## Adding a board

1. Create `targets/<id>.json`.
2. Add an environment to `platformio.ini`:
```ini
[env:<id>]
board = <PlatformIO board name>
custom_board = <id>
```
3. Run `python3 tools/check_boards.py`, then `pio run -e <id>`.
4. Add the board to the table above.

CI builds every environment, and the release workflow publishes an image for
every manifest automatically.

## Constraints

The firmware pins its sensor task to core 1 and its serial task to core 0, so
it needs a **dual-core** chip (ESP32, ESP32-S3). Single-core parts such as the
ESP32-C3 need a different task layout and are not supported yet.

All boards use the same sensors (MPU-6050, QMC5883L, BMP280, NEO-6M) on one
I²C bus and one UART. Sensor variants are a separate piece of work.
22 changes: 18 additions & 4 deletions include/config.h
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
#pragma once

// ── I²C ────────────────────────────────────────────────
// ── BOARD PINS ─────────────────────────────────────────
// Set per board from targets/<id>.json by scripts/board.py. The fallbacks
// below are the esp32dev values, for builds made outside PlatformIO.
#ifndef PIN_SDA
#define PIN_SDA 21
#endif
#ifndef PIN_SCL
#define PIN_SCL 22
#endif
#ifndef PIN_GPS_RX
#define PIN_GPS_RX 16
#endif
#ifndef PIN_GPS_TX
#define PIN_GPS_TX 17
#endif
#ifndef GPS_UART_NUM
#define GPS_UART_NUM 2
#endif

// ── I²C ────────────────────────────────────────────────
#define I2C_FREQ_HZ 400000

// ── GPS UART ───────────────────────────────────────────
#define GPS_UART_NUM 2
#define PIN_GPS_RX 16
#define PIN_GPS_TX 17
#define GPS_BAUD 9600

// ── SERIAL (host logging) ──────────────────────────────
Expand Down
22 changes: 17 additions & 5 deletions platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,27 @@ lib_deps =
build_flags =
-DCORE_DEBUG_LEVEL=0

extra_scripts = pre:scripts/version.py
extra_scripts =
pre:scripts/version.py
pre:scripts/board.py

; ── One environment per board ──────────────────────────
; The environment name is the board id and matches targets/<id>.json, which
; holds the pins, flash layout and status. See docs/boards.md to add one.

; Default build: binary wire protocol (docs/wire-protocol.md).
[env:esp32dev]
board = esp32dev
board = esp32dev
custom_board = esp32dev

[env:esp32-s3-devkitc-1]
board = esp32-s3-devkitc-1
custom_board = esp32-s3-devkitc-1

; Debug build: the original human-readable CSV stream, for `pio device monitor`.
; ── Debug ──────────────────────────────────────────────
; The original human-readable CSV stream, for `pio device monitor`.
[env:esp32dev-csv]
board = esp32dev
board = esp32dev
custom_board = esp32dev
build_flags =
${env.build_flags}
-DMSNS_WIRE_CSV=1
Binary file added scripts/__pycache__/boards.cpython-313.pyc
Binary file not shown.
18 changes: 18 additions & 0 deletions scripts/board.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""PlatformIO pre-build script: apply the board manifest named by `custom_board`."""
import sys
from pathlib import Path

Import("env") # noqa: F821 (provided by PlatformIO/SCons)

sys.path.insert(0, str(Path(env.subst("$PROJECT_DIR")) / "scripts")) # noqa: F821
import boards # noqa: E402

board_id = env.GetProjectOption("custom_board") # noqa: F821
board = boards.load(board_id)

for name, value in boards.defines(board).items():
if isinstance(value, str):
value = env.StringifyMacro(value) # noqa: F821
env.Append(CPPDEFINES=[(name, value)]) # noqa: F821

print(f"Board manifest: {board['id']} — {board['name']} ({board['status']})")
74 changes: 74 additions & 0 deletions scripts/boards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Board manifests (targets/<id>.json): loading and validation.

The directory is not called boards/ because PlatformIO reserves that name
for its own custom board definitions.

Shared by the PlatformIO pre-build script (scripts/board.py), the release
tool (tools/release.py) and the CI check (tools/check_boards.py). Standard
library only, so it runs inside PlatformIO's Python as well.
"""
import configparser
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
BOARDS_DIR = ROOT / "targets"

REQUIRED_PINS = ("sda", "scl", "gps_rx", "gps_tx")
REQUIRED_FLASH = ("mode", "freq", "size", "bootloader_offset")


class BoardError(ValueError):
pass


def validate(board: dict, source: str) -> None:
for key in ("id", "name", "chip", "status", "pins", "gps_uart", "flash"):
if key not in board:
raise BoardError(f"{source}: missing '{key}'")
for pin in REQUIRED_PINS:
if not isinstance(board["pins"].get(pin), int):
raise BoardError(f"{source}: pins.{pin} must be an integer GPIO number")
if len({board["pins"][p] for p in REQUIRED_PINS}) != len(REQUIRED_PINS):
raise BoardError(f"{source}: two signals share a GPIO")
if not isinstance(board["gps_uart"], int) or board["gps_uart"] == 0:
raise BoardError(f"{source}: gps_uart must be a UART other than 0 (UART0 is the host link)")
for key in REQUIRED_FLASH:
if key not in board["flash"]:
raise BoardError(f"{source}: missing flash.{key}")


def load(board_id: str) -> dict:
path = BOARDS_DIR / f"{board_id}.json"
if not path.is_file():
known = ", ".join(sorted(p.stem for p in BOARDS_DIR.glob("*.json")))
raise BoardError(f"no manifest targets/{board_id}.json (known boards: {known})")
board = json.loads(path.read_text())
validate(board, path.name)
if board["id"] != board_id:
raise BoardError(f"{path.name}: id is '{board['id']}', expected '{board_id}'")
return board


def load_all() -> list[dict]:
return [load(p.stem) for p in sorted(BOARDS_DIR.glob("*.json"))]


def defines(board: dict) -> dict:
"""C preprocessor definitions that config.h and version.h pick up."""
pins = board["pins"]
return {
"MSNS_BOARD_ID": board["id"],
"PIN_SDA": pins["sda"],
"PIN_SCL": pins["scl"],
"PIN_GPS_RX": pins["gps_rx"],
"PIN_GPS_TX": pins["gps_tx"],
"GPS_UART_NUM": board["gps_uart"],
}


def platformio_envs() -> dict[str, dict]:
"""{env name: its options} from platformio.ini."""
ini = configparser.ConfigParser()
ini.read(ROOT / "platformio.ini")
return {s[len("env:"):]: dict(ini[s]) for s in ini.sections() if s.startswith("env:")}
9 changes: 9 additions & 0 deletions targets/esp32-s3-devkitc-1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"id": "esp32-s3-devkitc-1",
"name": "ESP32-S3 DevKitC-1",
"chip": "esp32s3",
"status": "builds in CI, not yet run on hardware",
"pins": { "sda": 8, "scl": 9, "gps_rx": 18, "gps_tx": 17 },
"gps_uart": 1,
"flash": { "mode": "dio", "freq": "80m", "size": "8MB", "bootloader_offset": "0x0" }
}
9 changes: 9 additions & 0 deletions targets/esp32dev.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"id": "esp32dev",
"name": "ESP32 DevKit (ESP32-WROOM-32)",
"chip": "esp32",
"status": "tested",
"pins": { "sda": 21, "scl": 22, "gps_rx": 16, "gps_tx": 17 },
"gps_uart": 2,
"flash": { "mode": "dio", "freq": "40m", "size": "4MB", "bootloader_offset": "0x1000" }
}
Loading
Loading