main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. #include "esp_log.h"
  20. #include "nvs_flash.h"
  21. /* BLE */
  22. #include "nimble/nimble_port.h"
  23. #include "nimble/nimble_port_freertos.h"
  24. #include "host/ble_hs.h"
  25. #include "host/util/util.h"
  26. #include "console/console.h"
  27. #include "services/gap/ble_svc_gap.h"
  28. #include "bleprph.h"
  29. #if CONFIG_EXAMPLE_EXTENDED_ADV
  30. static uint8_t ext_adv_pattern_1[] = {
  31. 0x02, 0x01, 0x06,
  32. 0x03, 0x03, 0xab, 0xcd,
  33. 0x03, 0x03, 0x18, 0x11,
  34. 0x11, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 'b', 'l', 'e', 'p', 'r', 'p', 'h', '-', 'e',
  35. };
  36. #endif
  37. static const char *tag = "NimBLE_BLE_PRPH";
  38. static int bleprph_gap_event(struct ble_gap_event *event, void *arg);
  39. #if CONFIG_EXAMPLE_RANDOM_ADDR
  40. static uint8_t own_addr_type = BLE_OWN_ADDR_RANDOM;
  41. #else
  42. static uint8_t own_addr_type;
  43. #endif
  44. void ble_store_config_init(void);
  45. /**
  46. * Logs information about a connection to the console.
  47. */
  48. static void
  49. bleprph_print_conn_desc(struct ble_gap_conn_desc *desc)
  50. {
  51. MODLOG_DFLT(INFO, "handle=%d our_ota_addr_type=%d our_ota_addr=",
  52. desc->conn_handle, desc->our_ota_addr.type);
  53. print_addr(desc->our_ota_addr.val);
  54. MODLOG_DFLT(INFO, " our_id_addr_type=%d our_id_addr=",
  55. desc->our_id_addr.type);
  56. print_addr(desc->our_id_addr.val);
  57. MODLOG_DFLT(INFO, " peer_ota_addr_type=%d peer_ota_addr=",
  58. desc->peer_ota_addr.type);
  59. print_addr(desc->peer_ota_addr.val);
  60. MODLOG_DFLT(INFO, " peer_id_addr_type=%d peer_id_addr=",
  61. desc->peer_id_addr.type);
  62. print_addr(desc->peer_id_addr.val);
  63. MODLOG_DFLT(INFO, " conn_itvl=%d conn_latency=%d supervision_timeout=%d "
  64. "encrypted=%d authenticated=%d bonded=%d\n",
  65. desc->conn_itvl, desc->conn_latency,
  66. desc->supervision_timeout,
  67. desc->sec_state.encrypted,
  68. desc->sec_state.authenticated,
  69. desc->sec_state.bonded);
  70. }
  71. #if CONFIG_EXAMPLE_EXTENDED_ADV
  72. /**
  73. * Enables advertising with the following parameters:
  74. * o General discoverable mode.
  75. * o Undirected connectable mode.
  76. */
  77. static void
  78. ext_bleprph_advertise(void)
  79. {
  80. struct ble_gap_ext_adv_params params;
  81. struct os_mbuf *data;
  82. uint8_t instance = 1;
  83. int rc;
  84. /* use defaults for non-set params */
  85. memset (&params, 0, sizeof(params));
  86. /* enable connectable advertising */
  87. params.connectable = 1;
  88. params.scannable = 1;
  89. params.legacy_pdu = 1;
  90. /* advertise using random addr */
  91. params.own_addr_type = BLE_OWN_ADDR_PUBLIC;
  92. params.primary_phy = BLE_HCI_LE_PHY_1M;
  93. params.secondary_phy = BLE_HCI_LE_PHY_2M;
  94. //params.tx_power = 127;
  95. params.sid = 1;
  96. params.itvl_min = BLE_GAP_ADV_FAST_INTERVAL1_MIN;
  97. params.itvl_max = BLE_GAP_ADV_FAST_INTERVAL1_MIN;
  98. /* configure instance 0 */
  99. rc = ble_gap_ext_adv_configure(instance, &params, NULL,
  100. bleprph_gap_event, NULL);
  101. assert (rc == 0);
  102. /* in this case only scan response is allowed */
  103. /* get mbuf for scan rsp data */
  104. data = os_msys_get_pkthdr(sizeof(ext_adv_pattern_1), 0);
  105. assert(data);
  106. /* fill mbuf with scan rsp data */
  107. rc = os_mbuf_append(data, ext_adv_pattern_1, sizeof(ext_adv_pattern_1));
  108. assert(rc == 0);
  109. rc = ble_gap_ext_adv_set_data(instance, data);
  110. assert (rc == 0);
  111. /* start advertising */
  112. rc = ble_gap_ext_adv_start(instance, 0, 0);
  113. assert (rc == 0);
  114. }
  115. #else
  116. /**
  117. * Enables advertising with the following parameters:
  118. * o General discoverable mode.
  119. * o Undirected connectable mode.
  120. */
  121. static void
  122. bleprph_advertise(void)
  123. {
  124. struct ble_gap_adv_params adv_params;
  125. struct ble_hs_adv_fields fields;
  126. const char *name;
  127. int rc;
  128. /**
  129. * Set the advertisement data included in our advertisements:
  130. * o Flags (indicates advertisement type and other general info).
  131. * o Advertising tx power.
  132. * o Device name.
  133. * o 16-bit service UUIDs (alert notifications).
  134. */
  135. memset(&fields, 0, sizeof fields);
  136. /* Advertise two flags:
  137. * o Discoverability in forthcoming advertisement (general)
  138. * o BLE-only (BR/EDR unsupported).
  139. */
  140. fields.flags = BLE_HS_ADV_F_DISC_GEN |
  141. BLE_HS_ADV_F_BREDR_UNSUP;
  142. /* Indicate that the TX power level field should be included; have the
  143. * stack fill this value automatically. This is done by assigning the
  144. * special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
  145. */
  146. fields.tx_pwr_lvl_is_present = 1;
  147. fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
  148. name = ble_svc_gap_device_name();
  149. fields.name = (uint8_t *)name;
  150. fields.name_len = strlen(name);
  151. fields.name_is_complete = 1;
  152. fields.uuids16 = (ble_uuid16_t[]) {
  153. BLE_UUID16_INIT(GATT_SVR_SVC_ALERT_UUID)
  154. };
  155. fields.num_uuids16 = 1;
  156. fields.uuids16_is_complete = 1;
  157. rc = ble_gap_adv_set_fields(&fields);
  158. if (rc != 0) {
  159. MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc);
  160. return;
  161. }
  162. /* Begin advertising. */
  163. memset(&adv_params, 0, sizeof adv_params);
  164. adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
  165. adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
  166. rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
  167. &adv_params, bleprph_gap_event, NULL);
  168. if (rc != 0) {
  169. MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc);
  170. return;
  171. }
  172. }
  173. #endif
  174. /**
  175. * The nimble host executes this callback when a GAP event occurs. The
  176. * application associates a GAP event callback with each connection that forms.
  177. * bleprph uses the same callback for all connections.
  178. *
  179. * @param event The type of event being signalled.
  180. * @param ctxt Various information pertaining to the event.
  181. * @param arg Application-specified argument; unused by
  182. * bleprph.
  183. *
  184. * @return 0 if the application successfully handled the
  185. * event; nonzero on failure. The semantics
  186. * of the return code is specific to the
  187. * particular GAP event being signalled.
  188. */
  189. static int
  190. bleprph_gap_event(struct ble_gap_event *event, void *arg)
  191. {
  192. struct ble_gap_conn_desc desc;
  193. int rc;
  194. switch (event->type) {
  195. case BLE_GAP_EVENT_CONNECT:
  196. /* A new connection was established or a connection attempt failed. */
  197. MODLOG_DFLT(INFO, "connection %s; status=%d ",
  198. event->connect.status == 0 ? "established" : "failed",
  199. event->connect.status);
  200. if (event->connect.status == 0) {
  201. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  202. assert(rc == 0);
  203. bleprph_print_conn_desc(&desc);
  204. }
  205. MODLOG_DFLT(INFO, "\n");
  206. if (event->connect.status != 0) {
  207. /* Connection failed; resume advertising. */
  208. #if CONFIG_EXAMPLE_EXTENDED_ADV
  209. ext_bleprph_advertise();
  210. #else
  211. bleprph_advertise();
  212. #endif
  213. }
  214. return 0;
  215. case BLE_GAP_EVENT_DISCONNECT:
  216. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  217. bleprph_print_conn_desc(&event->disconnect.conn);
  218. MODLOG_DFLT(INFO, "\n");
  219. /* Connection terminated; resume advertising. */
  220. #if CONFIG_EXAMPLE_EXTENDED_ADV
  221. ext_bleprph_advertise();
  222. #else
  223. bleprph_advertise();
  224. #endif
  225. return 0;
  226. case BLE_GAP_EVENT_CONN_UPDATE:
  227. /* The central has updated the connection parameters. */
  228. MODLOG_DFLT(INFO, "connection updated; status=%d ",
  229. event->conn_update.status);
  230. rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
  231. assert(rc == 0);
  232. bleprph_print_conn_desc(&desc);
  233. MODLOG_DFLT(INFO, "\n");
  234. return 0;
  235. case BLE_GAP_EVENT_ADV_COMPLETE:
  236. MODLOG_DFLT(INFO, "advertise complete; reason=%d",
  237. event->adv_complete.reason);
  238. #if !CONFIG_EXAMPLE_EXTENDED_ADV
  239. bleprph_advertise();
  240. #endif
  241. return 0;
  242. case BLE_GAP_EVENT_ENC_CHANGE:
  243. /* Encryption has been enabled or disabled for this connection. */
  244. MODLOG_DFLT(INFO, "encryption change event; status=%d ",
  245. event->enc_change.status);
  246. rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
  247. assert(rc == 0);
  248. bleprph_print_conn_desc(&desc);
  249. MODLOG_DFLT(INFO, "\n");
  250. return 0;
  251. case BLE_GAP_EVENT_SUBSCRIBE:
  252. MODLOG_DFLT(INFO, "subscribe event; conn_handle=%d attr_handle=%d "
  253. "reason=%d prevn=%d curn=%d previ=%d curi=%d\n",
  254. event->subscribe.conn_handle,
  255. event->subscribe.attr_handle,
  256. event->subscribe.reason,
  257. event->subscribe.prev_notify,
  258. event->subscribe.cur_notify,
  259. event->subscribe.prev_indicate,
  260. event->subscribe.cur_indicate);
  261. return 0;
  262. case BLE_GAP_EVENT_MTU:
  263. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  264. event->mtu.conn_handle,
  265. event->mtu.channel_id,
  266. event->mtu.value);
  267. return 0;
  268. case BLE_GAP_EVENT_REPEAT_PAIRING:
  269. /* We already have a bond with the peer, but it is attempting to
  270. * establish a new secure link. This app sacrifices security for
  271. * convenience: just throw away the old bond and accept the new link.
  272. */
  273. /* Delete the old bond. */
  274. rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
  275. assert(rc == 0);
  276. ble_store_util_delete_peer(&desc.peer_id_addr);
  277. /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
  278. * continue with the pairing operation.
  279. */
  280. return BLE_GAP_REPEAT_PAIRING_RETRY;
  281. case BLE_GAP_EVENT_PASSKEY_ACTION:
  282. ESP_LOGI(tag, "PASSKEY_ACTION_EVENT started \n");
  283. struct ble_sm_io pkey = {0};
  284. int key = 0;
  285. if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
  286. pkey.action = event->passkey.params.action;
  287. pkey.passkey = 123456; // This is the passkey to be entered on peer
  288. ESP_LOGI(tag, "Enter passkey %d on the peer side", pkey.passkey);
  289. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  290. ESP_LOGI(tag, "ble_sm_inject_io result: %d\n", rc);
  291. } else if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) {
  292. ESP_LOGI(tag, "Passkey on device's display: %d", event->passkey.params.numcmp);
  293. ESP_LOGI(tag, "Accept or reject the passkey through console in this format -> key Y or key N");
  294. pkey.action = event->passkey.params.action;
  295. if (scli_receive_key(&key)) {
  296. pkey.numcmp_accept = key;
  297. } else {
  298. pkey.numcmp_accept = 0;
  299. ESP_LOGE(tag, "Timeout! Rejecting the key");
  300. }
  301. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  302. ESP_LOGI(tag, "ble_sm_inject_io result: %d\n", rc);
  303. } else if (event->passkey.params.action == BLE_SM_IOACT_OOB) {
  304. static uint8_t tem_oob[16] = {0};
  305. pkey.action = event->passkey.params.action;
  306. for (int i = 0; i < 16; i++) {
  307. pkey.oob[i] = tem_oob[i];
  308. }
  309. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  310. ESP_LOGI(tag, "ble_sm_inject_io result: %d\n", rc);
  311. } else if (event->passkey.params.action == BLE_SM_IOACT_INPUT) {
  312. ESP_LOGI(tag, "Enter the passkey through console in this format-> key 123456");
  313. pkey.action = event->passkey.params.action;
  314. if (scli_receive_key(&key)) {
  315. pkey.passkey = key;
  316. } else {
  317. pkey.passkey = 0;
  318. ESP_LOGE(tag, "Timeout! Passing 0 as the key");
  319. }
  320. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  321. ESP_LOGI(tag, "ble_sm_inject_io result: %d\n", rc);
  322. }
  323. return 0;
  324. }
  325. return 0;
  326. }
  327. static void
  328. bleprph_on_reset(int reason)
  329. {
  330. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  331. }
  332. #if CONFIG_EXAMPLE_RANDOM_ADDR
  333. static void
  334. ble_app_set_addr(void)
  335. {
  336. ble_addr_t addr;
  337. int rc;
  338. /* generate new non-resolvable private address */
  339. rc = ble_hs_id_gen_rnd(0, &addr);
  340. assert(rc == 0);
  341. /* set generated address */
  342. rc = ble_hs_id_set_rnd(addr.val);
  343. assert(rc == 0);
  344. }
  345. #endif
  346. static void
  347. bleprph_on_sync(void)
  348. {
  349. int rc;
  350. #if CONFIG_EXAMPLE_RANDOM_ADDR
  351. /* Generate a non-resolvable private address. */
  352. ble_app_set_addr();
  353. #endif
  354. /* Make sure we have proper identity address set (public preferred) */
  355. #if CONFIG_EXAMPLE_RANDOM_ADDR
  356. rc = ble_hs_util_ensure_addr(1);
  357. #else
  358. rc = ble_hs_util_ensure_addr(0);
  359. #endif
  360. assert(rc == 0);
  361. /* Figure out address to use while advertising (no privacy for now) */
  362. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  363. if (rc != 0) {
  364. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  365. return;
  366. }
  367. /* Printing ADDR */
  368. uint8_t addr_val[6] = {0};
  369. rc = ble_hs_id_copy_addr(own_addr_type, addr_val, NULL);
  370. MODLOG_DFLT(INFO, "Device Address: ");
  371. print_addr(addr_val);
  372. MODLOG_DFLT(INFO, "\n");
  373. /* Begin advertising. */
  374. #if CONFIG_EXAMPLE_EXTENDED_ADV
  375. ext_bleprph_advertise();
  376. #else
  377. bleprph_advertise();
  378. #endif
  379. }
  380. void bleprph_host_task(void *param)
  381. {
  382. ESP_LOGI(tag, "BLE Host Task Started");
  383. /* This function will return only when nimble_port_stop() is executed */
  384. nimble_port_run();
  385. nimble_port_freertos_deinit();
  386. }
  387. void
  388. app_main(void)
  389. {
  390. int rc;
  391. /* Initialize NVS — it is used to store PHY calibration data */
  392. esp_err_t ret = nvs_flash_init();
  393. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  394. ESP_ERROR_CHECK(nvs_flash_erase());
  395. ret = nvs_flash_init();
  396. }
  397. ESP_ERROR_CHECK(ret);
  398. nimble_port_init();
  399. /* Initialize the NimBLE host configuration. */
  400. ble_hs_cfg.reset_cb = bleprph_on_reset;
  401. ble_hs_cfg.sync_cb = bleprph_on_sync;
  402. ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
  403. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  404. ble_hs_cfg.sm_io_cap = CONFIG_EXAMPLE_IO_TYPE;
  405. #ifdef CONFIG_EXAMPLE_BONDING
  406. ble_hs_cfg.sm_bonding = 1;
  407. #endif
  408. #ifdef CONFIG_EXAMPLE_MITM
  409. ble_hs_cfg.sm_mitm = 1;
  410. #endif
  411. #ifdef CONFIG_EXAMPLE_USE_SC
  412. ble_hs_cfg.sm_sc = 1;
  413. #else
  414. ble_hs_cfg.sm_sc = 0;
  415. #endif
  416. #ifdef CONFIG_EXAMPLE_BONDING
  417. ble_hs_cfg.sm_our_key_dist = 1;
  418. ble_hs_cfg.sm_their_key_dist = 1;
  419. #endif
  420. rc = gatt_svr_init();
  421. assert(rc == 0);
  422. /* Set the default device name. */
  423. rc = ble_svc_gap_device_name_set("nimble-bleprph");
  424. assert(rc == 0);
  425. /* XXX Need to have template for store */
  426. ble_store_config_init();
  427. nimble_port_freertos_init(bleprph_host_task);
  428. /* Initialize command line interface to accept input from user */
  429. rc = scli_init();
  430. if (rc != ESP_OK) {
  431. ESP_LOGE(tag, "scli_init() failed");
  432. }
  433. }