From 73119c1cbec0e54fb36badb9f1567030a5785b85 Mon Sep 17 00:00:00 2001 From: Shivtej Gaikwad <91597404+ShivtejG236@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:46:25 +0000 Subject: [PATCH 1/2] Describe boards with manifests and build a release image per board - boards/.json holds pins, GPS UART, flash layout and status; scripts/board.py applies it to the build as preprocessor definitions - add esp32-s3-devkitc-1 alongside esp32dev - tools/release.py merges one flashable image per board and writes manifest.json for nav flash; the release workflow publishes both - tools/check_boards.py keeps manifests and PlatformIO environments in step - CI builds every environment and dry-runs the release assembly --- .github/workflows/build.yml | 19 ++-- .github/workflows/release.yml | 34 +++---- .gitignore | 1 + CHANGELOG.md | 7 ++ README.md | 15 ++- boards/esp32-s3-devkitc-1.json | 9 ++ boards/esp32dev.json | 9 ++ docs/boards.md | 59 ++++++++++++ include/config.h | 22 ++++- platformio.ini | 22 ++++- scripts/__pycache__/boards.cpython-313.pyc | Bin 0 -> 4857 bytes scripts/board.py | 18 ++++ scripts/boards.py | 71 ++++++++++++++ tools/check_boards.py | 39 ++++++++ tools/release.py | 103 +++++++++++++++++++++ 15 files changed, 387 insertions(+), 41 deletions(-) create mode 100644 boards/esp32-s3-devkitc-1.json create mode 100644 boards/esp32dev.json create mode 100644 docs/boards.md create mode 100644 scripts/__pycache__/boards.cpython-313.pyc create mode 100644 scripts/board.py create mode 100644 scripts/boards.py create mode 100644 tools/check_boards.py create mode 100644 tools/release.py 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..eac99ab 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** (`boards/.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..50e1c67 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 +├── boards/ # 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/boards/esp32-s3-devkitc-1.json b/boards/esp32-s3-devkitc-1.json new file mode 100644 index 0000000..ecb2bea --- /dev/null +++ b/boards/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/boards/esp32dev.json b/boards/esp32dev.json new file mode 100644 index 0000000..6bbaee7 --- /dev/null +++ b/boards/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/docs/boards.md b/docs/boards.md new file mode 100644 index 0000000..29fe06c --- /dev/null +++ b/docs/boards.md @@ -0,0 +1,59 @@ +# Boards + +Each supported board is described by one manifest, `boards/.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 `boards/.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..b626d25 100644 --- a/include/config.h +++ b/include/config.h @@ -1,14 +1,28 @@ #pragma once -// ── I²C ──────────────────────────────────────────────── +// ── BOARD PINS ───────────────────────────────────────── +// Set per board from boards/.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..f73aaed 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 boards/.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 0000000000000000000000000000000000000000..cb2489c794a7251e845c25babd34d1ceda376ace GIT binary patch literal 4857 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 literal 0 HcmV?d00001 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..9810653 --- /dev/null +++ b/scripts/boards.py @@ -0,0 +1,71 @@ +"""Board manifests (boards/.json): loading and validation. + +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 / "boards" + +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 boards/{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/tools/check_boards.py b/tools/check_boards.py new file mode 100644 index 0000000..2191eb3 --- /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"boards/{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()) From 4cc0665d299d1e6b611973ebf58bab1c344f4343 Mon Sep 17 00:00:00 2001 From: Shivtej Gaikwad <91597404+ShivtejG236@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:48:04 +0000 Subject: [PATCH 2/2] Keep board manifests in targets/ PlatformIO reserves a project-level boards/ directory for its own custom board definitions and rejected the manifests. --- CHANGELOG.md | 2 +- README.md | 2 +- docs/boards.md | 4 ++-- include/config.h | 2 +- platformio.ini | 2 +- scripts/__pycache__/boards.cpython-313.pyc | Bin 4857 -> 4974 bytes scripts/boards.py | 9 ++++++--- {boards => targets}/esp32-s3-devkitc-1.json | 0 {boards => targets}/esp32dev.json | 0 tools/check_boards.py | 2 +- 10 files changed, 13 insertions(+), 10 deletions(-) rename {boards => targets}/esp32-s3-devkitc-1.json (100%) rename {boards => targets}/esp32dev.json (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index eac99ab..68bce31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ 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** (`boards/.json`): pins, flash layout and status +- **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). diff --git a/README.md b/README.md index 50e1c67..bb1e147 100644 --- a/README.md +++ b/README.md @@ -303,7 +303,7 @@ firmware/ │ ├── transport.h # Host transport interface │ ├── wire.h # Wire protocol v1: framing, CRC, COBS │ └── version.h # Firmware version -├── boards/ # One manifest per supported board (pins, flash layout, status) +├── targets/ # One manifest per supported board (pins, flash layout, status) ├── scripts/ │ ├── version.py # Stamps the build with the git revision │ ├── board.py # Applies the board manifest to the build diff --git a/docs/boards.md b/docs/boards.md index 29fe06c..a97f26b 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -1,6 +1,6 @@ # Boards -Each supported board is described by one manifest, `boards/.json`, and +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. @@ -36,7 +36,7 @@ release images, `nav flash` and the firmware's `HELLO` frame all read from it. ## Adding a board -1. Create `boards/.json`. +1. Create `targets/.json`. 2. Add an environment to `platformio.ini`: ```ini [env:] diff --git a/include/config.h b/include/config.h index b626d25..6dbc0d1 100644 --- a/include/config.h +++ b/include/config.h @@ -1,7 +1,7 @@ #pragma once // ── BOARD PINS ───────────────────────────────────────── -// Set per board from boards/.json by scripts/board.py. The fallbacks +// 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 diff --git a/platformio.ini b/platformio.ini index f73aaed..f03b5eb 100644 --- a/platformio.ini +++ b/platformio.ini @@ -21,7 +21,7 @@ extra_scripts = pre:scripts/board.py ; ── One environment per board ────────────────────────── -; The environment name is the board id and matches boards/.json, which +; 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. [env:esp32dev] diff --git a/scripts/__pycache__/boards.cpython-313.pyc b/scripts/__pycache__/boards.cpython-313.pyc index cb2489c794a7251e845c25babd34d1ceda376ace..48df08887972370862bd2954a69ce485cb7e058a 100644 GIT binary patch delta 318 zcmeyV`c94aGcPX}0}zyCe$U#tkynjTx{;BA!6`qnC`BPRF)uSMwYa2ML8BzGC_S}g zvM-~0UPwl&LP};)YH~?_QKdp=u|i&ci9&K>PEKlyLJ~+{vA#l5YI0&}ajHTmz@F2n$Zl+?7$yv&l! z{Ji4Hg^W+w*`d})Gc_`bPQJ@DjZt)S3G;SlM#;@O?2XKfI+NFN=?RPE<-?t<0M+r1 z>jWT0RA)yx}!!GlMU*HJe+{5F;$Y`|rCT|rZquJ&Ver+a3 o=gkd*T8sj_fUf+&%*e?2k%^U&.json): loading and validation. +"""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 @@ -9,7 +12,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent.parent -BOARDS_DIR = ROOT / "boards" +BOARDS_DIR = ROOT / "targets" REQUIRED_PINS = ("sda", "scl", "gps_rx", "gps_tx") REQUIRED_FLASH = ("mode", "freq", "size", "bootloader_offset") @@ -39,7 +42,7 @@ 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 boards/{board_id}.json (known boards: {known})") + 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: diff --git a/boards/esp32-s3-devkitc-1.json b/targets/esp32-s3-devkitc-1.json similarity index 100% rename from boards/esp32-s3-devkitc-1.json rename to targets/esp32-s3-devkitc-1.json diff --git a/boards/esp32dev.json b/targets/esp32dev.json similarity index 100% rename from boards/esp32dev.json rename to targets/esp32dev.json diff --git a/tools/check_boards.py b/tools/check_boards.py index 2191eb3..71211d1 100644 --- a/tools/check_boards.py +++ b/tools/check_boards.py @@ -19,7 +19,7 @@ def main() -> int: for board in manifests: env = envs.get(board["id"]) if env is None: - errors.append(f"boards/{board['id']}.json has no [env:{board['id']}] in platformio.ini") + 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']}")