A truly modular keyboard
C
firmware: app installs the CPU2 stack itself, crash fallback to DFU
Nathan73b87922b2dd
diff --git a/firmware/Core/Inc/app_conf.h b/firmware/Core/Inc/app_conf.hindex e338121..d5ca2a8 100644--- a/firmware/Core/Inc/app_conf.h+++ b/firmware/Core/Inc/app_conf.h@@ -118,6 +118,7 @@ typedef enum{CFG_FIRST_TASK_ID_WITH_NO_HCICMD = CFG_LAST_TASK_ID_WITH_HCICMD - 1,CFG_TASK_SYSTEM_HCI_ASYNCH_EVT_ID,+ CFG_TASK_FUS_ID,CFG_LAST_TASK_ID_WITH_NO_HCICMD,} CFG_Task_Id_With_NO_HCI_Cmd_t;diff --git a/firmware/Core/Inc/fus.h b/firmware/Core/Inc/fus.hnew file mode 100644index 0000000..7ff4dba--- /dev/null+++ b/firmware/Core/Inc/fus.h@@ -0,0 +1,30 @@+/*+ * Installing the CPU2 BLE stack from the app, with CPU2 running only FUS.+ *+ * The stack binary is written as plain data over USB DFU to 0x080D0000+ * (ST's address for the 1.24.0 full stack on a 1 MB part). On boot, when+ * CPU2 reports FUS instead of the stack, the app finds the image (by ST's+ * footer) and asks FUS to install it (SHCI_C2_FUS_FwUpgrade), reporting+ * progress over USB CDC, then resets so CPU2 starts the new stack. That is+ * ST's CPU1-driven path from BLE_Ota / AN5185, with no option bytes from us+ * (FUS itself moves SFSA down to the stack).+ */+#ifndef FUS_H+#define FUS_H++#include <stddef.h>++/* From the CPU2 ready event (app_entry.c). With FUS running, a check+ * runs 3 s later (USB CDC is up by then) and installs a staged image. */+void FUS_OnCpu2Ready(int cpu2_state);++/* "v=2.2.0 state=idle stack=none sfsa=0xF4 image=129460" */+void FUS_Info(char *out, size_t n);++/* STACK INSTALL. NULL when started, else why not. */+const char *FUS_Install(void);++/* 1 while an install runs (SAVE and OTA are refused then). */+int FUS_Busy(void);++#endif /* FUS_H */diff --git a/firmware/Core/Inc/ota.h b/firmware/Core/Inc/ota.hindex cc4cd88..48889a0 100644--- a/firmware/Core/Inc/ota.h+++ b/firmware/Core/Inc/ota.h@@ -21,6 +21,13 @@ void OTA_Request(void);/* Reset into the ROM USB DFU bootloader in 500 ms. No option bytes. */void OTA_RequestDfu(void);+/* Plain reset back into the app in 500 ms. */+void OTA_ResetSoon(void);++/* Call every main loop pass: feeds the bootloader's IWDG and marks the+ * app healthy (crash count zeroed) after it has run 10 s. */+void OTA_Service(void);+/* "ble v=1.24.0 fus=2.2.0", "none fus=2.2.0" or "unknown". */void OTA_StackInfo(char *out, size_t n);diff --git a/firmware/Core/Inc/proto.h b/firmware/Core/Inc/proto.hindex f72c3b4..9cfe728 100644--- a/firmware/Core/Inc/proto.h+++ b/firmware/Core/Inc/proto.h@@ -20,6 +20,7 @@ typedef struct{void (*write)(const char *data, uint16_t len);volatile uint8_t connected;+ uint8_t local; /* USB CDC: allowed to run CPU2 firmware commands */uint8_t overflow;uint16_t len;char line[PROTO_LINE_MAX];diff --git a/firmware/Core/Inc/stackimg.h b/firmware/Core/Inc/stackimg.hnew file mode 100644index 0000000..e1fc1bb--- /dev/null+++ b/firmware/Core/Inc/stackimg.h@@ -0,0 +1,32 @@+/*+ * A CPU2 firmware image (BLE stack or FUS) written into user flash for FUS+ * to install. No HAL, so it runs in the host test (test/stackimg_test.c).+ *+ * ST's images end in a 20 byte footer, the same in stm32wb5x_FUS_fw.bin and+ * stm32wb5x_BLE_Stack_full_fw.bin (STM32CubeWB 1.24.0):+ * 0x12341234, 0xABCDABCD, 0xFFFF5740, <info word>, 0xD3A12C5E+ */+#ifndef STACKIMG_H+#define STACKIMG_H++#include <stdint.h>++#define STACKIMG_ADDRESS 0x080D0000u /* ST's install address for the 1.24.0 full stack, 1 MB part */+#define STACKIMG_FOOTER_LEN 20u++/* FUS states (SHCI_C2_FUS_GetState) */+#define FUS_STATE_IDLE 0x00u+#define FUS_STATE_UPGRADE_FIRST 0x10u /* firmware or FUS upgrade ongoing: 0x10..0x2F */+#define FUS_STATE_UPGRADE_LAST 0x2Fu+#define FUS_STATE_ERROR 0xFFu++/* Looks for the footer in data[0..len), word by word from the start (the+ * image begins at data[0]). Returns the image length (up to and including+ * the footer), or 0 when there is none or data[0] is erased flash. */+uint32_t STACKIMG_Find(const uint8_t *data, uint32_t len);++/* Start an install on our own? Only with CPU2 running FUS and idle, an+ * image staged, and fewer than 2 tries since the stack last ran. */+int STACKIMG_ShouldAutoInstall(int fus_running, uint8_t fus_state, uint32_t image_len, uint32_t attempts);++#endif /* STACKIMG_H */diff --git a/firmware/Core/Src/app_entry.c b/firmware/Core/Src/app_entry.cindex e9f20fb..951eb3f 100644--- a/firmware/Core/Src/app_entry.c+++ b/firmware/Core/Src/app_entry.c@@ -21,6 +21,7 @@#include "otp.h"#include "keymap.h"#include "ota.h"+#include "fus.h"RTC_HandleTypeDef hrtc;@@ -44,7 +45,10 @@ void MX_APPE_Config(void)#if (CFG_HW_RESET_BY_FW == 1)/* After a pin reset (not a software one) CPU2 may still be running with* stale IPCC state, so start both clean. */- if (LL_RCC_IsActiveFlag_PINRST() && !LL_RCC_IsActiveFlag_SFTRST())+ /* A watchdog reset also sets PINRST; keep the backup domain (the+ * bootloader's crash count lives there) unless it was a real pin reset. */+ if (LL_RCC_IsActiveFlag_PINRST() && !LL_RCC_IsActiveFlag_SFTRST()+ && !LL_RCC_IsActiveFlag_IWDGRST() && !LL_RCC_IsActiveFlag_WWDGRST()){HAL_PWR_EnableBkUpAccess();__HAL_RCC_BACKUPRESET_FORCE();@@ -157,6 +161,7 @@ int APPE_Cpu2State(void)void MX_APPE_Process(void){+ OTA_Service();UTIL_SEQ_Run(UTIL_SEQ_DEFAULT);}@@ -181,6 +186,7 @@ static void APPE_SysUserEvtRx(void *pPayload)if (p_ready->sysevt_ready_rsp == WIRELESS_FW_RUNNING){cpu2_state = CPU2_BLE;+ FUS_OnCpu2Ready(CPU2_BLE);SHCI_C2_CONFIG_Cmd_Param_t config_param = {0};config_param.PayloadCmdSize = SHCI_C2_CONFIG_PAYLOAD_CMD_SIZE;config_param.EvtMask1 = SHCI_C2_CONFIG_EVTMASK1_BIT0_ERROR_NOTIF_ENABLE@@ -197,7 +203,7 @@ static void APPE_SysUserEvtRx(void *pPayload)/* FUS is running instead of the BLE stack: the stack binary is missing* or was never started. No BLE (and no OTA); STACK? reports it. */cpu2_state = CPU2_FUS;- ((tSHCI_UserEvtRxParam *)pPayload)->status = SHCI_TL_UserEventFlow_Disable;+ FUS_OnCpu2Ready(CPU2_FUS); /* installs a staged stack image, if any */}}diff --git a/firmware/Core/Src/fus.c b/firmware/Core/Src/fus.cnew file mode 100644index 0000000..a3594d7--- /dev/null+++ b/firmware/Core/Src/fus.c@@ -0,0 +1,212 @@+#include <stdio.h>+#include "app_common.h"+#include "main.h"+#include "shci.h"+#include "stm32_seq.h"+#include "app_entry.h"+#include "boot_shared.h"+#include "ota.h"+#include "proto.h"+#include "stackimg.h"+#include "fus.h"++#define CHECK_DELAY_MS 3000 /* after the ready event: let USB CDC enumerate first */+#define POLL_MS 2000 /* ST's BLE_Ota polls every 10 s; 2 s for progress lines */+#define POLL_LIMIT 300 /* 10 min */++static uint8_t timer_id;+static uint8_t auto_check; /* next task run is the boot-time check */+static uint8_t installing;+static uint8_t seen_upgrading;+static uint16_t polls;++static uint32_t Sfsa_Page(void)+{+ return (FLASH->SFR & FLASH_SFR_SFSA) >> FLASH_SFR_SFSA_Pos;+}++/* The staged image: from 0x080D0000 up to the page before SFSA (the one+ * below SFSA is the keymap page, kept clear of the image). */+static uint32_t Image_Len(void)+{+ uint32_t end = FLASH_BASE + (Sfsa_Page() - 1) * FLASH_PAGE_SIZE;+ if (end <= STACKIMG_ADDRESS) return 0; /* stack installed: SFSA moved down to it */+ return STACKIMG_Find((const uint8_t *)STACKIMG_ADDRESS, end - STACKIMG_ADDRESS);+}++static int Upgrading(uint8_t st)+{+ return st >= FUS_STATE_UPGRADE_FIRST && st <= FUS_STATE_UPGRADE_LAST;+}++/* A wireless stack is installed when SFSA has moved down to (or below)+ * the stack's address: FUS moves it on install (0xF4 with FUS alone, 0xD0+ * with the 1.24.0 full stack). Going by SFSA rather than FUS's version+ * field, which isn't defined without a stack. */+static int Stack_Installed(void)+{+ return FLASH_BASE + Sfsa_Page() * FLASH_PAGE_SIZE <= STACKIMG_ADDRESS;+}++static void Schedule(uint32_t ms)+{+ HW_TS_Start(timer_id, MS_TO_TS_TICKS(ms));+}++static void Done(void)+{+ installing = 0;+ BOOT_FUS_BUSY = 0;+}++static void Start(void)+{+ BOOT_FUS_BUSY = BOOT_FUS_BUSY_MAGIC; /* bootloader: don't count resets as crashes now */+ BOOT_FUS_ATTEMPTS = BOOT_FUS_ATTEMPTS + 1;+ PROTO_Send("STACK INSTALL start image=%lu", (unsigned long)Image_Len());+ if (SHCI_C2_FUS_FwUpgrade(0, 0) != SHCI_Success) /* 0, 0: FUS finds the image itself */+ {+ PROTO_Send("ERR STACK FwUpgrade refused");+ Done();+ return;+ }+ installing = 1;+ seen_upgrading = 0;+ polls = 0;+ Schedule(POLL_MS);+}++static void Task(void)+{+ SHCI_FUS_GetState_ErrorCode_t err = 0;++ if (!installing)+ {+ if (!auto_check) return;+ auto_check = 0;+ uint8_t st = SHCI_C2_FUS_GetState(&err);+ if (Upgrading(st))+ {+ /* we came back mid-install (watchdog or reset): keep reporting */+ installing = 1;+ seen_upgrading = 1;+ polls = 0;+ Schedule(POLL_MS);+ return;+ }+ if (st == FUS_STATE_IDLE && Stack_Installed())+ {+ /* Installed but FUS still runs (as after an install): start the+ * stack like ST's BLE_Ota does. CPU2 reboots into it and its ready+ * event brings BLE up. */+ PROTO_Send("STACK starting");+ BOOT_FUS_BUSY = 0;+ SHCI_C2_FUS_StartWs();+ return;+ }+ if (STACKIMG_ShouldAutoInstall(1, st, Image_Len(), BOOT_FUS_ATTEMPTS)) Start();+ else BOOT_FUS_BUSY = 0;+ return;+ }++ uint8_t st = SHCI_C2_FUS_GetState(&err);+ PROTO_Send("STACK PROGRESS state=0x%02X err=0x%02X", st, (unsigned)err);+ if (Upgrading(st))+ {+ seen_upgrading = 1;+ if (++polls < POLL_LIMIT) Schedule(POLL_MS);+ else+ {+ PROTO_Send("ERR STACK timeout, reset the keyword");+ Done();+ }+ return;+ }++ if (st == FUS_STATE_IDLE && Stack_Installed())+ {+ /* ST's BLE_Ota resets here. On the way back up either CPU2 boots the+ * stack (ready event, BLE starts) or FUS is still running and the+ * boot-time check above starts the stack. */+ PROTO_Send("OK STACK installed, resetting");+ OTA_ResetSoon();+ return;+ }+ if (st == FUS_STATE_IDLE && !seen_upgrading && ++polls < 5)+ {+ Schedule(POLL_MS); /* FUS may not have started yet */+ return;+ }+ PROTO_Send("ERR STACK state=0x%02X err=0x%02X", st, (unsigned)err);+ Done();+}++static void Tick(void)+{+ UTIL_SEQ_SetTask(1 << CFG_TASK_FUS_ID, CFG_SCH_PRIO_0);+}++void FUS_OnCpu2Ready(int cpu2_state)+{+ if (cpu2_state == CPU2_BLE)+ {+ BOOT_FUS_BUSY = 0;+ BOOT_FUS_ATTEMPTS = 0;+ return;+ }+ UTIL_SEQ_RegTask(1 << CFG_TASK_FUS_ID, UTIL_SEQ_RFU, Task);+ if (!timer_id) HW_TS_Create(CFG_TIM_PROC_ID_ISR, &timer_id, hw_ts_SingleShot, Tick);+ auto_check = 1;+ Schedule(CHECK_DELAY_MS);+}++int FUS_Busy(void)+{+ return installing;+}++const char *FUS_Install(void)+{+ if (APPE_Cpu2State() != CPU2_FUS) return "CPU2 is not running FUS";+ if (installing) return "already installing";+ if (!Image_Len()) return "no image at 0x080D0000";+ SHCI_FUS_GetState_ErrorCode_t err = 0;+ uint8_t st = SHCI_C2_FUS_GetState(&err);+ if (st != FUS_STATE_IDLE) return "FUS busy";+ BOOT_FUS_ATTEMPTS = 0; /* a manual try starts the count over */+ Start();+ return NULL;+}++void FUS_Info(char *out, size_t n)+{+ WirelessFwInfo_t info;+ int cpu2 = APPE_Cpu2State();+ if (cpu2 == CPU2_UNKNOWN || SHCI_GetWirelessFwInfo(&info) != SHCI_Success)+ {+ snprintf(out, n, "v=unknown state=unknown stack=unknown sfsa=0x%02lX image=%lu",+ (unsigned long)Sfsa_Page(), (unsigned long)Image_Len());+ return;+ }+ char state[8];+ if (cpu2 == CPU2_BLE)+ {+ snprintf(state, sizeof(state), "stack"); /* asking FUS would stop the stack */+ }+ else+ {+ SHCI_FUS_GetState_ErrorCode_t err = 0;+ uint8_t st = installing ? FUS_STATE_UPGRADE_FIRST : SHCI_C2_FUS_GetState(&err);+ if (st == FUS_STATE_IDLE) snprintf(state, sizeof(state), "idle");+ else if (Upgrading(st)) snprintf(state, sizeof(state), "upgrade");+ else snprintf(state, sizeof(state), "0x%02X", st);+ }+ char stack[12] = "none";+ if (Stack_Installed())+ {+ snprintf(stack, sizeof(stack), "%u.%u.%u", info.VersionMajor, info.VersionMinor, info.VersionSub);+ }+ snprintf(out, n, "v=%u.%u.%u state=%s stack=%s sfsa=0x%02lX image=%lu",+ info.FusVersionMajor, info.FusVersionMinor, info.FusVersionSub, state, stack,+ (unsigned long)Sfsa_Page(), (unsigned long)Image_Len());+}diff --git a/firmware/Core/Src/ota.c b/firmware/Core/Src/ota.cindex 5c04d70..3941165 100644--- a/firmware/Core/Src/ota.c+++ b/firmware/Core/Src/ota.c@@ -3,6 +3,7 @@#include "main.h"#include "shci.h"#include "app_entry.h"+#include "boot_shared.h"#include "ota.h"/* The validity tag ST's BLE_Ota checks (CheckFwAppValidity): the word at@@ -11,40 +12,36 @@PLACE_IN_SECTION("TAG_OTA_END") const uint32_t MagicKeywordValue = 0x94448A29;PLACE_IN_SECTION("TAG_OTA_START") const uint32_t MagicKeywordAddress = (uint32_t)&MagicKeywordValue;-/* Boot request in SRAM1, kept across a software reset. Must match- * ota_bootloader/Core/Inc/app_conf.h; RAM1 starts at 0x20000008 in both- * linker scripts so these 8 bytes are never touched otherwise. */-#define REBOOT_ON_BLE_OTA_APP 0x01-#define APP_FIRST_PAGE 7-#define REBOOT_VAL_MSG (*(volatile uint8_t *)(SRAM1_BASE + 0))-#define START_SECTOR_VAL_MSG (*(volatile uint8_t *)(SRAM1_BASE + 1))-#define NBR_OF_SECTOR_VAL_MSG (*(volatile uint8_t *)(SRAM1_BASE + 2))-#define SYSDFU_REQ_WORD (*(volatile uint32_t *)(SRAM1_BASE + 4))-#define SYSDFU_REQ_MAGIC 0x4446553FUL-#define RESET_DELAY_MS 500+enum { RESET_PLAIN, RESET_OTA, RESET_DFU };+static uint8_t reset_timer_id;-static uint8_t want_dfu;+static uint8_t reset_mode;+static uint8_t healthy;static void Reset_Now(void){- if (want_dfu)+ if (reset_mode == RESET_DFU)+ {+ BOOT_SYSDFU_REQ_WORD = BOOT_SYSDFU_REQ_MAGIC;+ }+ else if (reset_mode == RESET_OTA){- SYSDFU_REQ_WORD = SYSDFU_REQ_MAGIC;+ BOOT_REBOOT_VAL_MSG = BOOT_REBOOT_ON_BLE_OTA_APP;+ BOOT_START_SECTOR_MSG = BOOT_APP_FIRST_PAGE;+ BOOT_NBR_OF_SECTOR_MSG = 0xFF; /* the loader clamps this to below the keymap page */}else{- REBOOT_VAL_MSG = REBOOT_ON_BLE_OTA_APP;- START_SECTOR_VAL_MSG = APP_FIRST_PAGE;- NBR_OF_SECTOR_VAL_MSG = 0xFF; /* the loader clamps this to below the keymap page */+ BOOT_REBOOT_VAL_MSG = BOOT_REBOOT_ON_FW_APP;}NVIC_SystemReset();}-static void Reset_Later(uint8_t dfu)+static void Reset_Later(uint8_t mode){- want_dfu = dfu;+ reset_mode = mode;if (!reset_timer_id){HW_TS_Create(CFG_TIM_PROC_ID_ISR, &reset_timer_id, hw_ts_SingleShot, Reset_Now);@@ -59,12 +56,31 @@ int OTA_Available(void)void OTA_Request(void){- Reset_Later(0);+ Reset_Later(RESET_OTA);}void OTA_RequestDfu(void){- Reset_Later(1);+ Reset_Later(RESET_DFU);+}++void OTA_ResetSoon(void)+{+ Reset_Later(RESET_PLAIN);+}++/* Every main loop pass: feed the IWDG the bootloader started (no effect+ * if it didn't), and after BOOT_HEALTHY_MS of running tell the bootloader+ * this app is fine by zeroing its crash count. */+void OTA_Service(void)+{+ IWDG->KR = 0xAAAA;+ if (!healthy && HAL_GetTick() >= BOOT_HEALTHY_MS)+ {+ healthy = 1;+ HAL_PWR_EnableBkUpAccess();+ BOOT_CRASH_COUNT = 0;+ }}void OTA_StackInfo(char *out, size_t n)diff --git a/firmware/Core/Src/proto.c b/firmware/Core/Src/proto.cindex 84749d6..166f0db 100644--- a/firmware/Core/Src/proto.c+++ b/firmware/Core/Src/proto.c@@ -5,6 +5,7 @@#include "batt.h"#include "keybit_image.h"#include "ota.h"+#include "fus.h"#include "proto.h"/* Optional features the desktop app can use, only what's implemented.@@ -175,6 +176,34 @@ static void Handle_Line(proto_port_t *port, char *cmd)Reply(port, "KEYWORD v=%s proto=1 caps=%s%s kb=%u", KEYWORD_FW_VERSION, CAPS,OTA_Available() ? ",ota" : "", keybit_image_version);}+#ifdef KEYWORD_DEBUG_CMDS+ else if (strcmp(cmd, "CRASH") == 0 && port->local)+ {+ /* Test for the bootloader's crash fallback: hang until the IWDG resets+ * us. Three in a row should end in ROM USB DFU. Debug builds only. */+ Reply(port, "OK CRASH");+ for (volatile uint32_t i = 0; i < 2000000; i++); /* let the reply out */+ while (1);+ }+#endif+ else if (strcmp(cmd, "FUS?") == 0)+ {+ char info[96];+ FUS_Info(info, sizeof(info));+ Reply(port, "FUS %s", info);+ }+ else if (strcmp(cmd, "STACK") == 0 && strcmp(args, "INSTALL") == 0)+ {+ /* Hands CPU2's flash to FUS: only from someone at the USB cable */+ if (!port->local)+ {+ Reply(port, "ERR STACK INSTALL is USB only");+ return;+ }+ const char *why = FUS_Install();+ if (why) Reply(port, "ERR %s", why);+ else Reply(port, "OK STACK INSTALL");+ }else if (strcmp(cmd, "STACK?") == 0){char info[48];@@ -346,6 +375,13 @@ static void Handle_Line(proto_port_t *port, char *cmd)}else if (strcmp(cmd, "SAVE") == 0){+ /* Without the BLE stack the keymap page (SFSA - 1) moves when the stack+ * gets installed, and FUS may be writing flash: don't save then. */+ if (!OTA_Available() || FUS_Busy())+ {+ Reply(port, "ERR no BLE stack yet, keymap not saved");+ return;+ }if (KEYMAP_Save() != 0) Reply(port, "ERR flash write failed");else Reply(port, "OK SAVE");}diff --git a/firmware/Core/Src/stackimg.c b/firmware/Core/Src/stackimg.cnew file mode 100644index 0000000..b7f1b28--- /dev/null+++ b/firmware/Core/Src/stackimg.c@@ -0,0 +1,25 @@+#include "stackimg.h"++static uint32_t Word(const uint8_t *p)+{+ return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;+}++uint32_t STACKIMG_Find(const uint8_t *data, uint32_t len)+{+ if (len < STACKIMG_FOOTER_LEN || Word(data) == 0xFFFFFFFFu) return 0;+ for (uint32_t off = 0; off + STACKIMG_FOOTER_LEN <= len; off += 4)+ {+ if (Word(data + off) == 0x12341234u && Word(data + off + 4) == 0xABCDABCDu+ && Word(data + off + 8) == 0xFFFF5740u && Word(data + off + 16) == 0xD3A12C5Eu)+ {+ return off + STACKIMG_FOOTER_LEN;+ }+ }+ return 0;+}++int STACKIMG_ShouldAutoInstall(int fus_running, uint8_t fus_state, uint32_t image_len, uint32_t attempts)+{+ return fus_running && fus_state == FUS_STATE_IDLE && image_len > 0 && attempts < 2;+}diff --git a/firmware/README.md b/firmware/README.mdindex 44244f8..4fa0676 100644--- a/firmware/README.md+++ b/firmware/README.md@@ -57,19 +57,30 @@ the app asked for an update.### First install over USB DFU-This needs the CPU2 BLE stack already installed (see "First flash: the CPU2 BLE-stack" below). Put the keyword in DFU, then write `keyword_full.bin` at-0x08000000. Either of these only erases the pages the image covers (about 23 of-them), so the keymap page and CPU2's area stay as they are. No option bytes,-no full chip erase:+> **Warning: over USB DFU, only ever use plain writes (`-d ... -v`) and reads.**+> STM32CubeProgrammer's "run after programming" steps rewrite the option bytes+> over USB: `-startfus` set `nSWBOOT0=0` on this board, which makes it boot+> from flash and ignore BOOT0 from then on. Never use `-g`/`--go`, `-s`, `-rst`,+> `-startfus`, `-fwupgrade`, `-startwirelessstack`, `-ob ...` or dfu-util's+> `:leave` over USB. Leave DFU by unplugging and plugging the keyword back in.++Two plain writes. Neither erases anything but the pages it covers, so the+keymap page and CPU2's area stay as they are:```sh+# bootloader + appSTM32_Programmer_CLI -c port=usb1 -d release/keyword_full.bin 0x08000000 -v-# or-dfu-util -a 0 -d 0483:df11 -s 0x08000000:leave -D release/keyword_full.bin+# CPU2 BLE stack 1.24.0 (from STM32CubeWB, see below), only as data for now+STM32_Programmer_CLI -c port=usb1 -d stm32wb5x_BLE_Stack_full_fw.bin 0x080D0000 -v```-After this every update goes over Bluetooth.+`dfu-util -a 0 -d 0483:df11 -s 0x08000000 -D release/keyword_full.bin` works+too (no `:leave`). Then unplug and plug the keyword back in.++On that first boot the app comes up on USB serial first, then finds the stack+image at 0x080D0000 and has FUS install it, printing `STACK PROGRESS ...` lines+over USB serial. It resets once when it's done and comes back as the Bluetooth+keyboard **Keyword**. `FUS?` and `STACK?` show where it is.### Updating over BLE@@ -90,7 +101,12 @@ Send `DFU` over USB serial or BLE. The keyword answers `OK DFU`, resets, and thebootloader starts ST's ROM USB DFU bootloader (system memory at 0x1FFF0000)straight out of the reset, so it shows up as `0483:df11` without touching BOOT0or the option bytes. The bootloader also does this by itself if CPU2 has no BLE-stack, since then OTA can't work. A reset out of DFU boots the app again.+stack and the app is broken. A reset out of DFU boots the app again.++The bootloader also starts an 8 s watchdog before it runs the app, and the app+feeds it from its main loop. If the app hangs or crashes three times in a row+(before it has run 10 s), the bootloader goes to USB DFU instead, so a bad app+can't lock the keyword out.### ST-Link over SWD@@ -169,32 +185,25 @@ cc -std=c99 -ICore/Inc test/keyact_test.c Core/Src/keyact.c -o /tmp/keyact_testcc -std=c99 -Itest/stub -ICore/Inc test/batt_test.c Core/Src/batt.c -o /tmp/batt_test && /tmp/batt_test```-### First flash: the CPU2 BLE stack--The radio runs on the second core (CPU2), which needs ST's BLE stack flashed-once with STM32CubeProgrammer 2.20 or newer. The binaries are in-[STM32CubeWB](https://github.com/STMicroelectronics/STM32CubeWB) under-`Projects/STM32WB_Copro_Wireless_Binaries/STM32WB5x`. The 1.24.0 stack needs-FUS v2, so check that first:--```sh-STM32_Programmer_CLI -c port=SWD -startfus-STM32_Programmer_CLI -c port=SWD mode=UR -r32 0x20030030 1 # 0x0202xx00 = FUS v2.2, good-```--If it reads `0x0102xx00` (FUS v1.2), update FUS first. If it is older than-v1.2, go through `stm32wb5x_FUS_fw_1_2_0.bin` at 0x080EC000 first.+### The CPU2 BLE stack-```sh-STM32_Programmer_CLI -c port=SWD mode=UR -fwupgrade stm32wb5x_FUS_fw.bin 0x080EE000 firstinstall=0-```+The radio runs on CPU2, which needs ST's BLE stack. The keyword installs it+itself, so it never needs `-startfus` or `-fwupgrade` (see the warning above):-Then the stack itself (addresses are for the 1 MB STM32WB55RG):+1. Write `stm32wb5x_BLE_Stack_full_fw.bin` (1.24.0, 129460 bytes, SHA-256+ b7855d9ce0b012fabff5782a574a3038e6e5b1889c5c9bcdb06c2cab2201c05d) to+ 0x080D0000 over DFU as above. It's in+ [STM32CubeWB](https://github.com/STMicroelectronics/STM32CubeWB) under+ `Projects/STM32WB_Copro_Wireless_Binaries/STM32WB5x`. It isn't in this repo:+ ST's SLA0044 doesn't allow it in an MIT licensed project.+2. When CPU2 boots with only FUS (no stack), the app checks 0x080D0000 for ST's+ image footer and asks FUS to install it (`SHCI_C2_FUS_FwUpgrade`, ST's+ CPU1-driven path). FUS moves SFSA down to 0xD0 itself. Over USB serial, `FUS?`+ shows `v=<fus> state=<idle|upgrade> stack=<version|none> sfsa=<page>+ image=<bytes>`, and `STACK INSTALL` starts it by hand.+3. Then the app resets and starts the stack. `STACK?` should answer+ `STACK ble v=1.24.0 fus=2.2.0`.-```sh-STM32_Programmer_CLI -c port=SWD mode=UR -fwupgrade stm32wb5x_BLE_Stack_full_fw.bin 0x080D0000 firstinstall=0-```+This board has FUS 2.2.0, which the 1.24.0 stack needs, so no FUS update.+Until the stack runs, `SAVE` is refused, since the keymap page moves with SFSA.-ST's notes end by setting nSWBOOT0 back to 1, skip that here or the floating-BOOT0 comes back. After this the app flashes as normal with the steps above.-If the stack is missing the app still runs, it just never advertises.diff --git a/firmware/STM32-for-VSCode.config.yaml b/firmware/STM32-for-VSCode.config.yamlindex 9ac4197..3dbb652 100644--- a/firmware/STM32-for-VSCode.config.yaml+++ b/firmware/STM32-for-VSCode.config.yaml@@ -83,6 +83,7 @@ includeDirectories:- Core/Src/**- Core/Lib/**- Drivers/CH32V003+ - Shared- STM32_WPAN/App- Middlewares/ST/STM32_WPAN- Middlewares/ST/STM32_WPAN/blediff --git a/firmware/STM32Make.make b/firmware/STM32Make.makeindex 6113d37..1d160af 100644--- a/firmware/STM32Make.make+++ b/firmware/STM32Make.make@@ -78,7 +78,9 @@ C_SOURCES = \Core/Src/keybit_bus.c \Core/Src/keybit_image.c \Core/Src/main.c \+Core/Src/fus.c \Core/Src/ota.c \+Core/Src/stackimg.c \Core/Src/stm32wbxx_hal_msp.c \Core/Src/stm32wbxx_it.c \Core/Src/syscalls.c \@@ -243,6 +245,7 @@ AS_INCLUDES = \# C includesC_INCLUDES = \-ICore/Inc \+-IShared \-IDrivers/CH32V003 \-IDrivers/CMSIS/Device/ST/STM32WBxx/Include \-IDrivers/CMSIS/Include \diff --git a/firmware/Shared/boot_shared.h b/firmware/Shared/boot_shared.hnew file mode 100644index 0000000..1d9ec65--- /dev/null+++ b/firmware/Shared/boot_shared.h@@ -0,0 +1,45 @@+/*+ * What the app and the OTA bootloader (ota_bootloader/) agree on. Both+ * build with -IShared, so this is the one copy.+ */+#ifndef BOOT_SHARED_H+#define BOOT_SHARED_H++#include <stdint.h>++/* ---- flash ---- */+#define BOOT_APP_FIRST_PAGE 7u /* app at 0x08007000 */+#define BOOT_APP_ADDRESS (0x08000000u + BOOT_APP_FIRST_PAGE * 0x1000u)++/* ---- boot request in SRAM1, kept across a software reset ----+ * ST's BLE_Ota bytes at SRAM1 + 0..2, plus the ROM DFU word at + 4. RAM1+ * starts at 0x20000008 in both linker scripts so nothing else uses them. */+#define BOOT_REBOOT_ON_FW_APP 0x00u+#define BOOT_REBOOT_ON_BLE_OTA_APP 0x01u+#define BOOT_REBOOT_VAL_MSG (*(volatile uint8_t *)(0x20000000u + 0))+#define BOOT_START_SECTOR_MSG (*(volatile uint8_t *)(0x20000000u + 1))+#define BOOT_NBR_OF_SECTOR_MSG (*(volatile uint8_t *)(0x20000000u + 2))+#define BOOT_SYSDFU_REQ_WORD (*(volatile uint32_t *)(0x20000000u + 4))+#define BOOT_SYSDFU_REQ_MAGIC 0x4446553Fu /* "?UFD" */++/* ---- crash fallback, in RTC backup registers (kept across any reset but+ * a backup domain reset, which the app only does on a real pin reset) ----+ * The bootloader starts the IWDG before jumping to the app, and counts+ * watchdog resets in BOOT_CRASH_COUNT. At BOOT_CRASH_LIMIT in a row it+ * goes to ROM USB DFU instead of the app. The app feeds the IWDG from its+ * main loop and zeroes the count once it has run BOOT_HEALTHY_MS. While+ * BOOT_FUS_BUSY holds BOOT_FUS_BUSY_MAGIC (a CPU2 stack install in+ * progress, where a stuck SHCI call is expected) resets aren't counted. */+#define BOOT_CRASH_COUNT (RTC->BKP19R)+#define BOOT_FUS_BUSY (RTC->BKP18R)+#define BOOT_FUS_ATTEMPTS (RTC->BKP17R)+#define BOOT_FUS_BUSY_MAGIC 0x46555342u /* "BSUF" */+#define BOOT_CRASH_LIMIT 3u+#define BOOT_HEALTHY_MS 10000u++/* IWDG: LSI ~32 kHz / 256 = 125 Hz, reload 1000 -> about 8 s. Longer than+ * any blocking path in the app (dock flash 1-2 s, keymap SAVE < 1 s). */+#define BOOT_IWDG_PR 6u+#define BOOT_IWDG_RLR 1000u++#endif /* BOOT_SHARED_H */diff --git a/firmware/USB_Device/App/usbd_cdc_if.c b/firmware/USB_Device/App/usbd_cdc_if.cindex 5c8aa9e..5937ab6 100644--- a/firmware/USB_Device/App/usbd_cdc_if.c+++ b/firmware/USB_Device/App/usbd_cdc_if.c@@ -38,7 +38,7 @@ static volatile uint16_t tx_head, tx_tail;static uint8_t line_coding[7] = {0x00, 0xC2, 0x01, 0x00, 0x00, 0x00, 0x08};static void CDC_Write(const char *data, uint16_t len);-static proto_port_t cdc_port = {.write = CDC_Write};+static proto_port_t cdc_port = {.write = CDC_Write, .local = 1};static uint16_t Rx_Free(void){diff --git a/firmware/ota_bootloader/Core/Inc/app_conf.h b/firmware/ota_bootloader/Core/Inc/app_conf.hindex 5bbe886..ecf3c67 100644--- a/firmware/ota_bootloader/Core/Inc/app_conf.h+++ b/firmware/ota_bootloader/Core/Inc/app_conf.h@@ -10,29 +10,27 @@#include "hw_conf.h"#include "hw_if.h"#include "ble_bufsize.h"+#include "boot_shared.h"/* ---- flash map ----* 0x08000000 this bootloader, pages 0-6 (28 KB)* 0x08007000 the keyword app, page 7 up to the keymap page* SFSA - 1 the app's saved keymap, never erased or written here* SFSA CPU2 (BLE stack, FUS), never touched */-#define CFG_APP_START_SECTOR_INDEX (7)-#define CFG_APP_START_ADDRESS (FLASH_BASE + CFG_APP_START_SECTOR_INDEX * FLASH_PAGE_SIZE)+#define CFG_APP_START_SECTOR_INDEX (BOOT_APP_FIRST_PAGE)+#define CFG_APP_START_ADDRESS (BOOT_APP_ADDRESS)#define CFG_APP_TAG_OFFSET (0x140) /* word holding the address of the 0x94448A29 tag */#define CFG_APP_MAGIC (0x94448A29UL)-/* ---- boot request in SRAM1, kept across a software reset ----- * Same bytes as ST's BLE_Ota (SRAM1_BASE + 0..2), so the app sets them the- * same way. The DFU word at + 4 is the keyword's addition; RAM1 in both- * linker scripts starts at 0x20000008 so nothing else lives there. */-#define CFG_REBOOT_ON_FW_APP (0x00)-#define CFG_REBOOT_ON_BLE_OTA_APP (0x01)-#define CFG_REBOOT_ON_CPU2_UPGRADE (0x02)-#define CFG_OTA_REBOOT_VAL_MSG (*(volatile uint8_t *)(SRAM1_BASE + 0))-#define CFG_OTA_START_SECTOR_IDX_VAL_MSG (*(volatile uint8_t *)(SRAM1_BASE + 1))-#define CFG_OTA_NBR_OF_SECTOR_VAL_MSG (*(volatile uint8_t *)(SRAM1_BASE + 2))-#define CFG_SYSDFU_REQ_WORD (*(volatile uint32_t *)(SRAM1_BASE + 4))-#define CFG_SYSDFU_REQ_MAGIC (0x4446553FUL) /* "?UFD" */+/* ---- boot request in SRAM1 (Shared/boot_shared.h), names as in ST's code ---- */+#define CFG_REBOOT_ON_FW_APP BOOT_REBOOT_ON_FW_APP+#define CFG_REBOOT_ON_BLE_OTA_APP BOOT_REBOOT_ON_BLE_OTA_APP+#define CFG_REBOOT_ON_CPU2_UPGRADE (0x02)+#define CFG_OTA_REBOOT_VAL_MSG BOOT_REBOOT_VAL_MSG+#define CFG_OTA_START_SECTOR_IDX_VAL_MSG BOOT_START_SECTOR_MSG+#define CFG_OTA_NBR_OF_SECTOR_VAL_MSG BOOT_NBR_OF_SECTOR_MSG+#define CFG_SYSDFU_REQ_WORD BOOT_SYSDFU_REQ_WORD+#define CFG_SYSDFU_REQ_MAGIC BOOT_SYSDFU_REQ_MAGIC/* ---- GAP ---- */#define CFG_TX_POWER (0x18) /* -0.15 dBm */diff --git a/firmware/ota_bootloader/Core/Inc/main.h b/firmware/ota_bootloader/Core/Inc/main.hindex 2580f66..7a6519c 100644--- a/firmware/ota_bootloader/Core/Inc/main.h+++ b/firmware/ota_bootloader/Core/Inc/main.h@@ -9,4 +9,10 @@ void Error_Handler(void);/* Reset into ST's ROM USB DFU bootloader (system memory). See main.c. */void BOOT_RequestSystemDfu(void);+/* OTA can't run: reset into the app if it's valid, else into ROM DFU. */+void BOOT_LeaveLoader(void);++/* system_stm32wbxx.c: 1 if the app at 0x08007000 carries a valid tag. */+uint8_t BOOT_AppValid(void);+#endif /* MAIN_H */diff --git a/firmware/ota_bootloader/Core/Src/app_entry.c b/firmware/ota_bootloader/Core/Src/app_entry.cindex 106e217..85a509e 100644--- a/firmware/ota_bootloader/Core/Src/app_entry.c+++ b/firmware/ota_bootloader/Core/Src/app_entry.c@@ -2,9 +2,9 @@* CPU2 boot and transport layer for the OTA bootloader, from ST's BLE_Ota* app_entry.c. The difference: when CPU2 comes up running FUS instead of* the BLE stack, ST's version tells FUS to install whatever it finds in- * flash. Here there is no BLE stack to do an OTA with, so it resets into- * the ROM USB DFU bootloader instead and never starts a FUS operation- * (those can move SFSA).+ * flash. Here there is no BLE stack to do an OTA with, so it goes back to+ * the app if the app is valid (the app installs the stack itself), or to+ * the ROM USB DFU bootloader if not. It never starts a FUS operation.*/#include "app_common.h"#include "main.h"@@ -46,7 +46,7 @@ static void APPE_SysUserEvtRx(void *pPayload)else{((tSHCI_UserEvtRxParam *)pPayload)->status = SHCI_TL_UserEventFlow_Disable;- BOOT_RequestSystemDfu(); /* no BLE stack: USB DFU is the only way in */+ BOOT_LeaveLoader(); /* no BLE stack, no OTA: app if valid, else USB DFU */}}diff --git a/firmware/ota_bootloader/Core/Src/main.c b/firmware/ota_bootloader/Core/Src/main.cindex 1176f32..e06872e 100644--- a/firmware/ota_bootloader/Core/Src/main.c+++ b/firmware/ota_bootloader/Core/Src/main.c@@ -19,7 +19,10 @@ RTC_HandleTypeDef hrtc;* stale IPCC state after a pin reset. */static void Reset_Device(void){- if (LL_RCC_IsActiveFlag_PINRST() && !LL_RCC_IsActiveFlag_SFTRST())+ /* A watchdog reset also sets PINRST; keep the backup domain (the crash+ * count lives there) unless it was a real pin reset. */+ if (LL_RCC_IsActiveFlag_PINRST() && !LL_RCC_IsActiveFlag_SFTRST()+ && !LL_RCC_IsActiveFlag_IWDGRST() && !LL_RCC_IsActiveFlag_WWDGRST()){HAL_PWR_EnableBkUpAccess();__HAL_RCC_BACKUPRESET_FORCE();@@ -95,8 +98,18 @@ void BOOT_RequestSystemDfu(void)NVIC_SystemReset();}-void Error_Handler(void)+void BOOT_LeaveLoader(void){- /* Can't run BLE: fall back to USB DFU so the keyword stays recoverable. */+ if (BOOT_AppValid())+ {+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_FW_APP; /* SystemInit jumps to it */+ NVIC_SystemReset();+ }BOOT_RequestSystemDfu();}++void Error_Handler(void)+{+ /* Can't run BLE: back to the app if there is one, else USB DFU. */+ BOOT_LeaveLoader();+}diff --git a/firmware/ota_bootloader/Core/Src/system_stm32wbxx.c b/firmware/ota_bootloader/Core/Src/system_stm32wbxx.cindex b247df1..4b21f97 100644--- a/firmware/ota_bootloader/Core/Src/system_stm32wbxx.c+++ b/firmware/ota_bootloader/Core/Src/system_stm32wbxx.c@@ -211,6 +211,9 @@ static void JumpSelectionOnPowerUp( void );static uint8_t CheckFwAppValidity( void );+/* For app_entry.c / main.c: 1 if the app at 0x08007000 is valid. */+uint8_t BOOT_AppValid( void );+static uint8_t CheckFwAppValidity( void ){uint8_t status;@@ -251,10 +254,33 @@ static uint8_t CheckFwAppValidity( void )* Jump to existing FW App in flash* It never returns*/+uint8_t BOOT_AppValid( void )+{+ return CheckFwAppValidity();+}++/**+ * Keyword: start the IWDG (about 8 s) just before handing over to the app,+ * so an app that hangs gets reset and counted (see BootModeCheck). The app+ * feeds it from its main loop. Once started it can't be stopped until the+ * next reset.+ */+static void StartAppWatchdog( void )+{+ IWDG->KR = 0xCCCC; /* start (also starts the LSI) */+ IWDG->KR = 0x5555; /* unlock PR/RLR */+ IWDG->PR = BOOT_IWDG_PR;+ IWDG->RLR = BOOT_IWDG_RLR;+ while (IWDG->SR != 0);+ IWDG->KR = 0xAAAA; /* reload */+}+static void JumpFwApp( void ){fct_t app_reset_handler;+ StartAppWatchdog();+SCB->VTOR = FLASH_BASE + (CFG_APP_START_SECTOR_INDEX * 0x1000);__set_MSP(*(uint32_t*)(FLASH_BASE + (CFG_APP_START_SECTOR_INDEX * 0x1000)));app_reset_handler = (fct_t)(*(uint32_t*)(FLASH_BASE + (CFG_APP_START_SECTOR_INDEX * 0x1000) + 4));@@ -298,12 +324,53 @@ static void JumpSystemDfu( void )__WFI(); /* never reached, see JumpFwApp() */}+/**+ * Keyword crash fallback: count resets the app caused (IWDG or WWDG) in an+ * RTC backup register. A software reset leaves the count alone, any other+ * reset (power, pin) clears it, and the app clears it after running+ * BOOT_HEALTHY_MS. At BOOT_CRASH_LIMIT the app is skipped for ROM DFU, the+ * only way back in once BOOT0 is ignored. Resets during a CPU2 stack+ * install (BOOT_FUS_BUSY) aren't counted. Returns 1 to go to DFU.+ */+static uint8_t CrashLoopCheck( void )+{+ uint32_t csr = RCC->CSR;+ RCC->APB1ENR1 |= RCC_APB1ENR1_RTCAPBEN; /* backup registers */+ (void)RCC->APB1ENR1;+ PWR->CR1 |= PWR_CR1_DBP; /* allow writing them */++ if (csr & (RCC_CSR_IWDGRSTF | RCC_CSR_WWDGRSTF))+ {+ if (BOOT_FUS_BUSY != BOOT_FUS_BUSY_MAGIC)+ {+ BOOT_CRASH_COUNT = BOOT_CRASH_COUNT + 1;+ }+ }+ else if (!(csr & RCC_CSR_SFTRSTF))+ {+ BOOT_CRASH_COUNT = 0;+ }++ if (BOOT_CRASH_COUNT >= BOOT_CRASH_LIMIT)+ {+ BOOT_CRASH_COUNT = 0;+ return 1;+ }+ return 0;+}+static void BootModeCheck( void ){+ if (CrashLoopCheck())+ {+ CFG_SYSDFU_REQ_WORD = 0;+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_FW_APP;+ JumpSystemDfu();+ }+/**- * Keyword: the app (DFU command) or this loader (no BLE stack) asked for- * the ROM USB DFU bootloader. The magic is cleared first, so a reset out- * of DFU boots normally again.+ * Keyword: the app asked for the ROM USB DFU bootloader (DFU command).+ * The magic is cleared first, so a reset out of DFU boots normally again.*/if(LL_RCC_IsActiveFlag_SFTRST( ) && (CFG_SYSDFU_REQ_WORD == CFG_SYSDFU_REQ_MAGIC)){diff --git a/firmware/ota_bootloader/Makefile b/firmware/ota_bootloader/Makefileindex 12bc740..fe16c11 100644--- a/firmware/ota_bootloader/Makefile+++ b/firmware/ota_bootloader/Makefile@@ -66,6 +66,7 @@ ASM_SOURCES = startup_stm32wb55xx_cm4.sC_INCLUDES = \-ICore/Inc \+-I$(FW)/Shared \-ISTM32_WPAN/App \-I$(FW)/Drivers/CMSIS/Device/ST/STM32WBxx/Include \-I$(FW)/Drivers/CMSIS/Include \diff --git a/firmware/test/proto_test.c b/firmware/test/proto_test.cindex 48bd42a..d4fe352 100644--- a/firmware/test/proto_test.c+++ b/firmware/test/proto_test.c@@ -15,7 +15,7 @@static char out[2048], out2[2048];static void write1(const char *data, uint16_t len) { strncat(out, data, len); }static void write2(const char *data, uint16_t len) { strncat(out2, data, len); }-static proto_port_t port = {.write = write1};+static proto_port_t port = {.write = write1, .local = 1}; /* like USB CDC */static proto_port_t port2 = {.write = write2};/* The real keytable.c is linked; the bus side of keymap.c is faked. */@@ -27,6 +27,11 @@ int OTA_Available(void) { return stack_ok; }void OTA_Request(void) { ota_asked++; }void OTA_RequestDfu(void) { dfu_asked++; }void OTA_StackInfo(char *out, size_t n) { snprintf(out, n, stack_ok ? "ble v=1.24.0 fus=2.2.0" : "none fus=2.2.0"); }+static int fus_installs;+static const char *fus_refuse;+void FUS_Info(char *out, size_t n) { snprintf(out, n, "v=2.2.0 state=idle stack=none sfsa=0xF4 image=129460"); }+const char *FUS_Install(void) { if (fus_refuse) return fus_refuse; fus_installs++; return NULL; }+int FUS_Busy(void) { return 0; }static batt_t batt_fake;const batt_t *BATT_Get(void) { return &batt_fake; }int KEYMAP_Save(void) { return 0; }@@ -213,7 +218,23 @@ int main(void)assert(ota_asked == 1);expect("DFU\n", "OK DFU\n");assert(dfu_asked == 1);+ /* FUS? and STACK INSTALL (USB only) */+ expect("FUS?\n", "FUS v=2.2.0 state=idle stack=none sfsa=0xF4 image=129460\n");+ expect("STACK INSTALL\n", "OK STACK INSTALL\n");+ assert(fus_installs == 1);+ fus_refuse = "no image at 0x080D0000";+ expect("STACK INSTALL\n", "ERR no image at 0x080D0000\n");+ fus_refuse = NULL;+ expect("STACK BOGUS\n", "ERR unknown command\n");+ out2[0] = 0;+ PROTO_Input(&port2, (const uint8_t *)"STACK INSTALL\n", 14); /* port2 is like NUS */+ assert(strcmp(out2, "ERR STACK INSTALL is USB only\n") == 0 && fus_installs == 1);+ out2[0] = 0;+ PROTO_Input(&port2, (const uint8_t *)"FUS?\n", 5); /* reading is fine anywhere */+ assert(strncmp(out2, "FUS v=2.2.0", 11) == 0);+stack_ok = 0; /* FUS only, no BLE stack: no OTA, and HELLO says so */+ expect("SAVE\n", "ERR no BLE stack yet, keymap not saved\n");expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro kb=3\n");expect("STACK?\n", "STACK none fus=2.2.0\n");expect("OTA\n", "ERR no BLE stack on CPU2, use DFU\n");diff --git a/firmware/test/stackimg_test.c b/firmware/test/stackimg_test.cnew file mode 100644index 0000000..5859602--- /dev/null+++ b/firmware/test/stackimg_test.c@@ -0,0 +1,81 @@+/*+ * Host check for Core/Src/stackimg.c with a made-up image that ends in+ * ST's CPU2 footer (the same layout as stm32wb5x_BLE_Stack_full_fw.bin).+ * cc -std=c99 -ICore/Inc test/stackimg_test.c Core/Src/stackimg.c -o /tmp/stackimg_test && /tmp/stackimg_test+ *+ * With a real binary as argument it also checks that one:+ * /tmp/stackimg_test stm32wb5x_BLE_Stack_full_fw.bin+ */+#include <assert.h>+#include <stdio.h>+#include <string.h>+#include "stackimg.h"++static uint8_t flash[0x2000];++static void put(uint32_t off, uint32_t w)+{+ flash[off] = (uint8_t)w;+ flash[off + 1] = (uint8_t)(w >> 8);+ flash[off + 2] = (uint8_t)(w >> 16);+ flash[off + 3] = (uint8_t)(w >> 24);+}++int main(int argc, char **argv)+{+ /* erased flash: nothing */+ memset(flash, 0xFF, sizeof(flash));+ assert(STACKIMG_Find(flash, sizeof(flash)) == 0);++ /* an image of 0x1234 bytes (word sized, like ST's) with the footer at its end */+ for (uint32_t i = 0; i < 0x1234 - STACKIMG_FOOTER_LEN; i++) flash[i] = (uint8_t)(i * 7);+ put(0, 0x20030000); /* first word not erased */+ uint32_t f = 0x1234 - STACKIMG_FOOTER_LEN;+ put(f, 0x12341234);+ put(f + 4, 0xABCDABCD);+ put(f + 8, 0xFFFF5740);+ put(f + 12, 0x22110045);+ put(f + 16, 0xD3A12C5E);+ assert(STACKIMG_Find(flash, sizeof(flash)) == 0x1234);++ /* a broken magic or a missing marker word is not an image */+ put(f + 16, 0xD3A12C5F);+ assert(STACKIMG_Find(flash, sizeof(flash)) == 0);+ put(f + 16, 0xD3A12C5E);+ put(f + 4, 0xABCDABCE);+ assert(STACKIMG_Find(flash, sizeof(flash)) == 0);+ put(f + 4, 0xABCDABCD);++ /* footer must fit in the window */+ assert(STACKIMG_Find(flash, 0x1234 - 1) == 0);+ assert(STACKIMG_Find(flash, 0x1234) == 0x1234);++ /* first word erased: nothing staged even if a footer is somewhere */+ put(0, 0xFFFFFFFF);+ assert(STACKIMG_Find(flash, sizeof(flash)) == 0);++ /* auto install only when FUS runs, is idle, an image is there, < 2 tries */+ assert(STACKIMG_ShouldAutoInstall(1, FUS_STATE_IDLE, 0x1234, 0));+ assert(STACKIMG_ShouldAutoInstall(1, FUS_STATE_IDLE, 0x1234, 1));+ assert(!STACKIMG_ShouldAutoInstall(1, FUS_STATE_IDLE, 0x1234, 2));+ assert(!STACKIMG_ShouldAutoInstall(0, FUS_STATE_IDLE, 0x1234, 0)); /* stack already running */+ assert(!STACKIMG_ShouldAutoInstall(1, 0x10, 0x1234, 0)); /* already upgrading */+ assert(!STACKIMG_ShouldAutoInstall(1, FUS_STATE_ERROR, 0x1234, 0));+ assert(!STACKIMG_ShouldAutoInstall(1, FUS_STATE_IDLE, 0, 0)); /* nothing staged */++ if (argc > 1)+ {+ static uint8_t img[0x40000];+ FILE *fp = fopen(argv[1], "rb");+ assert(fp);+ size_t n = fread(img, 1, sizeof(img), fp);+ fclose(fp);+ memset(img + n, 0xFF, sizeof(img) - n); /* erased flash after it */+ uint32_t got = STACKIMG_Find(img, sizeof(img));+ printf("%s: %zu bytes, footer found -> %u bytes\n", argv[1], n, got);+ assert(got == n);+ }++ puts("stackimg_test: ok");+ return 0;+}