gap.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #include "gap.h"
  2. #include "ble.h"
  3. #include <furi_hal.h>
  4. #include <furi.h>
  5. #define TAG "BtGap"
  6. #define FAST_ADV_TIMEOUT 30000
  7. #define INITIAL_ADV_TIMEOUT 60000
  8. #define GAP_INTERVAL_TO_MS(x) (uint16_t)((x)*1.25)
  9. typedef struct {
  10. uint16_t gap_svc_handle;
  11. uint16_t dev_name_char_handle;
  12. uint16_t appearance_char_handle;
  13. uint16_t connection_handle;
  14. uint8_t adv_svc_uuid_len;
  15. uint8_t adv_svc_uuid[20];
  16. char* adv_name;
  17. } GapSvc;
  18. typedef struct {
  19. GapSvc service;
  20. GapConfig* config;
  21. GapConnectionParams connection_params;
  22. GapState state;
  23. osMutexId_t state_mutex;
  24. GapEventCallback on_event_cb;
  25. void* context;
  26. osTimerId_t advertise_timer;
  27. FuriThread* thread;
  28. osMessageQueueId_t command_queue;
  29. bool enable_adv;
  30. } Gap;
  31. typedef enum {
  32. GapCommandAdvFast,
  33. GapCommandAdvLowPower,
  34. GapCommandAdvStop,
  35. GapCommandKillThread,
  36. } GapCommand;
  37. typedef struct {
  38. GapScanCallback callback;
  39. void* context;
  40. } GapScan;
  41. // Identity root key
  42. static const uint8_t gap_irk[16] =
  43. {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0};
  44. // Encryption root key
  45. static const uint8_t gap_erk[16] =
  46. {0xfe, 0xdc, 0xba, 0x09, 0x87, 0x65, 0x43, 0x21, 0xfe, 0xdc, 0xba, 0x09, 0x87, 0x65, 0x43, 0x21};
  47. static Gap* gap = NULL;
  48. static GapScan* gap_scan = NULL;
  49. static void gap_advertise_start(GapState new_state);
  50. static int32_t gap_app(void* context);
  51. static void gap_verify_connection_parameters(Gap* gap) {
  52. furi_assert(gap);
  53. FURI_LOG_I(
  54. TAG,
  55. "Connection parameters: Connection Interval: %d (%d ms), Slave Latency: %d, Supervision Timeout: %d",
  56. gap->connection_params.conn_interval,
  57. GAP_INTERVAL_TO_MS(gap->connection_params.conn_interval),
  58. gap->connection_params.slave_latency,
  59. gap->connection_params.supervisor_timeout);
  60. // Send connection parameters request update if necessary
  61. GapConnectionParamsRequest* params = &gap->config->conn_param;
  62. if(params->conn_int_min > gap->connection_params.conn_interval ||
  63. params->conn_int_max < gap->connection_params.conn_interval) {
  64. FURI_LOG_W(TAG, "Unsupported connection interval. Request connection parameters update");
  65. if(aci_l2cap_connection_parameter_update_req(
  66. gap->service.connection_handle,
  67. params->conn_int_min,
  68. params->conn_int_max,
  69. gap->connection_params.slave_latency,
  70. gap->connection_params.supervisor_timeout)) {
  71. FURI_LOG_E(TAG, "Failed to request connection parameters update");
  72. }
  73. }
  74. }
  75. SVCCTL_UserEvtFlowStatus_t SVCCTL_App_Notification(void* pckt) {
  76. hci_event_pckt* event_pckt;
  77. evt_le_meta_event* meta_evt;
  78. evt_blue_aci* blue_evt;
  79. hci_le_phy_update_complete_event_rp0* evt_le_phy_update_complete;
  80. uint8_t tx_phy;
  81. uint8_t rx_phy;
  82. tBleStatus ret = BLE_STATUS_INVALID_PARAMS;
  83. event_pckt = (hci_event_pckt*)((hci_uart_pckt*)pckt)->data;
  84. if(gap) {
  85. osMutexAcquire(gap->state_mutex, osWaitForever);
  86. }
  87. switch(event_pckt->evt) {
  88. case EVT_DISCONN_COMPLETE: {
  89. hci_disconnection_complete_event_rp0* disconnection_complete_event =
  90. (hci_disconnection_complete_event_rp0*)event_pckt->data;
  91. if(disconnection_complete_event->Connection_Handle == gap->service.connection_handle) {
  92. gap->service.connection_handle = 0;
  93. gap->state = GapStateIdle;
  94. FURI_LOG_I(
  95. TAG, "Disconnect from client. Reason: %02X", disconnection_complete_event->Reason);
  96. }
  97. if(gap->enable_adv) {
  98. // Restart advertising
  99. gap_advertise_start(GapStateAdvFast);
  100. furi_hal_power_insomnia_exit();
  101. }
  102. GapEvent event = {.type = GapEventTypeDisconnected};
  103. gap->on_event_cb(event, gap->context);
  104. } break;
  105. case EVT_LE_META_EVENT:
  106. meta_evt = (evt_le_meta_event*)event_pckt->data;
  107. switch(meta_evt->subevent) {
  108. case EVT_LE_CONN_UPDATE_COMPLETE: {
  109. hci_le_connection_update_complete_event_rp0* event =
  110. (hci_le_connection_update_complete_event_rp0*)meta_evt->data;
  111. gap->connection_params.conn_interval = event->Conn_Interval;
  112. gap->connection_params.slave_latency = event->Conn_Latency;
  113. gap->connection_params.supervisor_timeout = event->Supervision_Timeout;
  114. FURI_LOG_I(TAG, "Connection parameters event complete");
  115. gap_verify_connection_parameters(gap);
  116. break;
  117. }
  118. case EVT_LE_PHY_UPDATE_COMPLETE:
  119. evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data;
  120. if(evt_le_phy_update_complete->Status) {
  121. FURI_LOG_E(
  122. TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status);
  123. } else {
  124. FURI_LOG_I(TAG, "Update PHY succeed");
  125. }
  126. ret = hci_le_read_phy(gap->service.connection_handle, &tx_phy, &rx_phy);
  127. if(ret) {
  128. FURI_LOG_E(TAG, "Read PHY failed, status: %d", ret);
  129. } else {
  130. FURI_LOG_I(TAG, "PHY Params TX = %d, RX = %d ", tx_phy, rx_phy);
  131. }
  132. break;
  133. case EVT_LE_CONN_COMPLETE:
  134. furi_hal_power_insomnia_enter();
  135. hci_le_connection_complete_event_rp0* event =
  136. (hci_le_connection_complete_event_rp0*)meta_evt->data;
  137. gap->connection_params.conn_interval = event->Conn_Interval;
  138. gap->connection_params.slave_latency = event->Conn_Latency;
  139. gap->connection_params.supervisor_timeout = event->Supervision_Timeout;
  140. // Stop advertising as connection completed
  141. osTimerStop(gap->advertise_timer);
  142. // Update connection status and handle
  143. gap->state = GapStateConnected;
  144. gap->service.connection_handle = event->Connection_Handle;
  145. gap_verify_connection_parameters(gap);
  146. // Start pairing by sending security request
  147. aci_gap_slave_security_req(event->Connection_Handle);
  148. break;
  149. case EVT_LE_ADVERTISING_REPORT: {
  150. if(gap_scan) {
  151. GapAddress address;
  152. hci_le_advertising_report_event_rp0* evt =
  153. (hci_le_advertising_report_event_rp0*)meta_evt->data;
  154. for(uint8_t i = 0; i < evt->Num_Reports; i++) {
  155. Advertising_Report_t* rep = &evt->Advertising_Report[i];
  156. address.type = rep->Address_Type;
  157. // Original MAC addres is in inverted order
  158. for(uint8_t j = 0; j < sizeof(address.mac); j++) {
  159. address.mac[j] = rep->Address[sizeof(address.mac) - j - 1];
  160. }
  161. gap_scan->callback(address, gap_scan->context);
  162. }
  163. }
  164. } break;
  165. default:
  166. break;
  167. }
  168. break;
  169. case EVT_VENDOR:
  170. blue_evt = (evt_blue_aci*)event_pckt->data;
  171. switch(blue_evt->ecode) {
  172. aci_gap_pairing_complete_event_rp0* pairing_complete;
  173. case EVT_BLUE_GAP_LIMITED_DISCOVERABLE:
  174. FURI_LOG_I(TAG, "Limited discoverable event");
  175. break;
  176. case EVT_BLUE_GAP_PASS_KEY_REQUEST: {
  177. // Generate random PIN code
  178. uint32_t pin = rand() % 999999;
  179. aci_gap_pass_key_resp(gap->service.connection_handle, pin);
  180. if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagLock)) {
  181. FURI_LOG_I(TAG, "Pass key request event. Pin: ******");
  182. } else {
  183. FURI_LOG_I(TAG, "Pass key request event. Pin: %06d", pin);
  184. }
  185. GapEvent event = {.type = GapEventTypePinCodeShow, .data.pin_code = pin};
  186. gap->on_event_cb(event, gap->context);
  187. } break;
  188. case EVT_BLUE_ATT_EXCHANGE_MTU_RESP: {
  189. aci_att_exchange_mtu_resp_event_rp0* pr = (void*)blue_evt->data;
  190. FURI_LOG_I(TAG, "Rx MTU size: %d", pr->Server_RX_MTU);
  191. // Set maximum packet size given header size is 3 bytes
  192. GapEvent event = {
  193. .type = GapEventTypeUpdateMTU, .data.max_packet_size = pr->Server_RX_MTU - 3};
  194. gap->on_event_cb(event, gap->context);
  195. } break;
  196. case EVT_BLUE_GAP_AUTHORIZATION_REQUEST:
  197. FURI_LOG_D(TAG, "Authorization request event");
  198. break;
  199. case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED:
  200. FURI_LOG_D(TAG, "Slave security initiated");
  201. break;
  202. case EVT_BLUE_GAP_BOND_LOST:
  203. FURI_LOG_D(TAG, "Bond lost event. Start rebonding");
  204. aci_gap_allow_rebond(gap->service.connection_handle);
  205. break;
  206. case EVT_BLUE_GAP_DEVICE_FOUND:
  207. FURI_LOG_D(TAG, "Device found event");
  208. break;
  209. case EVT_BLUE_GAP_ADDR_NOT_RESOLVED:
  210. FURI_LOG_D(TAG, "Address not resolved event");
  211. break;
  212. case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION:
  213. FURI_LOG_D(TAG, "Key press notification event");
  214. break;
  215. case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE: {
  216. uint32_t pin =
  217. ((aci_gap_numeric_comparison_value_event_rp0*)(blue_evt->data))->Numeric_Value;
  218. FURI_LOG_I(TAG, "Verify numeric comparison: %06d", pin);
  219. GapEvent event = {.type = GapEventTypePinCodeVerify, .data.pin_code = pin};
  220. bool result = gap->on_event_cb(event, gap->context);
  221. aci_gap_numeric_comparison_value_confirm_yesno(gap->service.connection_handle, result);
  222. break;
  223. }
  224. case EVT_BLUE_GAP_PAIRING_CMPLT:
  225. pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data;
  226. if(pairing_complete->Status) {
  227. FURI_LOG_E(
  228. TAG,
  229. "Pairing failed with status: %d. Terminating connection",
  230. pairing_complete->Status);
  231. aci_gap_terminate(gap->service.connection_handle, 5);
  232. } else {
  233. FURI_LOG_I(TAG, "Pairing complete");
  234. GapEvent event = {.type = GapEventTypeConnected};
  235. gap->on_event_cb(event, gap->context);
  236. }
  237. break;
  238. case EVT_BLUE_GAP_PROCEDURE_COMPLETE:
  239. FURI_LOG_D(TAG, "Procedure complete event");
  240. break;
  241. case EVT_BLUE_L2CAP_CONNECTION_UPDATE_RESP: {
  242. uint16_t result =
  243. ((aci_l2cap_connection_update_resp_event_rp0*)(blue_evt->data))->Result;
  244. if(result == 0) {
  245. FURI_LOG_D(TAG, "Connection parameters accepted");
  246. } else if(result == 1) {
  247. FURI_LOG_D(TAG, "Connection parameters denied");
  248. }
  249. break;
  250. }
  251. }
  252. default:
  253. break;
  254. }
  255. if(gap) {
  256. osMutexRelease(gap->state_mutex);
  257. }
  258. return SVCCTL_UserEvtFlowEnable;
  259. }
  260. static void set_advertisment_service_uid(uint8_t* uid, uint8_t uid_len) {
  261. if(uid_len == 2) {
  262. gap->service.adv_svc_uuid[0] = AD_TYPE_16_BIT_SERV_UUID;
  263. } else if(uid_len == 4) {
  264. gap->service.adv_svc_uuid[0] = AD_TYPE_32_BIT_SERV_UUID;
  265. } else if(uid_len == 16) {
  266. gap->service.adv_svc_uuid[0] = AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST;
  267. }
  268. memcpy(&gap->service.adv_svc_uuid[gap->service.adv_svc_uuid_len], uid, uid_len);
  269. gap->service.adv_svc_uuid_len += uid_len;
  270. }
  271. static void gap_init_svc(Gap* gap) {
  272. tBleStatus status;
  273. uint32_t srd_bd_addr[2];
  274. // HCI Reset to synchronise BLE Stack
  275. hci_reset();
  276. // Configure mac address
  277. aci_hal_write_config_data(
  278. CONFIG_DATA_PUBADDR_OFFSET, CONFIG_DATA_PUBADDR_LEN, gap->config->mac_address);
  279. /* Static random Address
  280. * The two upper bits shall be set to 1
  281. * The lowest 32bits is read from the UDN to differentiate between devices
  282. * The RNG may be used to provide a random number on each power on
  283. */
  284. srd_bd_addr[1] = 0x0000ED6E;
  285. srd_bd_addr[0] = LL_FLASH_GetUDN();
  286. aci_hal_write_config_data(
  287. CONFIG_DATA_RANDOM_ADDRESS_OFFSET, CONFIG_DATA_RANDOM_ADDRESS_LEN, (uint8_t*)srd_bd_addr);
  288. // Set Identity root key used to derive LTK and CSRK
  289. aci_hal_write_config_data(CONFIG_DATA_IR_OFFSET, CONFIG_DATA_IR_LEN, (uint8_t*)gap_irk);
  290. // Set Encryption root key used to derive LTK and CSRK
  291. aci_hal_write_config_data(CONFIG_DATA_ER_OFFSET, CONFIG_DATA_ER_LEN, (uint8_t*)gap_erk);
  292. // Set TX Power to 0 dBm
  293. aci_hal_set_tx_power_level(1, 0x19);
  294. // Initialize GATT interface
  295. aci_gatt_init();
  296. // Initialize GAP interface
  297. // Skip fist symbol AD_TYPE_COMPLETE_LOCAL_NAME
  298. char* name = gap->service.adv_name + 1;
  299. aci_gap_init(
  300. GAP_PERIPHERAL_ROLE,
  301. 0,
  302. strlen(name),
  303. &gap->service.gap_svc_handle,
  304. &gap->service.dev_name_char_handle,
  305. &gap->service.appearance_char_handle);
  306. // Set GAP characteristics
  307. status = aci_gatt_update_char_value(
  308. gap->service.gap_svc_handle,
  309. gap->service.dev_name_char_handle,
  310. 0,
  311. strlen(name),
  312. (uint8_t*)name);
  313. if(status) {
  314. FURI_LOG_E(TAG, "Failed updating name characteristic: %d", status);
  315. }
  316. uint8_t gap_appearence_char_uuid[2] = {
  317. gap->config->appearance_char & 0xff, gap->config->appearance_char >> 8};
  318. status = aci_gatt_update_char_value(
  319. gap->service.gap_svc_handle,
  320. gap->service.appearance_char_handle,
  321. 0,
  322. 2,
  323. gap_appearence_char_uuid);
  324. if(status) {
  325. FURI_LOG_E(TAG, "Failed updating appearence characteristic: %d", status);
  326. }
  327. // Set default PHY
  328. hci_le_set_default_phy(ALL_PHYS_PREFERENCE, TX_2M_PREFERRED, RX_2M_PREFERRED);
  329. // Set I/O capability
  330. bool keypress_supported = false;
  331. if(gap->config->pairing_method == GapPairingPinCodeShow) {
  332. aci_gap_set_io_capability(IO_CAP_DISPLAY_ONLY);
  333. } else if(gap->config->pairing_method == GapPairingPinCodeVerifyYesNo) {
  334. aci_gap_set_io_capability(IO_CAP_DISPLAY_YES_NO);
  335. keypress_supported = true;
  336. }
  337. // Setup authentication
  338. aci_gap_set_authentication_requirement(
  339. gap->config->bonding_mode,
  340. CFG_MITM_PROTECTION,
  341. CFG_SC_SUPPORT,
  342. keypress_supported,
  343. CFG_ENCRYPTION_KEY_SIZE_MIN,
  344. CFG_ENCRYPTION_KEY_SIZE_MAX,
  345. CFG_USED_FIXED_PIN,
  346. 0,
  347. PUBLIC_ADDR);
  348. // Configure whitelist
  349. aci_gap_configure_whitelist();
  350. }
  351. static void gap_advertise_start(GapState new_state) {
  352. tBleStatus status;
  353. uint16_t min_interval;
  354. uint16_t max_interval;
  355. if(new_state == GapStateAdvFast) {
  356. min_interval = 0x80; // 80 ms
  357. max_interval = 0xa0; // 100 ms
  358. } else {
  359. min_interval = 0x0640; // 1 s
  360. max_interval = 0x0fa0; // 2.5 s
  361. }
  362. // Stop advertising timer
  363. osTimerStop(gap->advertise_timer);
  364. if((new_state == GapStateAdvLowPower) &&
  365. ((gap->state == GapStateAdvFast) || (gap->state == GapStateAdvLowPower))) {
  366. // Stop advertising
  367. status = aci_gap_set_non_discoverable();
  368. if(status) {
  369. FURI_LOG_E(TAG, "Stop Advertising Failed, result: %d", status);
  370. }
  371. }
  372. // Configure advertising
  373. status = aci_gap_set_discoverable(
  374. ADV_IND,
  375. min_interval,
  376. max_interval,
  377. PUBLIC_ADDR,
  378. 0,
  379. strlen(gap->service.adv_name),
  380. (uint8_t*)gap->service.adv_name,
  381. gap->service.adv_svc_uuid_len,
  382. gap->service.adv_svc_uuid,
  383. 0,
  384. 0);
  385. if(status) {
  386. FURI_LOG_E(TAG, "Set discoverable err: %d", status);
  387. }
  388. gap->state = new_state;
  389. GapEvent event = {.type = GapEventTypeStartAdvertising};
  390. gap->on_event_cb(event, gap->context);
  391. osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT);
  392. }
  393. static void gap_advertise_stop() {
  394. if(gap->state > GapStateIdle) {
  395. if(gap->state == GapStateConnected) {
  396. // Terminate connection
  397. aci_gap_terminate(gap->service.connection_handle, 0x13);
  398. }
  399. // Stop advertising
  400. osTimerStop(gap->advertise_timer);
  401. aci_gap_set_non_discoverable();
  402. gap->state = GapStateIdle;
  403. }
  404. GapEvent event = {.type = GapEventTypeStopAdvertising};
  405. gap->on_event_cb(event, gap->context);
  406. }
  407. void gap_start_advertising() {
  408. osMutexAcquire(gap->state_mutex, osWaitForever);
  409. if(gap->state == GapStateIdle) {
  410. gap->state = GapStateStartingAdv;
  411. FURI_LOG_I(TAG, "Start advertising");
  412. gap->enable_adv = true;
  413. GapCommand command = GapCommandAdvFast;
  414. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  415. }
  416. osMutexRelease(gap->state_mutex);
  417. }
  418. void gap_stop_advertising() {
  419. osMutexAcquire(gap->state_mutex, osWaitForever);
  420. if(gap->state > GapStateIdle) {
  421. FURI_LOG_I(TAG, "Stop advertising");
  422. gap->enable_adv = false;
  423. GapCommand command = GapCommandAdvStop;
  424. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  425. }
  426. osMutexRelease(gap->state_mutex);
  427. }
  428. static void gap_advetise_timer_callback(void* context) {
  429. GapCommand command = GapCommandAdvLowPower;
  430. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  431. }
  432. bool gap_init(GapConfig* config, GapEventCallback on_event_cb, void* context) {
  433. if(!ble_glue_is_radio_stack_ready()) {
  434. return false;
  435. }
  436. gap = malloc(sizeof(Gap));
  437. gap->config = config;
  438. srand(DWT->CYCCNT);
  439. // Create advertising timer
  440. gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, NULL, NULL);
  441. // Initialization of GATT & GAP layer
  442. gap->service.adv_name = config->adv_name;
  443. gap_init_svc(gap);
  444. // Initialization of the BLE Services
  445. SVCCTL_Init();
  446. // Initialization of the GAP state
  447. gap->state_mutex = osMutexNew(NULL);
  448. gap->state = GapStateIdle;
  449. gap->service.connection_handle = 0xFFFF;
  450. gap->enable_adv = true;
  451. // Thread configuration
  452. gap->thread = furi_thread_alloc();
  453. furi_thread_set_name(gap->thread, "BleGapDriver");
  454. furi_thread_set_stack_size(gap->thread, 1024);
  455. furi_thread_set_context(gap->thread, gap);
  456. furi_thread_set_callback(gap->thread, gap_app);
  457. furi_thread_start(gap->thread);
  458. // Command queue allocation
  459. gap->command_queue = osMessageQueueNew(8, sizeof(GapCommand), NULL);
  460. uint8_t adv_service_uid[2];
  461. gap->service.adv_svc_uuid_len = 1;
  462. adv_service_uid[0] = gap->config->adv_service_uuid & 0xff;
  463. adv_service_uid[1] = gap->config->adv_service_uuid >> 8;
  464. set_advertisment_service_uid(adv_service_uid, sizeof(adv_service_uid));
  465. // Set callback
  466. gap->on_event_cb = on_event_cb;
  467. gap->context = context;
  468. return true;
  469. }
  470. GapState gap_get_state() {
  471. GapState state;
  472. if(gap) {
  473. osMutexAcquire(gap->state_mutex, osWaitForever);
  474. state = gap->state;
  475. osMutexRelease(gap->state_mutex);
  476. } else {
  477. state = GapStateUninitialized;
  478. }
  479. return state;
  480. }
  481. void gap_start_scan(GapScanCallback callback, void* context) {
  482. furi_assert(callback);
  483. gap_scan = malloc(sizeof(GapScan));
  484. gap_scan->callback = callback;
  485. gap_scan->context = context;
  486. // Scan interval 250 ms
  487. hci_le_set_scan_parameters(1, 4000, 200, 0, 0);
  488. hci_le_set_scan_enable(1, 1);
  489. }
  490. void gap_stop_scan() {
  491. furi_assert(gap_scan);
  492. hci_le_set_scan_enable(0, 1);
  493. free(gap_scan);
  494. gap_scan = NULL;
  495. }
  496. void gap_thread_stop() {
  497. if(gap) {
  498. osMutexAcquire(gap->state_mutex, osWaitForever);
  499. gap->enable_adv = false;
  500. GapCommand command = GapCommandKillThread;
  501. osMessageQueuePut(gap->command_queue, &command, 0, osWaitForever);
  502. osMutexRelease(gap->state_mutex);
  503. furi_thread_join(gap->thread);
  504. furi_thread_free(gap->thread);
  505. // Free resources
  506. osMutexDelete(gap->state_mutex);
  507. osMessageQueueDelete(gap->command_queue);
  508. osTimerStop(gap->advertise_timer);
  509. while(xTimerIsTimerActive(gap->advertise_timer) == pdTRUE) osDelay(1);
  510. furi_check(osTimerDelete(gap->advertise_timer) == osOK);
  511. free(gap);
  512. gap = NULL;
  513. }
  514. }
  515. static int32_t gap_app(void* context) {
  516. GapCommand command;
  517. while(1) {
  518. osStatus_t status = osMessageQueueGet(gap->command_queue, &command, NULL, osWaitForever);
  519. if(status != osOK) {
  520. FURI_LOG_E(TAG, "Message queue get error: %d", status);
  521. continue;
  522. }
  523. osMutexAcquire(gap->state_mutex, osWaitForever);
  524. if(command == GapCommandKillThread) {
  525. break;
  526. }
  527. if(command == GapCommandAdvFast) {
  528. gap_advertise_start(GapStateAdvFast);
  529. } else if(command == GapCommandAdvLowPower) {
  530. gap_advertise_start(GapStateAdvLowPower);
  531. } else if(command == GapCommandAdvStop) {
  532. gap_advertise_stop();
  533. }
  534. osMutexRelease(gap->state_mutex);
  535. }
  536. return 0;
  537. }