gap.c 16 KB

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