gap.c 18 KB

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