A truly modular keyboard
C
firmware: app at 0x08007000 behind the OTA bootloader, OTA/DFU/STACK? commands
Nathanbfc1a20f6367
diff --git a/firmware/Core/Inc/app_entry.h b/firmware/Core/Inc/app_entry.hindex f69e85c..bcf0c42 100644--- a/firmware/Core/Inc/app_entry.h+++ b/firmware/Core/Inc/app_entry.h@@ -61,6 +61,8 @@ void Init_Exti(void);void Init_Smps(void);/* USER CODE BEGIN EF */+/* CPU2_UNKNOWN / CPU2_BLE / CPU2_FUS (ota.h), from CPU2's ready event */+int APPE_Cpu2State(void);/* USER CODE END EF */diff --git a/firmware/Core/Inc/ota.h b/firmware/Core/Inc/ota.hnew file mode 100644index 0000000..cc4cd88--- /dev/null+++ b/firmware/Core/Inc/ota.h@@ -0,0 +1,27 @@+/*+ * Hand-off to the OTA bootloader in ota_bootloader/ (pages 0-6) and to+ * ST's ROM USB DFU bootloader. Both go through a software reset with a+ * request left in SRAM1, which the bootloader reads in SystemInit.+ */+#ifndef OTA_H+#define OTA_H++#include <stddef.h>++/* CPU2 state as of its ready event. */+enum { CPU2_UNKNOWN = 0, CPU2_BLE = 1, CPU2_FUS = 2 };++/* 1 when the CPU2 BLE stack runs, which the OTA bootloader needs. */+int OTA_Available(void);++/* Reset into the bootloader's OTA mode ("Keyword OTA") in 500 ms, so the+ * reply that asked for it can still go out. It erases the app first. */+void OTA_Request(void);++/* Reset into the ROM USB DFU bootloader in 500 ms. No option bytes. */+void OTA_RequestDfu(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);++#endif /* OTA_H */diff --git a/firmware/Core/Src/app_entry.c b/firmware/Core/Src/app_entry.cindex 0fc134c..e9f20fb 100644--- a/firmware/Core/Src/app_entry.c+++ b/firmware/Core/Src/app_entry.c@@ -20,6 +20,7 @@#include "shci.h"#include "otp.h"#include "keymap.h"+#include "ota.h"RTC_HandleTypeDef hrtc;@@ -31,6 +32,7 @@ PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static uint8_t SystemSpareEvtBuffer[sizeof(PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static uint8_t BleSpareEvtBuffer[sizeof(TL_PacketHeader_t) + TL_EVT_HDR_SIZE + 255U];static void APPE_SysUserEvtRx(void *pPayload);+static uint8_t cpu2_state = CPU2_UNKNOWN;static void APPE_SysStatusNot(SHCI_TL_CmdStatus_t status);/* Runs before SystemClock_Config: the backup domain reset has to happen@@ -59,6 +61,10 @@ void MX_APPE_Config(void)LL_C2_IPCC_DisableReceiveChannel(IPCC, ch);#endif+ /* The OTA bootloader trusts its SRAM1 request only after a software+ * reset, so every boot must start from fresh flags. */+ __HAL_RCC_CLEAR_RESET_FLAGS();+OTP_ID0_t *p_otp = (OTP_ID0_t *)OTP_Read(0);if (p_otp){@@ -144,6 +150,11 @@ void MX_APPE_Init(void)TL_Enable();}+int APPE_Cpu2State(void)+{+ return cpu2_state;+}+void MX_APPE_Process(void){UTIL_SEQ_Run(UTIL_SEQ_DEFAULT);@@ -169,6 +180,7 @@ static void APPE_SysUserEvtRx(void *pPayload)SHCI_C2_Ready_Evt_t *p_ready = (SHCI_C2_Ready_Evt_t *)p_sys_event->payload;if (p_ready->sysevt_ready_rsp == WIRELESS_FW_RUNNING){+ cpu2_state = 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@@ -183,7 +195,8 @@ static void APPE_SysUserEvtRx(void *pPayload)else{/* FUS is running instead of the BLE stack: the stack binary is missing- * or was never started. Keep the user event flow off, nothing to do. */+ * or was never started. No BLE (and no OTA); STACK? reports it. */+ cpu2_state = CPU2_FUS;((tSHCI_UserEvtRxParam *)pPayload)->status = SHCI_TL_UserEventFlow_Disable;}}diff --git a/firmware/Core/Src/ota.c b/firmware/Core/Src/ota.cnew file mode 100644index 0000000..5c04d70--- /dev/null+++ b/firmware/Core/Src/ota.c@@ -0,0 +1,88 @@+#include <stdio.h>+#include "app_common.h"+#include "main.h"+#include "shci.h"+#include "app_entry.h"+#include "ota.h"++/* The validity tag ST's BLE_Ota checks (CheckFwAppValidity): the word at+ * app + 0x140 holds the address of 0x94448A29, which the linker script+ * puts after the last byte loaded from flash. */+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++static uint8_t reset_timer_id;+static uint8_t want_dfu;++static void Reset_Now(void)+{+ if (want_dfu)+ {+ SYSDFU_REQ_WORD = SYSDFU_REQ_MAGIC;+ }+ 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 */+ }+ NVIC_SystemReset();+}++static void Reset_Later(uint8_t dfu)+{+ want_dfu = dfu;+ if (!reset_timer_id)+ {+ HW_TS_Create(CFG_TIM_PROC_ID_ISR, &reset_timer_id, hw_ts_SingleShot, Reset_Now);+ }+ HW_TS_Start(reset_timer_id, MS_TO_TS_TICKS(RESET_DELAY_MS));+}++int OTA_Available(void)+{+ return APPE_Cpu2State() == CPU2_BLE;+}++void OTA_Request(void)+{+ Reset_Later(0);+}++void OTA_RequestDfu(void)+{+ Reset_Later(1);+}++void OTA_StackInfo(char *out, size_t n)+{+ WirelessFwInfo_t info;+ int state = APPE_Cpu2State();+ if (state == CPU2_UNKNOWN || SHCI_GetWirelessFwInfo(&info) != SHCI_Success)+ {+ snprintf(out, n, "unknown");+ return;+ }+ if (state == CPU2_BLE)+ {+ snprintf(out, n, "ble v=%u.%u.%u fus=%u.%u.%u", info.VersionMajor, info.VersionMinor, info.VersionSub,+ info.FusVersionMajor, info.FusVersionMinor, info.FusVersionSub);+ }+ else+ {+ snprintf(out, n, "none fus=%u.%u.%u", info.FusVersionMajor, info.FusVersionMinor, info.FusVersionSub);+ }+}diff --git a/firmware/Core/Src/proto.c b/firmware/Core/Src/proto.cindex fd21982..84749d6 100644--- a/firmware/Core/Src/proto.c+++ b/firmware/Core/Src/proto.c@@ -4,9 +4,11 @@#include "keymap.h"#include "batt.h"#include "keybit_image.h"+#include "ota.h"#include "proto.h"-/* Optional features the desktop app can use, only what's implemented. */+/* Optional features the desktop app can use, only what's implemented.+ * ota only while the CPU2 BLE stack runs, since the OTA bootloader needs it. */#define CAPS "batt,hold,macro"static proto_port_t *ports[PROTO_MAX_PORTS];@@ -170,7 +172,31 @@ static void Handle_Line(proto_port_t *port, char *cmd)if (strcmp(cmd, "HELLO") == 0){/* kb: version of the Keybit image this keyword flashes onto new Keybits */- Reply(port, "KEYWORD v=%s proto=1 caps=%s kb=%u", KEYWORD_FW_VERSION, CAPS, keybit_image_version);+ Reply(port, "KEYWORD v=%s proto=1 caps=%s%s kb=%u", KEYWORD_FW_VERSION, CAPS,+ OTA_Available() ? ",ota" : "", keybit_image_version);+ }+ else if (strcmp(cmd, "STACK?") == 0)+ {+ char info[48];+ OTA_StackInfo(info, sizeof(info));+ Reply(port, "STACK %s", info);+ }+ else if (strcmp(cmd, "OTA") == 0)+ {+ /* The loader runs on the same CPU2 BLE stack: without it OTA would+ * just strand the keyword in the loader (which then drops to DFU). */+ if (!OTA_Available())+ {+ Reply(port, "ERR no BLE stack on CPU2, use DFU");+ return;+ }+ Reply(port, "OK OTA");+ OTA_Request();+ }+ else if (strcmp(cmd, "DFU") == 0)+ {+ Reply(port, "OK DFU");+ OTA_RequestDfu();}else if (strcmp(cmd, "BATT?") == 0){diff --git a/firmware/README.md b/firmware/README.mdindex 4a69357..44244f8 100644--- a/firmware/README.md+++ b/firmware/README.md@@ -18,41 +18,97 @@ U14 is an XL-1608RGBC, common anode to +3.3V, so each colour is active LOW.## Build-Needs `arm-none-eabi-gcc`, `make` and OpenOCD (`brew install --cask gcc-arm-embedded`-and `brew install open-ocd` on macOS). `.stm32env` holds Windows tool paths from-the STM32 for VSCode extension, so override them on the command line:+Needs an `arm-none-eabi-gcc` with newlib and `make`. The Arm GNU Toolchain+(`brew install --cask gcc-arm-embedded`) or the xPack one that STM32 for VSCode+downloads both work. The bare `arm-none-eabi-gcc` brew formula doesn't (no+`stdint.h`). `.stm32env` holds the extension's tool paths, so override them on+the command line:```shcd firmware-make -f STM32Make.make ARM_GCC_PATH="$(dirname "$(which arm-none-eabi-gcc)")" OPENOCD=openocd+make -C ota_bootloader release ARM_GCC_PATH="$(dirname "$(which arm-none-eabi-gcc)")"```-The ELF lands in `build/debug/keyword.elf`.+That builds the OTA bootloader (`ota_bootloader/`) and the app, and writes+`release/`:-## Flash (ST-Link over SWD)+| File | What | Where |+|------|------|-------|+| `keyword_full.bin` / `.hex` | bootloader + app in one image | 0x08000000, first install over USB DFU |+| `keyword_app.bin` | app only | 0x08007000, updates over BLE |-Wire an ST-Link to the SWD header (SWDIO, SWCLK, GND, 3V3, NRST), then:+The app alone still builds with `make -f STM32Make.make` (`build/debug/keyword.elf`).++## Flash map++| Address | Pages | What |+|---------|-------|------|+| 0x08000000 | 0-6 | OTA bootloader, ST's BLE_Ota adapted (`ota_bootloader/`) |+| 0x08007000 | 7 up | the app |+| 0x080CF000 | SFSA - 1 | saved keymap, never erased by flashing or OTA |+| 0x080D0000 | SFSA up | CPU2: BLE stack and FUS |++On reset the bootloader jumps straight to the app if the app is valid (ST's+0x94448A29 tag at the end of the image, pointed to from app + 0x140). It only+stays and advertises **Keyword OTA** when the app is missing or broken, or when+the app asked for an update.++## Flash++### 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:```sh-make -f STM32Make.make flash ARM_GCC_PATH="$(dirname "$(which arm-none-eabi-gcc)")" OPENOCD=openocd-# or directly:-openocd -f openocd.cfg -c "program build/debug/keyword.elf verify reset exit"+STM32_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```-### First flash: BOOT0 option bytes+After this every update goes over Bluetooth.++### Updating over BLE-BOOT0 (PH3) is floating on the keyword board, so the chip may randomly boot into-the system bootloader instead of your code. Once per chip, tell it to ignore the-pin and always boot from flash (`nSWBOOT0 = 0`, `nBOOT0 = 1`) with-STM32CubeProgrammer:+1. Send `OTA` from the desktop app or over USB serial. The keyword answers+ `OK OTA` and reboots into the bootloader, which erases the old app and+ advertises as **Keyword OTA**. `STACK?` shows whether the BLE stack is there;+ without it `OTA` answers an error instead.+2. Send `keyword_app.bin` to address 0x7000 with ST BLE Toolbox (or the desktop+ app once it does OTA).+3. When it's done the bootloader checks the tag and starts the new app.++If the transfer stops halfway the bootloader stays in OTA mode, so just send+the file again.++### Back to USB DFU without BOOT0++Send `DFU` over USB serial or BLE. The keyword answers `OK DFU`, resets, and the+bootloader 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 BOOT0+or 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.++### ST-Link over SWD++Still works if an ST-Link is wired to the SWD header (SWDIO, SWCLK, GND, 3V3,+NRST). The app now lives at 0x08007000 and needs the bootloader in front of it:```sh-STM32_Programmer_CLI -c port=SWD mode=UR -ob nSWBOOT0=0 nBOOT0=1-STM32_Programmer_CLI -c port=SWD -ob displ # check: nSWBOOT0 = 0x0, nBOOT0 = 0x1+openocd -f openocd.cfg -c "program ota_bootloader/build/ota_bootloader.elf verify" \+ -c "program build/debug/keyword.elf verify reset exit"```-The same can be done in the STM32CubeProgrammer GUI under Option bytes > User-Configuration. This only needs doing once; it survives reflashing and mass erase.+### BOOT0 option bytes++BOOT0 (PH3) is floating on the keyword board, so the chip could randomly boot+into the system bootloader instead of the firmware. That's why its option bytes+were set to ignore the pin and always boot from flash (`nSWBOOT0 = 0`,+`nBOOT0 = 1`). Leave them like that: `DFU` above gets into the system+bootloader without them.## Keybit dock and side busdiff --git a/firmware/STM32-for-VSCode.config.yaml b/firmware/STM32-for-VSCode.config.yamlindex 5ca2e4b..9ac4197 100644--- a/firmware/STM32-for-VSCode.config.yaml+++ b/firmware/STM32-for-VSCode.config.yaml@@ -20,7 +20,9 @@ floatAbi: -mfloat-abi=hardldscript: stm32wb55xx_flash_cm4.ld # linker script# Compiler definitions. The -D prefix for the compiler will be automatically added.-cDefinitions: []+cDefinitions:+ - USER_VECT_TAB_ADDRESS+ - VECT_TAB_OFFSET=0x7000 # the app runs at 0x08007000 behind ota_bootloader/cxxDefinitions: []asDefinitions: []diff --git a/firmware/STM32Make.make b/firmware/STM32Make.makeindex 8a5d836..6113d37 100644--- a/firmware/STM32Make.make+++ b/firmware/STM32Make.make@@ -78,6 +78,7 @@ C_SOURCES = \Core/Src/keybit_bus.c \Core/Src/keybit_image.c \Core/Src/main.c \+Core/Src/ota.c \Core/Src/stm32wbxx_hal_msp.c \Core/Src/stm32wbxx_it.c \Core/Src/syscalls.c \@@ -225,7 +226,9 @@ AS_DEFS =# C definesC_DEFS = \-DSTM32WB55xx \--DUSE_HAL_DRIVER+-DUSE_HAL_DRIVER \+-DUSER_VECT_TAB_ADDRESS \+-DVECT_TAB_OFFSET=0x7000# CXX definesdiff --git a/firmware/stm32wb55xx_flash_cm4.ld b/firmware/stm32wb55xx_flash_cm4.ldindex 8230b56..4c2d4e6 100644--- a/firmware/stm32wb55xx_flash_cm4.ld+++ b/firmware/stm32wb55xx_flash_cm4.ld@@ -39,7 +39,10 @@ ENTRY(Reset_Handler)/* Specify the memory areas */MEMORY{-FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K+/* 0x08000000-0x08006FFF is the OTA bootloader (ota_bootloader/). The app+ * runs from page 7 up to the keymap page at 0x080CF000 (SFSA - 1 with the+ * v1.24.0 full BLE stack at 0x080D0000). */+FLASH (rx) : ORIGIN = 0x08007000, LENGTH = 0xC8000RAM1 (xrw) : ORIGIN = 0x20000008, LENGTH = 0x2FFF8RAM_SHARED (xrw) : ORIGIN = 0x20030000, LENGTH = 10K}@@ -60,6 +63,15 @@ SECTIONS. = ALIGN(4);} >FLASH+ /* The bootloader reads the address of the end tag from app + 0x140+ * (ST's BLE_Ota CheckFwAppValidity). Fixed address: the link fails if+ * the vector table ever grows into it. */+ .ota_region 0x08007140 :+ {+ KEEP(*(TAG_OTA_START))+ . = ALIGN(4);+ } >FLASH+/* The program code and other data goes into FLASH */.text :{@@ -229,6 +241,17 @@ SECTIONS*(MB_MEM2) ;_eMB_MEM2 = . ;} >RAM_SHARED AT> FLASH++ /* The 0x94448A29 end tag goes after everything that loads from flash+ * (ST puts it before the .data image), so an OTA cut off anywhere+ * before the last byte leaves no valid tag and the bootloader keeps+ * waiting for a new image. */+ .ota_region_end :+ {+ . = ALIGN(4);+ KEEP(*(TAG_OTA_END))+ . = ALIGN(4);+ } >FLASH}diff --git a/firmware/test/proto_test.c b/firmware/test/proto_test.cindex ec66edf..48bd42a 100644--- a/firmware/test/proto_test.c+++ b/firmware/test/proto_test.c@@ -22,6 +22,11 @@ static proto_port_t port2 = {.write = write2};static keybit_info_t present[2];static int remote_listed;const uint8_t keybit_image_version = 3;+static int stack_ok = 1, ota_asked, dfu_asked;+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 batt_t batt_fake;const batt_t *BATT_Get(void) { return &batt_fake; }int KEYMAP_Save(void) { return 0; }@@ -63,9 +68,9 @@ int main(void)memset(present[1].uid, 0xAB, UID_LEN);present[1].at = 'T';- expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro kb=3\n");- expect("HELLO\r\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro kb=3\n");- expect("HELLO\r", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro kb=3\n"); /* terminal Enter */+ expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro,ota kb=3\n");+ expect("HELLO\r\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro,ota kb=3\n");+ expect("HELLO\r", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro,ota kb=3\n"); /* terminal Enter */expect("\r\n\r\n", "");expect("SIDES?\n", "SIDES L=1 R=0 T=1\n");expect("BATT?\n", "ERR no battery reading yet\n");@@ -200,7 +205,22 @@ int main(void)longline[sizeof(longline) - 2] = '\n';longline[sizeof(longline) - 1] = 0;expect(longline, "ERR line too long\n");+ expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro,ota kb=3\n");++ /* OTA / DFU / STACK? */+ expect("STACK?\n", "STACK ble v=1.24.0 fus=2.2.0\n");+ expect("OTA\n", "OK OTA\n");+ assert(ota_asked == 1);+ expect("DFU\n", "OK DFU\n");+ assert(dfu_asked == 1);+ stack_ok = 0; /* FUS only, no BLE stack: no OTA, and HELLO says so */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");+ assert(ota_asked == 1);+ expect("DFU\n", "OK DFU\n"); /* DFU still works */+ assert(dfu_asked == 2);+ stack_ok = 1;/* Two transports at once: each has its own line buffer, so half a line* on one doesn't mix with the other, and replies go back where they@@ -211,7 +231,7 @@ int main(void)assert(out[0] == 0);assert(strcmp(out2, "SIDES L=1 R=0 T=1\n") == 0);PROTO_Input(&port, (const uint8_t *)"LO\n", 3);- assert(strcmp(out, "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro kb=3\n") == 0);+ assert(strcmp(out, "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro,ota kb=3\n") == 0);assert(strcmp(out2, "SIDES L=1 R=0 T=1\n") == 0);/* Unsolicited events go to every connected port, and only those. */