2026 dongle: own firmware for the USB nRF24 stick, wire-free USB flashing

Reverse-engineered the AliExpress "USB_24RF Ver3.1" stick (STM32F030F4P6 +
Si24R1 + AT2401C PA + CH330N) and replaced its closed AT-command firmware so it
can be the PC-side radio for the hexapod.

- Pin map found over SWD and confirmed at runtime: USART1 PA9/PA10 (CH330N),
  SPI1 PA5/6/7, nRF CSN PA3 / CE PA4 / IRQ PA2. LED + AT2401C control are among
  the 5 free pins, still to map.
- Two-stage firmware so wire-free flashing can't be broken by an app update:
  - safeboot (4 KB, pages 0-3): permanent recovery bootloader, fixed-baud flash
    protocol over USB, only it survives every update;
  - app (12 KB, pages 4+): the radio firmware, the only part updates rewrite.
  The app updater never erases safeboot; recovery works even with a dead app.
- tools/dongle_flash.py: one-time install via the STM32 ROM bootloader (the only
  time the BOOT0 wire is used). tools/safeboot_flash.py: wire-free app updates.
- dongle/README.md documents the hardware, pin map, RDP1 (factory fw can't be
  dumped), the memory map and the flashing workflow.
- README: add dongle/ to the layout and the PC-radio plan.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
mangavalkandClaude Opus 4.8 committed 2026-11-14 23:14:16 +01:00
1 parent 0f9655d646
commit 97f580b6a5
12 files changed
+885 -10

No files matched your search

