gap.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 <furi-hal.h>
  11. #define GAP_TAG "BLE"
  12. #define FAST_ADV_TIMEOUT 30000
  13. #define INITIAL_ADV_TIMEOUT 60000
  14. #define BD_ADDR_SIZE_LOCAL 6
  15. typedef struct {
  16. uint16_t gap_svc_handle;
  17. uint16_t dev_name_char_handle;
  18. uint16_t appearance_char_handle;
  19. uint16_t connection_handle;
  20. uint8_t adv_svc_uuid_len;
  21. uint8_t adv_svc_uuid[20];
  22. } GapSvc;
  23. typedef struct {
  24. GapSvc gap_svc;
  25. GapState state;
  26. osMutexId_t state_mutex;
  27. uint8_t mac_address[BD_ADDR_SIZE_LOCAL];
  28. Bt* bt;
  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");
  70. }
  71. if(gap->enable_adv) {
  72. // Restart advertising
  73. gap_start_advertising();
  74. furi_hal_power_insomnia_exit();
  75. }
  76. }
  77. break;
  78. case EVT_LE_META_EVENT:
  79. meta_evt = (evt_le_meta_event*) event_pckt->data;
  80. switch (meta_evt->subevent) {
  81. case EVT_LE_CONN_UPDATE_COMPLETE:
  82. FURI_LOG_D(GAP_TAG, "Connection update event");
  83. break;
  84. case EVT_LE_PHY_UPDATE_COMPLETE:
  85. evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data;
  86. if(evt_le_phy_update_complete->Status) {
  87. FURI_LOG_E(GAP_TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status);
  88. } else {
  89. FURI_LOG_I(GAP_TAG, "Update PHY succeed");
  90. }
  91. ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy);
  92. if(ret) {
  93. FURI_LOG_E(GAP_TAG, "Read PHY failed, status: %d", ret);
  94. } else {
  95. FURI_LOG_I(GAP_TAG, "PHY Params TX = %d, RX = %d ", tx_phy, rx_phy);
  96. }
  97. break;
  98. case EVT_LE_CONN_COMPLETE:
  99. furi_hal_power_insomnia_enter();
  100. hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data;
  101. FURI_LOG_I(GAP_TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle);
  102. // Stop advertising as connection completed
  103. osTimerStop(gap->advertise_timer);
  104. // Update connection status and handle
  105. gap->state = GapStateConnected;
  106. gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle;
  107. // Start pairing by sending security request
  108. aci_gap_slave_security_req(connection_complete_event->Connection_Handle);
  109. break;
  110. default:
  111. break;
  112. }
  113. break;
  114. case EVT_VENDOR:
  115. blue_evt = (evt_blue_aci*) event_pckt->data;
  116. switch (blue_evt->ecode) {
  117. aci_gap_pairing_complete_event_rp0 *pairing_complete;
  118. case EVT_BLUE_GAP_LIMITED_DISCOVERABLE:
  119. FURI_LOG_I(GAP_TAG, "Limited discoverable event");
  120. break;
  121. case EVT_BLUE_GAP_PASS_KEY_REQUEST:
  122. {
  123. // Generate random PIN code
  124. uint32_t pin = rand() % 999999;
  125. aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin);
  126. FURI_LOG_I(GAP_TAG, "Pass key request event. Pin: %d", pin);
  127. bt_pin_code_show(gap->bt, pin);
  128. }
  129. break;
  130. case EVT_BLUE_GAP_AUTHORIZATION_REQUEST:
  131. FURI_LOG_I(GAP_TAG, "Authorization request event");
  132. break;
  133. case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED:
  134. FURI_LOG_I(GAP_TAG, "Slave security initiated");
  135. break;
  136. case EVT_BLUE_GAP_BOND_LOST:
  137. FURI_LOG_I(GAP_TAG, "Bond lost event. Start rebonding");
  138. aci_gap_allow_rebond(gap->gap_svc.connection_handle);
  139. break;
  140. case EVT_BLUE_GAP_DEVICE_FOUND:
  141. FURI_LOG_I(GAP_TAG, "Device found event");
  142. break;
  143. case EVT_BLUE_GAP_ADDR_NOT_RESOLVED:
  144. FURI_LOG_I(GAP_TAG, "Address not resolved event");
  145. break;
  146. case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION:
  147. FURI_LOG_I(GAP_TAG, "Key press notification event");
  148. break;
  149. case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE:
  150. FURI_LOG_I(GAP_TAG, "Hex_value = %lx",
  151. ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value);
  152. aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1);
  153. break;
  154. case EVT_BLUE_GAP_PAIRING_CMPLT:
  155. pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data;
  156. if (pairing_complete->Status) {
  157. FURI_LOG_E(GAP_TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status);
  158. aci_gap_terminate(gap->gap_svc.connection_handle, 5);
  159. } else {
  160. FURI_LOG_I(GAP_TAG, "Pairing complete");
  161. }
  162. break;
  163. case EVT_BLUE_GAP_PROCEDURE_COMPLETE:
  164. FURI_LOG_I(GAP_TAG, "Procedure complete event");
  165. break;
  166. }
  167. default:
  168. break;
  169. }
  170. osMutexRelease(gap->state_mutex);
  171. return SVCCTL_UserEvtFlowEnable;
  172. }
  173. void SVCCTL_SvcInit() {
  174. // Dummy function to prevent unused services initialization
  175. // TODO refactor (disable all services in WPAN config)
  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(GAP_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(GAP_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(GAP_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(GAP_TAG, "Set discoverable err: %d", status);
  290. }
  291. gap->state = new_state;
  292. bt_update_statusbar(gap->bt);
  293. osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT);
  294. }
  295. static void gap_advertise_stop() {
  296. if(gap->state == GapStateConnected) {
  297. // Terminate connection
  298. aci_gap_terminate(gap->gap_svc.connection_handle, 0x13);
  299. }
  300. if(gap->state > GapStateIdle) {
  301. // Stop advertising
  302. osTimerStop(gap->advertise_timer);
  303. aci_gap_set_non_discoverable();
  304. gap->state = GapStateIdle;
  305. bt_update_statusbar(gap->bt);
  306. }
  307. }
  308. void gap_start_advertising() {
  309. gap->enable_adv = true;
  310. GapCommand command = GapCommandAdvFast;
  311. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  312. }
  313. void gap_stop_advertising() {
  314. gap->enable_adv = false;
  315. GapCommand command = GapCommandAdvStop;
  316. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  317. }
  318. static void gap_advetise_timer_callback(void* context) {
  319. GapCommand command = GapCommandAdvLowPower;
  320. furi_check(osMessageQueuePut(gap->command_queue, &command, 0, 0) == osOK);
  321. }
  322. bool gap_init() {
  323. if (APPE_Status() != BleGlueStatusStarted) {
  324. return false;
  325. }
  326. gap = furi_alloc(sizeof(Gap));
  327. srand(DWT->CYCCNT);
  328. // Open Bt record
  329. gap->bt = furi_record_open("bt");
  330. // Create advertising timer
  331. gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, NULL, NULL);
  332. // Initialization of GATT & GAP layer
  333. gap_init_svc(gap);
  334. // Initialization of the BLE Services
  335. SVCCTL_Init();
  336. // Initialization of the GAP state
  337. gap->state_mutex = osMutexNew(NULL);
  338. gap->state = GapStateIdle;
  339. gap->gap_svc.connection_handle = 0xFFFF;
  340. gap->enable_adv = true;
  341. // Thread configuration
  342. gap->thread_attr.name = "BLE advertising";
  343. gap->thread_attr.stack_size = 1024;
  344. gap->thread_id = osThreadNew(gap_app, NULL, &gap->thread_attr);
  345. // Command queue allocation
  346. gap->command_queue = osMessageQueueNew(8, sizeof(GapCommand), NULL);
  347. // Start Device Information service
  348. dev_info_svc_start();
  349. // Start Battery service
  350. battery_svc_start();
  351. // Start Serial application
  352. serial_svc_start();
  353. // Configure advirtise service UUID
  354. uint8_t adv_service_uid[2];
  355. adv_service_uid[0] = 0x80 | furi_hal_version_get_hw_color();
  356. adv_service_uid[1] = 0x30;
  357. set_advertisment_service_uid(adv_service_uid, sizeof(adv_service_uid));
  358. return true;
  359. }
  360. static void gap_app(void *arg) {
  361. GapCommand command;
  362. while(1) {
  363. furi_check(osMessageQueueGet(gap->command_queue, &command, NULL, osWaitForever) == osOK);
  364. osMutexAcquire(gap->state_mutex, osWaitForever);
  365. if(command == GapCommandAdvFast) {
  366. gap_advertise_start(GapStateAdvFast);
  367. } else if(command == GapCommandAdvLowPower) {
  368. gap_advertise_start(GapStateAdvLowPower);
  369. } else if(command == GapCommandAdvStop) {
  370. gap_advertise_stop();
  371. }
  372. osMutexRelease(gap->state_mutex);
  373. }
  374. }