main.c 15 KB

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