gap.c 21 KB

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