main.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 = 0;
  83. int rc;
  84. /* First check if any instance is already active */
  85. if(ble_gap_ext_adv_active(instance)) {
  86. return;
  87. }
  88. /* use defaults for non-set params */
  89. memset (&params, 0, sizeof(params));
  90. /* enable connectable advertising */
  91. params.connectable = 1;
  92. /* advertise using random addr */
  93. params.own_addr_type = BLE_OWN_ADDR_PUBLIC;
  94. params.primary_phy = BLE_HCI_LE_PHY_1M;
  95. params.secondary_phy = BLE_HCI_LE_PHY_2M;
  96. //params.tx_power = 127;
  97. params.sid = 1;
  98. params.itvl_min = BLE_GAP_ADV_FAST_INTERVAL1_MIN;
  99. params.itvl_max = BLE_GAP_ADV_FAST_INTERVAL1_MIN;
  100. /* configure instance 0 */
  101. rc = ble_gap_ext_adv_configure(instance, &params, NULL,
  102. bleprph_gap_event, NULL);
  103. assert (rc == 0);
  104. /* in this case only scan response is allowed */
  105. /* get mbuf for scan rsp data */
  106. data = os_msys_get_pkthdr(sizeof(ext_adv_pattern_1), 0);
  107. assert(data);
  108. /* fill mbuf with scan rsp data */
  109. rc = os_mbuf_append(data, ext_adv_pattern_1, sizeof(ext_adv_pattern_1));
  110. assert(rc == 0);
  111. rc = ble_gap_ext_adv_set_data(instance, data);
  112. assert (rc == 0);
  113. /* start advertising */
  114. rc = ble_gap_ext_adv_start(instance, 0, 0);
  115. assert (rc == 0);
  116. }
  117. #else
  118. /**
  119. * Enables advertising with the following parameters:
  120. * o General discoverable mode.
  121. * o Undirected connectable mode.
  122. */
  123. static void
  124. bleprph_advertise(void)
  125. {
  126. struct ble_gap_adv_params adv_params;
  127. struct ble_hs_adv_fields fields;
  128. const char *name;
  129. int rc;
  130. /**
  131. * Set the advertisement data included in our advertisements:
  132. * o Flags (indicates advertisement type and other general info).
  133. * o Advertising tx power.
  134. * o Device name.
  135. * o 16-bit service UUIDs (alert notifications).
  136. */
  137. memset(&fields, 0, sizeof fields);
  138. /* Advertise two flags:
  139. * o Discoverability in forthcoming advertisement (general)
  140. * o BLE-only (BR/EDR unsupported).
  141. */
  142. fields.flags = BLE_HS_ADV_F_DISC_GEN |
  143. BLE_HS_ADV_F_BREDR_UNSUP;
  144. /* Indicate that the TX power level field should be included; have the
  145. * stack fill this value automatically. This is done by assigning the
  146. * special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
  147. */
  148. fields.tx_pwr_lvl_is_present = 1;
  149. fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
  150. name = ble_svc_gap_device_name();
  151. fields.name = (uint8_t *)name;
  152. fields.name_len = strlen(name);
  153. fields.name_is_complete = 1;
  154. fields.uuids16 = (ble_uuid16_t[]) {
  155. BLE_UUID16_INIT(GATT_SVR_SVC_ALERT_UUID)
  156. };
  157. fields.num_uuids16 = 1;
  158. fields.uuids16_is_complete = 1;
  159. rc = ble_gap_adv_set_fields(&fields);
  160. if (rc != 0) {
  161. MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc);
  162. return;
  163. }
  164. /* Begin advertising. */
  165. memset(&adv_params, 0, sizeof adv_params);
  166. adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
  167. adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
  168. rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
  169. &adv_params, bleprph_gap_event, NULL);
  170. if (rc != 0) {
  171. MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc);
  172. return;
  173. }
  174. }
  175. #endif
  176. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  177. static void bleprph_power_control(uint16_t conn_handle)
  178. {
  179. int rc;
  180. rc = ble_gap_read_remote_transmit_power_level(conn_handle, 0x01 ); // Attempting on LE 1M phy
  181. assert (rc == 0);
  182. rc = ble_gap_set_transmit_power_reporting_enable(conn_handle, 0x1, 0x1);
  183. assert (rc == 0);
  184. }
  185. #endif
  186. /**
  187. * The nimble host executes this callback when a GAP event occurs. The
  188. * application associates a GAP event callback with each connection that forms.
  189. * bleprph uses the same callback for all connections.
  190. *
  191. * @param event The type of event being signalled.
  192. * @param ctxt Various information pertaining to the event.
  193. * @param arg Application-specified argument; unused by
  194. * bleprph.
  195. *
  196. * @return 0 if the application successfully handled the
  197. * event; nonzero on failure. The semantics
  198. * of the return code is specific to the
  199. * particular GAP event being signalled.
  200. */
  201. static int
  202. bleprph_gap_event(struct ble_gap_event *event, void *arg)
  203. {
  204. struct ble_gap_conn_desc desc;
  205. int rc;
  206. switch (event->type) {
  207. case BLE_GAP_EVENT_CONNECT:
  208. /* A new connection was established or a connection attempt failed. */
  209. MODLOG_DFLT(INFO, "connection %s; status=%d ",
  210. event->connect.status == 0 ? "established" : "failed",
  211. event->connect.status);
  212. if (event->connect.status == 0) {
  213. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  214. assert(rc == 0);
  215. bleprph_print_conn_desc(&desc);
  216. }
  217. MODLOG_DFLT(INFO, "\n");
  218. if (event->connect.status != 0) {
  219. /* Connection failed; resume advertising. */
  220. #if CONFIG_EXAMPLE_EXTENDED_ADV
  221. ext_bleprph_advertise();
  222. #else
  223. bleprph_advertise();
  224. #endif
  225. }
  226. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  227. bleprph_power_control(event->connect.conn_handle);
  228. #endif
  229. return 0;
  230. case BLE_GAP_EVENT_DISCONNECT:
  231. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  232. bleprph_print_conn_desc(&event->disconnect.conn);
  233. MODLOG_DFLT(INFO, "\n");
  234. /* Connection terminated; resume advertising. */
  235. #if CONFIG_EXAMPLE_EXTENDED_ADV
  236. ext_bleprph_advertise();
  237. #else
  238. bleprph_advertise();
  239. #endif
  240. return 0;
  241. case BLE_GAP_EVENT_CONN_UPDATE:
  242. /* The central has updated the connection parameters. */
  243. MODLOG_DFLT(INFO, "connection updated; status=%d ",
  244. event->conn_update.status);
  245. rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
  246. assert(rc == 0);
  247. bleprph_print_conn_desc(&desc);
  248. MODLOG_DFLT(INFO, "\n");
  249. return 0;
  250. case BLE_GAP_EVENT_ADV_COMPLETE:
  251. MODLOG_DFLT(INFO, "advertise complete; reason=%d",
  252. event->adv_complete.reason);
  253. #if CONFIG_EXAMPLE_EXTENDED_ADV
  254. ext_bleprph_advertise();
  255. #else
  256. bleprph_advertise();
  257. #endif
  258. return 0;
  259. case BLE_GAP_EVENT_ENC_CHANGE:
  260. /* Encryption has been enabled or disabled for this connection. */
  261. MODLOG_DFLT(INFO, "encryption change event; status=%d ",
  262. event->enc_change.status);
  263. rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
  264. assert(rc == 0);
  265. bleprph_print_conn_desc(&desc);
  266. MODLOG_DFLT(INFO, "\n");
  267. return 0;
  268. case BLE_GAP_EVENT_NOTIFY_TX:
  269. MODLOG_DFLT(INFO, "notify_tx event; conn_handle=%d attr_handle=%d "
  270. "status=%d is_indication=%d",
  271. event->notify_tx.conn_handle,
  272. event->notify_tx.attr_handle,
  273. event->notify_tx.status,
  274. event->notify_tx.indication);
  275. return 0;
  276. case BLE_GAP_EVENT_SUBSCRIBE:
  277. MODLOG_DFLT(INFO, "subscribe event; conn_handle=%d attr_handle=%d "
  278. "reason=%d prevn=%d curn=%d previ=%d curi=%d\n",
  279. event->subscribe.conn_handle,
  280. event->subscribe.attr_handle,
  281. event->subscribe.reason,
  282. event->subscribe.prev_notify,
  283. event->subscribe.cur_notify,
  284. event->subscribe.prev_indicate,
  285. event->subscribe.cur_indicate);
  286. return 0;
  287. case BLE_GAP_EVENT_MTU:
  288. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  289. event->mtu.conn_handle,
  290. event->mtu.channel_id,
  291. event->mtu.value);
  292. return 0;
  293. case BLE_GAP_EVENT_REPEAT_PAIRING:
  294. /* We already have a bond with the peer, but it is attempting to
  295. * establish a new secure link. This app sacrifices security for
  296. * convenience: just throw away the old bond and accept the new link.
  297. */
  298. /* Delete the old bond. */
  299. rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
  300. assert(rc == 0);
  301. ble_store_util_delete_peer(&desc.peer_id_addr);
  302. /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
  303. * continue with the pairing operation.
  304. */
  305. return BLE_GAP_REPEAT_PAIRING_RETRY;
  306. case BLE_GAP_EVENT_PASSKEY_ACTION:
  307. ESP_LOGI(tag, "PASSKEY_ACTION_EVENT started");
  308. struct ble_sm_io pkey = {0};
  309. int key = 0;
  310. if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
  311. pkey.action = event->passkey.params.action;
  312. pkey.passkey = 123456; // This is the passkey to be entered on peer
  313. ESP_LOGI(tag, "Enter passkey %" PRIu32 "on the peer side", pkey.passkey);
  314. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  315. ESP_LOGI(tag, "ble_sm_inject_io result: %d", rc);
  316. } else if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) {
  317. ESP_LOGI(tag, "Passkey on device's display: %" PRIu32 , event->passkey.params.numcmp);
  318. ESP_LOGI(tag, "Accept or reject the passkey through console in this format -> key Y or key N");
  319. pkey.action = event->passkey.params.action;
  320. if (scli_receive_key(&key)) {
  321. pkey.numcmp_accept = key;
  322. } else {
  323. pkey.numcmp_accept = 0;
  324. ESP_LOGE(tag, "Timeout! Rejecting the key");
  325. }
  326. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  327. ESP_LOGI(tag, "ble_sm_inject_io result: %d", rc);
  328. } else if (event->passkey.params.action == BLE_SM_IOACT_OOB) {
  329. static uint8_t tem_oob[16] = {0};
  330. pkey.action = event->passkey.params.action;
  331. for (int i = 0; i < 16; i++) {
  332. pkey.oob[i] = tem_oob[i];
  333. }
  334. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  335. ESP_LOGI(tag, "ble_sm_inject_io result: %d", rc);
  336. } else if (event->passkey.params.action == BLE_SM_IOACT_INPUT) {
  337. ESP_LOGI(tag, "Enter the passkey through console in this format-> key 123456");
  338. pkey.action = event->passkey.params.action;
  339. if (scli_receive_key(&key)) {
  340. pkey.passkey = key;
  341. } else {
  342. pkey.passkey = 0;
  343. ESP_LOGE(tag, "Timeout! Passing 0 as the key");
  344. }
  345. rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
  346. ESP_LOGI(tag, "ble_sm_inject_io result: %d", rc);
  347. }
  348. return 0;
  349. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  350. case BLE_GAP_EVENT_TRANSMIT_POWER:
  351. MODLOG_DFLT(INFO, "Transmit power event : status=%d conn_handle=%d reason=%d "
  352. "phy=%d power_level=%x power_level_flag=%d delta=%d",
  353. event->transmit_power.status,
  354. event->transmit_power.conn_handle,
  355. event->transmit_power.reason,
  356. event->transmit_power.phy,
  357. event->transmit_power.transmit_power_level,
  358. event->transmit_power.transmit_power_level_flag,
  359. event->transmit_power.delta);
  360. return 0;
  361. case BLE_GAP_EVENT_PATHLOSS_THRESHOLD:
  362. MODLOG_DFLT(INFO, "Pathloss threshold event : conn_handle=%d current path loss=%d "
  363. "zone_entered =%d",
  364. event->pathloss_threshold.conn_handle,
  365. event->pathloss_threshold.current_path_loss,
  366. event->pathloss_threshold.zone_entered);
  367. return 0;
  368. #endif
  369. }
  370. return 0;
  371. }
  372. static void
  373. bleprph_on_reset(int reason)
  374. {
  375. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  376. }
  377. #if CONFIG_EXAMPLE_RANDOM_ADDR
  378. static void
  379. ble_app_set_addr(void)
  380. {
  381. ble_addr_t addr;
  382. int rc;
  383. /* generate new non-resolvable private address */
  384. rc = ble_hs_id_gen_rnd(0, &addr);
  385. assert(rc == 0);
  386. /* set generated address */
  387. rc = ble_hs_id_set_rnd(addr.val);
  388. assert(rc == 0);
  389. }
  390. #endif
  391. static void
  392. bleprph_on_sync(void)
  393. {
  394. int rc;
  395. #if CONFIG_EXAMPLE_RANDOM_ADDR
  396. /* Generate a non-resolvable private address. */
  397. ble_app_set_addr();
  398. #endif
  399. /* Make sure we have proper identity address set (public preferred) */
  400. #if CONFIG_EXAMPLE_RANDOM_ADDR
  401. rc = ble_hs_util_ensure_addr(1);
  402. #else
  403. rc = ble_hs_util_ensure_addr(0);
  404. #endif
  405. assert(rc == 0);
  406. /* Figure out address to use while advertising (no privacy for now) */
  407. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  408. if (rc != 0) {
  409. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  410. return;
  411. }
  412. /* Printing ADDR */
  413. uint8_t addr_val[6] = {0};
  414. rc = ble_hs_id_copy_addr(own_addr_type, addr_val, NULL);
  415. MODLOG_DFLT(INFO, "Device Address: ");
  416. print_addr(addr_val);
  417. MODLOG_DFLT(INFO, "\n");
  418. /* Begin advertising. */
  419. #if CONFIG_EXAMPLE_EXTENDED_ADV
  420. ext_bleprph_advertise();
  421. #else
  422. bleprph_advertise();
  423. #endif
  424. }
  425. void bleprph_host_task(void *param)
  426. {
  427. ESP_LOGI(tag, "BLE Host Task Started");
  428. /* This function will return only when nimble_port_stop() is executed */
  429. nimble_port_run();
  430. nimble_port_freertos_deinit();
  431. }
  432. void
  433. app_main(void)
  434. {
  435. int rc;
  436. /* Initialize NVS — it is used to store PHY calibration data */
  437. esp_err_t ret = nvs_flash_init();
  438. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  439. ESP_ERROR_CHECK(nvs_flash_erase());
  440. ret = nvs_flash_init();
  441. }
  442. ESP_ERROR_CHECK(ret);
  443. ret = nimble_port_init();
  444. if (ret != ESP_OK) {
  445. ESP_LOGE(tag, "Failed to init nimble %d ", ret);
  446. return;
  447. }
  448. /* Initialize the NimBLE host configuration. */
  449. ble_hs_cfg.reset_cb = bleprph_on_reset;
  450. ble_hs_cfg.sync_cb = bleprph_on_sync;
  451. ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
  452. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  453. ble_hs_cfg.sm_io_cap = CONFIG_EXAMPLE_IO_TYPE;
  454. #ifdef CONFIG_EXAMPLE_BONDING
  455. ble_hs_cfg.sm_bonding = 1;
  456. /* Enable the appropriate bit masks to make sure the keys
  457. * that are needed are exchanged
  458. */
  459. ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC;
  460. ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC;
  461. #endif
  462. #ifdef CONFIG_EXAMPLE_MITM
  463. ble_hs_cfg.sm_mitm = 1;
  464. #endif
  465. #ifdef CONFIG_EXAMPLE_USE_SC
  466. ble_hs_cfg.sm_sc = 1;
  467. #else
  468. ble_hs_cfg.sm_sc = 0;
  469. #endif
  470. #ifdef CONFIG_EXAMPLE_RESOLVE_PEER_ADDR
  471. /* Stores the IRK */
  472. ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ID;
  473. ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ID;
  474. #endif
  475. rc = gatt_svr_init();
  476. assert(rc == 0);
  477. /* Set the default device name. */
  478. rc = ble_svc_gap_device_name_set("nimble-bleprph");
  479. assert(rc == 0);
  480. /* XXX Need to have template for store */
  481. ble_store_config_init();
  482. nimble_port_freertos_init(bleprph_host_task);
  483. /* Initialize command line interface to accept input from user */
  484. rc = scli_init();
  485. if (rc != ESP_OK) {
  486. ESP_LOGE(tag, "scli_init() failed");
  487. }
  488. }