main.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*
  2. * SPDX-FileCopyrightText: 2021-2022 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_prph.h"
  16. #if CONFIG_EXAMPLE_EXTENDED_ADV
  17. static uint8_t ext_adv_pattern_1M[] = {
  18. 0x02, 0x01, 0x06,
  19. 0x03, 0x03, 0xab, 0xcd,
  20. 0x03, 0x03, 0xAB, 0xF2,
  21. 0x0e, 0X09, 'b', 'l', 'e', 'p', 'r', 'p', 'h', '-', 'p', 'h', 'y', '-', '1', 'M',
  22. };
  23. static uint8_t ext_adv_pattern_2M[] = {
  24. 0x02, 0x01, 0x06,
  25. 0x03, 0x03, 0xab, 0xcd,
  26. 0x03, 0x03, 0xAB, 0xF2,
  27. 0x0e, 0X09, 'b', 'l', 'e', 'p', 'r', 'p', 'h', '-', 'p', 'h', 'y', '-', '2', 'M',
  28. };
  29. static uint8_t ext_adv_pattern_coded[] = {
  30. 0x02, 0x01, 0x06,
  31. 0x03, 0x03, 0xab, 0xcd,
  32. 0x03, 0x03, 0xAB, 0xF2,
  33. 0x11, 0X09, 'b', 'l', 'e', 'p', 'r', 'p', 'h', '-', 'p', 'h', 'y', '-', 'c', 'o', 'd', 'e',
  34. 'd',
  35. };
  36. #endif
  37. static const char *tag = "NimBLE_BLE_PHY_PRPH";
  38. static int bleprph_gap_event(struct ble_gap_event *event, void *arg);
  39. static uint8_t own_addr_type;
  40. static uint8_t s_current_phy;
  41. void ble_store_config_init(void);
  42. /* Set default LE PHY before establishing connection */
  43. void set_default_le_phy_before_conn(uint8_t tx_phys_mask, uint8_t rx_phys_mask)
  44. {
  45. int rc = ble_gap_set_prefered_default_le_phy(tx_phys_mask, rx_phys_mask);
  46. if (rc == 0) {
  47. MODLOG_DFLT(INFO, "Default LE PHY set successfully");
  48. } else {
  49. MODLOG_DFLT(ERROR, "Failed to set default LE PHY");
  50. }
  51. }
  52. /**
  53. * Logs information about a connection to the console.
  54. */
  55. static void
  56. bleprph_print_conn_desc(struct ble_gap_conn_desc *desc)
  57. {
  58. MODLOG_DFLT(INFO, "handle=%d our_ota_addr_type=%d our_ota_addr=",
  59. desc->conn_handle, desc->our_ota_addr.type);
  60. print_addr(desc->our_ota_addr.val);
  61. MODLOG_DFLT(INFO, " our_id_addr_type=%d our_id_addr=",
  62. desc->our_id_addr.type);
  63. print_addr(desc->our_id_addr.val);
  64. MODLOG_DFLT(INFO, " peer_ota_addr_type=%d peer_ota_addr=",
  65. desc->peer_ota_addr.type);
  66. print_addr(desc->peer_ota_addr.val);
  67. MODLOG_DFLT(INFO, " peer_id_addr_type=%d peer_id_addr=",
  68. desc->peer_id_addr.type);
  69. print_addr(desc->peer_id_addr.val);
  70. MODLOG_DFLT(INFO, " conn_itvl=%d conn_latency=%d supervision_timeout=%d "
  71. "encrypted=%d authenticated=%d bonded=%d\n",
  72. desc->conn_itvl, desc->conn_latency,
  73. desc->supervision_timeout,
  74. desc->sec_state.encrypted,
  75. desc->sec_state.authenticated,
  76. desc->sec_state.bonded);
  77. }
  78. #if CONFIG_EXAMPLE_EXTENDED_ADV
  79. static struct os_mbuf *
  80. ext_get_data(uint8_t ext_adv_pattern[], int size)
  81. {
  82. struct os_mbuf *data;
  83. int rc;
  84. data = os_msys_get_pkthdr(size, 0);
  85. assert(data);
  86. rc = os_mbuf_append(data, ext_adv_pattern, size);
  87. assert(rc == 0);
  88. return data;
  89. }
  90. /**
  91. * Enables advertising with the following parameters:
  92. * o General discoverable mode.
  93. * o Undirected connectable mode.
  94. */
  95. static void
  96. ext_bleprph_advertise(void)
  97. {
  98. struct ble_gap_ext_adv_params params;
  99. struct os_mbuf *data = NULL;
  100. uint8_t instance = 1;
  101. int rc;
  102. /* use defaults for non-set params */
  103. memset (&params, 0, sizeof(params));
  104. /* enable connectable advertising */
  105. params.connectable = 1;
  106. params.scannable = 1;
  107. params.legacy_pdu = 1;
  108. /* advertise using random addr */
  109. params.own_addr_type = BLE_OWN_ADDR_PUBLIC;
  110. /* Set current phy; get mbuf for scan rsp data; fill mbuf with scan rsp data */
  111. switch (s_current_phy) {
  112. case BLE_HCI_LE_PHY_1M_PREF_MASK:
  113. params.primary_phy = BLE_HCI_LE_PHY_1M;
  114. params.secondary_phy = BLE_HCI_LE_PHY_1M;
  115. data = ext_get_data(ext_adv_pattern_1M, sizeof(ext_adv_pattern_1M));
  116. break;
  117. case BLE_HCI_LE_PHY_2M_PREF_MASK:
  118. params.primary_phy = BLE_HCI_LE_PHY_1M;
  119. params.secondary_phy = BLE_HCI_LE_PHY_2M;
  120. data = ext_get_data(ext_adv_pattern_2M, sizeof(ext_adv_pattern_2M));
  121. break;
  122. case BLE_HCI_LE_PHY_CODED_PREF_MASK:
  123. params.primary_phy = BLE_HCI_LE_PHY_CODED;
  124. params.secondary_phy = BLE_HCI_LE_PHY_CODED;
  125. data = ext_get_data(ext_adv_pattern_coded, sizeof(ext_adv_pattern_coded));
  126. break;
  127. }
  128. //params.tx_power = 127;
  129. params.sid = 1;
  130. params.itvl_min = BLE_GAP_ADV_FAST_INTERVAL1_MIN;
  131. params.itvl_max = BLE_GAP_ADV_FAST_INTERVAL1_MIN;
  132. /* configure instance 0 */
  133. rc = ble_gap_ext_adv_configure(instance, &params, NULL,
  134. bleprph_gap_event, NULL);
  135. assert (rc == 0);
  136. rc = ble_gap_ext_adv_set_data(instance, data);
  137. assert (rc == 0);
  138. /* start advertising */
  139. rc = ble_gap_ext_adv_start(instance, 0, 0);
  140. assert (rc == 0);
  141. }
  142. #else
  143. /**
  144. * Enables advertising with the following parameters:
  145. * o General discoverable mode.
  146. * o Undirected connectable mode.
  147. */
  148. static void
  149. bleprph_advertise(void)
  150. {
  151. struct ble_gap_adv_params adv_params;
  152. struct ble_hs_adv_fields fields;
  153. const char *name;
  154. int rc;
  155. /**
  156. * Set the advertisement data included in our advertisements:
  157. * o Flags (indicates advertisement type and other general info).
  158. * o Advertising tx power.
  159. * o Device name.
  160. * o 16-bit service UUIDs (alert notifications).
  161. */
  162. memset(&fields, 0, sizeof fields);
  163. /* Advertise two flags:
  164. * o Discoverability in forthcoming advertisement (general)
  165. * o BLE-only (BR/EDR unsupported).
  166. */
  167. fields.flags = BLE_HS_ADV_F_DISC_GEN |
  168. BLE_HS_ADV_F_BREDR_UNSUP;
  169. /* Indicate that the TX power level field should be included; have the
  170. * stack fill this value automatically. This is done by assigning the
  171. * special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
  172. */
  173. fields.tx_pwr_lvl_is_present = 1;
  174. fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
  175. name = ble_svc_gap_device_name();
  176. fields.name = (uint8_t *)name;
  177. fields.name_len = strlen(name);
  178. fields.name_is_complete = 1;
  179. fields.uuids16 = (ble_uuid16_t[]) {
  180. BLE_UUID16_INIT(LE_PHY_UUID16)
  181. };
  182. fields.num_uuids16 = 1;
  183. fields.uuids16_is_complete = 1;
  184. rc = ble_gap_adv_set_fields(&fields);
  185. if (rc != 0) {
  186. MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc);
  187. return;
  188. }
  189. /* Begin advertising. */
  190. memset(&adv_params, 0, sizeof adv_params);
  191. adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
  192. adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
  193. rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
  194. &adv_params, bleprph_gap_event, NULL);
  195. if (rc != 0) {
  196. MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc);
  197. return;
  198. }
  199. }
  200. #endif
  201. /**
  202. * The nimble host executes this callback when a GAP event occurs. The
  203. * application associates a GAP event callback with each connection that forms.
  204. * bleprph uses the same callback for all connections.
  205. *
  206. * @param event The type of event being signalled.
  207. * @param ctxt Various information pertaining to the event.
  208. * @param arg Application-specified argument; unused by
  209. * bleprph.
  210. *
  211. * @return 0 if the application successfully handled the
  212. * event; nonzero on failure. The semantics
  213. * of the return code is specific to the
  214. * particular GAP event being signalled.
  215. */
  216. static int
  217. bleprph_gap_event(struct ble_gap_event *event, void *arg)
  218. {
  219. struct ble_gap_conn_desc desc;
  220. int rc;
  221. switch (event->type) {
  222. case BLE_GAP_EVENT_CONNECT:
  223. /* A new connection was established or a connection attempt failed. */
  224. MODLOG_DFLT(INFO, "connection %s; status=%d ",
  225. event->connect.status == 0 ? "established" : "failed",
  226. event->connect.status);
  227. if (event->connect.status == 0) {
  228. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  229. assert(rc == 0);
  230. bleprph_print_conn_desc(&desc);
  231. }
  232. MODLOG_DFLT(INFO, "\n");
  233. if (event->connect.status != 0) {
  234. /* Connection failed; resume advertising. */
  235. #if CONFIG_EXAMPLE_EXTENDED_ADV
  236. ext_bleprph_advertise();
  237. #else
  238. bleprph_advertise();
  239. #endif
  240. }
  241. return 0;
  242. case BLE_GAP_EVENT_DISCONNECT:
  243. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  244. bleprph_print_conn_desc(&event->disconnect.conn);
  245. MODLOG_DFLT(INFO, "\n");
  246. /* Connection terminated; resume advertising. */
  247. #if CONFIG_EXAMPLE_EXTENDED_ADV
  248. switch (s_current_phy) {
  249. case BLE_HCI_LE_PHY_1M_PREF_MASK:
  250. /* Setting current phy to create connection on 2M PHY */
  251. s_current_phy = BLE_HCI_LE_PHY_2M_PREF_MASK;
  252. break;
  253. case BLE_HCI_LE_PHY_2M_PREF_MASK:
  254. /* Setting current phy to create connection on CODED PHY */
  255. s_current_phy = BLE_HCI_LE_PHY_CODED_PREF_MASK;
  256. break;
  257. case BLE_HCI_LE_PHY_CODED_PREF_MASK:
  258. return 0;
  259. default:
  260. return 0;
  261. }
  262. set_default_le_phy_before_conn(s_current_phy, s_current_phy);
  263. ext_bleprph_advertise();
  264. #else
  265. bleprph_advertise();
  266. #endif
  267. return 0;
  268. case BLE_GAP_EVENT_CONN_UPDATE:
  269. /* The central has updated the connection parameters. */
  270. MODLOG_DFLT(INFO, "connection updated; status=%d ",
  271. event->conn_update.status);
  272. rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
  273. assert(rc == 0);
  274. bleprph_print_conn_desc(&desc);
  275. MODLOG_DFLT(INFO, "\n");
  276. return 0;
  277. case BLE_GAP_EVENT_ADV_COMPLETE:
  278. MODLOG_DFLT(INFO, "advertise complete; reason=%d",
  279. event->adv_complete.reason);
  280. #if !CONFIG_EXAMPLE_EXTENDED_ADV
  281. bleprph_advertise();
  282. #endif
  283. return 0;
  284. case BLE_GAP_EVENT_PHY_UPDATE_COMPLETE:
  285. MODLOG_DFLT(INFO, "LE PHY Update completed; status=%d conn_handle=%d tx_phy=%d "
  286. "rx_phy = %d\n", event->phy_updated.status,
  287. event->phy_updated.conn_handle, event->phy_updated.tx_phy,
  288. event->phy_updated.rx_phy);
  289. return 0;
  290. }
  291. return 0;
  292. }
  293. static void
  294. bleprph_on_reset(int reason)
  295. {
  296. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  297. }
  298. static void
  299. bleprph_on_sync(void)
  300. {
  301. int rc;
  302. /* Make sure we have proper identity address set (public preferred) */
  303. rc = ble_hs_util_ensure_addr(0);
  304. assert(rc == 0);
  305. /* Figure out address to use while advertising (no privacy for now) */
  306. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  307. if (rc != 0) {
  308. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  309. return;
  310. }
  311. /* Printing ADDR */
  312. uint8_t addr_val[6] = {0};
  313. rc = ble_hs_id_copy_addr(own_addr_type, addr_val, NULL);
  314. MODLOG_DFLT(INFO, "Device Address: ");
  315. print_addr(addr_val);
  316. MODLOG_DFLT(INFO, "\n");
  317. s_current_phy = BLE_HCI_LE_PHY_1M_PREF_MASK;
  318. /* Begin advertising. */
  319. #if CONFIG_EXAMPLE_EXTENDED_ADV
  320. ext_bleprph_advertise();
  321. #else
  322. bleprph_advertise();
  323. #endif
  324. }
  325. void bleprph_host_task(void *param)
  326. {
  327. ESP_LOGI(tag, "BLE Host Task Started");
  328. /* This function will return only when nimble_port_stop() is executed */
  329. nimble_port_run();
  330. nimble_port_freertos_deinit();
  331. }
  332. void
  333. app_main(void)
  334. {
  335. int rc;
  336. /* Initialize NVS — it is used to store PHY calibration data */
  337. esp_err_t ret = nvs_flash_init();
  338. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  339. ESP_ERROR_CHECK(nvs_flash_erase());
  340. ret = nvs_flash_init();
  341. }
  342. ESP_ERROR_CHECK(ret);
  343. //ESP_ERROR_CHECK(esp_nimble_hci_and_controller_init());
  344. ret = nimble_port_init();
  345. if (ret != ESP_OK) {
  346. MODLOG_DFLT(ERROR, "Failed to init nimble %d \n", ret);
  347. return;
  348. }
  349. /* Initialize the NimBLE host configuration. */
  350. ble_hs_cfg.reset_cb = bleprph_on_reset;
  351. ble_hs_cfg.sync_cb = bleprph_on_sync;
  352. ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
  353. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  354. ble_hs_cfg.sm_io_cap = CONFIG_EXAMPLE_IO_TYPE;
  355. #ifdef CONFIG_EXAMPLE_BONDING
  356. ble_hs_cfg.sm_bonding = 1;
  357. #endif
  358. #ifdef CONFIG_EXAMPLE_MITM
  359. ble_hs_cfg.sm_mitm = 1;
  360. #endif
  361. #ifdef CONFIG_EXAMPLE_USE_SC
  362. ble_hs_cfg.sm_sc = 1;
  363. #else
  364. ble_hs_cfg.sm_sc = 0;
  365. #endif
  366. #ifdef CONFIG_EXAMPLE_BONDING
  367. ble_hs_cfg.sm_our_key_dist = 1;
  368. ble_hs_cfg.sm_their_key_dist = 1;
  369. #endif
  370. rc = gatt_svr_init_le_phy();
  371. assert(rc == 0);
  372. /* Set the default device name. */
  373. rc = ble_svc_gap_device_name_set("bleprph-phy");
  374. assert(rc == 0);
  375. /* XXX Need to have template for store */
  376. ble_store_config_init();
  377. nimble_port_freertos_init(bleprph_host_task);
  378. /* Initialize command line interface to accept input from user */
  379. rc = scli_init();
  380. if (rc != ESP_OK) {
  381. ESP_LOGE(tag, "scli_init() failed");
  382. }
  383. }