main.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /*
  2. * SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. #include "esp_log.h"
  7. #include "nvs_flash.h"
  8. /* BLE */
  9. #include "nimble/nimble_port.h"
  10. #include "nimble/nimble_port_freertos.h"
  11. #include "host/ble_hs.h"
  12. #include "host/util/util.h"
  13. #include "console/console.h"
  14. #include "services/gap/ble_svc_gap.h"
  15. #include "phy_cent.h"
  16. static const char *tag = "NimBLE_BLE_PHY_CENT";
  17. static int blecent_gap_event(struct ble_gap_event *event, void *arg);
  18. static uint8_t peer_addr[6];
  19. static ble_addr_t conn_addr;
  20. static void blecent_scan(void);
  21. static uint8_t s_current_phy;
  22. void ble_store_config_init(void);
  23. /**
  24. * Performs GATT operation against the specified peer:
  25. * 1. Reads the Supported LE PHY characteristic.
  26. * 2. After read is completed, performs write blob
  27. *
  28. * If the peer does not support a required service, characteristic, or
  29. * descriptor, then the peer lied when it claimed support for the LE
  30. * PHY service! When this happens, or if a GATT procedure fails,
  31. * this function immediately terminates the connection.
  32. */
  33. static int
  34. blecent_on_write(uint16_t conn_handle,
  35. const struct ble_gatt_error *error,
  36. struct ble_gatt_attr *attr,
  37. void *arg)
  38. {
  39. MODLOG_DFLT(INFO, "Write complete; status=%d conn_handle=%d", error->status,
  40. conn_handle);
  41. if (error->status == 0) {
  42. MODLOG_DFLT(INFO, " attr_handle=%d", attr->handle);
  43. }
  44. /* Terminate the connection once GATT procedure is completed */
  45. ble_gap_terminate(conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  46. MODLOG_DFLT(INFO, "\n");
  47. return 0;
  48. }
  49. static int
  50. blecent_on_read(uint16_t conn_handle,
  51. const struct ble_gatt_error *error,
  52. struct ble_gatt_attr *attr,
  53. void *arg)
  54. {
  55. MODLOG_DFLT(INFO, "Read complete; status=%d conn_handle=%d", error->status,
  56. conn_handle);
  57. if (error->status == 0) {
  58. MODLOG_DFLT(INFO, " attr_handle=%d value=", attr->handle);
  59. print_mbuf(attr->om);
  60. }
  61. MODLOG_DFLT(INFO, "\n");
  62. /* Write 1000 bytes to the LE PHY characteristic.*/
  63. const struct peer_chr *chr;
  64. int len = 1000;
  65. uint8_t value[len];
  66. int rc;
  67. struct os_mbuf *txom;
  68. const struct peer *peer = peer_find(conn_handle);
  69. chr = peer_chr_find_uuid(peer,
  70. BLE_UUID16_DECLARE(LE_PHY_UUID16),
  71. BLE_UUID16_DECLARE(LE_PHY_CHR_UUID16));
  72. if (chr == NULL) {
  73. MODLOG_DFLT(ERROR, "Error: Peer doesn't support the Alert "
  74. "Notification Control Point characteristic\n");
  75. goto err;
  76. }
  77. /* Fill the value array with data */
  78. for (int i = 0; i < len; i++) {
  79. value[i] = i;
  80. }
  81. txom = ble_hs_mbuf_from_flat(&value, len);
  82. if (!txom) {
  83. MODLOG_DFLT(ERROR, "Insufficient memory");
  84. goto err;
  85. }
  86. rc = ble_gattc_write_long(conn_handle, chr->chr.val_handle, 0,
  87. txom, blecent_on_write, NULL);
  88. if (rc != 0) {
  89. MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
  90. rc);
  91. goto err;
  92. }
  93. return 0;
  94. err:
  95. /* Terminate the connection. */
  96. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  97. }
  98. static void
  99. blecent_read(const struct peer *peer)
  100. {
  101. const struct peer_chr *chr;
  102. int rc;
  103. /* Read the supported-new-alert-category characteristic. */
  104. chr = peer_chr_find_uuid(peer,
  105. BLE_UUID16_DECLARE(LE_PHY_UUID16),
  106. BLE_UUID16_DECLARE(LE_PHY_CHR_UUID16));
  107. if (chr == NULL) {
  108. MODLOG_DFLT(ERROR, "Error: Peer doesn't support the Supported "
  109. "LE PHY characteristic\n");
  110. goto err;
  111. }
  112. rc = ble_gattc_read(peer->conn_handle, chr->chr.val_handle,
  113. blecent_on_read, NULL);
  114. if (rc != 0) {
  115. MODLOG_DFLT(ERROR, "Error: Failed to read characteristic; rc=%d\n",
  116. rc);
  117. goto err;
  118. }
  119. return;
  120. err:
  121. /* Terminate the connection. */
  122. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  123. }
  124. /**
  125. * Called when service discovery of the specified peer has completed.
  126. */
  127. static void
  128. blecent_on_disc_complete(const struct peer *peer, int status, void *arg)
  129. {
  130. if (status != 0) {
  131. /* Service discovery failed. Terminate the connection. */
  132. MODLOG_DFLT(ERROR, "Error: Service discovery failed; status=%d "
  133. "conn_handle=%d\n", status, peer->conn_handle);
  134. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  135. return;
  136. }
  137. /* Service discovery has completed successfully. Now we have a complete
  138. * list of services, characteristics, and descriptors that the peer
  139. * supports.
  140. */
  141. MODLOG_DFLT(INFO, "Service discovery complete; status=%d "
  142. "conn_handle=%d\n", status, peer->conn_handle);
  143. /* Now perform GATT procedure against the peer: read
  144. */
  145. blecent_read(peer);
  146. }
  147. /* Set default LE PHY before establishing connection */
  148. void set_default_le_phy(uint8_t tx_phys_mask, uint8_t rx_phys_mask)
  149. {
  150. int rc = ble_gap_set_prefered_default_le_phy(tx_phys_mask, rx_phys_mask);
  151. if (rc == 0) {
  152. MODLOG_DFLT(INFO, "Default LE PHY set successfully; tx_phy = %d, rx_phy = %d",
  153. tx_phys_mask, rx_phys_mask);
  154. } else {
  155. MODLOG_DFLT(ERROR, "Failed to set default LE PHY");
  156. }
  157. }
  158. /**
  159. * Initiates the GAP general discovery procedure.
  160. */
  161. static void
  162. blecent_scan(void)
  163. {
  164. uint8_t own_addr_type;
  165. struct ble_gap_disc_params disc_params;
  166. int rc;
  167. /* Figure out address to use while advertising (no privacy for now) */
  168. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  169. if (rc != 0) {
  170. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  171. return;
  172. }
  173. /* Tell the controller to filter duplicates; we don't want to process
  174. * repeated advertisements from the same device.
  175. */
  176. disc_params.filter_duplicates = 1;
  177. /**
  178. * Perform a passive scan. I.e., don't send follow-up scan requests to
  179. * each advertiser.
  180. */
  181. disc_params.passive = 1;
  182. /* Use defaults for the rest of the parameters. */
  183. disc_params.itvl = 0;
  184. disc_params.window = 0;
  185. disc_params.filter_policy = 0;
  186. disc_params.limited = 0;
  187. rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params,
  188. blecent_gap_event, NULL);
  189. if (rc != 0) {
  190. MODLOG_DFLT(ERROR, "Error initiating GAP discovery procedure; rc=%d\n",
  191. rc);
  192. }
  193. }
  194. /**
  195. * Indicates whether we should try to connect to the sender of the specified
  196. * advertisement. The function returns a positive result if the device
  197. * advertises connectability and support for the LE PHY service.
  198. */
  199. static int
  200. ext_blecent_should_connect(const struct ble_gap_ext_disc_desc *disc)
  201. {
  202. int offset = 0;
  203. int ad_struct_len = 0;
  204. if (disc->legacy_event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND &&
  205. disc->legacy_event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
  206. return 0;
  207. }
  208. if (strlen(CONFIG_EXAMPLE_PEER_ADDR) && (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen("ADDR_ANY")) != 0)) {
  209. ESP_LOGI(tag, "Peer address from menuconfig: %s", CONFIG_EXAMPLE_PEER_ADDR);
  210. /* Convert string to address */
  211. sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
  212. &peer_addr[5], &peer_addr[4], &peer_addr[3],
  213. &peer_addr[2], &peer_addr[1], &peer_addr[0]);
  214. if (memcmp(peer_addr, disc->addr.val, sizeof(disc->addr.val)) != 0) {
  215. return 0;
  216. }
  217. }
  218. /* The device has to advertise support LE PHY UUID (0xABF2).
  219. */
  220. do {
  221. ad_struct_len = disc->data[offset];
  222. if (!ad_struct_len) {
  223. break;
  224. }
  225. /* Search if LE PHY UUID is advertised */
  226. if (disc->data[offset] == 0x03 && disc->data[offset + 1] == 0x03) {
  227. if ( disc->data[offset + 2] == 0xAB && disc->data[offset + 3] == 0xF2 ) {
  228. return 1;
  229. }
  230. }
  231. offset += ad_struct_len + 1;
  232. } while ( offset < disc->length_data );
  233. return 0;
  234. }
  235. /**
  236. * Connects to the sender of the specified advertisement of it looks
  237. * interesting. A device is "interesting" if it advertises connectability and
  238. * support for the LE PHY service.
  239. */
  240. static void
  241. blecent_connect_if_interesting(void *disc)
  242. {
  243. uint8_t own_addr_type;
  244. int rc;
  245. ble_addr_t *addr;
  246. /* Don't do anything if we don't care about this advertiser. */
  247. if (!ext_blecent_should_connect((struct ble_gap_ext_disc_desc *)disc)) {
  248. return;
  249. }
  250. /* Scanning must be stopped before a connection can be initiated. */
  251. rc = ble_gap_disc_cancel();
  252. if (rc != 0) {
  253. MODLOG_DFLT(DEBUG, "Failed to cancel scan; rc=%d\n", rc);
  254. return;
  255. }
  256. /* Figure out address to use for connect (no privacy for now) */
  257. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  258. if (rc != 0) {
  259. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  260. return;
  261. }
  262. addr = &((struct ble_gap_ext_disc_desc *)disc)->addr;
  263. /* Copy addr information for next connection */
  264. memcpy(&conn_addr, addr, sizeof(conn_addr));
  265. MODLOG_DFLT(INFO, "Attempting to connect to : %x %x %x %x %x %x with type %d \n",
  266. conn_addr.val[5],conn_addr.val[4], conn_addr.val[3], conn_addr.val[2], conn_addr.val[1], conn_addr.val[0],
  267. conn_addr.type);
  268. /* Try to connect the the advertiser. Allow 30 seconds (30000 ms) for
  269. * timeout.
  270. */
  271. rc = ble_gap_connect(own_addr_type, &conn_addr, 30000, NULL,
  272. blecent_gap_event, NULL);
  273. if (rc != 0) {
  274. MODLOG_DFLT(ERROR, "Error: Failed to connect to device; addr_type=%d "
  275. "addr=%s; rc=%d\n",
  276. conn_addr.type, addr_str(conn_addr.val), rc);
  277. return;
  278. }
  279. }
  280. /**
  281. * The nimble host executes this callback when a GAP event occurs. The
  282. * application associates a GAP event callback with each connection that is
  283. * established. blecent uses the same callback for all connections.
  284. *
  285. * @param event The event being signalled.
  286. * @param arg Application-specified argument; unused by
  287. * blecent.
  288. *
  289. * @return 0 if the application successfully handled the
  290. * event; nonzero on failure. The semantics
  291. * of the return code is specific to the
  292. * particular GAP event being signalled.
  293. */
  294. static int
  295. blecent_gap_event(struct ble_gap_event *event, void *arg)
  296. {
  297. struct ble_gap_conn_desc desc;
  298. int rc;
  299. switch (event->type) {
  300. case BLE_GAP_EVENT_CONNECT:
  301. /* A new connection was established or a connection attempt failed. */
  302. if (event->connect.status == 0) {
  303. /* Connection successfully established. */
  304. switch (s_current_phy) {
  305. case BLE_HCI_LE_PHY_1M_PREF_MASK:
  306. MODLOG_DFLT(INFO,"Connection established on 1M Phy");
  307. break;
  308. case BLE_HCI_LE_PHY_2M_PREF_MASK:
  309. case BLE_HCI_LE_PHY_1M_PREF_MASK | BLE_HCI_LE_PHY_2M_PREF_MASK:
  310. MODLOG_DFLT(INFO,"Connection established on 2M Phy");
  311. break;
  312. case BLE_HCI_LE_PHY_CODED_PREF_MASK:
  313. MODLOG_DFLT(INFO,"Connection established on Coded Phy");
  314. break;
  315. }
  316. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  317. assert(rc == 0);
  318. print_conn_desc(&desc);
  319. MODLOG_DFLT(INFO, "\n");
  320. /* Remember peer. */
  321. rc = peer_add(event->connect.conn_handle);
  322. if (rc != 0) {
  323. MODLOG_DFLT(ERROR, "Failed to add peer; rc=%d\n", rc);
  324. return 0;
  325. }
  326. /* Perform service discovery. */
  327. rc = peer_disc_all(event->connect.conn_handle,
  328. blecent_on_disc_complete, NULL);
  329. if (rc != 0) {
  330. MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
  331. return 0;
  332. }
  333. } else {
  334. /* Connection attempt failed; resume scanning. */
  335. MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n",
  336. event->connect.status);
  337. blecent_scan();
  338. }
  339. return 0;
  340. case BLE_GAP_EVENT_DISCONNECT:
  341. /* Connection terminated. */
  342. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  343. print_conn_desc(&event->disconnect.conn);
  344. MODLOG_DFLT(INFO, "\n");
  345. /* Forget about peer. */
  346. peer_delete(event->disconnect.conn.conn_handle);
  347. switch (s_current_phy) {
  348. case BLE_HCI_LE_PHY_1M_PREF_MASK:
  349. /* Setting current phy to create connection on 2M PHY */
  350. s_current_phy = BLE_HCI_LE_PHY_2M_PREF_MASK;
  351. break;
  352. case BLE_HCI_LE_PHY_2M_PREF_MASK:
  353. /* Setting current phy to create connection on CODED PHY */
  354. s_current_phy = BLE_HCI_LE_PHY_CODED_PREF_MASK;
  355. break;
  356. case BLE_HCI_LE_PHY_CODED_PREF_MASK:
  357. return 0;
  358. }
  359. vTaskDelay(200);
  360. /* Attempt direct connection on 2M or Coded phy now */
  361. if (s_current_phy == BLE_HCI_LE_PHY_CODED_PREF_MASK) {
  362. MODLOG_DFLT(INFO, " Attempting to initiate connection on Coded PHY \n");
  363. ble_gap_ext_connect(0, &conn_addr, 30000, BLE_HCI_LE_PHY_CODED_PREF_MASK,
  364. NULL, NULL, NULL, blecent_gap_event, NULL);
  365. }
  366. else if (s_current_phy == BLE_HCI_LE_PHY_2M_PREF_MASK) {
  367. MODLOG_DFLT(INFO, " Attempting to initiate connection on 2M PHY \n");
  368. ble_gap_ext_connect(0, &conn_addr, 30000, (BLE_HCI_LE_PHY_1M_PREF_MASK | BLE_HCI_LE_PHY_2M_PREF_MASK),
  369. NULL, NULL, NULL, blecent_gap_event, NULL);
  370. }
  371. return 0;
  372. case BLE_GAP_EVENT_DISC_COMPLETE:
  373. MODLOG_DFLT(INFO, "discovery complete; reason=%d\n",
  374. event->disc_complete.reason);
  375. return 0;
  376. case BLE_GAP_EVENT_EXT_DISC:
  377. /* An advertisment report was received during GAP discovery. */
  378. ext_print_adv_report(&event->disc);
  379. blecent_connect_if_interesting(&event->disc);
  380. return 0;
  381. default:
  382. return 0;
  383. }
  384. }
  385. static void
  386. blecent_on_reset(int reason)
  387. {
  388. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  389. }
  390. static void
  391. blecent_on_sync(void)
  392. {
  393. int ii, rc;
  394. uint8_t all_phy;
  395. /* Make sure we have proper identity address set (public preferred) */
  396. rc = ble_hs_util_ensure_addr(0);
  397. assert(rc == 0);
  398. s_current_phy = BLE_HCI_LE_PHY_1M_PREF_MASK;
  399. all_phy = BLE_HCI_LE_PHY_1M_PREF_MASK | BLE_HCI_LE_PHY_2M_PREF_MASK | BLE_HCI_LE_PHY_CODED_PREF_MASK;
  400. set_default_le_phy(all_phy, all_phy);
  401. if (s_current_phy != BLE_HCI_LE_PHY_1M_PREF_MASK) {
  402. /* Check if peer address is set in EXAMPLE_PEER_ADDR */
  403. if (strlen(CONFIG_EXAMPLE_PEER_ADDR) &&
  404. (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen("ADDR_ANY")) != 0)) {
  405. /* User wants to connect on 2M or coded phy directly */
  406. sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
  407. &peer_addr[5], &peer_addr[4], &peer_addr[3],
  408. &peer_addr[2], &peer_addr[1], &peer_addr[0]);
  409. for(ii = 0 ;ii < 6; ii++)
  410. conn_addr.val[ii] = peer_addr[ii];
  411. conn_addr.type = 0;
  412. vTaskDelay(300);
  413. if (s_current_phy == BLE_HCI_LE_PHY_2M_PREF_MASK)
  414. s_current_phy = BLE_HCI_LE_PHY_1M_PREF_MASK | BLE_HCI_LE_PHY_2M_PREF_MASK ;
  415. ble_gap_ext_connect(0, &conn_addr, 30000, s_current_phy,
  416. NULL, NULL, NULL, blecent_gap_event, NULL);
  417. }
  418. }
  419. else {
  420. /* Begin scanning for a peripheral to connect to. */
  421. blecent_scan();
  422. }
  423. }
  424. void blecent_host_task(void *param)
  425. {
  426. ESP_LOGI(tag, "BLE Host Task Started");
  427. /* This function will return only when nimble_port_stop() is executed */
  428. nimble_port_run();
  429. nimble_port_freertos_deinit();
  430. }
  431. void
  432. app_main(void)
  433. {
  434. int rc;
  435. /* Initialize NVS — it is used to store PHY calibration data */
  436. esp_err_t ret = nvs_flash_init();
  437. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  438. ESP_ERROR_CHECK(nvs_flash_erase());
  439. ret = nvs_flash_init();
  440. }
  441. ESP_ERROR_CHECK(ret);
  442. ret = nimble_port_init();
  443. if (ret != ESP_OK) {
  444. MODLOG_DFLT(ERROR, "Failed to init nimble %d \n", ret);
  445. return;
  446. }
  447. /* Configure the host. */
  448. ble_hs_cfg.reset_cb = blecent_on_reset;
  449. ble_hs_cfg.sync_cb = blecent_on_sync;
  450. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  451. /* Initialize data structures to track connected peers. */
  452. rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
  453. assert(rc == 0);
  454. /* Set the default device name. */
  455. rc = ble_svc_gap_device_name_set("blecent-phy");
  456. assert(rc == 0);
  457. /* XXX Need to have template for store */
  458. ble_store_config_init();
  459. nimble_port_freertos_init(blecent_host_task);
  460. }