furi_hal_bt.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #include <furi_hal_bt.h>
  2. #include <ble.h>
  3. #include <stm32wbxx.h>
  4. #include <shci.h>
  5. #include <cmsis_os2.h>
  6. #include <furi_hal_version.h>
  7. #include <furi_hal_bt_hid.h>
  8. #include <furi_hal_bt_serial.h>
  9. #include "battery_service.h"
  10. #include <furi.h>
  11. #define TAG "FuriHalBt"
  12. #define FURI_HAL_BT_DEFAULT_MAC_ADDR \
  13. { 0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72 }
  14. /* Time, in ms, to wait for mode transition before crashing */
  15. #define C2_MODE_SWITCH_TIMEOUT 10000
  16. osMutexId_t furi_hal_bt_core2_mtx = NULL;
  17. static FuriHalBtStack furi_hal_bt_stack = FuriHalBtStackUnknown;
  18. typedef void (*FuriHalBtProfileStart)(void);
  19. typedef void (*FuriHalBtProfileStop)(void);
  20. typedef struct {
  21. FuriHalBtProfileStart start;
  22. FuriHalBtProfileStart stop;
  23. GapConfig config;
  24. uint16_t appearance_char;
  25. uint16_t advertise_service_uuid;
  26. } FuriHalBtProfileConfig;
  27. FuriHalBtProfileConfig profile_config[FuriHalBtProfileNumber] = {
  28. [FuriHalBtProfileSerial] =
  29. {
  30. .start = furi_hal_bt_serial_start,
  31. .stop = furi_hal_bt_serial_stop,
  32. .config =
  33. {
  34. .adv_service_uuid = 0x3080,
  35. .appearance_char = 0x8600,
  36. .bonding_mode = true,
  37. .pairing_method = GapPairingPinCodeShow,
  38. .mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR,
  39. .conn_param =
  40. {
  41. .conn_int_min = 0x18, // 30 ms
  42. .conn_int_max = 0x24, // 45 ms
  43. .slave_latency = 0,
  44. .supervisor_timeout = 0,
  45. },
  46. },
  47. },
  48. [FuriHalBtProfileHidKeyboard] =
  49. {
  50. .start = furi_hal_bt_hid_start,
  51. .stop = furi_hal_bt_hid_stop,
  52. .config =
  53. {
  54. .adv_service_uuid = HUMAN_INTERFACE_DEVICE_SERVICE_UUID,
  55. .appearance_char = GAP_APPEARANCE_KEYBOARD,
  56. .bonding_mode = true,
  57. .pairing_method = GapPairingPinCodeVerifyYesNo,
  58. .mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR,
  59. .conn_param =
  60. {
  61. .conn_int_min = 0x18, // 30 ms
  62. .conn_int_max = 0x24, // 45 ms
  63. .slave_latency = 0,
  64. .supervisor_timeout = 0,
  65. },
  66. },
  67. },
  68. };
  69. FuriHalBtProfileConfig* current_profile = NULL;
  70. void furi_hal_bt_init() {
  71. if(!furi_hal_bt_core2_mtx) {
  72. furi_hal_bt_core2_mtx = osMutexNew(NULL);
  73. furi_assert(furi_hal_bt_core2_mtx);
  74. }
  75. // Explicitly tell that we are in charge of CLK48 domain
  76. if(!LL_HSEM_IsSemaphoreLocked(HSEM, CFG_HW_CLK48_CONFIG_SEMID)) {
  77. furi_check(LL_HSEM_1StepLock(HSEM, CFG_HW_CLK48_CONFIG_SEMID) == 0);
  78. }
  79. // Start Core2
  80. ble_glue_init();
  81. }
  82. void furi_hal_bt_lock_core2() {
  83. furi_assert(furi_hal_bt_core2_mtx);
  84. furi_check(osMutexAcquire(furi_hal_bt_core2_mtx, osWaitForever) == osOK);
  85. }
  86. void furi_hal_bt_unlock_core2() {
  87. furi_assert(furi_hal_bt_core2_mtx);
  88. furi_check(osMutexRelease(furi_hal_bt_core2_mtx) == osOK);
  89. }
  90. static bool furi_hal_bt_radio_stack_is_supported(const BleGlueC2Info* info) {
  91. bool supported = false;
  92. if(info->StackType == INFO_STACK_TYPE_BLE_HCI) {
  93. furi_hal_bt_stack = FuriHalBtStackHciLayer;
  94. supported = true;
  95. } else if(info->StackType == INFO_STACK_TYPE_BLE_LIGHT) {
  96. if(info->VersionMajor >= FURI_HAL_BT_STACK_VERSION_MAJOR &&
  97. info->VersionMinor >= FURI_HAL_BT_STACK_VERSION_MINOR) {
  98. furi_hal_bt_stack = FuriHalBtStackLight;
  99. supported = true;
  100. }
  101. } else {
  102. furi_hal_bt_stack = FuriHalBtStackUnknown;
  103. }
  104. return supported;
  105. }
  106. bool furi_hal_bt_start_radio_stack() {
  107. bool res = false;
  108. furi_assert(furi_hal_bt_core2_mtx);
  109. osMutexAcquire(furi_hal_bt_core2_mtx, osWaitForever);
  110. // Explicitly tell that we are in charge of CLK48 domain
  111. if(!LL_HSEM_IsSemaphoreLocked(HSEM, CFG_HW_CLK48_CONFIG_SEMID)) {
  112. furi_check(LL_HSEM_1StepLock(HSEM, CFG_HW_CLK48_CONFIG_SEMID) == 0);
  113. }
  114. do {
  115. // Wait until C2 is started or timeout
  116. if(!ble_glue_wait_for_c2_start(FURI_HAL_BT_C2_START_TIMEOUT)) {
  117. FURI_LOG_E(TAG, "Core2 start failed");
  118. ble_glue_thread_stop();
  119. break;
  120. }
  121. // If C2 is running, start radio stack fw
  122. if(!furi_hal_bt_ensure_c2_mode(BleGlueC2ModeStack)) {
  123. break;
  124. }
  125. // Check whether we support radio stack
  126. const BleGlueC2Info* c2_info = ble_glue_get_c2_info();
  127. if(!furi_hal_bt_radio_stack_is_supported(c2_info)) {
  128. FURI_LOG_E(TAG, "Unsupported radio stack");
  129. // Don't stop SHCI for crypto enclave support
  130. break;
  131. }
  132. // Starting radio stack
  133. if(!ble_glue_start()) {
  134. FURI_LOG_E(TAG, "Failed to start radio stack");
  135. ble_glue_thread_stop();
  136. ble_app_thread_stop();
  137. break;
  138. }
  139. res = true;
  140. } while(false);
  141. osMutexRelease(furi_hal_bt_core2_mtx);
  142. return res;
  143. }
  144. FuriHalBtStack furi_hal_bt_get_radio_stack() {
  145. return furi_hal_bt_stack;
  146. }
  147. bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, void* context) {
  148. furi_assert(event_cb);
  149. furi_assert(profile < FuriHalBtProfileNumber);
  150. bool ret = false;
  151. do {
  152. if(!ble_glue_is_radio_stack_ready()) {
  153. FURI_LOG_E(TAG, "Can't start BLE App - radio stack did not start");
  154. break;
  155. }
  156. if(furi_hal_bt_stack != FuriHalBtStackLight) {
  157. FURI_LOG_E(TAG, "Can't start Ble App - unsupported radio stack");
  158. break;
  159. }
  160. // Set mac address
  161. memcpy(
  162. profile_config[profile].config.mac_address,
  163. furi_hal_version_get_ble_mac(),
  164. sizeof(profile_config[profile].config.mac_address));
  165. // Set advertise name
  166. strlcpy(
  167. profile_config[profile].config.adv_name,
  168. furi_hal_version_get_ble_local_device_name_ptr(),
  169. FURI_HAL_VERSION_DEVICE_NAME_LENGTH);
  170. // Configure GAP
  171. GapConfig* config = &profile_config[profile].config;
  172. if(profile == FuriHalBtProfileSerial) {
  173. config->adv_service_uuid |= furi_hal_version_get_hw_color();
  174. } else if(profile == FuriHalBtProfileHidKeyboard) {
  175. // Change MAC address for HID profile
  176. config->mac_address[2]++;
  177. // Change name Flipper -> Keynote
  178. const char* clicker_str = "Keynote";
  179. memcpy(&config->adv_name[1], clicker_str, strlen(clicker_str));
  180. }
  181. if(!gap_init(config, event_cb, context)) {
  182. gap_thread_stop();
  183. FURI_LOG_E(TAG, "Failed to init GAP");
  184. break;
  185. }
  186. // Start selected profile services
  187. if(furi_hal_bt_stack == FuriHalBtStackLight) {
  188. profile_config[profile].start();
  189. }
  190. ret = true;
  191. } while(false);
  192. current_profile = &profile_config[profile];
  193. return ret;
  194. }
  195. void furi_hal_bt_reinit() {
  196. FURI_LOG_I(TAG, "Disconnect and stop advertising");
  197. furi_hal_bt_stop_advertising();
  198. FURI_LOG_I(TAG, "Stop current profile services");
  199. current_profile->stop();
  200. // Magic happens here
  201. hci_reset();
  202. FURI_LOG_I(TAG, "Stop BLE related RTOS threads");
  203. ble_app_thread_stop();
  204. gap_thread_stop();
  205. FURI_LOG_I(TAG, "Reset SHCI");
  206. furi_check(ble_glue_reinit_c2());
  207. osDelay(100);
  208. ble_glue_thread_stop();
  209. FURI_LOG_I(TAG, "Start BT initialization");
  210. furi_hal_bt_init();
  211. furi_hal_bt_start_radio_stack();
  212. }
  213. bool furi_hal_bt_change_app(FuriHalBtProfile profile, GapEventCallback event_cb, void* context) {
  214. furi_assert(event_cb);
  215. furi_assert(profile < FuriHalBtProfileNumber);
  216. bool ret = true;
  217. furi_hal_bt_reinit();
  218. ret = furi_hal_bt_start_app(profile, event_cb, context);
  219. if(ret) {
  220. current_profile = &profile_config[profile];
  221. }
  222. return ret;
  223. }
  224. bool furi_hal_bt_is_active() {
  225. return gap_get_state() > GapStateIdle;
  226. }
  227. void furi_hal_bt_start_advertising() {
  228. if(gap_get_state() == GapStateIdle) {
  229. gap_start_advertising();
  230. }
  231. }
  232. void furi_hal_bt_stop_advertising() {
  233. if(furi_hal_bt_is_active()) {
  234. gap_stop_advertising();
  235. while(furi_hal_bt_is_active()) {
  236. osDelay(1);
  237. }
  238. }
  239. }
  240. void furi_hal_bt_update_battery_level(uint8_t battery_level) {
  241. if(battery_svc_is_started()) {
  242. battery_svc_update_level(battery_level);
  243. }
  244. }
  245. void furi_hal_bt_update_power_state() {
  246. if(battery_svc_is_started()) {
  247. battery_svc_update_power_state();
  248. }
  249. }
  250. void furi_hal_bt_get_key_storage_buff(uint8_t** key_buff_addr, uint16_t* key_buff_size) {
  251. ble_app_get_key_storage_buff(key_buff_addr, key_buff_size);
  252. }
  253. void furi_hal_bt_set_key_storage_change_callback(
  254. BleGlueKeyStorageChangedCallback callback,
  255. void* context) {
  256. furi_assert(callback);
  257. ble_glue_set_key_storage_changed_callback(callback, context);
  258. }
  259. void furi_hal_bt_nvm_sram_sem_acquire() {
  260. while(LL_HSEM_1StepLock(HSEM, CFG_HW_BLE_NVM_SRAM_SEMID)) {
  261. osThreadYield();
  262. }
  263. }
  264. void furi_hal_bt_nvm_sram_sem_release() {
  265. LL_HSEM_ReleaseLock(HSEM, CFG_HW_BLE_NVM_SRAM_SEMID, 0);
  266. }
  267. bool furi_hal_bt_clear_white_list() {
  268. furi_hal_bt_nvm_sram_sem_acquire();
  269. tBleStatus status = aci_gap_clear_security_db();
  270. if(status) {
  271. FURI_LOG_E(TAG, "Clear while list failed with status %d", status);
  272. }
  273. furi_hal_bt_nvm_sram_sem_release();
  274. return status != BLE_STATUS_SUCCESS;
  275. }
  276. void furi_hal_bt_dump_state(string_t buffer) {
  277. if(furi_hal_bt_is_alive()) {
  278. uint8_t HCI_Version;
  279. uint16_t HCI_Revision;
  280. uint8_t LMP_PAL_Version;
  281. uint16_t Manufacturer_Name;
  282. uint16_t LMP_PAL_Subversion;
  283. tBleStatus ret = hci_read_local_version_information(
  284. &HCI_Version, &HCI_Revision, &LMP_PAL_Version, &Manufacturer_Name, &LMP_PAL_Subversion);
  285. string_cat_printf(
  286. buffer,
  287. "Ret: %d, HCI_Version: %d, HCI_Revision: %d, LMP_PAL_Version: %d, Manufacturer_Name: %d, LMP_PAL_Subversion: %d",
  288. ret,
  289. HCI_Version,
  290. HCI_Revision,
  291. LMP_PAL_Version,
  292. Manufacturer_Name,
  293. LMP_PAL_Subversion);
  294. } else {
  295. string_cat_printf(buffer, "BLE not ready");
  296. }
  297. }
  298. bool furi_hal_bt_is_alive() {
  299. return ble_glue_is_alive();
  300. }
  301. void furi_hal_bt_start_tone_tx(uint8_t channel, uint8_t power) {
  302. aci_hal_set_tx_power_level(0, power);
  303. aci_hal_tone_start(channel, 0);
  304. }
  305. void furi_hal_bt_stop_tone_tx() {
  306. aci_hal_tone_stop();
  307. }
  308. void furi_hal_bt_start_packet_tx(uint8_t channel, uint8_t pattern, uint8_t datarate) {
  309. hci_le_enhanced_transmitter_test(channel, 0x25, pattern, datarate);
  310. }
  311. void furi_hal_bt_start_packet_rx(uint8_t channel, uint8_t datarate) {
  312. hci_le_enhanced_receiver_test(channel, datarate, 0);
  313. }
  314. uint16_t furi_hal_bt_stop_packet_test() {
  315. uint16_t num_of_packets = 0;
  316. hci_le_test_end(&num_of_packets);
  317. return num_of_packets;
  318. }
  319. void furi_hal_bt_start_rx(uint8_t channel) {
  320. aci_hal_rx_start(channel);
  321. }
  322. float furi_hal_bt_get_rssi() {
  323. float val;
  324. uint8_t rssi_raw[3];
  325. if(aci_hal_read_raw_rssi(rssi_raw) != BLE_STATUS_SUCCESS) {
  326. return 0.0f;
  327. }
  328. // Some ST magic with rssi
  329. uint8_t agc = rssi_raw[2] & 0xFF;
  330. int rssi = (((int)rssi_raw[1] << 8) & 0xFF00) + (rssi_raw[0] & 0xFF);
  331. if(rssi == 0 || agc > 11) {
  332. val = -127.0;
  333. } else {
  334. val = agc * 6.0f - 127.0f;
  335. while(rssi > 30) {
  336. val += 6.0;
  337. rssi >>= 1;
  338. }
  339. val += (417 * rssi + 18080) >> 10;
  340. }
  341. return val;
  342. }
  343. uint32_t furi_hal_bt_get_transmitted_packets() {
  344. uint32_t packets = 0;
  345. aci_hal_le_tx_test_packet_number(&packets);
  346. return packets;
  347. }
  348. void furi_hal_bt_stop_rx() {
  349. aci_hal_rx_stop();
  350. }
  351. bool furi_hal_bt_start_scan(GapScanCallback callback, void* context) {
  352. if(furi_hal_bt_stack != FuriHalBtStackHciLayer) {
  353. return false;
  354. }
  355. gap_start_scan(callback, context);
  356. return true;
  357. }
  358. void furi_hal_bt_stop_scan() {
  359. if(furi_hal_bt_stack == FuriHalBtStackHciLayer) {
  360. gap_stop_scan();
  361. }
  362. }
  363. bool furi_hal_bt_ensure_c2_mode(BleGlueC2Mode mode) {
  364. BleGlueCommandResult fw_start_res = ble_glue_force_c2_mode(mode);
  365. if(fw_start_res == BleGlueCommandResultOK) {
  366. return true;
  367. } else if(fw_start_res == BleGlueCommandResultRestartPending) {
  368. // Do nothing and wait for system reset
  369. osDelay(C2_MODE_SWITCH_TIMEOUT);
  370. furi_crash("Waiting for FUS->radio stack transition");
  371. return true;
  372. }
  373. FURI_LOG_E(TAG, "Failed to switch C2 mode: %d", fw_start_res);
  374. return false;
  375. }