gap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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_GAP_AUTHORIZATION_REQUEST:
  133. FURI_LOG_I(TAG, "Authorization request event");
  134. break;
  135. case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED:
  136. FURI_LOG_I(TAG, "Slave security initiated");
  137. break;
  138. case EVT_BLUE_GAP_BOND_LOST:
  139. FURI_LOG_I(TAG, "Bond lost event. Start rebonding");
  140. aci_gap_allow_rebond(gap->gap_svc.connection_handle);
  141. break;
  142. case EVT_BLUE_GAP_DEVICE_FOUND:
  143. FURI_LOG_I(TAG, "Device found event");
  144. break;
  145. case EVT_BLUE_GAP_ADDR_NOT_RESOLVED:
  146. FURI_LOG_I(TAG, "Address not resolved event");
  147. break;
  148. case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION:
  149. FURI_LOG_I(TAG, "Key press notification event");
  150. break;
  151. case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE:
  152. FURI_LOG_I(TAG, "Hex_value = %lx",
  153. ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value);
  154. aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1);
  155. break;
  156. case EVT_BLUE_GAP_PAIRING_CMPLT:
  157. pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data;
  158. if (pairing_complete->Status) {
  159. FURI_LOG_E(TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status);
  160. aci_gap_terminate(gap->gap_svc.connection_handle, 5);
  161. } else {
  162. FURI_LOG_I(TAG, "Pairing complete");
  163. BleEvent event = {.type = BleEventTypeConnected};
  164. gap->on_event_cb(event, gap->context);
  165. }
  166. break;
  167. case EVT_BLUE_GAP_PROCEDURE_COMPLETE:
  168. FURI_LOG_I(TAG, "Procedure complete event");
  169. break;
  170. }
  171. default:
  172. break;
  173. }
  174. osMutexRelease(gap->state_mutex);
  175. return SVCCTL_UserEvtFlowEnable;
  176. }
  177. static void set_advertisment_service_uid(uint8_t* uid, uint8_t uid_len) {
  178. gap->gap_svc.adv_svc_uuid_len = 1;
  179. if(uid_len == 2) {
  180. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_16_BIT_SERV_UUID;
  181. } else if (uid_len == 4) {
  182. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_32_BIT_SERV_UUID;
  183. } else if(uid_len == 16) {
  184. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST;
  185. }
  186. memcpy(&gap->gap_svc.adv_svc_uuid[1], uid, uid_len);
  187. gap->gap_svc.adv_svc_uuid_len += uid_len;
  188. }
  189. GapState gap_get_state() {
  190. return gap->state;
  191. }
  192. void gap_init_mac_address(Gap* gap) {
  193. uint8_t *otp_addr;
  194. uint32_t udn;
  195. uint32_t company_id;
  196. uint32_t device_id;
  197. udn = LL_FLASH_GetUDN();
  198. if(udn != 0xFFFFFFFF) {
  199. company_id = LL_FLASH_GetSTCompanyID();
  200. device_id = LL_FLASH_GetDeviceID();
  201. gap->mac_address[0] = (uint8_t)(udn & 0x000000FF);
  202. gap->mac_address[1] = (uint8_t)( (udn & 0x0000FF00) >> 8 );
  203. gap->mac_address[2] = (uint8_t)( (udn & 0x00FF0000) >> 16 );
  204. gap->mac_address[3] = (uint8_t)device_id;
  205. gap->mac_address[4] = (uint8_t)(company_id & 0x000000FF);;
  206. gap->mac_address[5] = (uint8_t)( (company_id & 0x0000FF00) >> 8 );
  207. } else {
  208. otp_addr = OTP_Read(0);
  209. if(otp_addr) {
  210. memcpy(gap->mac_address, ((OTP_ID0_t*)otp_addr)->bd_address, sizeof(gap->mac_address));
  211. } else {
  212. memcpy(gap->mac_address, gap_default_mac_addr, sizeof(gap->mac_address));
  213. }
  214. }
  215. }
  216. static void gap_init_svc(Gap* gap) {
  217. tBleStatus status;
  218. uint32_t srd_bd_addr[2];
  219. // HCI Reset to synchronise BLE Stack
  220. hci_reset();
  221. // Configure mac address
  222. gap_init_mac_address(gap);
  223. aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET, CONFIG_DATA_PUBADDR_LEN, (uint8_t*)gap->mac_address);
  224. /* Static random Address
  225. * The two upper bits shall be set to 1
  226. * The lowest 32bits is read from the UDN to differentiate between devices
  227. * The RNG may be used to provide a random number on each power on
  228. */
  229. srd_bd_addr[1] = 0x0000ED6E;
  230. srd_bd_addr[0] = LL_FLASH_GetUDN();
  231. aci_hal_write_config_data( CONFIG_DATA_RANDOM_ADDRESS_OFFSET, CONFIG_DATA_RANDOM_ADDRESS_LEN, (uint8_t*)srd_bd_addr );
  232. // Set Identity root key used to derive LTK and CSRK
  233. aci_hal_write_config_data( CONFIG_DATA_IR_OFFSET, CONFIG_DATA_IR_LEN, (uint8_t*)gap_irk );
  234. // Set Encryption root key used to derive LTK and CSRK
  235. aci_hal_write_config_data( CONFIG_DATA_ER_OFFSET, CONFIG_DATA_ER_LEN, (uint8_t*)gap_erk );
  236. // Set TX Power to 0 dBm
  237. aci_hal_set_tx_power_level(1, 0x19);
  238. // Initialize GATT interface
  239. aci_gatt_init();
  240. // Initialize GAP interface
  241. const char *name = furi_hal_version_get_device_name_ptr();
  242. aci_gap_init(GAP_PERIPHERAL_ROLE, 0, strlen(name),
  243. &gap->gap_svc.gap_svc_handle, &gap->gap_svc.dev_name_char_handle, &gap->gap_svc.appearance_char_handle);
  244. // Set GAP characteristics
  245. 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);
  246. if (status) {
  247. FURI_LOG_E(TAG, "Failed updating name characteristic: %d", status);
  248. }
  249. status = aci_gatt_update_char_value(gap->gap_svc.gap_svc_handle, gap->gap_svc.appearance_char_handle, 0, 2, gap_appearence_char_uuid);
  250. if(status) {
  251. FURI_LOG_E(TAG, "Failed updating appearence characteristic: %d", status);
  252. }
  253. // Set default PHY
  254. hci_le_set_default_phy(ALL_PHYS_PREFERENCE, TX_2M_PREFERRED, RX_2M_PREFERRED);
  255. // Set I/O capability
  256. aci_gap_set_io_capability(IO_CAP_DISPLAY_ONLY);
  257. // Setup authentication
  258. aci_gap_set_authentication_requirement(1, 1, 1, 0, 8, 16, 1, 0, PUBLIC_ADDR);
  259. // Configure whitelist
  260. aci_gap_configure_whitelist();
  261. }
  262. static void gap_advertise_start(GapState new_state)
  263. {
  264. tBleStatus status;
  265. uint16_t min_interval;
  266. uint16_t max_interval;
  267. if (new_state == GapStateAdvFast) {
  268. min_interval = 0x80; // 80 ms
  269. max_interval = 0xa0; // 100 ms
  270. } else {
  271. min_interval = 0x0640; // 1 s
  272. max_interval = 0x0fa0; // 2.5 s
  273. }
  274. // Stop advertising timer
  275. osTimerStop(gap->advertise_timer);
  276. if ((new_state == GapStateAdvLowPower) && ((gap->state == GapStateAdvFast) || (gap->state == GapStateAdvLowPower))) {
  277. // Stop advertising
  278. status = aci_gap_set_non_discoverable();
  279. if (status) {
  280. FURI_LOG_E(TAG, "Stop Advertising Failed, result: %d", status);
  281. }
  282. }
  283. // Configure advertising
  284. const char* name = furi_hal_version_get_ble_local_device_name_ptr();
  285. status = aci_gap_set_discoverable(ADV_IND, min_interval, max_interval, PUBLIC_ADDR, 0,
  286. strlen(name), (uint8_t*)name,
  287. gap->gap_svc.adv_svc_uuid_len, gap->gap_svc.adv_svc_uuid, 0, 0);
  288. if(status) {
  289. FURI_LOG_E(TAG, "Set discoverable err: %d", status);
  290. }
  291. gap->state = new_state;
  292. BleEvent event = {.type = BleEventTypeStartAdvertising};
  293. gap->on_event_cb(event, gap->context);
  294. osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT);
  295. }
  296. static void gap_advertise_stop() {
  297. if(gap->state == GapStateConnected) {
  298. // Terminate connection
  299. aci_gap_terminate(gap->gap_svc.connection_handle, 0x13);
  300. }
  301. if(gap->state > GapStateIdle) {
  302. // Stop advertising
  303. osTimerStop(gap->advertise_timer);
  304. aci_gap_set_non_discoverable();
  305. gap->state = GapStateIdle;
  306. }
  307. BleEvent event = {.type = BleEventTypeStopAdvertising};
  308. gap->on_event_cb(event, gap->context);
  309. }
  310. void gap_start_advertising() {
  311. FURI_LOG_I(TAG, "Start advertising");
  312. gap->enable_adv = true;
  313. GapCommand command = GapCommandAdvFast;
  314. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  315. }
  316. void gap_stop_advertising() {
  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. static void gap_advetise_timer_callback(void* context) {
  323. GapCommand command = GapCommandAdvLowPower;
  324. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  325. }
  326. bool gap_init(BleEventCallback on_event_cb, void* context) {
  327. if (!ble_glue_is_radio_stack_ready()) {
  328. return false;
  329. }
  330. gap = furi_alloc(sizeof(Gap));
  331. srand(DWT->CYCCNT);
  332. // Create advertising timer
  333. gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, NULL, NULL);
  334. // Initialization of GATT & GAP layer
  335. gap_init_svc(gap);
  336. // Initialization of the BLE Services
  337. SVCCTL_Init();
  338. // Initialization of the GAP state
  339. gap->state_mutex = osMutexNew(NULL);
  340. gap->state = GapStateIdle;
  341. gap->gap_svc.connection_handle = 0xFFFF;
  342. gap->enable_adv = true;
  343. // Thread configuration
  344. gap->thread_attr.name = "BleGapWorker";
  345. gap->thread_attr.stack_size = 1024;
  346. gap->thread_id = osThreadNew(gap_app, NULL, &gap->thread_attr);
  347. // Command queue allocation
  348. gap->command_queue = osMessageQueueNew(8, sizeof(GapCommand), NULL);
  349. // Start Device Information service
  350. dev_info_svc_start();
  351. // Start Battery service
  352. battery_svc_start();
  353. // Start Serial application
  354. serial_svc_start();
  355. // Configure advirtise service UUID
  356. uint8_t adv_service_uid[2];
  357. adv_service_uid[0] = 0x80 | furi_hal_version_get_hw_color();
  358. adv_service_uid[1] = 0x30;
  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. static void gap_app(void *arg) {
  366. GapCommand command;
  367. while(1) {
  368. furi_check(osMessageQueueGet(gap->command_queue, &command, NULL, osWaitForever) == osOK);
  369. osMutexAcquire(gap->state_mutex, osWaitForever);
  370. if(command == GapCommandAdvFast) {
  371. gap_advertise_start(GapStateAdvFast);
  372. } else if(command == GapCommandAdvLowPower) {
  373. gap_advertise_start(GapStateAdvLowPower);
  374. } else if(command == GapCommandAdvStop) {
  375. gap_advertise_stop();
  376. }
  377. osMutexRelease(gap->state_mutex);
  378. }
  379. }