A truly modular keyboard
C
firmware: BLE HID keyboard and NUS config channel
Nathan1f1ad4c01462
diff --git a/firmware/Core/Inc/app_common.h b/firmware/Core/Inc/app_common.hnew file mode 100644index 0000000..1f0fc57--- /dev/null+++ b/firmware/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/Core/Inc/app_conf.h b/firmware/Core/Inc/app_conf.hnew file mode 100644index 0000000..ff3f3a5--- /dev/null+++ b/firmware/Core/Inc/app_conf.h@@ -0,0 +1,146 @@+/*+ * STM32_WPAN config for the keyword, trimmed down from ST's BLE_Hid example+ * (STM32CubeWB 1.24.0). Peripheral only, one link, Just Works bonding.+ */+#ifndef APP_CONF_H+#define APP_CONF_H++#include "hw.h"+#include "hw_conf.h"+#include "hw_if.h"+#include "ble_bufsize.h"++/* ---- GAP ---- */+#define CFG_TX_POWER (0x18) /* -0.15 dBm */+#define CFG_ADV_BD_ADDRESS (0x7257acd87a6c) /* only used if the UDN and OTP are both blank */+#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 (0x30) /* 30 ms */+#define CFG_FAST_CONN_ADV_INTERVAL_MAX (0x60) /* 60 ms */+#define CFG_LP_CONN_ADV_INTERVAL_MIN (0x640) /* 1 s */+#define CFG_LP_CONN_ADV_INTERVAL_MAX (0xFA0) /* 2.5 s */++/* Just Works: no display or keyboard on the keyword, bond so the host+ * reconnects without asking again. */+#define CFG_BONDING_MODE (1)+#define CFG_ENCRYPTION_KEY_SIZE_MAX (16)+#define CFG_ENCRYPTION_KEY_SIZE_MIN (8)+#define CFG_IO_CAPABILITY IO_CAP_NO_INPUT_NO_OUTPUT+#define CFG_MITM_PROTECTION MITM_PROTECTION_NOT_REQUIRED+#define CFG_SC_SUPPORT (0x01) /* LE Secure Connections optional */+#define CFG_KEYPRESS_NOTIFICATION_SUPPORT (0x00)++/* Identity root / encryption root keys. ST's defaults: fine for a hobby+ * board, swap for per-device random ones before shipping many. */+#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}++/* SMPS stays in bypass. Turn on only if the SMPS inductor is fitted. */+#define CFG_USE_SMPS 0++/* ---- BLE stack (SHCI_C2_BLE_Init) ---- */+#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 (156)+#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+/* PeriphCommonClock_Config feeds RFWKP from HSE/1024, so the stack's sleep+ * clock has to match. Switch both to LSE if low power ever gets turned on. */+#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)++/* ---- transport layer ---- */+#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++/* Off: the keyword's main loop also bit-bangs SWIO and polls I2C3, which a+ * STOP2 entry from the sequencer idle would break. */+#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)+#define MS_TO_TS_TICKS(ms) ((uint32_t)((ms) * 1000UL / CFG_TS_TICK_VAL))++typedef enum+{+ CFG_TIM_PROC_ID_ISR,+} CFG_TimProcID_t;++#define CFG_HW_RESET_BY_FW 1+#define CFG_DEBUGGER_SUPPORTED 1++/* No debug UART on the keyword. */+#define APP_DBG_MSG PRINT_NO_MESG+#define CFG_DEBUG_TRACE_FULL 0+#define CFG_DEBUG_TRACE_LIGHT 0++/* ---- sequencer ---- */+typedef enum+{+ CFG_TASK_ADV_UPDATE_ID,+ CFG_TASK_KEYS_ID,+ CFG_TASK_NUS_RX_ID,+ CFG_TASK_HCI_ASYNCH_EVT_ID,+ CFG_LAST_TASK_ID_WITH_HCICMD, /* shall be last in this list */+} 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/Core/Inc/app_entry.h b/firmware/Core/Inc/app_entry.hnew file mode 100644index 0000000..f69e85c--- /dev/null+++ b/firmware/Core/Inc/app_entry.h@@ -0,0 +1,71 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file app_entry.h+ * @author MCD Application Team+ * @brief Interface to the application+ ******************************************************************************+ * @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 APP_ENTRY_H+#define APP_ENTRY_H++#ifdef __cplusplus+extern "C" {+#endif++/* Includes ------------------------------------------------------------------*/++/* Private includes ----------------------------------------------------------*/+/* USER CODE BEGIN Includes */++/* USER CODE END Includes */++/* Exported types ------------------------------------------------------------*/+/* USER CODE BEGIN ET */++/* USER CODE END ET */++/* Exported constants --------------------------------------------------------*/+/* USER CODE BEGIN EC */++/* USER CODE END EC */++/* Exported variables --------------------------------------------------------*/+/* USER CODE BEGIN EV */++/* USER CODE END EV */++/* Exported macros ------------------------------------------------------------*/+/* USER CODE BEGIN EM */++/* USER CODE END EM */++/* Exported functions ---------------------------------------------*/+void MX_APPE_Config(void);+void MX_APPE_Init(void);+void MX_APPE_Process(void);+void Init_Exti(void);+void Init_Smps(void);++/* USER CODE BEGIN EF */++/* USER CODE END EF */++#ifdef __cplusplus+} /* extern "C" */+#endif++#endif /* APP_ENTRY_H */diff --git a/firmware/Core/Inc/hw_conf.h b/firmware/Core/Inc/hw_conf.hnew file mode 100644index 0000000..33625e1--- /dev/null+++ b/firmware/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/Core/Inc/hw_if.h b/firmware/Core/Inc/hw_if.hnew file mode 100644index 0000000..778d936--- /dev/null+++ b/firmware/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/Core/Inc/keymap.h b/firmware/Core/Inc/keymap.hnew file mode 100644index 0000000..b06433b--- /dev/null+++ b/firmware/Core/Inc/keymap.h@@ -0,0 +1,33 @@+/*+ * Keymap: which HID modifiers and key each Keybit sends, keyed by the+ * Keybit's 96-bit UID. Lives in RAM, remapped over the config protocol,+ * saved to one flash page just below CPU2's secure area.+ *+ * A 5 ms sequencer task watches keybits[] from main.c, sends a HID report+ * whenever the set of held mapped keys changes, and emits the protocol's+ * KEY+/KEY-/PRESS/SIDES events.+ */+#ifndef KEYMAP_H+#define KEYMAP_H++#include <stdint.h>+#include "keybit_bus.h"++#define KEYMAP_MAX 32+#define UID_LEN 12++void KEYMAP_Init(void);++/* 0 on success, -1 when the table is full. key may be 0 (mods only). */+int KEYMAP_Set(const uint8_t uid[UID_LEN], uint8_t mods, uint8_t key);+/* 0/0 when unmapped. */+void KEYMAP_Get(const uint8_t uid[UID_LEN], uint8_t *mods, uint8_t *key);+void KEYMAP_Unmap(const uint8_t uid[UID_LEN]);+void KEYMAP_Clear(void);+/* 0 on success (also when flash already matched), -1 on a flash error. */+int KEYMAP_Save(void);++/* Keybits as of the last key task run, the same set the events describe. */+const keybit_info_t *KEYMAP_Present(int *count);++#endif /* KEYMAP_H */diff --git a/firmware/Core/Inc/proto.h b/firmware/Core/Inc/proto.hnew file mode 100644index 0000000..f6be818--- /dev/null+++ b/firmware/Core/Inc/proto.h@@ -0,0 +1,22 @@+/*+ * Line based config protocol (protocol 1) shared by every transport. See+ * app/PROTOCOL.md for the commands. Lines end in \n, \r\n is accepted.+ */+#ifndef PROTO_H+#define PROTO_H++#include <stdint.h>++#define KEYWORD_FW_VERSION "0.1.0"++/* Feed received bytes in any chunk size. */+void PROTO_Input(const uint8_t *data, uint16_t len);++/* Send one line (printf style, \n added). */+void PROTO_Send(const char *fmt, ...) __attribute__((format(printf, 1, 2)));++/* 96-bit little endian UID as 24 uppercase hex digits, most significant+ * byte first. out must hold 25 chars. */+void PROTO_FormatUid(char *out, const uint8_t uid[12]);++#endif /* PROTO_H */diff --git a/firmware/Core/Inc/stm32_lpm_if.h b/firmware/Core/Inc/stm32_lpm_if.hnew file mode 100644index 0000000..22ebf25--- /dev/null+++ b/firmware/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/Core/Inc/stm32wbxx_hal_conf.h b/firmware/Core/Inc/stm32wbxx_hal_conf.hindex ba34acb..e692cce 100644--- a/firmware/Core/Inc/stm32wbxx_hal_conf.h+++ b/firmware/Core/Inc/stm32wbxx_hal_conf.h@@ -38,7 +38,7 @@/*#define HAL_CRYP_MODULE_ENABLED *//*#define HAL_COMP_MODULE_ENABLED *//*#define HAL_CRC_MODULE_ENABLED */-/*#define HAL_HSEM_MODULE_ENABLED */+#define HAL_HSEM_MODULE_ENABLED#define HAL_I2C_MODULE_ENABLED/*#define HAL_IPCC_MODULE_ENABLED *//*#define HAL_IRDA_MODULE_ENABLED */@@ -49,7 +49,7 @@/*#define HAL_PKA_MODULE_ENABLED */#define HAL_QSPI_MODULE_ENABLED/*#define HAL_RNG_MODULE_ENABLED */-/*#define HAL_RTC_MODULE_ENABLED */+#define HAL_RTC_MODULE_ENABLED/*#define HAL_SAI_MODULE_ENABLED *//*#define HAL_SMBUS_MODULE_ENABLED *//*#define HAL_SMARTCARD_MODULE_ENABLED */diff --git a/firmware/Core/Inc/utilities_conf.h b/firmware/Core/Inc/utilities_conf.hnew file mode 100644index 0000000..b301820--- /dev/null+++ b/firmware/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/Core/Src/app_entry.c b/firmware/Core/Src/app_entry.cnew file mode 100644index 0000000..110e9c9--- /dev/null+++ b/firmware/Core/Src/app_entry.c@@ -0,0 +1,220 @@+/*+ * STM32_WPAN entry: CPU2 boot, transport layer, timer server and the+ * sequencer hook. Trimmed from ST's BLE_Hid app_entry.c (STM32CubeWB 1.24.0)+ * without the Nucleo LEDs, buttons and debug UART.+ *+ * main.c calls, all from USER CODE sections:+ * MX_APPE_Config() before SystemClock_Config (Init)+ * MX_APPE_Init() after the peripherals (RF_Init 2)+ * MX_APPE_Process() once per pass of the main loop (WHILE)+ */+#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"+#include "otp.h"++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_SysUserEvtRx(void *pPayload);+static void APPE_SysStatusNot(SHCI_TL_CmdStatus_t status);++/* Runs before SystemClock_Config: the backup domain reset has to happen+ * before the LSE is started, and the HSE trim before the HSE is. */+void MX_APPE_Config(void)+{+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);++#if (CFG_HW_RESET_BY_FW == 1)+ /* After a pin reset (not a software one) CPU2 may still be running with+ * stale IPCC state, so start both clean. */+ if (LL_RCC_IsActiveFlag_PINRST() && !LL_RCC_IsActiveFlag_SFTRST())+ {+ 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);+#endif++ OTP_ID0_t *p_otp = (OTP_ID0_t *)OTP_Read(0);+ if (p_otp)+ {+ LL_RCC_HSE_SetCapacitorTuning(p_otp->hse_tuning);+ }+}++/* The timer server runs off the RTC wakeup timer, clocked from the LSE. */+static void Init_Rtc(void)+{+ RCC_PeriphCLKInitTypeDef clk = {0};+ clk.PeriphClockSelection = RCC_PERIPHCLK_RTC;+ clk.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;+ if (HAL_RCCEx_PeriphCLKConfig(&clk) != HAL_OK)+ {+ Error_Handler();+ }+ __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;+ hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;+ hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;+ hrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;+ if (HAL_RTC_Init(&hrtc) != HAL_OK)+ {+ Error_Handler();+ }+ HAL_RTCEx_EnableBypassShadow(&hrtc);++ LL_RTC_DisableWriteProtection(RTC);+ LL_RTC_WAKEUP_SetClock(RTC, CFG_RTC_WUCKSEL_DIVIDER);+ LL_RTC_EnableWriteProtection(RTC);+}++void MX_APPE_Init(void)+{+ __HAL_RCC_HSEM_CLK_ENABLE();++#if (CFG_USE_SMPS != 0)+ LL_PWR_SMPS_SetStartupCurrent(LL_PWR_SMPS_STARTUP_CURRENT_80MA);+ LL_PWR_SMPS_SetOutputVoltageLevel(LL_PWR_SMPS_OUTPUT_VOLTAGE_1V40);+ LL_PWR_SMPS_Enable();+#endif+ /* IPCC and HSEM wake CPU1 up */+ LL_EXTI_EnableIT_32_63(LL_EXTI_LINE_36 | LL_EXTI_LINE_38);+ Init_Rtc();++ LL_RCC_SetClkAfterWakeFromStop(LL_RCC_STOP_WAKEUPCLOCK_HSI);+ UTIL_LPM_Init();+ /* CPU2 may drop to shutdown whenever it wants, CPU1 decides the real mode. */+ 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);++ /* Transport layer. CPU2 boots once TL_Enable() runs and answers with+ * SHCI_SUB_EVT_CODE_READY, which brings up the BLE app. */+ 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 MX_APPE_Process(void)+{+ UTIL_SEQ_Run(UTIL_SEQ_DEFAULT);+}++void UTIL_SEQ_Idle(void)+{+#if (CFG_LPM_SUPPORTED == 1)+ UTIL_LPM_EnterLowPower();+#endif+}++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_CONFIG_Cmd_Param_t config_param = {0};+ config_param.PayloadCmdSize = SHCI_C2_CONFIG_PAYLOAD_CMD_SIZE;+ config_param.EvtMask1 = SHCI_C2_CONFIG_EVTMASK1_BIT0_ERROR_NOTIF_ENABLE+ + SHCI_C2_CONFIG_EVTMASK1_BIT1_BLE_NVM_RAM_UPDATE_ENABLE;+ config_param.RevisionID = (uint16_t)LL_DBGMCU_GetRevisionID();+ config_param.DeviceID = (uint16_t)LL_DBGMCU_GetDeviceID();+ (void)SHCI_C2_Config(&config_param);++ APP_BLE_Init();+ UTIL_LPM_SetOffMode(1U << CFG_LPM_APP, UTIL_LPM_ENABLE);+ }+ else+ {+ /* FUS is running instead of the BLE stack: the stack binary is missing+ * or was never started. Keep the user event flow off, nothing to do. */+ ((tSHCI_UserEvtRxParam *)pPayload)->status = SHCI_TL_UserEventFlow_Disable;+ }+}++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);+}++/* These IRQs aren't enabled in keyword.ioc, so the handlers live here+ * rather than in the generated stm32wbxx_it.c. */+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/Core/Src/hw_timerserver.c b/firmware/Core/Src/hw_timerserver.cnew file mode 100644index 0000000..a895535--- /dev/null+++ b/firmware/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/Core/Src/keymap.c b/firmware/Core/Src/keymap.cnew file mode 100644index 0000000..8e3297a--- /dev/null+++ b/firmware/Core/Src/keymap.c@@ -0,0 +1,268 @@+#include "app_common.h"+#include "main.h"+#include "stm32_seq.h"+#include "shci.h"+#include "utilities_conf.h"+#include "hids_app.h"+#include "proto.h"+#include "keymap.h"++#define KEYS_PERIOD_MS 5+#define MAP_MAGIC 0x50414D4BUL /* "KMAP" */+#define MAP_VERSION 1++/* Owned by main.c's Keybit code, refreshed from its own poll calls in the+ * main loop. The key task runs from the same loop, so no locking. */+extern keybit_info_t keybits[KEYBIT_MAX];+extern int keybit_count;+extern volatile uint32_t keybit_changed;++typedef struct {+ uint8_t uid[UID_LEN];+ uint8_t mods;+ uint8_t key;+ uint8_t pad[2]; /* keeps an entry at two flash doublewords */+} map_entry_t;++/* Flash image: one header doubleword, then the entries. */+typedef struct {+ uint32_t magic;+ uint16_t version;+ uint16_t count;+ map_entry_t entries[KEYMAP_MAX];+} map_image_t;++static map_image_t map __attribute__((aligned(8)));+static keybit_info_t present[KEYBIT_MAX];+static int present_count;+static char sides[3]; /* last SIDES sent: L, R, T present */+static uint8_t keys_timer_id;++/* One page under SFSA (the first page CPU2 owns). With the v1.24 full+ * stack at 0x080D0000 that is page 0xCF at 0x080CF000. Reading SFSA keeps+ * it right if a different stack moves the boundary. */+static uint32_t Map_Page(void)+{+ return (FLASH->SFR & FLASH_SFR_SFSA) - 1;+}++static const map_image_t *Map_Flash(void)+{+ return (const map_image_t *)(FLASH_BASE + Map_Page() * FLASH_PAGE_SIZE);+}++static uint32_t Map_Size(const map_image_t *m)+{+ return 8 + m->count * sizeof(map_entry_t);+}++static int Find(const uint8_t uid[UID_LEN])+{+ for (int i = 0; i < map.count; i++)+ {+ if (memcmp(map.entries[i].uid, uid, UID_LEN) == 0) return i;+ }+ return -1;+}++int KEYMAP_Set(const uint8_t uid[UID_LEN], uint8_t mods, uint8_t key)+{+ int i = Find(uid);+ if (i < 0)+ {+ if (map.count >= KEYMAP_MAX) return -1;+ i = map.count++;+ memset(&map.entries[i], 0xFF, sizeof(map_entry_t));+ memcpy(map.entries[i].uid, uid, UID_LEN);+ }+ map.entries[i].mods = mods;+ map.entries[i].key = key;+ return 0;+}++void KEYMAP_Get(const uint8_t uid[UID_LEN], uint8_t *mods, uint8_t *key)+{+ int i = Find(uid);+ *mods = i < 0 ? 0 : map.entries[i].mods;+ *key = i < 0 ? 0 : map.entries[i].key;+}++void KEYMAP_Unmap(const uint8_t uid[UID_LEN])+{+ int i = Find(uid);+ if (i < 0) return;+ map.entries[i] = map.entries[--map.count];+}++void KEYMAP_Clear(void)+{+ map.count = 0;+}++const keybit_info_t *KEYMAP_Present(int *count)+{+ *count = present_count;+ return present;+}++/* One erase or program, done when neither CPU is blocking flash access:+ * ST's sequence from BLE_RfWithFlash's flash_driver.c. CPU2 was told to+ * use semaphore 7 in APP_BLE_Init. Returns 0 when it ran. */+static int Flash_Op(uint8_t erase, uint32_t addr_or_page, uint64_t data)+{+ for (int tries = 0; tries < 1000; tries++)+ {+ int done = 0;+ while (LL_FLASH_IsActiveFlag_OperationSuspended());+ UTILS_ENTER_CRITICAL_SECTION();+ if (!LL_HSEM_GetStatus(HSEM, CFG_HW_BLOCK_FLASH_REQ_BY_CPU1_SEMID)+ && LL_HSEM_1StepLock(HSEM, CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID) == 0)+ {+ if (erase)+ {+ FLASH_EraseInitTypeDef e = {.TypeErase = FLASH_TYPEERASE_PAGES, .Page = addr_or_page, .NbPages = 1};+ uint32_t page_error;+ HAL_FLASHEx_Erase(&e, &page_error);+ }+ else+ {+ HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, addr_or_page, data);+ }+ LL_HSEM_ReleaseLock(HSEM, CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID, 0);+ done = 1;+ }+ UTILS_EXIT_CRITICAL_SECTION();+ if (done)+ {+ while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_CFGBSY));+ return 0;+ }+ HAL_Delay(1); /* CPU2 is in a radio event, try again */+ }+ return -1;+}++int KEYMAP_Save(void)+{+ map.magic = MAP_MAGIC;+ map.version = MAP_VERSION;+ uint32_t size = Map_Size(&map);+ if (memcmp(Map_Flash(), &map, size) == 0) return 0; /* nothing changed */++ int err = 0;+ while (LL_HSEM_1StepLock(HSEM, CFG_HW_FLASH_SEMID));+ HAL_FLASH_Unlock();+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);++ SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_ON);+ err |= Flash_Op(1, Map_Page(), 0);+ SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_OFF);++ uint32_t addr = (uint32_t)Map_Flash();+ const uint64_t *src = (const uint64_t *)↦+ for (uint32_t i = 0; i < size / 8 && !err; i++)+ {+ err |= Flash_Op(0, addr + 8 * i, src[i]);+ }++ HAL_FLASH_Lock();+ LL_HSEM_ReleaseLock(HSEM, CFG_HW_FLASH_SEMID, 0);+ if (err || memcmp(Map_Flash(), &map, size) != 0) return -1;+ return 0;+}++static void Map_Load(void)+{+ const map_image_t *f = Map_Flash();+ if (f->magic == MAP_MAGIC && f->version == MAP_VERSION && f->count <= KEYMAP_MAX)+ {+ memcpy(&map, f, Map_Size(f));+ }+ else+ {+ map.count = 0;+ }+}++static const keybit_info_t *Find_Keybit(const keybit_info_t *list, int n, const uint8_t uid[UID_LEN])+{+ for (int i = 0; i < n; i++)+ {+ if (memcmp(list[i].uid, uid, UID_LEN) == 0) return &list[i];+ }+ return NULL;+}++/* Diff keybits[] against what we reported last time, by UID: indexes move+ * every time main.c rescans the bus. */+static void Keys_Task(void)+{+ char uid[UID_LEN * 2 + 1];+ keybit_changed = 0; /* only main-loop code sets it, no ISR */++ for (int i = 0; i < present_count; i++)+ {+ if (!Find_Keybit(keybits, keybit_count, present[i].uid))+ {+ PROTO_FormatUid(uid, present[i].uid);+ PROTO_Send("KEY- uid=%s", uid);+ }+ }+ for (int i = 0; i < keybit_count; i++)+ {+ const keybit_info_t *old = Find_Keybit(present, present_count, keybits[i].uid);+ PROTO_FormatUid(uid, keybits[i].uid);+ if (!old) PROTO_Send("KEY+ uid=%s at=%c", uid, keybits[i].at);+ if ((old ? old->key_down : 0) != keybits[i].key_down)+ {+ PROTO_Send("PRESS uid=%s down=%d", uid, keybits[i].key_down);+ }+ }++ present_count = keybit_count;+ memcpy(present, keybits, sizeof(keybit_info_t) * keybit_count);++ char now[3] = {0, 0, 0};+ for (int i = 0; i < present_count; i++)+ {+ if (present[i].at == 'L') now[0] = 1;+ if (present[i].at == 'R') now[1] = 1;+ if (present[i].at == 'T') now[2] = 1;+ }+ if (memcmp(now, sides, sizeof(sides)) != 0)+ {+ memcpy(sides, now, sizeof(sides));+ PROTO_Send("SIDES L=%d R=%d T=%d", sides[0], sides[1], sides[2]);+ }++ /* 6KRO: modifiers OR together, the first six keys fill the slots and a+ * seventh turns every slot into ErrorRollOver as HID asks. */+ uint8_t report[8] = {0};+ int slots = 0;+ for (int i = 0; i < present_count; i++)+ {+ if (!present[i].key_down) continue;+ int m = Find(present[i].uid);+ if (m < 0) continue; /* unmapped Keybits send nothing */+ report[0] |= map.entries[m].mods;+ uint8_t key = map.entries[m].key;+ if (!key) continue;+ if (slots < 6) report[2 + slots] = key;+ else memset(&report[2], 0x01, 6);+ slots++;+ }+ HIDSAPP_SendKeyboard(report);+}++static void Keys_Tick(void)+{+ UTIL_SEQ_SetTask(1 << CFG_TASK_KEYS_ID, CFG_SCH_PRIO_0);+}++void KEYMAP_Init(void)+{+ Map_Load();+ UTIL_SEQ_RegTask(1 << CFG_TASK_KEYS_ID, UTIL_SEQ_RFU, Keys_Task);+ HW_TS_Create(CFG_TIM_PROC_ID_ISR, &keys_timer_id, hw_ts_Repeated, Keys_Tick);+ HW_TS_Start(keys_timer_id, MS_TO_TS_TICKS(KEYS_PERIOD_MS));+}diff --git a/firmware/Core/Src/main.c b/firmware/Core/Src/main.cindex a770432..2c7675f 100644--- a/firmware/Core/Src/main.c+++ b/firmware/Core/Src/main.c@@ -21,6 +21,7 @@/* Private includes ----------------------------------------------------------*//* USER CODE BEGIN Includes */+#include "app_entry.h"/* USER CODE END Includes */@@ -93,7 +94,7 @@ int main(void)HAL_Init();/* USER CODE BEGIN Init */-+ MX_APPE_Config(); /* STM32_WPAN: IPCC/backup reset and HSE trim, before the clocks start *//* USER CODE END Init *//* Configure the system clock */@@ -127,6 +128,7 @@ int main(void)/* USER CODE BEGIN WHILE */while (1){+ MX_APPE_Process(); /* STM32_WPAN sequencer: BLE events, keymap, NUS *//* USER CODE END WHILE *//* USER CODE BEGIN 3 */@@ -322,7 +324,7 @@ static void MX_RF_Init(void)/* USER CODE END RF_Init 1 *//* USER CODE BEGIN RF_Init 2 */-+ MX_APPE_Init(); /* STM32_WPAN: RTC timer server, transport layer, boots CPU2 *//* USER CODE END RF_Init 2 */}diff --git a/firmware/Core/Src/proto.c b/firmware/Core/Src/proto.cnew file mode 100644index 0000000..e06b9be--- /dev/null+++ b/firmware/Core/Src/proto.c@@ -0,0 +1,193 @@+#include <stdarg.h>+#include <stdio.h>+#include <string.h>+#include "keymap.h"+#include "nus.h"+#include "proto.h"++#define LINE_MAX 128++static char line[LINE_MAX];+static uint16_t line_len;+static uint8_t line_overflow;++void PROTO_Send(const char *fmt, ...)+{+ char out[LINE_MAX];+ va_list ap;+ va_start(ap, fmt);+ int n = vsnprintf(out, sizeof(out) - 1, fmt, ap);+ va_end(ap);+ if (n < 0) return;+ if (n > (int)sizeof(out) - 2) n = sizeof(out) - 2;+ out[n++] = '\n';+ NUS_Write(out, (uint16_t)n); /* add USB CDC here once there is one */+}++void PROTO_FormatUid(char *out, const uint8_t uid[UID_LEN])+{+ static const char hex[] = "0123456789ABCDEF";+ for (int i = 0; i < UID_LEN; i++)+ {+ uint8_t b = uid[UID_LEN - 1 - i];+ out[2 * i] = hex[b >> 4];+ out[2 * i + 1] = hex[b & 0xF];+ }+ out[2 * UID_LEN] = 0;+}++static int Hex_Digit(char c)+{+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ return -1;+}++/* Finds "name=" in args and parses exactly digits hex chars after it into+ * out, most significant first. Returns 0 on success. */+static int Arg_Hex(const char *args, const char *name, int digits, uint8_t *out)+{+ size_t nl = strlen(name);+ for (const char *p = args; (p = strstr(p, name)) != NULL; p += nl)+ {+ if ((p != args && p[-1] != ' ') || p[nl] != '=') continue;+ const char *v = p + nl + 1;+ for (int i = 0; i < digits; i++)+ {+ if (Hex_Digit(v[i]) < 0) return -1;+ }+ if (v[digits] != 0 && v[digits] != ' ') return -1;+ for (int i = 0; i < digits / 2; i++)+ {+ out[i] = (uint8_t)(Hex_Digit(v[2 * i]) << 4 | Hex_Digit(v[2 * i + 1]));+ }+ return 0;+ }+ return -1;+}++/* uid= is printed most significant byte first, stored little endian. */+static int Arg_Uid(const char *args, uint8_t uid[UID_LEN])+{+ uint8_t be[UID_LEN];+ if (Arg_Hex(args, "uid", UID_LEN * 2, be) != 0) return -1;+ for (int i = 0; i < UID_LEN; i++) uid[i] = be[UID_LEN - 1 - i];+ return 0;+}++static void Handle_Line(char *cmd)+{+ char uid_s[UID_LEN * 2 + 1];+ uint8_t uid[UID_LEN];+ char *args = strchr(cmd, ' ');+ if (args) *args++ = 0;+ else args = cmd + strlen(cmd);++ if (strcmp(cmd, "HELLO") == 0)+ {+ PROTO_Send("KEYWORD v=%s proto=1", KEYWORD_FW_VERSION);+ }+ else if (strcmp(cmd, "SIDES?") == 0)+ {+ int n;+ const keybit_info_t *k = KEYMAP_Present(&n);+ int l = 0, r = 0, t = 0;+ for (int i = 0; i < n; i++)+ {+ l |= k[i].at == 'L';+ r |= k[i].at == 'R';+ t |= k[i].at == 'T';+ }+ PROTO_Send("SIDES L=%d R=%d T=%d", l, r, t);+ }+ else if (strcmp(cmd, "KEYS?") == 0)+ {+ int n;+ const keybit_info_t *k = KEYMAP_Present(&n);+ for (int i = 0; i < n; i++)+ {+ PROTO_FormatUid(uid_s, k[i].uid);+ PROTO_Send("KEY+ uid=%s at=%c", uid_s, k[i].at);+ }+ PROTO_Send("KEYS END");+ }+ else if (strcmp(cmd, "MAP") == 0)+ {+ uint8_t mods, key;+ if (Arg_Uid(args, uid) || Arg_Hex(args, "mods", 2, &mods) || Arg_Hex(args, "key", 2, &key))+ {+ PROTO_Send("ERR usage: MAP uid=<24hex> mods=<2hex> key=<2hex>");+ return;+ }+ if (KEYMAP_Set(uid, mods, key) != 0)+ {+ PROTO_Send("ERR keymap full");+ return;+ }+ PROTO_FormatUid(uid_s, uid);+ PROTO_Send("OK MAP uid=%s", uid_s);+ }+ else if (strcmp(cmd, "MAP?") == 0)+ {+ uint8_t mods, key;+ if (Arg_Uid(args, uid))+ {+ PROTO_Send("ERR usage: MAP? uid=<24hex>");+ return;+ }+ KEYMAP_Get(uid, &mods, &key);+ PROTO_FormatUid(uid_s, uid);+ PROTO_Send("MAP uid=%s mods=%02X key=%02X", uid_s, mods, key);+ }+ else if (strcmp(cmd, "UNMAP") == 0)+ {+ if (Arg_Uid(args, uid))+ {+ PROTO_Send("ERR usage: UNMAP uid=<24hex>");+ return;+ }+ KEYMAP_Unmap(uid);+ PROTO_FormatUid(uid_s, uid);+ PROTO_Send("OK UNMAP uid=%s", uid_s);+ }+ else if (strcmp(cmd, "CLEAR") == 0)+ {+ KEYMAP_Clear();+ PROTO_Send("OK CLEAR");+ }+ else if (strcmp(cmd, "SAVE") == 0)+ {+ if (KEYMAP_Save() != 0) PROTO_Send("ERR flash write failed");+ else PROTO_Send("OK SAVE");+ }+ else+ {+ PROTO_Send("ERR unknown command");+ }+}++void PROTO_Input(const uint8_t *data, uint16_t len)+{+ for (uint16_t i = 0; i < len; i++)+ {+ char c = (char)data[i];+ if (c == '\n')+ {+ if (line_len && line[line_len - 1] == '\r') line_len--;+ line[line_len] = 0;+ if (line_overflow) PROTO_Send("ERR line too long");+ else if (line_len) Handle_Line(line);+ line_len = 0;+ line_overflow = 0;+ }+ else if (line_len < LINE_MAX - 1)+ {+ line[line_len++] = c;+ }+ else+ {+ line_overflow = 1;+ }+ }+}diff --git a/firmware/Core/Src/stm32_lpm_if.c b/firmware/Core/Src/stm32_lpm_if.cnew file mode 100644index 0000000..fe9b2f2--- /dev/null+++ b/firmware/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/STM32-for-VSCode.config.yaml b/firmware/STM32-for-VSCode.config.yamlindex c5b2295..10c8c20 100644--- a/firmware/STM32-for-VSCode.config.yaml+++ b/firmware/STM32-for-VSCode.config.yaml@@ -80,6 +80,20 @@ includeDirectories:- Src/**- Core/Src/**- Core/Lib/**+ - STM32_WPAN/App+ - Middlewares/ST/STM32_WPAN+ - Middlewares/ST/STM32_WPAN/ble+ - Middlewares/ST/STM32_WPAN/ble/core+ - Middlewares/ST/STM32_WPAN/ble/core/auto+ - Middlewares/ST/STM32_WPAN/ble/core/template+ - Middlewares/ST/STM32_WPAN/ble/svc/Inc+ - Middlewares/ST/STM32_WPAN/ble/svc/Src+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/shci+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl+ - Middlewares/ST/STM32_WPAN/utilities+ - Utilities/lpm/tiny_lpm+ - Utilities/sequencer# Files that should be included in the compilation.@@ -91,6 +105,30 @@ sourceFiles:- Src/**- Core/Src/**- Core/Lib/**+ - STM32_WPAN/**+ - Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rtc.c+ - Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rtc_ex.c+ - Middlewares/ST/STM32_WPAN/ble/core/auto/ble_gap_aci.c+ - Middlewares/ST/STM32_WPAN/ble/core/auto/ble_gatt_aci.c+ - Middlewares/ST/STM32_WPAN/ble/core/auto/ble_hal_aci.c+ - Middlewares/ST/STM32_WPAN/ble/core/auto/ble_hci_le.c+ - Middlewares/ST/STM32_WPAN/ble/core/auto/ble_l2cap_aci.c+ - Middlewares/ST/STM32_WPAN/ble/core/template/osal.c+ - Middlewares/ST/STM32_WPAN/ble/svc/Src/bas.c+ - Middlewares/ST/STM32_WPAN/ble/svc/Src/dis.c+ - Middlewares/ST/STM32_WPAN/ble/svc/Src/hids.c+ - Middlewares/ST/STM32_WPAN/ble/svc/Src/svc_ctl.c+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/shci/shci.c+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/hci_tl.c+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/hci_tl_if.c+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/shci_tl.c+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/shci_tl_if.c+ - Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/tl_mbox.c+ - Middlewares/ST/STM32_WPAN/utilities/otp.c+ - Middlewares/ST/STM32_WPAN/utilities/stm_list.c+ - Middlewares/ST/STM32_WPAN/utilities/stm_queue.c+ - Utilities/lpm/tiny_lpm/stm32_lpm.c+ - Utilities/sequencer/stm32_seq.c# When no makefile is present it will show a warning pop-up.diff --git a/firmware/STM32Make.make b/firmware/STM32Make.makeindex 0842290..35dc2aa 100644--- a/firmware/STM32Make.make+++ b/firmware/STM32Make.make@@ -100,7 +100,39 @@ Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_qspi.c \Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rcc.c \Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rcc_ex.c \Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_ll_rcc.c \-Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_ll_usb.c+Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_ll_usb.c \+Core/Src/app_entry.c \+Core/Src/hw_timerserver.c \+Core/Src/keymap.c \+Core/Src/proto.c \+Core/Src/stm32_lpm_if.c \+Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rtc.c \+Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rtc_ex.c \+Middlewares/ST/STM32_WPAN/ble/core/auto/ble_gap_aci.c \+Middlewares/ST/STM32_WPAN/ble/core/auto/ble_gatt_aci.c \+Middlewares/ST/STM32_WPAN/ble/core/auto/ble_hal_aci.c \+Middlewares/ST/STM32_WPAN/ble/core/auto/ble_hci_le.c \+Middlewares/ST/STM32_WPAN/ble/core/auto/ble_l2cap_aci.c \+Middlewares/ST/STM32_WPAN/ble/core/template/osal.c \+Middlewares/ST/STM32_WPAN/ble/svc/Src/bas.c \+Middlewares/ST/STM32_WPAN/ble/svc/Src/dis.c \+Middlewares/ST/STM32_WPAN/ble/svc/Src/hids.c \+Middlewares/ST/STM32_WPAN/ble/svc/Src/svc_ctl.c \+Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/shci/shci.c \+Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/hci_tl.c \+Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/hci_tl_if.c \+Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/shci_tl.c \+Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/shci_tl_if.c \+Middlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl/tl_mbox.c \+Middlewares/ST/STM32_WPAN/utilities/otp.c \+Middlewares/ST/STM32_WPAN/utilities/stm_list.c \+Middlewares/ST/STM32_WPAN/utilities/stm_queue.c \+STM32_WPAN/App/app_ble.c \+STM32_WPAN/App/hids_app.c \+STM32_WPAN/App/nus.c \+STM32_WPAN/Target/hw_ipcc.c \+Utilities/lpm/tiny_lpm/stm32_lpm.c \+Utilities/sequencer/stm32_seq.cCXX_SOURCES = \@@ -197,7 +229,21 @@ C_INCLUDES = \-IDrivers/CMSIS/Device/ST/STM32WBxx/Include \-IDrivers/CMSIS/Include \-IDrivers/STM32WBxx_HAL_Driver/Inc \--IDrivers/STM32WBxx_HAL_Driver/Inc/Legacy+-IDrivers/STM32WBxx_HAL_Driver/Inc/Legacy \+-IMiddlewares/ST/STM32_WPAN \+-IMiddlewares/ST/STM32_WPAN/ble \+-IMiddlewares/ST/STM32_WPAN/ble/core \+-IMiddlewares/ST/STM32_WPAN/ble/core/auto \+-IMiddlewares/ST/STM32_WPAN/ble/core/template \+-IMiddlewares/ST/STM32_WPAN/ble/svc/Inc \+-IMiddlewares/ST/STM32_WPAN/ble/svc/Src \+-IMiddlewares/ST/STM32_WPAN/interface/patterns/ble_thread \+-IMiddlewares/ST/STM32_WPAN/interface/patterns/ble_thread/shci \+-IMiddlewares/ST/STM32_WPAN/interface/patterns/ble_thread/tl \+-IMiddlewares/ST/STM32_WPAN/utilities \+-ISTM32_WPAN/App \+-IUtilities/lpm/tiny_lpm \+-IUtilities/sequencerdiff --git a/firmware/STM32_WPAN/App/app_ble.c b/firmware/STM32_WPAN/App/app_ble.cnew file mode 100644index 0000000..94220ff--- /dev/null+++ b/firmware/STM32_WPAN/App/app_ble.c@@ -0,0 +1,332 @@+/*+ * BLE app for the keyword, based on ST's BLE_Hid app_ble.c (STM32CubeWB+ * 1.24.0). GAP peripheral named "Keyword" with the HID keyboard+ * appearance, Just Works pairing with bonding, and the services in+ * SVCCTL_SvcInit below.+ */+#include "main.h"+#include "app_common.h"+#include "ble.h"+#include "tl.h"+#include "app_ble.h"+#include "hids_app.h"+#include "nus.h"+#include "keymap.h"+#include "proto.h"+#include "stm32_seq.h"+#include "shci.h"+#include "otp.h"+#include "stm32_lpm.h"++#define DEVICE_NAME "Keyword"+#define MANUFACTURER "keybytes"++#define FAST_ADV_TIMEOUT (30 * 1000 * 1000 / CFG_TS_TICK_VAL) /* 30 s, then slow adv */++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 = APP_BLE_NO_CONN;+static uint8_t adv_timer_id;+static uint8_t a_BdAddr[6];++/* Scan response would need an extra round trip, so it all goes in the+ * advertising packet: flags (added by the stack) + name + services ++ * appearance = 22 of 31 bytes. NUS's 128-bit UUID doesn't fit; the+ * desktop app finds the keyword by its name. */+static const uint8_t a_LocalName[] = {AD_TYPE_COMPLETE_LOCAL_NAME, 'K', 'e', 'y', 'w', 'o', 'r', 'd'};+static const uint8_t a_ServUuids[] = {AD_TYPE_16_BIT_SERV_UUID,+ (uint8_t)HUMAN_INTERFACE_DEVICE_SERVICE_UUID, (uint8_t)(HUMAN_INTERFACE_DEVICE_SERVICE_UUID >> 8),+ (uint8_t)BATTERY_SERVICE_UUID, (uint8_t)(BATTERY_SERVICE_UUID >> 8)};+static const uint8_t a_Appearance[] = {3, AD_TYPE_APPEARANCE,+ (uint8_t)BLE_CFG_GAP_APPEARANCE, (uint8_t)(BLE_CFG_GAP_APPEARANCE >> 8)};++static void BLE_UserEvtRx(void *p_Payload);+static void BLE_StatusNot(HCI_TL_CmdStatus_t Status);+static void Gap_Gatt_Init(void);+static void Adv_Start(uint8_t fast);++uint16_t APP_BLE_ConnHandle(void)+{+ return conn_handle;+}++static void Adv_Slow(void)+{+ if (conn_handle == APP_BLE_NO_CONN) Adv_Start(0);+}++static void Adv_Timeout(void)+{+ UTIL_SEQ_SetTask(1 << CFG_TASK_ADV_UPDATE_ID, CFG_SCH_PRIO_0);+}++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();+ }++ /* Keymap SAVE writes flash while CPU2 is running: make CPU2 use+ * semaphore 7 to guard its radio timing instead of the PES bit. */+ SHCI_C2_SetFlashActivityControl(FLASH_ACTIVITY_CONTROL_SEM7);++ Gap_Gatt_Init();+ SVCCTL_Init();++ UTIL_SEQ_RegTask(1 << CFG_TASK_ADV_UPDATE_ID, UTIL_SEQ_RFU, Adv_Slow);+ HW_TS_Create(CFG_TIM_PROC_ID_ISR, &adv_timer_id, hw_ts_SingleShot, Adv_Timeout);++ DIS_Data_t dis;+ dis.pPayload = (uint8_t *)MANUFACTURER;+ dis.Length = sizeof(MANUFACTURER) - 1;+ DIS_UpdateChar(MANUFACTURER_NAME_UUID, &dis);+ dis.pPayload = (uint8_t *)DEVICE_NAME;+ dis.Length = sizeof(DEVICE_NAME) - 1;+ DIS_UpdateChar(MODEL_NUMBER_UUID, &dis);+ dis.pPayload = (uint8_t *)KEYWORD_FW_VERSION;+ dis.Length = sizeof(KEYWORD_FW_VERSION) - 1;+ DIS_UpdateChar(FIRMWARE_REVISION_UUID, &dis);++ /* ponytail: fixed 100 %, the board has no battery gauge wired to the MCU yet */+ uint8_t level = 100;+ BAS_Update_Char(BATTERY_LEVEL_CHAR_UUID, 0, &level);++ HIDSAPP_Init();+ KEYMAP_Init();++ Adv_Start(1);+}++/* Only the services the keyword uses (the weak default inits every service+ * in the middleware). */+void SVCCTL_SvcInit(void)+{+ DIS_Init();+ BAS_Init();+ HIDS_Init();+ NUS_Init();+}++void BAS_Notification(BAS_Notification_evt_t *pNotification)+{+ UNUSED(pNotification);+}++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:+ conn_handle = APP_BLE_NO_CONN;+ HIDSAPP_Disconnected();+ NUS_Disconnected();+ Adv_Start(1);+ break;++ case HCI_LE_META_EVT_CODE:+ {+ evt_le_meta_event *p_meta_evt = (evt_le_meta_event *)p_event_pckt->data;+ uint16_t handle = APP_BLE_NO_CONN;+ if (p_meta_evt->subevent == HCI_LE_CONNECTION_COMPLETE_SUBEVT_CODE)+ {+ 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)+ {+ handle = ((hci_le_enhanced_connection_complete_event_rp0 *)p_meta_evt->data)->Connection_Handle;+ }+ if (handle != APP_BLE_NO_CONN)+ {+ HW_TS_Stop(adv_timer_id);+ conn_handle = handle;+ /* Ask the host to pair (or re-encrypt with the bond) right away+ * instead of waiting for it to hit an encrypted attribute. */+ aci_gap_peripheral_security_req(conn_handle);+ }+ break;+ }++ case HCI_VENDOR_SPECIFIC_DEBUG_EVT_CODE:+ {+ evt_blecore_aci *p_blecore_evt = (evt_blecore_aci *)p_event_pckt->data;+ switch (p_blecore_evt->ecode)+ {+ case ACI_GAP_BOND_LOST_VSEVT_CODE:+ /* The host forgot us but we still hold its old bond: let it pair again. */+ aci_gap_allow_rebond(conn_handle);+ break;++ case ACI_GATT_INDICATION_VSEVT_CODE:+ aci_gatt_confirm_indication(((aci_gatt_indication_event_rp0 *)p_blecore_evt->data)->Connection_Handle);+ break;++ default:+ break;+ }+ break;+ }++ default:+ break;+ }+ return SVCCTL_UserEvtFlowEnable;+}++/* Public address from the chip's unique ID (same as ST's examples). */+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 Gap_Gatt_Init(void)+{+ uint16_t gap_service_handle, gap_dev_name_char_handle, gap_appearance_char_handle;+ uint16_t appearance = BLE_CFG_GAP_APPEARANCE;++ hci_reset();+ aci_hal_write_config_data(CONFIG_DATA_PUBLIC_ADDRESS_OFFSET, CONFIG_DATA_PUBLIC_ADDRESS_LEN, (uint8_t *)BleGetBdAddress());+ 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(DEVICE_NAME) - 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(DEVICE_NAME) - 1, (uint8_t *)DEVICE_NAME);+ aci_gatt_update_char_value(gap_service_handle, gap_appearance_char_handle, 0, 2, (uint8_t *)&appearance);++ aci_gap_set_io_capability(CFG_IO_CAPABILITY);+ aci_gap_set_authentication_requirement(CFG_BONDING_MODE,+ CFG_MITM_PROTECTION,+ CFG_SC_SUPPORT,+ CFG_KEYPRESS_NOTIFICATION_SUPPORT,+ CFG_ENCRYPTION_KEY_SIZE_MIN,+ CFG_ENCRYPTION_KEY_SIZE_MAX,+ USE_FIXED_PIN_FOR_PAIRING_FORBIDDEN,+ 0,+ CFG_IDENTITY_ADDRESS);+ aci_gap_configure_filter_accept_list();+}++static void Adv_Start(uint8_t fast)+{+ HW_TS_Stop(adv_timer_id);+ aci_gap_set_non_discoverable();+ aci_gap_set_discoverable(ADV_IND,+ fast ? CFG_FAST_CONN_ADV_INTERVAL_MIN : CFG_LP_CONN_ADV_INTERVAL_MIN,+ fast ? CFG_FAST_CONN_ADV_INTERVAL_MAX : CFG_LP_CONN_ADV_INTERVAL_MAX,+ CFG_BLE_ADDRESS_TYPE,+ NO_WHITE_LIST_USE,+ sizeof(a_LocalName), a_LocalName,+ sizeof(a_ServUuids), (uint8_t *)a_ServUuids,+ 0, 0);+ aci_gap_update_adv_data(sizeof(a_Appearance), a_Appearance);+ if (fast) HW_TS_Start(adv_timer_id, FAST_ADV_TIMEOUT);+}++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;+ if (SVCCTL_UserEvtRx((void *)&(p_param->pckt->evtserial)) != SVCCTL_UserEvtFlowDisable)+ {+ p_param->status = HCI_TL_UserEventFlow_Enable;+ }+ else+ {+ p_param->status = 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/STM32_WPAN/App/app_ble.h b/firmware/STM32_WPAN/App/app_ble.hnew file mode 100644index 0000000..7351160--- /dev/null+++ b/firmware/STM32_WPAN/App/app_ble.h@@ -0,0 +1,18 @@+/*+ * The keyword's BLE app: one peripheral link carrying HID (keyboard ++ * consumer), Battery, Device Information and the NUS config channel.+ */+#ifndef APP_BLE_H+#define APP_BLE_H++#include <stdint.h>+#include "hci_tl.h"++#define APP_BLE_NO_CONN 0xFFFF++void APP_BLE_Init(void);++/* Handle of the current link, APP_BLE_NO_CONN when nobody is connected. */+uint16_t APP_BLE_ConnHandle(void);++#endif /* APP_BLE_H */diff --git a/firmware/STM32_WPAN/App/ble_conf.h b/firmware/STM32_WPAN/App/ble_conf.hnew file mode 100644index 0000000..edd8a74--- /dev/null+++ b/firmware/STM32_WPAN/App/ble_conf.h@@ -0,0 +1,130 @@+/* USER CODE BEGIN Header */+/**+ ******************************************************************************+ * @file ble_conf.h+ * @author MCD Application Team+ * @brief 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_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++/******************************************************************************+ * Device Information Service (DIS)+ ******************************************************************************/+/**< Options: Supported(1) or Not Supported(0) */+#define BLE_CFG_DIS_MANUFACTURER_NAME_STRING 1+#define BLE_CFG_DIS_MODEL_NUMBER_STRING 1+#define BLE_CFG_DIS_SERIAL_NUMBER_STRING 0+#define BLE_CFG_DIS_HARDWARE_REVISION_STRING 0+#define BLE_CFG_DIS_FIRMWARE_REVISION_STRING 1+#define BLE_CFG_DIS_SOFTWARE_REVISION_STRING 0+#define BLE_CFG_DIS_SYSTEM_ID 0+#define BLE_CFG_DIS_IEEE_CERTIFICATION 0+#define BLE_CFG_DIS_PNP_ID 0++/**+ * device information service characteristic lengths+ */+#define BLE_CFG_DIS_SYSTEM_ID_LEN_MAX (8)+#define BLE_CFG_DIS_MODEL_NUMBER_STRING_LEN_MAX (32)+#define BLE_CFG_DIS_SERIAL_NUMBER_STRING_LEN_MAX (32)+#define BLE_CFG_DIS_FIRMWARE_REVISION_STRING_LEN_MAX (32)+#define BLE_CFG_DIS_HARDWARE_REVISION_STRING_LEN_MAX (32)+#define BLE_CFG_DIS_SOFTWARE_REVISION_STRING_LEN_MAX (32)+#define BLE_CFG_DIS_MANUFACTURER_NAME_STRING_LEN_MAX (32)+#define BLE_CFG_DIS_IEEE_CERTIFICATION_LEN_MAX (32)+#define BLE_CFG_DIS_PNP_ID_LEN_MAX (7)++/******************************************************************************+ * Battery Service (BAS)+ ******************************************************************************/+#define BLE_CFG_BAS_NUMBER 1+#define BLE_CFG_BAS_LEVEL_NOT_PROP 1 /**< Battery Level characteristic Notification property*/+++/******************************************************************************+ * Human Interface Device Service (HIDS)+ ******************************************************************************/+#define BLE_CFG_HIDS_NUMBER 1+#define BLE_CFG_HIDS_REPORT_MAP_MAX_LEN 128+#define BLE_CFG_HIDS_REPORT_REFERENCE_LEN 2+#define BLE_CFG_HIDS_REPORT_MAX_LEN 8+#define BLE_CFG_HIDS_EXTERNAL_REPORT_REFERENCE_LEN 2+#define BLE_CFG_HIDS_BOOT_KEYBOARD_INPUT_REPORT_MAX_LEN 80+#define BLE_CFG_HIDS_BOOT_KEYBOARD_OUTPUT_REPORT_MAX_LEN 80+#define BLE_CFG_HIDS_BOOT_MOUSE_INPUT_REPORT_MAX_LEN 80+#define BLE_CFG_HIDS_INFORMATION_LEN 4+#define BLE_CFG_HIDS_CONTROL_POINT_LEN 1+#define BLE_CFG_HIDS_PROTOCOL_MODE_LEN 1++#define BLE_CFG_HIDS_PROTOCOL_MODE_CHAR 0 /**< Support of Protocol Mode Characteristic */+#define BLE_CFG_HIDS_INPUT_REPORT_NB 2 /**< Number of Input Report */+#define BLE_CFG_HIDS_INPUT_WRITE 0 /**< Support of Input Write property */+#define BLE_CFG_HIDS_OUTPUT_REPORT_NB 0 /**< Number of Output Report */+#define BLE_CFG_HIDS_FEATURE_REPORT_NB 0 /**< Number of Feature Report */+#define BLE_CFG_HIDS_EXTERNAL_REPORT_REFERENCE 0 /**< Support of EXTERNAL REPORT Reference Descriptor */+#define BLE_CFG_HIDS_KEYBOARD_DEVICE 0 /**< Support of BOOT KEYBOARD Report Characteristic */+#define BLE_CFG_HIDS_KEYBOARD_INPUT_WRITE 0 /**< Support of Keyboard Input Write property */+#define BLE_CFG_HIDS_MOUSE_DEVICE 0 /**< Support of BOOT MOUSE Report Characteristic */+#define BLE_CFG_HIDS_MOUSE_INPUT_WRITE 0 /**< Support of Mouse Input Write property */+#define BLE_CFG_HIDS_REPORT_CHAR BLE_CFG_HIDS_INPUT_REPORT_NB +\+ BLE_CFG_HIDS_OUTPUT_REPORT_NB +\+ BLE_CFG_HIDS_FEATURE_REPORT_NB+#define BLE_CFG_HIDS_PROTOCOL_MODE 1 /**< Report Protocol Mode */++/******************************************************************************+ * GAP Service - Appearance+ ******************************************************************************/++#define BLE_CFG_UNKNOWN_APPEARANCE (0)+#define BLE_CFG_HID_MOUSE_APPEARANCE (962)+#define BLE_CFG_HID_KEYBOARD_APPEARANCE (961)+#define BLE_CFG_GAP_APPEARANCE (BLE_CFG_HID_KEYBOARD_APPEARANCE)++#endif /* BLE_CONF_H */diff --git a/firmware/STM32_WPAN/App/ble_dbg_conf.h b/firmware/STM32_WPAN/App/ble_dbg_conf.hnew file mode 100644index 0000000..76207ba--- /dev/null+++ b/firmware/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/STM32_WPAN/App/hids_app.c b/firmware/STM32_WPAN/App/hids_app.cnew file mode 100644index 0000000..79b6698--- /dev/null+++ b/firmware/STM32_WPAN/App/hids_app.c@@ -0,0 +1,97 @@+#include "app_common.h"+#include "ble.h"+#include "app_ble.h"+#include "hids_app.h"++#define REPORT_IDX_KEYBOARD 0 /* report ID 1, see the patch in hids.c */+#define REPORT_IDX_CONSUMER 1 /* report ID 2 */++static const uint8_t report_map[] =+{+ 0x05, 0x01, /* Usage Page (Generic Desktop) */+ 0x09, 0x06, /* Usage (Keyboard) */+ 0xA1, 0x01, /* Collection (Application) */+ 0x85, 0x01, /* Report ID (1) */+ 0x05, 0x07, /* Usage Page (Keyboard/Keypad) */+ 0x19, 0xE0, /* Usage Minimum (Left Control) */+ 0x29, 0xE7, /* Usage Maximum (Right GUI) */+ 0x15, 0x00, /* Logical Minimum (0) */+ 0x25, 0x01, /* Logical Maximum (1) */+ 0x75, 0x01, /* Report Size (1) */+ 0x95, 0x08, /* Report Count (8) */+ 0x81, 0x02, /* Input (Data, Var, Abs): modifiers */+ 0x75, 0x08, /* Report Size (8) */+ 0x95, 0x01, /* Report Count (1) */+ 0x81, 0x01, /* Input (Const): reserved */+ 0x75, 0x08, /* Report Size (8) */+ 0x95, 0x06, /* Report Count (6) */+ 0x15, 0x00, /* Logical Minimum (0) */+ 0x25, 0xFF, /* Logical Maximum (255) */+ 0x19, 0x00, /* Usage Minimum (0) */+ 0x29, 0xFF, /* Usage Maximum (255) */+ 0x81, 0x00, /* Input (Data, Array): 6 keys */+ 0xC0, /* End Collection */++ 0x05, 0x0C, /* Usage Page (Consumer) */+ 0x09, 0x01, /* Usage (Consumer Control) */+ 0xA1, 0x01, /* Collection (Application) */+ 0x85, 0x02, /* Report ID (2) */+ 0x15, 0x00, /* Logical Minimum (0) */+ 0x26, 0xFF, 0x03, /* Logical Maximum (0x3FF) */+ 0x19, 0x00, /* Usage Minimum (0) */+ 0x2A, 0xFF, 0x03, /* Usage Maximum (0x3FF) */+ 0x75, 0x10, /* Report Size (16) */+ 0x95, 0x01, /* Report Count (1) */+ 0x81, 0x00, /* Input (Data, Array) */+ 0xC0, /* End Collection */+};++/* bcdHID 1.11, country 0, flags: RemoteWake | NormallyConnectable */+static const uint8_t hid_info[4] = {0x11, 0x01, 0x00, 0x03};++static uint8_t last_keyboard[8];+static uint16_t last_consumer;++void HIDSAPP_Init(void)+{+ HIDS_Update_Char(REPORT_MAP_CHAR_UUID, 0, 0, sizeof(report_map), (uint8_t *)report_map);+ HIDS_Update_Char(HID_INFORMATION_CHAR_UUID, 0, 0, sizeof(hid_info), (uint8_t *)hid_info);+ HIDS_Update_Char(REPORT_CHAR_UUID, 0, REPORT_IDX_KEYBOARD, sizeof(last_keyboard), last_keyboard);+ HIDS_Update_Char(REPORT_CHAR_UUID, 0, REPORT_IDX_CONSUMER, sizeof(last_consumer), (uint8_t *)&last_consumer);+}++/* A host reconnecting expects every key released, so reset the cache and+ * let the next change go out. */+void HIDSAPP_Disconnected(void)+{+ memset(last_keyboard, 0, sizeof(last_keyboard));+ last_consumer = 0;+}++void HIDSAPP_SendKeyboard(const uint8_t report[8])+{+ if (memcmp(report, last_keyboard, sizeof(last_keyboard)) == 0) return;+ if (APP_BLE_ConnHandle() == APP_BLE_NO_CONN) return;+ /* Only remember what actually went out, so a report dropped for lack of+ * TX buffers is retried on the next 5 ms tick instead of leaving a key+ * stuck down on the host. */+ if (HIDS_Update_Char(REPORT_CHAR_UUID, 0, REPORT_IDX_KEYBOARD, 8, (uint8_t *)report) == BLE_STATUS_SUCCESS)+ {+ memcpy(last_keyboard, report, sizeof(last_keyboard));+ }+}++void HIDSAPP_SendConsumer(uint16_t usage)+{+ if (usage == last_consumer) return;+ if (APP_BLE_ConnHandle() == APP_BLE_NO_CONN) return;+ if (HIDS_Update_Char(REPORT_CHAR_UUID, 0, REPORT_IDX_CONSUMER, sizeof(usage), (uint8_t *)&usage) == BLE_STATUS_SUCCESS)+ {+ last_consumer = usage;+ }+}++void HIDS_Notification(HIDS_App_Notification_evt_t *pNotification)+{+ UNUSED(pNotification);+}diff --git a/firmware/STM32_WPAN/App/hids_app.h b/firmware/STM32_WPAN/App/hids_app.hnew file mode 100644index 0000000..c24a6b6--- /dev/null+++ b/firmware/STM32_WPAN/App/hids_app.h@@ -0,0 +1,17 @@+/*+ * HID over GATT: report 1 is a boot-style 8 byte keyboard report+ * (modifiers, reserved, 6 keys), report 2 is one 16-bit consumer usage.+ */+#ifndef HIDS_APP_H+#define HIDS_APP_H++#include <stdint.h>++void HIDSAPP_Init(void);+void HIDSAPP_Disconnected(void);++/* Both send only when the value changed since the last send. */+void HIDSAPP_SendKeyboard(const uint8_t report[8]);+void HIDSAPP_SendConsumer(uint16_t usage);++#endif /* HIDS_APP_H */diff --git a/firmware/STM32_WPAN/App/nus.c b/firmware/STM32_WPAN/App/nus.cnew file mode 100644index 0000000..f9e2a2b--- /dev/null+++ b/firmware/STM32_WPAN/App/nus.c@@ -0,0 +1,138 @@+#include "app_common.h"+#include "ble.h"+#include "stm32_seq.h"+#include "app_ble.h"+#include "nus.h"+#include "proto.h"++#define NUS_CHUNK 20 /* fits the default 23 byte ATT MTU */+#define TX_SIZE 1024+#define RX_SIZE 256++/* 6e40000x-b5a3-f393-e0a9-e50e24dcca9e, little endian, x at byte 12 */+#define NUS_UUID(x) {0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0, 0x93, 0xf3, 0xa3, 0xb5, (x), 0x00, 0x40, 0x6e}++static uint16_t svc_handle, rx_handle, tx_handle;+static uint8_t tx_enabled;++/* Single producer, single consumer, both in the sequencer, so plain indexes. */+static char tx_buf[TX_SIZE];+static uint16_t tx_head, tx_tail;+static uint8_t rx_buf[RX_SIZE];+static uint16_t rx_head, rx_tail;++static void Tx_Drain(void)+{+ while (tx_enabled && tx_tail != tx_head && APP_BLE_ConnHandle() != APP_BLE_NO_CONN)+ {+ uint8_t chunk[NUS_CHUNK];+ uint8_t n = 0;+ for (uint16_t t = tx_tail; n < NUS_CHUNK && t != tx_head; t = (t + 1) % TX_SIZE)+ {+ chunk[n++] = (uint8_t)tx_buf[t];+ }+ /* Out of TX buffers: ACI_GATT_TX_POOL_AVAILABLE calls us again. */+ if (aci_gatt_update_char_value(svc_handle, tx_handle, 0, n, chunk) != BLE_STATUS_SUCCESS) return;+ tx_tail = (tx_tail + n) % TX_SIZE;+ }+}++void NUS_Write(const char *data, uint16_t len)+{+ if (!tx_enabled) return; /* nobody listening, don't replay stale events later */+ for (uint16_t i = 0; i < len; i++)+ {+ uint16_t next = (tx_head + 1) % TX_SIZE;+ if (next == tx_tail) break; /* full: drop the rest, the host can ask again */+ tx_buf[tx_head] = data[i];+ tx_head = next;+ }+ Tx_Drain();+}++void NUS_Disconnected(void)+{+ tx_enabled = 0;+ tx_head = tx_tail = 0;+ rx_head = rx_tail = 0;+}++static void Rx_Task(void)+{+ while (rx_tail != rx_head)+ {+ uint16_t end = rx_head;+ uint16_t n = (end > rx_tail ? end : RX_SIZE) - rx_tail;+ PROTO_Input(&rx_buf[rx_tail], n);+ rx_tail = (rx_tail + n) % RX_SIZE;+ }+}++static SVCCTL_EvtAckStatus_t NUS_Event_Handler(void *Event)+{+ hci_event_pckt *event_pckt = (hci_event_pckt *)(((hci_uart_pckt *)Event)->data);+ if (event_pckt->evt != HCI_VENDOR_SPECIFIC_DEBUG_EVT_CODE) return SVCCTL_EvtNotAck;++ evt_blecore_aci *blecore_evt = (evt_blecore_aci *)event_pckt->data;+ switch (blecore_evt->ecode)+ {+ case ACI_GATT_ATTRIBUTE_MODIFIED_VSEVT_CODE:+ {+ aci_gatt_attribute_modified_event_rp0 *mod = (aci_gatt_attribute_modified_event_rp0 *)blecore_evt->data;+ if (mod->Attr_Handle == tx_handle + 2) /* TX CCCD */+ {+ tx_enabled = mod->Attr_Data[0] & 1;+ Tx_Drain();+ return SVCCTL_EvtAckFlowEnable;+ }+ if (mod->Attr_Handle == rx_handle + 1) /* RX value */+ {+ for (uint16_t i = 0; i < mod->Attr_Data_Length; i++)+ {+ uint16_t next = (rx_head + 1) % RX_SIZE;+ if (next == rx_tail) break;+ rx_buf[rx_head] = mod->Attr_Data[i];+ rx_head = next;+ }+ UTIL_SEQ_SetTask(1 << CFG_TASK_NUS_RX_ID, CFG_SCH_PRIO_0);+ return SVCCTL_EvtAckFlowEnable;+ }+ break;+ }++ case ACI_GATT_TX_POOL_AVAILABLE_VSEVT_CODE:+ Tx_Drain();+ break; /* not acked: other services may be waiting on it too */++ default:+ break;+ }+ return SVCCTL_EvtNotAck;+}++void NUS_Init(void)+{+ Char_UUID_t uuid;+ const uint8_t svc_uuid[16] = NUS_UUID(0x01);+ const uint8_t rx_uuid[16] = NUS_UUID(0x02);+ const uint8_t tx_uuid[16] = NUS_UUID(0x03);++ SVCCTL_RegisterSvcHandler(NUS_Event_Handler);+ UTIL_SEQ_RegTask(1 << CFG_TASK_NUS_RX_ID, UTIL_SEQ_RFU, Rx_Task);++ memcpy(uuid.Char_UUID_128, svc_uuid, 16);+ /* service + RX (decl, value) + TX (decl, value, CCCD) */+ aci_gatt_add_service(UUID_TYPE_128, (Service_UUID_t *)&uuid, PRIMARY_SERVICE, 6, &svc_handle);++ /* Writes need an encrypted (bonded) link so a stranger can't remap keys. */+ memcpy(uuid.Char_UUID_128, rx_uuid, 16);+ aci_gatt_add_char(svc_handle, UUID_TYPE_128, &uuid, CFG_BLE_MAX_ATT_MTU - 3,+ CHAR_PROP_WRITE | CHAR_PROP_WRITE_WITHOUT_RESP,+ ATTR_PERMISSION_ENCRY_WRITE, GATT_NOTIFY_ATTRIBUTE_WRITE,+ 10, CHAR_VALUE_LEN_VARIABLE, &rx_handle);++ memcpy(uuid.Char_UUID_128, tx_uuid, 16);+ aci_gatt_add_char(svc_handle, UUID_TYPE_128, &uuid, NUS_CHUNK,+ CHAR_PROP_NOTIFY, ATTR_PERMISSION_NONE, GATT_DONT_NOTIFY_EVENTS,+ 10, CHAR_VALUE_LEN_VARIABLE, &tx_handle);+}diff --git a/firmware/STM32_WPAN/App/nus.h b/firmware/STM32_WPAN/App/nus.hnew file mode 100644index 0000000..0f0811a--- /dev/null+++ b/firmware/STM32_WPAN/App/nus.h@@ -0,0 +1,15 @@+/*+ * Nordic UART Service, the config channel for the desktop app. Bytes+ * written to RX go to PROTO_Input(); NUS_Write() queues bytes for TX and+ * sends them as 20 byte notifications.+ */+#ifndef NUS_H+#define NUS_H++#include <stdint.h>++void NUS_Init(void);+void NUS_Disconnected(void);+void NUS_Write(const char *data, uint16_t len);++#endif /* NUS_H */diff --git a/firmware/STM32_WPAN/App/tl_dbg_conf.h b/firmware/STM32_WPAN/App/tl_dbg_conf.hnew file mode 100644index 0000000..9e45903--- /dev/null+++ b/firmware/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/STM32_WPAN/Target/hw_ipcc.c b/firmware/STM32_WPAN/Target/hw_ipcc.cnew file mode 100644index 0000000..6a311b1--- /dev/null+++ b/firmware/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/keyword.ioc b/firmware/keyword.iocindex b3d6d13..778d4c5 100644--- a/firmware/keyword.ioc+++ b/firmware/keyword.ioc@@ -151,7 +151,7 @@ ProjectManager.ProjectFileName=keyword.iocProjectManager.ProjectName=keywordProjectManager.ProjectStructure=ProjectManager.RegisterCallBack=-ProjectManager.StackSize=0x400+ProjectManager.StackSize=0x1000ProjectManager.TargetToolchain=MakefileProjectManager.ToolChainLocation=ProjectManager.UAScriptAfterPath=diff --git a/firmware/stm32wb55xx_flash_cm4.ld b/firmware/stm32wb55xx_flash_cm4.ldindex 5625ece..8230b56 100644--- a/firmware/stm32wb55xx_flash_cm4.ld+++ b/firmware/stm32wb55xx_flash_cm4.ld@@ -47,7 +47,7 @@ RAM_SHARED (xrw) : ORIGIN = 0x20030000, LENGTH = 10K_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 = 0x400; /* required amount of stack */+_Min_Stack_Size = 0x1000; /* required amount of stack: BLE event handlers + vsnprintf in proto.c *//* Define output sections */SECTIONSdiff --git a/firmware/test/proto_test.c b/firmware/test/proto_test.cnew file mode 100644index 0000000..4b4b2f4--- /dev/null+++ b/firmware/test/proto_test.c@@ -0,0 +1,100 @@+/*+ * Host check for the config protocol parser in Core/Src/proto.c, with the+ * keymap and NUS replaced by small fakes.+ * cc -std=c99 -Itest/stub -ICore/Inc -ISTM32_WPAN/App test/proto_test.c Core/Src/proto.c -o /tmp/proto_test && /tmp/proto_test+ */+#include <assert.h>+#include <stdio.h>+#include <string.h>+#include "keymap.h"+#include "nus.h"+#include "proto.h"++static char out[2048];++void NUS_Write(const char *data, uint16_t len) { strncat(out, data, len); }++static struct { uint8_t uid[UID_LEN], mods, key; } table[KEYMAP_MAX];+static int n;+static keybit_info_t present[2];++static int find(const uint8_t *uid)+{+ for (int i = 0; i < n; i++) if (!memcmp(table[i].uid, uid, UID_LEN)) return i;+ return -1;+}+int KEYMAP_Set(const uint8_t *uid, uint8_t mods, uint8_t key)+{+ int i = find(uid);+ if (i < 0) { if (n == KEYMAP_MAX) return -1; i = n++; memcpy(table[i].uid, uid, UID_LEN); }+ table[i].mods = mods; table[i].key = key;+ return 0;+}+void KEYMAP_Get(const uint8_t *uid, uint8_t *mods, uint8_t *key)+{+ int i = find(uid);+ *mods = i < 0 ? 0 : table[i].mods; *key = i < 0 ? 0 : table[i].key;+}+void KEYMAP_Unmap(const uint8_t *uid) { int i = find(uid); if (i >= 0) table[i] = table[--n]; }+void KEYMAP_Clear(void) { n = 0; }+int KEYMAP_Save(void) { return 0; }+const keybit_info_t *KEYMAP_Present(int *count) { *count = 2; return present; }++static void expect(const char *in, const char *want)+{+ out[0] = 0;+ PROTO_Input((const uint8_t *)in, (uint16_t)strlen(in));+ if (strcmp(out, want) != 0) { printf("in: %s\nwant: %s\ngot: %s\n", in, want, out); assert(0); }+}++#define U "0102030405060708090A0B0C"++int main(void)+{+ for (int i = 0; i < UID_LEN; i++) present[0].uid[i] = (uint8_t)(12 - i); /* prints as U */+ present[0].at = 'L';+ memset(present[1].uid, 0xAB, UID_LEN);+ present[1].at = 'T';++ expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1\n");+ expect("HELLO\r\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1\n");+ expect("SIDES?\n", "SIDES L=1 R=0 T=1\n");+ expect("KEYS?\n", "KEY+ uid=" U " at=L\nKEY+ uid=ABABABABABABABABABABABAB at=T\nKEYS END\n");+ expect("MAP? uid=" U "\n", "MAP uid=" U " mods=00 key=00\n");+ expect("MAP uid=" U " mods=02 key=04\n", "OK MAP uid=" U "\n");+ assert(table[0].uid[0] == 0x0C && table[0].uid[11] == 0x01); /* stored little endian */+ expect("MAP? uid=0102030405060708090a0b0c\n", "MAP uid=" U " mods=02 key=04\n");+ expect("MAP uid=" U " mods=01 key=00\n", "OK MAP uid=" U "\n");+ expect("MAP? uid=" U "\n", "MAP uid=" U " mods=01 key=00\n");+ expect("UNMAP uid=" U "\n", "OK UNMAP uid=" U "\n");+ expect("MAP? uid=" U "\n", "MAP uid=" U " mods=00 key=00\n");+ expect("CLEAR\n", "OK CLEAR\n");+ expect("SAVE\n", "OK SAVE\n");++ /* chunked like 20 byte BLE writes */+ out[0] = 0;+ PROTO_Input((const uint8_t *)"MAP uid=01020304050", 19);+ assert(out[0] == 0);+ PROTO_Input((const uint8_t *)"60708090A0B0C mods=", 19);+ PROTO_Input((const uint8_t *)"00 key=1E\n", 10);+ assert(strcmp(out, "OK MAP uid=" U "\n") == 0);++ expect("MAP uid=0102 mods=00 key=04\n", "ERR usage: MAP uid=<24hex> mods=<2hex> key=<2hex>\n");+ expect("MAP uid=" U " mods=0 key=04\n", "ERR usage: MAP uid=<24hex> mods=<2hex> key=<2hex>\n");+ expect("MAP uid=" U "\n", "ERR usage: MAP uid=<24hex> mods=<2hex> key=<2hex>\n");+ expect("BOGUS\n", "ERR unknown command\n");+ expect("\n", "");++ n = KEYMAP_MAX;+ expect("MAP uid=FFFFFFFFFFFFFFFFFFFFFFFF mods=00 key=04\n", "ERR keymap full\n");++ char longline[300];+ memset(longline, 'A', sizeof(longline) - 2);+ longline[sizeof(longline) - 2] = '\n';+ longline[sizeof(longline) - 1] = 0;+ expect(longline, "ERR line too long\n");+ expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1\n");++ puts("proto_test: ok");+ return 0;+}diff --git a/firmware/test/stub/stm32wbxx_hal.h b/firmware/test/stub/stm32wbxx_hal.hnew file mode 100644index 0000000..d0cbf3c--- /dev/null+++ b/firmware/test/stub/stm32wbxx_hal.h@@ -0,0 +1,2 @@+/* Host build stand-in: keybit_bus.h only needs the I2C handle type. */+typedef struct { int unused; } I2C_HandleTypeDef;