diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c8b4e10..c1c7dfd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 @@ -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/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 546f16d..0d78aad 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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: @@ -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 diff --git a/.gitignore b/.gitignore index 88be9f4..324cfcc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .pio .vscode .DS_Store +dist/ diff --git a/CHANGELOG.md b/CHANGELOG.md index d5caa6a..68bce31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/.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. diff --git a/README.md b/README.md index 5879f05..bb1e147 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 ``` @@ -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: diff --git a/docs/boards.md b/docs/boards.md new file mode 100644 index 0000000..a97f26b --- /dev/null +++ b/docs/boards.md @@ -0,0 +1,59 @@ +# Boards + +Each supported board is described by one manifest, `targets/.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/.json`. +2. Add an environment to `platformio.ini`: + ```ini + [env:] + board = + custom_board = + ``` +3. Run `python3 tools/check_boards.py`, then `pio run -e `. +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. diff --git a/include/config.h b/include/config.h index cd958a4..6dbc0d1 100644 --- a/include/config.h +++ b/include/config.h @@ -1,14 +1,28 @@ #pragma once -// ── I²C ──────────────────────────────────────────────── +// ── BOARD PINS ───────────────────────────────────────── +// Set per board from targets/.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) ────────────────────────────── diff --git a/platformio.ini b/platformio.ini index 48213d5..f03b5eb 100644 --- a/platformio.ini +++ b/platformio.ini @@ -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/.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 diff --git a/scripts/__pycache__/boards.cpython-313.pyc b/scripts/__pycache__/boards.cpython-313.pyc new file mode 100644 index 0000000..48df088 Binary files /dev/null and b/scripts/__pycache__/boards.cpython-313.pyc differ diff --git a/scripts/board.py b/scripts/board.py new file mode 100644 index 0000000..c785e3e --- /dev/null +++ b/scripts/board.py @@ -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']})") diff --git a/scripts/boards.py b/scripts/boards.py new file mode 100644 index 0000000..38c7cd3 --- /dev/null +++ b/scripts/boards.py @@ -0,0 +1,74 @@ +"""Board manifests (targets/.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:")} diff --git a/targets/esp32-s3-devkitc-1.json b/targets/esp32-s3-devkitc-1.json new file mode 100644 index 0000000..ecb2bea --- /dev/null +++ b/targets/esp32-s3-devkitc-1.json @@ -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" } +} diff --git a/targets/esp32dev.json b/targets/esp32dev.json new file mode 100644 index 0000000..6bbaee7 --- /dev/null +++ b/targets/esp32dev.json @@ -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" } +} diff --git a/tools/check_boards.py b/tools/check_boards.py new file mode 100644 index 0000000..71211d1 --- /dev/null +++ b/tools/check_boards.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""CI check: every board manifest is valid and has a PlatformIO environment.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) +import boards # noqa: E402 + + +def main() -> int: + errors = [] + envs = boards.platformio_envs() + try: + manifests = boards.load_all() + except boards.BoardError as e: + print(f"ERROR: {e}") + return 1 + + for board in manifests: + env = envs.get(board["id"]) + if env is None: + errors.append(f"targets/{board["id"]}.json has no [env:{board['id']}] in platformio.ini") + elif env.get("custom_board") != board["id"]: + errors.append(f"[env:{board['id']}] must set custom_board = {board['id']}") + + known = {b["id"] for b in manifests} + for name, env in envs.items(): + if env.get("custom_board") not in known: + errors.append(f"[env:{name}] custom_board = {env.get('custom_board')!r} has no manifest") + + for e in errors: + print(f"ERROR: {e}") + if not errors: + print(f"{len(manifests)} board manifests OK: {', '.join(sorted(known))}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release.py b/tools/release.py new file mode 100644 index 0000000..89c3102 --- /dev/null +++ b/tools/release.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Assemble release artifacts from a finished PlatformIO build. + +For every board manifest this merges bootloader + partition table + boot_app0 ++ application into one image flashable at 0x0, then writes manifest.json — +the file `nav flash` and the web flasher read to find the right image. + + pio run # build every environment first + python tools/release.py --tag v0.2.0 --out dist + +Requires esptool >= 5 on PATH. +""" +import argparse +import hashlib +import json +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "scripts")) +import boards # noqa: E402 + +DEFAULT_BOOT_APP0 = (Path.home() / ".platformio" / "packages" / "framework-arduinoespressif32" + / "tools" / "partitions" / "boot_app0.bin") + + +def macro(header: str, name: str) -> str: + text = (ROOT / "include" / header).read_text() + m = re.search(rf'^#define\s+{name}\s+"?([^"\s]+)"?', text, re.M) + if not m: + raise SystemExit(f"{name} not found in include/{header}") + return m.group(1) + + +def git_sha() -> str: + try: + return subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, + stderr=subprocess.DEVNULL).decode().strip() + except Exception: + return "unknown" + + +def merge(board: dict, build_dir: Path, boot_app0: Path, out: Path) -> None: + flash = board["flash"] + parts = [ + (flash["bootloader_offset"], build_dir / "bootloader.bin"), + ("0x8000", build_dir / "partitions.bin"), + ("0xe000", boot_app0), + ("0x10000", build_dir / "firmware.bin"), + ] + for _, path in parts: + if not path.is_file(): + raise SystemExit(f"missing build output: {path} (run `pio run -e {board['id']}` first)") + cmd = ["esptool", "--chip", board["chip"], "merge-bin", "-o", str(out), + "--flash-mode", flash["mode"], "--flash-freq", flash["freq"], "--flash-size", flash["size"]] + for offset, path in parts: + cmd += [offset, str(path)] + subprocess.run(cmd, check=True) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--tag", required=True, help="release tag, e.g. v0.2.0") + ap.add_argument("--out", type=Path, default=ROOT / "dist") + ap.add_argument("--build-root", type=Path, default=ROOT / ".pio" / "build") + ap.add_argument("--boot-app0", type=Path, default=DEFAULT_BOOT_APP0) + args = ap.parse_args() + + fw_version = macro("version.h", "MSNS_FW_VERSION") + if args.tag != f"v{fw_version}": + raise SystemExit(f"tag {args.tag} does not match MSNS_FW_VERSION {fw_version} in include/version.h") + + args.out.mkdir(parents=True, exist_ok=True) + manifest = { + "schema": 1, + "version": args.tag, + "git": git_sha(), + "proto": int(macro("wire.h", "WIRE_PROTO_VERSION")), + "boards": {}, + } + for board in boards.load_all(): + image = args.out / f"msns-firmware-{board['id']}-{args.tag}.bin" + merge(board, args.build_root / board["id"], args.boot_app0, image) + manifest["boards"][board["id"]] = { + "name": board["name"], + "chip": board["chip"], + "status": board["status"], + "image": image.name, + "sha256": hashlib.sha256(image.read_bytes()).hexdigest(), + "size": image.stat().st_size, + "offset": "0x0", + } + print(f" {image.name} {manifest['boards'][board['id']]['sha256'][:16]}…") + + (args.out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + print(f" manifest.json ({len(manifest['boards'])} boards, proto {manifest['proto']})") + return 0 + + +if __name__ == "__main__": + sys.exit(main())