+9 -10
View File
@@ -16,6 +16,7 @@ remote/ remote firmware: 2 x 3-axis sticks, MPU6050 tilt, Nex
shared/ HexapodProtocol: the CmdPacket wire format + radio settings used by both shared/ HexapodProtocol: the CmdPacket wire format + radio settings used by both
sim/ the unchanged robot firmware compiled into a DLL for the simulation sim/ the unchanged robot firmware compiled into a DLL for the simulation
Hexapod_Simulation_Unity/ Unity project that runs that DLL on the 3D model Hexapod_Simulation_Unity/ Unity project that runs that DLL on the 3D model
dongle/ USB nRF24 stick firmware (STM32F030): the PC-side radio, see dongle/README.md
hardware/openscad/ OpenSCAD model of the robot (rebuilt from the Fusion designs) and the new remote hardware/openscad/ OpenSCAD model of the robot (rebuilt from the Fusion designs) and the new remote
hardware/openscad/stl/ print-ready STL exports hardware/openscad/stl/ print-ready STL exports
hardware/fusion360/ Fusion 360 designs: body, legs, servo, servo horn, remote case hardware/fusion360/ Fusion 360 designs: body, legs, servo, servo horn, remote case
@@ -78,16 +79,14 @@ Design notes, checks and open points: [hardware/openscad/PLANNING.md](hardware/o
## Planned ## Planned
- **PC radio link (owner, later):** a USB nRF24L01 stick on the PC (it - **PC radio link (owner, later):** a USB nRF24L01 stick on the PC as the
probably shows up as a serial port), on the same radio as the robot and the PC-side radio, on the same air settings as the robot and the remote, so Unity
remote, so Unity on the PC can both receive data from (telemetry) and send on the PC can both receive data from (telemetry) and send data to the robot
data to the robot and the remote. Not designed yet. To work out: and the remote. The stick is now reverse-engineered and reflashed with our own
- what the stick's firmware does: many of these sticks are a USB-serial firmware (STM32F030 + Si24R1 + AT2401C); it shows up as a COM port and is
chip with a microcontroller set up by AT commands (address, channel, data updated wire-free over USB. See **[dongle/README.md](dongle/README.md)**. Still
rate) that passes raw payloads through; check that it can match to do:
`HXP_RADIO_*` in `shared/HexapodProtocol/HexapodProtocol.h` (channel 96, - map the stick's LED and AT2401C power-amp control pins (app toggles them);
250 kbps, 5-byte address `HXPD1`, fixed payload of `sizeof(CmdPacket)`)
and whether it can do auto-ack and ack payloads;
- the radio protocol: today the remote only transmits a `CmdPacket` to the - the radio protocol: today the remote only transmits a `CmdPacket` to the
robot and nothing comes back. Three nodes need an address per node (or robot and nothing comes back. Three nodes need an address per node (or
per pipe), a packet type byte, and telemetry back (e.g. as ack payloads per pipe), a packet type byte, and telemetry back (e.g. as ack payloads
+2
View File
@@ -0,0 +1,2 @@
# build artifacts (regenerate with firmware/build.ps1)
build/
+169
View File
@@ -0,0 +1,169 @@
# USB nRF24 dongle
A cheap "USB NRF24L01+ 2.4G" stick (AliExpress, board marked **USB_24RF
Ver 3.1**, Rainsun chip antenna) reflashed with our own firmware so it can be
the PC-side radio for the hexapod: same nRF24 air settings as the robot and the
remote, talking to Unity over USB serial.
It shipped with a closed "AT command" bridge firmware. We replaced that with the
two-stage firmware in `firmware/`. **The factory firmware could not be backed
up** (read-protected, see below), so this is a one-way change — done on the
owner's say-so.
## Hardware (reverse-engineered from the board)
| Part | Chip | Notes |
|------|------|-------|
| MCU | **STM32F030F4P6** | Cortex-M0, 16 KB flash, 4 KB RAM, TSSOP-20 |
| USB-serial | **CH330N** | shows up as "USB-SERIAL CH340" on Windows (COM port) |
| Radio | **Si24R1** | nRF24L01+ clone, driven over SPI; 16 MHz crystal |
| PA/LNA | **AT2401C** | 2.4 GHz power amp + low-noise amp (range booster) |
| antenna | Rainsun chip antenna | |
### Pin map (MCU)
Found by probing the board over SWD and confirmed at runtime by our firmware:
| Function | STM32 pin |
|----------|-----------|
| USB serial (USART1) TX / RX | PA9 / PA10 → CH330N |
| SPI1 SCK / MISO / MOSI | PA5 / PA6 / PA7 → Si24R1 |
| nRF CSN / CE / IRQ | PA3 / PA4 / PA2 |
| free (LED + AT2401C TX/RX enable) | PA0, PA1, PB1, PF0, PF1 — **not yet mapped** |
The LED and the AT2401C control lines are somewhere in those 5 free pins (the
TSSOP-20 has no other GPIO); the app firmware toggles them one at a time so we
can identify them by eye / by a range test. Until the PA control is known the
radio still works, just at reduced range.
### Programming header (5 holes next to the CH330N)
Square pad = hole 1.
| Hole | Signal |
|------|--------|
| 1 | BOOT0 |
| 2 | 3V3 |
| 3 | GND |
| 4 | SWDIO (PA13) |
| 5 | SWCLK (PA14) |
The factory firmware repurposed PA13/PA14, so SWD only answered with **BOOT0
tied high** (hole 1 → hole 2) at power-up. With our firmware this header is not
needed at all — see flashing below.
### Flash readout protection
The STM32 was at **RDP level 1**: reads of flash are refused over both SWD and
the ROM bootloader, so the factory firmware cannot be dumped. Level 1 (not the
permanent level 2) still allows reflashing — unlocking does a mass-erase, which
is what wiped the factory firmware. The only way past RDP1 to read it would be
the F0 cold-boot stepping exploit (thousands of power cycles); not worth it.
## Firmware: two stages, so wire-free flashing can never break
The whole point of the design: **once installed, the dongle is reflashed over
USB forever, with no BOOT0 wire and no ST-Link — and no firmware update can take
that ability away.**
```
flash (16 KB):
0x08000000 +--------------------+ page 0
| safeboot (4 KB) | stage 1: permanent recovery bootloader
0x08001000 +--------------------+ page 4
| app (12 KB) | stage 2: the radio firmware
0x08004000 +--------------------+ page 16
RAM (4 KB): 0x20000000 = magic word (app -> safeboot signal); .data/.bss from +4
```
- **`safeboot`** (`firmware/safeboot.c`) runs first on every reset. It speaks a
tiny, fixed-baud (115200 8N1) flash protocol over USB and can always erase and
rewrite the app. It has no dependencies and is flashed once.
- **`app`** (`firmware/app.c`) is the actual radio firmware. It is the only part
future updates rewrite.
- **The app updater only erases pages 4-15 — never safeboot.** So a buggy app
can't remove the recovery path.
Recovery is guaranteed three ways, none needing the wire:
1. normal update — the running app resets into safeboot on the `b` command (the
CH330N keeps its USB power across an MCU reset, so the COM port doesn't drop);
2. a corrupt/missing app — safeboot sees the app's reset vector is invalid and
stays in flash mode;
3. a booting-but-wedged app — safeboot opens a 1.5 s knock window on every cold
boot; the updater spams `S` after a replug to catch it.
The only thing that could break it is corrupting safeboot itself, which the
updater never writes.
### safeboot flash protocol (115200 8N1)
Each command replies one byte, `K` = ok / `E` = error, unless noted.
| Cmd | Bytes | Action |
|-----|-------|--------|
| `P` | | ping |
| `V` | | prints `SBV1` (identify) |
| `E` | | erase app region (pages 4-15) |
| `W` | addr(LE32) n data[n] | program n bytes (n even, ≤128) |
| `R` | addr(LE32) n | read n bytes (returns n bytes, no `K`) |
| `G` | | `K`, then boot the app |
Banners: `SBF` = entered flash mode via the app; `SB1` = cold boot (knock
window open); `SBR` = no valid app, staying in flash mode.
## Building
Needs the ARM toolchain PlatformIO ships:
```
C:\Users\you\.platformio\penv\Scripts\pio.exe pkg install -g -p ststm32
```
Then, from `firmware/`:
```
.\build.ps1
```
Produces `build/safeboot.bin`, `build/app.bin`, and `build/dongle_combined.bin`
(safeboot padded to 4 KB + app), plus the sizes.
## Flashing
### One-time install (the only time the BOOT0 wire is used)
Puts safeboot + app on a stick that still has the factory (or any) firmware.
1. Wire **hole 1 → hole 2** (BOOT0 high) and plug the stick into USB.
2. `python tools/dongle_flash.py firmware/build/dongle_combined.bin`
- unlocks (mass-erase, the step that wipes the factory firmware),
- writes and verifies the combined image,
- starts it.
3. Remove the wire. Never needed again.
`dongle_flash.py` drives the STM32 **ROM** UART bootloader (one-shot auto-baud
per power-up, so power-cycle between attempts).
### App updates (normal, wire-free, forever after)
```
python tools/safeboot_flash.py firmware/build/app.bin
```
This resets the running app into safeboot and rewrites only the app region. If
the app is dead, replug the stick and re-run — it will catch the knock window.
## Air settings
Matches `shared/HexapodProtocol/HexapodProtocol.h`: 2.4 GHz channel 96
(2.496 GHz), 250 kbps, 5-byte address `HXPD1`, 16-bit CRC. The app sets these on
the Si24R1 over SPI (same register layout as the nRF24L01+).
## Status / next
- [x] identify the hardware, map the radio + serial pins
- [x] permanent two-stage firmware, wire-free USB flashing
- [ ] identify the LED and AT2401C TX/RX-enable pins (app toggles the 5 free pins)
- [ ] radio hub app: carry `CmdPacket` both ways, per-node addressing, telemetry
- [ ] Unity serial bridge (PC as hub when online, robot as hub when not) — see
`../README.md` "Planned"
+112
View File
@@ -0,0 +1,112 @@
/* Hexapod dongle - stage 2 "app" (bring-up / radio firmware).
*
* Links at 0x08001000 (after safeboot). Uses polling only (no interrupts), so
* no Cortex-M0 vector relocation is needed - safeboot jumps straight to it.
*
* This v0 brings up the hardware and helps map the last unknown pins:
* - USART1 PA9/PA10 115200 8N1 (USB serial via CH330N)
* - SPI1 PA5/6/7, nRF24 CSN PA3 CE PA4 IRQ PA2
* - free pins PA0 PA1 PB1 PF0 PF1 (LED + AT2401C control, still to identify)
* Serial commands: v=info r=nRF regs 0-4=toggle a free pin b=reflash (safeboot)
*/
#include "common.h"
#define CSN_HI() BSRR(GPIOA) = (1u << 3)
#define CSN_LO() BSRR(GPIOA) = (1u << (3 + 16))
#define CE_LO() BSRR(GPIOA) = (1u << (4 + 16))
static void spi_init(void)
{
RCC_AHBENR |= (1u << 17); /* GPIOA */
RCC_APB2ENR |= (1u << 12); /* SPI1 */
MODER(GPIOA) = (MODER(GPIOA) & ~((3u << 10) | (3u << 12) | (3u << 14)))
| (2u << 10) | (2u << 12) | (2u << 14); /* PA5/6/7 AF0 */
MODER(GPIOA) = (MODER(GPIOA) & ~((3u << 6) | (3u << 8)))
| (1u << 6) | (1u << 8); /* PA3/PA4 out */
MODER(GPIOA) &= ~(3u << 4); /* PA2 in */
PUPDR(GPIOA) = (PUPDR(GPIOA) & ~(3u << 4)) | (1u << 4); /* PA2 pull-up */
CSN_HI(); CE_LO();
REG(0x40013000) = (1u << 2) | (1u << 9) | (1u << 8) | (2u << 3); /* CR1 */
REG(0x40013004) = (7u << 8) | (1u << 12); /* CR2 8-bit */
REG(0x40013000) |= (1u << 6); /* SPE */
}
static uint8_t spi_xfer(uint8_t b)
{
REG8(0x4001300C) = b;
while (!(REG(0x40013008) & (1u << 0))) {}
return REG8(0x4001300C);
}
static uint8_t nrf_read(uint8_t reg)
{
CSN_LO(); spi_xfer(reg & 0x1F); uint8_t v = spi_xfer(0xFF); CSN_HI();
return v;
}
static void nrf_write(uint8_t reg, uint8_t val)
{
CSN_LO(); spi_xfer(0x20 | (reg & 0x1F)); spi_xfer(val); CSN_HI();
}
static const struct { uint32_t port; uint8_t pin; const char *name; } FREE[] = {
{ GPIOA, 0, "PA0" }, { GPIOA, 1, "PA1" }, { GPIOB, 1, "PB1" },
{ GPIOF, 0, "PF0" }, { GPIOF, 1, "PF1" },
};
#define NFREE 5
static uint8_t fst[NFREE];
static void free_init(void)
{
RCC_AHBENR |= (1u << 17) | (1u << 18) | (1u << 22);
for (int i = 0; i < NFREE; i++) {
MODER(FREE[i].port) = (MODER(FREE[i].port) & ~(3u << (FREE[i].pin * 2)))
| (1u << (FREE[i].pin * 2));
BSRR(FREE[i].port) = (1u << (FREE[i].pin + 16));
}
}
static void hex2(uint8_t b) { const char *h = "0123456789ABCDEF"; uart_putc(h[b >> 4]); uart_putc(h[b & 0xF]); }
static void banner(void)
{
uart_puts("\r\nhexapod dongle app v0 (@0x08001000)\r\n");
uart_puts("nRF CONFIG=0x"); hex2(nrf_read(0)); uart_puts(" STATUS=0x"); hex2(nrf_read(7));
uart_puts(" RF_CH=0x"); hex2(nrf_read(5)); uart_puts(" RF_SETUP=0x"); hex2(nrf_read(6));
uart_puts("\r\ncmds: v r 0-4(PA0/PA1/PB1/PF0/PF1) b=reflash\r\n");
}
static void regdump(void)
{
static const uint8_t rg[] = {0,1,2,3,4,5,6,7,8,9,0x17};
for (unsigned i = 0; i < sizeof(rg); i++) { uart_puts(" R"); hex2(rg[i]); uart_putc('='); hex2(nrf_read(rg[i])); }
uart_puts("\r\n");
}
static void reflash(void) /* ask safeboot to take over, no wire needed */
{
uart_puts("resetting into safeboot flash mode...\r\n");
while (!(USART1_ISR & (1u << 6))) {} /* TC */
REG(MAGIC_ADDR) = MAGIC_FLASH;
REG(0xE000ED0C) = 0x05FA0004; /* SCB AIRCR SYSRESETREQ */
for (;;) {}
}
int main(void)
{
uart_init8n1();
spi_init();
free_init();
nrf_write(0, 0x0E);
delay_ms(5);
banner();
uint32_t t = 0;
for (;;) {
int c = uart_getc();
if (c == 'v' || c == 'V') banner();
else if (c == 'r' || c == 'R') regdump();
else if (c == 'b' || c == 'B') reflash();
else if (c >= '0' && c <= '4') {
int i = c - '0';
fst[i] = !fst[i];
BSRR(FREE[i].port) = fst[i] ? (1u << FREE[i].pin) : (1u << (FREE[i].pin + 16));
uart_puts("pin "); uart_puts(FREE[i].name); uart_puts(fst[i] ? " HIGH\r\n" : " LOW\r\n");
}
delay_ms(1);
if (++t >= 2000) { t = 0; uart_puts("hb STATUS=0x"); hex2(nrf_read(7)); uart_puts("\r\n"); }
}
}
+18
View File
@@ -0,0 +1,18 @@
/* app: flash pages 4-15 (12 KB) after safeboot. RAM starts at +4 so the magic
* word at 0x20000000 (used to signal safeboot) is left alone. */
MEMORY
{
FLASH (rx) : ORIGIN = 0x08001000, LENGTH = 12K
RAM (rwx) : ORIGIN = 0x20000004, LENGTH = 4092
}
_estack = 0x20001000;
SECTIONS
{
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH
.text : { *(.text*) *(.rodata*) . = ALIGN(4); } > FLASH
_sidata = LOADADDR(.data);
.data : { . = ALIGN(4); _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT > FLASH
.bss : { . = ALIGN(4); _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
/DISCARD/ : { *(.ARM.exidx*) *(.ARM.extab*) }
}
@@ -0,0 +1,22 @@
/* Startup for the stage-2 app. Polling only, so no IRQ vectors are needed
* beyond SP/Reset; safeboot jumps here directly (no M0 vector relocation). */
#include <stdint.h>
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;
int main(void);
void Reset_Handler(void)
{
uint32_t *src = &_sidata, *dst = &_sdata;
while (dst < &_edata) *dst++ = *src++;
for (dst = &_sbss; dst < &_ebss;) *dst++ = 0;
main();
for (;;) {}
}
void Default_Handler(void) { for (;;) {} }
__attribute__((section(".isr_vector"), used))
void (*const g_vectors[])(void) = {
(void (*)(void))&_estack, Reset_Handler, Default_Handler, Default_Handler,
0, 0, 0, 0, 0, 0, 0, Default_Handler, 0, 0, Default_Handler, Default_Handler,
};
+36
View File
@@ -0,0 +1,36 @@
# Build the dongle firmware: safeboot.bin (stage 1), app.bin (stage 2), and
# dongle_combined.bin (safeboot padded to 4 KB + app) for the one-time install.
# Uses the ARM toolchain PlatformIO installed (pio pkg install -g -p ststm32).
$ErrorActionPreference = "Stop"
$bin = "$env:USERPROFILE\.platformio\packages\toolchain-gccarmnoneeabi\bin"
$gcc = (Get-ChildItem "$bin\arm-none-eabi-gcc*.exe" | Select-Object -First 1).FullName
$objcopy = (Get-ChildItem "$bin\arm-none-eabi-objcopy*.exe" | Select-Object -First 1).FullName
$size = (Get-ChildItem "$bin\arm-none-eabi-size*.exe" | Select-Object -First 1).FullName
$cf = "-mcpu=cortex-m0 -mthumb -Os -ffreestanding -nostdlib -ffunction-sections -fdata-sections -Wall -Wextra"
$here = $PSScriptRoot
Set-Location $here
$out = "$here\build"; New-Item -ItemType Directory -Force $out | Out-Null
$lf = @("-mcpu=cortex-m0", "-mthumb", "-nostdlib", "-Wl,--gc-sections")
# stage 1
& $gcc $cf.Split(' ') -c safeboot.c -o "$out\safeboot.o"
& $gcc $lf -T safeboot.ld "$out\safeboot.o" -o "$out\safeboot.elf"
& $objcopy -O binary "$out\safeboot.elf" "$out\safeboot.bin"
# stage 2
& $gcc $cf.Split(' ') -c app.c -o "$out\app.o"
& $gcc $cf.Split(' ') -c app_startup.c -o "$out\app_startup.o"
& $gcc $lf -T app.ld "$out\app.o" "$out\app_startup.o" -o "$out\app.elf"
& $objcopy -O binary "$out\app.elf" "$out\app.bin"
& $size "$out\safeboot.elf" "$out\app.elf"
# combined image: safeboot in [0,4KB), app at 4KB
$sb = [System.IO.File]::ReadAllBytes("$out\safeboot.bin")
$ap = [System.IO.File]::ReadAllBytes("$out\app.bin")
if ($sb.Length -gt 4096) { throw "safeboot is $($sb.Length) bytes, over the 4 KB reserved" }
$img = New-Object byte[] (4096 + $ap.Length)
for ($i = 0; $i -lt $img.Length; $i++) { $img[$i] = 0xFF }
[Array]::Copy($sb, 0, $img, 0, $sb.Length)
[Array]::Copy($ap, 0, $img, 4096, $ap.Length)
[System.IO.File]::WriteAllBytes("$out\dongle_combined.bin", $img)
Write-Host "safeboot $($sb.Length) B, app $($ap.Length) B, combined $($img.Length) B -> build\dongle_combined.bin"
+81
View File
@@ -0,0 +1,81 @@
/* Shared register defs + helpers for the hexapod dongle (STM32F030F4 @ 8 MHz).
* Magic word at 0x20000000 survives a soft reset: the app sets it to ask
* safeboot to enter flash mode. Both linker scripts keep RAM clear of it
* (RAM ORIGIN 0x20000004). */
#ifndef DONGLE_COMMON_H
#define DONGLE_COMMON_H
#include <stdint.h>
#define REG(a) (*(volatile uint32_t *)(a))
#define REG8(a) (*(volatile uint8_t *)(a))
#define MAGIC_ADDR 0x20000000u
#define MAGIC_FLASH 0xB00710ADu /* "BOOT LOAD": app -> safeboot flash */
#define APP_BASE 0x08001000u /* stage 2 starts here (page 4) */
#define APP_PAGE_LO 4
#define APP_PAGE_HI 15 /* 16 KB / 1 KB pages = 0..15 */
#define PAGE_SIZE 1024u
/* RCC */
#define RCC_AHBENR REG(0x40021014)
#define RCC_APB2ENR REG(0x40021018)
#define RCC_APB2RSTR REG(0x4002100C)
#define RCC_AHBRSTR REG(0x40021028)
/* GPIO */
#define GPIOA 0x48000000u
#define GPIOB 0x48000400u
#define GPIOF 0x48001400u
#define MODER(p) REG((p)+0x00)
#define OTYPER(p) REG((p)+0x04)
#define PUPDR(p) REG((p)+0x0C)
#define IDR(p) REG((p)+0x10)
#define BSRR(p) REG((p)+0x18)
#define AFRH(p) REG((p)+0x24)
/* USART1 */
#define USART1_CR1 REG(0x40013800)
#define USART1_BRR REG(0x4001380C)
#define USART1_ISR REG(0x4001381C)
#define USART1_RDR REG(0x40013824)
#define USART1_TDR REG(0x40013828)
/* SysTick */
#define STK_CTRL REG(0xE000E010)
#define STK_LOAD REG(0xE000E014)
#define STK_VAL REG(0xE000E018)
/* FLASH */
#define FLASH_KEYR REG(0x40022004)
#define FLASH_SR REG(0x4002200C)
#define FLASH_CR REG(0x40022010)
#define FLASH_AR REG(0x40022014)
static inline void uart_init8n1(void) /* USART1 PA9/PA10, 115200 8N1, 8 MHz */
{
RCC_AHBENR |= (1u << 17); /* GPIOA */
RCC_APB2ENR |= (1u << 14); /* USART1 */
MODER(GPIOA) = (MODER(GPIOA) & ~((3u << 18) | (3u << 20)))
| (2u << 18) | (2u << 20);
AFRH(GPIOA) = (AFRH(GPIOA) & ~((0xFu << 4) | (0xFu << 8)))
| (1u << 4) | (1u << 8);
USART1_BRR = 69;
USART1_CR1 = (1u << 0) | (1u << 2) | (1u << 3);
}
static inline void uart_putc(char c)
{
while (!(USART1_ISR & (1u << 7))) {}
USART1_TDR = (uint8_t)c;
}
static inline void uart_puts(const char *s) { while (*s) uart_putc(*s++); }
static inline int uart_getc(void) /* non-blocking, -1 if none */
{
if (USART1_ISR & (1u << 5)) return (uint8_t)USART1_RDR;
return -1;
}
static inline uint8_t uart_getc_block(void)
{
while (!(USART1_ISR & (1u << 5))) {}
return (uint8_t)USART1_RDR;
}
static inline void systick_setup(void) { STK_LOAD = 8000 - 1; STK_VAL = 0; STK_CTRL = 5; }
static inline void delay_ms(uint32_t ms) { systick_setup(); while (ms--) { while (!(STK_CTRL & 0x10000)) {} } STK_CTRL = 0; }
#endif
+154
View File
@@ -0,0 +1,154 @@
/* Hexapod dongle - stage 1 "safeboot" (permanent recovery bootloader).
*
* Lives in the first 4 KB of flash (pages 0-3) and runs first on every reset.
* It speaks a tiny fixed-baud (115200 8N1) flashing protocol over USB and can
* always erase/rewrite the application (pages 4-15). It is flashed ONCE and the
* host flasher never erases it, so no application update can remove the
* wire-free recovery path. See ../README.md.
*
* Entry decisions:
* - soft reset with MAGIC_FLASH set -> enter flash mode immediately
* - else print banner, open a knock window; host 'S' -> flash mode
* - else if the app looks valid -> jump to it
* - else (no valid app) -> stay in flash mode (recovery)
*
* Flash-mode protocol (host -> safeboot, each replies one byte 'K' ok / 'E' err
* unless noted):
* 'P' ping -> 'K'
* 'E' erase app region (pages 4-15)
* 'W' a0 a1 a2 a3 n d[n] write n bytes (n even, <=128) at little-endian addr
* 'R' a0 a1 a2 a3 n read n bytes at addr -> sends n bytes (no K)
* 'G' 'K', then boot the app (or reset)
* 'V' -> prints "SBV1\n" (identify)
*/
#include "common.h"
#define KNOCK_MS 1500
/* ---- startup (custom: read the magic word before touching RAM) ---- */
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;
int sb_main(int forced);
void Reset_Handler(void)
{
uint32_t m = REG(MAGIC_ADDR);
REG(MAGIC_ADDR) = 0;
uint32_t *src = &_sidata, *dst = &_sdata;
while (dst < &_edata) *dst++ = *src++;
for (dst = &_sbss; dst < &_ebss;) *dst++ = 0;
sb_main(m == MAGIC_FLASH);
for (;;) {}
}
void Default_Handler(void) { for (;;) {} }
__attribute__((section(".isr_vector"), used))
void (*const g_vectors[])(void) = {
(void (*)(void))&_estack, Reset_Handler, Default_Handler, Default_Handler,
0, 0, 0, 0, 0, 0, 0, Default_Handler, 0, 0, Default_Handler, Default_Handler,
};
/* ---- flash programming ---- */
static void flash_unlock(void)
{
if (FLASH_CR & (1u << 7)) { FLASH_KEYR = 0x45670123; FLASH_KEYR = 0xCDEF89AB; }
}
static int flash_wait(void)
{
while (FLASH_SR & (1u << 0)) {} /* BSY */
uint32_t sr = FLASH_SR;
FLASH_SR = (1u << 5) | (1u << 2) | (1u << 4); /* clear EOP/PGERR/WRPRT */
return !(sr & ((1u << 2) | (1u << 4))); /* ok if no error bits */
}
static int flash_erase_page(uint32_t addr)
{
flash_wait();
FLASH_CR |= (1u << 1); /* PER */
FLASH_AR = addr;
FLASH_CR |= (1u << 6); /* STRT */
int ok = flash_wait();
FLASH_CR &= ~(1u << 1);
return ok;
}
static int flash_prog_hw(uint32_t addr, uint16_t hw)
{
flash_wait();
FLASH_CR |= (1u << 0); /* PG */
*(volatile uint16_t *)addr = hw;
int ok = flash_wait();
FLASH_CR &= ~(1u << 0);
return ok && (*(volatile uint16_t *)addr == hw);
}
static int erase_app(void)
{
flash_unlock();
for (int p = APP_PAGE_LO; p <= APP_PAGE_HI; p++)
if (!flash_erase_page(0x08000000u + p * PAGE_SIZE)) return 0;
return 1;
}
static uint32_t rd4(void)
{
uint32_t v = uart_getc_block();
v |= (uint32_t)uart_getc_block() << 8;
v |= (uint32_t)uart_getc_block() << 16;
v |= (uint32_t)uart_getc_block() << 24;
return v;
}
static void boot_app(void)
{
uint32_t sp = *(volatile uint32_t *)APP_BASE;
uint32_t pc = *(volatile uint32_t *)(APP_BASE + 4);
if (sp >= 0x20000000u && sp <= 0x20001000u) {
__asm volatile("msr msp, %0" : : "r"(sp));
((void (*)(void))pc)();
}
}
static void flash_loop(void)
{
flash_unlock();
for (;;) {
int c = uart_getc_block();
if (c == 'P') uart_putc('K');
else if (c == 'V') uart_puts("SBV1\r\n");
else if (c == 'E') uart_putc(erase_app() ? 'K' : 'E');
else if (c == 'W') {
uint32_t a = rd4();
uint8_t n = uart_getc_block();
uint8_t buf[128];
for (uint8_t i = 0; i < n; i++) buf[i] = uart_getc_block();
int ok = (n <= 128) && !(n & 1) && a >= APP_BASE && (a + n) <= 0x08004000u;
for (uint8_t i = 0; ok && i < n; i += 2)
ok = flash_prog_hw(a + i, (uint16_t)(buf[i] | (buf[i + 1] << 8)));
uart_putc(ok ? 'K' : 'E');
}
else if (c == 'R') {
uint32_t a = rd4();
uint8_t n = uart_getc_block();
for (uint8_t i = 0; i < n; i++) uart_putc(*(volatile uint8_t *)(a + i));
}
else if (c == 'G') { uart_putc('K'); boot_app(); /* if it returns, stay */ }
}
}
int sb_main(int forced)
{
uart_init8n1();
if (forced) { uart_puts("SBF\r\n"); flash_loop(); }
uart_puts("SB1\r\n"); /* cold boot: offer a knock window */
systick_setup();
uint32_t ms = 0;
while (ms < KNOCK_MS) {
int c = uart_getc();
if (c == 'S') { uart_putc('K'); flash_loop(); }
if (STK_CTRL & 0x10000) ms++;
}
STK_CTRL = 0;
boot_app(); /* valid app -> never returns */
uart_puts("SBR\r\n"); /* no app -> recovery flash mode */
flash_loop();
return 0;
}
+18
View File
@@ -0,0 +1,18 @@
/* safeboot: first 4 KB of flash. RAM starts at +4 so the magic word at
* 0x20000000 is never touched by .data/.bss. */
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 4K
RAM (rwx) : ORIGIN = 0x20000004, LENGTH = 4092
}
_estack = 0x20001000;
SECTIONS
{
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH
.text : { *(.text*) *(.rodata*) . = ALIGN(4); } > FLASH
_sidata = LOADADDR(.data);
.data : { . = ALIGN(4); _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT > FLASH
.bss : { . = ALIGN(4); _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
/DISCARD/ : { *(.ARM.exidx*) *(.ARM.extab*) }
}
+161
View File
@@ -0,0 +1,161 @@
"""Flash a .bin to the dongle's STM32F030 over the ROM UART bootloader (COM16).
First run unlocks (readout-unprotect = mass erase + drop RDP), then writes & verifies.
usage: dongle_flash.py firmware.bin [--port COM16]"""
import sys, time, serial
ACK, NACK = 0x79, 0x1F
FLASH = 0x08000000
class BL:
def __init__(self, port):
self.port = port
self.s = serial.Serial(port, 115200, parity=serial.PARITY_EVEN,
stopbits=1, bytesize=8, timeout=1.0)
def reopen(self):
self.s.close(); time.sleep(0.3)
self.s = serial.Serial(self.port, 115200, parity=serial.PARITY_EVEN,
stopbits=1, bytesize=8, timeout=1.0)
def _wait_ack(self, what, tmo=3.0):
self.s.timeout = tmo
b = self.s.read(1)
self.s.timeout = 1.0
if b == bytes([ACK]):
return True
if b == bytes([NACK]):
raise RuntimeError("%s: NACK" % what)
raise RuntimeError("%s: no answer (%r)" % (what, b))
def _probe_get(self):
"""Already synced? A GET (0x00) ACKs and returns the command list."""
self.s.reset_input_buffer()
self.s.write(bytes([0x00, 0xFF])); time.sleep(0.15)
b = self.s.read(1)
if b == bytes([ACK]):
n = self.s.read(1)[0]; self.s.read(n + 1); self.s.read(1)
return True
return b == bytes([NACK])
def sync(self):
# autobaud (works once per power-up)
self.s.reset_input_buffer()
self.s.write(b"\x7f"); time.sleep(0.15)
b = self.s.read(1)
if b in (bytes([ACK]), bytes([NACK])):
return True
# already synced this power cycle?
if self._probe_get():
return True
raise RuntimeError("no bootloader sync (BOOT0 high? on USB power? replug it)")
def cmd(self, c):
self.s.write(bytes([c, c ^ 0xFF]))
return self._wait_ack("cmd 0x%02X" % c)
def get(self):
self.cmd(0x00)
n = self.s.read(1)[0]
data = self.s.read(n + 1)
self.s.read(1)
return data
def readable(self):
self.s.write(bytes([0x11, 0xEE]))
b = self.s.read(1)
if b == bytes([ACK]):
# send a dummy address so the bootloader doesn't hang mid-command
self._addr(FLASH); self.s.write(bytes([0, 0xFF])); self.s.read(1)
self.s.read(1)
return True
return False
def _addr(self, addr):
a = addr.to_bytes(4, "big")
self.s.write(a + bytes([a[0] ^ a[1] ^ a[2] ^ a[3]]))
self._wait_ack("address 0x%08X" % addr)
def unprotect(self):
"""Readout-unprotect: mass-erase + drop RDP to 0. Erases factory firmware."""
self.s.write(bytes([0x92, 0x6D]))
self._wait_ack("readout-unprotect start")
self._wait_ack("readout-unprotect erase", tmo=6.0)
time.sleep(1.0) # chip resets; BOOT0 still high -> bootloader again
self.reopen(); self.sync()
def mass_erase(self):
self.s.write(bytes([0x44, 0xBB]))
self._wait_ack("ext-erase start")
self.s.write(bytes([0xFF, 0xFF, 0x00])) # 0xFFFF = global mass erase, cksum 0
self._wait_ack("mass erase", tmo=8.0)
def write(self, addr, data):
self.cmd(0x31)
self._addr(addr)
n = len(data) - 1
cs = n
for b in data:
cs ^= b
self.s.write(bytes([n]) + data + bytes([cs]))
self._wait_ack("write @0x%08X" % addr, tmo=3.0)
def read(self, addr, n):
self.cmd(0x11)
self._addr(addr)
self.s.write(bytes([n - 1, (n - 1) ^ 0xFF]))
self._wait_ack("read @0x%08X" % addr)
return self.s.read(n)
def go(self, addr):
self.cmd(0x21)
self._addr(addr)
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
port = "COM16"
if "--port" in sys.argv:
port = sys.argv[sys.argv.index("--port") + 1]
data = open(args[0], "rb").read()
if len(data) % 4:
data += b"\xFF" * (4 - len(data) % 4)
print("firmware %s: %d bytes" % (args[0], len(data)))
bl = BL(port)
bl.sync()
time.sleep(0.1)
bl.s.reset_input_buffer()
print("sync ok")
# Erase. On an unlocked chip a mass-erase is enough; if it's still locked
# (factory RDP1) the erase NACKs, so fall back to readout-unprotect.
try:
bl.mass_erase()
print("mass-erased.")
except RuntimeError:
print("locked -> readout-unprotect (ERASES factory firmware)...")
bl.unprotect()
print("unlocked and erased.")
print("writing...")
for off in range(0, len(data), 256):
chunk = data[off:off + 256]
bl.write(FLASH + off, chunk)
print("verifying...")
bad = 0
for off in range(0, len(data), 256):
chunk = data[off:off + 256]
rb = bl.read(FLASH + off, len(chunk))
if rb != chunk:
bad += 1
print(" mismatch at +0x%X" % off)
if bad:
print("VERIFY FAILED (%d blocks)" % bad); return 1
print("verify OK. starting firmware...")
bl.go(FLASH)
return 0
if __name__ == "__main__":
sys.exit(main())
+103
View File
@@ -0,0 +1,103 @@
"""Update the dongle application over USB via the permanent 'safeboot' stage 1.
No BOOT0 wire, no ST-Link, no ROM bootloader. Writes only the app region
(pages 4-15); safeboot itself is never touched.
usage: safeboot_flash.py app.bin [--port COM16]
How it enters flash mode:
1) if the app is running, 'b' makes it soft-reset into safeboot flash mode;
2) otherwise (dead/absent app) replug the dongle and this spams 'S' to catch
safeboot's cold-boot knock window.
"""
import sys, time, serial
APP_BASE = 0x08001000
PORT = "COM16"
def open_port(port):
return serial.Serial(port, 115200, timeout=0.3)
def enter_flash(s):
# path 1: tell a running app to reset into safeboot
s.reset_input_buffer()
s.write(b"b")
t = time.time()
buf = b""
while time.time() - t < 1.5:
buf += s.read(64)
if b"SBF" in buf:
return True
time.sleep(0.05)
# path 2: knock (works during safeboot's cold-boot window, after a replug)
t = time.time()
while time.time() - t < 6.0:
s.write(b"S")
r = s.read(16)
if b"K" in r or b"SBF" in r or b"SB1" in r:
# drain, then confirm we're in flash mode
time.sleep(0.1); s.reset_input_buffer()
s.write(b"V"); time.sleep(0.1)
if b"SBV" in s.read(16):
return True
time.sleep(0.1)
return False
def expect(s, ch, what):
r = s.read(1)
if r != ch:
raise RuntimeError("%s: expected %r got %r" % (what, ch, r))
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
port = sys.argv[sys.argv.index("--port") + 1] if "--port" in sys.argv else PORT
data = open(args[0], "rb").read()
if len(data) % 2:
data += b"\xFF"
print("app %s: %d bytes -> 0x%08X" % (args[0], len(data), APP_BASE))
s = open_port(port)
print("entering safeboot flash mode...")
if not enter_flash(s):
print("could not enter flash mode (app not running? replug and retry)")
return 1
s.reset_input_buffer()
s.write(b"V"); time.sleep(0.1)
print("safeboot:", s.read(16).decode("ascii", "replace").strip())
print("erasing app region...")
s.write(b"E"); s.timeout = 3.0; expect(s, b"K", "erase"); s.timeout = 0.5
print("writing...")
for off in range(0, len(data), 128):
chunk = data[off:off + 128]
addr = APP_BASE + off
s.write(b"W" + addr.to_bytes(4, "little") + bytes([len(chunk)]) + chunk)
expect(s, b"K", "write @0x%08X" % addr)
print("verifying...")
bad = 0
for off in range(0, len(data), 128):
chunk = data[off:off + 128]
addr = APP_BASE + off
s.write(b"R" + addr.to_bytes(4, "little") + bytes([len(chunk)]))
rb = s.read(len(chunk))
if rb != chunk:
bad += 1
print(" mismatch @0x%08X" % addr)
if bad:
print("VERIFY FAILED (%d blocks)" % bad); return 1
print("verify OK; booting app.")
s.write(b"G"); expect(s, b"K", "go")
time.sleep(0.3)
print(s.read(256).decode("ascii", "replace").strip())
s.close()
return 0
if __name__ == "__main__":
sys.exit(main())