Skip to content
Open
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
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ jobs:
./test_wire
- name: Board manifests
run: python3 tools/check_boards.py
- name: Pin rules
run: python3 tools/test_pin_rules.py

build:
runs-on: ubuntu-latest
Expand Down
22 changes: 22 additions & 0 deletions chips/esp32.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"chip": "esp32",
"source": "https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/gpio.html",
"gpio": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33, 34, 35, 36, 37, 38, 39],
"input_only": [34, 35, 36, 37, 38, 39],
"uarts": [1, 2],
"blocked": {
"0": "strapping pin: selects download mode at reset",
"2": "strapping pin: must be low or floating to enter download mode",
"5": "strapping pin: sets SDIO timing at reset",
"12": "strapping pin: a pull-up here selects 1.8 V flash and the board will not boot",
"15": "strapping pin: controls the boot log at reset",
"1": "UART0 TX, the host link",
"3": "UART0 RX, the host link",
"6": "connected to the SPI flash",
"7": "connected to the SPI flash",
"8": "connected to the SPI flash",
"9": "connected to the SPI flash",
"10": "connected to the SPI flash",
"11": "connected to the SPI flash"
}
}
24 changes: 24 additions & 0 deletions chips/esp32s3.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"chip": "esp32s3",
"source": "https://docs.espressif.com/projects/esp-idf/en/stable/esp32s3/api-reference/peripherals/gpio.html",
"gpio": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48],
"input_only": [],
"uarts": [1, 2],
"blocked": {
"0": "strapping pin: selects download mode at reset",
"3": "strapping pin: selects the JTAG source at reset",
"45": "strapping pin: selects the flash voltage at reset",
"46": "strapping pin: selects download mode and boot log at reset",
"19": "USB D-, used for flashing and the USB serial port",
"20": "USB D+, used for flashing and the USB serial port",
"43": "UART0 TX, the host link",
"44": "UART0 RX, the host link",
"26": "connected to the SPI flash / PSRAM",
"27": "connected to the SPI flash / PSRAM",
"28": "connected to the SPI flash / PSRAM",
"29": "connected to the SPI flash / PSRAM",
"30": "connected to the SPI flash / PSRAM",
"31": "connected to the SPI flash / PSRAM",
"32": "connected to the SPI flash / PSRAM"
}
}
17 changes: 16 additions & 1 deletion docs/boards.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,26 @@ release images, `nav flash` and the firmware's `HELLO` frame all read from it.
| `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 |
| `reserved` | Optional. GPIOs this particular board already uses (LED, PSRAM, …), as `{"<gpio>": "<reason>"}` |
| `flash` | Parameters for merging the release image. `bootloader_offset` is `0x1000` on the ESP32 and `0x0` on the ESP32-S3/C3 |

## Pin rules

`chips/<chip>.json` lists, for each chip family, which GPIOs exist, which are
input-only, which UARTs the GPS may use and which GPIOs can never carry a
sensor signal (strapping pins, flash and PSRAM pins, USB, the UART0 host
link), each with its reason. `boards.pin_errors()` checks an assignment
against those rules plus the board's `reserved` list and returns every
problem it finds. Manifests that break a rule fail `tools/check_boards.py`
and the build.

Strapping pins are blocked outright, including the ones that are safe with a
pull-up, so that no allowed assignment can stop a board from booting or
flashing.

## Adding a board

1. Create `targets/<id>.json`.
1. Create `targets/<id>.json`. If the chip is new, add `chips/<chip>.json` from the vendor's GPIO documentation first.
2. Add an environment to `platformio.ini`:
```ini
[env:<id>]
Expand Down
54 changes: 47 additions & 7 deletions scripts/boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,65 @@
ROOT = Path(__file__).resolve().parent.parent
BOARDS_DIR = ROOT / "targets"

CHIPS_DIR = ROOT / "chips"

REQUIRED_PINS = ("sda", "scl", "gps_rx", "gps_tx")
# Signals the chip drives. gps_rx only listens, so an input-only GPIO is fine.
OUTPUT_PINS = ("sda", "scl", "gps_tx")
REQUIRED_FLASH = ("mode", "freq", "size", "bootloader_offset")


class BoardError(ValueError):
pass


def load_chip(chip: str) -> dict:
"""Pin rules for one chip family (chips/<chip>.json)."""
path = CHIPS_DIR / f"{chip}.json"
if not path.is_file():
known = ", ".join(sorted(p.stem for p in CHIPS_DIR.glob("*.json")))
raise BoardError(f"no pin rules chips/{chip}.json (known chips: {known})")
return json.loads(path.read_text())


