gap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #include "gap.h"
  2. #include "ble.h"
  3. #include "cmsis_os.h"
  4. #include "otp.h"
  5. #include "dev_info_service.h"
  6. #include "battery_service.h"
  7. #include "serial_service.h"
  8. #include <furi-hal.h>
  9. #define TAG "BtGap"
  10. #define FAST_ADV_TIMEOUT 30000
  11. #define INITIAL_ADV_TIMEOUT 60000
  12. #define BD_ADDR_SIZE_LOCAL 6
  13. typedef struct {
  14. uint16_t gap_svc_handle;
  15. uint16_t dev_name_char_handle;
  16. uint16_t appearance_char_handle;
  17. uint16_t connection_handle;
  18. uint8_t adv_svc_uuid_len;
  19. uint8_t adv_svc_uuid[20];
  20. } GapSvc;
  21. typedef struct {
  22. GapSvc gap_svc;
  23. GapState state;
  24. osMutexId_t state_mutex;
  25. uint8_t mac_address[BD_ADDR_SIZE_LOCAL];
  26. BleEventCallback on_event_cb;
  27. void* context;
  28. osTimerId advertise_timer;
  29. osThreadAttr_t thread_attr;
  30. osThreadId_t thread_id;
  31. osMessageQueueId_t command_queue;
  32. bool enable_adv;
  33. } Gap;
  34. typedef enum {
  35. GapCommandAdvFast,
  36. GapCommandAdvLowPower,
  37. GapCommandAdvStop,
  38. } GapCommand;
  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. // Appearence characteristic UUID
  44. static const uint8_t gap_appearence_char_uuid[] = {0x00, 0x86};
  45. // Default MAC address
  46. static const uint8_t gap_default_mac_addr[] = {0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72};
  47. static Gap* gap = NULL;
  48. static void gap_advertise_start(GapState new_state);
  49. static void gap_app(void *arg);
  50. SVCCTL_UserEvtFlowStatus_t SVCCTL_App_Notification( void *pckt )
  51. {
  52. hci_event_pckt *event_pckt;
  53. evt_le_meta_event *meta_evt;
  54. evt_blue_aci *blue_evt;
  55. hci_le_phy_update_complete_event_rp0 *evt_le_phy_update_complete;
  56. uint8_t tx_phy;
  57. uint8_t rx_phy;
  58. tBleStatus ret = BLE_STATUS_INVALID_PARAMS;
  59. event_pckt = (hci_event_pckt*) ((hci_uart_pckt *) pckt)->data;
  60. osMutexAcquire(gap->state_mutex, osWaitForever);
  61. switch (event_pckt->evt) {
  62. case EVT_DISCONN_COMPLETE:
  63. {
  64. hci_disconnection_complete_event_rp0 *disconnection_complete_event = (hci_disconnection_complete_event_rp0 *) event_pckt->data;
  65. if (disconnection_complete_event->Connection_Handle == gap->gap_svc.connection_handle) {
  66. gap->gap_svc.connection_handle = 0;
  67. gap->state = GapStateIdle;
  68. FURI_LOG_I(TAG, "Disconnect from client. Reason: %d", disconnection_complete_event->Reason);
  69. }
  70. if(gap->enable_adv) {
  71. // Restart advertising
  72. gap_start_advertising();
  73. furi_hal_power_insomnia_exit();
  74. }
  75. BleEvent event = {.type = BleEventTypeDisconnected};
  76. gap->on_event_cb(event, gap->context);
  77. }
  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(TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status);
  89. } else {
  90. FURI_LOG_I(TAG, "Update PHY succeed");
  91. }
  92. ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy);
  93. if(ret) {
  94. FURI_LOG_E(TAG, "Read PHY failed, status: %d", ret);
  95. } else {
  96. FURI_LOG_I(TAG, "PHY Params TX = %d, RX = %d ", tx_phy, rx_phy);
  97. }
  98. break;
  99. case EVT_LE_CONN_COMPLETE:
  100. furi_hal_power_insomnia_enter();
  101. hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data;
  102. FURI_LOG_I(TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle);
  103. // Stop advertising as connection completed
  104. osTimerStop(gap->advertise_timer);
  105. // Update connection status and handle
  106. gap->state = GapStateConnected;
  107. gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle;
  108. // Start pairing by sending security request
  109. aci_gap_slave_security_req(connection_complete_event->Connection_Handle);
  110. break;
  111. default:
  112. break;
  113. }
  114. break;
  115. case EVT_VENDOR:
  116. blue_evt = (evt_blue_aci*) event_pckt->data;
  117. switch (blue_evt->ecode) {
  118. aci_gap_pairing_complete_event_rp0 *pairing_complete;
  119. case EVT_BLUE_GAP_LIMITED_DISCOVERABLE:
  120. FURI_LOG_I(TAG, "Limited discoverable event");
  121. break;
  122. case EVT_BLUE_GAP_PASS_KEY_REQUEST:
  123. {
  124. // Generate random PIN code
  125. uint32_t pin = rand() % 999999;
  126. aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin);
  127. FURI_LOG_I(TAG, "Pass key request event. Pin: %d", pin);
  128. BleEvent event = {.type = BleEventTypePinCodeShow, .data.pin_code = pin};
  129. gap->on_event_cb(event, gap->context);
  130. }
  131. break;
  132. case EVT_BLUE_ATT_EXCHANGE_MTU_RESP:
  133. {
  134. aci_att_exchange_mtu_resp_event_rp0 *pr = (void*)blue_evt->data;
  135. FURI_LOG_I(TAG, "Rx MTU size: %d", pr->Server_RX_MTU);
  136. // Set maximum packet size given header size is 3 bytes
  137. BleEvent event = {.type = BleEventTypeUpdateMTU, .data.max_packet_size = pr->Server_RX_MTU - 3};
  138. gap->on_event_cb(event, gap->context);
  139. }
  140. break;
  141. case EVT_BLUE_GAP_AUTHORIZATION_REQUEST:
  142. FURI_LOG_I(TAG, "Authorization request event");
  143. break;
  144. case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED:
  145. FURI_LOG_I(TAG, "Slave security initiated");
  146. break;
  147. case EVT_BLUE_GAP_BOND_LOST:
  148. FURI_LOG_I(TAG, "Bond lost event. Start rebonding");
  149. aci_gap_allow_rebond(gap->gap_svc.connection_handle);
  150. break;
  151. case EVT_BLUE_GAP_DEVICE_FOUND:
  152. FURI_LOG_I(TAG, "Device found event");
  153. break;
  154. case EVT_BLUE_GAP_ADDR_NOT_RESOLVED:
  155. FURI_LOG_I(TAG, "Address not resolved event");
  156. break;
  157. case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION:
  158. FURI_LOG_I(TAG, "Key press notification event");
  159. break;
  160. case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE:
  161. FURI_LOG_I(TAG, "Hex_value = %lx",
  162. ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value);
  163. aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1);
  164. break;
  165. case EVT_BLUE_GAP_PAIRING_CMPLT:
  166. pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data;
  167. if (pairing_complete->Status) {
  168. FURI_LOG_E(TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status);
  169. aci_gap_terminate(gap->gap_svc.connection_handle, 5);
  170. } else {
  171. FURI_LOG_I(TAG, "Pairing complete");
  172. BleEvent event = {.type = BleEventTypeConnected};
  173. gap->on_event_cb(event, gap->context);
  174. }
  175. break;
  176. case EVT_BLUE_GAP_PROCEDURE_COMPLETE:
  177. FURI_LOG_I(TAG, "Procedure complete event");
  178. break;
  179. }
  180. default:
  181. break;
  182. }
  183. osMutexRelease(gap->state_mutex);
  184. return SVCCTL_UserEvtFlowEnable;
  185. }
  186. static void set_advertisment_service_uid(uint8_t* uid, uint8_t uid_len) {
  187. gap->gap_svc.adv_svc_uuid_len = 1;
  188. if(uid_len == 2) {
  189. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_16_BIT_SERV_UUID;
  190. } else if (uid_len == 4) {
  191. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_32_BIT_SERV_UUID;
  192. } else if(uid_len == 16) {
  193. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST;
  194. }
  195. memcpy(&gap->gap_svc.adv_svc_uuid[1], uid, uid_len);
  196. gap->gap_svc.adv_svc_uuid_len += uid_len;
  197. }
  198. GapState gap_get_state() {
  199. return gap->state;
  200. }
  201. void gap_init_mac_address(Gap* gap) {
  202. uint8_t *otp_addr;
  203. uint32_t udn;
  204. uint32_t company_id;
  205. uint32_t device_id;
  206. udn = LL_FLASH_GetUDN();
  207. if(udn != 0xFFFFFFFF) {
  208. company_id = LL_FLASH_GetSTCompanyID();
  209. device_id = LL_FLASH_GetDeviceID();
  210. gap->mac_address[0] = (uint8_t)(udn & 0x000000FF);
  211. gap->mac_address[1] = (uint8_t)( (udn & 0x0000FF00) >> 8 );
  212. gap->mac_address[2] = (uint8_t)( (udn & 0x00FF0000) >> 16 );
  213. gap->mac_address[3] = (uint8_t)device_id;
  214. gap->mac_address[4] = (uint8_t)(company_id & 0x000000FF);;
  215. gap->mac_address[5] = (uint8_t)( (company_id & 0x0000FF00) >> 8 );
  216. } else {
  217. otp_addr = OTP_Read(0);
  218. if(otp_addr) {
  219. memcpy(gap->mac_address, ((OTP_ID0_t*)otp_addr)->bd_address, sizeof(gap->mac_address));
  220. } else {
  221. memcpy(gap->mac_address, gap_default_mac_addr, sizeof(gap->mac_address));
  222. }
  223. }
  224. }
  225. static void gap_init_svc(Gap* gap) {
  226. tBleStatus status;
  227. uint32_t srd_bd_addr[2];
  228. // HCI Reset to synchronise BLE Stack
  229. hci_reset();
  230. // Configure mac address
  231. gap_init_mac_address(gap);
  232. aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET, CONFIG_DATA_PUBADDR_LEN, (uint8_t*)gap->mac_address);
  233. /* Static random Address
  234. * The two upper bits shall be set to 1
  235. * The lowest 32bits is read from the UDN to differentiate between devices
  236. * The RNG may be used to provide a random number on each power on
  237. */
  238. srd_bd_addr[1] = 0x0000ED6E;
  239. srd_bd_addr[0] = LL_FLASH_GetUDN();
  240. aci_hal_write_config_data( 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. const char *name = furi_hal_version_get_device_name_ptr();
  251. aci_gap_init(GAP_PERIPHERAL_ROLE, 0, strlen(name),
  252. &gap->gap_svc.gap_svc_handle, &gap->gap_svc.dev_name_char_handle, &gap->gap_svc.appearance_char_handle);
  253. // Set GAP characteristics
  254. status = aci_gatt_update_char_value(gap->gap_svc.gap_svc_handle, gap->gap_svc.dev_name_char_handle, 0, strlen(name), (uint8_t *) name);
  255. if (status) {
  256. FURI_LOG_E(TAG, "Failed updating name characteristic: %d", status);
  257. }
  258. status = aci_gatt_update_char_value(gap->gap_svc.gap_svc_handle, gap->gap_svc.appearance_char_handle, 0, 2, gap_appearence_char_uuid);
  259. if(status) {
  260. FURI_LOG_E(TAG, "Failed updating appearence characteristic: %d", status);
  261. }
  262. // Set default PHY
  263. hci_le_set_default_phy(ALL_PHYS_PREFERENCE, TX_2M_PREFERRED, RX_2M_PREFERRED);
  264. // Set I/O capability
  265. aci_gap_set_io_capability(IO_CAP_DISPLAY_ONLY);
  266. // Setup authentication
  267. aci_gap_set_authentication_requirement(1, 1, 1, 0, 8, 16, 1, 0, PUBLIC_ADDR);
  268. // Configure whitelist
  269. aci_gap_configure_whitelist();
  270. }
  271. static void gap_advertise_start(GapState new_state)
  272. {
  273. tBleStatus status;
  274. uint16_t min_interval;
  275. uint16_t max_interval;
  276. if (new_state == GapStateAdvFast) {
  277. min_interval = 0x80; // 80 ms
  278. max_interval = 0xa0; // 100 ms
  279. } else {
  280. min_interval = 0x0640; // 1 s
  281. max_interval = 0x0fa0; // 2.5 s
  282. }
  283. // Stop advertising timer
  284. osTimerStop(gap->advertise_timer);
  285. if ((new_state == GapStateAdvLowPower) && ((gap->state == GapStateAdvFast) || (gap->state == GapStateAdvLowPower))) {
  286. // Stop advertising
  287. status = aci_gap_set_non_discoverable();
  288. if (status) {
  289. FURI_LOG_E(TAG, "Stop Advertising Failed, result: %d", status);
  290. }
  291. }
  292. // Configure advertising
  293. const char* name = furi_hal_version_get_ble_local_device_name_ptr();
  294. status = aci_gap_set_discoverable(ADV_IND, min_interval, max_interval, PUBLIC_ADDR, 0,
  295. strlen(name), (uint8_t*)name,
  296. gap->gap_svc.adv_svc_uuid_len, gap->gap_svc.adv_svc_uuid, 0, 0);
  297. if(status) {
  298. FURI_LOG_E(TAG, "Set discoverable err: %d", status);
  299. }
  300. gap->state = new_state;
  301. BleEvent event = {.type = BleEventTypeStartAdvertising};
  302. gap->on_event_cb(event, gap->context);
  303. osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT);
  304. }
  305. static void gap_advertise_stop() {
  306. if(gap->state == GapStateConnected) {
  307. // Terminate connection
  308. aci_gap_terminate(gap->gap_svc.connection_handle, 0x13);
  309. }
  310. if(gap->state > GapStateIdle) {
  311. // Stop advertising
  312. osTimerStop(gap->advertise_timer);
  313. aci_gap_set_non_discoverable();
  314. gap->state = GapStateIdle;
  315. }
  316. BleEvent event = {.type = BleEventTypeStopAdvertising};
  317. gap->on_event_cb(event, gap->context);
  318. }
  319. void gap_start_advertising() {
  320. FURI_LOG_I(TAG, "Start advertising");
  321. gap->enable_adv = true;
  322. GapCommand command = GapCommandAdvFast;
  323. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  324. }
  325. void gap_stop_advertising() {
  326. FURI_LOG_I(TAG, "Stop advertising");
  327. gap->enable_adv = false;
  328. GapCommand command = GapCommandAdvStop;
  329. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  330. }
  331. static void gap_advetise_timer_callback(void* context) {
  332. GapCommand command = GapCommandAdvLowPower;
  333. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  334. }
  335. bool gap_init(BleEventCallback on_event_cb, void* context) {
  336. if (!ble_glue_is_radio_stack_ready()) {
  337. return false;
  338. }
  339. gap = furi_alloc(sizeof(Gap));
  340. srand(DWT->CYCCNT);
  341. // Create advertising timer
  342. gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, NULL, NULL);
  343. // Initialization of GATT & GAP layer
  344. gap_init_svc(gap);
  345. // Initialization of the BLE Services
  346. SVCCTL_Init();
  347. // Initialization of the GAP state
  348. gap->state_mutex = osMutexNew(NULL);
  349. gap->state = GapStateIdle;
  350. gap->gap_svc.connection_handle = 0xFFFF;
  351. gap->enable_adv = true;
  352. // Thread configuration
  353. gap->thread_attr.name = "BleGapWorker";
  354. gap->thread_attr.stack_size = 1024;
  355. gap->thread_id = osThreadNew(gap_app, NULL, &gap->thread_attr);
  356. // Command queue allocation
  357. gap->command_queue = osMessageQueueNew(8, sizeof(GapCommand), NULL);
  358. // Start Device Information service
  359. dev_info_svc_start();
  360. // Start Battery service
  361. battery_svc_start();
  362. // Start Serial application
  363. serial_svc_start();
  364. // Configure advirtise service UUID
  365. uint8_t adv_service_uid[2];
  366. adv_service_uid[0] = 0x80 | furi_hal_version_get_hw_color();
  367. adv_service_uid[1] = 0x30;
  368. set_advertisment_service_uid(adv_service_uid, sizeof(adv_service_uid));
  369. // Set callback
  370. gap->on_event_cb = on_event_cb;
  371. gap->context = context;
  372. return true;
  373. }
  374. static void gap_app(void *arg) {
  375. GapCommand command;
  376. while(1) {
  377. furi_check(osMessageQueueGet(gap->command_queue, &command, NULL, osWaitForever) == osOK);
  378. osMutexAcquire(gap->state_mutex, osWaitForever);
  379. if(command == GapCommandAdvFast) {
  380. gap_advertise_start(GapStateAdvFast);
  381. } else if(command == GapCommandAdvLowPower) {
  382. gap_advertise_start(GapStateAdvLowPower);
  383. } else if(command == GapCommandAdvStop) {
  384. gap_advertise_stop();
  385. }
  386. osMutexRelease(gap->state_mutex);
  387. }
  388. }