main.c 13 KB

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