main.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include "esp_log.h"
  7. #include "nvs_flash.h"
  8. /* BLE */
  9. #include "nimble/nimble_port.h"
  10. #include "nimble/nimble_port_freertos.h"
  11. #include "host/ble_hs.h"
  12. #include "host/util/util.h"
  13. #include "console/console.h"
  14. #include "services/gap/ble_svc_gap.h"
  15. #include "gattc.h"
  16. #include "esp_timer.h"
  17. #include "linenoise/linenoise.h"
  18. #include "esp_console.h"
  19. #include "driver/uart.h"
  20. #include "esp_vfs_dev.h"
  21. #include "argtable3/argtable3.h"
  22. #include "cmd_system.h"
  23. #include "../src/ble_hs_hci_priv.h"
  24. /* 0000xxxx-8c26-476f-89a7-a108033a69c7 */
  25. #define THRPT_UUID_DECLARE(uuid16) \
  26. ((const ble_uuid_t *) (&(ble_uuid128_t) BLE_UUID128_INIT( \
  27. 0xc7, 0x69, 0x3a, 0x03, 0x08, 0xa1, 0xa7, 0x89, \
  28. 0x6f, 0x47, 0x26, 0x8c, uuid16, uuid16 >> 8, 0x00, 0x00 \
  29. )))
  30. /* 0000xxxx-8c26-476f-89a7-a108033a69c6 */
  31. #define THRPT_UUID_DECLARE_ALT(uuid16) \
  32. ((const ble_uuid_t *) (&(ble_uuid128_t) BLE_UUID128_INIT( \
  33. 0xc6, 0x69, 0x3a, 0x03, 0x08, 0xa1, 0xa7, 0x89, \
  34. 0x6f, 0x47, 0x26, 0x8c, uuid16, uuid16 >> 8, 0x00, 0x00 \
  35. )))
  36. #define THRPT_SVC 0x0001
  37. #define THRPT_CHR_READ_WRITE 0x0006
  38. #define THRPT_CHR_NOTIFY 0x000a
  39. #define THRPT_LONG_CHR_READ_WRITE 0x000b
  40. #define THRPT_LONG_CHR_READ_WRITE_ALT 0x001a
  41. #define THRPT_CHR_READ_WRITE_ALT 0x001f
  42. /* Throughput cases */
  43. #define READ_THROUGHPUT 1
  44. #define WRITE_THROUGHPUT 2
  45. #define NOTIFY_THROUGHPUT 3
  46. #define READ_THROUGHPUT_PAYLOAD 500
  47. #define WRITE_THROUGHPUT_PAYLOAD 500
  48. #define LL_PACKET_TIME 2120
  49. #define LL_PACKET_LENGTH 251
  50. static const char *tag = "blecent_throughput";
  51. static int blecent_gap_event(struct ble_gap_event *event, void *arg);
  52. static uint8_t peer_addr[6];
  53. static SemaphoreHandle_t xSemaphore;
  54. static int mbuf_len_total;
  55. static int failure_count;
  56. static int conn_params_def[] = {40, 40, 0, 500, 80, 80};
  57. static struct ble_gap_upd_params conn_params = {
  58. /** Minimum value for connection interval in 1.25ms units */
  59. .itvl_min = CONFIG_EXAMPLE_CONN_ITVL_MIN,
  60. /** Maximum value for connection interval in 1.25ms units */
  61. .itvl_max = CONFIG_EXAMPLE_CONN_ITVL_MAX,
  62. /** Connection latency */
  63. .latency = CONFIG_EXAMPLE_CONN_LATENCY,
  64. /** Supervision timeout in 10ms units */
  65. .supervision_timeout = CONFIG_EXAMPLE_CONN_TIMEOUT,
  66. /** Minimum length of connection event in 0.625ms units */
  67. .min_ce_len = CONFIG_EXAMPLE_CONN_CE_LEN_MIN,
  68. /** Maximum length of connection event in 0.625ms units */
  69. .max_ce_len = CONFIG_EXAMPLE_CONN_CE_LEN_MAX,
  70. };
  71. static int mtu_def = 512;
  72. /* test_data accepts test_name and test_time from CLI */
  73. static int test_data[] = {1, 600};
  74. void ble_store_config_init(void);
  75. static int
  76. blecent_notify(uint16_t conn_handle, uint16_t val_handle,
  77. ble_gatt_attr_fn *cb, struct peer *peer, int test_time)
  78. {
  79. uint8_t value[2] = {1, 0};/*To subscribe to notifications*/
  80. int rc;
  81. rc = ble_gattc_write_flat(conn_handle, val_handle,
  82. value, sizeof value, NULL, &test_time);
  83. if (rc != 0) {
  84. ESP_LOGE(tag, "Error: Failed to subscribe to characteristic; "
  85. "rc = %d", rc);
  86. goto err;
  87. }
  88. return 0;
  89. err:
  90. /* Terminate the connection. */
  91. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  92. }
  93. static int blecent_write(uint16_t conn_handle, uint16_t val_handle,
  94. struct peer *peer, int test_time)
  95. {
  96. int64_t start_time, end_time, write_time = 0;
  97. int write_count = 0;
  98. uint8_t value[WRITE_THROUGHPUT_PAYLOAD] = {0};
  99. int rc;
  100. value[0] = rand();
  101. failure_count = 0;
  102. start_time = esp_timer_get_time();
  103. while (write_time < test_time * 1000) {
  104. /* Wait till the previous write is complete. For first time Semaphore
  105. * is already available */
  106. label:
  107. rc = ble_gattc_write_no_rsp_flat(conn_handle, val_handle, &value, sizeof value);
  108. if(rc == BLE_HS_ENOMEM) {
  109. vTaskDelay(2); /* Wait for buffers to free up and try again */
  110. goto label;
  111. }
  112. else if (rc != 0) {
  113. ESP_LOGE(tag, "Error: Failed to write characteristic; rc=%d\n",rc);
  114. goto err;
  115. }
  116. end_time = esp_timer_get_time();
  117. write_time = (end_time - start_time) / 1000 ;
  118. write_count += 1;
  119. }
  120. /* Each successful write is of WRITE_THROUGHPUT_PAYLOAD Bytes of
  121. * application data. */
  122. printf("\n****************************************************************\n");
  123. ESP_LOGI(tag, "Application Write throughput = %d bps, write count = %d,"
  124. "failure count = %d",
  125. ((write_count - failure_count) * 8 * WRITE_THROUGHPUT_PAYLOAD) / test_time,
  126. write_count, failure_count);
  127. printf("\n****************************************************************\n");
  128. return 0;
  129. err:
  130. /* Terminate the connection. */
  131. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  132. }
  133. static int
  134. blecent_repeat_read(uint16_t conn_handle,
  135. const struct ble_gatt_error *error,
  136. struct ble_gatt_attr *attr,
  137. void *arg)
  138. {
  139. if (error->status == 0) {
  140. xSemaphoreGive(xSemaphore);
  141. ESP_LOGD(tag, " attr_handle=%d value=", attr->handle);
  142. mbuf_len_total += OS_MBUF_PKTLEN(attr->om);
  143. } else {
  144. ESP_LOGE(tag, " Read failed, callback error code = %d", error->status );
  145. xSemaphoreGive(xSemaphore);
  146. }
  147. return error->status;
  148. }
  149. static int blecent_read(uint16_t conn_handle, uint16_t val_handle,
  150. ble_gatt_attr_fn *cb, struct peer *peer, int test_time)
  151. {
  152. int rc, read_count = 0;
  153. int64_t start_time, end_time, read_time = 0;
  154. /* Keep track of number of bytes read from char */
  155. mbuf_len_total = 0;
  156. start_time = esp_timer_get_time();
  157. ESP_LOGD(tag, " Throughput read started :val_handle=%d test_time=%d", val_handle,
  158. test_time);
  159. while (read_time < (test_time * 1000)) {
  160. /* Wait till the previous read is complete. For first time use Semaphore
  161. * is already available */
  162. xSemaphoreTake(xSemaphore, portMAX_DELAY);
  163. rc = ble_gattc_read(peer->conn_handle, val_handle,
  164. blecent_repeat_read, (void *) &peer);
  165. if (rc != 0) {
  166. ESP_LOGE(tag, "Error: Failed to read characteristic; rc=%d",
  167. rc);
  168. goto err;
  169. }
  170. end_time = esp_timer_get_time();
  171. read_time = (end_time - start_time) / 1000 ;
  172. read_count += 1;
  173. }
  174. /* Application data throughput */
  175. printf("\n****************************************************************\n");
  176. ESP_LOGI(tag, "Application Read throughput = %d bps, Read op counter = %d",
  177. (mbuf_len_total * 8) / (test_time), read_count);
  178. printf("\n****************************************************************\n");
  179. return 0;
  180. err:
  181. /* Terminate the connection. */
  182. vTaskDelay(100 / portTICK_PERIOD_MS);
  183. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  184. }
  185. static void throughput_task(void *arg)
  186. {
  187. struct peer *peer = (struct peer *)arg;
  188. const struct peer_chr *chr;
  189. const struct peer_dsc *dsc;
  190. int rc = 0;
  191. while (1) {
  192. vTaskDelay(4000 / portTICK_PERIOD_MS);
  193. ESP_LOGI(tag, "Format for throughput demo:: throughput read 100");
  194. printf(" ==================================================================\n");
  195. printf(" | Steps to test nimble throughput |\n");
  196. printf(" | |\n");
  197. printf(" | 1. Enter throughput [--Type] [--Test time] |\n");
  198. printf(" | Type: read/write/notify. |\n");
  199. printf(" | Test time: Enter value in seconds. |\n");
  200. printf(" | |\n");
  201. printf(" | e.g. throughput read 600 |\n");
  202. printf(" | |\n");
  203. printf(" | ** Enter 'throughput read 60' for reading char for 60 seconds |\n");
  204. printf(" | OR 'throughput write 60' for writing to char for 60 seconds |\n");
  205. printf(" | OR 'throughput notify 60' for notifications (for 60 seconds)**|\n");
  206. printf(" | |\n");
  207. printf(" =================================================================\n\n");
  208. /* XXX Delay ? */
  209. vTaskDelay(1000 / portTICK_PERIOD_MS);
  210. if (!cli_receive_key(test_data)) {
  211. /* No command supplied, start with reading */
  212. test_data[0] = READ_THROUGHPUT;
  213. test_data[1] = 60;
  214. ESP_LOGI(tag, "No command received from user, start with READ op"
  215. " with 60 seconds test time");
  216. }
  217. scli_reset_queue();
  218. switch (test_data[0]) {
  219. case READ_THROUGHPUT:
  220. /* Read the characteristic supporting long read support
  221. * `THRPT_LONG_CHR_READ_WRITE` (0x000b) */
  222. chr = peer_chr_find_uuid(peer,
  223. THRPT_UUID_DECLARE(THRPT_SVC),
  224. THRPT_UUID_DECLARE(THRPT_LONG_CHR_READ_WRITE));
  225. if (chr == NULL) {
  226. ESP_LOGE(tag, "Peer does not support "
  227. "LONG_READ (0x000b) characteristic ");
  228. break;
  229. }
  230. if (test_data[1] > 0) {
  231. rc = blecent_read(peer->conn_handle, chr->chr.val_handle,
  232. blecent_repeat_read, (void *) peer, test_data[1]);
  233. if (rc != 0) {
  234. ESP_LOGE(tag, "Error while reading from GATTS; rc = %d", rc);
  235. }
  236. } else {
  237. ESP_LOGE(tag, "Please enter non-zero value for test time in seconds!!");
  238. }
  239. break;
  240. case WRITE_THROUGHPUT:
  241. chr = peer_chr_find_uuid(peer,
  242. THRPT_UUID_DECLARE(THRPT_SVC),
  243. THRPT_UUID_DECLARE(THRPT_CHR_READ_WRITE));
  244. if (chr == NULL) {
  245. ESP_LOGE(tag, "Error: Peer doesn't support the READ "
  246. "WRITE characteristic (0x0006) ");
  247. break;
  248. }
  249. if (test_data[1] > 0) {
  250. rc = blecent_write(peer->conn_handle, chr->chr.val_handle, (void *) peer, test_data[1]);
  251. if (rc != 0) {
  252. ESP_LOGE(tag, "Error while writing data; rc = %d", rc);
  253. }
  254. } else {
  255. ESP_LOGE(tag, "Please enter non-zero value for test time in seconds!!");
  256. }
  257. break;
  258. case NOTIFY_THROUGHPUT:
  259. chr = peer_chr_find_uuid(peer,
  260. THRPT_UUID_DECLARE(THRPT_SVC),
  261. THRPT_UUID_DECLARE(THRPT_CHR_NOTIFY));
  262. if (chr == NULL) {
  263. ESP_LOGE(tag, "Error: Peer doesn't support the NOTIFY "
  264. "characteristic (0x000a) ");
  265. break;
  266. }
  267. dsc = peer_dsc_find_uuid(peer,
  268. THRPT_UUID_DECLARE(THRPT_SVC),
  269. THRPT_UUID_DECLARE(THRPT_CHR_NOTIFY),
  270. BLE_UUID16_DECLARE(BLE_GATT_DSC_CLT_CFG_UUID16));
  271. if (dsc == NULL) {
  272. ESP_LOGE(tag, "Error: Peer lacks a CCCD for the Notify "
  273. "Status characteristic\n");
  274. break;
  275. }
  276. rc = blecent_notify(peer->conn_handle, dsc->dsc.handle,
  277. NULL, (void *) peer, test_data[1]);
  278. if (rc != 0) {
  279. ESP_LOGE(tag, "Subscribing to notification failed; rc = %d ", rc);
  280. } else {
  281. ESP_LOGI(tag, "Subscribed to notifications. Throughput number"
  282. " can be seen on peripheral terminal after %d seconds",
  283. test_data[1]);
  284. }
  285. vTaskDelay(test_data[1]*1000 / portTICK_PERIOD_MS);
  286. break;
  287. default:
  288. break;
  289. }
  290. vTaskDelay(5000 / portTICK_PERIOD_MS);
  291. }
  292. vTaskDelete(NULL);
  293. }
  294. static void
  295. blecent_read_write_subscribe(const struct peer *peer)
  296. {
  297. xTaskCreate(throughput_task, "throughput_task", 4096, (void *) peer, 10, NULL);
  298. return;
  299. }
  300. /**
  301. * Called when service discovery of the specified peer has completed.
  302. */
  303. static void
  304. blecent_on_disc_complete(const struct peer *peer, int status, void *arg)
  305. {
  306. if (status != 0) {
  307. /* Service discovery failed. Terminate the connection. */
  308. ESP_LOGE(tag, "Error: Service discovery failed; status=%d "
  309. "conn_handle=%d\n", status, peer->conn_handle);
  310. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  311. return;
  312. }
  313. /* Service discovery has completed successfully. Now we have a complete
  314. * list of services, characteristics, and descriptors that the peer
  315. * supports.
  316. */
  317. ESP_LOGI(tag, "Service discovery complete; status=%d "
  318. "conn_handle=%d\n", status, peer->conn_handle);
  319. /* Now perform three GATT procedures against the peer: read,
  320. * write, and subscribe to notifications depending upon user input.
  321. */
  322. blecent_read_write_subscribe(peer);
  323. }
  324. /**
  325. * Initiates the GAP general discovery procedure.
  326. */
  327. static void
  328. blecent_scan(void)
  329. {
  330. uint8_t own_addr_type;
  331. struct ble_gap_disc_params disc_params;
  332. int rc;
  333. /* Figure out address to use while advertising (no privacy for now) */
  334. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  335. if (rc != 0) {
  336. ESP_LOGE(tag, "error determining address type; rc=%d", rc);
  337. return;
  338. }
  339. /* Tell the controller to filter duplicates; we don't want to process
  340. * repeated advertisements from the same device.
  341. */
  342. disc_params.filter_duplicates = 1;
  343. /**
  344. * Perform a passive scan. I.e., don't send follow-up scan requests to
  345. * each advertiser.
  346. */
  347. disc_params.passive = 1;
  348. /* Use defaults for the rest of the parameters. */
  349. disc_params.itvl = 0;
  350. disc_params.window = 0;
  351. disc_params.filter_policy = 0;
  352. disc_params.limited = 0;
  353. rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params,
  354. blecent_gap_event, NULL);
  355. if (rc != 0) {
  356. ESP_LOGE(tag, "Error initiating GAP discovery procedure; rc=%d\n",
  357. rc);
  358. }
  359. }
  360. /**
  361. * Indicates whether we should try to connect to the sender of the specified
  362. * advertisement. The function returns a positive result if the device
  363. * advertises connectability and support for the THRPT service i.e. 0x0001.
  364. */
  365. static int
  366. blecent_should_connect(const struct ble_gap_disc_desc *disc)
  367. {
  368. struct ble_hs_adv_fields fields;
  369. int rc;
  370. int i;
  371. rc = ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data);
  372. if (rc != 0) {
  373. return rc;
  374. }
  375. if (strlen(CONFIG_EXAMPLE_PEER_ADDR) && (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen("ADDR_ANY")) != 0)) {
  376. ESP_LOGI(tag, "Peer address from menuconfig: %s", CONFIG_EXAMPLE_PEER_ADDR);
  377. /* Convert string to address */
  378. sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
  379. &peer_addr[5], &peer_addr[4], &peer_addr[3],
  380. &peer_addr[2], &peer_addr[1], &peer_addr[0]);
  381. if (memcmp(peer_addr, disc->addr.val, sizeof(disc->addr.val)) != 0) {
  382. return 0;
  383. }
  384. }
  385. ESP_LOGI(tag, "connect; fields.num_uuids128 =%d", fields.num_uuids128);
  386. for (i = 0; i < fields.num_uuids128; i++) {
  387. if ((memcmp(&fields.uuids128[i], THRPT_UUID_DECLARE(THRPT_SVC),
  388. sizeof(ble_uuid128_t))) == 0 ) {
  389. ESP_LOGI(tag, "blecent_should_connect 'THRPT' success");
  390. return 1;
  391. }
  392. }
  393. char serv_name[] = "nimble_prph";
  394. if (fields.name != NULL) {
  395. ESP_LOGI(tag, "Device Name = %s", (char *)fields.name);
  396. if (memcmp(fields.name, serv_name, fields.name_len) == 0) {
  397. ESP_LOGI(tag, "central connect to `nimble_prph` success");
  398. return 1;
  399. }
  400. }
  401. return 0;
  402. }
  403. /**
  404. * Connects to the sender of the specified advertisement of it looks
  405. * interesting. A device is "interesting" if it advertises connectability and
  406. * support for the Alert Notification service.
  407. */
  408. static void
  409. blecent_connect_if_interesting(const struct ble_gap_disc_desc *disc)
  410. {
  411. uint8_t own_addr_type;
  412. int rc;
  413. /* Don't do anything if we don't care about this advertiser. */
  414. if (!blecent_should_connect(disc)) {
  415. return;
  416. }
  417. /* Scanning must be stopped before a connection can be initiated. */
  418. rc = ble_gap_disc_cancel();
  419. if (rc != 0) {
  420. MODLOG_DFLT(DEBUG, "Failed to cancel scan; rc=%d\n", rc);
  421. return;
  422. }
  423. /* Figure out address to use for connect (no privacy for now) */
  424. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  425. if (rc != 0) {
  426. ESP_LOGE(tag, "error determining address type; rc=%d\n", rc);
  427. return;
  428. }
  429. /* Try to connect the the advertiser. Allow 30 seconds (30000 ms) for
  430. * timeout.
  431. */
  432. rc = ble_gap_connect(own_addr_type, &disc->addr, 30000, NULL,
  433. blecent_gap_event, NULL);
  434. if (rc != 0) {
  435. ESP_LOGE(tag, "Error: Failed to connect to device; addr_type=%d "
  436. "addr=%s; rc=%d\n",
  437. disc->addr.type, addr_str(disc->addr.val), rc);
  438. return;
  439. }
  440. }
  441. /**
  442. * The nimble host executes this callback when a GAP event occurs. The
  443. * application associates a GAP event callback with each connection that is
  444. * established. central uses the same callback for all connections.
  445. *
  446. * @param event The event being signalled.
  447. * @param arg Application-specified argument; unused by
  448. * gattc.
  449. *
  450. * @return 0 if the application successfully handled the
  451. * event; nonzero on failure. The semantics
  452. * of the return code is specific to the
  453. * particular GAP event being signalled.
  454. */
  455. static int
  456. blecent_gap_event(struct ble_gap_event *event, void *arg)
  457. {
  458. struct ble_gap_conn_desc desc;
  459. struct ble_hs_adv_fields fields;
  460. int rc;
  461. switch (event->type) {
  462. case BLE_GAP_EVENT_DISC:
  463. ESP_LOGI(tag, "Event DISC ");
  464. rc = ble_hs_adv_parse_fields(&fields, event->disc.data,
  465. event->disc.length_data);
  466. if (rc != 0) {
  467. return 0;
  468. }
  469. /* An advertisment report was received during GAP discovery. */
  470. print_adv_fields(&fields);
  471. /* Try to connect to the advertiser if it looks interesting. */
  472. blecent_connect_if_interesting(&event->disc);
  473. return 0;
  474. case BLE_GAP_EVENT_CONNECT:
  475. /* A new connection was established or a connection attempt failed. */
  476. if (event->connect.status == 0) {
  477. /* Connection successfully established. */
  478. /* XXX Set packet length in controller for better throughput */
  479. ESP_LOGI(tag, "Connection established ");
  480. rc = ble_hs_hci_util_set_data_len(event->connect.conn_handle,
  481. LL_PACKET_LENGTH, LL_PACKET_TIME);
  482. if (rc != 0) {
  483. ESP_LOGE(tag, "Set packet length failed; rc = %d", rc);
  484. }
  485. rc = ble_att_set_preferred_mtu(mtu_def);
  486. if (rc != 0) {
  487. ESP_LOGE(tag, "Failed to set preferred MTU; rc = %d", rc);
  488. }
  489. rc = ble_gattc_exchange_mtu(event->connect.conn_handle, NULL, NULL);
  490. if (rc != 0) {
  491. ESP_LOGE(tag, "Failed to negotiate MTU; rc = %d", rc);
  492. }
  493. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  494. assert(rc == 0);
  495. print_conn_desc(&desc);
  496. rc = ble_gap_update_params(event->connect.conn_handle, &conn_params);
  497. if (rc != 0) {
  498. ESP_LOGE(tag, "Failed to update params; rc = %d", rc);
  499. }
  500. /* Remember peer. */
  501. rc = peer_add(event->connect.conn_handle);
  502. if (rc != 0) {
  503. ESP_LOGE(tag, "Failed to add peer; rc = %d", rc);
  504. return 0;
  505. }
  506. /* Perform service discovery. */
  507. rc = peer_disc_all(event->connect.conn_handle,
  508. blecent_on_disc_complete, NULL);
  509. if (rc != 0) {
  510. ESP_LOGE(tag, "Failed to discover services; rc = %d", rc);
  511. return 0;
  512. }
  513. } else {
  514. /* Connection attempt failed; resume scanning. */
  515. ESP_LOGE(tag, "Error: Connection failed; status = %d",
  516. event->connect.status);
  517. blecent_scan();
  518. }
  519. return 0;
  520. case BLE_GAP_EVENT_DISCONNECT:
  521. /* Connection terminated. */
  522. ESP_LOGI(tag, "disconnect; reason=%d ", event->disconnect.reason);
  523. print_conn_desc(&event->disconnect.conn);
  524. ESP_LOGI(tag, "\n");
  525. /* Forget about peer. */
  526. peer_delete(event->disconnect.conn.conn_handle);
  527. /* Resume scanning. */
  528. blecent_scan();
  529. return 0;
  530. case BLE_GAP_EVENT_DISC_COMPLETE:
  531. ESP_LOGI(tag, "discovery complete; reason = %d",
  532. event->disc_complete.reason);
  533. return 0;
  534. case BLE_GAP_EVENT_ENC_CHANGE:
  535. /* Encryption has been enabled or disabled for this connection. */
  536. ESP_LOGI(tag, "encryption change event; status = %d ",
  537. event->enc_change.status);
  538. rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
  539. assert(rc == 0);
  540. print_conn_desc(&desc);
  541. return 0;
  542. case BLE_GAP_EVENT_NOTIFY_RX:
  543. /* Peer sent us a notification or indication. */
  544. mbuf_len_total = mbuf_len_total + OS_MBUF_PKTLEN(event->notify_rx.om);
  545. ESP_LOGI(tag, "received %s; conn_handle = %d attr_handle = %d "
  546. "attr_len = %d ; Total length = %d",
  547. event->notify_rx.indication ?
  548. "indication" :
  549. "notification",
  550. event->notify_rx.conn_handle,
  551. event->notify_rx.attr_handle,
  552. OS_MBUF_PKTLEN(event->notify_rx.om),
  553. mbuf_len_total);
  554. /* Attribute data is contained in event->notify_rx.attr_data. */
  555. return 0;
  556. case BLE_GAP_EVENT_MTU:
  557. ESP_LOGI(tag, "mtu update event; conn_handle = %d cid = %d mtu = %d",
  558. event->mtu.conn_handle,
  559. event->mtu.channel_id,
  560. event->mtu.value);
  561. return 0;
  562. default:
  563. return 0;
  564. }
  565. }
  566. static void
  567. blecent_on_reset(int reason)
  568. {
  569. ESP_LOGE(tag, "Resetting state; reason=%d\n", reason);
  570. }
  571. static void
  572. blecent_on_sync(void)
  573. {
  574. int rc;
  575. bool yes = false;
  576. /* Make sure we have proper identity address set (public preferred) */
  577. rc = ble_hs_util_ensure_addr(0);
  578. assert(rc == 0);
  579. ESP_LOGI(tag, "Do you want to configure connection params ? ");
  580. ESP_LOGI(tag, "If yes then enter in this format: `Insert Yes` ");
  581. if (scli_receive_yesno(&yes)) {
  582. if (yes) {
  583. ESP_LOGI(tag, " Enter preferred MTU, format:: `MTU 512` ");
  584. if (scli_receive_key(&mtu_def)) {
  585. ESP_LOGI(tag, "MTU provided by user= %d", mtu_def);
  586. } else {
  587. ESP_LOGD(tag, "No input for setting MTU; use default mtu = %d", mtu_def);
  588. }
  589. scli_reset_queue();
  590. ESP_LOGI(tag, "For Conn param: Enter `min_itvl` `max_itvl`"
  591. "`latency` `timeout` `min_ce` `max_ce` in same order");
  592. ESP_LOGI(tag, "Enter conn_update in this format:: `conn 6 120 0 500 0 0`");
  593. if (scli_receive_key(conn_params_def)) {
  594. /** Minimum value for connection interval in 1.25ms units */
  595. conn_params.itvl_min = conn_params_def[0];
  596. /** Maximum value for connection interval in 1.25ms units */
  597. conn_params.itvl_max = conn_params_def[1];
  598. /** Connection latency */
  599. conn_params.latency = conn_params_def[2];
  600. /** Supervision timeout in 10ms units */
  601. conn_params.supervision_timeout = conn_params_def[3];
  602. /** Minimum length of connection event in 0.625ms units */
  603. conn_params.min_ce_len = conn_params_def[4];
  604. /** Maximum length of connection event in 0.625ms units */
  605. conn_params.max_ce_len = conn_params_def[5];
  606. } else {
  607. ESP_LOGD(tag, "no input by user for conn param; use default ");
  608. }
  609. scli_reset_queue();
  610. }
  611. }
  612. /* Begin scanning for a peripheral to connect to. */
  613. blecent_scan();
  614. }
  615. void blecent_host_task(void *param)
  616. {
  617. ESP_LOGI(tag, "BLE Host Task Started");
  618. xSemaphore = xSemaphoreCreateBinary();
  619. xSemaphoreGive(xSemaphore);
  620. /* This function will return only when nimble_port_stop() is executed */
  621. nimble_port_run();
  622. vSemaphoreDelete(xSemaphore);
  623. nimble_port_freertos_deinit();
  624. }
  625. void
  626. app_main(void)
  627. {
  628. int rc;
  629. /* Initialize NVS — it is used to store PHY calibration data */
  630. esp_err_t ret = nvs_flash_init();
  631. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  632. ESP_ERROR_CHECK(nvs_flash_erase());
  633. ret = nvs_flash_init();
  634. }
  635. ESP_ERROR_CHECK(ret);
  636. nimble_port_init();
  637. /* Configure the host. */
  638. ble_hs_cfg.reset_cb = blecent_on_reset;
  639. ble_hs_cfg.sync_cb = blecent_on_sync;
  640. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  641. /* Initialize data structures to track connected peers. */
  642. rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
  643. assert(rc == 0);
  644. /* Set the default device name. */
  645. rc = ble_svc_gap_device_name_set("gattc-throughput");
  646. assert(rc == 0);
  647. /* XXX Need to have template for store */
  648. ble_store_config_init();
  649. /* Before starting with blecent host task, let us get CLI task up and
  650. * running */
  651. esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
  652. esp_console_dev_uart_config_t uart_config = ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT();
  653. esp_console_repl_t *repl = NULL;
  654. repl_config.prompt = "Throughput : ";
  655. ESP_ERROR_CHECK(esp_console_new_repl_uart(&uart_config, &repl_config, &repl));
  656. register_system();
  657. esp_console_register_help_command();
  658. /* Register commands */
  659. ble_register_cli();
  660. /* As BLE CLI has been registered, let us start nimble host task */
  661. nimble_port_freertos_init(blecent_host_task);
  662. printf("\n ===============================================================================================\n");
  663. printf(" | Steps to test nimble throughput |\n");
  664. printf(" | |\n");
  665. printf(" | 1. Print 'help' to gain overview of commands |\n");
  666. printf(" | |\n");
  667. printf("\n ===============================================================================================\n");
  668. const char *prompt = LOG_COLOR_I "Throughput demo >> " LOG_RESET_COLOR;
  669. while (true) {
  670. /* Get a line using linenoise.
  671. * The line is returned when ENTER is pressed.
  672. */
  673. char *line = linenoise(prompt);
  674. if (line == NULL) { /* Ignore empty lines */
  675. continue;
  676. }
  677. /* Add the command to the history */
  678. linenoiseHistoryAdd(line);
  679. /* Try to run the command */
  680. int ret;
  681. esp_err_t err = esp_console_run(line, &ret);
  682. if (err == ESP_ERR_NOT_FOUND) {
  683. printf("Unrecognized command\n");
  684. } else if (err == ESP_ERR_INVALID_ARG) {
  685. // command was empty
  686. } else if (err == ESP_OK && ret != ESP_OK) {
  687. printf("Command returned non-zero error code: 0x%x (%s)\n", ret, esp_err_to_name(ret));
  688. } else if (err != ESP_OK) {
  689. printf("Internal error: %s\n", esp_err_to_name(err));
  690. }
  691. /* linenoise allocates line buffer on the heap, so need to free it */
  692. linenoiseFree(line);
  693. }
  694. }