diff --git a/README.md b/README.md
index 57f45a1..a34098b 100644
--- a/README.md
+++ b/README.md
@@ -60,6 +60,21 @@ anything you can download you can also program directly. A collection that
lives in another repository has to be cloned next to this one; the error says
which `git clone` to run.
+A radio running [RadioFoundry](https://radiofoundry.org/) firmware can have
+the firmware pinned too. `firmware build` compiles it from one commit of a
+RadioFoundry checkout in the toolchain container that commit pins and checks
+the image against a recorded hash; `firmware install` flashes it; and
+`program` then refuses a radio that reports any other firmware:
+
+```bash
+uv run codeplugger firmware build --radio baofeng_dm32_radiofoundry
+uv run codeplugger firmware install --radio baofeng_dm32_radiofoundry \
+ --port /dev/cu.usbserial-2120 --confirm
+```
+
+The build needs Docker; the details and what has been verified are in
+[docs/backends.md](docs/backends.md#radiofoundry-firmware-firmware-build-and-firmware-install).
+
`--profile` also takes a git URL or a local directory, so a group does not have
to be in the registry to be usable:
@@ -130,6 +145,9 @@ flowchart LR
exporter["Exporter
CHIRP CSV / qdmr YAML / P4 TOML / benlink plan"]
cps["CPS tool
CHIRP / vendor CPS"]
artifacts["Artifacts
HTML reference + operation log"]
+ rfoundry["RadioFoundry checkout
one verified commit"]
+ fwbuild["firmware build
pinned toolchain container, image checked against firmware.lock.json"]
+ fwinstall["firmware install
gated flash through rfoundry"]
radio["Radio"]
public --> resolve
@@ -140,8 +158,14 @@ flowchart LR
resolved --> backend --> radio
resolved --> exporter --> cps --> radio
resolved --> artifacts
+ rfoundry --> fwbuild --> fwinstall --> radio
+ radio -. "reports its firmware commit" .-> backend
```
+The firmware path applies to RadioFoundry radios only: their firmware is
+built from one commit and flashed before the codeplug is written, and the
+write is refused when the radio reports any other firmware.
+
The diagram source is also available in [docs/workflow.mmd](docs/workflow.mmd).
## Documentation
@@ -154,7 +178,8 @@ The diagram source is also available in [docs/workflow.mmd](docs/workflow.mmd).
- [docs/backends.md](docs/backends.md): each exporter and programming
backend, with the write gates it enforces: CHIRP CSV and `chirp-writer`,
qdmr YAML and `dmrconf`, qdmr YAML and `radiofoundry-cps` for RadioFoundry
- firmware, P4 TOML and `p64tool`, benlink.
+ firmware, P4 TOML and `p64tool`, benlink. Also building and installing
+ RadioFoundry firmware at a pinned commit with `codeplugger firmware`.
- [docs/operations.md](docs/operations.md): HTML reference artifacts,
operation logs, and the registry-driven fleet dry run.
- [docs/architecture.md](docs/architecture.md): which repository owns which
@@ -171,7 +196,11 @@ four exporters, the five gated write backends, and HTML/operation-log
artifacts are working today. Which radios have had a codeplugger-generated
codeplug written to them and read back is recorded per radio on the
[project site](https://codeplugger.chicagooffline.com/); the benlink path has
-not yet been accepted against a physical radio. Prebuilt community codeplugs
+not yet been accepted against a physical radio. RadioFoundry firmware builds
+reproducibly from a pinned commit with `codeplugger firmware build`, and
+`codeplugger firmware install` has flashed one RT3S; the DM-32UV and DM-1701
+have not been flashed that way yet. Prebuilt
+community codeplugs
are published at
[codeplugger.chicagooffline.com/codeplugs/](https://codeplugger.chicagooffline.com/codeplugs/)
so members can download a file without installing anything. What comes next,
diff --git a/docs/backends.md b/docs/backends.md
index 5b2cf23..49a4654 100644
--- a/docs/backends.md
+++ b/docs/backends.md
@@ -173,10 +173,19 @@ the `radiofoundry-cps` backend, which drives RadioFoundry's own
`dmrconf` is still required, for encoding only. Rendering YAML into an image
stays with qdmr's encoder, reached through RadioFoundry's
-`tools/codeplug_port.py`, which puts back the TX contacts that encoder drops
-from DMR channels. The backend imports that module from the checkout rather
-than keeping a copy of it. Its optional group-list cleanup is switched off: it
-mangles the block-style `groupLists` qdmr 0.15.1 exports and drops every list.
+`tools/codeplug_port.py`. That module undoes two things the encoder does: it
+writes a channel's TX contact or its group list but never both, so the
+contact is put back, and it gives every contact a TS1 override that the
+firmware prefers to the channel's own timeslot, so the override is cleared.
+The backend imports that module from the checkout rather than keeping a copy
+of it. Its optional group-list cleanup is switched off: it mangles the
+block-style `groupLists` qdmr 0.15.1 exports and drops every list.
+
+Upstream finds channels and contacts by their indentation, as qdmr writes
+them, and reads a list whose items start in column zero as empty. Codeplugger
+writes its export that way, so the backend hands upstream a re-indented copy
+(`export-qdmr-style.yaml` in the work directory), and then compares the
+encoded result with the export itself (gate 6).
What it needs:
@@ -193,6 +202,15 @@ What it needs:
passed. Reads are not gated. The list is `VERIFIED_REVISIONS` in
`backends/radiofoundry.py`; add a commit only after a write through it has
read back clean.
+- The radio running firmware at one of the same verified revisions. The
+ codeplug layout, the regions a write may touch and the wire offset are the
+ firmware's to define, so the list that pins the tools pins the firmware
+ too. The radio reports the commit it was built from in `cps_client info`;
+ a write to any other commit, to a build from a modified tree (`-dirty`), or
+ to a radio that reports none is refused before the backup is read, unless
+ `--allow-unverified-firmware` is passed.
+ [`codeplugger firmware`](#radiofoundry-firmware-firmware-build-and-firmware-install)
+ builds and installs a verified revision.
- `dmrconf` on the path, or named with `--dmrconf`.
- `--port` for a radio on a programming cable, which means every DM-32UV.
Without it `cps_client` only finds a single USB `1FC9:0094` device, which is
@@ -239,38 +257,83 @@ The write gates, in order:
skips the model check, because 6 is what the firmware sends for any board
that declares no type of its own (the DM-32UV is one), so it identifies
nothing.
-4. A full read of the configured regions into the backup, retried across the
+4. The firmware commit the radio reported in that same `info` must be a
+ verified revision, or the run must opt in. The commit and the build stamp
+ go to the operation log as a `firmware` entry either way, so the log names
+ the firmware a write went to as well as the tools that sent it.
+5. A full read of the configured regions into the backup, retried across the
post-session reboot.
-5. The export is encoded and flattened into the image the CPS wire wants.
-6. The write. A serial fault mid-write is retried up to three times; a resumed
+6. The export is encoded and flattened into the image the CPS wire wants,
+ and the image is decoded and compared with the export. An image in which
+ a channel has lost or changed its TX contact, or a contact has a timeslot
+ override the export did not ask for, is refused before anything is
+ written. The read-back checks below compare the radio with the image, so
+ this is the only gate that compares it with what was asked for.
+7. The write. A serial fault mid-write is retried up to three times; a resumed
attempt only re-sends sectors that still differ. A refusal from the radio
is not retried.
-7. A read-back into the read-back path, with the same retry as the backup.
-8. `cps_client verify`, a byte-for-byte compare. If it disagrees, the
+8. A read-back into the read-back path, with the same retry as the backup.
+9. `cps_client verify`, a byte-for-byte compare. If it disagrees, the
read-back is decoded with `dmrconf` and compared against the codeplug that
was sent, and only a mismatch there fails the write.
-The fallback in step 8 exists because a byte compare flags good writes. On a
-DM-1701 whose decoded read-back was identical to the YAML sent, the compare
+The fallback in step 9 exists because a byte compare flags good writes. On a
+DM-1701 whose decoded read-back was identical to the YAML decoded from the
+image, the compare
still reported 8,634 differing bytes: 26 in the VFO A scratch area, which the
radio rewrites, and 8,608 of padding between image sections that is never
sent. The decoded compare checks channel, zone, contact and group-list counts
first; matching counts with differing YAML text still pass, and the output and
the operation log say which of the two it was.
-**Hardware-verified 2026-12-01** on both radios that have been tried:
+**Hardware-verified 2026-12-01** on the first two radios that were tried:
- DM-32UV (`eam_dm32_02`, over a USB-serial programming cable): 279 channels,
30 zones, 23 contacts and 5 group lists written at offset `0x700000`. The
pre-write backup and the read-back were both 1,179,648 bytes, and the
- decoded read-back was identical to the codeplug sent.
+ decoded read-back was identical to the encoded image.
- DM-1701: the same codeplug shape, with the decoded read-back identical to
- the YAML sent line for line. This is the write the byte-compare figures
+ the encoded image line for line. This is the write the byte-compare figures
above come from.
-Both ran RadioFoundry at git `62db1bae`. The RT3S entry has not been written
-on this firmware. The DM-32's progress bar is not evidence either way: it sat
-at 5% long after a read had finished on disk.
+Both ran RadioFoundry at git `62db1bae`. The DM-32's progress bar is not
+evidence either way: it sat at 5% long after a read had finished on disk.
+
+**Those writes went through the old path, and one has been checked.** They
+predate gate 6 and the re-indented export, and "identical" above means
+identical to the encoded image, not to the export. An RT3S programmed the
+same way on 2026-12-02 read back clean while holding 9 of the profile's 38 TX
+contacts and a TS1 override on all 23 contacts; RadioFoundry's spec says a
+channel without a contact talks to TG 9. A DM-32UV carrying the 279-channel
+bench codeplug was then read before being re-programmed: none of its 31 DMR
+channels with a group list had a TX contact, and all 23 contacts carried the
+TS1 override. The DM-1701 went through the same path and has not been read
+back; it should be re-programmed.
+
+**Hardware-verified 2026-12-02 with the fix**, on two radios carrying the
+same codeplug (232 channels, 8 zones, 23 contacts, 5 group lists), each
+passing the firmware gate (4) on `git=62db1bae`, `build=20261130182236`:
+
+- RT3S (`eam_rt3s_01`, USB): upstream cleared the 23 overrides and put 29
+ contacts back, the write changed 52 bytes, and the byte-for-byte verify
+ passed. This was the first `program --confirm` through the firmware gate,
+ after `firmware install` had put that commit on the radio; before the
+ install the same radio reported `acd7cd69` and the check refused it.
+- DM-32UV (`eam_dm32_03`, programming cable, offset `0x700000`): the write
+ took 35 seconds and the whole run under two minutes. The byte compare
+ differed in 4,541 bytes, 29 in the VFO scratch area and 4,512 of padding
+ at `0x020000`, all equal to the pre-write backup, and the decoded compare
+ was identical.
+
+For both, the read-back decoded and compared with the export shows no
+differences: 38 of 38 TX contacts and no timeslot overrides. The two exports
+are the same document, so the two radios hold the same codeplug.
+
+When the port cannot be opened at all (`Resource busy`), another program has
+it. On the bench Mac that was `gpsd`, started by a LaunchDaemon configured
+for the device name the radio happened to get; it runs as another user, so
+`lsof` does not show it without `sudo`. The RT3S then answered nothing over
+CPS or the debug link until it was reset and recabled.
When a cabled radio answers nothing, `tools/dm32_cps_probe.py PORT` separates
the two directions of the link. It sends commands that change the radio's
@@ -298,6 +361,181 @@ difference was contact `timeSlotOverride` reading `None` where qdmr encodes
without an `openGD77` block. `codeplugger program` no longer takes this path
for these radios, but the `dmrconf` backend can still be driven directly.
+## RadioFoundry firmware: `firmware build` and `firmware install`
+
+A codeplug is written into a layout the firmware defines, so a radio is only
+reproducible when its firmware is pinned as well. `codeplugger firmware`
+builds a RadioFoundry radio's firmware from one commit and flashes it, and
+`program` refuses a radio whose firmware is not a verified revision (gate 4
+above). Which commits count is `VERIFIED_REVISIONS`, the list that already
+pins the checkout, so one list covers both ends of the cable.
+
+A radio opts in by naming its RadioFoundry board in `capabilities.json`:
+
+```json
+"radiofoundry_firmware": {
+ "board": "dm32"
+}
+```
+
+`board` is the directory under `boards/` in a RadioFoundry checkout, built
+with the board's default options: `dm32`, `dm1701`, and `mduv380` for the
+RT3S. It is separate from `radiofoundry_cps.board` on purpose, because that
+field changes which regions a codeplug write protects.
+
+### Building
+
+```bash
+uv run codeplugger firmware build --radio baofeng_dm32_radiofoundry
+```
+
+No radio is involved. The build needs a container engine (`--docker`,
+default `docker`) and a RadioFoundry checkout with its submodules fetched,
+and does this:
+
+1. Clones the checkout at one commit into
+ `~/.cache/codeplugger/firmware/build/`, with the submodules cloned
+ from the checkout's own copies at the commits the superproject pins. The
+ default commit is the newest verified revision; `--commit` names another.
+ Nothing is compiled in the checkout itself, so uncommitted changes, a
+ moved HEAD and an old `build/` directory cannot reach the image. The clone
+ is replaced on every build.
+2. Reads the toolchain that commit pins in
+ `platform//platform.toml` and runs `make BOARD=` in a
+ `linux/amd64` container. The DM-32UV builds in the pinned C-SKY image,
+ which is a complete build environment. For the DM-1701 and RT3S upstream
+ pins the Arm toolchain by digest as an image holding only the compiler
+ tree, which its CI copies onto an Ubuntu runner; the build copies that
+ tree into the cache once and mounts it into the same C-SKY image, the one
+ runnable build environment upstream pins.
+3. Refuses an image that is not stamped with the clean commit. Upstream's
+ Makefile stamps a clean tree with the commit's time and a modified one
+ with the clock, so a `-dirty` stamp means the bytes depend on when it was
+ built.
+4. Packages the image with upstream's `tools/release.py` into
+ `.artifacts//firmware//`: the image, its manifest,
+ `SHA256SUMS` and `build.log`. The manifest carries the full commit, the
+ image's SHA-256 and the compiler's version line.
+5. Compares the image's SHA-256 with `radios//firmware.lock.json`.
+
+| The lock for this commit | Result |
+|---|---|
+| Holds the same SHA-256 | The build reproduced. Exit 0. |
+| Has no entry | Exit 0 with a note; `--update-lock` records the image. |
+| Holds a different SHA-256 | Error, exit 1. `--update-lock` never replaces an entry. |
+
+The packaged version label is `codeplugger-`, as in
+`rfoundry-dm32-codeplugger-62db1bae.bin`. The label is in the manifest and
+the file names only, never in the image, so it does not change the hash.
+
+What is and is not pinned:
+
+- Pinned: the source commit and its submodules, the compiler, and the
+ resulting image. The Arm toolchain is pinned by digest. The C-SKY image is
+ pinned upstream by tag only, so the image ID that actually ran is written
+ to the operation log, and a changed compiler shows up as a lock mismatch.
+- Not pinned: the AMBE codec, which is never part of a build and comes from
+ the radio or from a stock firmware file at install time, and the radio's
+ calibration.
+- `--build-image` builds in another image. The result then only matches the
+ lock if the compiler produces the same bytes.
+
+**Reproduced 2026-12-02** on an Apple silicon Mac (Docker 29.9.3, amd64
+emulated), at `62db1bae`:
+
+| Radio | Board | Compiler | Bytes | SHA-256 |
+|---|---|---|---|---|
+| DM-32UV | `dm32` | csky-elf-gcc 14.2.0 | 777,592 | `1b69a27841f6c1d3e926b4b859e024bb7c0fe813b0046def4c012c541fe7cc95` |
+| DM-1701 | `dm1701` | Arm GNU Toolchain 13.3.Rel1 | 704,852 | `37e475ebe70bdfaced85039b00a01ae2ecf6be0a39e8326e76aec32083414658` |
+| RT3S | `mduv380` | Arm GNU Toolchain 13.3.Rel1 | 706,132 | `30a1d79f48f8daace3734e63e10c8acb7065af7f314c9321a09ad93307e38bb1` |
+
+The DM-32UV and DM-1701 images came out identical from clones at three
+different paths, and the RT3S image from two builds at one path.
+RadioFoundry has published no release to compare against, so these hashes
+show the build is repeatable here, not that it equals an upstream artifact.
+Only the RT3S image has been flashed to a radio (below).
+
+Under emulation a parallel Arm build stops at the link: GCC 13's LTO step
+takes inherited file descriptors for make's jobserver and aborts in
+`return_token`. The build therefore runs `make -j` first and, if that fails,
+`make` serially, which only redoes what is missing. The image is the same
+either way; a real compile error fails both runs.
+
+### Installing
+
+```bash
+# Show rfoundry's plan; nothing is written
+uv run codeplugger firmware install --radio baofeng_dm32_radiofoundry \
+ --port /dev/cu.usbserial-2120
+
+# Flash, then confirm what the radio reports
+uv run codeplugger firmware install --radio baofeng_dm32_radiofoundry \
+ --port /dev/cu.usbserial-2120 --confirm
+```
+
+Flashing is done by upstream's `rfoundry`, run from `tools/rfoundry` in the
+checkout. It knows each board's bootloader route, keeps the radio's codec or
+writes it from `--stock`, and erases only the sectors it needs. The
+interpreter that runs it (the checkout's `.venv/bin/python` when there is
+one) needs rfoundry's own dependencies: `pyusb`, `libusb-package`,
+`pyserial` and `certifi`. Where neither environment has them, `uv run --with
+pyserial --with pyusb --with libusb-package --with certifi codeplugger
+firmware install ...` supplies them for one run. Without `--image`, the
+build of the newest verified revision under `--artifact-root` is used.
+
+The gates, in order:
+
+1. The image's manifest must describe the image beside it, and its board
+ must be the radio's.
+2. The image must be the locked build of a verified revision: its commit is
+ in `VERIFIED_REVISIONS` and its SHA-256 is the one `firmware.lock.json`
+ holds for that commit. `--allow-unverified-firmware` opts in.
+3. The checkout must be at a verified revision with `tools/` unmodified, as
+ for a codeplug write, because `rfoundry` is run from it.
+ `--allow-unverified-rfoundry` opts in.
+4. `rfoundry flash --dry-run` prints the plan: which sectors are erased and
+ written, and what happens to the codec. Without `--confirm` it stops here.
+5. `rfoundry flash` runs attached to the terminal. It asks for the
+ bootloader keys to be held at the radio and for a last confirmation, so
+ this step cannot run unattended.
+6. `cps_client info` must then report the commit that was sent. rfoundry
+ exiting cleanly is not treated as the radio running the new firmware.
+
+Each step is written to `.artifacts//firmware/operations.jsonl`.
+
+`rfoundry` reports every flash to the RadioFoundry project: the radio model,
+the firmware's version label, variant and feature list, and whether it
+succeeded. That is left on, and the `codeplugger-` label is what
+marks an install as made through codeplugger, since the report has no field
+for the calling tool. Setting `REPORTING=0` in the environment turns the
+report off.
+
+**Hardware-verified 2026-12-02 on the RT3S**, once. The radio was running
+`acd7cd69`, so the install was a downgrade to `62db1bae`. rfoundry found it
+over the debug link, kept its codec (`mduv380-1926-s11`), erased sectors 3
+to 9 and wrote 690 blocks through the bootloader, and left codec sectors 10
+and 11 and the bootloader alone. The radio restarted reporting `62db1bae`
+with DMR voice ready, codeplugger's read-back (gate 6) confirmed the commit,
+and a separate identity read afterwards gave `git=62db1bae`,
+`build=20261130182236`, which passes the firmware gate. That build stamp is
+the commit's time, not the time of the build two days later, which is the
+property the reproducible build depends on.
+
+What that run does not cover:
+
+- It was the second attempt. On the first the radio was not ready when
+ rfoundry went to flash, and the run stopped within a second of the plan
+ with nothing written; the operator started over.
+- The DM-32UV, which flashes over the programming cable by a different
+ route, and the DM-1701 have not been flashed through this command. The
+ DM-1701 image has only been through rfoundry's simulated flash.
+
+A codeplug was then written to that RT3S with `program --confirm`, which is
+the write recorded under `radiofoundry-cps` above.
+
+A plan-only run saves a copy of the radio's codec on the computer, in
+rfoundry's settings folder, the first time it sees the radio.
+
## P4 TOML and `p64tool`
The P4 exporter requires a TOML file produced by `p64tool decode` as its
diff --git a/docs/operations.md b/docs/operations.md
index 44b17b5..cde387c 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -18,7 +18,11 @@ This creates `.artifacts///reference.html` and
`operations.jsonl`. The latter records successful profile generation and can
also be passed to a backend as an `ArtifactStore` to audit device reads and
writes; `codeplugger program --artifact-root` does this, and the backups and
-read-back images it takes land in the same directory. Generated artifacts are
+read-back images it takes land in the same directory. `codeplugger firmware`
+keeps a log of its own at `.artifacts//firmware/operations.jsonl`,
+beside the images it builds, recording each build with its SHA-256 and
+compiler, each comparison with the firmware lock, and each install step.
+Generated artifacts are
evidence of an operation, not an authoritative profile or RF data source.
The reference begins with the radio model, instance identity, UTC generation
diff --git a/docs/plan.md b/docs/plan.md
index 6e3d947..25ff664 100644
--- a/docs/plan.md
+++ b/docs/plan.md
@@ -191,11 +191,12 @@ Working today:
radio against an image, where dmrconf can only archive a read-back.
dmrconf keeps the one job only it can do, encoding the YAML, through
RadioFoundry's `codeplug_port.py`, which is imported from the checkout
- rather than copied and which restores the TX contacts qdmr's encoder
- drops. The gates are the house pattern (confirm, identity, mandatory
+ rather than copied and which puts back the TX contacts qdmr's encoder
+ drops and clears the TS1 override it gives every contact. The gates are
+ the house pattern (confirm, identity, mandatory
backup, write, read-back, verify) with two bench lessons built in. A
byte compare is the wrong judge of a write: a DM-1701 whose decoded
- read-back matched the YAML sent line for line still differed in 8,634
+ read-back matched the image's YAML line for line still differed in 8,634
bytes, all of them VFO A scratch the radio rewrites or padding that is
never sent, so a failed byte compare falls back to decoding the read-back
and comparing that. And radio type 6 is not an identity: it is the
@@ -203,17 +204,58 @@ Working today:
a board, and reading it as "MD-UV380" refused every correct DM-32 write.
**Hardware-verified 2026-12-01** on the DM-32UV (`eam_dm32_02`, 279
channels / 30 zones / 23 contacts / 5 group lists, decoded read-back
- identical to the codeplug sent) and on the DM-1701 (the same counts,
- decoded read-back identical). The DM-1701 had been verified the day
- before over the `dmrconf` path, which both STM32 entries still carry a
- block for (**2026-11-30**, `eam_dm1701_01`, 278 channels / 30 zones,
+ identical to the encoded image) and on the DM-1701 (the same counts,
+ decoded read-back identical). **Neither write was what it claimed**: a
+ third lesson came
+ on 2026-12-02, when an RT3S written the same way read back clean while
+ holding 9 of its profile's 38 TX contacts and a TS1 override on all 23
+ contacts. Upstream finds channels and contacts by qdmr's indentation and
+ took codeplugger's export, whose list items start in column zero, for
+ empty lists, so neither fix-up ran, and both verify steps compare the
+ radio with the encoded image rather than with the export. The backend now
+ hands upstream a re-indented copy and refuses an image that differs from
+ the export in a channel's TX contact or a contact's timeslot override.
+ **Hardware-verified with that fix 2026-12-02** on the RT3S (`eam_rt3s_01`)
+ and on a DM-32UV (`eam_dm32_03`), both carrying the same codeplug (232
+ channels / 8 zones / 23 contacts / 5 group lists): 29 contacts put back,
+ 23 overrides cleared, and for each the decoded read-back compared with the
+ export shows no differences. That DM-32UV had been carrying the
+ 279-channel bench codeplug from the old path, and read back with no TX
+ contact on any of its 31 DMR channels that have a group list, which
+ confirms the loss on a second model. The DM-1701 had first been written
+ over the
+ `dmrconf` path, which both STM32 entries still
+ carry a block for (**2026-11-30**, `eam_dm1701_01`, 278 channels / 30 zones,
read-back decoded equal to the intended image); that run added `--port`
-> `--device` plumbing to the dmrconf backend (macOS lists `cu.*` and
`tty.*` as two devices and qdmr refuses to choose), a CLI
`--init-codeplug` flag, and a read-back retry because the radio reboots
- off USB on dmrconf's closing command. The RT3S entry remains unbadged:
- `eam_rt3s_01` runs OpenGD77, and nothing has been written to an RT3S on
- this firmware.
+ off USB on dmrconf's closing command.
+- RadioFoundry firmware is pinned as well as written to (2026-12-02), so a
+ RadioFoundry radio is one firmware commit plus one codeplug. Three pieces,
+ all keyed on `VERIFIED_REVISIONS`, the list that pins the checkout.
+ `program` reads the commit the radio reports in `cps_client info`, logs it,
+ and refuses a write to firmware that is not a verified revision
+ (`--allow-unverified-firmware` opts in). `codeplugger firmware build`
+ (`backends/radiofoundry_firmware.py`) compiles a radio's image from a
+ scratch clone of the checkout at one commit, in the toolchain container
+ that commit pins, packages it with upstream's `release.py`, and compares
+ its SHA-256 with `radios//firmware.lock.json`; the board comes from a
+ new `radiofoundry_firmware` capabilities block. `codeplugger firmware
+ install` flashes a locked image through upstream's `rfoundry`, showing its
+ plan first and afterwards requiring the radio to report the commit that
+ was sent. **Builds reproduced 2026-12-02** at `62db1bae` for all three
+ radios (`dm32` 777,592 bytes, `dm1701` 704,852, `mduv380` 706,132; hashes
+ in the lock files), each byte-identical across repeated builds from fresh
+ clones on an Apple silicon Mac under amd64 emulation. Upstream has no
+ published release to compare with, so that is repeatability, not equality
+ with an upstream artifact. **Install hardware-verified 2026-12-02 on the
+ RT3S**, once: a radio running `acd7cd69` was refused by the firmware
+ check, `firmware install` flashed the locked `62db1bae` image through
+ rfoundry (codec kept, sectors 3 to 9 rewritten), and the radio came back
+ reporting `62db1bae` with the commit's own build stamp and passed the
+ check. The DM-32UV's serial route and the DM-1701 have not been flashed
+ this way.
- Analog radios (UV-5R Mini, Ailunce HA2, Retevis C64, Baofeng BF-888S, Baofeng
W31E, Yaesu FT-270R / FT-277R / FT-2800M): CHIRP CSV export (FM, with NFM
as its narrow bandwidth, and receive-only AM), either imported in the CHIRP
@@ -702,6 +744,25 @@ Known gaps not tracked by an item above:
behaviour at that revision: the group-list cleanup is switched off because
it drops every list from qdmr 0.15.1's export, and serial faults are
retried around a write loop that does not catch them itself.
+- `codeplugger firmware install` has flashed one radio, an RT3S (the
+ first attempt stopped before flashing because the radio was not ready).
+ The DM-32UV and DM-1701 have not been flashed through it. The firmware
+ gate in `program` has run on that one radio: it refused `acd7cd69` on an
+ identity read and passed `62db1bae` through a full `program --confirm`.
+- The DM-1701 written on 2026-12-01 needs re-programming through the fixed
+ `radiofoundry-cps` path: it very likely holds a codeplug with most DMR
+ channels' TX contacts missing and a TS1 override on every contact, as the
+ RT3S and a DM-32UV written the same way both did, and it has not been
+ read back. Its `hw` flag on the site was earned by a write that matched
+ the encoded image, not the export. The DM-32UV row's flag is now backed by
+ a write that matches its export, and the RT3S RadioFoundry row, which has
+ one too, carries no flag yet. Two
+ limits on what the lock pins: the C-SKY toolchain image is pinned upstream
+ by tag, not digest, so a re-pushed tag surfaces as a lock mismatch rather
+ than being prevented, and the AMBE codec is outside the build entirely.
+ Arm boards are built inside the C-SKY image with the Arm toolchain mounted
+ in, because upstream publishes no runnable image of its pinned Arm
+ compiler; an upstream change to either image's layout breaks that.
## Later
diff --git a/docs/workflow.mmd b/docs/workflow.mmd
index ba13520..94b9c1c 100644
--- a/docs/workflow.mmd
+++ b/docs/workflow.mmd
@@ -9,6 +9,9 @@ flowchart LR
exporter["Exporter
CHIRP CSV / qdmr YAML / P4 TOML / benlink plan"]
cps["CPS tool
CHIRP / vendor CPS"]
artifacts["Artifacts
HTML reference + operation log"]
+ rfoundry["RadioFoundry checkout
one verified commit"]
+ fwbuild["firmware build
pinned toolchain container, image checked against firmware.lock.json"]
+ fwinstall["firmware install
gated flash through rfoundry"]
radio["Radio"]
public --> resolve
@@ -18,4 +21,6 @@ flowchart LR
resolve --> resolved
resolved --> backend --> radio
resolved --> exporter --> cps --> radio
- resolved --> artifacts
\ No newline at end of file
+ resolved --> artifacts
+ rfoundry --> fwbuild --> fwinstall --> radio
+ radio -. "reports its firmware commit" .-> backend
\ No newline at end of file
diff --git a/radios/baofeng_dm1701_radiofoundry/capabilities.json b/radios/baofeng_dm1701_radiofoundry/capabilities.json
index 46453a5..6f79cee 100644
--- a/radios/baofeng_dm1701_radiofoundry/capabilities.json
+++ b/radios/baofeng_dm1701_radiofoundry/capabilities.json
@@ -42,5 +42,8 @@
"regions": "codeplug",
"model": "DM-1701"
},
+ "radiofoundry_firmware": {
+ "board": "dm1701"
+ },
"notes": "Baofeng DM-1701 (also sold as the Retevis RT84) after installing RadioFoundry, the MIT-licensed multi-mode firmware (radiofoundry.org). To the toolchain it is a third radio beside baofeng_dm1701 (OEM) and baofeng_dm1701_opengd77: RadioFoundry stores the codeplug in the open-firmware layout and speaks qdmr's open-firmware CPS protocol through a compatibility shim (RadioFoundry docs/spec/open-firmware-cps.md and cps-protocol.md), so dmrconf can program it under radio key openuv380 exactly like the OpenGD77 entries, and the dmrconf block above is kept for that. codeplugger program no longer goes that way: the radiofoundry_cps block takes precedence, so dmrconf only encodes the image and RadioFoundry's own tools/cps_client.py moves it, which avoids dmrconf's cold-read failures against this firmware and adds a verify step. Its model assertion, 'DM-1701', is a string read off this radio. The USB details that follow describe the dmrconf path. On this STM32 radio the host port is USB CDC-ACM at VID 0x1FC9 PID 0x0094, which is the only identity qdmr auto-detects; the radio reports open-firmware radio type 8 (10 on the other panel variant), which qdmr's driver maps to its OpenUV380 model, so detect prints 'Open MD-UV380' and the backend's RADIO_NAMES gate holds unchanged. The radio must be in USB serial mode, not RadioFoundry's USB network mode (PID 0x0095/0x0096), which qdmr cannot see. Limits are qdmr v0.15.1 OpenGD77Limits, the same singleton the opengd77 entries cite, and they match what RadioFoundry itself reads from the image (RadioFoundry docs/user/04-programming.md): 1024 channels, 68 zones of 80 channels (RadioFoundry always writes the 80-channel zone layout), 1024 contacts, 76 RX group lists of 32, 16-character names. max_scan_lists is 0 on purpose: RadioFoundry's qdmr import drops scanLists (docs/spec/qdmr-yaml.md section 2) and qdmr marks them ignored on this key, so a profile carrying scan lists is refused loudly rather than silently trimmed. The UHF ceiling is 470 MHz because qdmr's OpenGD77Limits rejects anything above it on this key, although the hardware and RadioFoundry both cover 400-480. Modes are FM and DMR only: RadioFoundry's P25, NXDN and Tier III channels live in a radioFoundry block of the YAML that qdmr ignores and this exporter never writes, and the OpenGD77 limits define no AM channel class. The dmrconf verify stand-in (openuv380 -> opengd77) and the never-pass---radio-on-write rule in the backend apply as for OpenGD77. Flashing RadioFoundry over an OEM codeplug is a capacity downgrade (1024 channels and contacts against 3000 and 10000), so a profile built for baofeng_dm1701 has to be rebuilt against this entry, not reused. BENCH-VERIFIED 2026-11-30 on eam_dm1701_01 (MuehlMini, dmrconf 0.15.1): detect 'Open MD-UV380', pre-write backup, a 278-channel / 30-zone write, read-back decoded to the same channels, zones and TG lists as an offline encode of the sent YAML; the only decoded difference was contact timeSlotOverride reading None where qdmr had encoded TS1, which RadioFoundry's qdmr-yaml spec documents as the firmware's reading of a contact without an openGD77 block. Two operational facts from that run: on macOS the port must be passed (--port /dev/cu.usbmodem21101) because qdmr lists the cu.* and tty.* nodes as two devices and refuses to auto-detect; and the radio reboots on dmrconf's closing C 6 0 and drops off USB for a few seconds, so the backend retries the read-back. BENCH-VERIFIED 2026-12-01 over the radiofoundry_cps path (RadioFoundry git 62db1bae): 279 channels, 30 zones, 23 contacts and 5 group lists written, and the read-back decoded to YAML identical to what was sent. The byte compare still reported 8,634 differing bytes, 26 in the VFO_A scratch area the radio rewrites and 8,608 of padding that is never sent, which is why that backend verifies semantically. Sources: RadioFoundry docs at commit 62db1bae (2026-11-30)."
}
diff --git a/radios/baofeng_dm1701_radiofoundry/firmware.lock.json b/radios/baofeng_dm1701_radiofoundry/firmware.lock.json
new file mode 100644
index 0000000..2550806
--- /dev/null
+++ b/radios/baofeng_dm1701_radiofoundry/firmware.lock.json
@@ -0,0 +1,11 @@
+{
+ "board": "dm1701",
+ "format": "codeplugger-firmware-lock/1",
+ "images": {
+ "62db1bae38969bf5ac72764376b31416ba55a71e": {
+ "sha256": "37e475ebe70bdfaced85039b00a01ae2ecf6be0a39e8326e76aec32083414658",
+ "size": 704852,
+ "toolchain": "arm-none-eabi-gcc (Arm GNU Toolchain 13.3.Rel1 (Build arm-13.24)) 13.3.1 20240614"
+ }
+ }
+}
diff --git a/radios/baofeng_dm32_radiofoundry/capabilities.json b/radios/baofeng_dm32_radiofoundry/capabilities.json
index 9fb6e21..e27ec74 100644
--- a/radios/baofeng_dm32_radiofoundry/capabilities.json
+++ b/radios/baofeng_dm32_radiofoundry/capabilities.json
@@ -39,5 +39,8 @@
"regions": "codeplug",
"offset": "0x700000"
},
- "notes": "Baofeng DM-32UV after installing RadioFoundry, the MIT-licensed multi-mode firmware (radiofoundry.org, board dm32). This is a different radio from baofeng_dm32 (OEM): RadioFoundry drops the OEM codeplug format and keeps the codeplug in the open-firmware (OpenGD77/qdmr) layout, so the limits here are qdmr's OpenGD77Limits, not the OEM 4000-channel figures, and every profile has to be rebuilt against this entry. There is deliberately NO dmrconf block. qdmr cannot reach this radio: the DM-32UV has no USB of its own, its HR_C7000 platform exposes the CPS protocol only on the UART programming cable, and RadioFoundry places the open-firmware image 7 MB into the data flash, while qdmr's driver neither finds a generic USB-serial cable (it matches VID 0x1FC9 PID 0x0094 only) nor adds that offset, so its writes would land in the stock area where RadioFoundry refuses them. The radiofoundry_cps block above is the write path instead: codeplugger renders the codeplug with dmrconf against the limit-identical openuv380/opengd77 layout, then moves the image over RadioFoundry's own CPS link at offset 0x700000, which is where the open firmware actually reads it. 'dmrconf verify --radio=opengd77' still checks the YAML offline without hardware. RadioFoundry's manual routes remain available and produce the same file: tools/dm32_migrate.py restore --yaml FILE over the programming cable, or the browser Codeplug Editor at radiofoundry.org/codeplug (docs/user/23-radios.md, Programming). Limits: 1024 channels, 68 zones of 80, 1024 contacts, 76 RX group lists of 32, 16-character names, matching RadioFoundry's own description of what the radio reads from the codeplug. max_scan_lists is 0 because RadioFoundry drops qdmr scanLists on import and scans by zone. The UHF ceiling is 470 MHz because qdmr's OpenGD77Limits rejects above it when the YAML is encoded, although the hardware and RadioFoundry both cover 400-480. Modes are FM and DMR only: RadioFoundry's airband AM and broadcast FM receive on this radio have no channel class in the OpenGD77 limits, and its P25/NXDN/Tier III channels travel in a radioFoundry YAML block that qdmr ignores and this exporter does not write. The radio reports open-firmware radio type 6, which means 'the board declared no radio type', not an identity; the CPS backend accepts it rather than treating it as a model mismatch. If a future release gives qdmr a working offset-aware driver, add a dmrconf block then, not before. BENCH-VERIFIED 2026-12-01 on a clear-case DM-32UV running RadioFoundry (git 62db1bae): full write over the CPS link, then a read-back decoded and compared, identical to the codeplug sent. Verification is semantic, not byte-for-byte, because a correct write still differs in padding clusters and the VFO_A scratch area. Sources: RadioFoundry docs at commit 62db1bae."
+ "radiofoundry_firmware": {
+ "board": "dm32"
+ },
+ "notes": "Baofeng DM-32UV after installing RadioFoundry, the MIT-licensed multi-mode firmware (radiofoundry.org, board dm32). This is a different radio from baofeng_dm32 (OEM): RadioFoundry drops the OEM codeplug format and keeps the codeplug in the open-firmware (OpenGD77/qdmr) layout, so the limits here are qdmr's OpenGD77Limits, not the OEM 4000-channel figures, and every profile has to be rebuilt against this entry. There is deliberately NO dmrconf block. qdmr cannot reach this radio: the DM-32UV has no USB of its own, its HR_C7000 platform exposes the CPS protocol only on the UART programming cable, and RadioFoundry places the open-firmware image 7 MB into the data flash, while qdmr's driver neither finds a generic USB-serial cable (it matches VID 0x1FC9 PID 0x0094 only) nor adds that offset, so its writes would land in the stock area where RadioFoundry refuses them. The radiofoundry_cps block above is the write path instead: codeplugger renders the codeplug with dmrconf against the limit-identical openuv380/opengd77 layout, then moves the image over RadioFoundry's own CPS link at offset 0x700000, which is where the open firmware actually reads it. 'dmrconf verify --radio=opengd77' still checks the YAML offline without hardware. RadioFoundry's manual routes remain available and produce the same file: tools/dm32_migrate.py restore --yaml FILE over the programming cable, or the browser Codeplug Editor at radiofoundry.org/codeplug (docs/user/23-radios.md, Programming). Limits: 1024 channels, 68 zones of 80, 1024 contacts, 76 RX group lists of 32, 16-character names, matching RadioFoundry's own description of what the radio reads from the codeplug. max_scan_lists is 0 because RadioFoundry drops qdmr scanLists on import and scans by zone. The UHF ceiling is 470 MHz because qdmr's OpenGD77Limits rejects above it when the YAML is encoded, although the hardware and RadioFoundry both cover 400-480. Modes are FM and DMR only: RadioFoundry's airband AM and broadcast FM receive on this radio have no channel class in the OpenGD77 limits, and its P25/NXDN/Tier III channels travel in a radioFoundry YAML block that qdmr ignores and this exporter does not write. The radio reports open-firmware radio type 6, which means 'the board declared no radio type', not an identity; the CPS backend accepts it rather than treating it as a model mismatch. If a future release gives qdmr a working offset-aware driver, add a dmrconf block then, not before. BENCH-VERIFIED 2026-12-01 on a clear-case DM-32UV running RadioFoundry (git 62db1bae): full write over the CPS link, then a read-back decoded and compared, identical to the encoded image. That write went through a conversion that lost TX contacts: a DM-32UV carrying its 279-channel codeplug was read on 2026-12-02 with no TX contact on any of the 31 DMR channels that have a group list and a TS1 override on all 23 contacts. BENCH-VERIFIED 2026-12-02 with the conversion fixed, on eam_dm32_03 over the programming cable (RadioFoundry git 62db1bae, build 20261130182236): 232 channels, 8 zones, 23 contacts and 5 group lists written, and the read-back decoded and compared with the export shows all 38 TX contacts present and no contact timeslot override. Verification is semantic, not byte-for-byte, because a correct write still differs in padding clusters and the VFO_A scratch area (4,541 bytes on that write, all equal to the pre-write backup). Sources: RadioFoundry docs at commit 62db1bae."
}
diff --git a/radios/baofeng_dm32_radiofoundry/firmware.lock.json b/radios/baofeng_dm32_radiofoundry/firmware.lock.json
new file mode 100644
index 0000000..ece58b6
--- /dev/null
+++ b/radios/baofeng_dm32_radiofoundry/firmware.lock.json
@@ -0,0 +1,11 @@
+{
+ "board": "dm32",
+ "format": "codeplugger-firmware-lock/1",
+ "images": {
+ "62db1bae38969bf5ac72764376b31416ba55a71e": {
+ "sha256": "1b69a27841f6c1d3e926b4b859e024bb7c0fe813b0046def4c012c541fe7cc95",
+ "size": 777592,
+ "toolchain": "csky-elf-gcc (GCC) 14.2.0"
+ }
+ }
+}
diff --git a/radios/retevis_rt3s_radiofoundry/capabilities.json b/radios/retevis_rt3s_radiofoundry/capabilities.json
index 53a85da..ee1c099 100644
--- a/radios/retevis_rt3s_radiofoundry/capabilities.json
+++ b/radios/retevis_rt3s_radiofoundry/capabilities.json
@@ -41,5 +41,8 @@
"dmrconf_radio_key": "openuv380",
"regions": "codeplug"
},
- "notes": "Retevis RT3S (TYT MD-UV380 family, RadioFoundry board mduv380) after installing RadioFoundry, the MIT-licensed multi-mode firmware (radiofoundry.org). As with retevis_rt3s_opengd77 this is a different radio from the OEM one as far as the toolchain is concerned: RadioFoundry keeps the codeplug in the open-firmware layout and answers qdmr's open-firmware CPS protocol through a compatibility shim, so dmrconf can program it under radio key openuv380 and detect reports 'Open MD-UV380' (the radio reports open-firmware radio type 6, qdmr's OpenUV380 model). The dmrconf block above is kept for that, but codeplugger program does not use it: the radiofoundry_cps block takes precedence, so dmrconf only encodes the image and RadioFoundry's own tools/cps_client.py moves it. That block carries no model assertion, because no model string has been read off an RT3S running this firmware and a guess would refuse a good radio; type 6 is also what the firmware sends for a board that declares no type, so it proves nothing by itself. The host port is USB CDC-ACM at VID 0x1FC9 PID 0x0094, the only identity qdmr auto-detects; the radio must be in USB serial mode, not RadioFoundry's USB network mode. Limits are qdmr v0.15.1 OpenGD77Limits, identical to the opengd77 entries and to what RadioFoundry reads from the image: 1024 channels, 68 zones of 80, 1024 contacts, 76 RX group lists of 32, 16-character names, FM and DMR frequency ranges 136-174 and 400-470 MHz (qdmr rejects above 470 on this key; 470 still covers GMRS). max_scan_lists is 0 because RadioFoundry drops qdmr scanLists on import and scans by zone, so codeplugger refuses scan lists loudly instead of letting them vanish. Modes are FM and DMR only: RadioFoundry's P25/NXDN/Tier III channels travel in a radioFoundry YAML block that qdmr ignores and this exporter does not write, and OpenGD77Limits has no AM class. RadioFoundry ships two MD-UV380 images, 5 W (MD-UV380, MD-UV390, RT3S) and 10 W (MD-UV390 Plus); that choice matters for flashing, not for this file. RadioFoundry's own status for this board (2026-11-30) is 'run on radios by community testers' and its manual still calls it bring-up, so expect firmware churn. NOT BENCH-VERIFIED: eam_rt3s_01 runs OpenGD77, not RadioFoundry, and nothing has been written to an RT3S on this firmware through either backend; the site row carries no hw flag. Sources: RadioFoundry docs at commit 62db1bae."
+ "radiofoundry_firmware": {
+ "board": "mduv380"
+ },
+ "notes": "Retevis RT3S (TYT MD-UV380 family, RadioFoundry board mduv380) after installing RadioFoundry, the MIT-licensed multi-mode firmware (radiofoundry.org). As with retevis_rt3s_opengd77 this is a different radio from the OEM one as far as the toolchain is concerned: RadioFoundry keeps the codeplug in the open-firmware layout and answers qdmr's open-firmware CPS protocol through a compatibility shim, so dmrconf can program it under radio key openuv380 and detect reports 'Open MD-UV380' (the radio reports open-firmware radio type 6, qdmr's OpenUV380 model). The dmrconf block above is kept for that, but codeplugger program does not use it: the radiofoundry_cps block takes precedence, so dmrconf only encodes the image and RadioFoundry's own tools/cps_client.py moves it. That block carries no model assertion, because no model string has been read off an RT3S running this firmware and a guess would refuse a good radio; type 6 is also what the firmware sends for a board that declares no type, so it proves nothing by itself. The host port is USB CDC-ACM at VID 0x1FC9 PID 0x0094, the only identity qdmr auto-detects; the radio must be in USB serial mode, not RadioFoundry's USB network mode. Limits are qdmr v0.15.1 OpenGD77Limits, identical to the opengd77 entries and to what RadioFoundry reads from the image: 1024 channels, 68 zones of 80, 1024 contacts, 76 RX group lists of 32, 16-character names, FM and DMR frequency ranges 136-174 and 400-470 MHz (qdmr rejects above 470 on this key; 470 still covers GMRS). max_scan_lists is 0 because RadioFoundry drops qdmr scanLists on import and scans by zone, so codeplugger refuses scan lists loudly instead of letting them vanish. Modes are FM and DMR only: RadioFoundry's P25/NXDN/Tier III channels travel in a radioFoundry YAML block that qdmr ignores and this exporter does not write, and OpenGD77Limits has no AM class. RadioFoundry ships two MD-UV380 images, 5 W (MD-UV380, MD-UV390, RT3S) and 10 W (MD-UV390 Plus); that choice matters for flashing, not for this file. RadioFoundry's own status for this board (2026-11-30) is 'run on radios by community testers' and its manual still calls it bring-up, so expect firmware churn. BENCH-VERIFIED 2026-12-02 on eam_rt3s_01 over the radiofoundry_cps path, on RadioFoundry git 62db1bae installed with 'codeplugger firmware install' (the radio had been running acd7cd69): 232 channels, 8 zones, 23 contacts and 5 group lists written, and the read-back decoded and compared with the export shows all 38 TX contacts present and no contact timeslot override. The radio reported radio type 6 and model MD-UV380 over CPS, which is the undeclared-type fallback and not an identity, so the block still carries no model assertion. Nothing has been written to it through the dmrconf backend, and the site row carries no hw flag yet. Sources: RadioFoundry docs at commit 62db1bae."
}
diff --git a/radios/retevis_rt3s_radiofoundry/firmware.lock.json b/radios/retevis_rt3s_radiofoundry/firmware.lock.json
new file mode 100644
index 0000000..75c61ae
--- /dev/null
+++ b/radios/retevis_rt3s_radiofoundry/firmware.lock.json
@@ -0,0 +1,11 @@
+{
+ "board": "mduv380",
+ "format": "codeplugger-firmware-lock/1",
+ "images": {
+ "62db1bae38969bf5ac72764376b31416ba55a71e": {
+ "sha256": "30a1d79f48f8daace3734e63e10c8acb7065af7f314c9321a09ad93307e38bb1",
+ "size": 706132,
+ "toolchain": "arm-none-eabi-gcc (Arm GNU Toolchain 13.3.Rel1 (Build arm-13.24)) 13.3.1 20240614"
+ }
+ }
+}
diff --git a/schemas/capabilities-0.2.schema.json b/schemas/capabilities-0.2.schema.json
index b262e2c..95f0908 100644
--- a/schemas/capabilities-0.2.schema.json
+++ b/schemas/capabilities-0.2.schema.json
@@ -334,6 +334,21 @@
}
}
},
+ "radiofoundry_firmware": {
+ "type": "object",
+ "description": "Which RadioFoundry firmware image this radio runs, for `codeplugger firmware build` and `codeplugger firmware install`. Kept apart from `radiofoundry_cps.board`, which changes what a codeplug write protects: naming the board here changes nothing about how a codeplug is written. The image each commit builds to is recorded beside this file in `firmware.lock.json`.",
+ "required": [
+ "board"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "board": {
+ "type": "string",
+ "description": "RadioFoundry board ID, the directory under `boards/` in a RadioFoundry checkout, built as `make BOARD=` with the board's default build options. Flashing another board's image is how a radio in this family is bricked, so set it only from RadioFoundry's own board registry.",
+ "pattern": "^[a-z0-9_]+$"
+ }
+ }
+ },
"p64tool": {
"type": "object",
"description": "How the `p64tool` backend addresses this radio. The P4 has no from-scratch encoder: a codeplug is produced by editing a baseline decoded from a device, which is why this block records that requirement rather than a model string.",
diff --git a/src/codeplugger/backends/radiofoundry.py b/src/codeplugger/backends/radiofoundry.py
index 63d3fb0..1cacbc4 100644
--- a/src/codeplugger/backends/radiofoundry.py
+++ b/src/codeplugger/backends/radiofoundry.py
@@ -38,6 +38,8 @@
import time
from typing import Any, Mapping, Sequence
+import yaml
+
from ..artifacts import ArtifactStore
@@ -175,6 +177,127 @@ def git(*args: str) -> str | None:
return CheckoutRevision(commit=head.strip(), dirty=status is None or bool(status.strip()))
+def firmware_verified(reported: str) -> bool:
+ """Whether the commit a radio reports is one a write has been verified on.
+
+ The radio sends the short hash its image was stamped with at build time,
+ so the comparison is by prefix. A build from a modified tree reports
+ `-dirty` and one built outside git reports `unknown`; neither names
+ a commit, so neither can be a verified one.
+ """
+
+ short = reported.strip().lower()
+ if len(short) < 8 or any(char not in "0123456789abcdef" for char in short):
+ return False
+ return any(commit.startswith(short) for commit in VERIFIED_REVISIONS)
+
+
+class _QdmrStyleDumper(yaml.SafeDumper):
+ """Writes list items indented under their key, as qdmr writes its files."""
+
+ def increase_indent(self, flow: bool = False, indentless: bool = False) -> None:
+ return super().increase_indent(flow, False)
+
+
+class _DecodedLoader(yaml.SafeLoader):
+ """Reads what dmrconf decodes, which tags defaulted values (`!default`)."""
+
+
+def _untagged(loader: yaml.Loader, _suffix: str, node: yaml.Node) -> Any:
+ if isinstance(node, yaml.ScalarNode):
+ return loader.construct_scalar(node)
+ if isinstance(node, yaml.SequenceNode):
+ return loader.construct_sequence(node)
+ return loader.construct_mapping(node)
+
+
+_DecodedLoader.add_multi_constructor("!", _untagged)
+
+
+def qdmr_style(export_text: str) -> str:
+ """Re-indent an export the way qdmr writes YAML, for upstream's parser.
+
+ The same document, list items at two spaces and their fields at six
+ instead of at zero and four. `tools/codeplug_port.py` finds channels and
+ contacts by that indentation rather than by parsing YAML, and takes a list
+ whose items start in column zero for an empty one. Given the export as
+ codeplugger writes it, both of its fix-ups therefore did nothing and said
+ nothing: no TX contact was put back, and no contact's timeslot override
+ was cleared. An RT3S programmed that way had 9 of 38 TX contacts and
+ `timeSlotOverride: TS1` on all 23 contacts, behind a clean verify.
+ """
+
+ return yaml.dump(
+ yaml.safe_load(export_text),
+ Dumper=_QdmrStyleDumper,
+ sort_keys=False,
+ allow_unicode=True,
+ )
+
+
+def conversion_losses(export_text: str, encoded_text: str) -> list[str]:
+ """What the encoded image says differently from the export, per channel.
+
+ `encoded_text` is the YAML dmrconf decodes from the image about to be
+ written. The verify steps compare the radio with that image, so anything
+ the encoder dropped on the way there passes them; this is the comparison
+ with what was actually asked for. Two things qdmr's open-firmware encoder
+ is known to do are checked: it writes a channel's TX contact or its group
+ list but not both, and it gives every contact a TS1 override, which the
+ firmware then prefers to the channel's own timeslot.
+ """
+
+ export = yaml.safe_load(export_text) or {}
+ encoded = yaml.load(encoded_text, Loader=_DecodedLoader) or {}
+
+ def bodies(document: Mapping[str, Any], section: str) -> list[tuple[str, dict]]:
+ return [
+ (kind, body)
+ for item in document.get(section) or ()
+ for kind, body in item.items()
+ ]
+
+ def override(body: Mapping[str, Any]) -> str | None:
+ value = (body.get("openGD77") or {}).get("timeSlotOverride")
+ return None if value in (None, "None") else str(value)
+
+ losses: list[str] = []
+ numbers: dict[str, dict[Any, Any]] = {"export": {}, "encoded": {}}
+ wanted, got = bodies(export, "contacts"), bodies(encoded, "contacts")
+ if len(wanted) != len(got):
+ losses.append(f"{len(wanted)} contacts exported, {len(got)} encoded")
+ for (_, sent), (_, made) in zip(wanted, got):
+ numbers["export"][sent.get("id")] = sent.get("number")
+ numbers["encoded"][made.get("id")] = made.get("number")
+ if sent.get("number") != made.get("number"):
+ losses.append(
+ f"contact '{sent.get('name')}' is {made.get('number')}, "
+ f"not {sent.get('number')}"
+ )
+ elif override(sent) != override(made):
+ losses.append(
+ f"contact '{sent.get('name')}' has timeslot override "
+ f"{override(made)}, the export asked for {override(sent)}"
+ )
+
+ wanted, got = bodies(export, "channels"), bodies(encoded, "channels")
+ if len(wanted) != len(got):
+ losses.append(f"{len(wanted)} channels exported, {len(got)} encoded")
+ for (kind, sent), (_, made) in zip(wanted, got):
+ if kind != "dmr" or not sent.get("contact"):
+ continue
+ name = sent.get("name")
+ want = numbers["export"].get(sent["contact"])
+ if not made.get("contact"):
+ losses.append(f"channel '{name}' lost its TX contact ({want})")
+ elif numbers["encoded"].get(made["contact"]) != want:
+ losses.append(
+ f"channel '{name}' has TX contact "
+ f"{numbers['encoded'].get(made['contact'])}, not {want}"
+ )
+ return losses
+
+
def _interpreter(root: Path) -> str:
"""Prefer the checkout's virtualenv, which is where its deps are installed."""
@@ -283,6 +406,8 @@ class RadioFoundryCps:
python: Path | str | None = None
#: Write from a checkout that is not at a hardware-verified revision.
allow_unverified_revision: bool = False
+ #: Write to a radio whose firmware is not a hardware-verified revision.
+ allow_unverified_firmware: bool = False
# -- plumbing ---------------------------------------------------------
@@ -453,6 +578,42 @@ def identify(self, target: RadioFoundryTarget) -> dict[str, str]:
)
return fields
+ def check_firmware(self, fields: Mapping[str, str]) -> str:
+ """Refuse to write to firmware no write has been verified against.
+
+ `check_revision` pins the code on this side of the cable; this pins
+ the code on the other. The codeplug layout, the regions a write may
+ touch and the wire offset are all the firmware's to define, so a
+ codeplug verified against one revision says nothing about another.
+ `fields` is what `info` returned. The commit and build stamp the radio
+ reported go to the operation log either way, so a write's evidence
+ names the firmware it was written to.
+ """
+
+ reported = fields.get("git", "").strip()
+ built = fields.get("build", "").strip()
+ described = (reported or "no commit") + (f", built {built}" if built else "")
+ known = ", ".join(commit[:8] for commit in VERIFIED_REVISIONS)
+ if firmware_verified(reported):
+ self._record("firmware", "success", (), (), f"{described} (verified)")
+ return reported
+ detail = f"{described}; verified: {known}"
+ if not self.allow_unverified_firmware:
+ self._record("firmware", "failure", (), (), detail)
+ raise RadioFoundryError(
+ f"the radio reports firmware {described}, and writes have only "
+ f"been verified against {known}; install a verified revision "
+ "with `codeplugger firmware install` or pass "
+ "--allow-unverified-firmware"
+ )
+ self._record("firmware", "success", (), (), f"{detail} (unverified, allowed)")
+ print(
+ f"warning: writing to unverified radio firmware ({described}; "
+ f"verified: {known})",
+ file=sys.stderr,
+ )
+ return reported
+
def read(
self,
target: RadioFoundryTarget,
@@ -627,12 +788,16 @@ def build_image(
DfuSe targets are flattened into an image whose file offset is the
wire address. Upstream does both halves, including putting back the TX
contacts its encoder drops, so both halves are called rather than
- copied.
+ copied. What comes back is then compared with the export, and an image
+ that says something else is refused rather than returned.
"""
work_dir.mkdir(parents=True, exist_ok=True)
port = self._codeplug_port()
session = _PortSession(work_dir, self.dmrconf)
+ export_text = export_path.read_text(encoding="utf-8")
+ source = work_dir / "export-qdmr-style.yaml"
+ source.write_text(qdmr_style(export_text), encoding="utf-8")
# cleanup=False on purpose. Upstream's clean_group_lists() prunes RX
# group lists it considers redundant, but its text rewrite only
# understands a flow-style "groupLists: []". Against the block
@@ -643,8 +808,23 @@ def build_image(
# The lists are wanted here regardless: the verified DM-1701 write
# carried all five.
dfu_path, yaml_path, report = port.convert_for_rfoundry(
- session, str(export_path), target.dmrconf_radio_key, cleanup=False
+ session, str(source), target.dmrconf_radio_key, cleanup=False
)
+ command = [str(self.dmrconf), "encode", "--radio", target.dmrconf_radio_key]
+ losses = conversion_losses(
+ export_text, Path(yaml_path).read_text(encoding="utf-8")
+ )
+ if losses:
+ shown = "; ".join(losses[:6])
+ if len(losses) > 6:
+ shown += f"; and {len(losses) - 6} more"
+ self._record(
+ "encode", "failure", command, [export_path, Path(yaml_path)], shown
+ )
+ raise RadioFoundryError(
+ f"the encoded codeplug differs from the export in {len(losses)} "
+ f"place(s), so it will not be used: {shown}"
+ )
targets = port.parse_dfuse(Path(dfu_path).read_bytes())
image, _regions = port.dfu_image(targets)
out = work_dir / "rfoundry-codeplug.img"
@@ -657,7 +837,7 @@ def build_image(
self._record(
"encode",
"success",
- [str(self.dmrconf), "encode", "--radio", target.dmrconf_radio_key],
+ command,
[export_path, out],
detail=(
f"contacts={report.get('contacts')} "
@@ -681,7 +861,8 @@ def write(
"""Identify, back up, write, then prove the write by reading it back.
The order is the point. Nothing reaches the radio from a checkout at
- an unverified revision, nothing is written before a backup exists on
+ an unverified revision, nothing is read or written on a radio running
+ unverified firmware, nothing is written before a backup exists on
disk, and the call does not return success until the radio has been
read again and matched against what was sent.
"""
@@ -692,7 +873,7 @@ def write(
raise RadioFoundryError(f"backup path '{backup}' already exists")
self.check_revision()
- self.identify(target)
+ self.check_firmware(self.identify(target))
self.read(target, backup)
work = work_dir or backup.parent / "rfoundry-work"
diff --git a/src/codeplugger/backends/radiofoundry_firmware.py b/src/codeplugger/backends/radiofoundry_firmware.py
new file mode 100644
index 0000000..22f50a2
--- /dev/null
+++ b/src/codeplugger/backends/radiofoundry_firmware.py
@@ -0,0 +1,825 @@
+"""Build and install RadioFoundry firmware at a pinned revision.
+
+:mod:`.radiofoundry` makes the codeplug on a RadioFoundry radio reproducible.
+This module does the same for the firmware underneath it, so that a radio is
+one RadioFoundry commit plus one codeplug, both rebuilt from version control
+rather than inherited from whatever was flashed last.
+
+Three things decide the bytes of a firmware image, and each is pinned:
+
+* The source. A build never runs in the operator's RadioFoundry checkout. It
+ runs in a scratch clone of that checkout at one commit, so uncommitted
+ changes, a stale `build/` directory and a moved HEAD cannot reach the image.
+ Upstream's Makefile then stamps a clean tree with the commit's time, not
+ the clock.
+* The compiler. Upstream pins a toolchain per platform in
+ `platform//platform.toml`. The pin is read from the commit being
+ built, and the build runs in a container, because a host compiler of
+ another version produces a different image from the same source.
+* The result. `radios//firmware.lock.json` records the SHA-256 of the
+ image each commit builds to. A build that does not reproduce it fails, and
+ an install refuses an image that is not the locked one.
+
+Which commits may be flashed is not decided here. It is
+:data:`.radiofoundry.VERIFIED_REVISIONS`, the same list that gates a codeplug
+write, so the firmware on the radio and the tools that talk to it are held to
+one set of hardware-verified revisions.
+
+Flashing stays with upstream's `rfoundry`, run out of the checkout the way
+`cps_client.py` is. It knows each board's bootloader route, keeps or merges
+the AMBE codec, and erases only the sectors it needs; none of that is
+reimplemented. The codec is never part of a build: it comes from the radio or
+from the operator's stock firmware file, so it is outside what this pins.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+from typing import Any, Mapping, Sequence
+
+import tomlkit
+
+from ..artifacts import ArtifactStore
+from .radiofoundry import (
+ READ_ATTEMPTS,
+ VERIFIED_REVISIONS,
+ RadioFoundryCps,
+ RadioFoundryError,
+ RadioFoundryTarget,
+ _interpreter,
+)
+
+LOCK_FORMAT = "codeplugger-firmware-lock/1"
+LOCK_FILE_NAME = "firmware.lock.json"
+MANIFEST_FORMAT = "rfoundry-release/1"
+
+#: Scratch clones and extracted toolchains. Kept out of the profile cache so
+#: clearing one does not cost a 200 MB toolchain copy.
+DEFAULT_FIRMWARE_CACHE = (
+ Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
+ / "codeplugger"
+ / "firmware"
+)
+
+#: Both pinned toolchains are x86_64 Linux binaries, so the container is
+#: always that platform; on Apple silicon it runs emulated.
+CONTAINER_PLATFORM = "linux/amd64"
+
+#: Upstream's Makefile looks for the Arm toolchain under `$HOME/opt`, and its
+#: own container scripts set HOME the same way.
+CONTAINER_HOME = "/tmp"
+
+#: The platform whose pinned image is a complete build environment (Ubuntu
+#: with make, git and Python). The Arm pin is only a toolchain tree with no
+#: shell, copied onto a runner by upstream's CI, so Arm boards build inside
+#: this platform's image with that tree mounted in.
+RUNTIME_PLATFORM = "hrc7000"
+
+#: Prefix of the version label a build is packaged under, as in
+#: `codeplugger-62db1bae`. The label is in the manifest and the file names
+#: only, never in the image, so it does not affect the image's hash. It is
+#: also the one field of rfoundry's flash report a caller controls: rfoundry
+#: sends the manifest's version as `firmware`, which is how an install made
+#: through codeplugger is recognisable to the RadioFoundry project. Setting
+#: `REPORTING=0` in the environment turns that report off.
+VERSION_LABEL = "codeplugger"
+
+_IMAGE_LINE = re.compile(r"^image (\S+): (\d+) bytes, version (\S+)", re.MULTILINE)
+_PLATFORM_LINE = re.compile(r"^PLATFORM\s*:?=\s*(\S+)", re.MULTILINE)
+
+
+def default_revision() -> str:
+ """The commit to build when none is named.
+
+ The last entry of the list, on the understanding that revisions are
+ appended to it as they are verified.
+ """
+
+ return VERIFIED_REVISIONS[-1]
+
+
+@dataclass(frozen=True)
+class FirmwareTarget:
+ """The `radiofoundry_firmware` block of a capabilities file."""
+
+ board: str
+
+ @classmethod
+ def from_capabilities(cls, capabilities: Mapping[str, Any]) -> "FirmwareTarget":
+ try:
+ block = capabilities["radiofoundry_firmware"]
+ except KeyError as exc:
+ raise RadioFoundryError(
+ f"'{capabilities.get('id', '?')}' declares no "
+ "'radiofoundry_firmware' block, so there is no firmware to "
+ "build or install for it"
+ ) from exc
+ return cls(board=str(block["board"]))
+
+
+@dataclass(frozen=True)
+class Toolchain:
+ """What one board's build runs in, as the commit being built pins it."""
+
+ platform: str
+ #: The image the build container is started from.
+ image: str
+ #: A data-only image holding the compiler under `/opt/`, for a
+ #: platform whose pin is not a runnable image.
+ tree_image: str | None = None
+ tree_name: str | None = None
+
+
+@dataclass(frozen=True)
+class FirmwareImage:
+ """One packaged build: the image, its manifest, and what they claim."""
+
+ board: str
+ commit: str
+ path: Path
+ manifest_path: Path
+ sha256: str
+ size: int
+ toolchain: str
+
+ @classmethod
+ def load(cls, path: Path, manifest_path: Path | None = None) -> "FirmwareImage":
+ """Read an image and its manifest, and check each against the other.
+
+ A manifest that does not describe the bytes beside it is refused
+ rather than trusted for the commit it names: the commit is what the
+ verified-revision gate and the lock are keyed on.
+ """
+
+ manifest_path = manifest_path or path.with_suffix(".json")
+ try:
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ data = path.read_bytes()
+ except (OSError, ValueError) as exc:
+ raise RadioFoundryError(f"cannot read firmware image: {exc}") from exc
+ if manifest.get("format") != MANIFEST_FORMAT:
+ raise RadioFoundryError(
+ f"{manifest_path} is not a {MANIFEST_FORMAT} manifest"
+ )
+ digest = hashlib.sha256(data).hexdigest()
+ claimed = manifest.get("image", {})
+ if claimed.get("sha256") != digest or claimed.get("size") != len(data):
+ raise RadioFoundryError(
+ f"{path.name} does not match its manifest: the manifest says "
+ f"{claimed.get('size')} bytes, SHA-256 {claimed.get('sha256')}; "
+ f"the file is {len(data)} bytes, SHA-256 {digest}"
+ )
+ commit = str(manifest.get("git_full", ""))
+ if not re.fullmatch(r"[0-9a-f]{40}", commit):
+ raise RadioFoundryError(f"{manifest_path} names no full commit")
+ return cls(
+ board=str(manifest.get("board", "")),
+ commit=commit,
+ path=path,
+ manifest_path=manifest_path,
+ sha256=digest,
+ size=len(data),
+ toolchain=str(manifest.get("toolchain", "")),
+ )
+
+
+def built_image(directory: Path) -> FirmwareImage:
+ """Load the one packaged image a build left in `directory`."""
+
+ manifests = sorted(directory.glob("rfoundry-*.json")) if directory.is_dir() else []
+ if len(manifests) != 1:
+ raise RadioFoundryError(
+ f"no single built firmware image in {directory}; run "
+ "`codeplugger firmware build` first, or name one with --image"
+ )
+ return FirmwareImage.load(manifests[0].with_suffix(".bin"), manifests[0])
+
+
+# -- the lock -------------------------------------------------------------
+
+
+def lock_path(radio_root: Path, radio_id: str) -> Path:
+ return radio_root / radio_id / LOCK_FILE_NAME
+
+
+def load_lock(path: Path) -> dict[str, Any]:
+ """Read a radio's firmware lock; an absent file is an empty lock."""
+
+ if not path.is_file():
+ return {"format": LOCK_FORMAT, "images": {}}
+ lock = json.loads(path.read_text(encoding="utf-8"))
+ if lock.get("format") != LOCK_FORMAT:
+ raise RadioFoundryError(f"{path} is not a {LOCK_FORMAT} file")
+ lock.setdefault("images", {})
+ return lock
+
+
+def lock_status(lock: Mapping[str, Any], image: FirmwareImage) -> str:
+ """Compare an image with the lock: 'locked', 'unlocked', or raise.
+
+ 'unlocked' means the lock has no entry for the commit, which is what a
+ first build of a new revision looks like. A different image for a commit
+ the lock already holds is never a first build, so it is an error.
+ """
+
+ board = lock.get("board")
+ if board is not None and board != image.board:
+ raise RadioFoundryError(
+ f"the image is for board '{image.board}', but this radio's "
+ f"firmware lock is for '{board}'"
+ )
+ entry = lock.get("images", {}).get(image.commit)
+ if entry is None:
+ return "unlocked"
+ if entry.get("sha256") == image.sha256:
+ return "locked"
+ raise RadioFoundryError(
+ f"{image.board} at {image.commit[:8]} built to SHA-256 {image.sha256} "
+ f"with {image.toolchain or 'an unnamed toolchain'}, but the lock "
+ f"records {entry.get('sha256')} with "
+ f"{entry.get('toolchain') or 'an unnamed toolchain'}; the build is "
+ "not the one that was locked"
+ )
+
+
+def update_lock(path: Path, image: FirmwareImage) -> None:
+ """Record what a commit builds to. Never replaces a different image."""
+
+ lock = load_lock(path)
+ lock_status(lock, image)
+ lock["board"] = image.board
+ lock["images"][image.commit] = {
+ "sha256": image.sha256,
+ "size": image.size,
+ "toolchain": image.toolchain,
+ }
+ path.write_text(
+ json.dumps(lock, indent=2, sort_keys=True) + "\n", encoding="utf-8"
+ )
+
+
+# -- the source tree ------------------------------------------------------
+
+
+def _git(where: Path, *args: str) -> str:
+ try:
+ result = subprocess.run(
+ ["git", "-C", str(where), *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ except OSError as exc:
+ raise RadioFoundryError(f"git is required to build firmware: {exc}") from exc
+ if result.returncode != 0:
+ detail = (result.stderr or result.stdout).strip()
+ raise RadioFoundryError(f"git {' '.join(args)} failed in {where}: {detail}")
+ return result.stdout.strip()
+
+
+def resolve_commit(root: Path, revision: str) -> str:
+ """Turn a revision into the full commit hash the checkout knows it by."""
+
+ try:
+ return _git(root, "rev-parse", "--verify", "--quiet", f"{revision}^{{commit}}")
+ except RadioFoundryError as exc:
+ raise RadioFoundryError(
+ f"the RadioFoundry checkout at {root} has no commit '{revision}'; "
+ "fetch it there first"
+ ) from exc
+
+
+def prepare_tree(root: Path, commit: str, tree: Path) -> Path:
+ """Clone `root` at `commit` into `tree`, submodules included.
+
+ The clone is what makes the build independent of the checkout's state.
+ Submodules are cloned from the checkout's own copies instead of the
+ network; git still checks out the commit the superproject pins, so a
+ checkout whose submodules have moved cannot substitute other sources.
+ """
+
+ if tree.exists():
+ shutil.rmtree(tree)
+ tree.parent.mkdir(parents=True, exist_ok=True)
+ _git(root, "clone", "--quiet", "--no-checkout", str(root), str(tree))
+ _git(tree, "checkout", "--quiet", "--detach", commit)
+
+ if (tree / ".gitmodules").is_file():
+ listing = _git(
+ tree,
+ "config",
+ "--file",
+ ".gitmodules",
+ "--get-regexp",
+ r"^submodule\..*\.path$",
+ )
+ for line in listing.splitlines():
+ key, _, path = line.partition(" ")
+ name = key[len("submodule.") : -len(".path")]
+ source = root / path
+ if not (source / ".git").exists():
+ raise RadioFoundryError(
+ f"the RadioFoundry checkout has not fetched its '{path}' "
+ f"submodule; run `git -C {root} submodule update --init`"
+ )
+ _git(tree, "config", f"submodule.{name}.url", str(source))
+ _git(
+ tree,
+ "-c",
+ "protocol.file.allow=always",
+ "submodule",
+ "--quiet",
+ "update",
+ "--init",
+ )
+ return tree
+
+
+def _toolchain_table(tree: Path, platform: str) -> Mapping[str, Any]:
+ path = tree / "platform" / platform / "platform.toml"
+ try:
+ table = tomlkit.parse(path.read_text(encoding="utf-8")).get("toolchain")
+ except (OSError, ValueError) as exc:
+ raise RadioFoundryError(f"cannot read {path}: {exc}") from exc
+ if not table or not table.get("image"):
+ raise RadioFoundryError(f"{path} pins no toolchain image")
+ return table
+
+
+def toolchain_for(tree: Path, board: str) -> Toolchain:
+ """Read the toolchain a board builds with from the tree being built."""
+
+ board_mk = tree / "boards" / board / "board.mk"
+ if not board_mk.is_file():
+ raise RadioFoundryError(
+ f"RadioFoundry has no board '{board}' at this commit "
+ f"(no boards/{board}/board.mk)"
+ )
+ match = _PLATFORM_LINE.search(board_mk.read_text(encoding="utf-8"))
+ if match is None:
+ raise RadioFoundryError(f"{board_mk} names no PLATFORM")
+ platform = match.group(1)
+ pin = _toolchain_table(tree, platform)
+
+ if platform == RUNTIME_PLATFORM:
+ return Toolchain(platform=platform, image=str(pin["image"]))
+ if str(pin.get("id")) == "arm":
+ runtime = _toolchain_table(tree, RUNTIME_PLATFORM)
+ return Toolchain(
+ platform=platform,
+ image=str(runtime["image"]),
+ tree_image=str(pin["image"]),
+ tree_name=f"arm-gnu-toolchain-{pin['version']}-x86_64-arm-none-eabi",
+ )
+ raise RadioFoundryError(
+ f"no container build is known for platform '{platform}' "
+ f"(toolchain '{pin.get('id')}')"
+ )
+
+
+# -- building -------------------------------------------------------------
+
+
+@dataclass
+class FirmwareBuilder:
+ """Build one board's image at one commit, in the pinned container."""
+
+ root: Path
+ artifact_store: ArtifactStore | None = None
+ cache_root: Path = DEFAULT_FIRMWARE_CACHE
+ docker: str = "docker"
+ jobs: int = field(default_factory=lambda: os.cpu_count() or 4)
+ #: Start the build container from this image instead of the pinned one.
+ build_image: str | None = None
+
+ def _docker(self, *args: str) -> subprocess.CompletedProcess[str]:
+ try:
+ return subprocess.run(
+ [self.docker, *args], check=False, capture_output=True, text=True
+ )
+ except OSError as exc:
+ raise RadioFoundryError(
+ f"could not run '{self.docker}': {exc}; a firmware build runs "
+ "in a container so the compiler is the pinned one"
+ ) from exc
+
+ def _checked(self, *args: str) -> str:
+ result = self._docker(*args)
+ if result.returncode != 0:
+ detail = (result.stderr or result.stdout).strip()
+ raise RadioFoundryError(
+ f"{self.docker} {' '.join(args[:2])} failed: {detail}"
+ )
+ return result.stdout.strip()
+
+ def _record(
+ self,
+ outcome: str,
+ command: Sequence[str],
+ artifacts: Sequence[Path],
+ detail: str,
+ ) -> None:
+ if self.artifact_store is not None:
+ self.artifact_store.record(
+ "firmware-build",
+ outcome,
+ command=list(command),
+ artifacts=list(artifacts),
+ detail=detail,
+ )
+
+ def ensure_image(self, image: str) -> str:
+ """Pull an image if it is not here, and return the id that will run."""
+
+ if self._docker("image", "inspect", image).returncode != 0:
+ self._checked("pull", "--quiet", "--platform", CONTAINER_PLATFORM, image)
+ return self._checked("image", "inspect", "--format", "{{.Id}}", image)
+
+ def ensure_toolchain_tree(self, toolchain: Toolchain) -> Path | None:
+ """Copy a data-only toolchain image's tree into the cache, once."""
+
+ if toolchain.tree_image is None or toolchain.tree_name is None:
+ return None
+ # Keyed on the image reference as well as the name: a re-pinned digest
+ # for the same compiler version must not reuse the earlier copy.
+ key = hashlib.sha256(toolchain.tree_image.encode()).hexdigest()[:12]
+ home = self.cache_root / "toolchains" / f"{toolchain.tree_name}-{key}"
+ tree = home / toolchain.tree_name
+ if (tree / "bin").is_dir():
+ return tree
+ self.ensure_image(toolchain.tree_image)
+ if home.exists():
+ shutil.rmtree(home)
+ home.mkdir(parents=True)
+ # The image has no shell and is never started; the command only has
+ # to exist for `create` to accept it.
+ container = self._checked(
+ "create", "--platform", CONTAINER_PLATFORM, toolchain.tree_image, "/none"
+ )
+ try:
+ self._checked(
+ "cp", "--quiet", f"{container}:/opt/{toolchain.tree_name}", str(home)
+ )
+ finally:
+ self._docker("rm", container)
+ return tree
+
+ def _container(
+ self, toolchain: Toolchain, tree: Path, toolchain_tree: Path | None
+ ) -> list[str]:
+ command = [self.docker, "run", "--rm", "--platform", CONTAINER_PLATFORM]
+ if hasattr(os, "getuid"):
+ command += ["--user", f"{os.getuid()}:{os.getgid()}"]
+ command += ["-v", f"{tree}:{tree}", "-w", str(tree)]
+ if toolchain_tree is not None:
+ command += [
+ "-v",
+ f"{toolchain_tree}:{CONTAINER_HOME}/opt/{toolchain.tree_name}:ro",
+ ]
+ # safe.directory: git inside the container may run as another user
+ # than the tree's owner, and the Makefile reads the version from git.
+ command += [
+ "-e",
+ f"HOME={CONTAINER_HOME}",
+ "-e",
+ "GIT_CONFIG_COUNT=1",
+ "-e",
+ "GIT_CONFIG_KEY_0=safe.directory",
+ "-e",
+ "GIT_CONFIG_VALUE_0=*",
+ self.build_image or toolchain.image,
+ ]
+ return command
+
+ def build(self, board: str, revision: str, out_dir: Path) -> FirmwareImage:
+ """Clone, compile, package and check one image. Returns what was built."""
+
+ commit = resolve_commit(self.root, revision)
+ short = commit[:8]
+ scratch = self.cache_root / "build" / short
+ print(f"cloning RadioFoundry at {short} into {scratch}", file=sys.stderr)
+ tree = prepare_tree(self.root, commit, scratch)
+
+ toolchain = toolchain_for(tree, board)
+ image_id = self.ensure_image(self.build_image or toolchain.image)
+ toolchain_tree = self.ensure_toolchain_tree(toolchain)
+ container = self._container(toolchain, tree, toolchain_tree)
+ make = [*container, "make", f"BOARD={board}"]
+ log: list[str] = []
+
+ def run(command: Sequence[str]) -> subprocess.CompletedProcess[str]:
+ result = subprocess.run(
+ list(command),
+ check=False,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ log.append(f"$ {' '.join(command)}\n{result.stdout}")
+ return result
+
+ def fail(command: Sequence[str], what: str, output: str) -> RadioFoundryError:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ log_path = out_dir / "build.log"
+ log_path.write_text("\n".join(log), encoding="utf-8")
+ tail = "\n".join(output.strip().splitlines()[-8:])
+ self._record("failure", command, (log_path,), f"{board} {short}: {what}")
+ return RadioFoundryError(f"{what} (full log: {log_path})\n{tail}")
+
+ print(
+ f"building {board} in {self.build_image or toolchain.image}",
+ file=sys.stderr,
+ )
+ command = [*make, f"-j{self.jobs}"]
+ result = run(command)
+ if result.returncode != 0:
+ # A parallel build can die at the link under emulation: the LTO
+ # step mistakes inherited descriptors for make's jobserver and
+ # GCC aborts in return_token. Run serially, make has no jobserver
+ # to confuse it, and only what is still missing is rebuilt. A
+ # real compile error fails this second run too.
+ command = make
+ result = run(command)
+ if result.returncode != 0:
+ raise fail(command, f"make BOARD={board} failed", result.stdout)
+
+ built = _IMAGE_LINE.search(result.stdout)
+ stamp = built.group(3) if built else ""
+ # The Makefile stamps at least eight hex digits, more if git needs
+ # them to be unambiguous, and appends -dirty for a modified tree.
+ if len(stamp) < 8 or not commit.startswith(stamp):
+ raise fail(
+ command,
+ f"the image is stamped '{stamp or 'no version'}', not the "
+ f"clean commit '{short}', so it is not a reproducible build of it",
+ result.stdout,
+ )
+
+ dist = tree / "build" / "dist"
+ package = [
+ *container,
+ "python3",
+ "tools/release.py",
+ "--board",
+ board,
+ "--version",
+ f"{VERSION_LABEL}-{short}",
+ "--out",
+ str(dist),
+ ]
+ packaged = run(package)
+ if packaged.returncode != 0:
+ raise fail(package, "packaging with tools/release.py failed", packaged.stdout)
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ # An earlier build of this commit must not sit beside the new one.
+ for stale in out_dir.glob("rfoundry-*"):
+ stale.unlink()
+ for produced in sorted(dist.iterdir()):
+ shutil.copy2(produced, out_dir / produced.name)
+ log_path = out_dir / "build.log"
+ log_path.write_text("\n".join(log), encoding="utf-8")
+
+ image = built_image(out_dir)
+ if image.commit != commit or image.board != board:
+ raise fail(
+ package,
+ f"the manifest describes {image.board} at {image.commit[:8]}, "
+ f"not {board} at {short}",
+ packaged.stdout,
+ )
+ self._record(
+ "success",
+ command,
+ (image.path, image.manifest_path, log_path),
+ f"{board} {short}: {image.size} bytes, SHA-256 {image.sha256}, "
+ f"{image.toolchain}, container {image_id}"
+ + (f", toolchain from {toolchain.tree_image}" if toolchain.tree_image else ""),
+ )
+ return image
+
+
+# -- installing -----------------------------------------------------------
+
+
+def firmware_image_verified(
+ image: FirmwareImage, lock: Mapping[str, Any]
+) -> tuple[bool, str]:
+ """Whether an image may be flashed without an opt-in, and why not.
+
+ Two conditions, both needed: the commit is one a write has been verified
+ against, and the bytes are the ones the lock records for that commit. A
+ verified commit built by an unpinned compiler is a different image.
+ """
+
+ if image.commit not in VERIFIED_REVISIONS:
+ known = ", ".join(commit[:8] for commit in VERIFIED_REVISIONS)
+ return False, f"commit {image.commit[:8]} is not a verified revision ({known})"
+ try:
+ status = lock_status(lock, image)
+ except RadioFoundryError as exc:
+ return False, str(exc)
+ if status != "locked":
+ return False, f"the firmware lock has no image for commit {image.commit[:8]}"
+ return True, f"commit {image.commit[:8]}, SHA-256 {image.sha256} (locked)"
+
+
+@dataclass
+class FirmwareInstaller:
+ """Flash a built image through upstream's `rfoundry`, then confirm it."""
+
+ root: Path
+ artifact_store: ArtifactStore | None = None
+ port: str | None = None
+ python: Path | str | None = None
+ #: Flash with `rfoundry` from a checkout that is not at a verified revision.
+ allow_unverified_revision: bool = False
+ #: Flash an image that is not the locked build of a verified commit.
+ allow_unverified_firmware: bool = False
+
+ def _record(
+ self,
+ operation: str,
+ outcome: str,
+ command: Sequence[str],
+ artifacts: Sequence[Path],
+ detail: str,
+ ) -> None:
+ if self.artifact_store is not None:
+ self.artifact_store.record(
+ operation,
+ outcome,
+ command=list(command),
+ artifacts=list(artifacts),
+ detail=detail,
+ )
+
+ def _cps(self) -> RadioFoundryCps:
+ return RadioFoundryCps(
+ root=self.root,
+ artifact_store=self.artifact_store,
+ port=self.port,
+ python=self.python,
+ allow_unverified_revision=self.allow_unverified_revision,
+ )
+
+ def _flash_command(
+ self,
+ image: FirmwareImage,
+ *,
+ stock: Path | None,
+ codec: str | None,
+ dry_run: bool,
+ ) -> list[str]:
+ command = [
+ str(self.python or _interpreter(self.root)),
+ "-m",
+ "rfoundry",
+ "flash",
+ str(image.path.resolve()),
+ "--manifest",
+ str(image.manifest_path.resolve()),
+ "--board",
+ image.board,
+ ]
+ if self.port:
+ command += ["--port", self.port]
+ if stock is not None:
+ command += ["--stock", str(stock.resolve())]
+ if codec:
+ command += ["--codec", codec]
+ if dry_run:
+ command.append("--dry-run")
+ return command
+
+ def _rfoundry(self, command: Sequence[str]) -> int:
+ """Run rfoundry attached to the terminal: it prompts, and it must.
+
+ Entering the bootloader is done by hand at the radio, so rfoundry asks
+ the operator to do it and waits. Capturing its output would hide the
+ prompt that the whole step depends on.
+ """
+
+ module_home = self.root / "tools" / "rfoundry"
+ if not (module_home / "rfoundry" / "__main__.py").is_file():
+ raise RadioFoundryError(
+ f"the RadioFoundry checkout at {self.root} has no tools/rfoundry"
+ )
+ try:
+ # rfoundry writes straight to the terminal; anything printed
+ # before it must already be there, or the plan reads out of order.
+ sys.stdout.flush()
+ return subprocess.run(list(command), check=False, cwd=module_home).returncode
+ except OSError as exc:
+ raise RadioFoundryError(f"could not run rfoundry: {exc}") from exc
+
+ def install(
+ self,
+ image: FirmwareImage,
+ *,
+ target: RadioFoundryTarget,
+ firmware: FirmwareTarget,
+ lock: Mapping[str, Any],
+ stock: Path | None = None,
+ codec: str | None = None,
+ confirm: bool = False,
+ ) -> bool:
+ """Gate, show the plan, flash, then read the radio's commit back.
+
+ Returns False when only the plan was shown. The order matters the same
+ way it does for a codeplug write: nothing reaches the radio from an
+ unverified image or checkout, the plan is printed before anything is
+ erased, and success is the radio reporting the commit that was sent,
+ not rfoundry exiting cleanly.
+ """
+
+ if image.board != firmware.board:
+ raise RadioFoundryError(
+ f"the image is for board '{image.board}', but this radio "
+ f"takes '{firmware.board}'; refusing to flash it"
+ )
+ verified, detail = firmware_image_verified(image, lock)
+ artifacts = (image.path, image.manifest_path)
+ if not verified and not self.allow_unverified_firmware:
+ self._record("firmware-image", "failure", (), artifacts, detail)
+ raise RadioFoundryError(
+ f"refusing to flash {image.path.name}: {detail}; build it with "
+ "`codeplugger firmware build`, or pass --allow-unverified-firmware"
+ )
+ if not verified:
+ print(f"warning: flashing unverified firmware ({detail})", file=sys.stderr)
+ self._record(
+ "firmware-image",
+ "success",
+ (),
+ artifacts,
+ detail if verified else f"{detail} (unverified, allowed)",
+ )
+ self._cps().check_revision()
+
+ plan = self._flash_command(image, stock=stock, codec=codec, dry_run=True)
+ if self._rfoundry(plan) != 0:
+ self._record("firmware-plan", "failure", plan, artifacts, "rfoundry refused the plan")
+ raise RadioFoundryError("rfoundry could not plan this install; nothing was written")
+ self._record("firmware-plan", "success", plan, artifacts, "dry run")
+ if not confirm:
+ return False
+
+ flash = self._flash_command(image, stock=stock, codec=codec, dry_run=False)
+ if self._rfoundry(flash) != 0:
+ self._record("firmware-install", "failure", flash, artifacts, "rfoundry flash failed")
+ raise RadioFoundryError(
+ "rfoundry flash did not complete; run it again to finish an "
+ "install that stopped part-way"
+ )
+
+ # rfoundry has already waited for the restart, but the CPS link is not
+ # always awake when the debug link is, so this read gets the same
+ # patience as a read-back after a codeplug write.
+ try:
+ reported = (
+ self._cps().info(target, attempts=READ_ATTEMPTS).get("git", "").strip()
+ )
+ except RadioFoundryError as exc:
+ self._record(
+ "firmware-install",
+ "failure",
+ flash,
+ artifacts,
+ f"sent {image.commit[:8]}, radio did not answer afterwards",
+ )
+ raise RadioFoundryError(
+ f"rfoundry finished flashing {image.commit[:8]}, but the radio "
+ "did not answer the identity read afterwards, so the install "
+ "is not confirmed. Power-cycle the radio and run this command "
+ "again without --confirm: rfoundry's first lines show the "
+ f"commit the radio is running. ({str(exc).strip().splitlines()[-1]})"
+ ) from exc
+ if not reported or not image.commit.startswith(reported.lower()):
+ self._record(
+ "firmware-install",
+ "failure",
+ flash,
+ artifacts,
+ f"sent {image.commit[:8]}, radio reports '{reported}'",
+ )
+ raise RadioFoundryError(
+ f"flashed {image.commit[:8]}, but the radio reports firmware "
+ f"'{reported or 'nothing'}'; the install is not confirmed"
+ )
+ self._record(
+ "firmware-install",
+ "success",
+ flash,
+ artifacts,
+ f"radio reports {reported}, SHA-256 {image.sha256}",
+ )
+ return True
diff --git a/src/codeplugger/cli.py b/src/codeplugger/cli.py
index 797a77e..c90db42 100644
--- a/src/codeplugger/cli.py
+++ b/src/codeplugger/cli.py
@@ -540,6 +540,9 @@ def _program(build: Build, args: argparse.Namespace) -> None:
allow_unverified_revision=bool(
getattr(args, "allow_unverified_rfoundry", False)
),
+ allow_unverified_firmware=bool(
+ getattr(args, "allow_unverified_firmware", False)
+ ),
).write(
build.export_path,
target=target,
@@ -610,6 +613,139 @@ def _command_import(args: argparse.Namespace) -> int:
return 0
+# -- firmware -------------------------------------------------------------
+
+
+def _firmware_radio(args: argparse.Namespace) -> tuple[Radio, Any, Path, ArtifactStore]:
+ """The radio, its firmware block, the RadioFoundry checkout and the log."""
+
+ from .backends.radiofoundry import radiofoundry_root
+ from .backends.radiofoundry_firmware import FirmwareTarget
+
+ radio = find_radio(args.radio, args.radio_root)
+ firmware = FirmwareTarget.from_capabilities(radio.capabilities)
+ root = radiofoundry_root(args.rfoundry_root)
+ return radio, firmware, root, ArtifactStore(args.artifact_root, radio.id, "firmware")
+
+
+def _command_firmware_build(args: argparse.Namespace) -> int:
+ from .backends.radiofoundry import VERIFIED_REVISIONS, RadioFoundryError
+ from .backends.radiofoundry_firmware import (
+ FirmwareBuilder,
+ default_revision,
+ load_lock,
+ lock_path,
+ lock_status,
+ resolve_commit,
+ update_lock,
+ )
+
+ try:
+ radio, firmware, root, store = _firmware_radio(args)
+ commit = resolve_commit(root, args.commit or default_revision())
+ builder = FirmwareBuilder(
+ root=root,
+ artifact_store=store,
+ cache_root=args.cache_root,
+ docker=args.docker,
+ build_image=args.build_image,
+ )
+ if args.jobs:
+ builder.jobs = args.jobs
+ image = builder.build(firmware.board, commit, store.directory / commit[:8])
+
+ lock_file = lock_path(args.radio_root, radio.id)
+ try:
+ status = lock_status(load_lock(lock_file), image)
+ except RadioFoundryError as exc:
+ store.record("firmware-lock", "failure", artifacts=(image.path,), detail=str(exc))
+ raise
+ if status == "unlocked" and args.update_lock:
+ update_lock(lock_file, image)
+ status = "recorded"
+ store.record(
+ "firmware-lock",
+ "success",
+ artifacts=(image.path,),
+ detail=f"{image.commit[:8]} {image.sha256}: {status}",
+ )
+ except RadioFoundryError as exc:
+ raise CommandError(str(exc)) from exc
+
+ print(f"{radio.name}: firmware for board {image.board} at {image.commit[:8]}")
+ print(f" image: {image.path}")
+ print(f" sha256: {image.sha256}")
+ print(f" toolchain: {image.toolchain}")
+ print(
+ " lock: "
+ + {
+ "locked": f"matches {lock_file}",
+ "recorded": f"recorded in {lock_file}",
+ "unlocked": (
+ f"{lock_file} has no image for this commit; re-run with "
+ "--update-lock to record this one"
+ ),
+ }[status]
+ )
+ if image.commit not in VERIFIED_REVISIONS:
+ print(
+ f" note: {image.commit[:8]} is not a hardware-verified "
+ "revision, so installing it needs --allow-unverified-firmware"
+ )
+ return 0
+
+
+def _command_firmware_install(args: argparse.Namespace) -> int:
+ from .backends.radiofoundry import RadioFoundryError, RadioFoundryTarget
+ from .backends.radiofoundry_firmware import (
+ FirmwareImage,
+ FirmwareInstaller,
+ built_image,
+ default_revision,
+ load_lock,
+ lock_path,
+ )
+
+ try:
+ radio, firmware, root, store = _firmware_radio(args)
+ target = RadioFoundryTarget.from_capabilities(radio.capabilities)
+ image = (
+ FirmwareImage.load(args.image)
+ if args.image is not None
+ else built_image(store.directory / default_revision()[:8])
+ )
+ print(
+ f"{radio.name}: {image.path.name} "
+ f"(commit {image.commit[:8]}, SHA-256 {image.sha256})\n"
+ )
+ installed = FirmwareInstaller(
+ root=root,
+ artifact_store=store,
+ port=str(args.port) if args.port else None,
+ allow_unverified_revision=args.allow_unverified_rfoundry,
+ allow_unverified_firmware=args.allow_unverified_firmware,
+ ).install(
+ image,
+ target=target,
+ firmware=firmware,
+ lock=load_lock(lock_path(args.radio_root, radio.id)),
+ stock=args.stock,
+ codec=args.codec,
+ confirm=args.confirm,
+ )
+ except RadioFoundryError as exc:
+ raise CommandError(str(exc)) from exc
+
+ if not installed:
+ print(
+ f"\nNothing was written. Re-run with --confirm to flash "
+ f"{radio.name} with RadioFoundry {image.commit[:8]}."
+ )
+ return 0
+ print(f"\nDone. {radio.name} reports RadioFoundry {image.commit[:8]}.")
+ return 0
+
+
# -- argument parsing -----------------------------------------------------
@@ -726,6 +862,140 @@ def _check_build_arguments(
parser.error(f"{' and '.join(missing)} required (or use --profile)")
+def _add_firmware_commands(subparsers: Any) -> None:
+ from .backends.radiofoundry_firmware import DEFAULT_FIRMWARE_CACHE
+
+ firmware = subparsers.add_parser(
+ "firmware",
+ help="build and install RadioFoundry firmware at a pinned revision",
+ description=(
+ "Build a RadioFoundry radio's firmware from one commit in the "
+ "pinned toolchain container, check the image against the radio's "
+ "firmware lock, and flash it. `program` then refuses a radio whose "
+ "firmware is not a verified revision."
+ ),
+ )
+ commands = firmware.add_subparsers(dest="firmware_command", required=True)
+
+ def common(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--radio",
+ required=True,
+ help="radio ID; it must declare a radiofoundry_firmware block",
+ )
+ parser.add_argument(
+ "--rfoundry-root",
+ default=None,
+ help=(
+ "RadioFoundry checkout to build from and take the flasher from "
+ "(default: $RFOUNDRY_ROOT, then a sibling RadioFoundry directory)"
+ ),
+ )
+ parser.add_argument("--radio-root", type=Path, default=DEFAULT_RADIO_ROOT)
+ parser.add_argument(
+ "--artifact-root",
+ type=Path,
+ default=Path("."),
+ help="write .artifacts//firmware below this directory (default: .)",
+ )
+
+ build = commands.add_parser(
+ "build",
+ help="build the firmware image for a radio; touches no radio",
+ )
+ common(build)
+ build.add_argument(
+ "--commit",
+ default=None,
+ help="RadioFoundry commit to build (default: the newest verified revision)",
+ )
+ build.add_argument(
+ "--update-lock",
+ action="store_true",
+ help=(
+ "record the image in the radio's firmware.lock.json when the lock "
+ "has none for this commit; an image that differs from a locked "
+ "one is always an error"
+ ),
+ )
+ build.add_argument(
+ "--cache-root",
+ type=Path,
+ default=DEFAULT_FIRMWARE_CACHE,
+ help=f"scratch clones and toolchains (default: {DEFAULT_FIRMWARE_CACHE})",
+ )
+ build.add_argument("--docker", default="docker", help="container engine command")
+ build.add_argument(
+ "--build-image",
+ default=None,
+ help=(
+ "container image to build in, instead of the one the commit pins; "
+ "the image then only matches the lock if the compiler is the same"
+ ),
+ )
+ build.add_argument("--jobs", type=int, default=None, help="parallel compile jobs")
+ build.set_defaults(handler=_command_firmware_build)
+
+ install = commands.add_parser(
+ "install",
+ help="flash a built image with RadioFoundry's rfoundry tool",
+ description=(
+ "Show rfoundry's plan for flashing a built image, and with "
+ "--confirm flash it and read the radio's firmware commit back. "
+ "rfoundry asks for the bootloader keys at the radio, so run this "
+ "in a terminal."
+ ),
+ )
+ common(install)
+ install.add_argument(
+ "--image",
+ type=Path,
+ default=None,
+ help=(
+ "image to flash, with its .json manifest beside it (default: the "
+ "build of the newest verified revision under --artifact-root)"
+ ),
+ )
+ install.add_argument("--port", default=None, help="serial port of the radio or cable")
+ install.add_argument(
+ "--stock",
+ type=Path,
+ default=None,
+ help=(
+ "the radio's stock firmware file, when rfoundry needs it for the "
+ "AMBE codec or the bootloader key"
+ ),
+ )
+ install.add_argument(
+ "--codec",
+ choices=("auto", "keep", "merge"),
+ default=None,
+ help="passed to rfoundry: keep the radio's codec or write it from --stock",
+ )
+ install.add_argument(
+ "--confirm",
+ action="store_true",
+ help="actually flash; without it only the plan is shown",
+ )
+ install.add_argument(
+ "--allow-unverified-rfoundry",
+ action="store_true",
+ help=(
+ "flash with rfoundry from a RadioFoundry checkout that is not at "
+ "a hardware-verified revision"
+ ),
+ )
+ install.add_argument(
+ "--allow-unverified-firmware",
+ action="store_true",
+ help=(
+ "flash an image that is not the locked build of a "
+ "hardware-verified revision"
+ ),
+ )
+ install.set_defaults(handler=_command_firmware_install)
+
+
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="codeplugger",
@@ -809,6 +1079,14 @@ def main(argv: Sequence[str] | None = None) -> int:
"write has been hardware-verified against"
),
)
+ tools.add_argument(
+ "--allow-unverified-firmware",
+ action="store_true",
+ help=(
+ "write to a RadioFoundry radio whose firmware is not a revision a "
+ "write has been hardware-verified against"
+ ),
+ )
program.set_defaults(handler=_command_program)
importer = subparsers.add_parser(
@@ -854,6 +1132,8 @@ def main(argv: Sequence[str] | None = None) -> int:
importer.add_argument("--radio-root", type=Path, default=DEFAULT_RADIO_ROOT)
importer.set_defaults(handler=_command_import)
+ _add_firmware_commands(subparsers)
+
args = parser.parse_args(argv)
if args.command in {"build", "program"}:
_check_build_arguments(parser, args)
diff --git a/tests/test_radiofoundry_backend.py b/tests/test_radiofoundry_backend.py
index 9d3f0f3..8a7ecd2 100644
--- a/tests/test_radiofoundry_backend.py
+++ b/tests/test_radiofoundry_backend.py
@@ -7,6 +7,7 @@
from types import SimpleNamespace
import pytest
+import yaml
from codeplugger.artifacts import ArtifactStore
from codeplugger.backends.radiofoundry import (
@@ -16,6 +17,9 @@
RadioFoundryError,
RadioFoundryTarget,
checkout_revision,
+ conversion_losses,
+ firmware_verified,
+ qdmr_style,
radiofoundry_root,
)
@@ -428,6 +432,77 @@ def test_the_operation_log_names_the_revision_a_write_ran_at(
assert "ffffffff" in allowed["detail"] and "unverified" in allowed["detail"]
+# -- radio firmware -------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ ("reported", "verified"),
+ [
+ (VERIFIED_REVISIONS[0][:8], True),
+ (VERIFIED_REVISIONS[0], True),
+ # A build from a modified tree is not the commit it was started from.
+ (VERIFIED_REVISIONS[0][:8] + "-dirty", False),
+ # Too short to name one commit rather than a family of them.
+ (VERIFIED_REVISIONS[0][:4], False),
+ ("unknown", False),
+ ("", False),
+ ],
+)
+def test_only_a_clean_verified_commit_counts_as_verified_firmware(
+ reported: str, verified: bool
+) -> None:
+ assert firmware_verified(reported) is verified
+
+
+def test_write_stops_at_unverified_radio_firmware_before_the_backup(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The backup is a read of regions the firmware defines, so it waits too."""
+
+ calls: list[list[str]] = []
+ monkeypatch.setattr(
+ "codeplugger.backends.radiofoundry.subprocess.run",
+ _fake_run(calls, {"info": INFO + "git=deadbeef\nbuild=20261201120000\n"}),
+ )
+ _at(monkeypatch, CheckoutRevision(commit=VERIFIED_REVISIONS[0]))
+ store = ArtifactStore(tmp_path, "baofeng_dm1701_radiofoundry", "bench")
+
+ with pytest.raises(RadioFoundryError, match="deadbeef.*--allow-unverified-firmware"):
+ RadioFoundryCps(root=_checkout(tmp_path), artifact_store=store).write(
+ Path("codeplug.yaml"),
+ target=_target(),
+ backup=tmp_path / "b.bin",
+ read_back=tmp_path / "r.bin",
+ confirm=True,
+ )
+
+ assert calls and all(command[-1] == "info" for command in calls)
+ record = json.loads(store.log_path.read_text().splitlines()[-1])
+ assert (record["operation"], record["status"]) == ("firmware", "failure")
+ assert "deadbeef, built 20261201120000" in record["detail"]
+
+
+def test_the_operation_log_names_the_firmware_a_write_went_to(tmp_path: Path) -> None:
+ store = ArtifactStore(tmp_path, "baofeng_dm1701_radiofoundry", "bench")
+ root = _checkout(tmp_path)
+ short = VERIFIED_REVISIONS[0][:8]
+
+ RadioFoundryCps(root=root, artifact_store=store).check_firmware(
+ {"git": short, "build": "20261130184236"}
+ )
+ RadioFoundryCps(
+ root=root, artifact_store=store, allow_unverified_firmware=True
+ ).check_firmware({"git": "deadbeef"})
+
+ verified, allowed = (
+ json.loads(line) for line in store.log_path.read_text().splitlines()
+ )
+ assert verified["status"] == "success"
+ assert verified["detail"] == f"{short}, built 20261130184236 (verified)"
+ assert allowed["status"] == "success"
+ assert "deadbeef" in allowed["detail"] and "unverified" in allowed["detail"]
+
+
# -- checkout discovery ---------------------------------------------------
@@ -488,6 +563,8 @@ def test_conversion_disables_upstream_group_list_cleanup(tmp_path: Path) -> None
root = _checkout(tmp_path)
cps = RadioFoundryCps(root=root)
seen: dict = {}
+ export = tmp_path / "codeplug.yaml"
+ export.write_text(EXPORT)
class FakePort:
@staticmethod
@@ -495,7 +572,9 @@ def convert_for_rfoundry(sess, src, driver, cleanup=True):
seen["cleanup"] = cleanup
dfu = tmp_path / "out.dfu"
dfu.write_bytes(b"\x00")
- return str(dfu), str(tmp_path / "out.yaml"), {"contacts": (9, 9)}
+ encoded = tmp_path / "out.yaml"
+ encoded.write_text(ENCODED)
+ return str(dfu), str(encoded), {"contacts": (9, 9)}
@staticmethod
def parse_dfuse(_data):
@@ -507,11 +586,113 @@ def dfu_image(_targets):
# The wrapper is a frozen dataclass, so shadow the method past __setattr__.
object.__setattr__(cps, "_codeplug_port", lambda: FakePort())
- cps.build_image(tmp_path / "codeplug.yaml", _target(), tmp_path / "work")
+ cps.build_image(export, _target(), tmp_path / "work")
assert seen["cleanup"] is False
+# -- what the encoder drops -----------------------------------------------
+
+# The export as codeplugger writes it: list items start in column zero.
+EXPORT = """\
+contacts:
+- dmr:
+ id: cont1
+ name: FAMILY
+ type: GroupCall
+ number: 99
+channels:
+- fm:
+ id: ch1
+ name: FAM ALL
+- dmr:
+ id: ch2
+ name: DMR FAM T2
+ timeSlot: TS2
+ groupList: grp1
+ contact: cont1
+"""
+
+# What dmrconf decodes from a faithful image, tags and flow style included.
+ENCODED = """\
+contacts:
+ - dmr: {id: cont1, name: FAMILY, type: GroupCall, number: 99, openGD77: {timeSlotOverride: None}}
+channels:
+ - fm:
+ id: ch1
+ name: FAM ALL
+ squelch: !default ""
+ - dmr:
+ id: ch2
+ name: DMR FAM T2
+ timeSlot: TS2
+ groupList: grp1
+ contact: cont1
+"""
+
+
+def test_the_export_reaches_upstream_in_the_indentation_its_parser_reads() -> None:
+ """Upstream takes a list whose items start in column zero for an empty one.
+
+ Its two fix-ups then do nothing and report nothing, which is how an RT3S
+ came to hold 9 of 38 TX contacts behind a clean verify.
+ """
+
+ styled = qdmr_style(EXPORT)
+
+ assert yaml.safe_load(styled) == yaml.safe_load(EXPORT)
+ lines = styled.splitlines()
+ assert " - dmr:" in lines and " name: DMR FAM T2" in lines
+ assert not any(line.startswith("- ") for line in lines)
+
+
+def test_a_faithful_encoding_has_no_losses() -> None:
+ assert conversion_losses(EXPORT, ENCODED) == []
+
+
+def test_a_dropped_tx_contact_and_a_forced_timeslot_are_both_reported() -> None:
+ """Both pass a read-back verify, because the image itself carries them."""
+
+ encoded = ENCODED.replace(" contact: cont1\n", "").replace(
+ "timeSlotOverride: None", "timeSlotOverride: TS1"
+ )
+
+ losses = conversion_losses(EXPORT, encoded)
+
+ assert len(losses) == 2
+ assert "channel 'DMR FAM T2' lost its TX contact (99)" in losses
+ assert any("'FAMILY' has timeslot override TS1" in loss for loss in losses)
+
+
+def test_an_image_that_lost_a_tx_contact_is_refused_before_the_write(
+ tmp_path: Path,
+) -> None:
+ root = _checkout(tmp_path)
+ store = ArtifactStore(tmp_path, "retevis_rt3s_radiofoundry", "bench")
+ cps = RadioFoundryCps(root=root, artifact_store=store)
+ export = tmp_path / "codeplug.yaml"
+ export.write_text(EXPORT)
+ seen: dict = {}
+
+ class FakePort:
+ @staticmethod
+ def convert_for_rfoundry(sess, src, driver, cleanup=True):
+ seen["source"] = Path(src).read_text()
+ encoded = tmp_path / "out.yaml"
+ encoded.write_text(ENCODED.replace(" contact: cont1\n", ""))
+ return str(tmp_path / "out.dfu"), str(encoded), {"contacts": (0, 0)}
+
+ object.__setattr__(cps, "_codeplug_port", lambda: FakePort())
+
+ with pytest.raises(RadioFoundryError, match="'DMR FAM T2' lost its TX contact"):
+ cps.build_image(export, _target(), tmp_path / "work")
+
+ assert " - dmr:" in seen["source"].splitlines()
+ assert not (tmp_path / "work" / "rfoundry-codeplug.img").exists()
+ record = json.loads(store.log_path.read_text().splitlines()[-1])
+ assert (record["operation"], record["status"]) == ("encode", "failure")
+
+
def test_tool_modules_register_under_their_import_name(tmp_path: Path) -> None:
"""codeplug_port imports cps_client lazily, so a path-only load fails later."""
diff --git a/tests/test_radiofoundry_firmware.py b/tests/test_radiofoundry_firmware.py
new file mode 100644
index 0000000..f50a9ba
--- /dev/null
+++ b/tests/test_radiofoundry_firmware.py
@@ -0,0 +1,514 @@
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+import shutil
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+from codeplugger.artifacts import ArtifactStore
+from codeplugger.backends.radiofoundry import (
+ VERIFIED_REVISIONS,
+ CheckoutRevision,
+ RadioFoundryError,
+ RadioFoundryTarget,
+)
+from codeplugger.backends.radiofoundry_firmware import (
+ FirmwareBuilder,
+ FirmwareImage,
+ FirmwareInstaller,
+ FirmwareTarget,
+ load_lock,
+ lock_path,
+ lock_status,
+ prepare_tree,
+ toolchain_for,
+ update_lock,
+)
+from codeplugger.catalog import available_radios
+from codeplugger.cli import main
+from codeplugger.profile import DEFAULT_RADIO_ROOT
+
+VERIFIED = VERIFIED_REVISIONS[0]
+SHORT = VERIFIED[:8]
+MODULE = "codeplugger.backends.radiofoundry_firmware"
+
+DM32 = {
+ "id": "baofeng_dm32_radiofoundry",
+ "radiofoundry_cps": {"dmrconf_radio_key": "openuv380", "offset": "0x700000"},
+ "radiofoundry_firmware": {"board": "dm32"},
+}
+
+CSKY_IMAGE = "registry.example/csky-gcc14:1"
+ARM_IMAGE = "registry.example/arm-ci:13.3.rel1@sha256:" + "a" * 64
+
+
+def _image(
+ directory: Path,
+ *,
+ board: str = "dm32",
+ commit: str = VERIFIED,
+ data: bytes = b"firmware image",
+) -> FirmwareImage:
+ """A packaged build as `tools/release.py` leaves one: image plus manifest."""
+
+ directory.mkdir(parents=True, exist_ok=True)
+ name = f"rfoundry-{board}-codeplugger-{commit[:8]}"
+ (directory / f"{name}.bin").write_bytes(data)
+ (directory / f"{name}.json").write_text(
+ json.dumps(
+ {
+ "format": "rfoundry-release/1",
+ "board": board,
+ "version": f"codeplugger-{commit[:8]}",
+ "git": commit[:8],
+ "git_full": commit,
+ "image": {
+ "file": f"{name}.bin",
+ "size": len(data),
+ "sha256": hashlib.sha256(data).hexdigest(),
+ },
+ "toolchain": "test-gcc 1.0",
+ }
+ )
+ )
+ return FirmwareImage.load(directory / f"{name}.bin")
+
+
+def _tree(root: Path) -> Path:
+ """The parts of a RadioFoundry tree a build reads its pins from."""
+
+ for board, platform in (("dm32", "hrc7000"), ("dm1701", "stm32f4")):
+ board_dir = root / "boards" / board
+ board_dir.mkdir(parents=True)
+ (board_dir / "board.mk").write_text(f"NAME := x\nPLATFORM := {platform}\n")
+ for platform, table in (
+ ("hrc7000", f'id = "csky"\nversion = "14.2.0"\nimage = "{CSKY_IMAGE}"\n'),
+ ("stm32f4", f'id = "arm"\nversion = "13.3.rel1"\nimage = "{ARM_IMAGE}"\n'),
+ ):
+ platform_dir = root / "platform" / platform
+ platform_dir.mkdir(parents=True)
+ (platform_dir / "platform.toml").write_text(f"[toolchain]\n{table}")
+ return root
+
+
+def _checkout(tmp_path: Path) -> Path:
+ root = tmp_path / "RadioFoundry"
+ (root / "tools" / "rfoundry" / "rfoundry").mkdir(parents=True)
+ (root / "tools" / "rfoundry" / "rfoundry" / "__main__.py").write_text("# stub\n")
+ (root / "tools" / "cps_client.py").write_text("# stub\n")
+ return root
+
+
+def _git(root: Path, *args: str) -> str:
+ result = subprocess.run(
+ [
+ "git",
+ "-C",
+ str(root),
+ "-c",
+ "user.name=test",
+ "-c",
+ "user.email=test@example.invalid",
+ "-c",
+ "commit.gpgsign=false",
+ "-c",
+ "protocol.file.allow=always",
+ *args,
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ return result.stdout.strip()
+
+
+needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
+
+
+# -- the lock -------------------------------------------------------------
+
+
+def test_a_first_build_is_unlocked_and_a_repeat_is_locked(tmp_path: Path) -> None:
+ path = tmp_path / "firmware.lock.json"
+ image = _image(tmp_path / "out")
+
+ assert lock_status(load_lock(path), image) == "unlocked"
+ update_lock(path, image)
+ lock = load_lock(path)
+ assert lock_status(lock, image) == "locked"
+ assert lock["board"] == "dm32"
+ assert lock["images"][VERIFIED]["toolchain"] == "test-gcc 1.0"
+
+
+def test_a_different_image_for_a_locked_commit_is_never_recorded(
+ tmp_path: Path,
+) -> None:
+ """Otherwise --update-lock would turn a failed reproduction into the pin."""
+
+ path = tmp_path / "firmware.lock.json"
+ update_lock(path, _image(tmp_path / "first"))
+ before = path.read_text()
+ other = _image(tmp_path / "second", data=b"another compiler's image")
+
+ with pytest.raises(RadioFoundryError, match="not the one that was locked"):
+ update_lock(path, other)
+ assert path.read_text() == before
+
+
+def test_an_image_is_refused_when_its_manifest_describes_other_bytes(
+ tmp_path: Path,
+) -> None:
+ """The commit comes from the manifest, so the manifest must be this file's."""
+
+ image = _image(tmp_path)
+ image.path.write_bytes(b"swapped after packaging")
+ with pytest.raises(RadioFoundryError, match="does not match its manifest"):
+ FirmwareImage.load(image.path)
+
+
+def test_each_firmware_lock_is_for_the_board_its_radio_declares() -> None:
+ for radio in available_radios():
+ path = lock_path(DEFAULT_RADIO_ROOT, radio.id)
+ if not path.is_file():
+ continue
+ board = FirmwareTarget.from_capabilities(radio.capabilities).board
+ assert load_lock(path)["board"] == board, radio.id
+
+
+# -- the source tree ------------------------------------------------------
+
+
+@needs_git
+def test_the_build_tree_is_the_commit_not_the_checkout(tmp_path: Path) -> None:
+ """Uncommitted edits, a moved HEAD and stray files must not reach a build."""
+
+ library = tmp_path / "library"
+ library.mkdir()
+ (library / "lib.c").write_text("library\n")
+ _git(library, "init", "-q")
+ _git(library, "add", "-A")
+ _git(library, "commit", "-q", "-m", "library")
+
+ root = tmp_path / "RadioFoundry"
+ root.mkdir()
+ (root / "main.c").write_text("pinned\n")
+ _git(root, "init", "-q")
+ _git(root, "submodule", "--quiet", "add", str(library), "third_party/library")
+ _git(root, "add", "-A")
+ _git(root, "commit", "-q", "-m", "pinned")
+ pinned = _git(root, "rev-parse", "HEAD")
+
+ (root / "main.c").write_text("later commit\n")
+ _git(root, "commit", "-q", "-am", "later")
+ (root / "main.c").write_text("uncommitted\n")
+ (root / "stray.c").write_text("untracked\n")
+
+ tree = prepare_tree(root, pinned, tmp_path / "cache" / "tree")
+
+ assert (tree / "main.c").read_text() == "pinned\n"
+ assert not (tree / "stray.c").exists()
+ assert (tree / "third_party" / "library" / "lib.c").read_text() == "library\n"
+ assert _git(tree, "rev-parse", "HEAD") == pinned
+ assert _git(tree, "status", "--porcelain") == ""
+
+
+def test_the_toolchain_is_read_from_the_tree_being_built(tmp_path: Path) -> None:
+ tree = _tree(tmp_path)
+
+ csky = toolchain_for(tree, "dm32")
+ assert (csky.image, csky.tree_image) == (CSKY_IMAGE, None)
+
+ # The Arm pin is a bare toolchain tree, so it is mounted into the one
+ # image upstream pins that can actually run a build.
+ arm = toolchain_for(tree, "dm1701")
+ assert arm.image == CSKY_IMAGE
+ assert arm.tree_image == ARM_IMAGE
+ assert arm.tree_name == "arm-gnu-toolchain-13.3.rel1-x86_64-arm-none-eabi"
+
+ with pytest.raises(RadioFoundryError, match="no board 'rt99'"):
+ toolchain_for(tree, "rt99")
+
+
+# -- building -------------------------------------------------------------
+
+
+def _fake_build(monkeypatch, tmp_path: Path, *, stamp: str, parallel_fails: bool):
+ """Stand in for git and docker; returns the commands that were run."""
+
+ commands: list[list[str]] = []
+ tree = _tree(tmp_path / "tree")
+ monkeypatch.setattr(f"{MODULE}.resolve_commit", lambda _root, _revision: VERIFIED)
+ monkeypatch.setattr(f"{MODULE}.prepare_tree", lambda _root, _commit, _tree: tree)
+
+ def fake_run(command: list[str], **_: object) -> object:
+ commands.append(command)
+ stdout = ""
+ returncode = 0
+ if "make" in command:
+ if parallel_fails and command[-1].startswith("-j"):
+ returncode, stdout = 2, "lto1: internal compiler error: in return_token\n"
+ else:
+ stdout = f"image build/dm32/rfoundry_dm32.bin: 14 bytes, version {stamp}\n"
+ elif "tools/release.py" in command:
+ _image(Path(command[command.index("--out") + 1]))
+ elif command[1:3] == ["image", "inspect"]:
+ stdout = "sha256:c0ffee\n"
+ return SimpleNamespace(returncode=returncode, stdout=stdout, stderr="")
+
+ monkeypatch.setattr(f"{MODULE}.subprocess.run", fake_run)
+ return commands, tree
+
+
+def test_a_build_retries_serially_and_packages_under_the_codeplugger_label(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Under emulation the parallel link aborts; the serial one finishes it."""
+
+ commands, tree = _fake_build(monkeypatch, tmp_path, stamp=SHORT, parallel_fails=True)
+ store = ArtifactStore(tmp_path, "baofeng_dm32_radiofoundry", "firmware")
+ builder = FirmwareBuilder(
+ root=tmp_path, artifact_store=store, cache_root=tmp_path / "cache", jobs=8
+ )
+
+ image = builder.build("dm32", VERIFIED, tmp_path / "out")
+
+ makes = [command for command in commands if "make" in command]
+ assert [command[-1] for command in makes] == ["-j8", "BOARD=dm32"]
+ # Every build step runs in the image the tree pins, on the cloned tree.
+ assert all(CSKY_IMAGE in command and f"{tree}:{tree}" in command for command in makes)
+ package = next(command for command in commands if "tools/release.py" in command)
+ assert package[package.index("--version") + 1] == f"codeplugger-{SHORT}"
+
+ assert image.path.parent == tmp_path / "out"
+ assert image.sha256 == hashlib.sha256(b"firmware image").hexdigest()
+ record = json.loads(store.log_path.read_text().splitlines()[-1])
+ assert (record["operation"], record["status"]) == ("firmware-build", "success")
+ assert image.sha256 in record["detail"] and "sha256:c0ffee" in record["detail"]
+
+
+def test_an_image_stamped_dirty_is_not_packaged(tmp_path: Path, monkeypatch) -> None:
+ """A dirty stamp means build-time bytes in the image: not reproducible."""
+
+ commands, _ = _fake_build(
+ monkeypatch, tmp_path, stamp=f"{SHORT}-dirty", parallel_fails=False
+ )
+ builder = FirmwareBuilder(root=tmp_path, cache_root=tmp_path / "cache")
+
+ with pytest.raises(RadioFoundryError, match="not a reproducible build"):
+ builder.build("dm32", VERIFIED, tmp_path / "out")
+ assert not any("tools/release.py" in command for command in commands)
+ assert (tmp_path / "out" / "build.log").is_file()
+
+
+# -- installing -----------------------------------------------------------
+
+
+def _installer(tmp_path: Path, monkeypatch, *, reports: str, **options: bool):
+ """An installer whose rfoundry and radio are faked; returns it and the calls."""
+
+ flashes: list[list[str]] = []
+
+ # One stand-in for both tools: the two modules share `subprocess.run`.
+ def fake_run(command: list[str], **_: object) -> object:
+ if "rfoundry" in command:
+ flashes.append(command)
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+ return SimpleNamespace(
+ returncode=0, stdout=f"radio_type=6\ngit={reports}\n", stderr=""
+ )
+
+ monkeypatch.setattr(f"{MODULE}.subprocess.run", fake_run)
+ monkeypatch.setattr(
+ "codeplugger.backends.radiofoundry.checkout_revision",
+ lambda _root: CheckoutRevision(commit=VERIFIED),
+ )
+ store = ArtifactStore(tmp_path, "baofeng_dm32_radiofoundry", "firmware")
+ installer = FirmwareInstaller(
+ root=_checkout(tmp_path), artifact_store=store, port="/dev/cu.test", **options
+ )
+ return installer, flashes, store
+
+
+def _install(installer: FirmwareInstaller, image: FirmwareImage, lock: dict, **kwargs):
+ return installer.install(
+ image,
+ target=RadioFoundryTarget.from_capabilities(DM32),
+ firmware=FirmwareTarget.from_capabilities(DM32),
+ lock=lock,
+ **kwargs,
+ )
+
+
+def _locked(tmp_path: Path, image: FirmwareImage) -> dict:
+ path = tmp_path / "firmware.lock.json"
+ update_lock(path, image)
+ return load_lock(path)
+
+
+def test_install_shows_the_plan_and_flashes_nothing_without_confirm(
+ tmp_path: Path, monkeypatch
+) -> None:
+ installer, flashes, _ = _installer(tmp_path, monkeypatch, reports=SHORT)
+ image = _image(tmp_path / "out")
+
+ assert _install(installer, image, _locked(tmp_path, image)) is False
+ assert len(flashes) == 1 and flashes[0][-1] == "--dry-run"
+
+
+def test_install_is_confirmed_by_the_commit_the_radio_reports(
+ tmp_path: Path, monkeypatch
+) -> None:
+ installer, flashes, store = _installer(tmp_path, monkeypatch, reports=SHORT)
+ image = _image(tmp_path / "out")
+
+ assert _install(installer, image, _locked(tmp_path, image), confirm=True) is True
+
+ plan, flash = flashes
+ assert plan[-1] == "--dry-run" and "--dry-run" not in flash
+ assert flash[flash.index("--board") + 1] == "dm32"
+ assert flash[flash.index("--port") + 1] == "/dev/cu.test"
+ # rfoundry's flash report is how upstream sees a codeplugger install.
+ assert "--no-reporting" not in flash
+ record = json.loads(store.log_path.read_text().splitlines()[-1])
+ assert (record["operation"], record["status"]) == ("firmware-install", "success")
+
+
+def test_a_radio_still_reporting_other_firmware_is_not_a_finished_install(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """rfoundry exiting cleanly is not the radio running what was sent."""
+
+ installer, _, store = _installer(tmp_path, monkeypatch, reports="0ldf1rm0")
+ image = _image(tmp_path / "out")
+
+ with pytest.raises(RadioFoundryError, match="0ldf1rm0.*not confirmed"):
+ _install(installer, image, _locked(tmp_path, image), confirm=True)
+ record = json.loads(store.log_path.read_text().splitlines()[-1])
+ assert (record["operation"], record["status"]) == ("firmware-install", "failure")
+
+
+def test_a_radio_that_goes_silent_after_the_flash_says_the_flash_finished(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """An RT3S on the bench answered nothing until it was reset and recabled."""
+
+ installer, flashes, store = _installer(tmp_path, monkeypatch, reports=SHORT)
+ image = _image(tmp_path / "out")
+ lock = _locked(tmp_path, image)
+
+ def silent_radio(command: list[str], **_: object) -> object:
+ if "rfoundry" in command:
+ flashes.append(command)
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+ return SimpleNamespace(
+ returncode=1, stdout="", stderr="error: R 9 0x0 32: reply b''"
+ )
+
+ monkeypatch.setattr(f"{MODULE}.subprocess.run", silent_radio)
+ monkeypatch.setattr("codeplugger.backends.radiofoundry.time.sleep", lambda _: None)
+
+ with pytest.raises(RadioFoundryError, match="finished flashing.*not confirmed"):
+ _install(installer, image, lock, confirm=True)
+ assert len(flashes) == 2
+ record = json.loads(store.log_path.read_text().splitlines()[-1])
+ assert (record["operation"], record["status"]) == ("firmware-install", "failure")
+ assert "did not answer" in record["detail"]
+
+
+@pytest.mark.parametrize(
+ ("commit", "lock_it", "reason"),
+ [
+ ("f" * 40, True, "not a verified revision"),
+ # A verified commit built by some other compiler is another image.
+ (VERIFIED, False, "lock has no image"),
+ ],
+)
+def test_install_refuses_an_unverified_image_before_running_rfoundry(
+ tmp_path: Path, monkeypatch, commit: str, lock_it: bool, reason: str
+) -> None:
+ installer, flashes, _ = _installer(tmp_path, monkeypatch, reports=SHORT)
+ image = _image(tmp_path / "out", commit=commit)
+ lock = _locked(tmp_path, image) if lock_it else load_lock(tmp_path / "none.json")
+
+ with pytest.raises(RadioFoundryError, match=f"{reason}.*--allow-unverified-firmware"):
+ _install(installer, image, lock, confirm=True)
+ assert flashes == []
+
+
+def test_the_opt_in_flashes_an_image_that_differs_from_the_lock(
+ tmp_path: Path, monkeypatch
+) -> None:
+ installer, flashes, store = _installer(
+ tmp_path, monkeypatch, reports=SHORT, allow_unverified_firmware=True
+ )
+ lock = _locked(tmp_path, _image(tmp_path / "locked"))
+ other = _image(tmp_path / "other", data=b"built with another compiler")
+
+ assert _install(installer, other, lock, confirm=True) is True
+ assert len(flashes) == 2
+ gate = json.loads(store.log_path.read_text().splitlines()[0])
+ assert gate["operation"] == "firmware-image"
+ assert "unverified, allowed" in gate["detail"]
+
+
+def test_install_refuses_another_board_s_image(tmp_path: Path, monkeypatch) -> None:
+ """Cross-flashing within this family is how a radio is bricked."""
+
+ installer, flashes, _ = _installer(
+ tmp_path, monkeypatch, reports=SHORT, allow_unverified_firmware=True
+ )
+ image = _image(tmp_path / "out", board="dm1701")
+
+ with pytest.raises(RadioFoundryError, match="'dm1701'.*takes 'dm32'"):
+ _install(installer, image, load_lock(tmp_path / "none.json"), confirm=True)
+ assert flashes == []
+
+
+# -- the command ----------------------------------------------------------
+
+
+def test_firmware_build_records_a_first_image_and_fails_a_different_one(
+ tmp_path: Path, monkeypatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ radio_root = tmp_path / "radios"
+ shutil.copytree(
+ DEFAULT_RADIO_ROOT / "baofeng_dm32_radiofoundry",
+ radio_root / "baofeng_dm32_radiofoundry",
+ ignore=shutil.ignore_patterns("firmware.lock.json"),
+ )
+ monkeypatch.setattr(f"{MODULE}.resolve_commit", lambda _root, _revision: VERIFIED)
+ built = {"data": b"first build"}
+ monkeypatch.setattr(
+ f"{MODULE}.FirmwareBuilder.build",
+ lambda self, board, commit, out_dir: _image(out_dir, data=built["data"]),
+ )
+ arguments = [
+ "firmware",
+ "build",
+ "--radio",
+ "baofeng_dm32_radiofoundry",
+ "--radio-root",
+ str(radio_root),
+ "--rfoundry-root",
+ str(_checkout(tmp_path)),
+ "--artifact-root",
+ str(tmp_path),
+ ]
+ lock_file = lock_path(radio_root, "baofeng_dm32_radiofoundry")
+
+ assert main(arguments) == 0
+ assert not lock_file.exists()
+ assert "--update-lock" in capsys.readouterr().out
+
+ assert main([*arguments, "--update-lock"]) == 0
+ recorded = lock_file.read_text()
+ assert hashlib.sha256(b"first build").hexdigest() in recorded
+
+ built["data"] = b"a build that did not reproduce"
+ assert main([*arguments, "--update-lock"]) == 1
+ assert "not the one that was locked" in capsys.readouterr().err
+ assert lock_file.read_text() == recorded