gap.c 16 KB

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