gap.c 17 KB

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