main.c 17 KB

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