ble_glue.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. #include "ble_glue.h"
  2. #include "app_common.h"
  3. #include "ble_app.h"
  4. #include <ble/ble.h>
  5. #include <hci_tl.h>
  6. #include <interface/patterns/ble_thread/tl/tl.h>
  7. #include <interface/patterns/ble_thread/shci/shci.h>
  8. #include <interface/patterns/ble_thread/tl/shci_tl.h>
  9. #include "app_debug.h"
  10. #include <furi_hal.h>
  11. #define TAG "Core2"
  12. #define BLE_GLUE_FLAG_SHCI_EVENT (1UL << 0)
  13. #define BLE_GLUE_FLAG_KILL_THREAD (1UL << 1)
  14. #define BLE_GLUE_FLAG_ALL (BLE_GLUE_FLAG_SHCI_EVENT | BLE_GLUE_FLAG_KILL_THREAD)
  15. #define POOL_SIZE \
  16. (CFG_TLBLE_EVT_QUEUE_LENGTH * 4U * \
  17. DIVC((sizeof(TL_PacketHeader_t) + TL_BLE_EVENT_FRAME_SIZE), 4U))
  18. PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static uint8_t ble_glue_event_pool[POOL_SIZE];
  19. PLACE_IN_SECTION("MB_MEM2") ALIGN(4) static TL_CmdPacket_t ble_glue_system_cmd_buff;
  20. PLACE_IN_SECTION("MB_MEM2")
  21. ALIGN(4)
  22. static uint8_t ble_glue_system_spare_event_buff[sizeof(TL_PacketHeader_t) + TL_EVT_HDR_SIZE + 255U];
  23. PLACE_IN_SECTION("MB_MEM2")
  24. ALIGN(4)
  25. static uint8_t ble_glue_ble_spare_event_buff[sizeof(TL_PacketHeader_t) + TL_EVT_HDR_SIZE + 255];
  26. typedef struct {
  27. FuriMutex* shci_mtx;
  28. FuriSemaphore* shci_sem;
  29. FuriThread* thread;
  30. BleGlueStatus status;
  31. BleGlueKeyStorageChangedCallback callback;
  32. BleGlueC2Info c2_info;
  33. void* context;
  34. } BleGlue;
  35. static BleGlue* ble_glue = NULL;
  36. static int32_t ble_glue_shci_thread(void* argument);
  37. static void ble_glue_sys_status_not_callback(SHCI_TL_CmdStatus_t status);
  38. static void ble_glue_sys_user_event_callback(void* pPayload);
  39. void ble_glue_set_key_storage_changed_callback(
  40. BleGlueKeyStorageChangedCallback callback,
  41. void* context) {
  42. furi_assert(ble_glue);
  43. furi_assert(callback);
  44. ble_glue->callback = callback;
  45. ble_glue->context = context;
  46. }
  47. ///////////////////////////////////////////////////////////////////////////////
  48. /* TL hook to catch hardfaults */
  49. int32_t ble_glue_TL_SYS_SendCmd(uint8_t* buffer, uint16_t size) {
  50. if(furi_hal_bt_get_hardfault_info()) {
  51. furi_crash("ST(R) Copro(R) HardFault");
  52. }
  53. return TL_SYS_SendCmd(buffer, size);
  54. }
  55. void shci_register_io_bus(tSHciIO* fops) {
  56. /* Register IO bus services */
  57. fops->Init = TL_SYS_Init;
  58. fops->Send = ble_glue_TL_SYS_SendCmd;
  59. }
  60. static int32_t ble_glue_TL_BLE_SendCmd(uint8_t* buffer, uint16_t size) {
  61. if(furi_hal_bt_get_hardfault_info()) {
  62. furi_crash("ST(R) Copro(R) HardFault");
  63. }
  64. return TL_BLE_SendCmd(buffer, size);
  65. }
  66. void hci_register_io_bus(tHciIO* fops) {
  67. /* Register IO bus services */
  68. fops->Init = TL_BLE_Init;
  69. fops->Send = ble_glue_TL_BLE_SendCmd;
  70. }
  71. ///////////////////////////////////////////////////////////////////////////////
  72. void ble_glue_init() {
  73. ble_glue = malloc(sizeof(BleGlue));
  74. ble_glue->status = BleGlueStatusStartup;
  75. #ifdef BLE_GLUE_DEBUG
  76. APPD_Init();
  77. #endif
  78. // Initialize all transport layers
  79. TL_MM_Config_t tl_mm_config;
  80. SHCI_TL_HciInitConf_t SHci_Tl_Init_Conf;
  81. // Reference table initialization
  82. TL_Init();
  83. ble_glue->shci_mtx = furi_mutex_alloc(FuriMutexTypeNormal);
  84. ble_glue->shci_sem = furi_semaphore_alloc(1, 0);
  85. // FreeRTOS system task creation
  86. ble_glue->thread = furi_thread_alloc_ex("BleShciDriver", 1024, ble_glue_shci_thread, ble_glue);
  87. furi_thread_start(ble_glue->thread);
  88. // System channel initialization
  89. SHci_Tl_Init_Conf.p_cmdbuffer = (uint8_t*)&ble_glue_system_cmd_buff;
  90. SHci_Tl_Init_Conf.StatusNotCallBack = ble_glue_sys_status_not_callback;
  91. shci_init(ble_glue_sys_user_event_callback, (void*)&SHci_Tl_Init_Conf);
  92. /**< Memory Manager channel initialization */
  93. tl_mm_config.p_BleSpareEvtBuffer = ble_glue_ble_spare_event_buff;
  94. tl_mm_config.p_SystemSpareEvtBuffer = ble_glue_system_spare_event_buff;
  95. tl_mm_config.p_AsynchEvtPool = ble_glue_event_pool;
  96. tl_mm_config.AsynchEvtPoolSize = POOL_SIZE;
  97. TL_MM_Init(&tl_mm_config);
  98. TL_Enable();
  99. /*
  100. * From now, the application is waiting for the ready event ( VS_HCI_C2_Ready )
  101. * received on the system channel before starting the Stack
  102. * This system event is received with ble_glue_sys_user_event_callback()
  103. */
  104. }
  105. const BleGlueC2Info* ble_glue_get_c2_info() {
  106. return &ble_glue->c2_info;
  107. }
  108. BleGlueStatus ble_glue_get_c2_status() {
  109. return ble_glue->status;
  110. }
  111. static const char* ble_glue_get_reltype_str(const uint8_t reltype) {
  112. static char relcode[3] = {0};
  113. switch(reltype) {
  114. case INFO_STACK_TYPE_BLE_FULL:
  115. return "F";
  116. case INFO_STACK_TYPE_BLE_HCI:
  117. return "H";
  118. case INFO_STACK_TYPE_BLE_LIGHT:
  119. return "L";
  120. case INFO_STACK_TYPE_BLE_BEACON:
  121. return "Be";
  122. case INFO_STACK_TYPE_BLE_BASIC:
  123. return "Ba";
  124. case INFO_STACK_TYPE_BLE_FULL_EXT_ADV:
  125. return "F+";
  126. case INFO_STACK_TYPE_BLE_HCI_EXT_ADV:
  127. return "H+";
  128. default:
  129. snprintf(relcode, sizeof(relcode), "%X", reltype);
  130. return relcode;
  131. }
  132. }
  133. static void ble_glue_update_c2_fw_info() {
  134. WirelessFwInfo_t wireless_info;
  135. SHCI_GetWirelessFwInfo(&wireless_info);
  136. BleGlueC2Info* local_info = &ble_glue->c2_info;
  137. local_info->VersionMajor = wireless_info.VersionMajor;
  138. local_info->VersionMinor = wireless_info.VersionMinor;
  139. local_info->VersionSub = wireless_info.VersionSub;
  140. local_info->VersionBranch = wireless_info.VersionBranch;
  141. local_info->VersionReleaseType = wireless_info.VersionReleaseType;
  142. local_info->MemorySizeSram2B = wireless_info.MemorySizeSram2B;
  143. local_info->MemorySizeSram2A = wireless_info.MemorySizeSram2A;
  144. local_info->MemorySizeSram1 = wireless_info.MemorySizeSram1;
  145. local_info->MemorySizeFlash = wireless_info.MemorySizeFlash;
  146. local_info->StackType = wireless_info.StackType;
  147. snprintf(
  148. local_info->StackTypeString,
  149. BLE_GLUE_MAX_VERSION_STRING_LEN,
  150. "%d.%d.%d:%s",
  151. local_info->VersionMajor,
  152. local_info->VersionMinor,
  153. local_info->VersionSub,
  154. ble_glue_get_reltype_str(local_info->StackType));
  155. local_info->FusVersionMajor = wireless_info.FusVersionMajor;
  156. local_info->FusVersionMinor = wireless_info.FusVersionMinor;
  157. local_info->FusVersionSub = wireless_info.FusVersionSub;
  158. local_info->FusMemorySizeSram2B = wireless_info.FusMemorySizeSram2B;
  159. local_info->FusMemorySizeSram2A = wireless_info.FusMemorySizeSram2A;
  160. local_info->FusMemorySizeFlash = wireless_info.FusMemorySizeFlash;
  161. }
  162. static void ble_glue_dump_stack_info() {
  163. const BleGlueC2Info* c2_info = &ble_glue->c2_info;
  164. FURI_LOG_I(
  165. TAG,
  166. "Core2: FUS: %d.%d.%d, mem %d/%d, flash %d pages",
  167. c2_info->FusVersionMajor,
  168. c2_info->FusVersionMinor,
  169. c2_info->FusVersionSub,
  170. c2_info->FusMemorySizeSram2B,
  171. c2_info->FusMemorySizeSram2A,
  172. c2_info->FusMemorySizeFlash);
  173. FURI_LOG_I(
  174. TAG,
  175. "Core2: Stack: %d.%d.%d, branch %d, reltype %d, stacktype %d, flash %d pages",
  176. c2_info->VersionMajor,
  177. c2_info->VersionMinor,
  178. c2_info->VersionSub,
  179. c2_info->VersionBranch,
  180. c2_info->VersionReleaseType,
  181. c2_info->StackType,
  182. c2_info->MemorySizeFlash);
  183. }
  184. bool ble_glue_wait_for_c2_start(int32_t timeout) {
  185. bool started = false;
  186. do {
  187. // TODO: use mutex?
  188. started = ble_glue->status == BleGlueStatusC2Started;
  189. if(!started) {
  190. timeout--;
  191. furi_delay_tick(1);
  192. }
  193. } while(!started && (timeout > 0));
  194. if(started) {
  195. FURI_LOG_I(
  196. TAG,
  197. "C2 boot completed, mode: %s",
  198. ble_glue->c2_info.mode == BleGlueC2ModeFUS ? "FUS" : "Stack");
  199. ble_glue_update_c2_fw_info();
  200. ble_glue_dump_stack_info();
  201. } else {
  202. FURI_LOG_E(TAG, "C2 startup failed");
  203. ble_glue->status = BleGlueStatusBroken;
  204. }
  205. return started;
  206. }
  207. bool ble_glue_start() {
  208. furi_assert(ble_glue);
  209. if(ble_glue->status != BleGlueStatusC2Started) {
  210. return false;
  211. }
  212. bool ret = false;
  213. if(ble_app_init()) {
  214. FURI_LOG_I(TAG, "Radio stack started");
  215. ble_glue->status = BleGlueStatusRadioStackRunning;
  216. ret = true;
  217. if(SHCI_C2_SetFlashActivityControl(FLASH_ACTIVITY_CONTROL_SEM7) == SHCI_Success) {
  218. FURI_LOG_I(TAG, "Flash activity control switched to SEM7");
  219. } else {
  220. FURI_LOG_E(TAG, "Failed to switch flash activity control to SEM7");
  221. }
  222. } else {
  223. FURI_LOG_E(TAG, "Radio stack startup failed");
  224. ble_glue->status = BleGlueStatusRadioStackMissing;
  225. ble_app_thread_stop();
  226. }
  227. return ret;
  228. }
  229. bool ble_glue_is_alive() {
  230. if(!ble_glue) {
  231. return false;
  232. }
  233. return ble_glue->status >= BleGlueStatusC2Started;
  234. }
  235. bool ble_glue_is_radio_stack_ready() {
  236. if(!ble_glue) {
  237. return false;
  238. }
  239. return ble_glue->status == BleGlueStatusRadioStackRunning;
  240. }
  241. BleGlueCommandResult ble_glue_force_c2_mode(BleGlueC2Mode desired_mode) {
  242. furi_check(desired_mode > BleGlueC2ModeUnknown);
  243. if(desired_mode == ble_glue->c2_info.mode) {
  244. return BleGlueCommandResultOK;
  245. }
  246. if((ble_glue->c2_info.mode == BleGlueC2ModeFUS) && (desired_mode == BleGlueC2ModeStack)) {
  247. if((ble_glue->c2_info.VersionMajor == 0) && (ble_glue->c2_info.VersionMinor == 0)) {
  248. FURI_LOG_W(TAG, "Stack isn't installed!");
  249. return BleGlueCommandResultError;
  250. }
  251. SHCI_CmdStatus_t status = SHCI_C2_FUS_StartWs();
  252. if(status) {
  253. FURI_LOG_E(TAG, "Failed to start Radio Stack with status: %02X", status);
  254. return BleGlueCommandResultError;
  255. }
  256. return BleGlueCommandResultRestartPending;
  257. }
  258. if((ble_glue->c2_info.mode == BleGlueC2ModeStack) && (desired_mode == BleGlueC2ModeFUS)) {
  259. SHCI_FUS_GetState_ErrorCode_t error_code = 0;
  260. uint8_t fus_state = SHCI_C2_FUS_GetState(&error_code);
  261. FURI_LOG_D(TAG, "FUS state: %X, error = %x", fus_state, error_code);
  262. if(fus_state == SHCI_FUS_CMD_NOT_SUPPORTED) {
  263. // Second call to SHCI_C2_FUS_GetState() restarts whole MCU & boots FUS
  264. fus_state = SHCI_C2_FUS_GetState(&error_code);
  265. FURI_LOG_D(TAG, "FUS state#2: %X, error = %x", fus_state, error_code);
  266. return BleGlueCommandResultRestartPending;
  267. }
  268. return BleGlueCommandResultOK;
  269. }
  270. return BleGlueCommandResultError;
  271. }
  272. static void ble_glue_sys_status_not_callback(SHCI_TL_CmdStatus_t status) {
  273. switch(status) {
  274. case SHCI_TL_CmdBusy:
  275. furi_mutex_acquire(ble_glue->shci_mtx, FuriWaitForever);
  276. break;
  277. case SHCI_TL_CmdAvailable:
  278. furi_mutex_release(ble_glue->shci_mtx);
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. /*
  285. * The type of the payload for a system user event is tSHCI_UserEvtRxParam
  286. * When the system event is both :
  287. * - a ready event (subevtcode = SHCI_SUB_EVT_CODE_READY)
  288. * - reported by the FUS (sysevt_ready_rsp == FUS_FW_RUNNING)
  289. * The buffer shall not be released
  290. * ( eg ((tSHCI_UserEvtRxParam*)pPayload)->status shall be set to SHCI_TL_UserEventFlow_Disable )
  291. * When the status is not filled, the buffer is released by default
  292. */
  293. static void ble_glue_sys_user_event_callback(void* pPayload) {
  294. UNUSED(pPayload);
  295. #ifdef BLE_GLUE_DEBUG
  296. APPD_EnableCPU2();
  297. #endif
  298. TL_AsynchEvt_t* p_sys_event =
  299. (TL_AsynchEvt_t*)(((tSHCI_UserEvtRxParam*)pPayload)->pckt->evtserial.evt.payload);
  300. if(p_sys_event->subevtcode == SHCI_SUB_EVT_CODE_READY) {
  301. FURI_LOG_I(TAG, "Core2 started");
  302. SHCI_C2_Ready_Evt_t* p_c2_ready_evt = (SHCI_C2_Ready_Evt_t*)p_sys_event->payload;
  303. if(p_c2_ready_evt->sysevt_ready_rsp == WIRELESS_FW_RUNNING) {
  304. ble_glue->c2_info.mode = BleGlueC2ModeStack;
  305. } else if(p_c2_ready_evt->sysevt_ready_rsp == FUS_FW_RUNNING) {
  306. ble_glue->c2_info.mode = BleGlueC2ModeFUS;
  307. }
  308. ble_glue->status = BleGlueStatusC2Started;
  309. } else if(p_sys_event->subevtcode == SHCI_SUB_EVT_ERROR_NOTIF) {
  310. FURI_LOG_E(TAG, "Error during initialization");
  311. } else if(p_sys_event->subevtcode == SHCI_SUB_EVT_BLE_NVM_RAM_UPDATE) {
  312. SHCI_C2_BleNvmRamUpdate_Evt_t* p_sys_ble_nvm_ram_update_event =
  313. (SHCI_C2_BleNvmRamUpdate_Evt_t*)p_sys_event->payload;
  314. if(ble_glue->callback) {
  315. ble_glue->callback(
  316. (uint8_t*)p_sys_ble_nvm_ram_update_event->StartAddress,
  317. p_sys_ble_nvm_ram_update_event->Size,
  318. ble_glue->context);
  319. }
  320. }
  321. }
  322. static void ble_glue_clear_shared_memory() {
  323. memset(ble_glue_event_pool, 0, sizeof(ble_glue_event_pool));
  324. memset(&ble_glue_system_cmd_buff, 0, sizeof(ble_glue_system_cmd_buff));
  325. memset(ble_glue_system_spare_event_buff, 0, sizeof(ble_glue_system_spare_event_buff));
  326. memset(ble_glue_ble_spare_event_buff, 0, sizeof(ble_glue_ble_spare_event_buff));
  327. }
  328. void ble_glue_thread_stop() {
  329. if(ble_glue) {
  330. FuriThreadId thread_id = furi_thread_get_id(ble_glue->thread);
  331. furi_assert(thread_id);
  332. furi_thread_flags_set(thread_id, BLE_GLUE_FLAG_KILL_THREAD);
  333. furi_thread_join(ble_glue->thread);
  334. furi_thread_free(ble_glue->thread);
  335. // Free resources
  336. furi_mutex_free(ble_glue->shci_mtx);
  337. furi_semaphore_free(ble_glue->shci_sem);
  338. ble_glue_clear_shared_memory();
  339. free(ble_glue);
  340. ble_glue = NULL;
  341. }
  342. }
  343. // Wrap functions
  344. static int32_t ble_glue_shci_thread(void* context) {
  345. UNUSED(context);
  346. uint32_t flags = 0;
  347. while(true) {
  348. flags = furi_thread_flags_wait(BLE_GLUE_FLAG_ALL, FuriFlagWaitAny, FuriWaitForever);
  349. if(flags & BLE_GLUE_FLAG_SHCI_EVENT) {
  350. shci_user_evt_proc();
  351. }
  352. if(flags & BLE_GLUE_FLAG_KILL_THREAD) {
  353. break;
  354. }
  355. }
  356. return 0;
  357. }
  358. void shci_notify_asynch_evt(void* pdata) {
  359. UNUSED(pdata);
  360. if(ble_glue) {
  361. FuriThreadId thread_id = furi_thread_get_id(ble_glue->thread);
  362. furi_assert(thread_id);
  363. furi_thread_flags_set(thread_id, BLE_GLUE_FLAG_SHCI_EVENT);
  364. }
  365. }
  366. void shci_cmd_resp_release(uint32_t flag) {
  367. UNUSED(flag);
  368. if(ble_glue) {
  369. furi_semaphore_release(ble_glue->shci_sem);
  370. }
  371. }
  372. void shci_cmd_resp_wait(uint32_t timeout) {
  373. UNUSED(timeout);
  374. if(ble_glue) {
  375. furi_hal_power_insomnia_enter();
  376. furi_semaphore_acquire(ble_glue->shci_sem, FuriWaitForever);
  377. furi_hal_power_insomnia_exit();
  378. }
  379. }
  380. bool ble_glue_reinit_c2() {
  381. return SHCI_C2_Reinit() == SHCI_Success;
  382. }
  383. BleGlueCommandResult ble_glue_fus_stack_delete() {
  384. FURI_LOG_I(TAG, "Erasing stack");
  385. SHCI_CmdStatus_t erase_stat = SHCI_C2_FUS_FwDelete();
  386. FURI_LOG_I(TAG, "Cmd res = %x", erase_stat);
  387. if(erase_stat == SHCI_Success) {
  388. return BleGlueCommandResultOperationOngoing;
  389. }
  390. ble_glue_fus_get_status();
  391. return BleGlueCommandResultError;
  392. }
  393. BleGlueCommandResult ble_glue_fus_stack_install(uint32_t src_addr, uint32_t dst_addr) {
  394. FURI_LOG_I(TAG, "Installing stack");
  395. SHCI_CmdStatus_t write_stat = SHCI_C2_FUS_FwUpgrade(src_addr, dst_addr);
  396. FURI_LOG_I(TAG, "Cmd res = %x", write_stat);
  397. if(write_stat == SHCI_Success) {
  398. return BleGlueCommandResultOperationOngoing;
  399. }
  400. ble_glue_fus_get_status();
  401. return BleGlueCommandResultError;
  402. }
  403. BleGlueCommandResult ble_glue_fus_get_status() {
  404. furi_check(ble_glue->c2_info.mode == BleGlueC2ModeFUS);
  405. SHCI_FUS_GetState_ErrorCode_t error_code = 0;
  406. uint8_t fus_state = SHCI_C2_FUS_GetState(&error_code);
  407. FURI_LOG_I(TAG, "FUS state: %x, error: %x", fus_state, error_code);
  408. if((error_code != 0) || (fus_state == FUS_STATE_VALUE_ERROR)) {
  409. return BleGlueCommandResultError;
  410. } else if(
  411. (fus_state >= FUS_STATE_VALUE_FW_UPGRD_ONGOING) &&
  412. (fus_state <= FUS_STATE_VALUE_SERVICE_ONGOING_END)) {
  413. return BleGlueCommandResultOperationOngoing;
  414. }
  415. return BleGlueCommandResultOK;
  416. }
  417. BleGlueCommandResult ble_glue_fus_wait_operation() {
  418. furi_check(ble_glue->c2_info.mode == BleGlueC2ModeFUS);
  419. while(true) {
  420. BleGlueCommandResult fus_status = ble_glue_fus_get_status();
  421. if(fus_status == BleGlueCommandResultOperationOngoing) {
  422. furi_delay_ms(20);
  423. } else if(fus_status == BleGlueCommandResultError) {
  424. return BleGlueCommandResultError;
  425. } else {
  426. return BleGlueCommandResultOK;
  427. }
  428. }
  429. }