def pin_errors(pins: dict, gps_uart: int, chip: dict, reserved=None) -> list[str]:
"""Every reason this pin assignment cannot work on this chip and board.

An empty list means the assignment is allowed. The same function backs the
manifest check and any tool that lets a user choose pins.
"""
errors = []
reserved = reserved or {}
for signal in REQUIRED_PINS:
gpio = pins.get(signal)
if not isinstance(gpio, int) or isinstance(gpio, bool):
errors.append(f"{signal}: must be an integer GPIO number")
continue
if gpio not in chip["gpio"]:
errors.append(f"{signal}: GPIO {gpio} does not exist on the {chip['chip']}")
elif str(gpio) in chip["blocked"]:
errors.append(f"{signal}: GPIO {gpio} is {chip['blocked'][str(gpio)]}")
elif str(gpio) in reserved:
errors.append(f"{signal}: GPIO {gpio} is reserved on this board: {reserved[str(gpio)]}")
elif signal in OUTPUT_PINS and gpio in chip["input_only"]:
errors.append(f"{signal}: GPIO {gpio} is input-only")
used = [pins[s] for s in REQUIRED_PINS if isinstance(pins.get(s), int)]
for gpio in sorted({g for g in used if used.count(g) > 1}):
shared = ", ".join(s for s in REQUIRED_PINS if pins.get(s) == gpio)
errors.append(f"GPIO {gpio} is assigned to more than one signal ({shared})")
if gps_uart not in chip["uarts"]:
allowed = ", ".join(str(u) for u in chip["uarts"])
errors.append(f"gps_uart: UART{gps_uart} cannot be used (allowed: {allowed}; UART0 is the host link)")
return errors


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)")
errors = pin_errors(board["pins"], board["gps_uart"], load_chip(board["chip"]), board.get("reserved"))
if errors:
raise BoardError(f"{source}: " + "; ".join(errors))
for key in REQUIRED_FLASH:
if key not in board["flash"]:
raise BoardError(f"{source}: missing flash.{key}")
Expand Down
7 changes: 7 additions & 0 deletions targets/esp32-s3-devkitc-1.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,12 @@
"status": "builds in CI, not yet run on hardware",
"pins": { "sda": 8, "scl": 9, "gps_rx": 18, "gps_tx": 17 },
"gps_uart": 1,
"reserved": {
"35": "octal PSRAM on the N8R8 / N16R8 module variants",
"36": "octal PSRAM on the N8R8 / N16R8 module variants",
"37": "octal PSRAM on the N8R8 / N16R8 module variants",
"48": "on-board RGB LED (GPIO 38 on board revision 1.1)",
"38": "on-board RGB LED on board revision 1.1 (GPIO 48 on revision 1.0)"
},
"flash": { "mode": "dio", "freq": "80m", "size": "8MB", "bootloader_offset": "0x0" }
}
58 changes: 58 additions & 0 deletions tools/test_pin_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Host test for the pin rules (chips/<chip>.json and boards.pin_errors)."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
import boards # noqa: E402

ESP32 = boards.load_chip("esp32")
S3 = boards.load_chip("esp32s3")
GOOD = {"sda": 21, "scl": 22, "gps_rx": 16, "gps_tx": 17}


def errs(chip, uart=2, reserved=None, **change):
return boards.pin_errors({**GOOD, **change}, uart, chip, reserved)


def expect(errors, fragment):
assert any(fragment in e for e in errors), f"expected {fragment!r} in {errors}"


def main() -> int:
# Rule files are internally consistent.
for chip in (ESP32, S3):
gpio = set(chip["gpio"])
assert {int(g) for g in chip["blocked"]} <= gpio, chip["chip"]
assert set(chip["input_only"]) <= gpio, chip["chip"]
assert 0 not in chip["uarts"], chip["chip"]

assert errs(ESP32) == []
expect(errs(ESP32, sda=6), "SPI flash")
expect(errs(ESP32, scl=12), "strapping")
expect(errs(ESP32, gps_tx=1), "host link")
expect(errs(ESP32, sda=34), "input-only")
assert errs(ESP32, gps_rx=34) == [] # a receive pin may be input-only
expect(errs(ESP32, sda=24), "does not exist")
expect(errs(ESP32, scl=21), "more than one signal")
expect(errs(ESP32, uart=0), "UART0")
expect(errs(ESP32, sda=True), "integer")
assert len(errs(ESP32, sda=6, scl=12)) == 2 # every problem is reported, not just the first

s3_good = {"sda": 8, "scl": 9, "gps_rx": 18, "gps_tx": 17}
assert boards.pin_errors(s3_good, 1, S3) == []
expect(boards.pin_errors({**s3_good, "sda": 19}, 1, S3), "USB")
expect(boards.pin_errors({**s3_good, "sda": 22}, 1, S3), "does not exist")
expect(boards.pin_errors({**s3_good, "sda": 35}, 1, S3, {"35": "octal PSRAM"}), "reserved on this board")

# Every shipped manifest passes its own chip's rules.
for board in boards.load_all():
chip = boards.load_chip(board["chip"])
assert boards.pin_errors(board["pins"], board["gps_uart"], chip, board.get("reserved")) == [], board["id"]

print("pin rules OK")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading