main.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. int rc;
  560. switch (event->type) {
  561. case BLE_GAP_EVENT_DISC:
  562. rc = ble_hs_adv_parse_fields(&fields, event->disc.data,
  563. event->disc.length_data);
  564. if (rc != 0) {
  565. return 0;
  566. }
  567. /* An advertisment report was received during GAP discovery. */
  568. print_adv_fields(&fields);
  569. /* Try to connect to the advertiser if it looks interesting. */
  570. blecent_connect_if_interesting(&event->disc);
  571. return 0;
  572. case BLE_GAP_EVENT_CONNECT:
  573. /* A new connection was established or a connection attempt failed. */
  574. if (event->connect.status == 0) {
  575. /* Connection successfully established. */
  576. MODLOG_DFLT(INFO, "Connection established ");
  577. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  578. assert(rc == 0);
  579. print_conn_desc(&desc);
  580. MODLOG_DFLT(INFO, "\n");
  581. /* Remember peer. */
  582. rc = peer_add(event->connect.conn_handle);
  583. if (rc != 0) {
  584. MODLOG_DFLT(ERROR, "Failed to add peer; rc=%d\n", rc);
  585. return 0;
  586. }
  587. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  588. blecent_power_control(event->connect.conn_handle);
  589. #endif
  590. #if MYNEWT_VAL(BLE_HCI_VS)
  591. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  592. int8_t vs_cmd[10]= {0, 0,-70,-60,-68,-58,-75,-65,-80,-70};
  593. vs_cmd[0] = ((uint8_t)(event->connect.conn_handle & 0xFF));
  594. vs_cmd[1] = ((uint8_t)(event->connect.conn_handle >> 8) & 0xFF);
  595. rc = ble_hs_hci_send_vs_cmd(BLE_HCI_OCF_VS_PCL_SET_RSSI ,
  596. &vs_cmd, sizeof(vs_cmd), NULL, 0);
  597. if (rc != 0) {
  598. MODLOG_DFLT(INFO, "Failed to send VSC %x \n", rc);
  599. return 0;
  600. }
  601. else
  602. MODLOG_DFLT(INFO, "Successfully issued VSC , rc = %d \n", rc);
  603. #endif
  604. #endif
  605. #if CONFIG_EXAMPLE_ENCRYPTION
  606. /** Initiate security - It will perform
  607. * Pairing (Exchange keys)
  608. * Bonding (Store keys)
  609. * Encryption (Enable encryption)
  610. * Will invoke event BLE_GAP_EVENT_ENC_CHANGE
  611. **/
  612. rc = ble_gap_security_initiate(event->connect.conn_handle);
  613. if (rc != 0) {
  614. MODLOG_DFLT(INFO, "Security could not be initiated, rc = %d\n", rc);
  615. return ble_gap_terminate(event->connect.conn_handle,
  616. BLE_ERR_REM_USER_CONN_TERM);
  617. } else {
  618. MODLOG_DFLT(INFO, "Connection secured\n");
  619. }
  620. #else
  621. /* Perform service discovery */
  622. rc = peer_disc_all(event->connect.conn_handle,
  623. blecent_on_disc_complete, NULL);
  624. if(rc != 0) {
  625. MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
  626. return 0;
  627. }
  628. #endif
  629. } else {
  630. /* Connection attempt failed; resume scanning. */
  631. MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n",
  632. event->connect.status);
  633. blecent_scan();
  634. }
  635. return 0;
  636. case BLE_GAP_EVENT_DISCONNECT:
  637. /* Connection terminated. */
  638. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  639. print_conn_desc(&event->disconnect.conn);
  640. MODLOG_DFLT(INFO, "\n");
  641. /* Forget about peer. */
  642. peer_delete(event->disconnect.conn.conn_handle);
  643. /* Resume scanning. */
  644. blecent_scan();
  645. return 0;
  646. case BLE_GAP_EVENT_DISC_COMPLETE:
  647. MODLOG_DFLT(INFO, "discovery complete; reason=%d\n",
  648. event->disc_complete.reason);
  649. return 0;
  650. case BLE_GAP_EVENT_ENC_CHANGE:
  651. /* Encryption has been enabled or disabled for this connection. */
  652. MODLOG_DFLT(INFO, "encryption change event; status=%d ",
  653. event->enc_change.status);
  654. rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
  655. assert(rc == 0);
  656. print_conn_desc(&desc);
  657. #if CONFIG_EXAMPLE_ENCRYPTION
  658. /*** Go for service discovery after encryption has been successfully enabled ***/
  659. rc = peer_disc_all(event->connect.conn_handle,
  660. blecent_on_disc_complete, NULL);
  661. if (rc != 0) {
  662. MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
  663. return 0;
  664. }
  665. #endif
  666. return 0;
  667. case BLE_GAP_EVENT_NOTIFY_RX:
  668. /* Peer sent us a notification or indication. */
  669. MODLOG_DFLT(INFO, "received %s; conn_handle=%d attr_handle=%d "
  670. "attr_len=%d\n",
  671. event->notify_rx.indication ?
  672. "indication" :
  673. "notification",
  674. event->notify_rx.conn_handle,
  675. event->notify_rx.attr_handle,
  676. OS_MBUF_PKTLEN(event->notify_rx.om));
  677. /* Attribute data is contained in event->notify_rx.om. Use
  678. * `os_mbuf_copydata` to copy the data received in notification mbuf */
  679. return 0;
  680. case BLE_GAP_EVENT_MTU:
  681. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  682. event->mtu.conn_handle,
  683. event->mtu.channel_id,
  684. event->mtu.value);
  685. return 0;
  686. case BLE_GAP_EVENT_REPEAT_PAIRING:
  687. /* We already have a bond with the peer, but it is attempting to
  688. * establish a new secure link. This app sacrifices security for
  689. * convenience: just throw away the old bond and accept the new link.
  690. */
  691. /* Delete the old bond. */
  692. rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
  693. assert(rc == 0);
  694. ble_store_util_delete_peer(&desc.peer_id_addr);
  695. /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
  696. * continue with the pairing operation.
  697. */
  698. return BLE_GAP_REPEAT_PAIRING_RETRY;
  699. #if CONFIG_EXAMPLE_EXTENDED_ADV
  700. case BLE_GAP_EVENT_EXT_DISC:
  701. /* An advertisment report was received during GAP discovery. */
  702. ext_print_adv_report(&event->disc);
  703. blecent_connect_if_interesting(&event->disc);
  704. return 0;
  705. #endif
  706. #if MYNEWT_VAL(BLE_POWER_CONTROL)
  707. case BLE_GAP_EVENT_TRANSMIT_POWER:
  708. MODLOG_DFLT(INFO, "Transmit power event : status=%d conn_handle=%d reason=%d "
  709. "phy=%d power_level=%d power_level_flag=%d delta=%d",
  710. event->transmit_power.status,
  711. event->transmit_power.conn_handle,
  712. event->transmit_power.reason,
  713. event->transmit_power.phy,
  714. event->transmit_power.transmit_power_level,
  715. event->transmit_power.transmit_power_level_flag,
  716. event->transmit_power.delta);
  717. return 0;
  718. case BLE_GAP_EVENT_PATHLOSS_THRESHOLD:
  719. MODLOG_DFLT(INFO, "Pathloss threshold event : conn_handle=%d current path loss=%d "
  720. "zone_entered =%d",
  721. event->pathloss_threshold.conn_handle,
  722. event->pathloss_threshold.current_path_loss,
  723. event->pathloss_threshold.zone_entered);
  724. return 0;
  725. #endif
  726. default:
  727. return 0;
  728. }
  729. }
  730. static void
  731. blecent_on_reset(int reason)
  732. {
  733. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  734. }
  735. static void
  736. blecent_on_sync(void)
  737. {
  738. int rc;
  739. /* Make sure we have proper identity address set (public preferred) */
  740. rc = ble_hs_util_ensure_addr(0);
  741. assert(rc == 0);
  742. #if !CONFIG_EXAMPLE_INIT_DEINIT_LOOP
  743. /* Begin scanning for a peripheral to connect to. */
  744. blecent_scan();
  745. #endif
  746. }
  747. void blecent_host_task(void *param)
  748. {
  749. ESP_LOGI(tag, "BLE Host Task Started");
  750. /* This function will return only when nimble_port_stop() is executed */
  751. nimble_port_run();
  752. nimble_port_freertos_deinit();
  753. }
  754. #if CONFIG_EXAMPLE_INIT_DEINIT_LOOP
  755. /* This function showcases stack init and deinit procedure. */
  756. static void stack_init_deinit(void)
  757. {
  758. int rc;
  759. while(1) {
  760. vTaskDelay(1000);
  761. ESP_LOGI(tag, "Deinit host");
  762. rc = nimble_port_stop();
  763. if (rc == 0) {
  764. nimble_port_deinit();
  765. } else {
  766. ESP_LOGI(tag, "Nimble port stop failed, rc = %d", rc);
  767. break;
  768. }
  769. vTaskDelay(1000);
  770. ESP_LOGI(tag, "Init host");
  771. rc = nimble_port_init();
  772. if (rc != ESP_OK) {
  773. ESP_LOGI(tag, "Failed to init nimble %d ", rc);
  774. break;
  775. }
  776. nimble_port_freertos_init(blecent_host_task);
  777. ESP_LOGI(tag, "Waiting for 1 second");
  778. }
  779. }
  780. #endif
  781. void
  782. app_main(void)
  783. {
  784. int rc;
  785. /* Initialize NVS — it is used to store PHY calibration data */
  786. esp_err_t ret = nvs_flash_init();
  787. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  788. ESP_ERROR_CHECK(nvs_flash_erase());
  789. ret = nvs_flash_init();
  790. }
  791. ESP_ERROR_CHECK(ret);
  792. ret = nimble_port_init();
  793. if (ret != ESP_OK) {
  794. ESP_LOGE(tag, "Failed to init nimble %d ", ret);
  795. return;
  796. }
  797. /* Configure the host. */
  798. ble_hs_cfg.reset_cb = blecent_on_reset;
  799. ble_hs_cfg.sync_cb = blecent_on_sync;
  800. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  801. /* Initialize data structures to track connected peers. */
  802. rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
  803. assert(rc == 0);
  804. /* Set the default device name. */
  805. rc = ble_svc_gap_device_name_set("nimble-blecent");
  806. assert(rc == 0);
  807. /* XXX Need to have template for store */
  808. ble_store_config_init();
  809. nimble_port_freertos_init(blecent_host_task);
  810. #if CONFIG_EXAMPLE_INIT_DEINIT_LOOP
  811. stack_init_deinit();
  812. #endif
  813. }