gap.c 17 KB

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