A truly modular keyboard
C
firmware: OTA bootloader in ota_bootloader/, adapted from ST's BLE_Ota
Nathan8ed3a100de64
diff --git a/firmware/Middlewares/ST/STM32_WPAN/ble/svc/Src/otas_stm.c b/firmware/Middlewares/ST/STM32_WPAN/ble/svc/Src/otas_stm.cnew file mode 100644index 0000000..c6fc76a--- /dev/null+++ b/firmware/Middlewares/ST/STM32_WPAN/ble/svc/Src/otas_stm.c@@ -0,0 +1,311 @@+/**+ ******************************************************************************+ * @file otas_stm.c+ * @author MCD Application Team+ * @brief OTA Service+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2018-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+++/* Includes ------------------------------------------------------------------*/+#include "common_blesvc.h"++/* Private typedef -----------------------------------------------------------*/+typedef enum+{+ OTAS_Conf_Not_Pending,+ OTAS_Conf_Pending,+} OTAS_Conf_Status_t;++typedef struct+{+ uint16_t OTAS_SvcHdle; /**< Service handle */+ uint16_t OTAS_Base_Addr_CharHdle; /**< Characteristic handle */+ uint16_t OTAS_Conf_CharHdle; /**< Characteristic handle */+ uint16_t OTAS_Raw_Data_CharHdle; /**< Characteristic handle */+ OTAS_Conf_Status_t OTAS_Conf_Status; /**< Indication Status */+}OTAS_Context_t;+++/* Private defines -----------------------------------------------------------*/+#define UUID_128_SUPPORTED 1+#if (UUID_128_SUPPORTED == 1)+#define OTA_UUID_LENGTH UUID_TYPE_128+#else+#define OTA_UUID_LENGTH UUID_TYPE_16+#endif++#define OTA_BASE_ADR_CHAR_SIZE (4)+#define OTA_CONF_CHAR_SIZE (1)+#define OTA_RAW_DATA_CHAR_SIZE OTAS_STM_RAW_DATA_SIZE++/**+* Service UUID+* 0000fe20-cc7a-482a-984a-7f2ed5b3e58f+*/+#if (UUID_128_SUPPORTED == 1)+const uint8_t OTAS_SVC_UUID[16] = {0x8f, 0xe5, 0xb3, 0xd5,+ 0x2e, 0x7f, 0x4a, 0x98,+ 0x2a, 0x48, 0x7a, 0xcc,+ 0x20, 0xFE, 0x00, 0x00};+#else+const uint8_t OTAS_SVC_UUID[2] = {0x20, 0xFE};+#endif+++/**+* Base Address Characteristic UUID+* 0000fe22-8e22-4541-9d4c-21edae82ed19+*/+#if (UUID_128_SUPPORTED == 1)+const uint8_t OTA_BASE_ADR_CHAR_UUID[16] = {0x19, 0xed, 0x82, 0xae,+ 0xed, 0x21, 0x4c, 0x9d,+ 0x41, 0x45, 0x22, 0x8e,+ 0x22, 0xFE, 0x00, 0x00};+#else+const uint8_t OTA_BASE_ADR_CHAR_UUID[2] = {0x22, 0xFE};+#endif++/**+* Confirmation Characteristic UUID+* 0000fe23-8e22-4541-9d4c-21edae82ed19+*/+#if (UUID_128_SUPPORTED == 1)+const uint8_t OTA_CONF_CHAR_UUID[16] = {0x19, 0xed, 0x82, 0xae,+ 0xed, 0x21, 0x4c, 0x9d,+ 0x41, 0x45, 0x22, 0x8e,+ 0x23, 0xFE, 0x00, 0x00};+#else+const uint8_t OTA_CONF_CHAR_UUID[2] = {0x23, 0xfe};+#endif++/**+* Raw Data Characteristic UUID+* 0000fe24-8e22-4541-9d4c-21edae82ed19+*/+#if (UUID_128_SUPPORTED == 1)+const uint8_t OTA_RAW_DATA_CHAR_UUID[16] = {0x19, 0xed, 0x82, 0xae,+ 0xed, 0x21, 0x4c, 0x9d,+ 0x41, 0x45, 0x22, 0x8e,+ 0x24, 0xFE, 0x00, 0x00};+#else+const uint8_t OTA_RAW_DATA_CHAR_UUID[2] = {0x24, 0xfe};+#endif+++/* Private macros ------------------------------------------------------------*/+/* Private variables ---------------------------------------------------------*/++/**+ * START of Section BLE_DRIVER_CONTEXT+ */+PLACE_IN_SECTION("BLE_DRIVER_CONTEXT") static OTAS_Context_t OTAS_Context;+/**+ * END of Section BLE_DRIVER_CONTEXT+ */++/* Private function prototypes -----------------------------------------------*/+static SVCCTL_EvtAckStatus_t OTAS_Event_Handler(void *Event);+++/* Functions Definition ------------------------------------------------------*/+/* Private functions ----------------------------------------------------------*/++/**+ * @brief Event handler+ * @param Event: Address of the buffer holding the Event+ * @retval Ack: Return whether the Event has been managed or not+ */+static SVCCTL_EvtAckStatus_t OTAS_Event_Handler(void *Event)+{+ SVCCTL_EvtAckStatus_t return_value;+ hci_event_pckt *event_pckt;+ evt_blecore_aci *blecore_evt;+ aci_gatt_attribute_modified_event_rp0 * attribute_modified;+ OTA_STM_Notification_t notification;++ return_value = SVCCTL_EvtNotAck;++ event_pckt = (hci_event_pckt *)(((hci_uart_pckt*)Event)->data);++ switch(event_pckt->evt)+ {+ case HCI_VENDOR_SPECIFIC_DEBUG_EVT_CODE:+ {+ blecore_evt = (evt_blecore_aci*)event_pckt->data;+ attribute_modified = (aci_gatt_attribute_modified_event_rp0*)blecore_evt->data;+ switch(blecore_evt->ecode)+ {+ case ACI_GATT_ATTRIBUTE_MODIFIED_VSEVT_CODE:+ {+ if(attribute_modified->Attr_Handle == (OTAS_Context.OTAS_Base_Addr_CharHdle + 1))+ {+ /**+ * Base Address+ */+ return_value = SVCCTL_EvtAckFlowEnable;++ notification.ChardId = OTAS_STM_BASE_ADDR_ID;+ notification.pPayload = (uint8_t*)&attribute_modified->Attr_Data[0];+ notification.ValueLength = attribute_modified->Attr_Data_Length;+ OTAS_STM_Notification( ¬ification );+ }+ else if(attribute_modified->Attr_Handle == (OTAS_Context.OTAS_Raw_Data_CharHdle + 1))+ {+ /**+ * Raw Data+ */+ return_value = SVCCTL_EvtAckFlowEnable;++ notification.ChardId = OTAS_STM_RAW_DATA_ID;+ notification.pPayload = (uint8_t*)&attribute_modified->Attr_Data[0];+ notification.ValueLength = attribute_modified->Attr_Data_Length;+ OTAS_STM_Notification( ¬ification );+ }+ }+ break;++ case ACI_GATT_SERVER_CONFIRMATION_VSEVT_CODE:+ {+ if( OTAS_Context.OTAS_Conf_Status != OTAS_Conf_Not_Pending)+ {+ /**+ * Confirmation Event+ */+ OTAS_Context.OTAS_Conf_Status = OTAS_Conf_Not_Pending;++ return_value = SVCCTL_EvtAckFlowEnable;++ notification.ChardId = OTAS_STM_CONF_EVENT_ID;+ notification.pPayload = (uint8_t*)&attribute_modified->Attr_Data[0];+ notification.ValueLength = attribute_modified->Attr_Data_Length;+ OTAS_STM_Notification( ¬ification );+ }+ }+ break;++ case ACI_GATT_WRITE_PERMIT_REQ_VSEVT_CODE:+ {+ aci_gatt_write_permit_req_event_rp0 * write_perm_req;+ write_perm_req = (aci_gatt_write_permit_req_event_rp0*)blecore_evt->data;+ if(write_perm_req->Attribute_Handle == (OTAS_Context.OTAS_Raw_Data_CharHdle + 1))+ {+ return_value = SVCCTL_EvtAckFlowEnable;+ aci_gatt_write_resp(write_perm_req->Connection_Handle,+ write_perm_req->Attribute_Handle,+ 0x00, /* write_status = 0 (no error))*/+ 0x00, /* err_code */+ write_perm_req->Data_Length,+ (uint8_t *)&(write_perm_req->Data[0]));+ }+ }+ break;++ default:+ break;+ }+ }+ break;++ default:+ break;+ }++ return(return_value);+}++/* Public functions ----------------------------------------------------------*/+void OTAS_STM_Init(void)+{+ /**+ * Register the event handler to the BLE controller+ */+ SVCCTL_RegisterSvcHandler(OTAS_Event_Handler);++ /**+ * Add OTA Service+ */+ aci_gatt_add_service(OTA_UUID_LENGTH,+ (Service_UUID_t *)OTAS_SVC_UUID,+ PRIMARY_SERVICE,+ 1+ + 2 /**< OTA_BASE CHAR */+ + 3 /**< OTA_CONF CHAR */+ + 2, /**< OTA_RAW_DATA CHAR */+ &(OTAS_Context.OTAS_SvcHdle));+++ /**+ * Add Base Address Characteristic+ */+ aci_gatt_add_char(OTAS_Context.OTAS_SvcHdle,+ OTA_UUID_LENGTH,+ (Char_UUID_t *)OTA_BASE_ADR_CHAR_UUID,+ OTA_BASE_ADR_CHAR_SIZE,+ CHAR_PROP_WRITE_WITHOUT_RESP,+ ATTR_PERMISSION_NONE,+ GATT_NOTIFY_ATTRIBUTE_WRITE,+ 10,+ 0,+ &(OTAS_Context.OTAS_Base_Addr_CharHdle));++ /**+ * Add Confirmation Characteristic+ */+ aci_gatt_add_char(OTAS_Context.OTAS_SvcHdle,+ OTA_UUID_LENGTH,+ (Char_UUID_t *)OTA_CONF_CHAR_UUID,+ OTA_CONF_CHAR_SIZE,+ CHAR_PROP_INDICATE,+ ATTR_PERMISSION_NONE,+ GATT_DONT_NOTIFY_EVENTS,+ 10,+ 0,+ &(OTAS_Context.OTAS_Conf_CharHdle));++ /**+ * Add Raw Data Characteristic+ */+ aci_gatt_add_char(OTAS_Context.OTAS_SvcHdle,+ OTA_UUID_LENGTH,+ (Char_UUID_t *)OTA_RAW_DATA_CHAR_UUID,+ OTA_RAW_DATA_CHAR_SIZE,+ CHAR_PROP_WRITE_WITHOUT_RESP,+ ATTR_PERMISSION_NONE,+ GATT_NOTIFY_ATTRIBUTE_WRITE | GATT_NOTIFY_WRITE_REQ_AND_WAIT_FOR_APPL_RESP,+ 10,+ 1,+ &(OTAS_Context.OTAS_Raw_Data_CharHdle));++ OTAS_Context.OTAS_Conf_Status = OTAS_Conf_Not_Pending;++ return;+}++tBleStatus OTAS_STM_UpdateChar(OTAS_STM_ChardId_t ChardId, uint8_t *p_payload)+{+ tBleStatus return_value;++ OTAS_Context.OTAS_Conf_Status = OTAS_Conf_Pending;++ return_value = aci_gatt_update_char_value(OTAS_Context.OTAS_SvcHdle,+ OTAS_Context.OTAS_Conf_CharHdle,+ 0, /**< charValOffset */+ OTA_CONF_CHAR_SIZE, /**< charValueLen */+ p_payload);++ return return_value;+}+++diff --git a/firmware/ota_bootloader/.gitignore b/firmware/ota_bootloader/.gitignorenew file mode 100644index 0000000..567609b--- /dev/null+++ b/firmware/ota_bootloader/.gitignore@@ -0,0 +1 @@+build/diff --git a/firmware/ota_bootloader/Core/Inc/app_common.h b/firmware/ota_bootloader/Core/Inc/app_common.hnew file mode 100644index 0000000..1f0fc57--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/app_common.h@@ -0,0 +1,113 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file app_common.h+ * @author MCD Application Team+ * @brief App Common application configuration file for STM32WPAN Middleware.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2020-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */+/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef APP_COMMON_H+#define APP_COMMON_H++#ifdef __cplusplus+extern "C"{+#endif++#include <stdint.h>+#include <string.h>+#include <stdio.h>+#include <stdlib.h>+#include <stdarg.h>++#include "app_conf.h"++/* -------------------------------- *+ * Basic definitions *+ * -------------------------------- */+#undef NULL+#define NULL 0++#undef FALSE+#define FALSE 0++#undef TRUE+#define TRUE (!0)++/* -------------------------------- *+ * Critical Section definition *+ * -------------------------------- */+#define BACKUP_PRIMASK() uint32_t primask_bit= __get_PRIMASK()+#define DISABLE_IRQ() __disable_irq()+#define RESTORE_PRIMASK() __set_PRIMASK(primask_bit)++/* -------------------------------- *+ * Macro delimiters *+ * -------------------------------- */+#define M_BEGIN do {++#define M_END } while(0)++/* -------------------------------- *+ * Some useful macro definitions *+ * -------------------------------- */+#ifndef MAX+#define MAX( x, y ) (((x)>(y))?(x):(y))+#endif++#ifndef MIN+#define MIN( x, y ) (((x)<(y))?(x):(y))+#endif++#define MODINC( a, m ) M_BEGIN (a)++; if ((a)>=(m)) (a)=0; M_END++#define MODDEC( a, m ) M_BEGIN if ((a)==0) (a)=(m); (a)--; M_END++#define MODADD( a, b, m ) M_BEGIN (a)+=(b); if ((a)>=(m)) (a)-=(m); M_END++#define MODSUB( a, b, m ) MODADD( a, (m)-(b), m )++#define PAUSE( t ) M_BEGIN \+ __IO int _i; \+ for ( _i = t; _i > 0; _i -- ); \+ M_END++#define DIVF( x, y ) ((x)/(y))++#define DIVC( x, y ) (((x)+(y)-1)/(y))++#define DIVR( x, y ) (((x)+((y)/2))/(y))++#define SHRR( x, n ) ((((x)>>((n)-1))+1)>>1)++#define BITN( w, n ) (((w)[(n)/32] >> ((n)%32)) & 1)++#define BITNSET( w, n, b ) M_BEGIN (w)[(n)/32] |= ((U32)(b))<<((n)%32); M_END++/* -------------------------------- *+ * Compiler *+ * -------------------------------- */+#define PLACE_IN_SECTION( __x__ ) __attribute__((section (__x__)))++#ifdef WIN32+#define ALIGN(n)+#else+#define ALIGN(n) __attribute__((aligned(n)))+#endif++#ifdef __cplusplus+} /* extern "C" */+#endif++#endif /* APP_COMMON_H */diff --git a/firmware/ota_bootloader/Core/Inc/app_conf.h b/firmware/ota_bootloader/Core/Inc/app_conf.hnew file mode 100644index 0000000..5bbe886--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/app_conf.h@@ -0,0 +1,144 @@+/*+ * Config for the keyword's OTA bootloader, from ST's BLE_Ota (STM32CubeWB+ * 1.24.0) with the keyword app's clocks (HSE, SMPS bypass, RF wakeup on+ * HSE/1024) and no Nucleo LEDs, buttons or debug UART.+ */+#ifndef APP_CONF_H+#define APP_CONF_H++#include "hw.h"+#include "hw_conf.h"+#include "hw_if.h"+#include "ble_bufsize.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_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" */++/* ---- GAP ---- */+#define CFG_TX_POWER (0x18) /* -0.15 dBm */+#define CFG_ADV_BD_ADDRESS (0x7257acd87a6c)+#define CFG_IDENTITY_ADDRESS GAP_PUBLIC_ADDR+#define CFG_PRIVACY PRIVACY_DISABLED+#define CFG_BLE_ADDRESS_TYPE CFG_IDENTITY_ADDRESS+#define CFG_FAST_CONN_ADV_INTERVAL_MIN (0x80) /* 80 ms */+#define CFG_FAST_CONN_ADV_INTERVAL_MAX (0xA0) /* 100 ms */+#define CFG_DEV_ID_OTA_FW_UPDATE (0x86) /* ST's id for an OTA loader, in the manufacturer data */+#define CFG_BLE_IR {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0}+#define CFG_BLE_ER {0xFE, 0xDC, 0xBA, 0x09, 0x87, 0x65, 0x43, 0x21, 0xFE, 0xDC, 0xBA, 0x09, 0x87, 0x65, 0x43, 0x21}++#define CFG_USE_SMPS 0++/* ---- BLE stack (SHCI_C2_BLE_Init), as BLE_Ota: 251 byte MTU for 248 byte chunks ---- */+#define CFG_BLE_NUM_LINK 1+#define CFG_BLE_NUM_GATT_SERVICES 8+#define CFG_BLE_NUM_GATT_ATTRIBUTES 68+#define CFG_BLE_MAX_ATT_MTU (251)+#define CFG_BLE_ATT_VALUE_ARRAY_SIZE (1344)+#define CFG_BLE_PREPARE_WRITE_LIST_SIZE BLE_PREP_WRITE_X_ATT(CFG_BLE_MAX_ATT_MTU)+#define CFG_BLE_MBLOCK_COUNT (BLE_MBLOCKS_CALC(CFG_BLE_PREPARE_WRITE_LIST_SIZE, CFG_BLE_MAX_ATT_MTU, CFG_BLE_NUM_LINK))+#define CFG_BLE_DATA_LENGTH_EXTENSION 1+#define CFG_BLE_PERIPHERAL_SCA 500+#define CFG_BLE_CENTRAL_SCA 0+/* Same as the app: RFWKP on HSE/1024 and the stack's sleep clock to match */+#define CFG_BLE_LS_SOURCE (SHCI_C2_BLE_INIT_CFG_BLE_LS_NOCALIB | SHCI_C2_BLE_INIT_CFG_BLE_LS_OTHER_DEV | SHCI_C2_BLE_INIT_CFG_BLE_LS_CLK_HSE_1024)+#define CFG_BLE_HSE_STARTUP_TIME 0x148+#define CFG_BLE_MAX_CONN_EVENT_LENGTH (0xFFFFFFFF)+#define CFG_BLE_VITERBI_MODE 1+#define CFG_BLE_OPTIONS (SHCI_C2_BLE_INIT_OPTIONS_LL_HOST | SHCI_C2_BLE_INIT_OPTIONS_WITH_SVC_CHANGE_DESC | SHCI_C2_BLE_INIT_OPTIONS_DEVICE_NAME_RW | SHCI_C2_BLE_INIT_OPTIONS_NO_EXT_ADV | SHCI_C2_BLE_INIT_OPTIONS_NO_CS_ALGO2 | SHCI_C2_BLE_INIT_OPTIONS_FULL_GATTDB_NVM | SHCI_C2_BLE_INIT_OPTIONS_GATT_CACHING_NOTUSED | SHCI_C2_BLE_INIT_OPTIONS_POWER_CLASS_2_3)+#define CFG_BLE_OPTIONS_EXT (SHCI_C2_BLE_INIT_OPTIONS_APPEARANCE_READONLY | SHCI_C2_BLE_INIT_OPTIONS_ENHANCED_ATT_NOTSUPPORTED)+#define CFG_BLE_MAX_COC_INITIATOR_NBR (32)+#define CFG_BLE_MIN_TX_POWER (-40)+#define CFG_BLE_MAX_TX_POWER (6)+#define CFG_BLE_MAX_ADD_EATT_BEARERS (4)+#define CFG_BLE_RX_MODEL_CONFIG (SHCI_C2_BLE_INIT_RX_MODEL_AGC_RSSI_LEGACY)+#define CFG_BLE_MAX_ADV_SET_NBR (3)+#define CFG_BLE_MAX_ADV_DATA_LEN (1650)+#define CFG_BLE_TX_PATH_COMPENS (0)+#define CFG_BLE_RX_PATH_COMPENS (0)+#define CFG_BLE_CORE_VERSION (SHCI_C2_BLE_INIT_BLE_CORE_5_4)++#define CFG_TLBLE_EVT_QUEUE_LENGTH 5+#define CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE 255+#define TL_BLE_EVENT_FRAME_SIZE (TL_EVT_HDR_SIZE + CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE)++#define CFG_USB_INTERFACE_ENABLE 0+#define CFG_LPM_SUPPORTED 0++/* ---- timer server on the RTC wakeup timer, LSE / 16 ---- */+#define CFG_RTCCLK_DIV (16)+#define CFG_RTC_WUCKSEL_DIVIDER (0)+#define CFG_RTC_ASYNCH_PRESCALER (0x0F)+#define CFG_RTC_SYNCH_PRESCALER (0x7FFF)+#define CFG_TS_TICK_VAL DIVR((CFG_RTCCLK_DIV * 1000000), LSE_VALUE)+#define CFG_TS_TICK_VAL_PS DIVR(((uint64_t)CFG_RTCCLK_DIV * 1e12), (uint64_t)LSE_VALUE)++typedef enum+{+ CFG_TIM_PROC_ID_ISR,+} CFG_TimProcID_t;++#define CFG_HW_RESET_BY_FW 1+#define CFG_DEBUGGER_SUPPORTED 1++#define APP_DBG_MSG PRINT_NO_MESG+#define CFG_DEBUG_TRACE_FULL 0+#define CFG_DEBUG_TRACE_LIGHT 0++/* ---- sequencer ---- */+typedef enum+{+ CFG_TASK_HCI_ASYNCH_EVT_ID,+ CFG_LAST_TASK_ID_WITH_HCICMD,+} CFG_Task_Id_With_HCI_Cmd_t;++typedef enum+{+ CFG_FIRST_TASK_ID_WITH_NO_HCICMD = CFG_LAST_TASK_ID_WITH_HCICMD - 1,+ CFG_TASK_SYSTEM_HCI_ASYNCH_EVT_ID,+ CFG_LAST_TASK_ID_WITH_NO_HCICMD,+} CFG_Task_Id_With_NO_HCI_Cmd_t;++#define CFG_TASK_NBR CFG_LAST_TASK_ID_WITH_NO_HCICMD++typedef enum+{+ CFG_SCH_PRIO_0,+ CFG_SCH_PRIO_NBR+} CFG_SCH_Prio_Id_t;++typedef enum+{+ CFG_IDLEEVT_HCI_CMD_EVT_RSP_ID,+ CFG_IDLEEVT_SYSTEM_HCI_CMD_EVT_RSP_ID,+} CFG_IdleEvt_Id_t;++typedef enum+{+ CFG_LPM_APP,+ CFG_LPM_APP_BLE,+} CFG_LPM_Id_t;++#define CFG_OTP_BASE_ADDRESS OTP_AREA_BASE+#define CFG_OTP_END_ADRESS OTP_AREA_END_ADDR++#endif /* APP_CONF_H */diff --git a/firmware/ota_bootloader/Core/Inc/app_entry.h b/firmware/ota_bootloader/Core/Inc/app_entry.hnew file mode 100644index 0000000..b2adece--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/app_entry.h@@ -0,0 +1,6 @@+#ifndef APP_ENTRY_H+#define APP_ENTRY_H++void APPE_Init(void);++#endif /* APP_ENTRY_H */diff --git a/firmware/ota_bootloader/Core/Inc/flash_driver.h b/firmware/ota_bootloader/Core/Inc/flash_driver.hnew file mode 100644index 0000000..5937889--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/flash_driver.h@@ -0,0 +1,176 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file flash_driver.h+ * @author MCD Application Team+ * @brief Dual core Flash driver interface+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2020-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef FLASH_DRIVER_H+#define FLASH_DRIVER_H++#ifdef __cplusplus+extern "C" {+#endif++ /* Includes ------------------------------------------------------------------*/++/* Private includes ----------------------------------------------------------*/+/* USER CODE BEGIN Includes */++/* USER CODE END Includes */++/* Exported types ------------------------------------------------------------*/+typedef enum+{+ SINGLE_FLASH_OPERATION_DONE,+ SINGLE_FLASH_OPERATION_NOT_EXECUTED,+}SingleFlashOperationStatus_t;++typedef enum+{+ WAITED_SEM_BUSY,+ WAITED_SEM_FREE,+}WaitedSemStatus_t;++typedef enum+{+ WAIT_FOR_SEM_BLOCK_FLASH_REQ_BY_CPU1,+ WAIT_FOR_SEM_BLOCK_FLASH_REQ_BY_CPU2,+}WaitedSemId_t;++/* Exported functions ------------------------------------------------------- */++ /**+ * @brief Implements the Dual core algorithm to erase multiple sectors in flash with CPU1+ * It calls for each sector to be erased the API FD_EraseSingleSector()+ *+ * @param FirstSector: The first sector to be erased+ * This parameter must be a value between 0 and (SFSA - 1)+ * @param NbrOfSectors: The number of sectors to erase+ * This parameter must be a value between 1 and (SFSA - FirstSector)+ * @retval Number of sectors not erased:+ * Depending on the implementation of FD_WaitForSemAvailable(),+ * it may still have some sectors not erased when the timing protection has been+ * enabled by either CPU1 or CPU2. When the value returned is not 0, the application+ * should wait until both timing protection before retrying to erase the last missing sectors.+ *+ * In addition, When the returned value is not 0:+ * - The Sem2 is NOT released+ * - The FLASH is NOT locked+ * - SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_OFF) is NOT called+ * It is expected that the user will call one more time this function to finish the process+ */+uint32_t FD_EraseSectors(uint32_t FirstSector, uint32_t NbrOfSectors);++ /**+ * @brief Implements the Dual core algorithm to write multiple 64bits data in flash with CPU1+ * The user shall first make sure the location to be written has been first erase.+ * Otherwise, the API will loop for ever as it will be not able to write in flash+ * The only value that can be written even though the destination is not erased is 0.+ * It calls for each 64bits to be written the API FD_WriteSingleData()+ *+ * @param DestAddress: Address of the flash to write the first data. It shall be 64bits aligned+ * @param pSrcBuffer: Address of the buffer holding the 64bits data to be written in flash+ * @param NbrOfData: Number of 64bits data to be written+ * @retval Number of 64bits data not written:+ * Depending on the implementation of FD_WaitForSemAvailable(),+ * it may still have 64bits data not written when the timing protection has been+ * enabled by either CPU1 or CPU2. When the value returned is not 0, the application+ * should wait until both timing protection before retrying to write the last missing 64bits data.+ *+ * In addition, When the returned value is not 0:+ * - The Sem2 is NOT released+ * - The FLASH is NOT locked+ * It is expected that the user will call one more time this function to finish the process+ */+ uint32_t FD_WriteData(uint32_t DestAddress, uint64_t * pSrcBuffer, uint32_t NbrOfData);++ /**+ * @brief Implements the Dual core algorithm to erase one sector in flash with CPU1+ *+ * It expects the following point before calling this API:+ * - The Sem2 is taken+ * - The FLASH is unlocked+ * - SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_ON) has been called+ * It expects the following point to be done when no more sectors need to be erased+ * - The Sem2 is released+ * - The FLASH is locked+ * - SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_OFF) is called+ *+ * The two point above are implemented in FD_EraseSectors()+ * This API needs to be used instead of FD_EraseSectors() in case a provided library is taking+ * care of these two points and request only a single operation.+ *+ * @param FirstSector: The sector to be erased+ * This parameter must be a value between 0 and (SFSA - 1)+ * @retval: SINGLE_FLASH_OPERATION_DONE -> The data has been written+ * SINGLE_FLASH_OPERATION_NOT_EXECUTED -> The data has not been written due to timing protection+ * from either CPU1 or CPU2. On a failure status, the user should check+ * both timing protection before retrying.+ */+ SingleFlashOperationStatus_t FD_EraseSingleSector(uint32_t SectorNumber);++ /**+ * @brief Implements the Dual core algorithm to write one 64bits data in flash with CPU1+ * The user shall first make sure the location to be written has been first erase.+ * Otherwise, the API will loop for ever as it will be not able to write in flash+ * The only value that can be written even though the destination is not erased is 0.+ *+ * It expects the following point before calling this API:+ * - The Sem2 is taken+ * - The FLASH is unlocked+ * It expects the following point to be done when no more sectors need to be erased+ * - The Sem2 is released+ * - The FLASH is locked+ *+ * The two point above are implemented in FD_WriteData()+ * This API needs to be used instead of FD_WriteData() in case a provided library is taking+ * care of these two points and request only a single operation.+ *+ * @param DestAddress: Address of the flash to write the data. It shall be 64bits aligned+ * @param Data: 64bits Data to be written+ * @retval: SINGLE_FLASH_OPERATION_DONE -> The data has been written+ * SINGLE_FLASH_OPERATION_NOT_EXECUTED -> The data has not been written due to timing protection+ * from either CPU1 or CPU2. On a failure status, the user should check+ * both timing protection before retrying.+ */+ SingleFlashOperationStatus_t FD_WriteSingleData(uint32_t DestAddress, uint64_t Data);++ /**+ * By default, this function is implemented weakly in flash_driver.c to return WAITED_SEM_BUSY.+ * When the semaphore is busy, this will result in either FD_WriteSingleData() or FD_EraseSingleSector()+ * to loop until the semaphore is free.+ *+ * This function may be implemented so that when using either an OS or the UTIL_SEQ_WaitEvt() API from the sequencer,+ * it could possible to run other tasks or enter idle mode until the waited semaphore is free.+ * This function shall not take the waited semaphore but just return when it is free.+ *+ * @param WaitedSemId: The semaphore ID this function should not return until it is free+ * @retval: WAITED_SEM_BUSY -> The function returned before waiting for the semaphore to be free. This will exit the loop+ * from either FD_EraseSingleSector() or FD_WriteSingleData() and the number of actions left to+ * be processed are reported to the user+ * WAITED_SEM_FREE -> The semaphore has been checked as free. Both FD_EraseSingleSector() and FD_WriteSingleData()+ * try again to process one more time the flash.+ */+ WaitedSemStatus_t FD_WaitForSemAvailable(WaitedSemId_t WaitedSemId);+++#ifdef __cplusplus+}+#endif++#endif /*FLASH_DRIVER_H */diff --git a/firmware/ota_bootloader/Core/Inc/hw_conf.h b/firmware/ota_bootloader/Core/Inc/hw_conf.hnew file mode 100644index 0000000..33625e1--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/hw_conf.h@@ -0,0 +1,168 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file hw_conf.h+ * @author MCD Application Team+ * @brief Configuration of hardware interface+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef HW_CONF_H+#define HW_CONF_H++/******************************************************************************+ * Semaphores+ * THIS SHALL NO BE CHANGED AS THESE SEMAPHORES ARE USED AS WELL ON THE CM0++ *****************************************************************************/+/**+* The CPU2 may be configured to store the Thread persistent data either in internal NVM storage on CPU2 or in+* SRAM2 buffer provided by the user application. This can be configured with the system command SHCI_C2_Config()+* When the CPU2 is requested to store persistent data in SRAM2, it can write data in this buffer at any time when needed.+* In order to read consistent data with the CPU1 from the SRAM2 buffer, the flow should be:+* + CPU1 takes CFG_HW_THREAD_NVM_SRAM_SEMID semaphore+* + CPU1 reads all persistent data from SRAM2 (most of the time, the goal is to write these data into an NVM managed by CPU1)+* + CPU1 releases CFG_HW_THREAD_NVM_SRAM_SEMID semaphore+* CFG_HW_THREAD_NVM_SRAM_SEMID semaphore makes sure CPU2 does not update the persistent data in SRAM2 at the same time CPU1 is reading them.+* There is no timing constraint on how long this semaphore can be kept.+*/+#define CFG_HW_THREAD_NVM_SRAM_SEMID 9++/**+* The CPU2 may be configured to store the BLE persistent data either in internal NVM storage on CPU2 or in+* SRAM2 buffer provided by the user application. This can be configured with the system command SHCI_C2_Config()+* When the CPU2 is requested to store persistent data in SRAM2, it can write data in this buffer at any time when needed.+* In order to read consistent data with the CPU1 from the SRAM2 buffer, the flow should be:+* + CPU1 takes CFG_HW_BLE_NVM_SRAM_SEMID semaphore+* + CPU1 reads all persistent data from SRAM2 (most of the time, the goal is to write these data into an NVM managed by CPU1)+* + CPU1 releases CFG_HW_BLE_NVM_SRAM_SEMID semaphore+* CFG_HW_BLE_NVM_SRAM_SEMID semaphore makes sure CPU2 does not update the persistent data in SRAM2 at the same time CPU1 is reading them.+* There is no timing constraint on how long this semaphore can be kept.+*/+#define CFG_HW_BLE_NVM_SRAM_SEMID 8++/**+* Index of the semaphore used by CPU2 to prevent the CPU1 to either write or erase data in flash+* The CPU1 shall not either write or erase in flash when this semaphore is taken by the CPU2+* When the CPU1 needs to either write or erase in flash, it shall first get the semaphore and release it just+* after writing a raw (64bits data) or erasing one sector.+* Once the Semaphore has been released, there shall be at least 1us before it can be taken again. This is required+* to give the opportunity to CPU2 to take it.+* On v1.4.0 and older CPU2 wireless firmware, this semaphore is unused and CPU2 is using PES bit.+* By default, CPU2 is using the PES bit to protect its timing. The CPU1 may request the CPU2 to use the semaphore+* instead of the PES bit by sending the system command SHCI_C2_SetFlashActivityControl()+*/+#define CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID 7++/**+* Index of the semaphore used by CPU1 to prevent the CPU2 to either write or erase data in flash+* In order to protect its timing, the CPU1 may get this semaphore to prevent the CPU2 to either+* write or erase in flash (as this will stall both CPUs)+* The PES bit shall not be used as this may stall the CPU2 in some cases.+*/+#define CFG_HW_BLOCK_FLASH_REQ_BY_CPU1_SEMID 6++/**+* Index of the semaphore used to manage the CLK48 clock configuration+* When the USB is required, this semaphore shall be taken before configuring te CLK48 for USB+* and should be released after the application switch OFF the clock when the USB is not used anymore+* When using the RNG, it is good enough to use CFG_HW_RNG_SEMID to control CLK48.+* More details in AN5289+*/+#define CFG_HW_CLK48_CONFIG_SEMID 5++/* Index of the semaphore used to manage the entry Stop Mode procedure */+#define CFG_HW_ENTRY_STOP_MODE_SEMID 4++/* Index of the semaphore used to access the RCC */+#define CFG_HW_RCC_SEMID 3++/* Index of the semaphore used to access the FLASH */+#define CFG_HW_FLASH_SEMID 2++/* Index of the semaphore used to access the PKA */+#define CFG_HW_PKA_SEMID 1++/* Index of the semaphore used to access the RNG */+#define CFG_HW_RNG_SEMID 0++/******************************************************************************+ * HW TIMER SERVER+ *****************************************************************************/+/**+ * The user may define the maximum number of virtual timers supported.+ * It shall not exceed 255+ */+#define CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER 6++/**+ * The user may define the priority in the NVIC of the RTC_WKUP interrupt handler that is used to manage the+ * wakeup timer.+ * This setting is the preemptpriority part of the NVIC.+ */+#define CFG_HW_TS_NVIC_RTC_WAKEUP_IT_PREEMPTPRIO 3++/**+ * The user may define the priority in the NVIC of the RTC_WKUP interrupt handler that is used to manage the+ * wakeup timer.+ * This setting is the subpriority part of the NVIC. It does not exist on all processors. When it is not supported+ * on the CPU, the setting is ignored+ */+#define CFG_HW_TS_NVIC_RTC_WAKEUP_IT_SUBPRIO 0++/**+ * Define a critical section in the Timer server+ * The Timer server does not support the API to be nested+ * The Application shall either:+ * a) Ensure this will never happen+ * b) Define the critical section+ * The default implementations is masking all interrupts using the PRIMASK bit+ * The TimerServer driver uses critical sections to avoid context corruption. This is achieved with the macro+ * TIMER_ENTER_CRITICAL_SECTION and TIMER_EXIT_CRITICAL_SECTION. When CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION is set+ * to 1, all STM32 interrupts are masked with the PRIMASK bit of the CortexM CPU. It is possible to use the BASEPRI+ * register of the CortexM CPU to keep allowed some interrupts with high priority. In that case, the user shall+ * re-implement TIMER_ENTER_CRITICAL_SECTION and TIMER_EXIT_CRITICAL_SECTION and shall make sure that no TimerServer+ * API are called when the TIMER critical section is entered+ */+#define CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION 1++/**+ * This value shall reflect the maximum delay there could be in the application between the time the RTC interrupt+ * is generated by the Hardware and the time when the RTC interrupt handler is called. This time is measured in+ * number of RTCCLK ticks.+ * A relaxed timing would be 10ms+ * When the value is too short, the timerserver will not be able to count properly and all timeout may be random.+ * When the value is too long, the device may wake up more often than the most optimal configuration. However, the+ * impact on power consumption would be marginal (unless the value selected is extremely too long). It is strongly+ * recommended to select a value large enough to make sure it is not too short to ensure reliability of the system+ * as this will have marginal impact on low power mode+ */+#define CFG_HW_TS_RTC_HANDLER_MAX_DELAY ( 10 * (LSI_VALUE/1000) )++ /**+ * Interrupt ID in the NVIC of the RTC Wakeup interrupt handler+ * It shall be type of IRQn_Type+ */+#define CFG_HW_TS_RTC_WAKEUP_HANDLER_ID RTC_WKUP_IRQn++/******************************************************************************+ * HW UART+ *****************************************************************************/+#define CFG_HW_LPUART1_ENABLED 1+#define CFG_HW_LPUART1_DMA_TX_SUPPORTED 1++#define CFG_HW_USART1_ENABLED 1+#define CFG_HW_USART1_DMA_TX_SUPPORTED 1++#endif /* HW_CONF_H */diff --git a/firmware/ota_bootloader/Core/Inc/hw_if.h b/firmware/ota_bootloader/Core/Inc/hw_if.hnew file mode 100644index 0000000..778d936--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/hw_if.h@@ -0,0 +1,247 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file hw_if.h+ * @author MCD Application Team+ * @brief Hardware Interface+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef HW_IF_H+#define HW_IF_H++#ifdef __cplusplus+extern "C" {+#endif++ /* Includes ------------------------------------------------------------------*/+#include "stm32wbxx.h"+#include "stm32wbxx_ll_exti.h"+#include "stm32wbxx_ll_system.h"+#include "stm32wbxx_ll_rcc.h"+#include "stm32wbxx_ll_ipcc.h"+#include "stm32wbxx_ll_bus.h"+#include "stm32wbxx_ll_pwr.h"+#include "stm32wbxx_ll_cortex.h"+#include "stm32wbxx_ll_utils.h"+#include "stm32wbxx_ll_hsem.h"+#include "stm32wbxx_ll_gpio.h"+#include "stm32wbxx_ll_rtc.h"++#ifdef USE_STM32WBXX_USB_DONGLE+#include "stm32wbxx_usb_dongle.h"+#endif+#ifdef USE_STM32WBXX_NUCLEO+#include "stm32wbxx_nucleo.h"+#endif+#ifdef USE_X_NUCLEO_EPD+#include "x_nucleo_epd.h"+#endif++/* Private includes ----------------------------------------------------------*/+/* USER CODE BEGIN Includes */++/* USER CODE END Includes */++ /******************************************************************************+ * HW UART+ ******************************************************************************/+ typedef enum+ {+ hw_uart1,+ hw_uart2,+ hw_lpuart1,+ } hw_uart_id_t;++ typedef enum+ {+ hw_uart_ok,+ hw_uart_error,+ hw_uart_busy,+ hw_uart_to,+ } hw_status_t;++ void HW_UART_Init(hw_uart_id_t hw_uart_id);+ void HW_UART_Receive_IT(hw_uart_id_t hw_uart_id, uint8_t *pData, uint16_t Size, void (*Callback)(void));+ void HW_UART_Transmit_IT(hw_uart_id_t hw_uart_id, uint8_t *pData, uint16_t Size, void (*Callback)(void));+ hw_status_t HW_UART_Transmit(hw_uart_id_t hw_uart_id, uint8_t *p_data, uint16_t size, uint32_t timeout);+ hw_status_t HW_UART_Transmit_DMA(hw_uart_id_t hw_uart_id, uint8_t *p_data, uint16_t size, void (*Callback)(void));+ void HW_UART_Interrupt_Handler(hw_uart_id_t hw_uart_id);+ void HW_UART_DMA_Interrupt_Handler(hw_uart_id_t hw_uart_id);++ /******************************************************************************+ * HW TimerServer+ ******************************************************************************/+ /* Exported types ------------------------------------------------------------*/+ /**+ * This setting is used when standby mode is supported.+ * hw_ts_InitMode_Limited should be used when the device restarts from Standby Mode. In that case, the Timer Server does+ * not re-initialized its context. Only the Hardware register which content has been lost is reconfigured+ * Otherwise, hw_ts_InitMode_Full should be requested (Start from Power ON) and everything is re-initialized.+ */+ typedef enum+ {+ hw_ts_InitMode_Full,+ hw_ts_InitMode_Limited,+ } HW_TS_InitMode_t;++ /**+ * When a Timer is created as a SingleShot timer, it is not automatically restarted when the timeout occurs. However,+ * the timer is kept reserved in the list and could be restarted at anytime with HW_TS_Start()+ *+ * When a Timer is created as a Repeated timer, it is automatically restarted when the timeout occurs.+ */+ typedef enum+ {+ hw_ts_SingleShot,+ hw_ts_Repeated+ } HW_TS_Mode_t;++ /**+ * hw_ts_Successful is returned when a Timer has been successfully created with HW_TS_Create(). Otherwise, hw_ts_Failed+ * is returned. When hw_ts_Failed is returned, that means there are not enough free slots in the list to create a+ * Timer. In that case, CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER should be increased+ */+ typedef enum+ {+ hw_ts_Successful,+ hw_ts_Failed,+ }HW_TS_ReturnStatus_t;++ typedef void (*HW_TS_pTimerCb_t)(void);++ /**+ * @brief Initialize the timer server+ * This API shall be called by the application before any timer is requested to the timer server. It+ * configures the RTC module to be connected to the LSI input clock.+ *+ * @param TimerInitMode: When the device restarts from Standby, it should request hw_ts_InitMode_Limited so that the+ * Timer context is not re-initialized. Otherwise, hw_ts_InitMode_Full should be requested+ * @param hrtc: RTC Handle+ * @retval None+ */+ void HW_TS_Init(HW_TS_InitMode_t TimerInitMode, RTC_HandleTypeDef *hrtc);++ /**+ * @brief Interface to create a virtual timer+ * The user shall call this API to create a timer. Once created, the timer is reserved to the module until it+ * has been deleted. When creating a timer, the user shall specify the mode (single shot or repeated), the+ * callback to be notified when the timer expires and a module ID to identify in the timer interrupt handler+ * which module is concerned. In return, the user gets a timer ID to handle it.+ *+ * @param TimerProcessID: This is an identifier provided by the user and returned in the callback to allow+ * identification of the requester+ * @param pTimerId: Timer Id returned to the user to request operation (start, stop, delete)+ * @param TimerMode: Mode of the virtual timer (Single shot or repeated)+ * @param pTimerCallBack: Callback when the virtual timer expires+ * @retval HW_TS_ReturnStatus_t: Return whether the creation is successful or not+ */+ HW_TS_ReturnStatus_t HW_TS_Create(uint32_t TimerProcessID, uint8_t *pTimerId, HW_TS_Mode_t TimerMode, HW_TS_pTimerCb_t pTimerCallBack);++ /**+ * @brief Stop a virtual timer+ * This API may be used to stop a running timer. A timer which is stopped is move to the pending state.+ * A pending timer may be restarted at any time with a different timeout value but the mode cannot be changed.+ * Nothing is done when it is called to stop a timer which has been already stopped+ *+ * @param TimerID: Id of the timer to stop+ * @retval None+ */+ void HW_TS_Stop(uint8_t TimerID);++ /**+ * @brief Start a virtual timer+ * This API shall be used to start a timer. The timeout value is specified and may be different each time.+ * When the timer is in the single shot mode, it will move to the pending state when it expires. The user may+ * restart it at any time with a different timeout value. When the timer is in the repeated mode, it always+ * stay in the running state. When the timer expires, it will be restarted with the same timeout value.+ * This API shall not be called on a running timer.+ *+ * @param TimerID: The ID Id of the timer to start+ * @param timeout_ticks: Number of ticks of the virtual timer (Maximum value is (0xFFFFFFFF-0xFFFF = 0xFFFF0000)+ * @retval None+ */+ void HW_TS_Start(uint8_t TimerID, uint32_t timeout_ticks);++ /**+ * @brief Delete a virtual timer from the list+ * This API should be used when a timer is not needed anymore by the user. A deleted timer is removed from+ * the timer list managed by the timer server. It cannot be restarted again. The user has to go with the+ * creation of a new timer if required and may get a different timer id+ *+ * @param TimerID: The ID of the timer to remove from the list+ * @retval None+ */+ void HW_TS_Delete(uint8_t TimerID);++ /**+ * @brief Schedule the timer list on the timer interrupt handler+ * This interrupt handler shall be called by the application in the RTC interrupt handler. This handler takes+ * care of clearing all status flag required in the RTC and EXTI peripherals+ *+ * @param None+ * @retval None+ */+ void HW_TS_RTC_Wakeup_Handler(void);++ /**+ * @brief Return the number of ticks to count before the interrupt+ * This API returns the number of ticks left to be counted before an interrupt is generated by the+ * Timer Server. This API may be used by the application for power management optimization. When the system+ * enters low power mode, the mode selection is a tradeoff between the wakeup time where the CPU is running+ * and the time while the CPU will be kept in low power mode before next wakeup. The deeper is the+ * low power mode used, the longer is the wakeup time. The low power mode management considering wakeup time+ * versus time in low power mode is implementation specific+ * When the timer is disabled (No timer in the list), it returns 0xFFFF+ *+ * @param None+ * @retval The number of ticks left to count+ */+ uint16_t HW_TS_RTC_ReadLeftTicksToCount(void);++ /**+ * @brief Notify the application that a registered timer has expired+ * This API shall be implemented by the user application.+ * This API notifies the application that a timer expires. This API is running in the RTC Wakeup interrupt+ * context. The application may implement an Operating System to change the context priority where the timer+ * callback may be handled. This API provides the module ID to identify which module is concerned and to allow+ * sending the information to the correct task+ *+ * @param TimerProcessID: The TimerProcessId associated with the timer when it has been created+ * @param TimerID: The TimerID of the expired timer+ * @param pTimerCallBack: The Callback associated with the timer when it has been created+ * @retval None+ */+ void HW_TS_RTC_Int_AppNot(uint32_t TimerProcessID, uint8_t TimerID, HW_TS_pTimerCb_t pTimerCallBack);++ /**+ * @brief Notify the application that the wakeupcounter has been updated+ * This API should be implemented by the user application+ * This API notifies the application that the counter has been updated. This is expected to be used along+ * with the HW_TS_RTC_ReadLeftTicksToCount () API. It could be that the counter has been updated since the+ * last call of HW_TS_RTC_ReadLeftTicksToCount () and before entering low power mode. This notification+ * provides a way to the application to solve that race condition to reevaluate the counter value before+ * entering low power mode+ *+ * @param None+ * @retval None+ */+ void HW_TS_RTC_CountUpdated_AppNot(void);++#ifdef __cplusplus+}+#endif++#endif /* HW_IF_H */diff --git a/firmware/ota_bootloader/Core/Inc/main.h b/firmware/ota_bootloader/Core/Inc/main.hnew file mode 100644index 0000000..2580f66--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/main.h@@ -0,0 +1,12 @@+#ifndef MAIN_H+#define MAIN_H++#include "stm32wbxx_hal.h"+#include "app_conf.h"++void Error_Handler(void);++/* Reset into ST's ROM USB DFU bootloader (system memory). See main.c. */+void BOOT_RequestSystemDfu(void);++#endif /* MAIN_H */diff --git a/firmware/ota_bootloader/Core/Inc/stm32_lpm_if.h b/firmware/ota_bootloader/Core/Inc/stm32_lpm_if.hnew file mode 100644index 0000000..22ebf25--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/stm32_lpm_if.h@@ -0,0 +1,80 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file stm32_lpm_if.h+ * @author MCD Application Team+ * @brief Header for stm32_lpm_if.c module (device specific LP management)+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef STM32_LPM_IF_H+#define STM32_LPM_IF_H++#ifdef __cplusplus+extern "C" {+#endif++/* Includes ------------------------------------------------------------------*/++/**+ * @brief Enters Low Power Off Mode+ * @param none+ * @retval none+ */+void PWR_EnterOffMode( void );+/**+ * @brief Exits Low Power Off Mode+ * @param none+ * @retval none+ */+void PWR_ExitOffMode( void );++/**+ * @brief Enters Low Power Stop Mode+ * @note ARM exists the function when waking up+ * @param none+ * @retval none+ */+void PWR_EnterStopMode( void );+/**+ * @brief Exits Low Power Stop Mode+ * @note Enable the pll at 32MHz+ * @param none+ * @retval none+ */+void PWR_ExitStopMode( void );++/**+ * @brief Enters Low Power Sleep Mode+ * @note ARM exits the function when waking up+ * @param none+ * @retval none+ */+void PWR_EnterSleepMode( void );++/**+ * @brief Exits Low Power Sleep Mode+ * @note ARM exits the function when waking up+ * @param none+ * @retval none+ */+void PWR_ExitSleepMode( void );++#ifdef __cplusplus+}+#endif++#endif /* STM32_LPM_IF_H */+diff --git a/firmware/ota_bootloader/Core/Inc/stm32wbxx_hal_conf.h b/firmware/ota_bootloader/Core/Inc/stm32wbxx_hal_conf.hnew file mode 100644index 0000000..e692cce--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/stm32wbxx_hal_conf.h@@ -0,0 +1,352 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file stm32wbxx_hal_conf.h+ * @author MCD Application Team+ * @brief HAL configuration file.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef __STM32WBxx_HAL_CONF_H+#define __STM32WBxx_HAL_CONF_H++#ifdef __cplusplus+ extern "C" {+#endif++/* Exported types ------------------------------------------------------------*/+/* Exported constants --------------------------------------------------------*/++/* ########################## Module Selection ############################## */+/**+ * @brief This is the list of modules to be used in the HAL driver+ */+#define HAL_MODULE_ENABLED+/*#define HAL_ADC_MODULE_ENABLED */+/*#define HAL_CRYP_MODULE_ENABLED */+/*#define HAL_COMP_MODULE_ENABLED */+/*#define HAL_CRC_MODULE_ENABLED */+#define HAL_HSEM_MODULE_ENABLED+#define HAL_I2C_MODULE_ENABLED+/*#define HAL_IPCC_MODULE_ENABLED */+/*#define HAL_IRDA_MODULE_ENABLED */+/*#define HAL_IWDG_MODULE_ENABLED */+/*#define HAL_LCD_MODULE_ENABLED */+/*#define HAL_LPTIM_MODULE_ENABLED */+#define HAL_PCD_MODULE_ENABLED+/*#define HAL_PKA_MODULE_ENABLED */+#define HAL_QSPI_MODULE_ENABLED+/*#define HAL_RNG_MODULE_ENABLED */+#define HAL_RTC_MODULE_ENABLED+/*#define HAL_SAI_MODULE_ENABLED */+/*#define HAL_SMBUS_MODULE_ENABLED */+/*#define HAL_SMARTCARD_MODULE_ENABLED */+/*#define HAL_SPI_MODULE_ENABLED */+/*#define HAL_TIM_MODULE_ENABLED */+/*#define HAL_TSC_MODULE_ENABLED */+/*#define HAL_UART_MODULE_ENABLED */+/*#define HAL_USART_MODULE_ENABLED */+/*#define HAL_WWDG_MODULE_ENABLED */+#define HAL_EXTI_MODULE_ENABLED+#define HAL_CORTEX_MODULE_ENABLED+#define HAL_DMA_MODULE_ENABLED+#define HAL_FLASH_MODULE_ENABLED+#define HAL_GPIO_MODULE_ENABLED+#define HAL_PWR_MODULE_ENABLED+#define HAL_RCC_MODULE_ENABLED++#define USE_HAL_ADC_REGISTER_CALLBACKS 0u+#define USE_HAL_COMP_REGISTER_CALLBACKS 0u+#define USE_HAL_CRYP_REGISTER_CALLBACKS 0u+#define USE_HAL_I2C_REGISTER_CALLBACKS 0u+#define USE_HAL_IRDA_REGISTER_CALLBACKS 0u+#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0u+#define USE_HAL_PCD_REGISTER_CALLBACKS 0u+#define USE_HAL_PKA_REGISTER_CALLBACKS 0u+#define USE_HAL_QSPI_REGISTER_CALLBACKS 0u+#define USE_HAL_RNG_REGISTER_CALLBACKS 0u+#define USE_HAL_RTC_REGISTER_CALLBACKS 0u+#define USE_HAL_SAI_REGISTER_CALLBACKS 0u+#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0u+#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0u+#define USE_HAL_SPI_REGISTER_CALLBACKS 0u+#define USE_HAL_TIM_REGISTER_CALLBACKS 0u+#define USE_HAL_TSC_REGISTER_CALLBACKS 0u+#define USE_HAL_UART_REGISTER_CALLBACKS 0u+#define USE_HAL_USART_REGISTER_CALLBACKS 0u+#define USE_HAL_WWDG_REGISTER_CALLBACKS 0u++/* ########################## Oscillator Values adaptation ####################*/+/**+ * @brief Adjust the value of External High Speed oscillator (HSE) used in your application.+ * This value is used by the RCC HAL module to compute the system frequency+ * (when HSE is used as system clock source, directly or through the PLL).+ */+#if !defined (HSE_VALUE)+#define HSE_VALUE 32000000U /*!< Value of the External oscillator in Hz */+#endif /* HSE_VALUE */++#if !defined (HSE_STARTUP_TIMEOUT)+ #define HSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSE start up, in ms */+#endif /* HSE_STARTUP_TIMEOUT */++/**+ * @brief Internal Multiple Speed oscillator (MSI) default value.+ * This value is the default MSI range value after Reset.+ */+#if !defined (MSI_VALUE)+ #define MSI_VALUE ((uint32_t)4000000) /*!< Value of the Internal oscillator in Hz*/+#endif /* MSI_VALUE */++/**+ * @brief Internal High Speed oscillator (HSI) value.+ * This value is used by the RCC HAL module to compute the system frequency+ * (when HSI is used as system clock source, directly or through the PLL).+ */+#if !defined (HSI_VALUE)+#define HSI_VALUE 16000000U /*!< Value of the Internal oscillator in Hz*/+#endif /* HSI_VALUE */++/**+ * @brief Internal Low Speed oscillator (LSI1) value.+ */+#if !defined (LSI1_VALUE)+ #define LSI1_VALUE ((uint32_t)32000) /*!< LSI1 Typical Value in Hz*/+#endif /* LSI1_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz+ The real value may vary depending on the variations+ in voltage and temperature.*/+/**+ * @brief Internal Low Speed oscillator (LSI2) value.+ */+#if !defined (LSI2_VALUE)+ #define LSI2_VALUE ((uint32_t)32000) /*!< LSI2 Typical Value in Hz*/+#endif /* LSI2_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz+ The real value may vary depending on the variations+ in voltage and temperature.*/++/**+ * @brief External Low Speed oscillator (LSE) value.+ * This value is used by the UART, RTC HAL module to compute the system frequency+ */+#if !defined (LSE_VALUE)+#define LSE_VALUE 32768U /*!< Value of the External oscillator in Hz*/+#endif /* LSE_VALUE */++/**+ * @brief Internal Multiple Speed oscillator (HSI48) default value.+ * This value is the default HSI48 range value after Reset.+ */+#if !defined (HSI48_VALUE)+ #define HSI48_VALUE ((uint32_t)48000000) /*!< Value of the Internal oscillator in Hz*/+#endif /* HSI48_VALUE */++#if !defined (LSE_STARTUP_TIMEOUT)+#define LSE_STARTUP_TIMEOUT 5000U /*!< Time out for LSE start up, in ms */+#endif /* LSE_STARTUP_TIMEOUT */++/**+ * @brief External clock source for SAI1 peripheral+ * This value is used by the RCC HAL module to compute the SAI1 & SAI2 clock source+ * frequency.+ */+#if !defined (EXTERNAL_SAI1_CLOCK_VALUE)+ #define EXTERNAL_SAI1_CLOCK_VALUE ((uint32_t)2097000) /*!< Value of the SAI1 External clock source in Hz*/+#endif /* EXTERNAL_SAI1_CLOCK_VALUE */++/* Tip: To avoid modifying this file each time you need to use different HSE,+ === you can define the HSE value in your toolchain compiler preprocessor. */++/* ########################### System Configuration ######################### */+/**+ * @brief This is the HAL system configuration section+ */++#define VDD_VALUE 3300U /*!< Value of VDD in mv */+#define TICK_INT_PRIORITY 15U /*!< tick interrupt priority */+#define USE_RTOS 0U+#define PREFETCH_ENABLE 1U+#define INSTRUCTION_CACHE_ENABLE 1U+#define DATA_CACHE_ENABLE 1U++/* ########################## Assert Selection ############################## */+/**+ * @brief Uncomment the line below to expanse the "assert_param" macro in the+ * HAL drivers code+ */+/* #define USE_FULL_ASSERT 1U */++/* ################## SPI peripheral configuration ########################## */++/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver+ * Activated: CRC code is present inside driver+ * Deactivated: CRC code cleaned from driver+ */++#define USE_SPI_CRC 0U++/* Includes ------------------------------------------------------------------*/+/**+ * @brief Include module's header file+ */+#ifdef HAL_DMA_MODULE_ENABLED+ #include "stm32wbxx_hal_dma.h"+#endif /* HAL_DMA_MODULE_ENABLED */++#ifdef HAL_ADC_MODULE_ENABLED+ #include "stm32wbxx_hal_adc.h"+#endif /* HAL_ADC_MODULE_ENABLED */++#ifdef HAL_COMP_MODULE_ENABLED+ #include "stm32wbxx_hal_comp.h"+#endif /* HAL_COMP_MODULE_ENABLED */++#ifdef HAL_CORTEX_MODULE_ENABLED+ #include "stm32wbxx_hal_cortex.h"+#endif /* HAL_CORTEX_MODULE_ENABLED */++#ifdef HAL_CRC_MODULE_ENABLED+ #include "stm32wbxx_hal_crc.h"+#endif /* HAL_CRC_MODULE_ENABLED */++#ifdef HAL_CRYP_MODULE_ENABLED+ #include "stm32wbxx_hal_cryp.h"+#endif /* HAL_CRYP_MODULE_ENABLED */++#ifdef HAL_EXTI_MODULE_ENABLED+ #include "stm32wbxx_hal_exti.h"+#endif /* HAL_EXTI_MODULE_ENABLED */++#ifdef HAL_FLASH_MODULE_ENABLED+ #include "stm32wbxx_hal_flash.h"+#endif /* HAL_FLASH_MODULE_ENABLED */++#ifdef HAL_GPIO_MODULE_ENABLED+ #include "stm32wbxx_hal_gpio.h"+#endif /* HAL_GPIO_MODULE_ENABLED */++#ifdef HAL_HSEM_MODULE_ENABLED+ #include "stm32wbxx_hal_hsem.h"+#endif /* HAL_HSEM_MODULE_ENABLED */++#ifdef HAL_I2C_MODULE_ENABLED+ #include "stm32wbxx_hal_i2c.h"+#endif /* HAL_I2C_MODULE_ENABLED */++#ifdef HAL_IPCC_MODULE_ENABLED+ #include "stm32wbxx_hal_ipcc.h"+#endif /* HAL_IPCC_MODULE_ENABLED */++#ifdef HAL_IRDA_MODULE_ENABLED+ #include "stm32wbxx_hal_irda.h"+#endif /* HAL_IRDA_MODULE_ENABLED */++#ifdef HAL_IWDG_MODULE_ENABLED+ #include "stm32wbxx_hal_iwdg.h"+#endif /* HAL_IWDG_MODULE_ENABLED */++#ifdef HAL_LCD_MODULE_ENABLED+ #include "stm32wbxx_hal_lcd.h"+#endif /* HAL_LCD_MODULE_ENABLED */++#ifdef HAL_LPTIM_MODULE_ENABLED+ #include "stm32wbxx_hal_lptim.h"+#endif /* HAL_LPTIM_MODULE_ENABLED */++#ifdef HAL_PCD_MODULE_ENABLED+ #include "stm32wbxx_hal_pcd.h"+#endif /* HAL_PCD_MODULE_ENABLED */++#ifdef HAL_PKA_MODULE_ENABLED+ #include "stm32wbxx_hal_pka.h"+#endif /* HAL_PKA_MODULE_ENABLED */++#ifdef HAL_PWR_MODULE_ENABLED+ #include "stm32wbxx_hal_pwr.h"+#endif /* HAL_PWR_MODULE_ENABLED */++#ifdef HAL_QSPI_MODULE_ENABLED+ #include "stm32wbxx_hal_qspi.h"+#endif /* HAL_QSPI_MODULE_ENABLED */++#ifdef HAL_RCC_MODULE_ENABLED+ #include "stm32wbxx_hal_rcc.h"+#endif /* HAL_RCC_MODULE_ENABLED */++#ifdef HAL_RNG_MODULE_ENABLED+ #include "stm32wbxx_hal_rng.h"+#endif /* HAL_RNG_MODULE_ENABLED */++#ifdef HAL_RTC_MODULE_ENABLED+ #include "stm32wbxx_hal_rtc.h"+#endif /* HAL_RTC_MODULE_ENABLED */++#ifdef HAL_SAI_MODULE_ENABLED+ #include "stm32wbxx_hal_sai.h"+#endif /* HAL_SAI_MODULE_ENABLED */++#ifdef HAL_SMARTCARD_MODULE_ENABLED+ #include "stm32wbxx_hal_smartcard.h"+#endif /* HAL_SMARTCARD_MODULE_ENABLED */++#ifdef HAL_SMBUS_MODULE_ENABLED+ #include "stm32wbxx_hal_smbus.h"+#endif /* HAL_SMBUS_MODULE_ENABLED */++#ifdef HAL_SPI_MODULE_ENABLED+ #include "stm32wbxx_hal_spi.h"+#endif /* HAL_SPI_MODULE_ENABLED */++#ifdef HAL_TIM_MODULE_ENABLED+ #include "stm32wbxx_hal_tim.h"+#endif /* HAL_TIM_MODULE_ENABLED */++#ifdef HAL_TSC_MODULE_ENABLED+ #include "stm32wbxx_hal_tsc.h"+#endif /* HAL_TSC_MODULE_ENABLED */++#ifdef HAL_UART_MODULE_ENABLED+ #include "stm32wbxx_hal_uart.h"+#endif /* HAL_UART_MODULE_ENABLED */++#ifdef HAL_USART_MODULE_ENABLED+ #include "stm32wbxx_hal_usart.h"+#endif /* HAL_USART_MODULE_ENABLED */++#ifdef HAL_WWDG_MODULE_ENABLED+ #include "stm32wbxx_hal_wwdg.h"+#endif /* HAL_WWDG_MODULE_ENABLED */++/* Exported macro ------------------------------------------------------------*/+#ifdef USE_FULL_ASSERT+/**+ * @brief The assert_param macro is used for function's parameters check.+ * @param expr If expr is false, it calls assert_failed function+ * which reports the name of the source file and the source+ * line number of the call that failed.+ * If expr is true, it returns no value.+ * @retval None+ */+ #define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__))+/* Exported functions ------------------------------------------------------- */+ void assert_failed(uint8_t* file, uint32_t line);+#else+ #define assert_param(expr) ((void)0U)+#endif /* USE_FULL_ASSERT */++#ifdef __cplusplus+}+#endif++#endif /* __STM32WBxx_HAL_CONF_H */diff --git a/firmware/ota_bootloader/Core/Inc/utilities_conf.h b/firmware/ota_bootloader/Core/Inc/utilities_conf.hnew file mode 100644index 0000000..b301820--- /dev/null+++ b/firmware/ota_bootloader/Core/Inc/utilities_conf.h@@ -0,0 +1,66 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file utilities_conf.h+ * @author MCD Application Team+ * @brief Configuration file for STM32 Utilities.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef UTILITIES_CONF_H+#define UTILITIES_CONF_H++#ifdef __cplusplus+extern "C" {+#endif++#include "cmsis_compiler.h"+#include "string.h"+#include "app_conf.h"++/******************************************************************************+ * common+ ******************************************************************************/+#define UTILS_ENTER_CRITICAL_SECTION( ) uint32_t primask_bit = __get_PRIMASK( );\+ __disable_irq( )++#define UTILS_EXIT_CRITICAL_SECTION( ) __set_PRIMASK( primask_bit )++#define UTILS_MEMSET8( dest, value, size ) memset( dest, value, size);++/******************************************************************************+ * tiny low power manager+ * (any macro that does not need to be modified can be removed)+ ******************************************************************************/+#define UTIL_LPM_INIT_CRITICAL_SECTION( )+#define UTIL_LPM_ENTER_CRITICAL_SECTION( ) UTILS_ENTER_CRITICAL_SECTION( )+#define UTIL_LPM_EXIT_CRITICAL_SECTION( ) UTILS_EXIT_CRITICAL_SECTION( )++/******************************************************************************+ * sequencer+ * (any macro that does not need to be modified can be removed)+ ******************************************************************************/+#define UTIL_SEQ_INIT_CRITICAL_SECTION( )+#define UTIL_SEQ_ENTER_CRITICAL_SECTION( ) UTILS_ENTER_CRITICAL_SECTION( )+#define UTIL_SEQ_EXIT_CRITICAL_SECTION( ) UTILS_EXIT_CRITICAL_SECTION( )+#define UTIL_SEQ_CONF_TASK_NBR (32)+#define UTIL_SEQ_CONF_PRIO_NBR CFG_SCH_PRIO_NBR+#define UTIL_SEQ_MEMSET8( dest, value, size ) UTILS_MEMSET8( dest, value, size )++#ifdef __cplusplus+}+#endif++#endif /* UTILITIES_CONF_H */diff --git a/firmware/ota_bootloader/Core/Src/app_entry.c b/firmware/ota_bootloader/Core/Src/app_entry.cnew file mode 100644index 0000000..106e217--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/app_entry.c@@ -0,0 +1,97 @@+/*+ * 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).+ */+#include "app_common.h"+#include "main.h"+#include "app_entry.h"+#include "app_ble.h"+#include "ble.h"+#include "tl.h"+#include "stm32_seq.h"+#include "shci_tl.h"+#include "stm32_lpm.h"+#include "shci.h"++extern RTC_HandleTypeDef hrtc;++#define POOL_SIZE (CFG_TLBLE_EVT_QUEUE_LENGTH * 4U * DIVC((sizeof(TL_PacketHeader_t) + TL_BLE_EVENT_FRAME_SIZE), 4U))++PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static uint8_t EvtPool[POOL_SIZE];+PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static TL_CmdPacket_t SystemCmdBuffer;+PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static uint8_t SystemSpareEvtBuffer[sizeof(TL_PacketHeader_t) + TL_EVT_HDR_SIZE + 255U];+PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static uint8_t BleSpareEvtBuffer[sizeof(TL_PacketHeader_t) + TL_EVT_HDR_SIZE + 255U];++static void APPE_SysStatusNot(SHCI_TL_CmdStatus_t status)+{+ UNUSED(status);+}++static void APPE_SysUserEvtRx(void *pPayload)+{+ TL_AsynchEvt_t *p_sys_event = (TL_AsynchEvt_t *)(((tSHCI_UserEvtRxParam *)pPayload)->pckt->evtserial.evt.payload);+ if (p_sys_event->subevtcode != SHCI_SUB_EVT_CODE_READY) return;++ 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)+ {+ SHCI_C2_SetFlashActivityControl(FLASH_ACTIVITY_CONTROL_SEM7);+ UTIL_LPM_SetOffMode(1 << CFG_LPM_APP, UTIL_LPM_ENABLE);+ APP_BLE_Init();+ }+ else+ {+ ((tSHCI_UserEvtRxParam *)pPayload)->status = SHCI_TL_UserEventFlow_Disable;+ BOOT_RequestSystemDfu(); /* no BLE stack: USB DFU is the only way in */+ }+}++void APPE_Init(void)+{+ __HAL_RCC_HSEM_CLK_ENABLE();+ LL_RCC_SetClkAfterWakeFromStop(LL_RCC_STOP_WAKEUPCLOCK_HSI);+ UTIL_LPM_Init();+ LL_C2_PWR_SetPowerMode(LL_PWR_MODE_SHUTDOWN);+ HW_TS_Init(hw_ts_InitMode_Full, &hrtc);+ UTIL_LPM_SetOffMode(1 << CFG_LPM_APP, UTIL_LPM_DISABLE);++ TL_MM_Config_t tl_mm_config;+ SHCI_TL_HciInitConf_t shci_conf;+ TL_Init();+ UTIL_SEQ_RegTask(1 << CFG_TASK_SYSTEM_HCI_ASYNCH_EVT_ID, UTIL_SEQ_RFU, shci_user_evt_proc);+ shci_conf.p_cmdbuffer = (uint8_t *)&SystemCmdBuffer;+ shci_conf.StatusNotCallBack = APPE_SysStatusNot;+ shci_init(APPE_SysUserEvtRx, (void *)&shci_conf);+ tl_mm_config.p_BleSpareEvtBuffer = BleSpareEvtBuffer;+ tl_mm_config.p_SystemSpareEvtBuffer = SystemSpareEvtBuffer;+ tl_mm_config.p_AsynchEvtPool = EvtPool;+ tl_mm_config.AsynchEvtPoolSize = POOL_SIZE;+ TL_MM_Init(&tl_mm_config);+ TL_Enable();+}++void UTIL_SEQ_Idle(void)+{+}++void shci_notify_asynch_evt(void *pdata)+{+ UNUSED(pdata);+ UTIL_SEQ_SetTask(1 << CFG_TASK_SYSTEM_HCI_ASYNCH_EVT_ID, CFG_SCH_PRIO_0);+}++void shci_cmd_resp_release(uint32_t flag)+{+ UNUSED(flag);+ UTIL_SEQ_SetEvt(1 << CFG_IDLEEVT_SYSTEM_HCI_CMD_EVT_RSP_ID);+}++void shci_cmd_resp_wait(uint32_t timeout)+{+ UNUSED(timeout);+ UTIL_SEQ_WaitEvt(1 << CFG_IDLEEVT_SYSTEM_HCI_CMD_EVT_RSP_ID);+}diff --git a/firmware/ota_bootloader/Core/Src/flash_driver.c b/firmware/ota_bootloader/Core/Src/flash_driver.cnew file mode 100644index 0000000..8279bf7--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/flash_driver.c@@ -0,0 +1,324 @@+/**+ ******************************************************************************+ * File Name : flash_driver.c+ * Description : Dual core Flash driver+ *+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */++/* Includes ------------------------------------------------------------------*/+#include "app_common.h"++#include "flash_driver.h"+#include "shci.h"+#include "utilities_conf.h"++/* Private typedef -----------------------------------------------------------*/+typedef enum+{+ SEM_LOCK_SUCCESSFUL,+ SEM_LOCK_BUSY,+}SemStatus_t;++typedef enum+{+ FLASH_ERASE,+ FLASH_WRITE,+}FlashOperationType_t;++/* Private defines -----------------------------------------------------------*/+/* Private macros ------------------------------------------------------------*/+/* Private variables ---------------------------------------------------------*/+/* Global variables ----------------------------------------------------------*/+/* Private function prototypes -----------------------------------------------*/+static SingleFlashOperationStatus_t ProcessSingleFlashOperation(FlashOperationType_t FlashOperationType,+ uint32_t SectorNumberOrDestAddress,+ uint64_t Data);+/* Public functions ----------------------------------------------------------*/+uint32_t FD_EraseSectors(uint32_t FirstSector, uint32_t NbrOfSectors)+{+ uint32_t loop_flash;+ uint32_t return_value;+ SingleFlashOperationStatus_t single_flash_operation_status;++ single_flash_operation_status = SINGLE_FLASH_OPERATION_DONE;++ /**+ * Take the semaphore to take ownership of the Flash IP+ */+ while(LL_HSEM_1StepLock(HSEM, CFG_HW_FLASH_SEMID));++ HAL_FLASH_Unlock();++ /**+ * Notify the CPU2 that some flash erase activity may be executed+ * On reception of this command, the CPU2 enables the BLE timing protection versus flash erase processing+ * The Erase flash activity will be executed only when the BLE RF is idle for at least 25ms+ * The CPU2 will prevent all flash activity (write or erase) in all cases when the BL RF Idle is shorter than 25ms.+ */+ SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_ON);++ for(loop_flash = 0; (loop_flash < NbrOfSectors) && (single_flash_operation_status == SINGLE_FLASH_OPERATION_DONE) ; loop_flash++)+ {+ single_flash_operation_status = FD_EraseSingleSector(FirstSector+loop_flash);+ }++ if(single_flash_operation_status != SINGLE_FLASH_OPERATION_DONE)+ {+ return_value = NbrOfSectors - loop_flash + 1;+ }+ else+ {+ /**+ * Notify the CPU2 there will be no request anymore to erase the flash+ * On reception of this command, the CPU2 will disables the BLE timing protection versus flash erase processing+ * The protection is active until next end of radio event.+ */+ SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_OFF);++ HAL_FLASH_Lock();++ /**+ * Release the ownership of the Flash IP+ */+ LL_HSEM_ReleaseLock(HSEM, CFG_HW_FLASH_SEMID, 0);++ return_value = 0;+ }++ return return_value;+}++uint32_t FD_WriteData(uint32_t DestAddress, uint64_t * pSrcBuffer, uint32_t NbrOfData)+{+ uint32_t loop_flash;+ uint32_t return_value;+ SingleFlashOperationStatus_t single_flash_operation_status;++ single_flash_operation_status = SINGLE_FLASH_OPERATION_DONE;++ /**+ * Take the semaphore to take ownership of the Flash IP+ */+ while(LL_HSEM_1StepLock(HSEM, CFG_HW_FLASH_SEMID));++ HAL_FLASH_Unlock();++ for(loop_flash = 0; (loop_flash < NbrOfData) && (single_flash_operation_status == SINGLE_FLASH_OPERATION_DONE) ; loop_flash++)+ {+ single_flash_operation_status = FD_WriteSingleData(DestAddress+(8*loop_flash), *(pSrcBuffer+loop_flash));+ }++ if(single_flash_operation_status != SINGLE_FLASH_OPERATION_DONE)+ {+ return_value = NbrOfData - loop_flash + 1;+ }+ else+ {+ HAL_FLASH_Lock();++ /**+ * Release the ownership of the Flash IP+ */+ LL_HSEM_ReleaseLock(HSEM, CFG_HW_FLASH_SEMID, 0);++ return_value = 0;+ }++ return return_value;+}++SingleFlashOperationStatus_t FD_EraseSingleSector(uint32_t SectorNumber)+{+ SingleFlashOperationStatus_t return_value;++ /* Add at least 5us (CPU1 up to 64MHz) to guarantee that CPU2 can take SEM7 to protect BLE timing */+ for (volatile uint32_t i = 0; i < 35; i++);++ /* The last parameter is unused in that case and set to 0 */+ return_value = ProcessSingleFlashOperation(FLASH_ERASE, SectorNumber, 0);++ return return_value;+}++SingleFlashOperationStatus_t FD_WriteSingleData(uint32_t DestAddress, uint64_t Data)+{+ SingleFlashOperationStatus_t return_value;++ return_value = ProcessSingleFlashOperation(FLASH_WRITE, DestAddress, Data);++ return return_value;+}++/*************************************************************+ *+ * LOCAL FUNCTIONS+ *+ *************************************************************/+static SingleFlashOperationStatus_t ProcessSingleFlashOperation(FlashOperationType_t FlashOperationType,+ uint32_t SectorNumberOrDestAddress,+ uint64_t Data)+{+ SemStatus_t cpu1_sem_status;+ SemStatus_t cpu2_sem_status;+ WaitedSemStatus_t waited_sem_status;+ SingleFlashOperationStatus_t return_status;++ uint32_t page_error;+ FLASH_EraseInitTypeDef p_erase_init;++ waited_sem_status = WAITED_SEM_FREE;++ p_erase_init.TypeErase = FLASH_TYPEERASE_PAGES;+ p_erase_init.NbPages = 1;+ p_erase_init.Page = SectorNumberOrDestAddress;++ do+ {+ /**+ * When the PESD bit mechanism is used by CPU2 to protect its timing, the PESD bit should be polled here.+ * If the PESD is set, the CPU1 will be stalled when reading literals from an ISR that may occur after+ * the flash processing has been requested but suspended due to the PESD bit.+ *+ * Note: This code is required only when the PESD mechanism is used to protect the CPU2 timing.+ * However, keeping that code make it compatible with the two mechanisms.+ */+ while(LL_FLASH_IsActiveFlag_OperationSuspended());++ UTILS_ENTER_CRITICAL_SECTION();++ /**+ * Depending on the application implementation, in case a multitasking is possible with an OS,+ * it should be checked here if another task in the application disallowed flash processing to protect+ * some latency in critical code execution+ * When flash processing is ongoing, the CPU cannot access the flash anymore.+ * Trying to access the flash during that time stalls the CPU.+ * The only way for CPU1 to disallow flash processing is to take CFG_HW_BLOCK_FLASH_REQ_BY_CPU1_SEMID.+ */+ cpu1_sem_status = (SemStatus_t)LL_HSEM_GetStatus(HSEM, CFG_HW_BLOCK_FLASH_REQ_BY_CPU1_SEMID);+ if(cpu1_sem_status == SEM_LOCK_SUCCESSFUL)+ {+ /**+ * Check now if the CPU2 disallows flash processing to protect its timing.+ * If the semaphore is locked, the CPU2 does not allow flash processing+ *+ * Note: By default, the CPU2 uses the PESD mechanism to protect its timing,+ * therefore, it is useless to get/release the semaphore.+ *+ * However, keeping that code make it compatible with the two mechanisms.+ * The protection by semaphore is enabled on CPU2 side with the command SHCI_C2_SetFlashActivityControl()+ *+ */+ cpu2_sem_status = (SemStatus_t)LL_HSEM_1StepLock(HSEM, CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID);+ if(cpu2_sem_status == SEM_LOCK_SUCCESSFUL)+ {+ /**+ * When CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID is taken, it is allowed to only erase one sector or+ * write one single 64bits data+ * When either several sectors need to be erased or several 64bits data need to be written,+ * the application shall first exit from the critical section and try again.+ */+ if(FlashOperationType == FLASH_ERASE)+ {+ HAL_FLASHEx_Erase(&p_erase_init, &page_error);+ }+ else+ {+ HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, SectorNumberOrDestAddress, Data);+ }+ /**+ * Release the semaphore to give the opportunity to CPU2 to protect its timing versus the next flash operation+ * by taking this semaphore.+ * Note that the CPU2 is polling on this semaphore so CPU1 shall release it as fast as possible.+ * This is why this code is protected by a critical section.+ */+ LL_HSEM_ReleaseLock(HSEM, CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID, 0);+ }+ }++ UTILS_EXIT_CRITICAL_SECTION();++ if(cpu1_sem_status != SEM_LOCK_SUCCESSFUL)+ {+ /**+ * To avoid looping in ProcessSingleFlashOperation(), FD_WaitForSemAvailable() should implement a mechanism to+ * continue only when CFG_HW_BLOCK_FLASH_REQ_BY_CPU1_SEMID is free+ */+ waited_sem_status = FD_WaitForSemAvailable(WAIT_FOR_SEM_BLOCK_FLASH_REQ_BY_CPU1);+ }+ else if(cpu2_sem_status != SEM_LOCK_SUCCESSFUL)+ {+ /**+ * To avoid looping in ProcessSingleFlashOperation(), FD_WaitForSemAvailable() should implement a mechanism to+ * continue only when CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID is free+ */+ waited_sem_status = FD_WaitForSemAvailable(WAIT_FOR_SEM_BLOCK_FLASH_REQ_BY_CPU2);+ }+ }+ while( ((cpu2_sem_status != SEM_LOCK_SUCCESSFUL) || (cpu1_sem_status != SEM_LOCK_SUCCESSFUL))+ && (waited_sem_status != WAITED_SEM_BUSY) );++ /**+ * In most BLE application, the flash should not be blocked by the CPU2 longer than FLASH_TIMEOUT_VALUE (1000ms)+ * However, it could be that for some marginal application, this time is longer.+ * In that case either HAL_FLASHEx_Erase() or HAL_FLASH_Program() will exit with FLASH_TIMEOUT_VALUE value.+ * This is not a failing case and there is no other way than waiting the operation to be completed.+ * If for any reason this test is never passed, this means there is a failure in the system and there is no other+ * way to recover than applying a device reset.+ *+ * Note: This code is required only when the PESD mechanism is used to protect the CPU2 timing.+ * However, keeping that code make it compatible with the two mechanisms.+ */+ while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_CFGBSY));++ if(waited_sem_status != WAITED_SEM_BUSY)+ {+ /**+ * The flash processing has been done. It has not been checked whether it has been successful or not.+ * The only commitment is that it is possible to request a new flash processing+ */+ return_status = SINGLE_FLASH_OPERATION_DONE;+ }+ else+ {+ /**+ * The flash processing has not been executed due to timing protection from either the CPU1 or the CPU2.+ * This status is reported up to the user that should retry after checking that each CPU do not+ * protect its timing anymore.+ */+ return_status = SINGLE_FLASH_OPERATION_NOT_EXECUTED;+ }++ return return_status;+}++/*************************************************************+ *+ * WEAK FUNCTIONS+ *+ *************************************************************/+__WEAK WaitedSemStatus_t FD_WaitForSemAvailable(WaitedSemId_t WaitedSemId)+{+ /**+ * The timing protection is enabled by either CPU1 or CPU2. It should be decided here if the driver shall+ * keep trying to erase/write the flash until successful or if it shall exit and report to the user that the action+ * has not been executed.+ * WAITED_SEM_BUSY returns to the user+ * WAITED_SEM_FREE keep looping in the driver until the action is executed. This will result in the current stack looping+ * until this is done. In a bare metal implementation, only the code within interrupt handler can be executed. With an OS,+ * only task with higher priority can be processed+ *+ */+ return WAITED_SEM_BUSY;+}+diff --git a/firmware/ota_bootloader/Core/Src/hw_timerserver.c b/firmware/ota_bootloader/Core/Src/hw_timerserver.cnew file mode 100644index 0000000..a895535--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/hw_timerserver.c@@ -0,0 +1,888 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file hw_timerserver.c+ * @author MCD Application Team+ * @brief Hardware timerserver source file for STM32WPAN Middleware.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Includes ------------------------------------------------------------------*/+#include "app_common.h"+#include "hw_conf.h"++/* Private typedef -----------------------------------------------------------*/+typedef enum+{+ TimerID_Free,+ TimerID_Created,+ TimerID_Running+}TimerIDStatus_t;++typedef enum+{+ SSR_Read_Requested,+ SSR_Read_Not_Requested+}RequestReadSSR_t;++typedef enum+{+ WakeupTimerValue_Overpassed,+ WakeupTimerValue_LargeEnough+}WakeupTimerLimitation_Status_t;++typedef struct+{+ HW_TS_pTimerCb_t pTimerCallBack;+ uint32_t CounterInit;+ uint32_t CountLeft;+ TimerIDStatus_t TimerIDStatus;+ HW_TS_Mode_t TimerMode;+ uint32_t TimerProcessID;+ uint8_t PreviousID;+ uint8_t NextID;+}TimerContext_t;++/* Private defines -----------------------------------------------------------*/+#define SSR_FORBIDDEN_VALUE 0xFFFFFFFF+#define TIMER_LIST_EMPTY 0xFFFF++/* Private macros ------------------------------------------------------------*/+/* Private variables ---------------------------------------------------------*/++/**+ * START of Section TIMERSERVER_CONTEXT+ */++static volatile TimerContext_t aTimerContext[CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER];+static volatile uint8_t CurrentRunningTimerID;+static volatile uint8_t PreviousRunningTimerID;+static volatile uint32_t SSRValueOnLastSetup;+static volatile WakeupTimerLimitation_Status_t WakeupTimerLimitation;++/**+ * END of Section TIMERSERVER_CONTEXT+ */++static uint8_t WakeupTimerDivider;+static uint8_t AsynchPrescalerUserConfig;+static uint16_t SynchPrescalerUserConfig;+static volatile uint16_t MaxWakeupTimerSetup;++/* Global variables ----------------------------------------------------------*/+extern RTC_HandleTypeDef hrtc;++/* Private function prototypes -----------------------------------------------*/+static void RestartWakeupCounter(uint16_t Value);+static uint16_t ReturnTimeElapsed(void);+static void RescheduleTimerList(void);+static void UnlinkTimer(uint8_t TimerID, RequestReadSSR_t RequestReadSSR);+static void LinkTimerBefore(uint8_t TimerID, uint8_t RefTimerID);+static void LinkTimerAfter(uint8_t TimerID, uint8_t RefTimerID);+static uint16_t linkTimer(uint8_t TimerID);+static uint32_t ReadRtcSsrValue(void);++__weak void HW_TS_RTC_CountUpdated_AppNot(void);++/* Functions Definition ------------------------------------------------------*/++/**+ * @brief Read the RTC_SSR value+ * As described in the reference manual, the RTC_SSR shall be read twice to ensure+ * reliability of the value+ * @param None+ * @retval SSR value read+ */+static uint32_t ReadRtcSsrValue(void)+{+ uint32_t first_read;+ uint32_t second_read;++ first_read = (uint32_t)(READ_BIT(RTC->SSR, RTC_SSR_SS));++ second_read = (uint32_t)(READ_BIT(RTC->SSR, RTC_SSR_SS));++ while(first_read != second_read)+ {+ first_read = second_read;++ second_read = (uint32_t)(READ_BIT(RTC->SSR, RTC_SSR_SS));+ }++ return second_read;+}++/**+ * @brief Insert a Timer in the list after the Timer ID specified+ * @param TimerID: The ID of the Timer+ * @param RefTimerID: The ID of the Timer to be linked after+ * @retval None+ */+static void LinkTimerAfter(uint8_t TimerID, uint8_t RefTimerID)+{+ uint8_t next_id;++ next_id = aTimerContext[RefTimerID].NextID;++ if(next_id != CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER)+ {+ aTimerContext[next_id].PreviousID = TimerID;+ }+ aTimerContext[TimerID].NextID = next_id;+ aTimerContext[TimerID].PreviousID = RefTimerID ;+ aTimerContext[RefTimerID].NextID = TimerID;++ return;+}++/**+ * @brief Insert a Timer in the list before the ID specified+ * @param TimerID: The ID of the Timer+ * @param RefTimerID: The ID of the Timer to be linked before+ * @retval None+ */+static void LinkTimerBefore(uint8_t TimerID, uint8_t RefTimerID)+{+ uint8_t previous_id;++ if(RefTimerID != CurrentRunningTimerID)+ {+ previous_id = aTimerContext[RefTimerID].PreviousID;++ aTimerContext[previous_id].NextID = TimerID;+ aTimerContext[TimerID].NextID = RefTimerID;+ aTimerContext[TimerID].PreviousID = previous_id ;+ aTimerContext[RefTimerID].PreviousID = TimerID;+ }+ else+ {+ aTimerContext[TimerID].NextID = RefTimerID;+ aTimerContext[RefTimerID].PreviousID = TimerID;+ }++ return;+}++/**+ * @brief Insert a Timer in the list+ * @param TimerID: The ID of the Timer+ * @retval None+ */+static uint16_t linkTimer(uint8_t TimerID)+{+ uint32_t time_left;+ uint16_t time_elapsed;+ uint8_t timer_id_lookup;+ uint8_t next_id;++ if(CurrentRunningTimerID == CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER)+ {+ /**+ * No timer in the list+ */+ PreviousRunningTimerID = CurrentRunningTimerID;+ CurrentRunningTimerID = TimerID;+ aTimerContext[TimerID].NextID = CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER;++ SSRValueOnLastSetup = SSR_FORBIDDEN_VALUE;+ time_elapsed = 0;+ }+ else+ {+ time_elapsed = ReturnTimeElapsed();++ /**+ * update count of the timer to be linked+ */+ aTimerContext[TimerID].CountLeft += time_elapsed;+ time_left = aTimerContext[TimerID].CountLeft;++ /**+ * Search for index where the new timer shall be linked+ */+ if(aTimerContext[CurrentRunningTimerID].CountLeft <= time_left)+ {+ /**+ * Search for the ID after the first one+ */+ timer_id_lookup = CurrentRunningTimerID;+ next_id = aTimerContext[timer_id_lookup].NextID;+ while((next_id != CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER) && (aTimerContext[next_id].CountLeft <= time_left))+ {+ timer_id_lookup = aTimerContext[timer_id_lookup].NextID;+ next_id = aTimerContext[timer_id_lookup].NextID;+ }++ /**+ * Link after the ID+ */+ LinkTimerAfter(TimerID, timer_id_lookup);+ }+ else+ {+ /**+ * Link before the first ID+ */+ LinkTimerBefore(TimerID, CurrentRunningTimerID);+ PreviousRunningTimerID = CurrentRunningTimerID;+ CurrentRunningTimerID = TimerID;+ }+ }++ return time_elapsed;+}++/**+ * @brief Remove a Timer from the list+ * @param TimerID: The ID of the Timer+ * @param RequestReadSSR: Request to read the SSR register or not+ * @retval None+ */+static void UnlinkTimer(uint8_t TimerID, RequestReadSSR_t RequestReadSSR)+{+ uint8_t previous_id;+ uint8_t next_id;++ if(TimerID == CurrentRunningTimerID)+ {+ PreviousRunningTimerID = CurrentRunningTimerID;+ CurrentRunningTimerID = aTimerContext[TimerID].NextID;+ }+ else+ {+ previous_id = aTimerContext[TimerID].PreviousID;+ next_id = aTimerContext[TimerID].NextID;++ aTimerContext[previous_id].NextID = aTimerContext[TimerID].NextID;+ if(next_id != CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER)+ {+ aTimerContext[next_id].PreviousID = aTimerContext[TimerID].PreviousID;+ }+ }++ /**+ * Timer is out of the list+ */+ aTimerContext[TimerID].TimerIDStatus = TimerID_Created;++ if((CurrentRunningTimerID == CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER) && (RequestReadSSR == SSR_Read_Requested))+ {+ SSRValueOnLastSetup = SSR_FORBIDDEN_VALUE;+ }++ return;+}++/**+ * @brief Return the number of ticks counted by the wakeuptimer since it has been started+ * @note The API is reading the SSR register to get how many ticks have been counted+ * since the time the timer has been started+ * @param None+ * @retval Time expired in Ticks+ */+static uint16_t ReturnTimeElapsed(void)+{+ uint32_t return_value;+ uint32_t wrap_counter;++ if(SSRValueOnLastSetup != SSR_FORBIDDEN_VALUE)+ {+ return_value = ReadRtcSsrValue(); /**< Read SSR register first */++ if (SSRValueOnLastSetup >= return_value)+ {+ return_value = SSRValueOnLastSetup - return_value;+ }+ else+ {+ wrap_counter = SynchPrescalerUserConfig - return_value;+ return_value = SSRValueOnLastSetup + wrap_counter;+ }++ /**+ * At this stage, ReturnValue holds the number of ticks counted by SSR+ * Need to translate in number of ticks counted by the Wakeuptimer+ */+ return_value = return_value*AsynchPrescalerUserConfig;+ return_value = return_value >> WakeupTimerDivider;+ }+ else+ {+ return_value = 0;+ }++ return (uint16_t)return_value;+}++/**+ * @brief Set the wakeup counter+ * @note The API is writing the counter value so that the value is decreased by one to cope with the fact+ * the interrupt is generated with 1 extra clock cycle (See RefManuel)+ * It assumes all condition are met to be allowed to write the wakeup counter+ * @param Value: Value to be written in the counter+ * @retval None+ */+static void RestartWakeupCounter(uint16_t Value)+{+ /**+ * The wakeuptimer has been disabled in the calling function to reduce the time to poll the WUTWF+ * FLAG when the new value will have to be written+ * __HAL_RTC_WAKEUPTIMER_DISABLE(&hrtc);+ */++ if(Value == 0)+ {+ SSRValueOnLastSetup = ReadRtcSsrValue();++ /**+ * Simulate that the Timer expired+ */+ HAL_NVIC_SetPendingIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID);+ }+ else+ {+ if((Value > 1) ||(WakeupTimerDivider != 1))+ {+ Value -= 1;+ }++ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTWF) == RESET);++ /**+ * make sure to clear the flags after checking the WUTWF.+ * It takes 2 RTCCLK between the time the WUTE bit is disabled and the+ * time the timer is disabled. The WUTWF bit somehow guarantee the system is stable+ * Otherwise, when the timer is periodic with 1 Tick, it may generate an extra interrupt in between+ * due to the autoreload feature+ */+ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, RTC_FLAG_WUTF); /**< Clear flag in RTC module */+ __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG(); /**< Clear flag in EXTI module */+ HAL_NVIC_ClearPendingIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Clear pending bit in NVIC */++ MODIFY_REG(RTC->WUTR, RTC_WUTR_WUT, Value);++ /**+ * Update the value here after the WUTWF polling that may take some time+ */+ SSRValueOnLastSetup = ReadRtcSsrValue();++ __HAL_RTC_WAKEUPTIMER_ENABLE(&hrtc); /**< Enable the Wakeup Timer */++ HW_TS_RTC_CountUpdated_AppNot();+ }++ return ;+}++/**+ * @brief Reschedule the list of timer+ * @note 1) Update the count left for each timer in the list+ * 2) Setup the wakeuptimer+ * @param None+ * @retval None+ */+static void RescheduleTimerList(void)+{+ uint8_t localTimerID;+ uint32_t timecountleft;+ uint16_t wakeup_timer_value;+ uint16_t time_elapsed;++ /**+ * The wakeuptimer is disabled now to reduce the time to poll the WUTWF+ * FLAG when the new value will have to be written+ */+ if((READ_BIT(RTC->CR, RTC_CR_WUTE) == (RTC_CR_WUTE)) == SET)+ {+ /**+ * Wait for the flag to be back to 0 when the wakeup timer is enabled+ */+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTWF) == SET);+ }+ __HAL_RTC_WAKEUPTIMER_DISABLE(&hrtc); /**< Disable the Wakeup Timer */++ localTimerID = CurrentRunningTimerID;++ /**+ * Calculate what will be the value to write in the wakeuptimer+ */+ timecountleft = aTimerContext[localTimerID].CountLeft;++ /**+ * Read how much has been counted+ */+ time_elapsed = ReturnTimeElapsed();++ if(timecountleft < time_elapsed )+ {+ /**+ * There is no tick left to count+ */+ wakeup_timer_value = 0;+ WakeupTimerLimitation = WakeupTimerValue_LargeEnough;+ }+ else+ {+ if(timecountleft > (time_elapsed + MaxWakeupTimerSetup))+ {+ /**+ * The number of tick left is greater than the Wakeuptimer maximum value+ */+ wakeup_timer_value = MaxWakeupTimerSetup;++ WakeupTimerLimitation = WakeupTimerValue_Overpassed;+ }+ else+ {+ wakeup_timer_value = timecountleft - time_elapsed;+ WakeupTimerLimitation = WakeupTimerValue_LargeEnough;+ }++ }++ /**+ * update ticks left to be counted for each timer+ */+ while(localTimerID != CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER)+ {+ if (aTimerContext[localTimerID].CountLeft < time_elapsed)+ {+ aTimerContext[localTimerID].CountLeft = 0;+ }+ else+ {+ aTimerContext[localTimerID].CountLeft -= time_elapsed;+ }+ localTimerID = aTimerContext[localTimerID].NextID;+ }++ /**+ * Write next count+ */+ RestartWakeupCounter(wakeup_timer_value);++ return ;+}++/* Public functions ----------------------------------------------------------*/++/**+ * For all public interface except that may need write access to the RTC, the RTC+ * shall be unlock at the beginning and locked at the output+ * In order to ease maintainability, the unlock is done at the top and the lock at then end+ * in case some new implementation is coming in the future+ */++void HW_TS_RTC_Wakeup_Handler(void)+{+ HW_TS_pTimerCb_t ptimer_callback;+ uint32_t timer_process_id;+ uint8_t local_current_running_timer_id;+#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ uint32_t primask_bit;+#endif++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ primask_bit = __get_PRIMASK(); /**< backup PRIMASK bit */+ __disable_irq(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/+#endif++/* Disable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_DISABLE( &hrtc );++ /**+ * Disable the Wakeup Timer+ * This may speed up a bit the processing to wait the timer to be disabled+ * The timer is still counting 2 RTCCLK+ */+ __HAL_RTC_WAKEUPTIMER_DISABLE(&hrtc);++ local_current_running_timer_id = CurrentRunningTimerID;++ if(aTimerContext[local_current_running_timer_id].TimerIDStatus == TimerID_Running)+ {+ ptimer_callback = aTimerContext[local_current_running_timer_id].pTimerCallBack;+ timer_process_id = aTimerContext[local_current_running_timer_id].TimerProcessID;++ /**+ * It should be good to check whether the TimeElapsed is greater or not than the tick left to be counted+ * However, due to the inaccuracy of the reading of the time elapsed, it may return there is 1 tick+ * to be left whereas the count is over+ * A more secure implementation has been done with a flag to state whereas the full count has been written+ * in the wakeuptimer or not+ */+ if(WakeupTimerLimitation != WakeupTimerValue_Overpassed)+ {+ if(aTimerContext[local_current_running_timer_id].TimerMode == hw_ts_Repeated)+ {+ UnlinkTimer(local_current_running_timer_id, SSR_Read_Not_Requested);+#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif+ HW_TS_Start(local_current_running_timer_id, aTimerContext[local_current_running_timer_id].CounterInit);++ /* Disable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_DISABLE( &hrtc );+ }+ else+ {+#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif+ HW_TS_Stop(local_current_running_timer_id);++ /* Disable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_DISABLE( &hrtc );+ }++ HW_TS_RTC_Int_AppNot(timer_process_id, local_current_running_timer_id, ptimer_callback);+ }+ else+ {+ RescheduleTimerList();+#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif+ }+ }+ else+ {+ /**+ * We should never end up in this case+ * However, if due to any bug in the timer server this is the case, the mistake may not impact the user.+ * We could just clean the interrupt flag and get out from this unexpected interrupt+ */+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTWF) == RESET);++ /**+ * make sure to clear the flags after checking the WUTWF.+ * It takes 2 RTCCLK between the time the WUTE bit is disabled and the+ * time the timer is disabled. The WUTWF bit somehow guarantee the system is stable+ * Otherwise, when the timer is periodic with 1 Tick, it may generate an extra interrupt in between+ * due to the autoreload feature+ */+ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, RTC_FLAG_WUTF); /**< Clear flag in RTC module */+ __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG(); /**< Clear flag in EXTI module */++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif+ }++ /* Enable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_ENABLE( &hrtc );++ return;+}++void HW_TS_Init(HW_TS_InitMode_t TimerInitMode, RTC_HandleTypeDef *phrtc)+{+ uint8_t loop;+ uint32_t localmaxwakeuptimersetup;++ /* Disable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_DISABLE( &hrtc );++ SET_BIT(RTC->CR, RTC_CR_BYPSHAD);++ /**+ * Readout the user config+ */+ WakeupTimerDivider = (4 - ((uint32_t)(READ_BIT(RTC->CR, RTC_CR_WUCKSEL))));++ AsynchPrescalerUserConfig = (uint8_t)(READ_BIT(RTC->PRER, RTC_PRER_PREDIV_A) >> (uint32_t)POSITION_VAL(RTC_PRER_PREDIV_A)) + 1;++ SynchPrescalerUserConfig = (uint16_t)(READ_BIT(RTC->PRER, RTC_PRER_PREDIV_S)) + 1;++ /**+ * Margin is taken to avoid wrong calculation when the wrap around is there and some+ * application interrupts may have delayed the reading+ */+ localmaxwakeuptimersetup = ((((SynchPrescalerUserConfig - 1)*AsynchPrescalerUserConfig) - CFG_HW_TS_RTC_HANDLER_MAX_DELAY) >> WakeupTimerDivider);++ if(localmaxwakeuptimersetup >= 0xFFFF)+ {+ MaxWakeupTimerSetup = 0xFFFF;+ }+ else+ {+ MaxWakeupTimerSetup = (uint16_t)localmaxwakeuptimersetup;+ }++ /**+ * Configure EXTI module+ */+ LL_EXTI_EnableRisingTrig_0_31(RTC_EXTI_LINE_WAKEUPTIMER_EVENT);+ LL_EXTI_EnableIT_0_31(RTC_EXTI_LINE_WAKEUPTIMER_EVENT);++ if(TimerInitMode == hw_ts_InitMode_Full)+ {+ WakeupTimerLimitation = WakeupTimerValue_LargeEnough;+ SSRValueOnLastSetup = SSR_FORBIDDEN_VALUE;++ /**+ * Initialize the timer server+ */+ for(loop = 0; loop < CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER; loop++)+ {+ aTimerContext[loop].TimerIDStatus = TimerID_Free;+ }++ CurrentRunningTimerID = CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER; /**< Set ID to non valid value */++ __HAL_RTC_WAKEUPTIMER_DISABLE(&hrtc); /**< Disable the Wakeup Timer */+ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, RTC_FLAG_WUTF); /**< Clear flag in RTC module */+ __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG(); /**< Clear flag in EXTI module */+ HAL_NVIC_ClearPendingIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Clear pending bit in NVIC */+ __HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hrtc, RTC_IT_WUT); /**< Enable interrupt in RTC module */+ }+ else+ {+ if(__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTF) != RESET)+ {+ /**+ * Simulate that the Timer expired+ */+ HAL_NVIC_SetPendingIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID);+ }+ }++ /* Enable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_ENABLE( &hrtc );++ HAL_NVIC_SetPriority(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID, CFG_HW_TS_NVIC_RTC_WAKEUP_IT_PREEMPTPRIO, CFG_HW_TS_NVIC_RTC_WAKEUP_IT_SUBPRIO); /**< Set NVIC priority */+ HAL_NVIC_EnableIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Enable NVIC */++ return;+}++HW_TS_ReturnStatus_t HW_TS_Create(uint32_t TimerProcessID, uint8_t *pTimerId, HW_TS_Mode_t TimerMode, HW_TS_pTimerCb_t pftimeout_handler)+{+ HW_TS_ReturnStatus_t localreturnstatus;+ uint8_t loop = 0;+#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ uint32_t primask_bit;+#endif++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ primask_bit = __get_PRIMASK(); /**< backup PRIMASK bit */+ __disable_irq(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/+#endif++ while((loop < CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER) && (aTimerContext[loop].TimerIDStatus != TimerID_Free))+ {+ loop++;+ }++ if(loop != CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER)+ {+ aTimerContext[loop].TimerIDStatus = TimerID_Created;++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif++ aTimerContext[loop].TimerProcessID = TimerProcessID;+ aTimerContext[loop].TimerMode = TimerMode;+ aTimerContext[loop].pTimerCallBack = pftimeout_handler;+ *pTimerId = loop;++ localreturnstatus = hw_ts_Successful;+ }+ else+ {+#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif++ localreturnstatus = hw_ts_Failed;+ }++ return(localreturnstatus);+}++void HW_TS_Delete(uint8_t timer_id)+{+ HW_TS_Stop(timer_id);++ aTimerContext[timer_id].TimerIDStatus = TimerID_Free; /**< release ID */++ return;+}++void HW_TS_Stop(uint8_t timer_id)+{+ uint8_t localcurrentrunningtimerid;++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ uint32_t primask_bit;+#endif++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ primask_bit = __get_PRIMASK(); /**< backup PRIMASK bit */+ __disable_irq(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/+#endif++ HAL_NVIC_DisableIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Disable NVIC */++ /* Disable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_DISABLE( &hrtc );++ if(aTimerContext[timer_id].TimerIDStatus == TimerID_Running)+ {+ UnlinkTimer(timer_id, SSR_Read_Requested);+ localcurrentrunningtimerid = CurrentRunningTimerID;++ if(localcurrentrunningtimerid == CFG_HW_TS_MAX_NBR_CONCURRENT_TIMER)+ {+ /**+ * List is empty+ */++ /**+ * Disable the timer+ */+ if((READ_BIT(RTC->CR, RTC_CR_WUTE) == (RTC_CR_WUTE)) == SET)+ {+ /**+ * Wait for the flag to be back to 0 when the wakeup timer is enabled+ */+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTWF) == SET);+ }+ __HAL_RTC_WAKEUPTIMER_DISABLE(&hrtc); /**< Disable the Wakeup Timer */++ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTWF) == RESET);++ /**+ * make sure to clear the flags after checking the WUTWF.+ * It takes 2 RTCCLK between the time the WUTE bit is disabled and the+ * time the timer is disabled. The WUTWF bit somehow guarantee the system is stable+ * Otherwise, when the timer is periodic with 1 Tick, it may generate an extra interrupt in between+ * due to the autoreload feature+ */+ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, RTC_FLAG_WUTF); /**< Clear flag in RTC module */+ __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG(); /**< Clear flag in EXTI module */+ HAL_NVIC_ClearPendingIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Clear pending bit in NVIC */+ }+ else if(PreviousRunningTimerID != localcurrentrunningtimerid)+ {+ RescheduleTimerList();+ }+ }++ /* Enable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_ENABLE( &hrtc );++ HAL_NVIC_EnableIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Enable NVIC */++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif++ return;+}++void HW_TS_Start(uint8_t timer_id, uint32_t timeout_ticks)+{+ uint16_t time_elapsed;+ uint8_t localcurrentrunningtimerid;++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ uint32_t primask_bit;+#endif++ if(aTimerContext[timer_id].TimerIDStatus == TimerID_Running)+ {+ HW_TS_Stop( timer_id );+ }++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ primask_bit = __get_PRIMASK(); /**< backup PRIMASK bit */+ __disable_irq(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/+#endif++ HAL_NVIC_DisableIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Disable NVIC */++ /* Disable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_DISABLE( &hrtc );++ aTimerContext[timer_id].TimerIDStatus = TimerID_Running;++ aTimerContext[timer_id].CountLeft = timeout_ticks;+ aTimerContext[timer_id].CounterInit = timeout_ticks;++ time_elapsed = linkTimer(timer_id);++ localcurrentrunningtimerid = CurrentRunningTimerID;++ if(PreviousRunningTimerID != localcurrentrunningtimerid)+ {+ RescheduleTimerList();+ }+ else+ {+ aTimerContext[timer_id].CountLeft -= time_elapsed;+ }++ /* Enable the write protection for RTC registers */+ __HAL_RTC_WRITEPROTECTION_ENABLE( &hrtc );++ HAL_NVIC_EnableIRQ(CFG_HW_TS_RTC_WAKEUP_HANDLER_ID); /**< Enable NVIC */++#if (CFG_HW_TS_USE_PRIMASK_AS_CRITICAL_SECTION == 1)+ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/+#endif++ return;+}++uint16_t HW_TS_RTC_ReadLeftTicksToCount(void)+{+ uint32_t primask_bit;+ uint16_t return_value, auro_reload_value, elapsed_time_value;++ primask_bit = __get_PRIMASK(); /**< backup PRIMASK bit */+ __disable_irq(); /**< Disable all interrupts by setting PRIMASK bit on Cortex*/++ if((READ_BIT(RTC->CR, RTC_CR_WUTE) == (RTC_CR_WUTE)) == SET)+ {+ auro_reload_value = (uint32_t)(READ_BIT(RTC->WUTR, RTC_WUTR_WUT));++ elapsed_time_value = ReturnTimeElapsed();++ if(auro_reload_value > elapsed_time_value)+ {+ return_value = auro_reload_value - elapsed_time_value;+ }+ else+ {+ return_value = 0;+ }+ }+ else+ {+ return_value = TIMER_LIST_EMPTY;+ }++ __set_PRIMASK(primask_bit); /**< Restore PRIMASK bit*/++ return (return_value);+}++__weak void HW_TS_RTC_Int_AppNot(uint32_t TimerProcessID, uint8_t TimerID, HW_TS_pTimerCb_t pTimerCallBack)+{+ pTimerCallBack();++ return;+}diff --git a/firmware/ota_bootloader/Core/Src/main.c b/firmware/ota_bootloader/Core/Src/main.cnew file mode 100644index 0000000..1176f32--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/main.c@@ -0,0 +1,102 @@+/*+ * Keyword OTA bootloader, based on ST's BLE_Ota (STM32CubeWB 1.24.0).+ *+ * The boot decision is made in SystemInit (system_stm32wbxx.c) before any+ * of this runs: a valid app is jumped to straight away, and only when the+ * app is missing, invalid or has asked for an update do we get here and+ * bring up BLE as "Keyword OTA".+ *+ * Only RCC, PWR, RTC, IPCC, HSEM and flash are touched. The status LED,+ * I2C3, SWIO and USB pins stay at their reset state.+ */+#include "main.h"+#include "app_entry.h"+#include "stm32_seq.h"++RTC_HandleTypeDef hrtc;++/* Same reset handling as the app's MX_APPE_Config: CPU2 may still hold+ * stale IPCC state after a pin reset. */+static void Reset_Device(void)+{+ if (LL_RCC_IsActiveFlag_PINRST() && !LL_RCC_IsActiveFlag_SFTRST())+ {+ HAL_PWR_EnableBkUpAccess();+ __HAL_RCC_BACKUPRESET_FORCE();+ __HAL_RCC_BACKUPRESET_RELEASE();+ }+ LL_AHB3_GRP1_EnableClock(LL_AHB3_GRP1_PERIPH_IPCC);+ uint32_t ch = LL_IPCC_CHANNEL_1 | LL_IPCC_CHANNEL_2 | LL_IPCC_CHANNEL_3+ | LL_IPCC_CHANNEL_4 | LL_IPCC_CHANNEL_5 | LL_IPCC_CHANNEL_6;+ LL_C1_IPCC_ClearFlag_CHx(IPCC, ch);+ LL_C2_IPCC_ClearFlag_CHx(IPCC, ch);+ LL_C1_IPCC_DisableTransmitChannel(IPCC, ch);+ LL_C2_IPCC_DisableTransmitChannel(IPCC, ch);+ LL_C1_IPCC_DisableReceiveChannel(IPCC, ch);+ LL_C2_IPCC_DisableReceiveChannel(IPCC, ch);+}++/* SystemInit (ST's) already runs SYSCLK from the 32 MHz HSE, trimmed from+ * OTP like the app. Here: LSE for the RTC, and RF wakeup on HSE/1024 as in+ * the app's PeriphCommonClock_Config. SMPS stays in bypass. */+static void SystemClock_Config(void)+{+ HAL_PWR_EnableBkUpAccess();+ LL_RCC_LSE_SetDriveCapability(LL_RCC_LSEDRIVE_MEDIUMHIGH);+ LL_RCC_LSE_Enable();+ while (!LL_RCC_LSE_IsReady());+ LL_RCC_SetRFWKPClockSource(LL_RCC_RFWKP_CLKSOURCE_HSE_DIV1024);+}++static void Init_Rtc(void)+{+ __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE);+ __HAL_RCC_RTC_ENABLE();+ __HAL_RCC_RTCAPB_CLK_ENABLE();+ HAL_NVIC_SetPriority(RTC_WKUP_IRQn, 0, 0);+ HAL_NVIC_EnableIRQ(RTC_WKUP_IRQn);+ hrtc.Instance = RTC;+ hrtc.Init.HourFormat = RTC_HOURFORMAT_24;+ hrtc.Init.AsynchPrediv = CFG_RTC_ASYNCH_PRESCALER;+ hrtc.Init.SynchPrediv = CFG_RTC_SYNCH_PRESCALER;+ hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;+ HAL_RTC_Init(&hrtc);+ LL_RTC_DisableWriteProtection(RTC);+ LL_RTC_WAKEUP_SetClock(RTC, CFG_RTC_WUCKSEL_DIVIDER);+ LL_RTC_EnableWriteProtection(RTC);+}++int main(void)+{+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);+ SystemCoreClockUpdate(); /* SystemInit switched to HSE */+ HAL_Init();+ Reset_Device();+ __HAL_RCC_CLEAR_RESET_FLAGS(); /* next boot decides on fresh flags */+ SystemClock_Config();+ /* only IPCC and HSEM may wake CPU1 */+ LL_EXTI_DisableIT_0_31(~0UL);+ LL_EXTI_DisableIT_32_63(~(LL_EXTI_LINE_36 | LL_EXTI_LINE_38));+ Init_Rtc();+ APPE_Init();++ while (1)+ {+ UTIL_SEQ_Run(UTIL_SEQ_DEFAULT);+ }+}++/* Asks SystemInit to start the ROM USB DFU bootloader on the next reset,+ * then resets. Entering it from a clean reset, before any clock or CPU2+ * is touched, needs no de-initialising and no option bytes. */+void BOOT_RequestSystemDfu(void)+{+ CFG_SYSDFU_REQ_WORD = CFG_SYSDFU_REQ_MAGIC;+ NVIC_SystemReset();+}++void Error_Handler(void)+{+ /* Can't run BLE: fall back to USB DFU so the keyword stays recoverable. */+ BOOT_RequestSystemDfu();+}diff --git a/firmware/ota_bootloader/Core/Src/stm32_lpm_if.c b/firmware/ota_bootloader/Core/Src/stm32_lpm_if.cnew file mode 100644index 0000000..fe9b2f2--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/stm32_lpm_if.c@@ -0,0 +1,352 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file stm32_lpm_if.c+ * @author MCD Application Team+ * @brief Low layer function to enter/exit low power modes (stop, sleep).+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Includes ------------------------------------------------------------------*/+#include "stm32_lpm_if.h"+#include "stm32_lpm.h"+#include "app_conf.h"+/* USER CODE BEGIN include */++/* USER CODE END include */++/* Exported variables --------------------------------------------------------*/+const struct UTIL_LPM_Driver_s UTIL_PowerDriver =+{+ PWR_EnterSleepMode,+ PWR_ExitSleepMode,++ PWR_EnterStopMode,+ PWR_ExitStopMode,++ PWR_EnterOffMode,+ PWR_ExitOffMode,+};++/* Private function prototypes -----------------------------------------------*/+static void Switch_On_HSI( void );+static void EnterLowPower( void );+static void ExitLowPower( void );+/* USER CODE BEGIN Private_Function_Prototypes */++/* USER CODE END Private_Function_Prototypes */+/* Private typedef -----------------------------------------------------------*/+/* USER CODE BEGIN Private_Typedef */++/* USER CODE END Private_Typedef */+/* Private define ------------------------------------------------------------*/+/* USER CODE BEGIN Private_Define */++/* USER CODE END Private_Define */+/* Private macro -------------------------------------------------------------*/+/* USER CODE BEGIN Private_Macro */++/* USER CODE END Private_Macro */+/* Private variables ---------------------------------------------------------*/+/* USER CODE BEGIN Private_Variables */++/* USER CODE END Private_Variables */++/* Functions Definition ------------------------------------------------------*/+/**+ * @brief Enters Low Power Off Mode+ * @param none+ * @retval none+ */+void PWR_EnterOffMode( void )+{+/* USER CODE BEGIN PWR_EnterOffMode_1 */++/* USER CODE END PWR_EnterOffMode_1 */+ /**+ * The systick should be disabled for the same reason than when the device enters stop mode because+ * at this time, the device may enter either OffMode or StopMode.+ */+ HAL_SuspendTick();++ EnterLowPower();++ /************************************************************************************+ * ENTER OFF MODE+ ***********************************************************************************/+ /*+ * There is no risk to clear all the WUF here because in the current implementation, this API is called+ * in critical section. If an interrupt occurs while in that critical section before that point,+ * the flag is set and will be cleared here but the system will not enter Off Mode+ * because an interrupt is pending in the NVIC. The ISR will be executed when moving out+ * of this critical section+ */+ LL_PWR_ClearFlag_WU( );++ LL_PWR_SetPowerMode( LL_PWR_MODE_STANDBY );++ LL_LPM_EnableDeepSleep( ); /**< Set SLEEPDEEP bit of Cortex System Control Register */++ /**+ * This option is used to ensure that store operations are completed+ */+#if defined (__CC_ARM) || defined (__ARMCC_VERSION)+ __force_stores( );+#endif++ __WFI();++/* USER CODE BEGIN PWR_EnterOffMode_2 */++/* USER CODE END PWR_EnterOffMode_2 */+ return;+}++/**+ * @brief Exits Low Power Off Mode+ * @param none+ * @retval none+ */+void PWR_ExitOffMode( void )+{+/* USER CODE BEGIN PWR_ExitOffMode_1 */++/* USER CODE END PWR_ExitOffMode_1 */+ HAL_ResumeTick();+/* USER CODE BEGIN PWR_ExitOffMode_2 */++/* USER CODE END PWR_ExitOffMode_2 */+ return;+}++/**+ * @brief Enters Low Power Stop Mode+ * @note ARM exists the function when waking up+ * @param none+ * @retval none+ */+void PWR_EnterStopMode( void )+{+/* USER CODE BEGIN PWR_EnterStopMode_1 */++/* USER CODE END PWR_EnterStopMode_1 */+ /**+ * When HAL_DBGMCU_EnableDBGStopMode() is called to keep the debugger active in Stop Mode,+ * the systick shall be disabled otherwise the cpu may crash when moving out from stop mode+ *+ * When in production, the HAL_DBGMCU_EnableDBGStopMode() is not called so that the device can reach best power consumption+ * However, the systick should be disabled anyway to avoid the case when it is about to expire at the same time the device enters+ * stop mode ( this will abort the Stop Mode entry ).+ */+ HAL_SuspendTick();++ /**+ * This function is called from CRITICAL SECTION+ */+ EnterLowPower();++ /************************************************************************************+ * ENTER STOP MODE+ ***********************************************************************************/+ LL_PWR_SetPowerMode( LL_PWR_MODE_STOP2 );++ LL_LPM_EnableDeepSleep( ); /**< Set SLEEPDEEP bit of Cortex System Control Register */++ /**+ * This option is used to ensure that store operations are completed+ */+#if defined (__CC_ARM) || defined (__ARMCC_VERSION)+ __force_stores( );+#endif++ __WFI();++/* USER CODE BEGIN PWR_EnterStopMode_2 */++/* USER CODE END PWR_EnterStopMode_2 */+ return;+}++/**+ * @brief Exits Low Power Stop Mode+ * @note Enable the pll at 32MHz+ * @param none+ * @retval none+ */+void PWR_ExitStopMode( void )+{+/* USER CODE BEGIN PWR_ExitStopMode_1 */++/* USER CODE END PWR_ExitStopMode_1 */+ /**+ * This function is called from CRITICAL SECTION+ */+ ExitLowPower();++ HAL_ResumeTick();+/* USER CODE BEGIN PWR_ExitStopMode_2 */++/* USER CODE END PWR_ExitStopMode_2 */+ return;+}++/**+ * @brief Enters Low Power Sleep Mode+ * @note ARM exits the function when waking up+ * @param none+ * @retval none+ */+void PWR_EnterSleepMode( void )+{+/* USER CODE BEGIN PWR_EnterSleepMode_1 */++/* USER CODE END PWR_EnterSleepMode_1 */++ HAL_SuspendTick();++ /************************************************************************************+ * ENTER SLEEP MODE+ ***********************************************************************************/+ LL_LPM_EnableSleep( ); /**< Clear SLEEPDEEP bit of Cortex System Control Register */++ /**+ * This option is used to ensure that store operations are completed+ */+#if defined (__CC_ARM) || defined (__ARMCC_VERSION)+ __force_stores();+#endif++ __WFI( );+/* USER CODE BEGIN PWR_EnterSleepMode_2 */++/* USER CODE END PWR_EnterSleepMode_2 */+ return;+}++/**+ * @brief Exits Low Power Sleep Mode+ * @note ARM exits the function when waking up+ * @param none+ * @retval none+ */+void PWR_ExitSleepMode( void )+{+/* USER CODE BEGIN PWR_ExitSleepMode_1 */++/* USER CODE END PWR_ExitSleepMode_1 */+ HAL_ResumeTick();+/* USER CODE BEGIN PWR_ExitSleepMode_2 */++/* USER CODE END PWR_ExitSleepMode_2 */+ return;+}++/*************************************************************+ *+ * LOCAL FUNCTIONS+ *+ *************************************************************/+/**+ * @brief Setup the system to enter either stop or off mode+ * @param none+ * @retval none+ */+static void EnterLowPower( void )+{+ /**+ * This function is called from CRITICAL SECTION+ */++ while( LL_HSEM_1StepLock( HSEM, CFG_HW_RCC_SEMID ) );++ if ( ! LL_HSEM_1StepLock( HSEM, CFG_HW_ENTRY_STOP_MODE_SEMID ) )+ {+ if( LL_PWR_IsActiveFlag_C2DS() || LL_PWR_IsActiveFlag_C2SB() )+ {+ /* Release ENTRY_STOP_MODE semaphore */+ LL_HSEM_ReleaseLock( HSEM, CFG_HW_ENTRY_STOP_MODE_SEMID, 0 );++ Switch_On_HSI();+ __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_0);+ }+ }+ else+ {+ Switch_On_HSI();+ __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_0);+ }++ /* Release RCC semaphore */+ LL_HSEM_ReleaseLock( HSEM, CFG_HW_RCC_SEMID, 0 );++ return;+}++/**+ * @brief Restore the system to exit stop mode+ * @param none+ * @retval none+ */+static void ExitLowPower( void )+{+ /* Release ENTRY_STOP_MODE semaphore */+ LL_HSEM_ReleaseLock( HSEM, CFG_HW_ENTRY_STOP_MODE_SEMID, 0 );++ while( LL_HSEM_1StepLock( HSEM, CFG_HW_RCC_SEMID ) );++ if(LL_RCC_GetSysClkSource( ) == LL_RCC_SYS_CLKSOURCE_STATUS_HSI)+ {+/* Restore the clock configuration of the application in this user section */+/* USER CODE BEGIN ExitLowPower_1 */+ LL_RCC_HSE_Enable( );+ __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_1);+ while(__HAL_FLASH_GET_LATENCY() != FLASH_LATENCY_1);+ while(!LL_RCC_HSE_IsReady( ));+ LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSE);+ while (LL_RCC_GetSysClkSource( ) != LL_RCC_SYS_CLKSOURCE_STATUS_HSE);+/* USER CODE END ExitLowPower_1 */+ }+ else+ {+/* If the application is not running on HSE restore the clock configuration in this user section */+/* USER CODE BEGIN ExitLowPower_2 */++/* USER CODE END ExitLowPower_2 */+ }++ /* Release RCC semaphore */+ LL_HSEM_ReleaseLock( HSEM, CFG_HW_RCC_SEMID, 0 );++ return;+}++/**+ * @brief Switch the system clock on HSI+ * @param none+ * @retval none+ */+static void Switch_On_HSI( void )+{+ LL_RCC_HSI_Enable( );+ while(!LL_RCC_HSI_IsReady( ));+ LL_RCC_SetSysClkSource( LL_RCC_SYS_CLKSOURCE_HSI );+ LL_RCC_SetSMPSClockSource(LL_RCC_SMPS_CLKSOURCE_HSI);+ while (LL_RCC_GetSysClkSource( ) != LL_RCC_SYS_CLKSOURCE_STATUS_HSI);+ return;+}++/* USER CODE BEGIN Private_Functions */++/* USER CODE END Private_Functions */+diff --git a/firmware/ota_bootloader/Core/Src/stm32wbxx_it.c b/firmware/ota_bootloader/Core/Src/stm32wbxx_it.cnew file mode 100644index 0000000..693814e--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/stm32wbxx_it.c@@ -0,0 +1,34 @@+#include "main.h"+#include "hw_if.h"++void NMI_Handler(void)+{+ while (1);+}++/* A crash in the bootloader shouldn't strand the keyword: reset, which+ * boots the app if it's valid or comes back here. */+void HardFault_Handler(void)+{+ NVIC_SystemReset();+}++void SysTick_Handler(void)+{+ HAL_IncTick();+}++void IPCC_C1_RX_IRQHandler(void)+{+ HW_IPCC_Rx_Handler();+}++void IPCC_C1_TX_IRQHandler(void)+{+ HW_IPCC_Tx_Handler();+}++void RTC_WKUP_IRQHandler(void)+{+ HW_TS_RTC_Wakeup_Handler();+}diff --git a/firmware/ota_bootloader/Core/Src/syscalls.c b/firmware/ota_bootloader/Core/Src/syscalls.cnew file mode 100644index 0000000..e10d76f--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/syscalls.c@@ -0,0 +1,244 @@+/**+ ******************************************************************************+ * @file syscalls.c+ * @author Auto-generated by STM32CubeMX+ * @brief Minimal System calls file+ *+ * For more information about which c-functions+ * need which of these lowlevel functions+ * please consult the Newlib or Picolibc libc-manual+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2020-2025 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */++/* Includes */+#include <sys/stat.h>+#include <stdlib.h>+#include <errno.h>+#include <stdio.h>+#include <signal.h>+#include <time.h>+#include <sys/time.h>+#include <sys/times.h>+++/* Variables */+extern int __io_putchar(int ch) __attribute__((weak));+extern int __io_getchar(void) __attribute__((weak));+++char *__env[1] = { 0 };+char **environ = __env;+++/* Functions */+void initialise_monitor_handles()+{+}++int _getpid(void)+{+ return 1;+}++int _kill(int pid, int sig)+{+ (void)pid;+ (void)sig;+ errno = EINVAL;+ return -1;+}++void _exit (int status)+{+ _kill(status, -1);+ while (1) {} /* Make sure we hang here */+}++__attribute__((weak)) int _read(int file, char *ptr, int len)+{+ (void)file;+ int DataIdx;++ for (DataIdx = 0; DataIdx < len; DataIdx++)+ {+ *ptr++ = __io_getchar();+ }++ return len;+}++__attribute__((weak)) int _write(int file, char *ptr, int len)+{+ (void)file;+ int DataIdx;++ for (DataIdx = 0; DataIdx < len; DataIdx++)+ {+ __io_putchar(*ptr++);+ }+ return len;+}++int _close(int file)+{+ (void)file;+ return -1;+}+++int _fstat(int file, struct stat *st)+{+ (void)file;+ st->st_mode = S_IFCHR;+ return 0;+}++int _isatty(int file)+{+ (void)file;+ return 1;+}++int _lseek(int file, int ptr, int dir)+{+ (void)file;+ (void)ptr;+ (void)dir;+ return 0;+}++int _open(char *path, int flags, ...)+{+ (void)path;+ (void)flags;+ /* Pretend like we always fail */+ return -1;+}++int _wait(int *status)+{+ (void)status;+ errno = ECHILD;+ return -1;+}++int _unlink(char *name)+{+ (void)name;+ errno = ENOENT;+ return -1;+}++clock_t _times(struct tms *buf)+{+ (void)buf;+ return -1;+}++int _stat(const char *file, struct stat *st)+{+ (void)file;+ st->st_mode = S_IFCHR;+ return 0;+}++int _link(char *old, char *new)+{+ (void)old;+ (void)new;+ errno = EMLINK;+ return -1;+}++int _fork(void)+{+ errno = EAGAIN;+ return -1;+}++int _execve(char *name, char **argv, char **env)+{+ (void)name;+ (void)argv;+ (void)env;+ errno = ENOMEM;+ return -1;+}++// --- Picolibc Specific Section ---+#if defined(__PICOLIBC__)++/**+ * @brief Picolibc helper function to output a character to a FILE stream.+ * This redirects the output to the low-level __io_putchar function.+ * @param c Character to write.+ * @param file FILE stream pointer (ignored).+ * @retval int The character written.+ */+static int starm_putc(char c, FILE *file)+{+ (void) file;+ __io_putchar(c);+ return c;+}++/**+ * @brief Picolibc helper function to input a character from a FILE stream.+ * This redirects the input from the low-level __io_getchar function.+ * @param file FILE stream pointer (ignored).+ * @retval int The character read, cast to an unsigned char then int.+ */+static int starm_getc(FILE *file)+{+ unsigned char c;+ (void) file;+ c = __io_getchar();+ return c;+}++// Define and initialize the standard I/O streams for Picolibc.+// FDEV_SETUP_STREAM connects the starm_putc and starm_getc helper functions to a FILE structure.+// _FDEV_SETUP_RW indicates the stream is for reading and writing.+static FILE __stdio = FDEV_SETUP_STREAM(starm_putc,+ starm_getc,+ NULL,+ _FDEV_SETUP_RW);++// Assign the standard stream pointers (stdin, stdout, stderr) to the initialized stream.+// Picolibc uses these pointers for standard I/O operations (printf, scanf, etc.).+FILE *const stdin = &__stdio;+__strong_reference(stdin, stdout);+__strong_reference(stdin, stderr);++// Create strong aliases mapping standard C library function names (without underscore)+// to the implemented system call stubs (with underscore). Picolibc uses these+// standard names internally, so this linking is required.+__strong_reference(_read, read);+__strong_reference(_write, write);+__strong_reference(_times, times);+__strong_reference(_execve, execve);+__strong_reference(_fork, fork);+__strong_reference(_link, link);+__strong_reference(_unlink, unlink);+__strong_reference(_stat, stat);+__strong_reference(_wait, wait);+__strong_reference(_open, open);+__strong_reference(_close, close);+__strong_reference(_lseek, lseek);+__strong_reference(_isatty, isatty);+__strong_reference(_fstat, fstat);+__strong_reference(_exit, exit);+__strong_reference(_kill, kill);+__strong_reference(_getpid, getpid);++#endif //__PICOLIBC__diff --git a/firmware/ota_bootloader/Core/Src/sysmem.c b/firmware/ota_bootloader/Core/Src/sysmem.cnew file mode 100644index 0000000..a875d42--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/sysmem.c@@ -0,0 +1,87 @@+/**+ ******************************************************************************+ * @file sysmem.c+ * @author Generated by STM32CubeMX+ * @brief System Memory calls file+ *+ * For more information about which C functions+ * need which of these lowlevel functions+ * please consult the Newlib or Picolibc libc manual+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2025 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */++/* Includes */+#include <errno.h>+#include <stdint.h>+#include <stddef.h>++/**+ * Pointer to the current high watermark of the heap usage+ */+static uint8_t *__sbrk_heap_end = NULL;++/**+ * @brief _sbrk() allocates memory to the newlib heap and is used by malloc+ * and others from the C library+ *+ * @verbatim+ * ############################################################################+ * # .data # .bss # newlib heap # MSP stack #+ * # # # # Reserved by _Min_Stack_Size #+ * ############################################################################+ * ^-- RAM start ^-- _end _estack, RAM end --^+ * @endverbatim+ *+ * This implementation starts allocating at the '_end' linker symbol+ * The '_Min_Stack_Size' linker symbol reserves a memory for the MSP stack+ * The implementation considers '_estack' linker symbol to be RAM end+ * NOTE: If the MSP stack, at any point during execution, grows larger than the+ * reserved size, please increase the '_Min_Stack_Size'.+ *+ * @param incr Memory size+ * @return Pointer to allocated memory+ */+void *_sbrk(ptrdiff_t incr)+{+ extern uint8_t _end; /* Symbol defined in the linker script */+ extern uint8_t _estack; /* Symbol defined in the linker script */+ extern uint32_t _Min_Stack_Size; /* Symbol defined in the linker script */+ const uint32_t stack_limit = (uint32_t)&_estack - (uint32_t)&_Min_Stack_Size;+ const uint8_t *max_heap = (uint8_t *)stack_limit;+ uint8_t *prev_heap_end;++ /* Initialize heap end at first call */+ if (NULL == __sbrk_heap_end)+ {+ __sbrk_heap_end = &_end;+ }++ /* Protect heap from growing into the reserved MSP stack */+ if (__sbrk_heap_end + incr > max_heap)+ {+ errno = ENOMEM;+ return (void *)-1;+ }++ prev_heap_end = __sbrk_heap_end;+ __sbrk_heap_end += incr;++ return (void *)prev_heap_end;+}++#if defined(__PICOLIBC__)+ // Picolibc expects syscalls without the leading underscore.+ // This creates a strong alias so that+ // calls to `sbrk()` are resolved to our `_sbrk()` implementation.+ __strong_reference(_sbrk, sbrk);+#endifdiff --git a/firmware/ota_bootloader/Core/Src/system_stm32wbxx.c b/firmware/ota_bootloader/Core/Src/system_stm32wbxx.cnew file mode 100644index 0000000..b247df1--- /dev/null+++ b/firmware/ota_bootloader/Core/Src/system_stm32wbxx.c@@ -0,0 +1,648 @@+/**+ ******************************************************************************+ * @file system_stm32wbxx.c+ * @author MCD Application Team+ * @brief CMSIS Cortex Device Peripheral Access Layer System Source File+ *+ * This file provides two functions and one global variable to be called from+ * user application:+ * - SystemInit(): This function is called at startup just after reset and+ * before branch to main program. This call is made inside+ * the "startup_stm32wbxx.s" file.+ *+ * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used+ * by the user application to setup the SysTick+ * timer or configure other parameters.+ *+ * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must+ * be called whenever the core clock is changed+ * during program execution.+ *+ * After each device reset the MSI (4 MHz) is used as system clock source.+ * Then SystemInit() function is called, in "startup_stm32wbxx.s" file, to+ * configure the system clock before to branch to main program.+ *+ * This file configures the system clock as follows:+ *=============================================================================+ *-----------------------------------------------------------------------------+ * System Clock source | MSI+ *-----------------------------------------------------------------------------+ * SYSCLK(Hz) | 4000000+ *-----------------------------------------------------------------------------+ * HCLK(Hz) | 4000000+ *-----------------------------------------------------------------------------+ * AHB Prescaler | 1+ *-----------------------------------------------------------------------------+ * APB1 Prescaler | 1+ *-----------------------------------------------------------------------------+ * APB2 Prescaler | 1+ *-----------------------------------------------------------------------------+ * PLL_M | 1+ *-----------------------------------------------------------------------------+ * PLL_N | 8+ *-----------------------------------------------------------------------------+ * PLL_P | 7+ *-----------------------------------------------------------------------------+ * PLL_Q | 2+ *-----------------------------------------------------------------------------+ * PLL_R | 2+ *-----------------------------------------------------------------------------+ * PLLSAI1_P | NA+ *-----------------------------------------------------------------------------+ * PLLSAI1_Q | NA+ *-----------------------------------------------------------------------------+ * PLLSAI1_R | NA+ *-----------------------------------------------------------------------------+ * Require 48MHz for USB OTG FS, | Disabled+ * SDIO and RNG clock |+ *-----------------------------------------------------------------------------+ *=============================================================================+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+++/** @addtogroup CMSIS+ * @{+ */++/** @addtogroup stm32WBxx_system+ * @{+ */++/** @addtogroup stm32WBxx_System_Private_Includes+ * @{+ */++#include "app_common.h"+#include "otp.h"++#ifdef OTA_SBSFU+#include "ota_sbsfu.h"+#endif /* OTA_SBSFU */++#if !defined (HSE_VALUE)+#define HSE_VALUE ((uint32_t)32000000) /*!< Value of the External oscillator in Hz */+#endif /* HSE_VALUE */++#if !defined (MSI_VALUE)+#define MSI_VALUE ((uint32_t)4000000) /*!< Value of the Internal oscillator in Hz*/+#endif /* MSI_VALUE */++#if !defined (HSI_VALUE)+#define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/+#endif /* HSI_VALUE */++#if !defined (LSI_VALUE)+#define LSI_VALUE ((uint32_t)32000) /*!< Value of LSI in Hz*/+#endif /* LSI_VALUE */++#if !defined (LSE_VALUE)+#define LSE_VALUE ((uint32_t)32768) /*!< Value of LSE in Hz*/+#endif /* LSE_VALUE */++/**+ * @}+ */++/** @addtogroup STM32WBxx_System_Private_TypesDefinitions+ * @{+ */++typedef void (*fct_t)(void);+/**+ * @}+ */++/** @addtogroup STM32WBxx_System_Private_Defines+ * @{+ */++/*!< Uncomment the following line if you need to relocate your vector Table in+ Internal SRAM. */+/* #define VECT_TAB_SRAM */+/*!< Vector Table base offset field. This value must be a multiple of 0x200. */+/* #define VECT_TAB_OFFSET 0x0U*/+#ifdef OTA_SBSFU+#if defined (__CC_ARM) || defined (__ARMCC_VERSION)+extern void * __Vectors;+#define VECT_TAB_OFFSET ((uint32_t) & __Vectors)+#elif defined(__ICCARM__)+extern uint32_t __vector_table;+#define VECT_TAB_OFFSET ((uint32_t)& __vector_table)+#elif defined(__GNUC__)+extern void * g_pfnVectors;+#define VECT_TAB_OFFSET ((uint32_t)& g_pfnVectors)+#endif+#endif+/**+ * @}+ */++/** @addtogroup STM32WBxx_System_Private_Macros+ * @{+ */++/**+ * @}+ */++/** @addtogroup STM32WBxx_System_Private_Variables+ * @{+ */+/* The SystemCoreClock variable is updated in three ways:+ 1) by calling CMSIS function SystemCoreClockUpdate()+ 2) by calling HAL API function HAL_RCC_GetHCLKFreq()+ 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency+ Note: If you use this function to configure the system clock; then there+ is no need to call the 2 first functions listed above, since SystemCoreClock+ variable is updated automatically.+ */+uint32_t SystemCoreClock = 4000000; /*CPU1: M4 on MSI clock after startup (4MHz)*/++const uint32_t AHBPrescTable[16] = {1, 3, 5, 1, 1, 6, 10, 32, 2, 4, 8, 16, 64, 128, 256, 512};+/* index=[0,...15]*/+const uint32_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};++const uint32_t MSIRangeTable[16UL] = {100000UL, 200000UL, 400000UL, 800000UL, 1000000UL, 2000000UL, \+ 4000000UL, 8000000UL, 16000000UL, 24000000UL, 32000000UL, 48000000UL, 0UL, 0UL, 0UL, 0UL}; /* 0UL values are incorrect cases */++#if defined(STM32WB55xx) || defined(STM32WB5Mxx) || defined(STM32WB35xx) || defined (STM32WB15xx)+ const uint32_t SmpsPrescalerTable[4UL][6UL]={{1UL,3UL,2UL,2UL,1UL,2UL}, \+ {2UL,6UL,4UL,3UL,2UL,4UL}, \+ {4UL,12UL,8UL,6UL,4UL,8UL}, \+ {4UL,12UL,8UL,6UL,4UL,8UL}};+#endif++/**+ * @}+ */++ /** @addtogroup STM32WBxx_System_Private_FunctionPrototypes+ * @{+ */++ /**+ * @}+ */++ /** @addtogroup STM32WBxx_System_Private_Functions+ * @{+ */+#ifndef OTA_SBSFU+/****************************/+static void JumpFwApp( void );+static void BootModeCheck( void );+static void JumpSelectionOnPowerUp( void );++/**+ * Return 0 if FW App not valid+ * Return 1 if Fw App valid+ */+static uint8_t CheckFwAppValidity( void );+++static uint8_t CheckFwAppValidity( void )+{+ uint8_t status;+ uint32_t magic_keyword_address;+ uint32_t last_user_flash_address;++ magic_keyword_address = *(uint32_t*)(FLASH_BASE + (CFG_APP_START_SECTOR_INDEX * 0x1000 + 0x140));+ last_user_flash_address = (((READ_BIT(FLASH->SFR, FLASH_SFR_SFSA) >> FLASH_SFR_SFSA_Pos) << 12) + FLASH_BASE) - 4;+ if( (magic_keyword_address < FLASH_BASE) || (magic_keyword_address > last_user_flash_address) )+ {+ /**+ * The address is not valid+ */+ status = 0;+ }+ else+ {+ if( (*(uint32_t*)magic_keyword_address) != 0x94448A29 )+ {+ /**+ * A firmware update procedure did not complete+ */+ status = 0;+ }+ else+ {+ /**+ * The firmware application is available+ */+ status = 1;+ }+ }++ return status;+}++/**+ * Jump to existing FW App in flash+ * It never returns+ */+static void JumpFwApp( void )+{+ fct_t app_reset_handler;++ 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));+ app_reset_handler();++ /**+ * app_reset_handler() never returns.+ * However, if for any reason a PUSH instruction is added at the entry of JumpFwApp(),+ * we need to make sure the POP instruction is not there before app_reset_handler() is called+ * The way to ensure this is to add a dummy code after app_reset_handler() is called+ * This prevents app_reset_handler() to be the last code in the function.+ */+ __WFI();+++ return;+}++/**+ * Check the Boot mode request+ * Depending on the result, the CPU may either jump to an existing application in the user flash+ * or keep on running the code to start the OTA loader+ */+/**+ * Keyword: start ST's ROM USB DFU bootloader in system memory, without+ * option bytes. Only called right out of a software reset, before any+ * clock, peripheral or CPU2 has been touched, so there is nothing to+ * de-initialise first. Interrupts are still off (SystemInit runs before+ * the app enables any).+ */+static void JumpSystemDfu( void )+{+ fct_t rom_reset_handler;++ LL_SYSCFG_SetRemapMemory(LL_SYSCFG_REMAP_SYSTEMFLASH);+ SCB->VTOR = SYSTEM_MEMORY_BASE;+ __set_MSP(*(uint32_t*)SYSTEM_MEMORY_BASE);+ rom_reset_handler = (fct_t)(*(uint32_t*)(SYSTEM_MEMORY_BASE + 4));+ rom_reset_handler();++ __WFI(); /* never reached, see JumpFwApp() */+}++static void BootModeCheck( void )+{+ /**+ * 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.+ */+ if(LL_RCC_IsActiveFlag_SFTRST( ) && (CFG_SYSDFU_REQ_WORD == CFG_SYSDFU_REQ_MAGIC))+ {+ CFG_SYSDFU_REQ_WORD = 0;+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_FW_APP;+ JumpSystemDfu();+ }++ if(LL_RCC_IsActiveFlag_SFTRST( ) || LL_RCC_IsActiveFlag_OBLRST( ))+ {+ /**+ * The SRAM1 content is kept on Software Reset.+ * In the Ble_Ota application, the first address of the SRAM1 indicates which kind of action has been requested+ */++ /**+ * Check Boot Mode from SRAM1+ */+ if((CFG_OTA_REBOOT_VAL_MSG == CFG_REBOOT_ON_FW_APP) && (CheckFwAppValidity( ) != 0))+ {+ /**+ * The user has requested to start on the firmware application and it has been checked+ * a valid application is ready+ * Jump now on the application+ */+ JumpFwApp();+ }+ else if((CFG_OTA_REBOOT_VAL_MSG == CFG_REBOOT_ON_FW_APP) && (CheckFwAppValidity( ) == 0))+ {+ /**+ * The user has requested to start on the firmware application but there is no valid application+ * Erase all sectors specified by byte1 and byte1 in SRAM1 to download a new App.+ */+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_BLE_OTA_APP; /* Request to reboot on BLE_Ota application */+ CFG_OTA_START_SECTOR_IDX_VAL_MSG = CFG_APP_START_SECTOR_INDEX;+ CFG_OTA_NBR_OF_SECTOR_VAL_MSG = 0xFF;+ }+ else if(CFG_OTA_REBOOT_VAL_MSG == CFG_REBOOT_ON_BLE_OTA_APP)+ {+ /**+ * It has been requested to reboot on BLE_Ota application to download data+ */+ }+ else if(CFG_OTA_REBOOT_VAL_MSG == CFG_REBOOT_ON_CPU2_UPGRADE)+ {+ /**+ * It has been requested to reboot on BLE_Ota application to keep running the firmware upgrade process+ *+ */+ }+ else+ {+ /**+ * There should be no use case to be there because the device already starts from power up+ * and the SRAM1 is then filled with the value define by the user+ * However, it could be that a reset occurs just after a power up and in that case, the Ble_Ota+ * will be running but the sectors to download a new App may not be erased+ */+ JumpSelectionOnPowerUp( );+ }+ }+ else+ {+ /**+ * On Power up, the content of SRAM1 is random+ * The only thing that could be done is to jump on either the firmware application+ * or the Ble_Ota application+ */+ JumpSelectionOnPowerUp( );+ }++ /**+ * Return to the startup file and run the Ble_Ota application+ */+ return;+}++static void JumpSelectionOnPowerUp( void )+{+ /**+ * Check if there is a FW App+ */+ if(CheckFwAppValidity( ) != 0)+ {+ /**+ * The SRAM1 is random+ * Initialize SRAM1 to indicate we requested to reboot of firmware application+ */+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_FW_APP;++ /**+ * A valid application is available+ * Jump now on the application+ */+ JumpFwApp();+ }+ else+ {+ /**+ * The SRAM1 is random+ * Initialize SRAM1 to indicate we requested to reboot of BLE_Ota application+ */+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_BLE_OTA_APP;++ /**+ * There is no valid application available+ * Erase all sectors specified by byte1 and byte1 in SRAM1 to download a new App.+ */+ CFG_OTA_START_SECTOR_IDX_VAL_MSG = CFG_APP_START_SECTOR_INDEX;+ CFG_OTA_NBR_OF_SECTOR_VAL_MSG = 0xFF;+ }+ return;+}+#endif /* OTA_SBSFU */++/**+ * @brief Setup the microcontroller system.+ * @param None+ * @retval None+ */+void SystemInit(void)+{+ OTP_ID0_t * p_otp;++#ifdef OTA_SBSFU+ if (STANDALONE_LOADER_STATE == STANDALONE_LOADER_DWL_REQ)+ {+ /* Standard SBSFU start-up at next reset */+ STANDALONE_LOADER_STATE = STANDALONE_LOADER_NO_REQ;+ }+#else+ BootModeCheck();+#endif /* OTA_SBSFU */++ /* FPU settings ------------------------------------------------------------*/+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)+ SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */+#endif++/**+ * When out of the SBSFU, the system configuration is+ * System Clock source = PLL (MSI)+ * SYSCLK(Hz) = 64000000+ * HCLK(Hz) = 64000000+ * HCLK1 Prescaler = 1+ * HCKL2 Prescaler = 2+ * HCKLS Prescaler = 1+ * APB1 Prescaler = 1+ * APB2 Prescaler = 1+ * MSI Frequency(Hz) = 4000000+ * PLL_M = 1+ * PLL_N = 32+ * PLL_P = 5+ * PLL_Q = 4+ * PLL_R = 2+ * Flash Latency(WS) = 3+ *+ * The new system configuration shall be applied in a different way when SBSFU is used versus+ * the case when the device is out of reset+ */++ /**+ * Read HSE_Tuning from OTP+ */+ p_otp = (OTP_ID0_t *) OTP_Read(0);+ if (p_otp)+ {+ LL_RCC_HSE_SetCapacitorTuning(p_otp->hse_tuning);+ }++ LL_RCC_HSE_Enable();++#ifndef OTA_SBSFU+ /**+ * Set FLASH latency to 1WS+ */+ LL_FLASH_SetLatency( LL_FLASH_LATENCY_1 );+ while( LL_FLASH_GetLatency() != LL_FLASH_LATENCY_1 );+#endif++ /**+ * Switch to HSE+ *+ */+ while(!LL_RCC_HSE_IsReady());+ LL_RCC_SetSysClkSource( LL_RCC_SYS_CLKSOURCE_HSE );+ while (LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSE);++#ifdef OTA_SBSFU+ /**+ * Switch OFF the PLL to save power+ */+ LL_RCC_PLL_Disable();++ /**+ * Set FLASH latency to 1WS+ */+ LL_FLASH_SetLatency( LL_FLASH_LATENCY_1 );+ while( LL_FLASH_GetLatency() != LL_FLASH_LATENCY_1 );++ /**+ * Set AHB2 prescaler so that CPU is clocked by 32 MHz+ */+ LL_C2_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);+#endif++ /**+ * Switch OFF MSI+ */+ LL_RCC_MSI_Disable();++ /* Configure the Vector Table location add offset address ------------------*/+#if defined(VECT_TAB_SRAM)+ /* program in SRAM1 */+ SCB->VTOR = RAM1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM1 for CPU1 */+#elif defined(VECT_TAB_OFFSET)+ SCB->VTOR = VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */+#endif++}++/**+ * @brief Update SystemCoreClock variable according to Clock Register Values.+ * The SystemCoreClock variable contains the core clock (HCLK), it can+ * be used by the user application to setup the SysTick timer or configure+ * other parameters.+ *+ * @note Each time the core clock (HCLK) changes, this function must be called+ * to update SystemCoreClock variable value. Otherwise, any configuration+ * based on this variable will be incorrect.+ *+ * @note - The system frequency computed by this function is not the real+ * frequency in the chip. It is calculated based on the predefined+ * constant and the selected clock source:+ *+ * - If SYSCLK source is MSI, SystemCoreClock will contain the MSI_VALUE(*)+ *+ * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(**)+ *+ * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(***)+ *+ * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(***)+ * or HSI_VALUE(*) or MSI_VALUE(*) multiplied/divided by the PLL factors.+ *+ * (*) MSI_VALUE is a constant defined in stm32wbxx_hal.h file (default value+ * 4 MHz) but the real value may vary depending on the variations+ * in voltage and temperature.+ *+ * (**) HSI_VALUE is a constant defined in stm32wbxx_hal_conf.h file (default value+ * 16 MHz) but the real value may vary depending on the variations+ * in voltage and temperature.+ *+ * (***) HSE_VALUE is a constant defined in stm32wbxx_hal_conf.h file (default value+ * 32 MHz), user has to ensure that HSE_VALUE is same as the real+ * frequency of the crystal used. Otherwise, this function may+ * have wrong result.+ *+ * - The result of this function could be not correct when using fractional+ * value for HSE crystal.+ *+ * @param None+ * @retval None+ */+void SystemCoreClockUpdate(void)+{+ uint32_t tmp = 0, msirange = 0, pllvco = 0, pllr = 2, pllsource = 0, pllm = 2;++ /* Get MSI Range frequency--------------------------------------------------*/++ /*MSI frequency range in Hz*/+ msirange = MSIRangeTable[(RCC->CR & RCC_CR_MSIRANGE) >> RCC_CR_MSIRANGE_Pos];++ /*SystemCoreClock=HAL_RCC_GetSysClockFreq();*/+ /* Get SYSCLK source -------------------------------------------------------*/+ switch (RCC->CFGR & RCC_CFGR_SWS)+ {+ case 0x00: /* MSI used as system clock source */+ SystemCoreClock = msirange;+ break;++ case 0x04: /* HSI used as system clock source */+ /* HSI used as system clock source */+ SystemCoreClock = HSI_VALUE;+ break;++ case 0x08: /* HSE used as system clock source */+ SystemCoreClock = HSE_VALUE;+ break;++ case 0x0C: /* PLL used as system clock source */+ /* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLN+ SYSCLK = PLL_VCO / PLLR+ */+ pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC);+ pllm = ((RCC->PLLCFGR & RCC_PLLCFGR_PLLM) >> RCC_PLLCFGR_PLLM_Pos) + 1 ;++ switch (pllsource)+ {+ case 0x02: /* HSI used as PLL clock source */+ pllvco = (HSI_VALUE / pllm);+ break;++ case 0x03: /* HSE used as PLL clock source */+ pllvco = (HSE_VALUE / pllm);+ break;++ default: /* MSI used as PLL clock source */+ pllvco = (msirange / pllm);+ break;+ }++ pllvco = pllvco * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos);+ pllr = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> RCC_PLLCFGR_PLLR_Pos) + 1);++ SystemCoreClock = pllvco/pllr;+ break;++ default:+ SystemCoreClock = msirange;+ break;+ }++ /* Compute HCLK clock frequency --------------------------------------------*/+ /* Get HCLK1 prescaler */+ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos)];+ /* HCLK clock frequency */+ SystemCoreClock = SystemCoreClock / tmp;++}+++/**+ * @}+ */++/**+ * @}+ */++/**+ * @}+ */diff --git a/firmware/ota_bootloader/Makefile b/firmware/ota_bootloader/Makefilenew file mode 100644index 0000000..889e4c2--- /dev/null+++ b/firmware/ota_bootloader/Makefile@@ -0,0 +1,140 @@+# Keyword OTA bootloader (pages 0-6, 0x08000000-0x08006FFF).+# Shares HAL, CMSIS, STM32_WPAN and utilities with the app in ../+#+# make build/ota_bootloader.{elf,bin,hex}+# make release also builds the app and writes ../release/:+# keyword_full.bin/.hex bootloader + app, for the one-time DFU install+# keyword_app.bin app only, for OTA at 0x08007000++TARGET = ota_bootloader+BUILD = build+FW = ..+PREFIX = arm-none-eabi-+ifdef ARM_GCC_PATH+PREFIX := $(ARM_GCC_PATH)/arm-none-eabi-+endif+CC = $(PREFIX)gcc+OBJCOPY = $(PREFIX)objcopy+SIZE = $(PREFIX)size++WPAN = $(FW)/Middlewares/ST/STM32_WPAN+HAL = $(FW)/Drivers/STM32WBxx_HAL_Driver++C_SOURCES = \+Core/Src/main.c \+Core/Src/app_entry.c \+Core/Src/system_stm32wbxx.c \+Core/Src/flash_driver.c \+Core/Src/hw_timerserver.c \+Core/Src/stm32_lpm_if.c \+Core/Src/stm32wbxx_it.c \+Core/Src/syscalls.c \+Core/Src/sysmem.c \+STM32_WPAN/App/app_ble.c \+STM32_WPAN/App/otas_app.c \+STM32_WPAN/Target/hw_ipcc.c \+$(HAL)/Src/stm32wbxx_hal.c \+$(HAL)/Src/stm32wbxx_hal_cortex.c \+$(HAL)/Src/stm32wbxx_hal_flash.c \+$(HAL)/Src/stm32wbxx_hal_flash_ex.c \+$(HAL)/Src/stm32wbxx_hal_pwr.c \+$(HAL)/Src/stm32wbxx_hal_pwr_ex.c \+$(HAL)/Src/stm32wbxx_hal_rcc.c \+$(HAL)/Src/stm32wbxx_hal_rcc_ex.c \+$(HAL)/Src/stm32wbxx_hal_rtc.c \+$(HAL)/Src/stm32wbxx_hal_rtc_ex.c \+$(WPAN)/ble/core/auto/ble_gap_aci.c \+$(WPAN)/ble/core/auto/ble_gatt_aci.c \+$(WPAN)/ble/core/auto/ble_hal_aci.c \+$(WPAN)/ble/core/auto/ble_hci_le.c \+$(WPAN)/ble/core/template/osal.c \+$(WPAN)/ble/svc/Src/svc_ctl.c \+$(WPAN)/ble/svc/Src/otas_stm.c \+$(WPAN)/interface/patterns/ble_thread/shci/shci.c \+$(WPAN)/interface/patterns/ble_thread/tl/hci_tl.c \+$(WPAN)/interface/patterns/ble_thread/tl/hci_tl_if.c \+$(WPAN)/interface/patterns/ble_thread/tl/shci_tl.c \+$(WPAN)/interface/patterns/ble_thread/tl/shci_tl_if.c \+$(WPAN)/interface/patterns/ble_thread/tl/tl_mbox.c \+$(WPAN)/utilities/otp.c \+$(WPAN)/utilities/stm_list.c \+$(WPAN)/utilities/stm_queue.c \+$(FW)/Utilities/lpm/tiny_lpm/stm32_lpm.c \+$(FW)/Utilities/sequencer/stm32_seq.c++ASM_SOURCES = startup_stm32wb55xx_cm4.s++C_INCLUDES = \+-ICore/Inc \+-ISTM32_WPAN/App \+-I$(FW)/Drivers/CMSIS/Device/ST/STM32WBxx/Include \+-I$(FW)/Drivers/CMSIS/Include \+-I$(HAL)/Inc \+-I$(HAL)/Inc/Legacy \+-I$(WPAN) \+-I$(WPAN)/ble \+-I$(WPAN)/ble/core \+-I$(WPAN)/ble/core/auto \+-I$(WPAN)/ble/core/template \+-I$(WPAN)/ble/svc/Inc \+-I$(WPAN)/ble/svc/Src \+-I$(WPAN)/interface/patterns/ble_thread \+-I$(WPAN)/interface/patterns/ble_thread/shci \+-I$(WPAN)/interface/patterns/ble_thread/tl \+-I$(WPAN)/utilities \+-I$(FW)/Utilities/lpm/tiny_lpm \+-I$(FW)/Utilities/sequencer++MCU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard+C_DEFS = -DSTM32WB55xx -DUSE_HAL_DRIVER -DCORE_CM4+# Size first: the loader has to stay inside 28 KB+CFLAGS = $(MCU) $(C_DEFS) $(C_INCLUDES) -Os -g -Wall -fdata-sections -ffunction-sections -MMD -MP+LDFLAGS = $(MCU) -specs=nano.specs -Tota_bootloader.ld -lc -lm -lnosys \+ -Wl,-Map=$(BUILD)/$(TARGET).map,--cref -Wl,--gc-sections -Wl,--print-memory-usage++OBJECTS = $(addprefix $(BUILD)/,$(notdir $(C_SOURCES:.c=.o))) $(addprefix $(BUILD)/,$(notdir $(ASM_SOURCES:.s=.o)))+vpath %.c $(sort $(dir $(C_SOURCES)))+vpath %.s $(sort $(dir $(ASM_SOURCES)))++all: $(BUILD)/$(TARGET).elf $(BUILD)/$(TARGET).bin $(BUILD)/$(TARGET).hex++$(BUILD)/%.o: %.c Makefile | $(BUILD)+ $(CC) -c $(CFLAGS) $< -o $@++$(BUILD)/%.o: %.s Makefile | $(BUILD)+ $(CC) -x assembler-with-cpp -c $(CFLAGS) $< -o $@++$(BUILD)/$(TARGET).elf: $(OBJECTS) ota_bootloader.ld+ $(CC) $(OBJECTS) $(LDFLAGS) -o $@+ $(SIZE) $@++$(BUILD)/%.bin: $(BUILD)/%.elf+ $(OBJCOPY) -O binary -S $< $@++$(BUILD)/%.hex: $(BUILD)/%.elf+ $(OBJCOPY) -O ihex $< $@++$(BUILD):+ mkdir -p $@++# ---- release images ----+APP_BIN = $(FW)/build/debug/keyword.bin+APP_OFFSET = 0x7000+REL = $(FW)/release++app:+ $(MAKE) -C $(FW) -f STM32Make.make ARM_GCC_PATH="$(ARM_GCC_PATH)" OPENOCD=openocd++release: all app+ mkdir -p $(REL)+ python3 tools/merge.py $(BUILD)/$(TARGET).bin $(APP_BIN) $(APP_OFFSET) $(REL)/keyword_full.bin+ $(OBJCOPY) -I binary -O ihex --change-addresses 0x08000000 $(REL)/keyword_full.bin $(REL)/keyword_full.hex+ cp $(APP_BIN) $(REL)/keyword_app.bin+ python3 tools/merge.py --check $(BUILD)/$(TARGET).bin $(APP_BIN) $(APP_OFFSET) $(REL)/keyword_full.bin++clean:+ rm -rf $(BUILD)++.PHONY: all app release clean++-include $(wildcard $(BUILD)/*.d)diff --git a/firmware/ota_bootloader/STM32_WPAN/App/app_ble.c b/firmware/ota_bootloader/STM32_WPAN/App/app_ble.cnew file mode 100644index 0000000..7db54a7--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/App/app_ble.c@@ -0,0 +1,250 @@+/*+ * BLE side of the OTA bootloader, from ST's BLE_Ota app_ble.c: advertise,+ * expose ST's OTA service (otas_stm.c, driven by otas_app.c) and erase the+ * app area before a download.+ *+ * It advertises "Keyword OTA" on the chip's public address + 1 (as ST+ * does), so a host bonded to the keyboard's own address doesn't mistake+ * the loader for it. No pairing: the OTA characteristics are open, which+ * is how ST's tools expect them.+ */+#include "main.h"+#include "app_common.h"+#include "ble.h"+#include "tl.h"+#include "app_ble.h"+#include "stm32_seq.h"+#include "stm32_lpm.h"+#include "shci.h"+#include "otp.h"+#include "flash_driver.h"++PLACE_IN_SECTION("MB_MEM1") ALIGN(4) static TL_CmdPacket_t BleCmdBuffer;++static const uint8_t a_BLE_CfgIrValue[16] = CFG_BLE_IR;+static const uint8_t a_BLE_CfgErValue[16] = CFG_BLE_ER;+static uint16_t conn_handle;++static const uint8_t a_LocalName[] = {AD_TYPE_COMPLETE_LOCAL_NAME,+ 'K', 'e', 'y', 'w', 'o', 'r', 'd', ' ', 'O', 'T', 'A'};+/* ST's BlueST layout, which ST BLE Toolbox uses to spot an OTA loader */+static uint8_t a_ManufData[14] = {sizeof(a_ManufData) - 1, AD_TYPE_MANUFACTURER_SPECIFIC_DATA,+ 0x01 /* SDK version */, CFG_DEV_ID_OTA_FW_UPDATE,+ 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* BD address, MSB first */};+static uint8_t a_BdAddr[6];++static void BLE_UserEvtRx(void *p_Payload);+static void BLE_StatusNot(HCI_TL_CmdStatus_t Status);++uint32_t APP_BLE_FirstAppPage(void)+{+ return CFG_APP_START_SECTOR_INDEX;+}++/* The app's keymap lives in the page just under SFSA (see the app's+ * keymap.c), and SFSA itself starts CPU2's area. ST's loader erased up to+ * SFSA; this stops one page earlier. */+uint32_t APP_BLE_EndAppPage(void)+{+ return ((FLASH->SFR & FLASH_SFR_SFSA) >> FLASH_SFR_SFSA_Pos) - 1;+}++/* Erase the pages the app asked for (start and count in SRAM1, set by the+ * app's OTA command or by SystemInit when there is no valid app), clamped+ * to [first app page, keymap page). Retries until every page is done: a+ * page left unerased would make a later write loop forever. */+static void Delete_Sectors(void)+{+ uint32_t start = CFG_OTA_START_SECTOR_IDX_VAL_MSG;+ uint32_t end = APP_BLE_EndAppPage();+ if (start < APP_BLE_FirstAppPage())+ {+ /* never erase the loader itself (ST's check let page 6 through) */+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_FW_APP;+ NVIC_SystemReset();+ }+ uint32_t count = CFG_OTA_NBR_OF_SECTOR_VAL_MSG;+ if (start >= end) return;+ if (start + count > end) count = end - start;++ uint32_t left = count;+ while (left)+ {+ left = FD_EraseSectors(start + (count - left), left);+ }+}++static const uint8_t *BleGetBdAddress(void)+{+ uint32_t udn = LL_FLASH_GetUDN();+ if (udn != 0xFFFFFFFF)+ {+ uint32_t company_id = LL_FLASH_GetSTCompanyID();+ a_BdAddr[0] = (uint8_t)(udn & 0xFF);+ a_BdAddr[1] = (uint8_t)((udn >> 8) & 0xFF);+ a_BdAddr[2] = (uint8_t)LL_FLASH_GetDeviceID();+ a_BdAddr[3] = (uint8_t)(company_id & 0xFF);+ a_BdAddr[4] = (uint8_t)((company_id >> 8) & 0xFF);+ a_BdAddr[5] = (uint8_t)((company_id >> 16) & 0xFF);+ return a_BdAddr;+ }+ uint8_t *p_otp = OTP_Read(0);+ if (p_otp) return ((OTP_ID0_t *)p_otp)->bd_address;+ for (int i = 0; i < 6; i++) a_BdAddr[i] = (uint8_t)(CFG_ADV_BD_ADDRESS >> (8 * i));+ return a_BdAddr;+}++static void Adv_Start(void)+{+ aci_gap_set_discoverable(ADV_IND, CFG_FAST_CONN_ADV_INTERVAL_MIN, CFG_FAST_CONN_ADV_INTERVAL_MAX,+ CFG_BLE_ADDRESS_TYPE, NO_WHITE_LIST_USE,+ sizeof(a_LocalName), a_LocalName, 0, 0, 0, 0);+ aci_gap_update_adv_data(sizeof(a_ManufData), a_ManufData);+}++void APP_BLE_Init(void)+{+ SHCI_C2_Ble_Init_Cmd_Packet_t ble_init_cmd_packet =+ {+ {{0, 0, 0}},+ {0,+ 0,+ CFG_BLE_NUM_GATT_ATTRIBUTES,+ CFG_BLE_NUM_GATT_SERVICES,+ CFG_BLE_ATT_VALUE_ARRAY_SIZE,+ CFG_BLE_NUM_LINK,+ CFG_BLE_DATA_LENGTH_EXTENSION,+ CFG_BLE_PREPARE_WRITE_LIST_SIZE,+ CFG_BLE_MBLOCK_COUNT,+ CFG_BLE_MAX_ATT_MTU,+ CFG_BLE_PERIPHERAL_SCA,+ CFG_BLE_CENTRAL_SCA,+ CFG_BLE_LS_SOURCE,+ CFG_BLE_MAX_CONN_EVENT_LENGTH,+ CFG_BLE_HSE_STARTUP_TIME,+ CFG_BLE_VITERBI_MODE,+ CFG_BLE_OPTIONS,+ 0,+ CFG_BLE_MAX_COC_INITIATOR_NBR,+ CFG_BLE_MIN_TX_POWER,+ CFG_BLE_MAX_TX_POWER,+ CFG_BLE_RX_MODEL_CONFIG,+ CFG_BLE_MAX_ADV_SET_NBR,+ CFG_BLE_MAX_ADV_DATA_LEN,+ CFG_BLE_TX_PATH_COMPENS,+ CFG_BLE_RX_PATH_COMPENS,+ CFG_BLE_CORE_VERSION,+ CFG_BLE_OPTIONS_EXT,+ CFG_BLE_MAX_ADD_EATT_BEARERS}+ };++ HCI_TL_HciInitConf_t hci_conf;+ hci_conf.p_cmdbuffer = (uint8_t *)&BleCmdBuffer;+ hci_conf.StatusNotCallBack = BLE_StatusNot;+ hci_init(BLE_UserEvtRx, (void *)&hci_conf);+ UTIL_LPM_SetOffMode(1 << CFG_LPM_APP_BLE, UTIL_LPM_DISABLE);+ UTIL_SEQ_RegTask(1 << CFG_TASK_HCI_ASYNCH_EVT_ID, UTIL_SEQ_RFU, hci_user_evt_proc);+ if (SHCI_C2_BLE_Init(&ble_init_cmd_packet) != SHCI_Success)+ {+ Error_Handler();+ }++ uint16_t gap_service_handle, gap_dev_name_char_handle, gap_appearance_char_handle;+ hci_reset();+ /* public address + 1, in the manufacturer data too (MSB first) */+ uint8_t addr[6];+ memcpy(addr, BleGetBdAddress(), 6);+ addr[0] += 1;+ aci_hal_write_config_data(CONFIG_DATA_PUBLIC_ADDRESS_OFFSET, CONFIG_DATA_PUBLIC_ADDRESS_LEN, addr);+ for (int i = 0; i < 6; i++) a_ManufData[sizeof(a_ManufData) - 1 - i] = addr[i];+ aci_hal_write_config_data(CONFIG_DATA_IR_OFFSET, CONFIG_DATA_IR_LEN, (uint8_t *)a_BLE_CfgIrValue);+ aci_hal_write_config_data(CONFIG_DATA_ER_OFFSET, CONFIG_DATA_ER_LEN, (uint8_t *)a_BLE_CfgErValue);+ aci_hal_set_tx_power_level(1, CFG_TX_POWER);+ aci_gatt_init();+ aci_gap_init(GAP_PERIPHERAL_ROLE, CFG_PRIVACY, sizeof(a_LocalName) - 1,+ &gap_service_handle, &gap_dev_name_char_handle, &gap_appearance_char_handle);+ aci_gatt_update_char_value(gap_service_handle, gap_dev_name_char_handle, 0,+ sizeof(a_LocalName) - 1, (uint8_t *)&a_LocalName[1]);+ SVCCTL_Init();++ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);+ Delete_Sectors();+ Adv_Start();+}++/* Only ST's OTA service (the weak default inits every service). */+void SVCCTL_SvcInit(void)+{+ OTAS_STM_Init();+}++SVCCTL_UserEvtFlowStatus_t SVCCTL_App_Notification(void *p_Pckt)+{+ hci_event_pckt *p_event_pckt = (hci_event_pckt *)((hci_uart_pckt *)p_Pckt)->data;+ switch (p_event_pckt->evt)+ {+ case HCI_DISCONNECTION_COMPLETE_EVT_CODE:+ Adv_Start();+ break;+ case HCI_LE_META_EVT_CODE:+ {+ evt_le_meta_event *p_meta_evt = (evt_le_meta_event *)p_event_pckt->data;+ if (p_meta_evt->subevent == HCI_LE_CONNECTION_COMPLETE_SUBEVT_CODE)+ {+ conn_handle = ((hci_le_connection_complete_event_rp0 *)p_meta_evt->data)->Connection_Handle;+ }+ else if (p_meta_evt->subevent == HCI_LE_ENHANCED_CONNECTION_COMPLETE_SUBEVT_CODE)+ {+ conn_handle = ((hci_le_enhanced_connection_complete_event_rp0 *)p_meta_evt->data)->Connection_Handle;+ }+ break;+ }+ case HCI_VENDOR_SPECIFIC_DEBUG_EVT_CODE:+ {+ evt_blecore_aci *p_blecore_evt = (evt_blecore_aci *)p_event_pckt->data;+ if (p_blecore_evt->ecode == ACI_GATT_INDICATION_VSEVT_CODE) aci_gatt_confirm_indication(conn_handle);+ break;+ }+ default:+ break;+ }+ return SVCCTL_UserEvtFlowEnable;+}++void hci_notify_asynch_evt(void *p_Data)+{+ UNUSED(p_Data);+ UTIL_SEQ_SetTask(1 << CFG_TASK_HCI_ASYNCH_EVT_ID, CFG_SCH_PRIO_0);+}++void hci_cmd_resp_release(uint32_t Flag)+{+ UNUSED(Flag);+ UTIL_SEQ_SetEvt(1 << CFG_IDLEEVT_HCI_CMD_EVT_RSP_ID);+}++void hci_cmd_resp_wait(uint32_t Timeout)+{+ UNUSED(Timeout);+ UTIL_SEQ_WaitEvt(1 << CFG_IDLEEVT_HCI_CMD_EVT_RSP_ID);+}++static void BLE_UserEvtRx(void *p_Payload)+{+ tHCI_UserEvtRxParam *p_param = (tHCI_UserEvtRxParam *)p_Payload;+ p_param->status = SVCCTL_UserEvtRx((void *)&(p_param->pckt->evtserial)) != SVCCTL_UserEvtFlowDisable+ ? HCI_TL_UserEventFlow_Enable : HCI_TL_UserEventFlow_Disable;+}++static void BLE_StatusNot(HCI_TL_CmdStatus_t Status)+{+ uint32_t task_id_list = (1 << CFG_LAST_TASK_ID_WITH_HCICMD) - 1;+ if (Status == HCI_TL_CmdBusy) UTIL_SEQ_PauseTask(task_id_list);+ else if (Status == HCI_TL_CmdAvailable) UTIL_SEQ_ResumeTask(task_id_list);+}++void SVCCTL_ResumeUserEventFlow(void)+{+ hci_resume_flow();+}diff --git a/firmware/ota_bootloader/STM32_WPAN/App/app_ble.h b/firmware/ota_bootloader/STM32_WPAN/App/app_ble.hnew file mode 100644index 0000000..0ea4b33--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/App/app_ble.h@@ -0,0 +1,12 @@+#ifndef APP_BLE_H+#define APP_BLE_H++#include "hci_tl.h"++void APP_BLE_Init(void);++/* First page OTA may write, and the first it may not (the keymap page). */+uint32_t APP_BLE_FirstAppPage(void);+uint32_t APP_BLE_EndAppPage(void);++#endif /* APP_BLE_H */diff --git a/firmware/ota_bootloader/STM32_WPAN/App/ble_conf.h b/firmware/ota_bootloader/STM32_WPAN/App/ble_conf.hnew file mode 100644index 0000000..6b88901--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/App/ble_conf.h@@ -0,0 +1,63 @@+/**+ ******************************************************************************+ * @file ble_conf.h+ * @author MCD Application Team+ * @brief BLE configuration file+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef __BLE_CONF_H+#define __BLE_CONF_H++#include "app_conf.h"++/******************************************************************************+ *+ * BLE SERVICES CONFIGURATION+ * blesvc+ *+ ******************************************************************************/++/**+ * This setting shall be set to '1' if the device needs to support the Peripheral Role+ * In the MS configuration, both BLE_CFG_PERIPHERAL and BLE_CFG_CENTRAL shall be set to '1'+ */+#define BLE_CFG_PERIPHERAL 1++/**+ * This setting shall be set to '1' if the device needs to support the Central Role+ * In the MS configuration, both BLE_CFG_PERIPHERAL and BLE_CFG_CENTRAL shall be set to '1'+ */+#define BLE_CFG_CENTRAL 0++/**+ * There is one handler per service enabled+ * Note: There is no handler for the Device Information Service+ *+ * This shall take into account all registered handlers+ * (from either the provided services or the custom services)+ */+#define BLE_CFG_SVC_MAX_NBR_CB 7++#define BLE_CFG_CLT_MAX_NBR_CB 0++/******************************************************************************+ * GAP Service - Appearance+ ******************************************************************************/+#define BLE_CFG_UNKNOWN_APPEARANCE (0)+#define BLE_CFG_HR_SENSOR_APPEARANCE (832)+#define BLE_CFG_GAP_APPEARANCE (BLE_CFG_UNKNOWN_APPEARANCE)++#endif /*__BLE_CONF_H */diff --git a/firmware/ota_bootloader/STM32_WPAN/App/ble_dbg_conf.h b/firmware/ota_bootloader/STM32_WPAN/App/ble_dbg_conf.hnew file mode 100644index 0000000..76207ba--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/App/ble_dbg_conf.h@@ -0,0 +1,216 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file ble_dbg_conf.h+ * @author MCD Application Team+ * @brief Debug configuration file for BLE Middleware.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2020-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef BLE_DBG_CONF_H+#define BLE_DBG_CONF_H++/**+ * Enable or Disable traces from BLE+ */++#define BLE_DBG_APP_EN 0+#define BLE_DBG_DIS_EN 0+#define BLE_DBG_HRS_EN 0+#define BLE_DBG_EDS_STM_EN 0+#define BLE_DBG_LBS_STM_EN 0+#define BLE_DBG_SVCCTL_EN 0+#define BLE_DBG_CTS_EN 0+#define BLE_DBG_HIDS_EN 0+#define BLE_DBG_PASS_EN 0+#define BLE_DBG_BLS_EN 0+#define BLE_DBG_HTS_EN 0+#define BLE_DBG_ANS_EN 0+#define BLE_DBG_ESS_EN 0+#define BLE_DBG_GLS_EN 0+#define BLE_DBG_BAS_EN 0+#define BLE_DBG_RTUS_EN 0+#define BLE_DBG_HPS_EN 0+#define BLE_DBG_TPS_EN 0+#define BLE_DBG_LLS_EN 0+#define BLE_DBG_IAS_EN 0+#define BLE_DBG_DTS_EN 0+#define BLE_DBG_WSS_EN 0+#define BLE_DBG_LNS_EN 0+#define BLE_DBG_SCPS_EN 0+#define BLE_DBG_P2P_STM_EN 0++/**+ * Macro definition+ */+#if (BLE_DBG_APP_EN != 0)+#define BLE_DBG_APP_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_APP_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_DIS_EN != 0)+#define BLE_DBG_DIS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_DIS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_HRS_EN != 0)+#define BLE_DBG_HRS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_HRS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_P2P_STM_EN != 0)+#define BLE_DBG_P2P_STM_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_P2P_STM_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_TEMPLATE_STM_EN != 0)+#define BLE_DBG_TEMPLATE_STM_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_TEMPLATE_STM_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_EDS_STM_EN != 0)+#define BLE_DBG_EDS_STM_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_EDS_STM_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_LBS_STM_EN != 0)+#define BLE_DBG_LBS_STM_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_LBS_STM_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_SVCCTL_EN != 0)+#define BLE_DBG_SVCCTL_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_SVCCTL_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_CTS_EN != 0)+#define BLE_DBG_CTS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_CTS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_HIDS_EN != 0)+#define BLE_DBG_HIDS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_HIDS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_PASS_EN != 0)+#define BLE_DBG_PASS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_PASS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_BLS_EN != 0)+#define BLE_DBG_BLS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_BLS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_HTS_EN != 0)+#define BLE_DBG_HTS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_HTS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_ANS_EN != 0)+#define BLE_DBG_ANS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_ANS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_ESS_EN != 0)+#define BLE_DBG_ESS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_ESS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_GLS_EN != 0)+#define BLE_DBG_GLS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_GLS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_BAS_EN != 0)+#define BLE_DBG_BAS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_BAS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_RTUS_EN != 0)+#define BLE_DBG_RTUS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_RTUS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_HPS_EN != 0)+#define BLE_DBG_HPS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_HPS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_TPS_EN != 0)+#define BLE_DBG_TPS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_TPS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_LLS_EN != 0)+#define BLE_DBG_LLS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_LLS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_IAS_EN != 0)+#define BLE_DBG_IAS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_IAS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_WSS_EN != 0)+#define BLE_DBG_WSS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_WSS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_LNS_EN != 0)+#define BLE_DBG_LNS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_LNS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_SCPS_EN != 0)+#define BLE_DBG_SCPS_MSG PRINT_MESG_DBG+#else+#define BLE_DBG_SCPS_MSG PRINT_NO_MESG+#endif++#if (BLE_DBG_DTS_EN != 0)+#define BLE_DBG_DTS_MSG PRINT_MESG_DBG+#define BLE_DBG_DTS_BUF PRINT_LOG_BUFF_DBG+#else+#define BLE_DBG_DTS_MSG PRINT_NO_MESG+#define BLE_DBG_DTS_BUF PRINT_NO_MESG+#endif++#endif /* BLE_DBG_CONF_H */diff --git a/firmware/ota_bootloader/STM32_WPAN/App/otas_app.c b/firmware/ota_bootloader/STM32_WPAN/App/otas_app.cnew file mode 100644index 0000000..a75eaff--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/App/otas_app.c@@ -0,0 +1,135 @@+/*+ * OTA service application side, same wire protocol as ST's BLE_Ota+ * otas_app.c (STM32CubeWB 1.24.0) so ST BLE Toolbox works with it:+ *+ * Base address char: [cmd, addr23..16, addr15..8, addr7..0]+ * cmd 0x02 = application upload starting at 0x08000000 + addr+ * cmd 0x07 = upload finished, we indicate 0x01 on the conf char+ * cmd 0x00 / 0x08 = stop / cancel+ * Raw data char: the image bytes, appended in order+ * Conf char: indication 0x01 "reboot confirmed"; once the client+ * confirms it we flush and reset into the new app.+ *+ * Differences from ST's, all to keep a bad transfer from hurting the+ * keyword:+ * - only application uploads, and only into [0x08007000, keymap page);+ * anything outside is dropped instead of written+ * - wireless (CPU2) uploads are refused: installing those through FUS+ * would move SFSA+ * - a doubleword that won't program (page not erased) aborts the upload+ * after a few tries instead of looping forever+ */+#include "app_common.h"+#include "main.h"+#include "ble.h"+#include "app_ble.h"+#include "flash_driver.h"++#define DW 8 /* flash programs 64 bits at a time */+#define TRIES 5++typedef enum+{+ ST_IDLE,+ ST_RECEIVING,+ ST_REJECTED,+} ota_state_t;++static ota_state_t state;+static uint32_t address; /* next doubleword to program */+static uint64_t pending; /* bytes waiting for a full doubleword */+static uint8_t pending_len;++static uint32_t End_Address(void)+{+ return FLASH_BASE + APP_BLE_EndAppPage() * FLASH_PAGE_SIZE;+}++/* Programs one doubleword at address. 0 on success. */+static int Program(uint64_t value)+{+ if (address < CFG_APP_START_ADDRESS || address + DW > End_Address()) return -1;+ for (int t = 0; t < TRIES; t++)+ {+ while (FD_WriteData(address, &value, 1) != 0); /* CPU2 busy: try again */+ if (*(volatile uint64_t *)address == value)+ {+ address += DW;+ return 0;+ }+ }+ return -1;+}++static void Raw_Data(const uint8_t *data, uint32_t len)+{+ while (len && state == ST_RECEIVING)+ {+ uint32_t n = DW - pending_len;+ if (n > len) n = len;+ memcpy((uint8_t *)&pending + pending_len, data, n);+ pending_len += n;+ data += n;+ len -= n;+ if (pending_len == DW)+ {+ if (Program(pending) != 0) state = ST_REJECTED;+ pending_len = 0;+ }+ }+}++void OTAS_STM_Notification(OTA_STM_Notification_t *p_notification)+{+ switch (p_notification->ChardId)+ {+ case OTAS_STM_BASE_ADDR_ID:+ {+ const OTA_STM_Base_Addr_Event_Format_t *cmd = (const OTA_STM_Base_Addr_Event_Format_t *)p_notification->pPayload;+ uint32_t addr = FLASH_BASE | (uint32_t)cmd->Base_Addr[0] << 16 | (uint32_t)cmd->Base_Addr[1] << 8 | cmd->Base_Addr[2];+ switch (cmd->Command)+ {+ case OTAS_STM_APPLICATION_UPLOAD:+ address = addr;+ pending_len = 0;+ state = (addr >= CFG_APP_START_ADDRESS && addr < End_Address() && (addr % DW) == 0) ? ST_RECEIVING : ST_REJECTED;+ break;+ case OTAS_STM_WIRELESS_FW_UPLOAD:+ state = ST_REJECTED;+ break;+ case OTAS_STM_UPLOAD_FINISHED:+ if (state == ST_RECEIVING)+ {+ OTAS_STM_Indication_Msg_t msg = OTAS_STM_REBOOT_CONFIRMED;+ OTAS_STM_UpdateChar(OTAS_STM_CONF_ID, (uint8_t *)&msg);+ }+ break;+ default: /* stop all, cancel */+ state = ST_IDLE;+ break;+ }+ break;+ }++ case OTAS_STM_RAW_DATA_ID:+ Raw_Data(p_notification->pPayload, p_notification->ValueLength);+ break;++ case OTAS_STM_CONF_EVENT_ID:+ /* The client confirmed "reboot": write the last partial doubleword+ * (padded with erased-flash 0xFF) and start the new app. If the+ * image never got its end tag the loader comes back up for another+ * try. */+ if (state == ST_RECEIVING && pending_len)+ {+ memset((uint8_t *)&pending + pending_len, 0xFF, DW - pending_len);+ Program(pending);+ }+ CFG_OTA_REBOOT_VAL_MSG = CFG_REBOOT_ON_FW_APP;+ NVIC_SystemReset();+ break;++ default:+ break;+ }+}diff --git a/firmware/ota_bootloader/STM32_WPAN/App/tl_dbg_conf.h b/firmware/ota_bootloader/STM32_WPAN/App/tl_dbg_conf.hnew file mode 100644index 0000000..9e45903--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/App/tl_dbg_conf.h@@ -0,0 +1,133 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file tl_dbg_conf.h+ * @author MCD Application Team+ * @brief Debug configuration file for stm32wpan transport layer interface.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2020-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef TL_DBG_CONF_H+#define TL_DBG_CONF_H++#ifdef __cplusplus+extern "C" {+#endif++/* USER CODE BEGIN Tl_Conf */++/* Includes ------------------------------------------------------------------*/+#include "app_conf.h" /* required as some configuration used in dbg_trace.h are set there */+#include "dbg_trace.h"+#include "hw_if.h"++/**+ * Enable or Disable traces+ * The raw data output is the hci binary packet format as specified by the BT specification *+ */+#define TL_SHCI_CMD_DBG_EN 0 /* Reports System commands sent to CPU2 and the command response */+#define TL_SHCI_CMD_DBG_RAW_EN 0 /* Reports raw data System commands sent to CPU2 and the command response */+#define TL_SHCI_EVT_DBG_EN 0 /* Reports System Asynchronous Events received from CPU2 */+#define TL_SHCI_EVT_DBG_RAW_EN 0 /* Reports raw data System Asynchronous Events received from CPU2 */++#define TL_HCI_CMD_DBG_EN 0 /* Reports BLE command sent to CPU2 and the command response */+#define TL_HCI_CMD_DBG_RAW_EN 0 /* Reports raw data BLE command sent to CPU2 and the command response */+#define TL_HCI_EVT_DBG_EN 0 /* Reports BLE Asynchronous Events received from CPU2 */+#define TL_HCI_EVT_DBG_RAW_EN 0 /* Reports raw data BLE Asynchronous Events received from CPU2 */++#define TL_MM_DBG_EN 0 /* Reports the information of the buffer released to CPU2 */++/**+ * Macro definition+ */++/**+ * System Transport Layer+ */+#if (TL_SHCI_CMD_DBG_EN != 0)+#define TL_SHCI_CMD_DBG_MSG PRINT_MESG_DBG+#define TL_SHCI_CMD_DBG_BUF PRINT_LOG_BUFF_DBG+#else+#define TL_SHCI_CMD_DBG_MSG(...)+#define TL_SHCI_CMD_DBG_BUF(...)+#endif++#if (TL_SHCI_CMD_DBG_RAW_EN != 0)+#define TL_SHCI_CMD_DBG_RAW(_PDATA_, _SIZE_) HW_UART_Transmit(hw_uart1, (uint8_t*)_PDATA_, _SIZE_, (~0))+#else+#define TL_SHCI_CMD_DBG_RAW(...)+#endif++#if (TL_SHCI_EVT_DBG_EN != 0)+#define TL_SHCI_EVT_DBG_MSG PRINT_MESG_DBG+#define TL_SHCI_EVT_DBG_BUF PRINT_LOG_BUFF_DBG+#else+#define TL_SHCI_EVT_DBG_MSG(...)+#define TL_SHCI_EVT_DBG_BUF(...)+#endif++#if (TL_SHCI_EVT_DBG_RAW_EN != 0)+#define TL_SHCI_EVT_DBG_RAW(_PDATA_, _SIZE_) HW_UART_Transmit(hw_uart1, (uint8_t*)_PDATA_, _SIZE_, (~0))+#else+#define TL_SHCI_EVT_DBG_RAW(...)+#endif++/**+ * BLE Transport Layer+ */+#if (TL_HCI_CMD_DBG_EN != 0)+#define TL_HCI_CMD_DBG_MSG PRINT_MESG_DBG+#define TL_HCI_CMD_DBG_BUF PRINT_LOG_BUFF_DBG+#else+#define TL_HCI_CMD_DBG_MSG(...)+#define TL_HCI_CMD_DBG_BUF(...)+#endif++#if (TL_HCI_CMD_DBG_RAW_EN != 0)+#define TL_HCI_CMD_DBG_RAW(_PDATA_, _SIZE_) HW_UART_Transmit(hw_uart1, (uint8_t*)_PDATA_, _SIZE_, (~0))+#else+#define TL_HCI_CMD_DBG_RAW(...)+#endif++#if (TL_HCI_EVT_DBG_EN != 0)+#define TL_HCI_EVT_DBG_MSG PRINT_MESG_DBG+#define TL_HCI_EVT_DBG_BUF PRINT_LOG_BUFF_DBG+#else+#define TL_HCI_EVT_DBG_MSG(...)+#define TL_HCI_EVT_DBG_BUF(...)+#endif++#if (TL_HCI_EVT_DBG_RAW_EN != 0)+#define TL_HCI_EVT_DBG_RAW(_PDATA_, _SIZE_) HW_UART_Transmit(hw_uart1, (uint8_t*)_PDATA_, _SIZE_, (~0))+#else+#define TL_HCI_EVT_DBG_RAW(...)+#endif++/**+ * Memory Manager - Released buffer tracing+ */+#if (TL_MM_DBG_EN != 0)+#define TL_MM_DBG_MSG PRINT_MESG_DBG+#else+#define TL_MM_DBG_MSG(...)+#endif++/* USER CODE END Tl_Conf */++#ifdef __cplusplus+}+#endif++#endif /* TL_DBG_CONF_H */diff --git a/firmware/ota_bootloader/STM32_WPAN/Target/hw_ipcc.c b/firmware/ota_bootloader/STM32_WPAN/Target/hw_ipcc.cnew file mode 100644index 0000000..6a311b1--- /dev/null+++ b/firmware/ota_bootloader/STM32_WPAN/Target/hw_ipcc.c@@ -0,0 +1,747 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file hw_ipcc.c+ * @author MCD Application Team+ * @brief Hardware IPCC source file for STM32WPAN Middleware.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2020-2021 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */+/* USER CODE END Header */++/* Includes ------------------------------------------------------------------*/+#include "app_common.h"+#include "mbox_def.h"+#include "utilities_conf.h"++/* Global variables ---------------------------------------------------------*/+/* Private defines -----------------------------------------------------------*/+#define HW_IPCC_TX_PENDING( channel ) ( !(LL_C1_IPCC_IsActiveFlag_CHx( IPCC, channel )) ) && (((~(IPCC->C1MR)) & (channel << 16U)))+#define HW_IPCC_RX_PENDING( channel ) (LL_C2_IPCC_IsActiveFlag_CHx( IPCC, channel )) && (((~(IPCC->C1MR)) & (channel << 0U)))++/* Private macros ------------------------------------------------------------*/+/* Private typedef -----------------------------------------------------------*/+/* Private variables ---------------------------------------------------------*/+static void (*FreeBufCb)( void );++/* Private function prototypes -----------------------------------------------*/+static void HW_IPCC_BLE_EvtHandler( void );+static void HW_IPCC_BLE_AclDataEvtHandler( void );+static void HW_IPCC_MM_FreeBufHandler( void );+static void HW_IPCC_SYS_CmdEvtHandler( void );+static void HW_IPCC_SYS_EvtHandler( void );+static void HW_IPCC_TRACES_EvtHandler( void );++#ifdef THREAD_WB+static void HW_IPCC_OT_CmdEvtHandler( void );+static void HW_IPCC_THREAD_NotEvtHandler( void );+static void HW_IPCC_THREAD_CliNotEvtHandler( void );+#endif++#ifdef LLD_TESTS_WB+static void HW_IPCC_LLDTESTS_ReceiveCliRspHandler( void );+static void HW_IPCC_LLDTESTS_ReceiveM0CmdHandler( void );+#endif+#ifdef LLD_BLE_WB+/*static void HW_IPCC_LLD_BLE_ReceiveCliRspHandler( void );*/+static void HW_IPCC_LLD_BLE_ReceiveRspHandler( void );+static void HW_IPCC_LLD_BLE_ReceiveM0CmdHandler( void );+#endif++#ifdef MAC_802_15_4_WB+static void HW_IPCC_MAC_802_15_4_CmdEvtHandler( void );+static void HW_IPCC_MAC_802_15_4_NotEvtHandler( void );+#endif++#ifdef ZIGBEE_WB+static void HW_IPCC_ZIGBEE_CmdEvtHandler( void );+static void HW_IPCC_ZIGBEE_StackNotifEvtHandler( void );+static void HW_IPCC_ZIGBEE_StackM0RequestHandler( void );+#endif++/* Public function definition -----------------------------------------------*/++/******************************************************************************+ * INTERRUPT HANDLER+ ******************************************************************************/+void HW_IPCC_Rx_Handler( void )+{+ if (HW_IPCC_RX_PENDING( HW_IPCC_SYSTEM_EVENT_CHANNEL ))+ {+ HW_IPCC_SYS_EvtHandler();+ }+#ifdef MAC_802_15_4_WB+ else if (HW_IPCC_RX_PENDING( HW_IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL ))+ {+ HW_IPCC_MAC_802_15_4_NotEvtHandler();+ }+#endif /* MAC_802_15_4_WB */+#ifdef THREAD_WB+ else if (HW_IPCC_RX_PENDING( HW_IPCC_THREAD_NOTIFICATION_ACK_CHANNEL ))+ {+ HW_IPCC_THREAD_NotEvtHandler();+ }+ else if (HW_IPCC_RX_PENDING( HW_IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL ))+ {+ HW_IPCC_THREAD_CliNotEvtHandler();+ }+#endif /* THREAD_WB */+#ifdef LLD_TESTS_WB+ else if (HW_IPCC_RX_PENDING( HW_IPCC_LLDTESTS_CLI_RSP_CHANNEL ))+ {+ HW_IPCC_LLDTESTS_ReceiveCliRspHandler();+ }+ else if (HW_IPCC_RX_PENDING( HW_IPCC_LLDTESTS_M0_CMD_CHANNEL ))+ {+ HW_IPCC_LLDTESTS_ReceiveM0CmdHandler();+ }+#endif /* LLD_TESTS_WB */+#ifdef LLD_BLE_WB+ else if (HW_IPCC_RX_PENDING( HW_IPCC_LLD_BLE_RSP_CHANNEL ))+ {+ HW_IPCC_LLD_BLE_ReceiveRspHandler();+ }+ else if (HW_IPCC_RX_PENDING( HW_IPCC_LLD_BLE_M0_CMD_CHANNEL ))+ {+ HW_IPCC_LLD_BLE_ReceiveM0CmdHandler();+ }+#endif /* LLD_TESTS_WB */+#ifdef ZIGBEE_WB+ else if (HW_IPCC_RX_PENDING( HW_IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL ))+ {+ HW_IPCC_ZIGBEE_StackNotifEvtHandler();+ }+ else if (HW_IPCC_RX_PENDING( HW_IPCC_ZIGBEE_M0_REQUEST_CHANNEL ))+ {+ HW_IPCC_ZIGBEE_StackM0RequestHandler();+ }+#endif /* ZIGBEE_WB */+ else if (HW_IPCC_RX_PENDING( HW_IPCC_BLE_EVENT_CHANNEL ))+ {+ HW_IPCC_BLE_EvtHandler();+ }+ else if (HW_IPCC_RX_PENDING( HW_IPCC_TRACES_CHANNEL ))+ {+ HW_IPCC_TRACES_EvtHandler();+ }++ return;+}++void HW_IPCC_Tx_Handler( void )+{+ if (HW_IPCC_TX_PENDING( HW_IPCC_SYSTEM_CMD_RSP_CHANNEL ))+ {+ HW_IPCC_SYS_CmdEvtHandler();+ }+#ifdef MAC_802_15_4_WB+ else if (HW_IPCC_TX_PENDING( HW_IPCC_MAC_802_15_4_CMD_RSP_CHANNEL ))+ {+ HW_IPCC_MAC_802_15_4_CmdEvtHandler();+ }+#endif /* MAC_802_15_4_WB */+#ifdef THREAD_WB+ else if (HW_IPCC_TX_PENDING( HW_IPCC_THREAD_OT_CMD_RSP_CHANNEL ))+ {+ HW_IPCC_OT_CmdEvtHandler();+ }+#endif /* THREAD_WB */+#ifdef LLD_TESTS_WB+// No TX handler for LLD tests+#endif /* LLD_TESTS_WB */+#ifdef ZIGBEE_WB+ if (HW_IPCC_TX_PENDING( HW_IPCC_ZIGBEE_CMD_APPLI_CHANNEL ))+ {+ HW_IPCC_ZIGBEE_CmdEvtHandler();+ }+#endif /* ZIGBEE_WB */+ else if (HW_IPCC_TX_PENDING( HW_IPCC_MM_RELEASE_BUFFER_CHANNEL ))+ {+ HW_IPCC_MM_FreeBufHandler();+ }+ else if (HW_IPCC_TX_PENDING( HW_IPCC_HCI_ACL_DATA_CHANNEL ))+ {+ HW_IPCC_BLE_AclDataEvtHandler();+ }++ return;+}+/******************************************************************************+ * GENERAL+ ******************************************************************************/+void HW_IPCC_Enable( void )+{+ /**+ * Such as IPCC IP available to the CPU2, it is required to keep the IPCC clock running+ * when FUS is running on CPU2 and CPU1 enters deep sleep mode+ */+ LL_C2_AHB3_GRP1_EnableClock(LL_C2_AHB3_GRP1_PERIPH_IPCC);++ /**+ * When the device is out of standby, it is required to use the EXTI mechanism to wakeup CPU2+ */+ LL_EXTI_EnableRisingTrig_32_63( LL_EXTI_LINE_41 );+ /* It is required to have at least a system clock cycle before a SEV after LL_EXTI_EnableRisingTrig_32_63() */+ LL_C2_EXTI_EnableEvent_32_63( LL_EXTI_LINE_41 );++ /**+ * In case the SBSFU is implemented, it may have already set the C2BOOT bit to startup the CPU2.+ * In that case, to keep the mechanism transparent to the user application, it shall call the system command+ * SHCI_C2_Reinit( ) before jumping to the application.+ * When the CPU2 receives that command, it waits for its event input to be set to restart the CPU2 firmware.+ * This is required because once C2BOOT has been set once, a clear/set on C2BOOT has no effect.+ * When SHCI_C2_Reinit( ) is not called, generating an event to the CPU2 does not have any effect+ * So, by default, the application shall both set the event flag and set the C2BOOT bit.+ */+ __SEV( ); /* Set the internal event flag and send an event to the CPU2 */+ __WFE( ); /* Clear the internal event flag */+ LL_PWR_EnableBootC2( );++ return;+}++void HW_IPCC_Init( void )+{+ LL_AHB3_GRP1_EnableClock( LL_AHB3_GRP1_PERIPH_IPCC );++ LL_C1_IPCC_EnableIT_RXO( IPCC );+ LL_C1_IPCC_EnableIT_TXF( IPCC );++ HAL_NVIC_EnableIRQ(IPCC_C1_RX_IRQn);+ HAL_NVIC_EnableIRQ(IPCC_C1_TX_IRQn);++ return;+}++/******************************************************************************+ * BLE+ ******************************************************************************/+void HW_IPCC_BLE_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_BLE_EVENT_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_BLE_SendCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_BLE_CMD_CHANNEL );++ return;+}++static void HW_IPCC_BLE_EvtHandler( void )+{+ HW_IPCC_BLE_RxEvtNot();++ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_BLE_EVENT_CHANNEL );++ return;+}++void HW_IPCC_BLE_SendAclData( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_HCI_ACL_DATA_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableTransmitChannel( IPCC, HW_IPCC_HCI_ACL_DATA_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++static void HW_IPCC_BLE_AclDataEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableTransmitChannel( IPCC, HW_IPCC_HCI_ACL_DATA_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_BLE_AclDataAckNot();++ return;+}++__weak void HW_IPCC_BLE_AclDataAckNot( void ){};+__weak void HW_IPCC_BLE_RxEvtNot( void ){};++/******************************************************************************+ * SYSTEM+ ******************************************************************************/+void HW_IPCC_SYS_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_SYSTEM_EVENT_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_SYS_SendCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_SYSTEM_CMD_RSP_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableTransmitChannel( IPCC, HW_IPCC_SYSTEM_CMD_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++static void HW_IPCC_SYS_CmdEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableTransmitChannel( IPCC, HW_IPCC_SYSTEM_CMD_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_SYS_CmdEvtNot();++ return;+}++static void HW_IPCC_SYS_EvtHandler( void )+{+ HW_IPCC_SYS_EvtNot();++ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_SYSTEM_EVENT_CHANNEL );++ return;+}++__weak void HW_IPCC_SYS_CmdEvtNot( void ){};+__weak void HW_IPCC_SYS_EvtNot( void ){};++/******************************************************************************+ * MAC 802.15.4+ ******************************************************************************/+#ifdef MAC_802_15_4_WB+void HW_IPCC_MAC_802_15_4_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_MAC_802_15_4_SendCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_MAC_802_15_4_CMD_RSP_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableTransmitChannel( IPCC, HW_IPCC_MAC_802_15_4_CMD_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_MAC_802_15_4_SendAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++static void HW_IPCC_MAC_802_15_4_CmdEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableTransmitChannel( IPCC, HW_IPCC_MAC_802_15_4_CMD_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_MAC_802_15_4_CmdEvtNot();++ return;+}++static void HW_IPCC_MAC_802_15_4_NotEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_MAC_802_15_4_EvtNot();++ return;+}+__weak void HW_IPCC_MAC_802_15_4_CmdEvtNot( void ){};+__weak void HW_IPCC_MAC_802_15_4_EvtNot( void ){};+#endif++/******************************************************************************+ * THREAD+ ******************************************************************************/+#ifdef THREAD_WB+void HW_IPCC_THREAD_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_THREAD_NOTIFICATION_ACK_CHANNEL );+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_OT_SendCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_THREAD_OT_CMD_RSP_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableTransmitChannel( IPCC, HW_IPCC_THREAD_OT_CMD_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_CLI_SendCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_THREAD_CLI_CMD_CHANNEL );++ return;+}++void HW_IPCC_THREAD_SendAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_THREAD_NOTIFICATION_ACK_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_THREAD_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_THREAD_CliSendAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++static void HW_IPCC_OT_CmdEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableTransmitChannel( IPCC, HW_IPCC_THREAD_OT_CMD_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_OT_CmdEvtNot();++ return;+}++static void HW_IPCC_THREAD_NotEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_THREAD_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_THREAD_EvtNot();++ return;+}++static void HW_IPCC_THREAD_CliNotEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_THREAD_CliEvtNot();++ return;+}++__weak void HW_IPCC_OT_CmdEvtNot( void ){};+__weak void HW_IPCC_CLI_CmdEvtNot( void ){};+__weak void HW_IPCC_THREAD_EvtNot( void ){};++#endif /* THREAD_WB */++/******************************************************************************+ * LLD TESTS+ ******************************************************************************/+#ifdef LLD_TESTS_WB+void HW_IPCC_LLDTESTS_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLDTESTS_CLI_RSP_CHANNEL );+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLDTESTS_M0_CMD_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ return;+}++void HW_IPCC_LLDTESTS_SendCliCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_LLDTESTS_CLI_CMD_CHANNEL );+ return;+}++static void HW_IPCC_LLDTESTS_ReceiveCliRspHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_LLDTESTS_CLI_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_LLDTESTS_ReceiveCliRsp();+ return;+}++void HW_IPCC_LLDTESTS_SendCliRspAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_LLDTESTS_CLI_RSP_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLDTESTS_CLI_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ return;+}++static void HW_IPCC_LLDTESTS_ReceiveM0CmdHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_LLDTESTS_M0_CMD_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ HW_IPCC_LLDTESTS_ReceiveM0Cmd();+ return;+}++void HW_IPCC_LLDTESTS_SendM0CmdAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_LLDTESTS_M0_CMD_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLDTESTS_M0_CMD_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ return;+}+__weak void HW_IPCC_LLDTESTS_ReceiveCliRsp( void ){};+__weak void HW_IPCC_LLDTESTS_ReceiveM0Cmd( void ){};+#endif /* LLD_TESTS_WB */++/******************************************************************************+ * LLD BLE+ ******************************************************************************/+#ifdef LLD_BLE_WB+void HW_IPCC_LLD_BLE_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_RSP_CHANNEL );+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_M0_CMD_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ return;+}++void HW_IPCC_LLD_BLE_SendCliCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_LLD_BLE_CLI_CMD_CHANNEL );+ return;+}++/*static void HW_IPCC_LLD_BLE_ReceiveCliRspHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_CLI_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ HW_IPCC_LLD_BLE_ReceiveCliRsp();+ return;+}*/++void HW_IPCC_LLD_BLE_SendCliRspAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_LLD_BLE_CLI_RSP_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_CLI_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ return;+}++static void HW_IPCC_LLD_BLE_ReceiveM0CmdHandler( void )+{+ //LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_M0_CMD_CHANNEL );+ HW_IPCC_LLD_BLE_ReceiveM0Cmd();+ return;+}++void HW_IPCC_LLD_BLE_SendM0CmdAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_LLD_BLE_M0_CMD_CHANNEL );+ //LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_M0_CMD_CHANNEL );+ return;+}+__weak void HW_IPCC_LLD_BLE_ReceiveCliRsp( void ){};+__weak void HW_IPCC_LLD_BLE_ReceiveM0Cmd( void ){};++/* Transparent Mode */+void HW_IPCC_LLD_BLE_SendCmd( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_LLD_BLE_CMD_CHANNEL );+ return;+}++static void HW_IPCC_LLD_BLE_ReceiveRspHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ HW_IPCC_LLD_BLE_ReceiveRsp();+ return;+}++void HW_IPCC_LLD_BLE_SendRspAck( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_LLD_BLE_RSP_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_LLD_BLE_RSP_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ return;+}++#endif /* LLD_BLE_WB */++/******************************************************************************+ * ZIGBEE+ ******************************************************************************/+#ifdef ZIGBEE_WB+void HW_IPCC_ZIGBEE_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL );+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_ZIGBEE_M0_REQUEST_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_ZIGBEE_SendM4RequestToM0( void )+{+ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_ZIGBEE_CMD_APPLI_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableTransmitChannel( IPCC, HW_IPCC_ZIGBEE_CMD_APPLI_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++void HW_IPCC_ZIGBEE_SendM4AckToM0Notify( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++static void HW_IPCC_ZIGBEE_CmdEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableTransmitChannel( IPCC, HW_IPCC_ZIGBEE_CMD_APPLI_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_ZIGBEE_RecvAppliAckFromM0();++ return;+}++static void HW_IPCC_ZIGBEE_StackNotifEvtHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_ZIGBEE_RecvM0NotifyToM4();++ return;+}++static void HW_IPCC_ZIGBEE_StackM0RequestHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableReceiveChannel( IPCC, HW_IPCC_ZIGBEE_M0_REQUEST_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ HW_IPCC_ZIGBEE_RecvM0RequestToM4();++ return;+}++void HW_IPCC_ZIGBEE_SendM4AckToM0Request( void )+{+ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_ZIGBEE_M0_REQUEST_CHANNEL );+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_ZIGBEE_M0_REQUEST_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++__weak void HW_IPCC_ZIGBEE_RecvAppliAckFromM0( void ){};+__weak void HW_IPCC_ZIGBEE_RecvM0NotifyToM4( void ){};+__weak void HW_IPCC_ZIGBEE_RecvM0RequestToM4( void ){};+#endif /* ZIGBEE_WB */++/******************************************************************************+ * MEMORY MANAGER+ ******************************************************************************/+void HW_IPCC_MM_SendFreeBuf( void (*cb)( void ) )+{+ if ( LL_C1_IPCC_IsActiveFlag_CHx( IPCC, HW_IPCC_MM_RELEASE_BUFFER_CHANNEL ) )+ {+ FreeBufCb = cb;+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableTransmitChannel( IPCC, HW_IPCC_MM_RELEASE_BUFFER_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();+ }+ else+ {+ cb();++ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_MM_RELEASE_BUFFER_CHANNEL );+ }++ return;+}++static void HW_IPCC_MM_FreeBufHandler( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_DisableTransmitChannel( IPCC, HW_IPCC_MM_RELEASE_BUFFER_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ FreeBufCb();++ LL_C1_IPCC_SetFlag_CHx( IPCC, HW_IPCC_MM_RELEASE_BUFFER_CHANNEL );++ return;+}++/******************************************************************************+ * TRACES+ ******************************************************************************/+void HW_IPCC_TRACES_Init( void )+{+ UTILS_ENTER_CRITICAL_SECTION();+ LL_C1_IPCC_EnableReceiveChannel( IPCC, HW_IPCC_TRACES_CHANNEL );+ UTILS_EXIT_CRITICAL_SECTION();++ return;+}++static void HW_IPCC_TRACES_EvtHandler( void )+{+ HW_IPCC_TRACES_EvtNot();++ LL_C1_IPCC_ClearFlag_CHx( IPCC, HW_IPCC_TRACES_CHANNEL );++ return;+}++__weak void HW_IPCC_TRACES_EvtNot( void ){};diff --git a/firmware/ota_bootloader/ota_bootloader.ld b/firmware/ota_bootloader/ota_bootloader.ldnew file mode 100644index 0000000..35d0bd4--- /dev/null+++ b/firmware/ota_bootloader/ota_bootloader.ld@@ -0,0 +1,234 @@+/**+*****************************************************************************+**+** File : stm32wb55xx_flash_cm4.ld+**+** Author : STM32CubeIDE+**+** Abstract : Linker script for STM32WB55xx Device+** 1024Kbytes FLASH+** 128Kbytes RAM+**+** Set heap size, stack size and stack location according+** to application requirements.+**+** Set memory bank area and size if external memory is used.+**+** Target : STMicroelectronics STM32+**+** Distribution: The file is distributed as is without any warranty+** of any kind.+**+*****************************************************************************+** @attention+**+** Copyright (c) 2019-2022 STMicroelectronics.+** All rights reserved.+**+** This software is licensed under terms that can be found in the LICENSE file+** in the root directory of this software component.+** If no LICENSE file comes with this software, it is provided AS-IS.+**+*****************************************************************************+*/++/* Entry Point */+ENTRY(Reset_Handler)+++/* Specify the memory areas */+MEMORY+{+FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 28K /* pages 0-6, the app starts at 0x08007000 */+RAM1 (xrw) : ORIGIN = 0x20000008, LENGTH = 0x2FFF8+RAM_SHARED (xrw) : ORIGIN = 0x20030000, LENGTH = 10K+}+/* Highest address of the user mode stack */+_estack = 0x20030000; /* end of RAM */+/* Generate a link error if heap and stack don't fit into RAM */+_Min_Heap_Size = 0x200; /* required amount of heap */+_Min_Stack_Size = 0x1000; /* required amount of stack: BLE event handlers + vsnprintf in proto.c */++/* Define output sections */+SECTIONS+{+ /* The startup code goes first into FLASH */+ .isr_vector :+ {+ . = ALIGN(4);+ KEEP(*(.isr_vector)) /* Startup code */+ . = ALIGN(4);+ } >FLASH++ /* The program code and other data goes into FLASH */+ .text :+ {+ . = ALIGN(4);+ *(.text) /* .text sections (code) */+ *(.text*) /* .text* sections (code) */+ *(.glue_7) /* glue arm to thumb code */+ *(.glue_7t) /* glue thumb to arm code */+ *(.eh_frame)++ KEEP (*(.init))+ KEEP (*(.fini))++ . = ALIGN(4);+ _etext = .; /* define a global symbols at end of code */+ } >FLASH++ /* Constant data goes into FLASH */+ .rodata :+ {+ . = ALIGN(4);+ *(.rodata) /* .rodata sections (constants, strings, etc.) */+ *(.rodata*) /* .rodata* sections (constants, strings, etc.) */+ . = ALIGN(4);+ } >FLASH++ .ARM.extab (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */+ {+ *(.ARM.extab* .gnu.linkonce.armextab.*)+ } >FLASH+ .ARM (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */+ {+ __exidx_start = .;+ *(.ARM.exidx*)+ __exidx_end = .;+ } >FLASH++ .preinit_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */+ {+ PROVIDE_HIDDEN (__preinit_array_start = .);+ KEEP (*(.preinit_array*))+ PROVIDE_HIDDEN (__preinit_array_end = .);+ } >FLASH+ .init_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */+ {+ PROVIDE_HIDDEN (__init_array_start = .);+ KEEP (*(SORT(.init_array.*)))+ KEEP (*(.init_array*))+ PROVIDE_HIDDEN (__init_array_end = .);+ } >FLASH+ .fini_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */+ {+ PROVIDE_HIDDEN (__fini_array_start = .);+ KEEP (*(SORT(.fini_array.*)))+ KEEP (*(.fini_array*))+ PROVIDE_HIDDEN (__fini_array_end = .);+ } >FLASH++ /* used by the startup to initialize data */+ _sidata = LOADADDR(.data);++ /* Initialized data sections goes into RAM, load LMA copy after code */+ .data :+ {+ . = ALIGN(4);+ _sdata = .; /* create a global symbol at data start */+ *(.data) /* .data sections */+ *(.data*) /* .data* sections */++ . = ALIGN(4);+ } >RAM1 AT> FLASH++ /* Initialized TLS data section */+ .tdata : ALIGN(4)+ {+ *(.tdata .tdata.* .gnu.linkonce.td.*)+ . = ALIGN(4);+ _edata = .; /* define a global symbol at data end */+ PROVIDE(__data_end = .);+ PROVIDE(__tdata_end = .);+ } >RAM1 AT> FLASH++ PROVIDE( __tdata_start = ADDR(.tdata) );+ PROVIDE( __tdata_size = __tdata_end - __tdata_start );++ PROVIDE( __data_start = ADDR(.data) );+ PROVIDE( __data_size = __data_end - __data_start );++ PROVIDE( __tdata_source = LOADADDR(.tdata) );+ PROVIDE( __tdata_source_end = LOADADDR(.tdata) + SIZEOF(.tdata) );+ PROVIDE( __tdata_source_size = __tdata_source_end - __tdata_source );++ PROVIDE( __data_source = LOADADDR(.data) );+ PROVIDE( __data_source_end = __tdata_source_end );+ PROVIDE( __data_source_size = __data_source_end - __data_source );+++ /* Uninitialized data section */+ /* Uninitialized TLS data section */+ .tbss (NOLOAD) : ALIGN(4)+ {+ _sbss = .; /* define a global symbol at bss start */+ __bss_start__ = _sbss;+ *(.tbss .tbss.*)+ . = ALIGN(4);+ PROVIDE( __tbss_end = . );+ } >RAM1++ PROVIDE( __tbss_start = ADDR(.tbss) );+ PROVIDE( __tbss_size = __tbss_end - __tbss_start );+ PROVIDE( __tbss_offset = ADDR(.tbss) - ADDR(.tdata) );++ PROVIDE( __tls_base = __tdata_start );+ PROVIDE( __tls_end = __tbss_end );+ PROVIDE( __tls_size = __tls_end - __tls_base );+ PROVIDE( __tls_align = MAX(ALIGNOF(.tdata), ALIGNOF(.tbss)) );+ PROVIDE( __tls_size_align = (__tls_size + __tls_align - 1) & ~(__tls_align - 1) );+ PROVIDE( __arm32_tls_tcb_offset = MAX(8, __tls_align) );+ PROVIDE( __arm64_tls_tcb_offset = MAX(16, __tls_align) );++ .bss (NOLOAD) : ALIGN(4)+ {+ /* This is used by the startup in order to initialize the .bss section */+ *(.bss)+ *(.bss*)+ *(COMMON)++ . = ALIGN(4);+ _ebss = .; /* define a global symbol at bss end */+ __bss_end__ = _ebss;+ PROVIDE( __bss_end = .);+ } >RAM1+ PROVIDE( __non_tls_bss_start = ADDR(.bss) );++ PROVIDE( __bss_start = __tbss_start );+ PROVIDE( __bss_size = __bss_end - __bss_start );+++ /* User_heap_stack section, used to check that there is enough RAM left */+ ._user_heap_stack (NOLOAD) :+ {+ . = ALIGN(8);+ PROVIDE ( end = . );+ PROVIDE ( _end = . );+ . = . + _Min_Heap_Size;+ . = . + _Min_Stack_Size;+ . = ALIGN(8);+ } >RAM1++ /* Remove information from the standard libraries */+ /DISCARD/ :+ {+ libc.a:* ( * )+ libm.a:* ( * )+ libgcc.a:* ( * )+ }++ .ARM.attributes 0 : { *(.ARM.attributes) }+ MAPPING_TABLE (NOLOAD) : { *(MAPPING_TABLE) } >RAM_SHARED+ MB_MEM1 (NOLOAD) : { *(MB_MEM1) } >RAM_SHARED++ /* used by the startup to initialize .MB_MEM2 data */+ _siMB_MEM2 = LOADADDR(.MB_MEM2);+ .MB_MEM2 :+ {+ _sMB_MEM2 = . ;+ *(MB_MEM2) ;+ _eMB_MEM2 = . ;+ } >RAM_SHARED AT> FLASH+}++diff --git a/firmware/ota_bootloader/startup_stm32wb55xx_cm4.s b/firmware/ota_bootloader/startup_stm32wb55xx_cm4.snew file mode 100644index 0000000..8f391be--- /dev/null+++ b/firmware/ota_bootloader/startup_stm32wb55xx_cm4.s@@ -0,0 +1,447 @@+/**+ ******************************************************************************+ * @file startup_stm32wb55xx_cm4.s+ * @author MCD Application Team+ * @brief STM32WB55xx devices vector table GCC toolchain.+ * This module performs:+ * - Set the initial SP+ * - Set the initial PC == Reset_Handler,+ * - Set the vector table entries with the exceptions ISR address+ * - Branches to main in the C library (which eventually+ * calls main()).+ * After Reset the Cortex-M4 processor is in Thread mode,+ * priority is Privileged, and the Stack is set to Main.+ ******************************************************************************+ * @attention+ *+ * Copyright (c) 2019-2022 STMicroelectronics.+ * All rights reserved.+ *+ * This software is licensed under terms that can be found in the LICENSE file+ * in the root directory of this software component.+ * If no LICENSE file comes with this software, it is provided AS-IS.+ *+ ******************************************************************************+ */++ .syntax unified+ .cpu cortex-m4+ .fpu softvfp+ .thumb++.global g_pfnVectors+.global Default_Handler++/* start address for the initialization values of the .data section.+defined in linker script */+.word _sidata+/* start address for the .data section. defined in linker script */+.word _sdata+/* end address for the .data section. defined in linker script */+.word _edata+/* start address for the .bss section. defined in linker script */+.word _sbss+/* end address for the .bss section. defined in linker script */+.word _ebss+/* start address for the initialization values of the .MB_MEM2 section.+defined in linker script */+.word _siMB_MEM2+/* start address for the .MB_MEM2 section. defined in linker script */+.word _sMB_MEM2+/* end address for the .MB_MEM2 section. defined in linker script */+.word _eMB_MEM2++/* INIT_BSS macro is used to fill the specified region [start : end] with zeros */+.macro INIT_BSS start, end+ ldr r0, =\start+ ldr r1, =\end+ movs r3, #0+ bl LoopFillZerobss+.endm++/* INIT_DATA macro is used to copy data in the region [start : end] starting from 'src' */+.macro INIT_DATA start, end, src+ ldr r0, =\start+ ldr r1, =\end+ ldr r2, =\src+ movs r3, #0+ bl LoopCopyDataInit+.endm++.section .text.data_initializers+CopyDataInit:+ ldr r4, [r2, r3]+ str r4, [r0, r3]+ adds r3, r3, #4++LoopCopyDataInit:+ adds r4, r0, r3+ cmp r4, r1+ bcc CopyDataInit+ bx lr++FillZerobss:+ str r3, [r0]+ adds r0, r0, #4++LoopFillZerobss:+ cmp r0, r1+ bcc FillZerobss+ bx lr++ .section .text.Reset_Handler+ .weak Reset_Handler+ .type Reset_Handler, %function+Reset_Handler:+ ldr r0, =_estack+ mov sp, r0 /* set stack pointer */+/* Call the clock system initialization function.*/+ bl SystemInit++/* Copy the data segment initializers from flash to SRAM */+ INIT_DATA _sdata, _edata, _sidata+ INIT_DATA _sMB_MEM2, _eMB_MEM2, _siMB_MEM2++/* Zero fill the bss segments. */+ INIT_BSS _sbss, _ebss++/* Call static constructors */+ bl __libc_init_array+/* Call the application s entry point.*/+ bl main++LoopForever:+ b LoopForever++.size Reset_Handler, .-Reset_Handler++/**+ * @brief This is the code that gets called when the processor receives an+ * unexpected interrupt. This simply enters an infinite loop, preserving+ * the system state for examination by a debugger.+ *+ * @param None+ * @retval None+*/+ .section .text.Default_Handler,"ax",%progbits+Default_Handler:+Infinite_Loop:+ b Infinite_Loop+ .size Default_Handler, .-Default_Handler+/******************************************************************************+*+* The minimal vector table for a Cortex-M4. Note that the proper constructs+* must be placed on this to ensure that it ends up at physical address+* 0x0000.0000.+*+******************************************************************************/+ .section .isr_vector,"a",%progbits+ .type g_pfnVectors, %object+++g_pfnVectors:+ .word _estack+ .word Reset_Handler+ .word NMI_Handler+ .word HardFault_Handler+ .word MemManage_Handler+ .word BusFault_Handler+ .word UsageFault_Handler+ .word 0+ .word 0+ .word 0+ .word 0+ .word SVC_Handler+ .word DebugMon_Handler+ .word 0+ .word PendSV_Handler+ .word SysTick_Handler+ .word WWDG_IRQHandler+ .word PVD_PVM_IRQHandler+ .word TAMP_STAMP_LSECSS_IRQHandler+ .word RTC_WKUP_IRQHandler+ .word FLASH_IRQHandler+ .word RCC_IRQHandler+ .word EXTI0_IRQHandler+ .word EXTI1_IRQHandler+ .word EXTI2_IRQHandler+ .word EXTI3_IRQHandler+ .word EXTI4_IRQHandler+ .word DMA1_Channel1_IRQHandler+ .word DMA1_Channel2_IRQHandler+ .word DMA1_Channel3_IRQHandler+ .word DMA1_Channel4_IRQHandler+ .word DMA1_Channel5_IRQHandler+ .word DMA1_Channel6_IRQHandler+ .word DMA1_Channel7_IRQHandler+ .word ADC1_IRQHandler+ .word USB_HP_IRQHandler+ .word USB_LP_IRQHandler+ .word C2SEV_PWR_C2H_IRQHandler+ .word COMP_IRQHandler+ .word EXTI9_5_IRQHandler+ .word TIM1_BRK_IRQHandler+ .word TIM1_UP_TIM16_IRQHandler+ .word TIM1_TRG_COM_TIM17_IRQHandler+ .word TIM1_CC_IRQHandler+ .word TIM2_IRQHandler+ .word PKA_IRQHandler+ .word I2C1_EV_IRQHandler+ .word I2C1_ER_IRQHandler+ .word I2C3_EV_IRQHandler+ .word I2C3_ER_IRQHandler+ .word SPI1_IRQHandler+ .word SPI2_IRQHandler+ .word USART1_IRQHandler+ .word LPUART1_IRQHandler+ .word SAI1_IRQHandler+ .word TSC_IRQHandler+ .word EXTI15_10_IRQHandler+ .word RTC_Alarm_IRQHandler+ .word CRS_IRQHandler+ .word PWR_SOTF_BLEACT_802ACT_RFPHASE_IRQHandler+ .word IPCC_C1_RX_IRQHandler+ .word IPCC_C1_TX_IRQHandler+ .word HSEM_IRQHandler+ .word LPTIM1_IRQHandler+ .word LPTIM2_IRQHandler+ .word LCD_IRQHandler+ .word QUADSPI_IRQHandler+ .word AES1_IRQHandler+ .word AES2_IRQHandler+ .word RNG_IRQHandler+ .word FPU_IRQHandler+ .word DMA2_Channel1_IRQHandler+ .word DMA2_Channel2_IRQHandler+ .word DMA2_Channel3_IRQHandler+ .word DMA2_Channel4_IRQHandler+ .word DMA2_Channel5_IRQHandler+ .word DMA2_Channel6_IRQHandler+ .word DMA2_Channel7_IRQHandler+ .word DMAMUX1_OVR_IRQHandler++ .size g_pfnVectors, .-g_pfnVectors++/*******************************************************************************+*+* Provide weak aliases for each Exception handler to the Default_Handler.+* As they are weak aliases, any function with the same name will override+* this definition.+*+*******************************************************************************/+ .weak NMI_Handler+ .thumb_set NMI_Handler,Default_Handler++ .weak HardFault_Handler+ .thumb_set HardFault_Handler,Default_Handler++ .weak MemManage_Handler+ .thumb_set MemManage_Handler,Default_Handler++ .weak BusFault_Handler+ .thumb_set BusFault_Handler,Default_Handler++ .weak UsageFault_Handler+ .thumb_set UsageFault_Handler,Default_Handler++ .weak SVC_Handler+ .thumb_set SVC_Handler,Default_Handler++ .weak DebugMon_Handler+ .thumb_set DebugMon_Handler,Default_Handler++ .weak PendSV_Handler+ .thumb_set PendSV_Handler,Default_Handler++ .weak SysTick_Handler+ .thumb_set SysTick_Handler,Default_Handler++ .weak WWDG_IRQHandler+ .thumb_set WWDG_IRQHandler,Default_Handler++ .weak PVD_PVM_IRQHandler+ .thumb_set PVD_PVM_IRQHandler,Default_Handler++ .weak TAMP_STAMP_LSECSS_IRQHandler+ .thumb_set TAMP_STAMP_LSECSS_IRQHandler,Default_Handler++ .weak RTC_WKUP_IRQHandler+ .thumb_set RTC_WKUP_IRQHandler,Default_Handler++ .weak FLASH_IRQHandler+ .thumb_set FLASH_IRQHandler,Default_Handler++ .weak RCC_IRQHandler+ .thumb_set RCC_IRQHandler,Default_Handler++ .weak EXTI0_IRQHandler+ .thumb_set EXTI0_IRQHandler,Default_Handler++ .weak EXTI1_IRQHandler+ .thumb_set EXTI1_IRQHandler,Default_Handler++ .weak EXTI2_IRQHandler+ .thumb_set EXTI2_IRQHandler,Default_Handler++ .weak EXTI3_IRQHandler+ .thumb_set EXTI3_IRQHandler,Default_Handler++ .weak EXTI4_IRQHandler+ .thumb_set EXTI4_IRQHandler,Default_Handler++ .weak DMA1_Channel1_IRQHandler+ .thumb_set DMA1_Channel1_IRQHandler,Default_Handler++ .weak DMA1_Channel2_IRQHandler+ .thumb_set DMA1_Channel2_IRQHandler,Default_Handler++ .weak DMA1_Channel3_IRQHandler+ .thumb_set DMA1_Channel3_IRQHandler,Default_Handler++ .weak DMA1_Channel4_IRQHandler+ .thumb_set DMA1_Channel4_IRQHandler,Default_Handler++ .weak DMA1_Channel5_IRQHandler+ .thumb_set DMA1_Channel5_IRQHandler,Default_Handler++ .weak DMA1_Channel6_IRQHandler+ .thumb_set DMA1_Channel6_IRQHandler,Default_Handler++ .weak DMA1_Channel7_IRQHandler+ .thumb_set DMA1_Channel7_IRQHandler,Default_Handler++ .weak ADC1_IRQHandler+ .thumb_set ADC1_IRQHandler,Default_Handler++ .weak USB_HP_IRQHandler+ .thumb_set USB_HP_IRQHandler,Default_Handler++ .weak USB_LP_IRQHandler+ .thumb_set USB_LP_IRQHandler,Default_Handler++ .weak C2SEV_PWR_C2H_IRQHandler+ .thumb_set C2SEV_PWR_C2H_IRQHandler,Default_Handler++ .weak COMP_IRQHandler+ .thumb_set COMP_IRQHandler,Default_Handler++ .weak EXTI9_5_IRQHandler+ .thumb_set EXTI9_5_IRQHandler,Default_Handler++ .weak TIM1_BRK_IRQHandler+ .thumb_set TIM1_BRK_IRQHandler,Default_Handler++ .weak TIM1_UP_TIM16_IRQHandler+ .thumb_set TIM1_UP_TIM16_IRQHandler,Default_Handler++ .weak TIM1_TRG_COM_TIM17_IRQHandler+ .thumb_set TIM1_TRG_COM_TIM17_IRQHandler,Default_Handler++ .weak TIM1_CC_IRQHandler+ .thumb_set TIM1_CC_IRQHandler,Default_Handler++ .weak TIM2_IRQHandler+ .thumb_set TIM2_IRQHandler,Default_Handler++ .weak PKA_IRQHandler+ .thumb_set PKA_IRQHandler,Default_Handler++ .weak I2C1_EV_IRQHandler+ .thumb_set I2C1_EV_IRQHandler,Default_Handler++ .weak I2C1_ER_IRQHandler+ .thumb_set I2C1_ER_IRQHandler,Default_Handler++ .weak I2C3_EV_IRQHandler+ .thumb_set I2C3_EV_IRQHandler,Default_Handler++ .weak I2C3_ER_IRQHandler+ .thumb_set I2C3_ER_IRQHandler,Default_Handler++ .weak SPI1_IRQHandler+ .thumb_set SPI1_IRQHandler,Default_Handler++ .weak SPI2_IRQHandler+ .thumb_set SPI2_IRQHandler,Default_Handler++ .weak USART1_IRQHandler+ .thumb_set USART1_IRQHandler,Default_Handler++ .weak LPUART1_IRQHandler+ .thumb_set LPUART1_IRQHandler,Default_Handler++ .weak SAI1_IRQHandler+ .thumb_set SAI1_IRQHandler,Default_Handler++ .weak TSC_IRQHandler+ .thumb_set TSC_IRQHandler,Default_Handler++ .weak EXTI15_10_IRQHandler+ .thumb_set EXTI15_10_IRQHandler,Default_Handler++ .weak RTC_Alarm_IRQHandler+ .thumb_set RTC_Alarm_IRQHandler,Default_Handler++ .weak CRS_IRQHandler+ .thumb_set CRS_IRQHandler,Default_Handler++ .weak PWR_SOTF_BLEACT_802ACT_RFPHASE_IRQHandler+ .thumb_set PWR_SOTF_BLEACT_802ACT_RFPHASE_IRQHandler,Default_Handler++ .weak IPCC_C1_RX_IRQHandler+ .thumb_set IPCC_C1_RX_IRQHandler,Default_Handler++ .weak IPCC_C1_TX_IRQHandler+ .thumb_set IPCC_C1_TX_IRQHandler,Default_Handler++ .weak HSEM_IRQHandler+ .thumb_set HSEM_IRQHandler,Default_Handler++ .weak LPTIM1_IRQHandler+ .thumb_set LPTIM1_IRQHandler,Default_Handler++ .weak LPTIM2_IRQHandler+ .thumb_set LPTIM2_IRQHandler,Default_Handler++ .weak LCD_IRQHandler+ .thumb_set LCD_IRQHandler,Default_Handler++ .weak QUADSPI_IRQHandler+ .thumb_set QUADSPI_IRQHandler,Default_Handler++ .weak AES1_IRQHandler+ .thumb_set AES1_IRQHandler,Default_Handler++ .weak AES2_IRQHandler+ .thumb_set AES2_IRQHandler,Default_Handler++ .weak RNG_IRQHandler+ .thumb_set RNG_IRQHandler,Default_Handler++ .weak FPU_IRQHandler+ .thumb_set FPU_IRQHandler,Default_Handler++ .weak DMA2_Channel1_IRQHandler+ .thumb_set DMA2_Channel1_IRQHandler,Default_Handler++ .weak DMA2_Channel2_IRQHandler+ .thumb_set DMA2_Channel2_IRQHandler,Default_Handler++ .weak DMA2_Channel3_IRQHandler+ .thumb_set DMA2_Channel3_IRQHandler,Default_Handler++ .weak DMA2_Channel4_IRQHandler+ .thumb_set DMA2_Channel4_IRQHandler,Default_Handler++ .weak DMA2_Channel5_IRQHandler+ .thumb_set DMA2_Channel5_IRQHandler,Default_Handler++ .weak DMA2_Channel6_IRQHandler+ .thumb_set DMA2_Channel6_IRQHandler,Default_Handler++ .weak DMA2_Channel7_IRQHandler+ .thumb_set DMA2_Channel7_IRQHandler,Default_Handler++ .weak DMAMUX1_OVR_IRQHandler+ .thumb_set DMAMUX1_OVR_IRQHandler,Default_Handler+diff --git a/firmware/ota_bootloader/tools/merge.py b/firmware/ota_bootloader/tools/merge.pynew file mode 100644index 0000000..c862484--- /dev/null+++ b/firmware/ota_bootloader/tools/merge.py@@ -0,0 +1,82 @@+"""+Builds the one-time install image: the OTA bootloader at 0x08000000, 0xFF+up to the app, the app at 0x08007000.++ merge.py BOOT.bin APP.bin 0x7000 OUT.bin write OUT.bin+ merge.py --check BOOT.bin APP.bin 0x7000 OUT.bin verify it byte by byte++The check also runs the bootloader's own validity test on the app (the+word at +0x140 must point at 0x94448A29 inside the image) and makes sure+nothing reaches the keymap page at 0x080CF000.+"""+import struct+import sys++FLASH_BASE = 0x08000000+KEYMAP_PAGE = 0x080CF000 # SFSA - 1 with the v1.24.0 full BLE stack at 0x080D0000+MAGIC = 0x94448A29+TAG_OFFSET = 0x140+++def fail(msg: str) -> None:+ sys.exit(f"merge.py: {msg}")+++def check_app(app: bytes, base: int) -> None:+ if len(app) < TAG_OFFSET + 4:+ fail("app image too small")+ sp, reset = struct.unpack_from("<II", app, 0)+ if not 0x20000000 <= sp <= 0x20030000:+ fail(f"app initial SP {sp:#x} is not in SRAM1")+ if not base <= (reset & ~1) < base + len(app):+ fail(f"app reset vector {reset:#x} is outside the app")+ (tag_addr,) = struct.unpack_from("<I", app, TAG_OFFSET)+ if not base <= tag_addr <= base + len(app) - 4:+ fail(f"app tag address {tag_addr:#x} is outside the image (TAG_OTA_START missing?)")+ (magic,) = struct.unpack_from("<I", app, tag_addr - base)+ if magic != MAGIC:+ fail(f"no {MAGIC:#x} at {tag_addr:#x}: the bootloader would refuse this app")+ if tag_addr - base + 4 != len(app) and tag_addr - base + 8 < len(app):+ fail(f"tag at {tag_addr:#x} is not at the end of the image ({base + len(app):#x})")+++def main() -> None:+ args = sys.argv[1:]+ check = args and args[0] == "--check"+ if check:+ args = args[1:]+ if len(args) != 4:+ fail(__doc__.strip())+ boot = open(args[0], "rb").read()+ app = open(args[1], "rb").read()+ offset = int(args[2], 0)++ if len(boot) > offset:+ fail(f"bootloader is {len(boot)} bytes, more than the {offset:#x} before the app")+ app_base = FLASH_BASE + offset+ if app_base + len(app) > KEYMAP_PAGE:+ fail(f"app ends at {app_base + len(app):#x}, past the keymap page {KEYMAP_PAGE:#x}")+ check_app(app, app_base)+ want = boot + b"\xff" * (offset - len(boot)) + app++ if not check:+ open(args[3], "wb").write(want)+ print(f"{args[3]}: {len(want)} bytes, bootloader {len(boot)} at {FLASH_BASE:#x}, "+ f"app {len(app)} at {app_base:#x}, ends {FLASH_BASE + len(want):#x}")+ return++ got = open(args[3], "rb").read()+ if got[:len(boot)] != boot:+ fail("bootloader bytes differ")+ if any(b != 0xFF for b in got[len(boot):offset]):+ fail("gap before the app is not all 0xFF")+ if got[offset:] != app:+ fail("app bytes differ")+ if got != want:+ fail("image differs")+ print(f"{args[3]}: verified, bootloader {len(boot)} B + 0xFF gap {offset - len(boot)} B "+ f"+ app {len(app)} B at {app_base:#x}")+++if __name__ == "__main__":+ main()