furi_hal_bt.c 13 KB

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