gap.c 19 KB

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