main.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.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 "multi_adv.h"
  16. static const char *tag = "NimBLE_MULTI_ADV";
  17. static int ble_multi_adv_gap_event(struct ble_gap_event *event, void *arg);
  18. static uint8_t own_addr_type = BLE_OWN_ADDR_RANDOM;
  19. struct ble_instance_cb_register ble_instance_cb[BLE_ADV_INSTANCES];
  20. void ble_store_config_init(void);
  21. static int ble_connectable_ext_cb(uint16_t instance);
  22. static int ble_scannable_legacy_ext_cb(uint16_t instance);
  23. static int ble_legacy_duration_cb(uint16_t instance);
  24. static int ble_non_conn_ext_cb(uint16_t instance);
  25. static void ble_multi_advertise(ble_addr_t addr);
  26. /* Advertising patterns */
  27. static uint8_t legacy_dur_adv_pattern[] = {
  28. 0x02, 0x01, 0x06,
  29. 0x03, 0x03, 0xab, 0xcd,
  30. 0x03, 0x03, 0x18, 0x11,
  31. 0x12, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 'l', 'e', 'g', 'a', 'c', 'y', '-', 'd', 'u',
  32. 'r'
  33. };
  34. static uint8_t scannable_legacy_adv_pattern[] = {
  35. 0x02, 0x01, 0x06,
  36. 0x03, 0x03, 0xab, 0xcd,
  37. 0x03, 0x03, 0x18, 0x11,
  38. 0x13, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 's', 'c', 'a', 'n', '-', 'l', 'e', 'g', 'a',
  39. 'c', 'y'
  40. };
  41. static uint8_t connectable_adv_pattern[] = {
  42. 0x02, 0x01, 0x06,
  43. 0x03, 0x03, 0xab, 0xcd,
  44. 0x03, 0x03, 0x18, 0x11,
  45. 0x12, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 'c', 'o', 'n', 'n', 'e', 't', 'a', 'b', 'l', 'e'
  46. };
  47. static uint8_t non_conn_adv_pattern[] = {
  48. 0x02, 0x01, 0x06,
  49. 0x03, 0x03, 0xab, 0xcd,
  50. 0x03, 0x03, 0x18, 0x11,
  51. 0x10, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 'n', 'o', 'n', '-', 'c', 'o', 'n', 'n'
  52. };
  53. /**
  54. * Logs information about a connection to the console.
  55. */
  56. static void
  57. ble_multi_adv_print_conn_desc(struct ble_gap_conn_desc *desc)
  58. {
  59. MODLOG_DFLT(INFO, "handle=%d our_ota_addr_type=%d our_ota_addr=",
  60. desc->conn_handle, desc->our_ota_addr.type);
  61. print_addr(desc->our_ota_addr.val);
  62. MODLOG_DFLT(INFO, " our_id_addr_type=%d our_id_addr=",
  63. desc->our_id_addr.type);
  64. print_addr(desc->our_id_addr.val);
  65. MODLOG_DFLT(INFO, " peer_ota_addr_type=%d peer_ota_addr=",
  66. desc->peer_ota_addr.type);
  67. print_addr(desc->peer_ota_addr.val);
  68. MODLOG_DFLT(INFO, " peer_id_addr_type=%d peer_id_addr=",
  69. desc->peer_id_addr.type);
  70. print_addr(desc->peer_id_addr.val);
  71. MODLOG_DFLT(INFO, " conn_itvl=%d conn_latency=%d supervision_timeout=%d "
  72. "encrypted=%d authenticated=%d bonded=%d\n",
  73. desc->conn_itvl, desc->conn_latency,
  74. desc->supervision_timeout,
  75. desc->sec_state.encrypted,
  76. desc->sec_state.authenticated,
  77. desc->sec_state.bonded);
  78. }
  79. /* Generates and sets random address */
  80. static int
  81. ble_multi_adv_set_addr(uint16_t instance)
  82. {
  83. ble_addr_t addr;
  84. int rc;
  85. /* generate new non-resolvable private address */
  86. rc = ble_hs_id_gen_rnd(1, &addr);
  87. if (rc != 0) {
  88. return rc;
  89. }
  90. /* Set generated address */
  91. rc = ble_gap_ext_adv_set_addr(instance, &addr);
  92. if (rc != 0) {
  93. return rc;
  94. }
  95. memcpy(&ble_instance_cb[instance].addr, &addr, sizeof(addr));
  96. return 0;
  97. }
  98. /* Configures extended advertsing params*/
  99. static void
  100. ble_multi_adv_conf_set_addr(uint16_t instance, struct ble_gap_ext_adv_params *params,
  101. uint8_t *pattern, int size_pattern, int duration)
  102. {
  103. int rc;
  104. struct os_mbuf *data;
  105. if (ble_gap_ext_adv_active(instance)) {
  106. ESP_LOGI(tag, "Instance already advertising");
  107. return;
  108. }
  109. rc = ble_gap_ext_adv_configure(instance, params, NULL,
  110. ble_multi_adv_gap_event, NULL);
  111. assert (rc == 0);
  112. rc = ble_multi_adv_set_addr(instance);
  113. assert (rc == 0);
  114. /* get mbuf for adv data */
  115. data = os_msys_get_pkthdr(size_pattern, 0);
  116. assert(data);
  117. /* fill mbuf with adv data */
  118. rc = os_mbuf_append(data, pattern, size_pattern);
  119. assert(rc == 0);
  120. rc = ble_gap_ext_adv_set_data(instance, data);
  121. assert (rc == 0);
  122. /* start advertising */
  123. rc = ble_gap_ext_adv_start(instance, duration, 0);
  124. assert (rc == 0);
  125. ESP_LOGI(tag, "Instance %d started", instance);
  126. }
  127. /* Starts advertising instance with 5sec timeout */
  128. static void
  129. start_legacy_duration(void)
  130. {
  131. uint8_t instance = 3;
  132. int duration = 500; /* 5seconds, 10ms units */
  133. struct ble_gap_ext_adv_params params;
  134. int size_pattern = sizeof(legacy_dur_adv_pattern) / sizeof(legacy_dur_adv_pattern[0]);
  135. memset (&params, 0, sizeof(params));
  136. params.legacy_pdu = 1;
  137. params.own_addr_type = BLE_OWN_ADDR_RANDOM;
  138. params.sid = 3;
  139. params.primary_phy = BLE_HCI_LE_PHY_1M;
  140. params.secondary_phy = BLE_HCI_LE_PHY_1M;
  141. params.tx_power = 127;
  142. ble_multi_adv_conf_set_addr(instance, &params, legacy_dur_adv_pattern,
  143. size_pattern, duration);
  144. ble_instance_cb[instance].cb = &ble_legacy_duration_cb;
  145. }
  146. /* Starts simple non-connectable scannable instance using legacy PUDs that
  147. * runs forever
  148. */
  149. static void
  150. start_scannable_legacy_ext(void)
  151. {
  152. uint8_t instance = 2;
  153. struct ble_gap_ext_adv_params params;
  154. int size_pattern = sizeof(scannable_legacy_adv_pattern)/sizeof(scannable_legacy_adv_pattern[0]);
  155. memset (&params, 0, sizeof(params));
  156. params.legacy_pdu = 1;
  157. params.scannable = 1;
  158. params.own_addr_type = BLE_OWN_ADDR_RANDOM;
  159. params.sid = 2;
  160. params.primary_phy = BLE_HCI_LE_PHY_1M;
  161. params.secondary_phy = BLE_HCI_LE_PHY_1M;
  162. params.tx_power = 127;
  163. ble_multi_adv_conf_set_addr(instance, &params, scannable_legacy_adv_pattern
  164. , size_pattern, 0);
  165. ble_instance_cb[instance].cb = &ble_scannable_legacy_ext_cb;
  166. }
  167. /* this is simple scannable instance that runs forever
  168. * TODO Get scan request notifications.
  169. */
  170. static void
  171. start_connectable_ext(void)
  172. {
  173. uint8_t instance = 1;
  174. struct ble_gap_ext_adv_params params;
  175. int size_pattern = sizeof(connectable_adv_pattern) / sizeof(connectable_adv_pattern[0]);
  176. memset (&params, 0, sizeof(params));
  177. params.connectable = 1;
  178. params.own_addr_type = BLE_OWN_ADDR_RANDOM;
  179. params.sid = 1;
  180. params.primary_phy = BLE_HCI_LE_PHY_1M;
  181. params.secondary_phy = BLE_HCI_LE_PHY_1M;
  182. params.tx_power = 127;
  183. ble_multi_adv_conf_set_addr(instance, &params, connectable_adv_pattern,
  184. size_pattern, 0);
  185. ble_instance_cb[instance].cb = &ble_connectable_ext_cb;
  186. }
  187. /* Starts a connectable instance */
  188. static void
  189. start_non_connectable_ext(void)
  190. {
  191. uint8_t instance = 0;
  192. struct ble_gap_ext_adv_params params;
  193. int size_pattern = sizeof(non_conn_adv_pattern) / sizeof(non_conn_adv_pattern[0]);
  194. memset (&params, 0, sizeof(params));
  195. params.own_addr_type = BLE_OWN_ADDR_RANDOM;
  196. params.sid = 0;
  197. params.primary_phy = BLE_HCI_LE_PHY_1M;
  198. params.secondary_phy = BLE_HCI_LE_PHY_2M;
  199. params.tx_power = 127;
  200. ble_multi_adv_conf_set_addr(instance, &params, non_conn_adv_pattern,
  201. size_pattern, 0);
  202. ble_instance_cb[instance].cb = &ble_non_conn_ext_cb;
  203. }
  204. /* Callbacks */
  205. static int
  206. ble_connectable_ext_cb(uint16_t instance)
  207. {
  208. ESP_LOGI(tag, "In %s, instance = %d", __func__, instance);
  209. return 0;
  210. }
  211. static int
  212. ble_scannable_legacy_ext_cb(uint16_t instance)
  213. {
  214. ESP_LOGI(tag, "In %s, instance = %d", __func__, instance);
  215. return 0;
  216. }
  217. static int
  218. ble_legacy_duration_cb(uint16_t instance)
  219. {
  220. ESP_LOGI(tag, "In %s, instance = %d", __func__, instance);
  221. return 0;
  222. }
  223. static int
  224. ble_non_conn_ext_cb(uint16_t instance)
  225. {
  226. ESP_LOGI(tag, "In %s, instance = %d", __func__, instance);
  227. return 0;
  228. }
  229. /* Finds instance associated with the random address passed and calls its callback function */
  230. static void
  231. ble_multi_advertise(ble_addr_t addr)
  232. {
  233. for (int i = 0; i < BLE_ADV_INSTANCES; i++) {
  234. if (memcmp(&addr, &ble_instance_cb[i].addr, sizeof(addr)) == 0) {
  235. switch(i) {
  236. case 0:
  237. start_non_connectable_ext();
  238. break;
  239. case 1:
  240. start_connectable_ext();
  241. break;
  242. case 2:
  243. start_scannable_legacy_ext();
  244. break;
  245. case 3:
  246. start_legacy_duration();
  247. break;
  248. default:
  249. ESP_LOGI(tag, "Instance not found");
  250. }
  251. }
  252. }
  253. }
  254. static void
  255. ble_multi_perform_gatt_proc(ble_addr_t addr)
  256. {
  257. /* GATT procedures like notify, indicate can be perfomed now */
  258. for (int i = 0; i < BLE_ADV_INSTANCES; i++) {
  259. if (memcmp(&addr, &ble_instance_cb[i].addr, sizeof(addr)) == 0) {
  260. if (ble_instance_cb[i].cb) {
  261. ble_instance_cb[i].cb(i);
  262. }
  263. }
  264. }
  265. return;
  266. }
  267. /**
  268. * The nimble host executes this callback when a GAP event occurs. The
  269. * application associates a GAP event callback with each connection that forms.
  270. * bleprph uses the same callback for all connections.
  271. *
  272. * @param event The type of event being signalled.
  273. * @param ctxt Various information pertaining to the event.
  274. * @param arg Application-specified argument; unused by
  275. * bleprph.
  276. *
  277. * @return 0 if the application successfully handled the
  278. * event; nonzero on failure. The semantics
  279. * of the return code is specific to the
  280. * particular GAP event being signalled.
  281. */
  282. static int
  283. ble_multi_adv_gap_event(struct ble_gap_event *event, void *arg)
  284. {
  285. struct ble_gap_conn_desc desc;
  286. int rc;
  287. switch (event->type) {
  288. case BLE_GAP_EVENT_CONNECT:
  289. /* A new connection was established or a connection attempt failed. */
  290. MODLOG_DFLT(INFO, "connection %s; status=%d ",
  291. event->connect.status == 0 ? "established" : "failed",
  292. event->connect.status);
  293. if (event->connect.status == 0) {
  294. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  295. assert(rc == 0);
  296. ble_multi_adv_print_conn_desc(&desc);
  297. ble_multi_perform_gatt_proc(desc.our_id_addr);
  298. }
  299. MODLOG_DFLT(INFO, "\n");
  300. return 0;
  301. case BLE_GAP_EVENT_DISCONNECT:
  302. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  303. ble_multi_adv_print_conn_desc(&event->disconnect.conn);
  304. MODLOG_DFLT(INFO, "\n");
  305. return 0;
  306. case BLE_GAP_EVENT_CONN_UPDATE:
  307. /* The central has updated the connection parameters. */
  308. MODLOG_DFLT(INFO, "connection updated; status=%d ",
  309. event->conn_update.status);
  310. rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
  311. assert(rc == 0);
  312. ble_multi_adv_print_conn_desc(&desc);
  313. MODLOG_DFLT(INFO, "\n");
  314. return 0;
  315. case BLE_GAP_EVENT_ADV_COMPLETE:
  316. MODLOG_DFLT(INFO, "advertise complete; reason=%d",
  317. event->adv_complete.reason);
  318. ble_multi_advertise(ble_instance_cb[event->adv_complete.instance].addr);
  319. return 0;
  320. case BLE_GAP_EVENT_ENC_CHANGE:
  321. /* Encryption has been enabled or disabled for this connection. */
  322. MODLOG_DFLT(INFO, "encryption change event; status=%d ",
  323. event->enc_change.status);
  324. rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
  325. assert(rc == 0);
  326. ble_multi_adv_print_conn_desc(&desc);
  327. MODLOG_DFLT(INFO, "\n");
  328. return 0;
  329. case BLE_GAP_EVENT_NOTIFY_TX:
  330. MODLOG_DFLT(INFO, "notify_tx event; conn_handle=%d attr_handle=%d "
  331. "status=%d is_indication=%d",
  332. event->notify_tx.conn_handle,
  333. event->notify_tx.attr_handle,
  334. event->notify_tx.status,
  335. event->notify_tx.indication);
  336. return 0;
  337. case BLE_GAP_EVENT_SUBSCRIBE:
  338. MODLOG_DFLT(INFO, "subscribe event; conn_handle=%d attr_handle=%d "
  339. "reason=%d prevn=%d curn=%d previ=%d curi=%d\n",
  340. event->subscribe.conn_handle,
  341. event->subscribe.attr_handle,
  342. event->subscribe.reason,
  343. event->subscribe.prev_notify,
  344. event->subscribe.cur_notify,
  345. event->subscribe.prev_indicate,
  346. event->subscribe.cur_indicate);
  347. return 0;
  348. case BLE_GAP_EVENT_MTU:
  349. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  350. event->mtu.conn_handle,
  351. event->mtu.channel_id,
  352. event->mtu.value);
  353. return 0;
  354. }
  355. return 0;
  356. }
  357. static void
  358. ble_multi_adv_on_reset(int reason)
  359. {
  360. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  361. }
  362. static void
  363. ble_multi_adv_on_sync(void)
  364. {
  365. int rc;
  366. rc = ble_hs_util_ensure_addr(0);
  367. assert(rc == 0);
  368. /* Figure out address to use while advertising (no privacy for now) */
  369. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  370. if (rc != 0) {
  371. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  372. return;
  373. }
  374. start_non_connectable_ext();
  375. start_connectable_ext();
  376. start_scannable_legacy_ext();
  377. start_legacy_duration();
  378. }
  379. void ble_multi_adv_host_task(void *param)
  380. {
  381. ESP_LOGI(tag, "BLE Host Task Started");
  382. /* This function will return only when nimble_port_stop() is executed */
  383. nimble_port_run();
  384. nimble_port_freertos_deinit();
  385. }
  386. void
  387. app_main(void)
  388. {
  389. int rc;
  390. /* Initialize NVS — it is used to store PHY calibration data */
  391. esp_err_t ret = nvs_flash_init();
  392. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  393. ESP_ERROR_CHECK(nvs_flash_erase());
  394. ret = nvs_flash_init();
  395. }
  396. ESP_ERROR_CHECK(ret);
  397. ret = nimble_port_init();
  398. if (ret != ESP_OK) {
  399. ESP_LOGE(tag, "Failed to init nimble %d ", ret);
  400. return;
  401. }
  402. /* Initialize the NimBLE host configuration. */
  403. ble_hs_cfg.reset_cb = ble_multi_adv_on_reset;
  404. ble_hs_cfg.sync_cb = ble_multi_adv_on_sync;
  405. ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
  406. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  407. ble_hs_cfg.sm_bonding = 1;
  408. ble_hs_cfg.sm_mitm = 1;
  409. ble_hs_cfg.sm_sc = 1;
  410. ble_hs_cfg.sm_sc = 0;
  411. /* Enable the appropriate bit masks to make sure the keys
  412. * that are needed are exchanged
  413. */
  414. ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC;
  415. ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC;
  416. /* Initialize callbacks to NULL */
  417. for (int i = 0; i < BLE_ADV_INSTANCES; i++) {
  418. ble_instance_cb[i].cb = NULL;
  419. }
  420. rc = gatt_svr_init();
  421. assert(rc == 0);
  422. /* Set the default device name. */
  423. rc = ble_svc_gap_device_name_set("nimble-multi-adv");
  424. assert(rc == 0);
  425. /* XXX Need to have template for store */
  426. ble_store_config_init();
  427. nimble_port_freertos_init(ble_multi_adv_host_task);
  428. }