main.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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 "blecent.h"
  29. /*** The UUID of the service containing the subscribable characterstic ***/
  30. static const ble_uuid_t * remote_svc_uuid =
  31. BLE_UUID128_DECLARE(0x2d, 0x71, 0xa2, 0x59, 0xb4, 0x58, 0xc8, 0x12,
  32. 0x99, 0x99, 0x43, 0x95, 0x12, 0x2f, 0x46, 0x59);
  33. /*** The UUID of the subscribable chatacteristic ***/
  34. static const ble_uuid_t * remote_chr_uuid =
  35. BLE_UUID128_DECLARE(0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,
  36. 0x22, 0x22, 0x22, 0x22, 0x33, 0x33, 0x33, 0x33);
  37. static const char *tag = "NimBLE_BLE_CENT";
  38. static int blecent_gap_event(struct ble_gap_event *event, void *arg);
  39. static uint8_t peer_addr[6];
  40. void ble_store_config_init(void);
  41. /**
  42. * Application Callback. Called when the custom subscribable chatacteristic
  43. * in the remote GATT server is read.
  44. * Expect to get the recently written data.
  45. **/
  46. static int
  47. blecent_on_custom_read(uint16_t conn_handle,
  48. const struct ble_gatt_error *error,
  49. struct ble_gatt_attr *attr,
  50. void *arg)
  51. {
  52. MODLOG_DFLT(INFO,
  53. "Read complete for the subscribable characteristic; "
  54. "status=%d conn_handle=%d", error->status, conn_handle);
  55. if (error->status == 0) {
  56. MODLOG_DFLT(INFO, " attr_handle=%d value=", attr->handle);
  57. print_mbuf(attr->om);
  58. }
  59. MODLOG_DFLT(INFO, "\n");
  60. return 0;
  61. }
  62. /**
  63. * Application Callback. Called when the custom subscribable characteristic
  64. * in the remote GATT server is written to.
  65. * Client has previously subscribed to this characeteristic,
  66. * so expect a notification from the server.
  67. **/
  68. static int
  69. blecent_on_custom_write(uint16_t conn_handle,
  70. const struct ble_gatt_error *error,
  71. struct ble_gatt_attr *attr,
  72. void *arg)
  73. {
  74. const struct peer_chr *chr;
  75. const struct peer *peer;
  76. int rc;
  77. MODLOG_DFLT(INFO,
  78. "Write to the custom subscribable characteristic complete; "
  79. "status=%d conn_handle=%d attr_handle=%d\n",
  80. error->status, conn_handle, attr->handle);
  81. peer = peer_find(conn_handle);
  82. chr = peer_chr_find_uuid(peer,
  83. remote_svc_uuid,
  84. remote_chr_uuid);
  85. if (chr == NULL) {
  86. MODLOG_DFLT(ERROR,
  87. "Error: Peer doesn't have the custom subscribable characteristic\n");
  88. goto err;
  89. }
  90. /*** Performs a read on the characteristic, the result is handled in blecent_on_new_read callback ***/
  91. rc = ble_gattc_read(conn_handle, chr->chr.val_handle,
  92. blecent_on_custom_read, NULL);
  93. if (rc != 0) {
  94. MODLOG_DFLT(ERROR,
  95. "Error: Failed to read the custom subscribable characteristic; "
  96. "rc=%d\n", rc);
  97. goto err;
  98. }
  99. return 0;
  100. err:
  101. /* Terminate the connection */
  102. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  103. }
  104. /**
  105. * Application Callback. Called when the custom subscribable characteristic
  106. * is subscribed to.
  107. **/
  108. static int
  109. blecent_on_custom_subscribe(uint16_t conn_handle,
  110. const struct ble_gatt_error *error,
  111. struct ble_gatt_attr *attr,
  112. void *arg)
  113. {
  114. const struct peer_chr *chr;
  115. uint8_t value;
  116. int rc;
  117. const struct peer *peer;
  118. MODLOG_DFLT(INFO,
  119. "Subscribe to the custom subscribable characteristic complete; "
  120. "status=%d conn_handle=%d", error->status, conn_handle);
  121. if (error->status == 0) {
  122. MODLOG_DFLT(INFO, " attr_handle=%d value=", attr->handle);
  123. print_mbuf(attr->om);
  124. }
  125. MODLOG_DFLT(INFO, "\n");
  126. peer = peer_find(conn_handle);
  127. chr = peer_chr_find_uuid(peer,
  128. remote_svc_uuid,
  129. remote_chr_uuid);
  130. if (chr == NULL) {
  131. MODLOG_DFLT(ERROR, "Error: Peer doesn't have the subscribable characteristic\n");
  132. goto err;
  133. }
  134. /* Write 1 byte to the new characteristic to test if it notifies after subscribing */
  135. value = 0x19;
  136. rc = ble_gattc_write_flat(conn_handle, chr->chr.val_handle,
  137. &value, sizeof(value), blecent_on_custom_write, NULL);
  138. if (rc != 0) {
  139. MODLOG_DFLT(ERROR,
  140. "Error: Failed to write to the subscribable characteristic; "
  141. "rc=%d\n", rc);
  142. goto err;
  143. }
  144. return 0;
  145. err:
  146. /* Terminate the connection */
  147. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  148. }
  149. /**
  150. * Performs 3 operations on the remote GATT server.
  151. * 1. Subscribes to a characteristic by writing 0x10 to it's CCCD.
  152. * 2. Writes to the characteristic and expect a notification from remote.
  153. * 3. Reads the characteristic and expect to get the recently written information.
  154. **/
  155. static void
  156. blecent_custom_gatt_operations(const struct peer* peer)
  157. {
  158. const struct peer_dsc *dsc;
  159. int rc;
  160. uint8_t value[2];
  161. dsc = peer_dsc_find_uuid(peer,
  162. remote_svc_uuid,
  163. remote_chr_uuid,
  164. BLE_UUID16_DECLARE(BLE_GATT_DSC_CLT_CFG_UUID16));
  165. if (dsc == NULL) {
  166. MODLOG_DFLT(ERROR, "Error: Peer lacks a CCCD for the subscribable characterstic\n");
  167. goto err;
  168. }
  169. /*** Write 0x00 and 0x01 (The subscription code) to the CCCD ***/
  170. value[0] = 1;
  171. value[1] = 0;
  172. rc = ble_gattc_write_flat(peer->conn_handle, dsc->dsc.handle,
  173. value, sizeof(value), blecent_on_custom_subscribe, NULL);
  174. if (rc != 0) {
  175. MODLOG_DFLT(ERROR,
  176. "Error: Failed to subscribe to the subscribable characteristic; "
  177. "rc=%d\n", rc);
  178. goto err;
  179. }
  180. return;
  181. err:
  182. /* Terminate the connection */
  183. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  184. }
  185. /**
  186. * Application callback. Called when the attempt to subscribe to notifications
  187. * for the ANS Unread Alert Status characteristic has completed.
  188. */
  189. static int
  190. blecent_on_subscribe(uint16_t conn_handle,
  191. const struct ble_gatt_error *error,
  192. struct ble_gatt_attr *attr,
  193. void *arg)
  194. {
  195. struct peer *peer;
  196. MODLOG_DFLT(INFO, "Subscribe complete; status=%d conn_handle=%d "
  197. "attr_handle=%d\n",
  198. error->status, conn_handle, attr->handle);
  199. peer = peer_find(conn_handle);
  200. if (peer == NULL) {
  201. MODLOG_DFLT(ERROR, "Error in finding peer, aborting...");
  202. ble_gap_terminate(conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  203. }
  204. /* Subscribe to, write to, and read the custom characteristic*/
  205. blecent_custom_gatt_operations(peer);
  206. return 0;
  207. }
  208. /**
  209. * Application callback. Called when the write to the ANS Alert Notification
  210. * Control Point characteristic has completed.
  211. */
  212. static int
  213. blecent_on_write(uint16_t conn_handle,
  214. const struct ble_gatt_error *error,
  215. struct ble_gatt_attr *attr,
  216. void *arg)
  217. {
  218. MODLOG_DFLT(INFO,
  219. "Write complete; status=%d conn_handle=%d attr_handle=%d\n",
  220. error->status, conn_handle, attr->handle);
  221. /* Subscribe to notifications for the Unread Alert Status characteristic.
  222. * A central enables notifications by writing two bytes (1, 0) to the
  223. * characteristic's client-characteristic-configuration-descriptor (CCCD).
  224. */
  225. const struct peer_dsc *dsc;
  226. uint8_t value[2];
  227. int rc;
  228. const struct peer *peer = peer_find(conn_handle);
  229. dsc = peer_dsc_find_uuid(peer,
  230. BLE_UUID16_DECLARE(BLECENT_SVC_ALERT_UUID),
  231. BLE_UUID16_DECLARE(BLECENT_CHR_UNR_ALERT_STAT_UUID),
  232. BLE_UUID16_DECLARE(BLE_GATT_DSC_CLT_CFG_UUID16));
  233. if (dsc == NULL) {
  234. MODLOG_DFLT(ERROR, "Error: Peer lacks a CCCD for the Unread Alert "
  235. "Status characteristic\n");
  236. goto err;
  237. }
  238. value[0] = 1;
  239. value[1] = 0;
  240. rc = ble_gattc_write_flat(conn_handle, dsc->dsc.handle,
  241. value, sizeof value, blecent_on_subscribe, NULL);
  242. if (rc != 0) {
  243. MODLOG_DFLT(ERROR, "Error: Failed to subscribe to characteristic; "
  244. "rc=%d\n", rc);
  245. goto err;
  246. }
  247. return 0;
  248. err:
  249. /* Terminate the connection. */
  250. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  251. }
  252. /**
  253. * Application callback. Called when the read of the ANS Supported New Alert
  254. * Category characteristic has completed.
  255. */
  256. static int
  257. blecent_on_read(uint16_t conn_handle,
  258. const struct ble_gatt_error *error,
  259. struct ble_gatt_attr *attr,
  260. void *arg)
  261. {
  262. MODLOG_DFLT(INFO, "Read complete; status=%d conn_handle=%d", error->status,
  263. conn_handle);
  264. if (error->status == 0) {
  265. MODLOG_DFLT(INFO, " attr_handle=%d value=", attr->handle);
  266. print_mbuf(attr->om);
  267. }
  268. MODLOG_DFLT(INFO, "\n");
  269. /* Write two bytes (99, 100) to the alert-notification-control-point
  270. * characteristic.
  271. */
  272. const struct peer_chr *chr;
  273. uint8_t value[2];
  274. int rc;
  275. const struct peer *peer = peer_find(conn_handle);
  276. chr = peer_chr_find_uuid(peer,
  277. BLE_UUID16_DECLARE(BLECENT_SVC_ALERT_UUID),
  278. BLE_UUID16_DECLARE(BLECENT_CHR_ALERT_NOT_CTRL_PT));
  279. if (chr == NULL) {
  280. MODLOG_DFLT(ERROR, "Error: Peer doesn't support the Alert "
  281. "Notification Control Point characteristic\n");
  282. goto err;
  283. }
  284. value[0] = 99;
  285. value[1] = 100;
  286. rc = ble_gattc_write_flat(conn_handle, chr->chr.val_handle,
  287. value, sizeof value, blecent_on_write, NULL);
  288. if (rc != 0) {
  289. MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
  290. rc);
  291. goto err;
  292. }
  293. return 0;
  294. err:
  295. /* Terminate the connection. */
  296. return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  297. }
  298. /**
  299. * Performs three GATT operations against the specified peer:
  300. * 1. Reads the ANS Supported New Alert Category characteristic.
  301. * 2. After read is completed, writes the ANS Alert Notification Control Point characteristic.
  302. * 3. After write is completed, subscribes to notifications for the ANS Unread Alert Status
  303. * characteristic.
  304. *
  305. * If the peer does not support a required service, characteristic, or
  306. * descriptor, then the peer lied when it claimed support for the alert
  307. * notification service! When this happens, or if a GATT procedure fails,
  308. * this function immediately terminates the connection.
  309. */
  310. static void
  311. blecent_read_write_subscribe(const struct peer *peer)
  312. {
  313. const struct peer_chr *chr;
  314. int rc;
  315. /* Read the supported-new-alert-category characteristic. */
  316. chr = peer_chr_find_uuid(peer,
  317. BLE_UUID16_DECLARE(BLECENT_SVC_ALERT_UUID),
  318. BLE_UUID16_DECLARE(BLECENT_CHR_SUP_NEW_ALERT_CAT_UUID));
  319. if (chr == NULL) {
  320. MODLOG_DFLT(ERROR, "Error: Peer doesn't support the Supported New "
  321. "Alert Category characteristic\n");
  322. goto err;
  323. }
  324. rc = ble_gattc_read(peer->conn_handle, chr->chr.val_handle,
  325. blecent_on_read, NULL);
  326. if (rc != 0) {
  327. MODLOG_DFLT(ERROR, "Error: Failed to read characteristic; rc=%d\n",
  328. rc);
  329. goto err;
  330. }
  331. return;
  332. err:
  333. /* Terminate the connection. */
  334. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  335. }
  336. /**
  337. * Called when service discovery of the specified peer has completed.
  338. */
  339. static void
  340. blecent_on_disc_complete(const struct peer *peer, int status, void *arg)
  341. {
  342. if (status != 0) {
  343. /* Service discovery failed. Terminate the connection. */
  344. MODLOG_DFLT(ERROR, "Error: Service discovery failed; status=%d "
  345. "conn_handle=%d\n", status, peer->conn_handle);
  346. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  347. return;
  348. }
  349. /* Service discovery has completed successfully. Now we have a complete
  350. * list of services, characteristics, and descriptors that the peer
  351. * supports.
  352. */
  353. MODLOG_DFLT(INFO, "Service discovery complete; status=%d "
  354. "conn_handle=%d\n", status, peer->conn_handle);
  355. /* Now perform three GATT procedures against the peer: read,
  356. * write, and subscribe to notifications for the ANS service.
  357. */
  358. blecent_read_write_subscribe(peer);
  359. }
  360. /**
  361. * Initiates the GAP general discovery procedure.
  362. */
  363. static void
  364. blecent_scan(void)
  365. {
  366. uint8_t own_addr_type;
  367. struct ble_gap_disc_params disc_params;
  368. int rc;
  369. /* Figure out address to use while advertising (no privacy for now) */
  370. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  371. if (rc != 0) {
  372. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  373. return;
  374. }
  375. /* Tell the controller to filter duplicates; we don't want to process
  376. * repeated advertisements from the same device.
  377. */
  378. disc_params.filter_duplicates = 1;
  379. /**
  380. * Perform a passive scan. I.e., don't send follow-up scan requests to
  381. * each advertiser.
  382. */
  383. disc_params.passive = 1;
  384. /* Use defaults for the rest of the parameters. */
  385. disc_params.itvl = 0;
  386. disc_params.window = 0;
  387. disc_params.filter_policy = 0;
  388. disc_params.limited = 0;
  389. rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params,
  390. blecent_gap_event, NULL);
  391. if (rc != 0) {
  392. MODLOG_DFLT(ERROR, "Error initiating GAP discovery procedure; rc=%d\n",
  393. rc);
  394. }
  395. }
  396. /**
  397. * Indicates whether we should try to connect to the sender of the specified
  398. * advertisement. The function returns a positive result if the device
  399. * advertises connectability and support for the Alert Notification service.
  400. */
  401. #if CONFIG_EXAMPLE_EXTENDED_ADV
  402. static int
  403. ext_blecent_should_connect(const struct ble_gap_ext_disc_desc *disc)
  404. {
  405. int offset = 0;
  406. int ad_struct_len = 0;
  407. if (disc->legacy_event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND &&
  408. disc->legacy_event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
  409. return 0;
  410. }
  411. if (strlen(CONFIG_EXAMPLE_PEER_ADDR) && (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen ("ADDR_ANY")) != 0)) {
  412. ESP_LOGI(tag, "Peer address from menuconfig: %s", CONFIG_EXAMPLE_PEER_ADDR);
  413. /* Convert string to address */
  414. sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
  415. &peer_addr[5], &peer_addr[4], &peer_addr[3],
  416. &peer_addr[2], &peer_addr[1], &peer_addr[0]);
  417. if (memcmp(peer_addr, disc->addr.val, sizeof(disc->addr.val)) != 0) {
  418. return 0;
  419. }
  420. }
  421. /* The device has to advertise support for the Alert Notification
  422. * service (0x1811).
  423. */
  424. do {
  425. ad_struct_len = disc->data[offset];
  426. if (!ad_struct_len) {
  427. break;
  428. }
  429. /* Search if ANS UUID is advertised */
  430. if (disc->data[offset] == 0x03 && disc->data[offset + 1] == 0x03) {
  431. if ( disc->data[offset + 2] == 0x18 && disc->data[offset + 3] == 0x11 ) {
  432. return 1;
  433. }
  434. }
  435. offset += ad_struct_len + 1;
  436. } while ( offset < disc->length_data );
  437. return 0;
  438. }
  439. #else
  440. static int
  441. blecent_should_connect(const struct ble_gap_disc_desc *disc)
  442. {
  443. struct ble_hs_adv_fields fields;
  444. int rc;
  445. int i;
  446. /* The device has to be advertising connectability. */
  447. if (disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND &&
  448. disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
  449. return 0;
  450. }
  451. rc = ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data);
  452. if (rc != 0) {
  453. return 0;
  454. }
  455. if (strlen(CONFIG_EXAMPLE_PEER_ADDR) && (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen("ADDR_ANY")) != 0)) {
  456. ESP_LOGI(tag, "Peer address from menuconfig: %s", CONFIG_EXAMPLE_PEER_ADDR);
  457. /* Convert string to address */
  458. sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
  459. &peer_addr[5], &peer_addr[4], &peer_addr[3],
  460. &peer_addr[2], &peer_addr[1], &peer_addr[0]);
  461. if (memcmp(peer_addr, disc->addr.val, sizeof(disc->addr.val)) != 0) {
  462. return 0;
  463. }
  464. }
  465. /* The device has to advertise support for the Alert Notification
  466. * service (0x1811).
  467. */
  468. for (i = 0; i < fields.num_uuids16; i++) {
  469. if (ble_uuid_u16(&fields.uuids16[i].u) == BLECENT_SVC_ALERT_UUID) {
  470. return 1;
  471. }
  472. }
  473. return 0;
  474. }
  475. #endif
  476. /**
  477. * Connects to the sender of the specified advertisement of it looks
  478. * interesting. A device is "interesting" if it advertises connectability and
  479. * support for the Alert Notification service.
  480. */
  481. static void
  482. blecent_connect_if_interesting(void *disc)
  483. {
  484. uint8_t own_addr_type;
  485. int rc;
  486. ble_addr_t *addr;
  487. /* Don't do anything if we don't care about this advertiser. */
  488. #if CONFIG_EXAMPLE_EXTENDED_ADV
  489. if (!ext_blecent_should_connect((struct ble_gap_ext_disc_desc *)disc)) {
  490. return;
  491. }
  492. #else
  493. if (!blecent_should_connect((struct ble_gap_disc_desc *)disc)) {
  494. return;
  495. }
  496. #endif
  497. /* Scanning must be stopped before a connection can be initiated. */
  498. rc = ble_gap_disc_cancel();
  499. if (rc != 0) {
  500. MODLOG_DFLT(DEBUG, "Failed to cancel scan; rc=%d\n", rc);
  501. return;
  502. }
  503. /* Figure out address to use for connect (no privacy for now) */
  504. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  505. if (rc != 0) {
  506. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  507. return;
  508. }
  509. /* Try to connect the the advertiser. Allow 30 seconds (30000 ms) for
  510. * timeout.
  511. */
  512. #if CONFIG_EXAMPLE_EXTENDED_ADV
  513. addr = &((struct ble_gap_ext_disc_desc *)disc)->addr;
  514. #else
  515. addr = &((struct ble_gap_disc_desc *)disc)->addr;
  516. #endif
  517. rc = ble_gap_connect(own_addr_type, addr, 30000, NULL,
  518. blecent_gap_event, NULL);
  519. if (rc != 0) {
  520. MODLOG_DFLT(ERROR, "Error: Failed to connect to device; addr_type=%d "
  521. "addr=%s; rc=%d\n",
  522. addr->type, addr_str(addr->val), rc);
  523. return;
  524. }
  525. }
  526. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  527. static void blecent_power_control(uint16_t conn_handle)
  528. {
  529. int rc;
  530. rc = ble_gap_read_remote_transmit_power_level(conn_handle, 0x01 ); // Attempting on LE 1M phy
  531. assert (rc == 0);
  532. rc = ble_gap_set_transmit_power_reporting_enable(conn_handle, 0x01, 0x01);
  533. assert (rc == 0);
  534. rc = ble_gap_set_path_loss_reporting_param(conn_handle, 60, 10, 30, 10, 2 ); //demo values
  535. assert (rc == 0);
  536. rc = ble_gap_set_path_loss_reporting_enable(conn_handle, 0x01);
  537. assert (rc == 0);
  538. }
  539. #endif
  540. /**
  541. * The nimble host executes this callback when a GAP event occurs. The
  542. * application associates a GAP event callback with each connection that is
  543. * established. blecent uses the same callback for all connections.
  544. *
  545. * @param event The event being signalled.
  546. * @param arg Application-specified argument; unused by
  547. * blecent.
  548. *
  549. * @return 0 if the application successfully handled the
  550. * event; nonzero on failure. The semantics
  551. * of the return code is specific to the
  552. * particular GAP event being signalled.
  553. */
  554. static int
  555. blecent_gap_event(struct ble_gap_event *event, void *arg)
  556. {
  557. struct ble_gap_conn_desc desc;
  558. struct ble_hs_adv_fields fields;
  559. #if MYNEWT_VAL(BLE_HCI_VS)
  560. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  561. struct ble_gap_set_auto_pcl_params params;
  562. #endif
  563. #endif
  564. int rc;
  565. switch (event->type) {
  566. case BLE_GAP_EVENT_DISC:
  567. rc = ble_hs_adv_parse_fields(&fields, event->disc.data,
  568. event->disc.length_data);
  569. if (rc != 0) {
  570. return 0;
  571. }
  572. /* An advertisment report was received during GAP discovery. */
  573. print_adv_fields(&fields);
  574. /* Try to connect to the advertiser if it looks interesting. */
  575. blecent_connect_if_interesting(&event->disc);
  576. return 0;
  577. case BLE_GAP_EVENT_CONNECT:
  578. /* A new connection was established or a connection attempt failed. */
  579. if (event->connect.status == 0) {
  580. /* Connection successfully established. */
  581. MODLOG_DFLT(INFO, "Connection established ");
  582. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  583. assert(rc == 0);
  584. print_conn_desc(&desc);
  585. MODLOG_DFLT(INFO, "\n");
  586. /* Remember peer. */
  587. rc = peer_add(event->connect.conn_handle);
  588. if (rc != 0) {
  589. MODLOG_DFLT(ERROR, "Failed to add peer; rc=%d\n", rc);
  590. return 0;
  591. }
  592. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  593. blecent_power_control(event->connect.conn_handle);
  594. #endif
  595. #if MYNEWT_VAL(BLE_HCI_VS)
  596. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  597. memset(&params, 0x0, sizeof(struct ble_gap_set_auto_pcl_params));
  598. params.conn_handle = event->connect.conn_handle;
  599. rc = ble_gap_set_auto_pcl_param(&params);
  600. if (rc != 0) {
  601. MODLOG_DFLT(INFO, "Failed to send VSC %x \n", rc);
  602. return 0;
  603. }
  604. else {
  605. MODLOG_DFLT(INFO, "Successfully issued VSC , rc = %d \n", rc);
  606. }
  607. #endif
  608. #endif
  609. #if CONFIG_EXAMPLE_ENCRYPTION
  610. /** Initiate security - It will perform
  611. * Pairing (Exchange keys)
  612. * Bonding (Store keys)
  613. * Encryption (Enable encryption)
  614. * Will invoke event BLE_GAP_EVENT_ENC_CHANGE
  615. **/
  616. rc = ble_gap_security_initiate(event->connect.conn_handle);
  617. if (rc != 0) {
  618. MODLOG_DFLT(INFO, "Security could not be initiated, rc = %d\n", rc);
  619. return ble_gap_terminate(event->connect.conn_handle,
  620. BLE_ERR_REM_USER_CONN_TERM);
  621. } else {
  622. MODLOG_DFLT(INFO, "Connection secured\n");
  623. }
  624. #else
  625. /* Perform service discovery */
  626. rc = peer_disc_all(event->connect.conn_handle,
  627. blecent_on_disc_complete, NULL);
  628. if(rc != 0) {
  629. MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
  630. return 0;
  631. }
  632. #endif
  633. } else {
  634. /* Connection attempt failed; resume scanning. */
  635. MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n",
  636. event->connect.status);
  637. blecent_scan();
  638. }
  639. return 0;
  640. case BLE_GAP_EVENT_DISCONNECT:
  641. /* Connection terminated. */
  642. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  643. print_conn_desc(&event->disconnect.conn);
  644. MODLOG_DFLT(INFO, "\n");
  645. /* Forget about peer. */
  646. peer_delete(event->disconnect.conn.conn_handle);
  647. /* Resume scanning. */
  648. blecent_scan();
  649. return 0;
  650. case BLE_GAP_EVENT_DISC_COMPLETE:
  651. MODLOG_DFLT(INFO, "discovery complete; reason=%d\n",
  652. event->disc_complete.reason);
  653. return 0;
  654. case BLE_GAP_EVENT_ENC_CHANGE:
  655. /* Encryption has been enabled or disabled for this connection. */
  656. MODLOG_DFLT(INFO, "encryption change event; status=%d ",
  657. event->enc_change.status);
  658. rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
  659. assert(rc == 0);
  660. print_conn_desc(&desc);
  661. #if CONFIG_EXAMPLE_ENCRYPTION
  662. /*** Go for service discovery after encryption has been successfully enabled ***/
  663. rc = peer_disc_all(event->connect.conn_handle,
  664. blecent_on_disc_complete, NULL);
  665. if (rc != 0) {
  666. MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
  667. return 0;
  668. }
  669. #endif
  670. return 0;
  671. case BLE_GAP_EVENT_NOTIFY_RX:
  672. /* Peer sent us a notification or indication. */
  673. MODLOG_DFLT(INFO, "received %s; conn_handle=%d attr_handle=%d "
  674. "attr_len=%d\n",
  675. event->notify_rx.indication ?
  676. "indication" :
  677. "notification",
  678. event->notify_rx.conn_handle,
  679. event->notify_rx.attr_handle,
  680. OS_MBUF_PKTLEN(event->notify_rx.om));
  681. /* Attribute data is contained in event->notify_rx.om. Use
  682. * `os_mbuf_copydata` to copy the data received in notification mbuf */
  683. return 0;
  684. case BLE_GAP_EVENT_MTU:
  685. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  686. event->mtu.conn_handle,
  687. event->mtu.channel_id,
  688. event->mtu.value);
  689. return 0;
  690. case BLE_GAP_EVENT_REPEAT_PAIRING:
  691. /* We already have a bond with the peer, but it is attempting to
  692. * establish a new secure link. This app sacrifices security for
  693. * convenience: just throw away the old bond and accept the new link.
  694. */
  695. /* Delete the old bond. */
  696. rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
  697. assert(rc == 0);
  698. ble_store_util_delete_peer(&desc.peer_id_addr);
  699. /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
  700. * continue with the pairing operation.
  701. */
  702. return BLE_GAP_REPEAT_PAIRING_RETRY;
  703. #if CONFIG_EXAMPLE_EXTENDED_ADV
  704. case BLE_GAP_EVENT_EXT_DISC:
  705. /* An advertisment report was received during GAP discovery. */
  706. ext_print_adv_report(&event->disc);
  707. blecent_connect_if_interesting(&event->disc);
  708. return 0;
  709. #endif
  710. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  711. case BLE_GAP_EVENT_TRANSMIT_POWER:
  712. MODLOG_DFLT(INFO, "Transmit power event : status=%d conn_handle=%d reason=%d "
  713. "phy=%d power_level=%d power_level_flag=%d delta=%d",
  714. event->transmit_power.status,
  715. event->transmit_power.conn_handle,
  716. event->transmit_power.reason,
  717. event->transmit_power.phy,
  718. event->transmit_power.transmit_power_level,
  719. event->transmit_power.transmit_power_level_flag,
  720. event->transmit_power.delta);
  721. return 0;
  722. case BLE_GAP_EVENT_PATHLOSS_THRESHOLD:
  723. MODLOG_DFLT(INFO, "Pathloss threshold event : conn_handle=%d current path loss=%d "
  724. "zone_entered =%d",
  725. event->pathloss_threshold.conn_handle,
  726. event->pathloss_threshold.current_path_loss,
  727. event->pathloss_threshold.zone_entered);
  728. return 0;
  729. #endif
  730. default:
  731. return 0;
  732. }
  733. }
  734. static void
  735. blecent_on_reset(int reason)
  736. {
  737. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  738. }
  739. static void
  740. blecent_on_sync(void)
  741. {
  742. int rc;
  743. /* Make sure we have proper identity address set (public preferred) */
  744. rc = ble_hs_util_ensure_addr(0);
  745. assert(rc == 0);
  746. #if !CONFIG_EXAMPLE_INIT_DEINIT_LOOP
  747. /* Begin scanning for a peripheral to connect to. */
  748. blecent_scan();
  749. #endif
  750. }
  751. void blecent_host_task(void *param)
  752. {
  753. ESP_LOGI(tag, "BLE Host Task Started");
  754. /* This function will return only when nimble_port_stop() is executed */
  755. nimble_port_run();
  756. nimble_port_freertos_deinit();
  757. }
  758. #if CONFIG_EXAMPLE_INIT_DEINIT_LOOP
  759. /* This function showcases stack init and deinit procedure. */
  760. static void stack_init_deinit(void)
  761. {
  762. int rc;
  763. while(1) {
  764. vTaskDelay(1000);
  765. ESP_LOGI(tag, "Deinit host");
  766. rc = nimble_port_stop();
  767. if (rc == 0) {
  768. nimble_port_deinit();
  769. } else {
  770. ESP_LOGI(tag, "Nimble port stop failed, rc = %d", rc);
  771. break;
  772. }
  773. vTaskDelay(1000);
  774. ESP_LOGI(tag, "Init host");
  775. rc = nimble_port_init();
  776. if (rc != ESP_OK) {
  777. ESP_LOGI(tag, "Failed to init nimble %d ", rc);
  778. break;
  779. }
  780. nimble_port_freertos_init(blecent_host_task);
  781. ESP_LOGI(tag, "Waiting for 1 second");
  782. }
  783. }
  784. #endif
  785. void
  786. app_main(void)
  787. {
  788. int rc;
  789. /* Initialize NVS — it is used to store PHY calibration data */
  790. esp_err_t ret = nvs_flash_init();
  791. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  792. ESP_ERROR_CHECK(nvs_flash_erase());
  793. ret = nvs_flash_init();
  794. }
  795. ESP_ERROR_CHECK(ret);
  796. ret = nimble_port_init();
  797. if (ret != ESP_OK) {
  798. ESP_LOGE(tag, "Failed to init nimble %d ", ret);
  799. return;
  800. }
  801. /* Configure the host. */
  802. ble_hs_cfg.reset_cb = blecent_on_reset;
  803. ble_hs_cfg.sync_cb = blecent_on_sync;
  804. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  805. /* Initialize data structures to track connected peers. */
  806. rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
  807. assert(rc == 0);
  808. /* Set the default device name. */
  809. rc = ble_svc_gap_device_name_set("nimble-blecent");
  810. assert(rc == 0);
  811. /* XXX Need to have template for store */
  812. ble_store_config_init();
  813. nimble_port_freertos_init(blecent_host_task);
  814. #if CONFIG_EXAMPLE_INIT_DEINIT_LOOP
  815. stack_init_deinit();
  816. #endif
  817. }