From 4bedb8372b90fbb6a8df302091012115ec1cb319 Mon Sep 17 00:00:00 2001 From: Rahul Tank Date: Mon, 27 Nov 2023 08:43:00 +0530 Subject: [PATCH] feat(nimble): Added example support for Current Time Service --- components/bt/CMakeLists.txt | 2 + .../nimble/ble_cts/cts_cent/CMakeLists.txt | 6 + .../nimble/ble_cts/cts_cent/README.md | 156 +++++ .../ble_cts/cts_cent/main/CMakeLists.txt | 4 + .../ble_cts/cts_cent/main/Kconfig.projbuild | 27 + .../ble_cts/cts_cent/main/ble_cts_cent.h | 29 + .../ble_cts/cts_cent/main/idf_component.yml | 3 + .../nimble/ble_cts/cts_cent/main/main.c | 560 ++++++++++++++++++ .../ble_cts/cts_cent/sdkconfig.defaults | 12 + .../nimble/ble_cts/cts_prph/CMakeLists.txt | 6 + .../nimble/ble_cts/cts_prph/README.md | 79 +++ .../ble_cts/cts_prph/main/CMakeLists.txt | 2 + .../ble_cts/cts_prph/main/Kconfig.projbuild | 14 + .../ble_cts/cts_prph/main/ble_cts_prph.h | 27 + .../nimble/ble_cts/cts_prph/main/gatt_svr.c | 163 +++++ .../ble_cts/cts_prph/main/idf_component.yml | 3 + .../nimble/ble_cts/cts_prph/main/main.c | 315 ++++++++++ .../ble_cts/cts_prph/sdkconfig.defaults | 12 + 18 files changed, 1420 insertions(+) create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/CMakeLists.txt create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/README.md create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/main/CMakeLists.txt create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/main/Kconfig.projbuild create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/main/ble_cts_cent.h create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/main/idf_component.yml create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/main/main.c create mode 100644 examples/bluetooth/nimble/ble_cts/cts_cent/sdkconfig.defaults create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/CMakeLists.txt create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/README.md create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/main/CMakeLists.txt create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/main/Kconfig.projbuild create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/main/ble_cts_prph.h create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/main/gatt_svr.c create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/main/idf_component.yml create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/main/main.c create mode 100644 examples/bluetooth/nimble/ble_cts/cts_prph/sdkconfig.defaults diff --git a/components/bt/CMakeLists.txt b/components/bt/CMakeLists.txt index f76f6896127..80395ed0295 100644 --- a/components/bt/CMakeLists.txt +++ b/components/bt/CMakeLists.txt @@ -619,6 +619,7 @@ if(CONFIG_BT_ENABLED) host/nimble/nimble/nimble/host/services/ipss/include host/nimble/nimble/nimble/host/services/lls/include host/nimble/nimble/nimble/host/services/prox/include + host/nimble/nimble/nimble/host/services/cts/include host/nimble/nimble/nimble/host/services/tps/include host/nimble/nimble/nimble/host/util/include host/nimble/nimble/nimble/host/store/ram/include @@ -639,6 +640,7 @@ if(CONFIG_BT_ENABLED) "host/nimble/nimble/nimble/host/services/dis/src/ble_svc_dis.c" "host/nimble/nimble/nimble/host/services/lls/src/ble_svc_lls.c" "host/nimble/nimble/nimble/host/services/prox/src/ble_svc_prox.c" + "host/nimble/nimble/nimble/host/services/cts/src/ble_svc_cts.c" "host/nimble/nimble/nimble/host/src/ble_hs_conn.c" "host/nimble/nimble/nimble/host/src/ble_store_util.c" "host/nimble/nimble/nimble/host/src/ble_sm.c" diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/CMakeLists.txt b/examples/bluetooth/nimble/ble_cts/cts_cent/CMakeLists.txt new file mode 100644 index 00000000000..30e34b1f9be --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/CMakeLists.txt @@ -0,0 +1,6 @@ +# The following lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(cts_cent) diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/README.md b/examples/bluetooth/nimble/ble_cts/cts_cent/README.md new file mode 100644 index 00000000000..1dd4b84ff0e --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/README.md @@ -0,0 +1,156 @@ +| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-S3 | +| ----------------- | ----- | -------- | -------- | -------- | -------- | -------- | + +# BLE CTS Cent Example + +(See the README.md file in the upper level 'examples' directory for more information about examples.) + +This example creates GATT client and performs passive scan, it then connects to peripheral device if the device advertises connectability and the device advertises support for the Current Time Service (0x1805) as primary service UUID. + +It performs following GATT operations against the specified peer: + +* Reads the Current Time characteristic. + +If the peer does not support a required service, characteristic, or descriptor, then the peer lied when it claimed support for the Current Time Service! When this happens, or if a GATT procedure fails, this function immediately terminates the connection. + +It uses ESP32's Bluetooth controller and NimBLE stack based BLE host. + +This example aims at understanding BLE service discovery, connection, encryption and characteristic operations. + +To test this demo, use any BLE GATT server app that advertises support for the Current Time Service (0x1805) and includes it in the GATT database. + +## How to Use Example + +Before project configuration and build, be sure to set the correct chip target using: + +```bash +idf.py set-target +``` + +### Hardware Required + +* A development board with ESP32/ESP32-C2/ESP32-C3/ESP32-S3/ESP32-H2/ESP32-C6 SoC (e.g., ESP32-DevKitC, ESP-WROVER-KIT, etc.) +* A USB cable for Power supply and programming + +See [Development Boards](https://www.espressif.com/en/products/devkits) for more information about it. + +### Configure the Project + +Open the project configuration menu: + +```bash +idf.py menuconfig +``` + +In the `Example Configuration` menu: + +* Change the `Peer Address` option if needed. + +### Build and Flash + +Run `idf.py -p PORT flash monitor` to build, flash and monitor the project. + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the [Getting Started Guide](https://idf.espressif.com/) for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +This is the console output on successful connection: + +``` +I (358) BLE_INIT: BT controller compile version [59725b5] +I (358) BLE_INIT: Bluetooth MAC: 60:55:f9:68:c4:fa +I (368) phy_init: phy_version 1110,9c20f0a,Jul 27 2023,10:42:54 +I (408) NimBLE_CTS_CENT: BLE Host Task Started +I (408) NimBLE: GAP procedure initiated: stop advertising. + +I (408) NimBLE: GAP procedure initiated: discovery; +I (408) NimBLE: own_addr_type=0 filter_policy=0 passive=1 limited=0 filter_duplicates=1 +I (418) NimBLE: duration=forever +I (428) NimBLE: + +I (428) main_task: Returned from app_main() +I (628) NimBLE: GAP procedure initiated: connect; +I (628) NimBLE: peer_addr_type=1 peer_addr= +I (628) NimBLE: 6b:93:b5:30:71:cf +I (638) NimBLE: scan_itvl=16 scan_window=16 itvl_min=24 itvl_max=40 latency=0 supervision_timeout=256 min_ce_len=0 max_ce_len=0 own_addr_type=0 +I (648) NimBLE: + +I (908) NimBLE: Connection established +I (908) NimBLE: + +I (918) NimBLE: Connection secured + +I (1208) NimBLE: received indication; conn_handle=1 attr_handle=3 attr_len=4 + +I (1208) NimBLE: GAP procedure initiated: +I (1208) NimBLE: connection parameter update; conn_handle=1 itvl_min=6 itvl_max=6 latency=0 supervision_timeout=500 min_ce_len=0 max_ce_len=0 +I (1228) NimBLE: + +I (3568) NimBLE: encryption change event; status=0 +I (3568) NimBLE: GATT procedure initiated: discover all services + +I (3608) NimBLE: GATT procedure initiated: discover all characteristics; +I (3608) NimBLE: start_handle=1 end_handle=9 + +I (3658) NimBLE: GATT procedure initiated: discover all characteristics; +I (3658) NimBLE: start_handle=20 end_handle=26 + +I (3688) NimBLE: GATT procedure initiated: discover all characteristics; +I (3688) NimBLE: start_handle=134 end_handle=141 + +I (3718) NimBLE: GATT procedure initiated: discover all characteristics; +I (3718) NimBLE: start_handle=142 end_handle=151 + +I (3758) NimBLE: GATT procedure initiated: discover all characteristics; +I (3758) NimBLE: start_handle=152 end_handle=158 + +I (3788) NimBLE: GATT procedure initiated: discover all characteristics; +I (3788) NimBLE: start_handle=159 end_handle=65535 + +I (3818) NimBLE: GATT procedure initiated: discover all descriptors; +I (3818) NimBLE: chr_val_handle=136 end_handle=137 + +I (3838) NimBLE: GATT procedure initiated: discover all descriptors; +I (3838) NimBLE: chr_val_handle=144 end_handle=148 + +I (3898) NimBLE: GATT procedure initiated: discover all descriptors; +I (3898) NimBLE: chr_val_handle=150 end_handle=151 + +I (3908) NimBLE: GATT procedure initiated: discover all descriptors; +I (3908) NimBLE: chr_val_handle=161 end_handle=162 + +I (3928) NimBLE: GATT procedure initiated: discover all descriptors; +I (3928) NimBLE: chr_val_handle=164 end_handle=65535 + +I (3938) NimBLE: Service discovery complete; status=0 conn_handle=1 + +I (3938) NimBLE: GATT procedure initiated: read; +I (3938) NimBLE: att_handle=161 + +I (3958) NimBLE: Read Current time complete; status=0 conn_handle=1 +I (3958) NimBLE: attr_handle=161 value= +I (3958) NimBLE: 0xe7 +I (3958) NimBLE: :0x07 +I (3958) NimBLE: :0x08 +I (3968) NimBLE: :0x1e +I (3968) NimBLE: :0x14 +I (3968) NimBLE: :0x25 +I (3978) NimBLE: :0x02 +I (3978) NimBLE: :0x03 +I (3978) NimBLE: :0xf6 +I (3978) NimBLE: :0x00 +I (3988) NimBLE: + +I (3988) NimBLE_CTS_CENT: Date : 30/8/2023 +I (3998) NimBLE_CTS_CENT: hours : 20 minutes : 37 +I (3998) NimBLE_CTS_CENT: seconds : 2 + +I (4008) NimBLE_CTS_CENT: fractions : 0 + +``` + +## Troubleshooting + +For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon. diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/main/CMakeLists.txt b/examples/bluetooth/nimble/ble_cts/cts_cent/main/CMakeLists.txt new file mode 100644 index 00000000000..18d510d9882 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/main/CMakeLists.txt @@ -0,0 +1,4 @@ +set(srcs "main.c") + +idf_component_register(SRCS "${srcs}" + INCLUDE_DIRS ".") diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/main/Kconfig.projbuild b/examples/bluetooth/nimble/ble_cts/cts_cent/main/Kconfig.projbuild new file mode 100644 index 00000000000..8cad8f99527 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/main/Kconfig.projbuild @@ -0,0 +1,27 @@ +menu "Example Configuration" + + config EXAMPLE_PEER_ADDR + string "Peer Address" + default "ADDR_ANY" + help + Enter the peer address in aa:bb:cc:dd:ee:ff form to connect to a specific peripheral + + config EXAMPLE_ENCRYPTION + bool + prompt "Enable Link Encryption" + default y + help + This enables bonding and encryption after connection has been established. + + config EXAMPLE_EXTENDED_ADV + bool + depends on SOC_BLE_50_SUPPORTED + default y if SOC_ESP_NIMBLE_CONTROLLER + select BT_NIMBLE_EXT_ADV + prompt "Enable Extended Adv" + help + Use this option to enable extended advertising in the example. + If this option is disabled, ensure config BT_NIMBLE_EXT_ADV is + also disabled from Nimble stack menuconfig + +endmenu diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/main/ble_cts_cent.h b/examples/bluetooth/nimble/ble_cts/cts_cent/main/ble_cts_cent.h new file mode 100644 index 00000000000..2a734676bb8 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/main/ble_cts_cent.h @@ -0,0 +1,29 @@ +/* + * SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef H_BLE_CTS_CENT_ +#define H_BLE_CTS_CENT_ + +#include "modlog/modlog.h" +#include "esp_central.h" +#ifdef __cplusplus +extern "C" { +#endif + +struct ble_hs_adv_fields; +struct ble_gap_conn_desc; +struct ble_hs_cfg; +union ble_store_value; +union ble_store_key; + +/* 16 BIT CCCD UUID */ +#define BLE_SVC_CTS_DSC_CLT_CFG_UUID16 0x2902 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/main/idf_component.yml b/examples/bluetooth/nimble/ble_cts/cts_cent/main/idf_component.yml new file mode 100644 index 00000000000..db8886afea4 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/main/idf_component.yml @@ -0,0 +1,3 @@ +dependencies: + nimble_central_utils: + path: ${IDF_PATH}/examples/bluetooth/nimble/common/nimble_central_utils diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/main/main.c b/examples/bluetooth/nimble/ble_cts/cts_cent/main/main.c new file mode 100644 index 00000000000..fd235c4dfeb --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/main/main.c @@ -0,0 +1,560 @@ +/* + * SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "esp_log.h" +#include "nvs_flash.h" +/* BLE */ +#include "nimble/nimble_port.h" +#include "nimble/nimble_port_freertos.h" +#include "host/ble_hs.h" +#include "host/util/util.h" +#include "console/console.h" +#include "services/gap/ble_svc_gap.h" +#include "ble_cts_cent.h" +#include "services/cts/ble_svc_cts.h" + +static const char *tag = "NimBLE_CTS_CENT"; +static int ble_cts_cent_gap_event(struct ble_gap_event *event, void *arg); +static uint8_t peer_addr[6]; + +static char *day_of_week[7] = { + "Unknown" + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday" +}; +void ble_store_config_init(void); +static void ble_cts_cent_scan(void); + +void printtime(struct ble_svc_cts_curr_time ctime) { + ESP_LOGI(tag, "Date : %d/%d/%d %s", ctime.et_256.d_d_t.d_t.day, + ctime.et_256.d_d_t.d_t.month, + ctime.et_256.d_d_t.d_t.year, + day_of_week[ctime.et_256.d_d_t.day_of_week]); + ESP_LOGI(tag, "hours : %d minutes : %d ", + ctime.et_256.d_d_t.d_t.hours, + ctime.et_256.d_d_t.d_t.minutes); + ESP_LOGI(tag, "seconds : %d\n", ctime.et_256.d_d_t.d_t.seconds); + ESP_LOGI(tag, "fractions : %d\n", ctime.et_256.fractions_256); +} + +/** + * Application callback. Called when the read of the cts current time + * characteristic has completed. + */ +static int +ble_cts_cent_on_read(uint16_t conn_handle, + const struct ble_gatt_error *error, + struct ble_gatt_attr *attr, + void *arg) +{ + struct ble_svc_cts_curr_time ctime; /* store the read time */ + MODLOG_DFLT(INFO, "Read Current time complete; status=%d conn_handle=%d\n", + error->status, conn_handle); + if (error->status == 0) { + MODLOG_DFLT(INFO, " attr_handle=%d value=\n", attr->handle); + print_mbuf(attr->om); + } + else { + goto err; + } + MODLOG_DFLT(INFO, "\n"); + ble_hs_mbuf_to_flat(attr->om, &ctime, sizeof(ctime), NULL); + printtime(ctime); + return 0; +err: + /* Terminate the connection. */ + return ble_gap_terminate(conn_handle, BLE_ERR_REM_USER_CONN_TERM); +} + +/** + * Performs read on the current time characteristic + * + */ +static int +ble_cts_cent_read_time(const struct peer *peer) +{ + + /* Subscribe to notifications for the Current Time Characteristic. + * A central enables notifications by writing two bytes (1, 0) to the + * characteristic's client-characteristic-configuration-descriptor (CCCD). + */ + const struct peer_chr *chr; + int rc; + + chr = peer_chr_find_uuid(peer, + BLE_UUID16_DECLARE(BLE_SVC_CTS_UUID16), + BLE_UUID16_DECLARE(BLE_SVC_CTS_CHR_UUID16_CURRENT_TIME)); + if (chr == NULL) { + MODLOG_DFLT(ERROR, "Error: Peer doesn't support the CTS " + " characteristic\n"); + goto err; + } + rc = ble_gattc_read(peer->conn_handle, chr->chr.val_handle, + ble_cts_cent_on_read, NULL); + if (rc != 0) { + MODLOG_DFLT(ERROR, "Error: Failed to read characteristic; rc=%d\n", + rc); + goto err; + } + + return 0; +err: + /* Terminate the connection. */ + return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM); +} + +/** + * Called when service discovery of the specified peer has completed. + */ +static void +ble_cts_cent_on_disc_complete(const struct peer *peer, int status, void *arg) +{ + + if (status != 0) { + /* Service discovery failed. Terminate the connection. */ + MODLOG_DFLT(ERROR, "Error: Service discovery failed; status=%d " + "conn_handle=%d\n", status, peer->conn_handle); + ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM); + return; + } + + /* Service discovery has completed successfully. Now we have a complete + * list of services, characteristics, and descriptors that the peer + * supports. + */ + MODLOG_DFLT(INFO, "Service discovery complete; status=%d " + "conn_handle=%d\n", status, peer->conn_handle); + + /* Now perform GATT procedure against the peer: read + * for the cts service. + */ + ble_cts_cent_read_time(peer); +} + +/** + * Initiates the GAP general discovery procedure. + */ +static void +ble_cts_cent_scan(void) +{ + uint8_t own_addr_type; + struct ble_gap_disc_params disc_params; + int rc; + + /* Figure out address to use while advertising (no privacy for now) */ + rc = ble_hs_id_infer_auto(0, &own_addr_type); + if (rc != 0) { + MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc); + return; + } + + /* Tell the controller to filter duplicates; we don't want to process + * repeated advertisements from the same device. + */ + disc_params.filter_duplicates = 1; + + /** + * Perform a passive scan. I.e., don't send follow-up scan requests to + * each advertiser. + */ + disc_params.passive = 1; + + /* Use defaults for the rest of the parameters. */ + disc_params.itvl = 0; + disc_params.window = 0; + disc_params.filter_policy = 0; + disc_params.limited = 0; + + rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params, + ble_cts_cent_gap_event, NULL); + if (rc != 0) { + MODLOG_DFLT(ERROR, "Error initiating GAP discovery procedure; rc=%d\n", + rc); + } +} + +/** + * Indicates whether we should try to connect to the sender of the specified + * advertisement. The function returns a positive result if the device + * advertises connectability and support for the Current Time Service. + */ + +#if CONFIG_EXAMPLE_EXTENDED_ADV +static int +ext_ble_cts_cent_should_connect(const struct ble_gap_ext_disc_desc *disc) +{ + int offset = 0; + int ad_struct_len = 0; + + if (disc->legacy_event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND && + disc->legacy_event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) { + return 0; + } + if (strlen(CONFIG_EXAMPLE_PEER_ADDR) && (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen("ADDR_ANY")) != 0)) { + ESP_LOGI(tag, "Peer address from menuconfig: %s", CONFIG_EXAMPLE_PEER_ADDR); + /* Convert string to address */ + sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", + &peer_addr[5], &peer_addr[4], &peer_addr[3], + &peer_addr[2], &peer_addr[1], &peer_addr[0]); + if (memcmp(peer_addr, disc->addr.val, sizeof(disc->addr.val)) != 0) { + return 0; + } + } + + /* The device has to advertise support for the CTS + * service (0x1805). + */ + do { + ad_struct_len = disc->data[offset]; + + if (!ad_struct_len) { + break; + } + + /* Search if cts UUID is advertised */ + if (disc->data[offset + 1] == 0x03) { + int temp = 2; + while(temp < disc->data[offset + 1]) { + if(disc->data[offset + temp] == 0x05 && + disc->data[offset + temp + 1] == 0x18) { + return 1; + } + temp += 2; + } + } + offset += ad_struct_len + 1; + } while ( offset < disc->length_data ); + + return 0; +} +#else + +static int +ble_cts_cent_should_connect(const struct ble_gap_disc_desc *disc) +{ + struct ble_hs_adv_fields fields; + int rc; + int i; + + /* The device has to be advertising connectability. */ + if (disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND && + disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) { + + return 0; + } + + rc = ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data); + if (rc != 0) { + return 0; + } + + if (strlen(CONFIG_EXAMPLE_PEER_ADDR) && (strncmp(CONFIG_EXAMPLE_PEER_ADDR, "ADDR_ANY", strlen("ADDR_ANY")) != 0)) { + ESP_LOGI(tag, "Peer address from menuconfig: %s", CONFIG_EXAMPLE_PEER_ADDR); + /* Convert string to address */ + sscanf(CONFIG_EXAMPLE_PEER_ADDR, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", + &peer_addr[5], &peer_addr[4], &peer_addr[3], + &peer_addr[2], &peer_addr[1], &peer_addr[0]); + if (memcmp(peer_addr, disc->addr.val, sizeof(disc->addr.val)) != 0) { + return 0; + } + } + + /* The device has to advertise support for the Current Time + * service (0x1805). + */ + for (i = 0; i < fields.num_uuids16; i++) { + if (ble_uuid_u16(&fields.uuids16[i].u) == BLE_SVC_CTS_UUID16) { + return 1; + } + } + + return 0; +} +#endif + +/** + * Connects to the sender of the specified advertisement of it looks + * interesting. A device is "interesting" if it advertises connectability and + * support for the Current Time service. + */ +static void +ble_cts_cent_connect_if_interesting(void *disc) +{ + uint8_t own_addr_type; + int rc; + ble_addr_t *addr; + + /* Don't do anything if we don't care about this advertiser. */ +#if CONFIG_EXAMPLE_EXTENDED_ADV + if (!ext_ble_cts_cent_should_connect((struct ble_gap_ext_disc_desc *)disc)) { + return; + } +#else + if (!ble_cts_cent_should_connect((struct ble_gap_disc_desc *)disc)) { + return; + } +#endif + + /* Scanning must be stopped before a connection can be initiated. */ + rc = ble_gap_disc_cancel(); + if (rc != 0) { + MODLOG_DFLT(DEBUG, "Failed to cancel scan; rc=%d\n", rc); + return; + } + + /* Figure out address to use for connect (no privacy for now) */ + rc = ble_hs_id_infer_auto(0, &own_addr_type); + if (rc != 0) { + MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc); + return; + } + + /* Try to connect the the advertiser. Allow 30 seconds (30000 ms) for + * timeout. + */ +#if CONFIG_EXAMPLE_EXTENDED_ADV + addr = &((struct ble_gap_ext_disc_desc *)disc)->addr; +#else + addr = &((struct ble_gap_disc_desc *)disc)->addr; +#endif + rc = ble_gap_connect(own_addr_type, addr, 30000, NULL, + ble_cts_cent_gap_event, NULL); + if (rc != 0) { + MODLOG_DFLT(ERROR, "Error: Failed to connect to device; addr_type=%d " + "addr=%s; rc=%d\n", + addr->type, addr_str(addr->val), rc); + return; + } +} + +/** + * The nimble host executes this callback when a GAP event occurs. The + * application associates a GAP event callback with each connection that is + * established. ble_cts_cent uses the same callback for all connections. + * + * @param event The event being signalled. + * @param arg Application-specified argument; unused by + * ble_cts_cent. + * + * @return 0 if the application successfully handled the + * event; nonzero on failure. The semantics + * of the return code is specific to the + * particular GAP event being signalled. + */ +static int +ble_cts_cent_gap_event(struct ble_gap_event *event, void *arg) +{ + struct ble_gap_conn_desc desc; + struct ble_hs_adv_fields fields; + int rc; + + switch (event->type) { + case BLE_GAP_EVENT_DISC: + rc = ble_hs_adv_parse_fields(&fields, event->disc.data, + event->disc.length_data); + if (rc != 0) { + return 0; + } + + /* An advertisment report was received during GAP discovery. */ + print_adv_fields(&fields); + + /* Try to connect to the advertiser if it looks interesting. */ + ble_cts_cent_connect_if_interesting(&event->disc); + return 0; + + case BLE_GAP_EVENT_CONNECT: + /* A new connection was established or a connection attempt failed. */ + if (event->connect.status == 0) { + /* Connection successfully established. */ + MODLOG_DFLT(INFO, "Connection established "); + + rc = ble_gap_conn_find(event->connect.conn_handle, &desc); + assert(rc == 0); + print_conn_desc(&desc); + MODLOG_DFLT(INFO, "\n"); + + /* Remember peer. */ + rc = peer_add(event->connect.conn_handle); + if (rc != 0) { + MODLOG_DFLT(ERROR, "Failed to add peer; rc=%d\n", rc); + return 0; + } + +#if CONFIG_EXAMPLE_ENCRYPTION + /** Initiate security - It will perform + * Pairing (Exchange keys) + * Bonding (Store keys) + * Encryption (Enable encryption) + * Will invoke event BLE_GAP_EVENT_ENC_CHANGE + **/ + rc = ble_gap_security_initiate(event->connect.conn_handle); + if (rc != 0) { + MODLOG_DFLT(INFO, "Security could not be initiated, rc = %d\n", rc); + return ble_gap_terminate(event->connect.conn_handle, + BLE_ERR_REM_USER_CONN_TERM); + } else { + MODLOG_DFLT(INFO, "Connection secured\n"); + } +#else + /* Perform service discovery */ + rc = peer_disc_all(event->connect.conn_handle, + ble_cts_cent_on_disc_complete, NULL); + if (rc != 0) { + MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc); + return 0; + } +#endif + } else { + /* Connection attempt failed; resume scanning. */ + MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n", + event->connect.status); + ble_cts_cent_scan(); + } + + return 0; + + case BLE_GAP_EVENT_DISCONNECT: + /* Connection terminated. */ + MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason); + print_conn_desc(&event->disconnect.conn); + MODLOG_DFLT(INFO, "\n"); + + /* Forget about peer. */ + peer_delete(event->disconnect.conn.conn_handle); + + /* Resume scanning. */ + ble_cts_cent_scan(); + return 0; + + case BLE_GAP_EVENT_DISC_COMPLETE: + MODLOG_DFLT(INFO, "discovery complete; reason=%d\n", + event->disc_complete.reason); + return 0; + + case BLE_GAP_EVENT_ENC_CHANGE: + /* Encryption has been enabled or disabled for this connection. */ + MODLOG_DFLT(INFO, "encryption change event; status=%d ", + event->enc_change.status); + rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc); + assert(rc == 0); + print_conn_desc(&desc); +#if CONFIG_EXAMPLE_ENCRYPTION + /*** Go for service discovery after encryption has been successfully enabled ***/ + rc = peer_disc_all(event->connect.conn_handle, + ble_cts_cent_on_disc_complete, NULL); + if (rc != 0) { + MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc); + return 0; + } +#endif + return 0; + + case BLE_GAP_EVENT_NOTIFY_RX: + /* Peer sent us a notification or indication. */ + MODLOG_DFLT(INFO, "received %s; conn_handle=%d attr_handle=%d " + "attr_len=%d\n", + event->notify_rx.indication ? + "indication" : + "notification", + event->notify_rx.conn_handle, + event->notify_rx.attr_handle, + OS_MBUF_PKTLEN(event->notify_rx.om)); + + /* Attribute data is contained in event->notify_rx.om. Use + * `os_mbuf_copydata` to copy the data received in notification mbuf */ + return 0; + + case BLE_GAP_EVENT_MTU: + MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n", + event->mtu.conn_handle, + event->mtu.channel_id, + event->mtu.value); + return 0; + +#if CONFIG_EXAMPLE_EXTENDED_ADV + case BLE_GAP_EVENT_EXT_DISC: + /* An advertisment report was received during GAP discovery. */ + ext_print_adv_report(&event->disc); + + ble_cts_cent_connect_if_interesting(&event->disc); + return 0; +#endif + + default: + return 0; + } +} + +static void +ble_cts_cent_on_reset(int reason) +{ + MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason); +} + +static void +ble_cts_cent_on_sync(void) +{ + int rc; + + /* Make sure we have proper identity address set (public preferred) */ + rc = ble_hs_util_ensure_addr(0); + assert(rc == 0); + + /* Begin scanning for a peripheral to connect to. */ + ble_cts_cent_scan(); +} + +void ble_cts_cent_host_task(void *param) +{ + ESP_LOGI(tag, "BLE Host Task Started"); + /* This function will return only when nimble_port_stop() is executed */ + nimble_port_run(); + + nimble_port_freertos_deinit(); +} + +void +app_main(void) +{ + int rc; + /* Initialize NVS — it is used to store PHY calibration data */ + esp_err_t ret = nvs_flash_init(); + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + ESP_ERROR_CHECK(ret); + + ret = nimble_port_init(); + if (ret != ESP_OK) { + ESP_LOGE(tag, "Failed to init nimble %d ", ret); + return; + } + + /* Configure the host. */ + ble_hs_cfg.reset_cb = ble_cts_cent_on_reset; + ble_hs_cfg.sync_cb = ble_cts_cent_on_sync; + ble_hs_cfg.store_status_cb = ble_store_util_status_rr; + + /* Initialize data structures to track connected peers. */ + rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64); + assert(rc == 0); + + /* Set the default device name. */ + rc = ble_svc_gap_device_name_set("nimble-cts-cent"); + assert(rc == 0); + + /* XXX Need to have template for store */ + ble_store_config_init(); + + nimble_port_freertos_init(ble_cts_cent_host_task); +} diff --git a/examples/bluetooth/nimble/ble_cts/cts_cent/sdkconfig.defaults b/examples/bluetooth/nimble/ble_cts/cts_cent/sdkconfig.defaults new file mode 100644 index 00000000000..c829fc5c002 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_cent/sdkconfig.defaults @@ -0,0 +1,12 @@ +# Override some defaults so BT stack is enabled +# in this example + +# +# BT config +# +CONFIG_BT_ENABLED=y +CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y +CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n +CONFIG_BTDM_CTRL_MODE_BTDM=n +CONFIG_BT_BLUEDROID_ENABLED=n +CONFIG_BT_NIMBLE_ENABLED=y diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/CMakeLists.txt b/examples/bluetooth/nimble/ble_cts/cts_prph/CMakeLists.txt new file mode 100644 index 00000000000..81409326b1f --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/CMakeLists.txt @@ -0,0 +1,6 @@ +# The following lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(cts_prph) diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/README.md b/examples/bluetooth/nimble/ble_cts/cts_prph/README.md new file mode 100644 index 00000000000..9897fd4c527 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/README.md @@ -0,0 +1,79 @@ +| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-S3 | +| ----------------- | ----- | -------- | -------- | -------- | -------- | -------- | + +# BLE Current Time Service Example + +(See the README.md file in the upper level 'examples' directory for more information about examples.) + +This example creates GATT server demonstrating standard Current Time Service. + +It advertises support for the Current Time Service(0x1805) as primary service UUID. + +It uses ESP32's Bluetooth controller and NimBLE stack based BLE host + + +## How to Use Example + +Before project configuration and build, be sure to set the correct chip target using: + +```bash +idf.py set-target +``` + +### Hardware Required + +* A development board with ESP32/ESP32-C3 SoC (e.g., ESP32-DevKitC, ESP-WROVER-KIT, etc.) +* A USB cable for Power supply and programming + +See [Development Boards](https://www.espressif.com/en/products/devkits) for more information about it. + +### Build and Flash + +Run `idf.py -p PORT flash monitor` to build, flash and monitor the project. + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the [Getting Started Guide](https://idf.espressif.com/) for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +This console output can be observed when client is connected to server : + +``` +I (357) BLE_INIT: BT controller compile version [59725b5] +I (357) BLE_INIT: Bluetooth MAC: 60:55:f9:68:c4:fa +I (367) phy_init: phy_version 1110,9c20f0a,Jul 27 2023,10:42:54 +I (407) NimBLE_cts_PRPH: BLE Host Task Started +I (407) NimBLE: GAP procedure initiated: stop advertising. + +I (407) NimBLE: Failed to restore IRKs from store; status=8 + +I (407) NimBLE: Device Address: +I (417) NimBLE: 60:55:f9:68:c4:fa +I (417) NimBLE: + +I (417) NimBLE: GAP procedure initiated: advertise; +I (427) NimBLE: disc_mode=2 +I (427) NimBLE: adv_channel_map=0 own_addr_type=0 adv_filter_policy=0 adv_itvl_min=0 adv_itvl_max=0 +I (437) NimBLE: + +I (447) main_task: Returned from app_main() + +I (27317) NimBLE: GAP procedure initiated: advertise; +I (27317) NimBLE: disc_mode=2 +I (27327) NimBLE: adv_channel_map=0 own_addr_type=0 adv_filter_policy=0 adv_itvl_min=0 adv_itvl_max=0 +I (27337) NimBLE: + +I (31987) NimBLE: connection established; status=0 + +I (53297) NimBLE: subscribe event; cur_notify=1 + value handle; val_handle=12 + + I (68317) NimBLE: subscribe event; cur_notify=0 + value handle; val_handle=12 + +``` + +## Troubleshooting + +For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon. diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/main/CMakeLists.txt b/examples/bluetooth/nimble/ble_cts/cts_prph/main/CMakeLists.txt new file mode 100644 index 00000000000..e8a76d0b091 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "main.c" "gatt_svr.c" + INCLUDE_DIRS ".") diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/main/Kconfig.projbuild b/examples/bluetooth/nimble/ble_cts/cts_prph/main/Kconfig.projbuild new file mode 100644 index 00000000000..a5240035348 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/main/Kconfig.projbuild @@ -0,0 +1,14 @@ +menu "Example Configuration" + + config EXAMPLE_EXTENDED_ADV + bool + depends on SOC_BLE_50_SUPPORTED + default y if SOC_ESP_NIMBLE_CONTROLLER + select BT_NIMBLE_EXT_ADV + prompt "Enable Extended Adv" + help + Use this option to enable extended advertising in the example. + If this option is disabled, ensure config BT_NIMBLE_EXT_ADV is + also disabled from Nimble stack menuconfig + +endmenu diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/main/ble_cts_prph.h b/examples/bluetooth/nimble/ble_cts/cts_prph/main/ble_cts_prph.h new file mode 100644 index 00000000000..744130053f2 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/main/ble_cts_prph.h @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef H_BLE_CTS_PRPH_ +#define H_BLE_CTS_PRPH_ + +#include "nimble/ble.h" +#include "modlog/modlog.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct ble_hs_cfg; +struct ble_gatt_register_ctxt; + +void gatt_svr_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg); +int gatt_svr_init(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/main/gatt_svr.c b/examples/bluetooth/nimble/ble_cts/cts_prph/main/gatt_svr.c new file mode 100644 index 00000000000..7a5cc19367b --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/main/gatt_svr.c @@ -0,0 +1,163 @@ +/* + * SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include "host/ble_hs.h" +#include "host/ble_uuid.h" +#include "services/gap/ble_svc_gap.h" +#include "services/gatt/ble_svc_gatt.h" +#include "ble_cts_prph.h" +#include "services/cts/ble_svc_cts.h" +#include +#include "sys/time.h" + + +void +gatt_svr_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg) +{ + char buf[BLE_UUID_STR_LEN]; + + switch (ctxt->op) { + case BLE_GATT_REGISTER_OP_SVC: + MODLOG_DFLT(DEBUG, "registered service %s with handle=%d\n", + ble_uuid_to_str(ctxt->svc.svc_def->uuid, buf), + ctxt->svc.handle); + break; + + case BLE_GATT_REGISTER_OP_CHR: + MODLOG_DFLT(DEBUG, "registering characteristic %s with " + "def_handle=%d val_handle=%d\n", + ble_uuid_to_str(ctxt->chr.chr_def->uuid, buf), + ctxt->chr.def_handle, + ctxt->chr.val_handle); + break; + + case BLE_GATT_REGISTER_OP_DSC: + MODLOG_DFLT(DEBUG, "registering descriptor %s with handle=%d\n", + ble_uuid_to_str(ctxt->dsc.dsc_def->uuid, buf), + ctxt->dsc.handle); + break; + + default: + assert(0); + break; + } +} + +static struct ble_svc_cts_local_time_info local_info = { .timezone = 0, .dst_offset = TIME_STANDARD }; +static struct timeval last_updated; +uint8_t adjust_reason; +int fetch_current_time(struct ble_svc_cts_curr_time *ctime) { + time_t now; + struct tm timeinfo; + struct timeval tv_now; + /* time given by 'time()' api does not persist after reboots */ + time(&now); + localtime_r(&now, &timeinfo); + gettimeofday(&tv_now, NULL); + if(ctime != NULL) { + /* fill date_time */ + ctime->et_256.d_d_t.d_t.year = timeinfo.tm_year + 1900; + ctime->et_256.d_d_t.d_t.month = timeinfo.tm_mon + 1; + ctime->et_256.d_d_t.d_t.day = timeinfo.tm_mday; + ctime->et_256.d_d_t.d_t.hours = timeinfo.tm_hour; + ctime->et_256.d_d_t.d_t.minutes = timeinfo.tm_min; + ctime->et_256.d_d_t.d_t.seconds = timeinfo.tm_sec; + + /* day of week */ + /* time gives day range of [0, 6], current_time_sevice + has day range of [1,7] */ + ctime->et_256.d_d_t.day_of_week = timeinfo.tm_wday + 1; + + /* fractions_256 */ + ctime->et_256.fractions_256 = (((uint64_t)tv_now.tv_usec * 256L )/ 1000000L); + + ctime->adjust_reason = adjust_reason; + } + return 0; +} + +int set_current_time(struct ble_svc_cts_curr_time ctime) { + time_t now; + struct tm timeinfo; + struct timeval tv_now; + /* fill date_time */ + timeinfo.tm_year= ctime.et_256.d_d_t.d_t.year - 1900 ; + timeinfo.tm_mon = ctime.et_256.d_d_t.d_t.month - 1; + timeinfo.tm_mday = ctime.et_256.d_d_t.d_t.day; + timeinfo.tm_hour = ctime.et_256.d_d_t.d_t.hours; + timeinfo.tm_min = ctime.et_256.d_d_t.d_t.minutes; + timeinfo.tm_sec = ctime.et_256.d_d_t.d_t.seconds; + timeinfo.tm_wday = ctime.et_256.d_d_t.day_of_week - 1; + now = mktime(&timeinfo); + tv_now.tv_sec = now; + settimeofday(&tv_now, NULL); + /* set the last updated */ + gettimeofday(&last_updated, NULL); + adjust_reason = ctime.adjust_reason; + return 0; +} + +int fetch_local_time_info(struct ble_svc_cts_local_time_info *info) { + + if(info != NULL) { + memcpy(info, &local_info, sizeof local_info); + } + return 0; +} + +int set_local_time_info(struct ble_svc_cts_local_time_info info) { + /* just store the dst offset and timezone locally + as we don't have the access to time using ntp server */ + local_info.timezone = info.timezone; + local_info.dst_offset = info.dst_offset; + gettimeofday(&last_updated, NULL); + return 0; +} +int fetch_reference_time_info(struct ble_svc_cts_reference_time_info *info) { + struct timeval tv_now; + uint64_t days_since_update; + uint64_t hours_since_update; + + gettimeofday(&tv_now, NULL); + /* subtract the time when the last time was updated */ + tv_now.tv_sec -= last_updated.tv_sec; /* ignore microseconds */ + info->time_source = TIME_SOURCE_MANUAL; + info->time_accuracy = 0; + days_since_update = (tv_now.tv_sec / 86400L); + hours_since_update = (tv_now.tv_sec / 3600); + info->days_since_update = days_since_update < 255 ? days_since_update : 255; + + if(days_since_update > 254) { + info->hours_since_update = 255; + } + else { + hours_since_update = (tv_now.tv_sec % 86400L) / 3600; + info->hours_since_update = hours_since_update; + } + adjust_reason = (CHANGE_OF_DST_MASK | CHANGE_OF_TIME_ZONE_MASK); + + return 0; +} +int +gatt_svr_init(void) +{ + struct ble_svc_cts_cfg cfg; + + ble_svc_gap_init(); + ble_svc_gatt_init(); + + cfg.fetch_time_cb = fetch_current_time; + cfg.local_time_info_cb = fetch_local_time_info; + cfg.ref_time_info_cb = fetch_reference_time_info; + cfg.set_time_cb = set_current_time; + cfg.set_local_time_info_cb = set_local_time_info; + ble_svc_cts_init(cfg); + + return 0; +} diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/main/idf_component.yml b/examples/bluetooth/nimble/ble_cts/cts_prph/main/idf_component.yml new file mode 100644 index 00000000000..d6e735fe770 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/main/idf_component.yml @@ -0,0 +1,3 @@ +dependencies: + nimble_peripheral_utils: + path: ${IDF_PATH}/examples/bluetooth/nimble/common/nimble_peripheral_utils diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/main/main.c b/examples/bluetooth/nimble/ble_cts/cts_prph/main/main.c new file mode 100644 index 00000000000..53bb6897bc6 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/main/main.c @@ -0,0 +1,315 @@ +/* + * SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "esp_log.h" +#include "nvs_flash.h" +#include "freertos/FreeRTOSConfig.h" +/* BLE */ +#include "nimble/nimble_port.h" +#include "nimble/nimble_port_freertos.h" +#include "host/ble_hs.h" +#include "host/util/util.h" +#include "console/console.h" +#include "services/gap/ble_svc_gap.h" +#include "ble_cts_prph.h" +#include "services/cts/ble_svc_cts.h" + +#if CONFIG_EXAMPLE_EXTENDED_ADV +static uint8_t ext_adv_pattern_1[] = { + 0x02, 0x01, 0x06, + 0x03, 0x03, 0xab, 0xcd, + 0x03, 0x03, 0x05, 0x18, + 0x12, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 'c', 't', 's', '-', 'p', 'r', 'p', 'h', '-', 'e', +}; +#endif + +static const char *tag = "NimBLE_CTS_PRPH"; +static const char *device_name = "ble_cts_prph"; + +static int ble_cts_prph_gap_event(struct ble_gap_event *event, void *arg); + +static uint8_t ble_cts_prph_addr_type; + +/** + * Utility function to log an array of bytes. + */ +void +print_bytes(const uint8_t *bytes, int len) +{ + int i; + for (i = 0; i < len; i++) { + MODLOG_DFLT(INFO, "%s0x%02x", i != 0 ? ":" : "", bytes[i]); + } +} + +void +print_addr(const void *addr) +{ + const uint8_t *u8p; + + u8p = addr; + MODLOG_DFLT(INFO, "%02x:%02x:%02x:%02x:%02x:%02x", + u8p[5], u8p[4], u8p[3], u8p[2], u8p[1], u8p[0]); +} + +#if CONFIG_EXAMPLE_EXTENDED_ADV +/** + * Enables advertising with the following parameters: + * o General discoverable mode. + * o Undirected connectable mode. + */ +static void +ext_ble_cts_prph_advertise(void) +{ + struct ble_gap_ext_adv_params params; + struct os_mbuf *data; + uint8_t instance = 0; + int rc; + + /* First check if any instance is already active */ + if (ble_gap_ext_adv_active(instance)) { + return; + } + + /* use defaults for non-set params */ + memset (¶ms, 0, sizeof(params)); + + /* enable connectable advertising */ + params.connectable = 1; + + /* advertise using random addr */ + params.own_addr_type = BLE_OWN_ADDR_PUBLIC; + + params.primary_phy = BLE_HCI_LE_PHY_1M; + params.secondary_phy = BLE_HCI_LE_PHY_2M; + params.sid = 1; + + params.itvl_min = BLE_GAP_ADV_FAST_INTERVAL1_MIN; + params.itvl_max = BLE_GAP_ADV_FAST_INTERVAL1_MIN; + + /* configure instance 0 */ + rc = ble_gap_ext_adv_configure(instance, ¶ms, NULL, + ble_cts_prph_gap_event, NULL); + assert (rc == 0); + + /* in this case only scan response is allowed */ + + /* get mbuf for scan rsp data */ + data = os_msys_get_pkthdr(sizeof(ext_adv_pattern_1), 0); + assert(data); + + /* fill mbuf with scan rsp data */ + rc = os_mbuf_append(data, ext_adv_pattern_1, sizeof(ext_adv_pattern_1)); + assert(rc == 0); + + rc = ble_gap_ext_adv_set_data(instance, data); + assert (rc == 0); + + /* start advertising */ + rc = ble_gap_ext_adv_start(instance, 0, 0); + assert (rc == 0); +} +#else + +static void +ble_cts_prph_advertise(void) +{ + struct ble_gap_adv_params adv_params; + struct ble_hs_adv_fields fields; + int rc; + + /* + * Set the advertisement data included in our advertisements: + * o Flags (indicates advertisement type and other general info) + * o Advertising tx power + * o Device name + */ + memset(&fields, 0, sizeof(fields)); + + /* + * Advertise two flags: + * o Discoverability in forthcoming advertisement (general) + * o BLE-only (BR/EDR unsupported) + */ + fields.flags = BLE_HS_ADV_F_DISC_GEN | + BLE_HS_ADV_F_BREDR_UNSUP; + + /* + * Indicate that the TX power level field should be included; have the + * stack fill this value automatically. This is done by assigning the + * special value BLE_HS_ADV_TX_PWR_LVL_AUTO. + */ + fields.tx_pwr_lvl_is_present = 1; + fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO; + + fields.name = (uint8_t *)device_name; + fields.name_len = strlen(device_name); + fields.name_is_complete = 1; + + fields.uuids16 = (ble_uuid16_t[]) { + BLE_UUID16_INIT(BLE_SVC_CTS_UUID16) + }; + fields.num_uuids16 = 1; + fields.uuids16_is_complete = 1; + + rc = ble_gap_adv_set_fields(&fields); + if (rc != 0) { + MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc); + return; + } + + /* Begin advertising */ + memset(&adv_params, 0, sizeof(adv_params)); + adv_params.conn_mode = BLE_GAP_CONN_MODE_UND; + adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN; + rc = ble_gap_adv_start(ble_cts_prph_addr_type, NULL, BLE_HS_FOREVER, + &adv_params, ble_cts_prph_gap_event, NULL); + if (rc != 0) { + MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc); + return; + } +} +#endif + +static int +ble_cts_prph_gap_event(struct ble_gap_event *event, void *arg) +{ + switch (event->type) { + case BLE_GAP_EVENT_CONNECT: + /* A new connection was established or a connection attempt failed */ + MODLOG_DFLT(INFO, "connection %s; status=%d\n", + event->connect.status == 0 ? "established" : "failed", + event->connect.status); + + if (event->connect.status != 0) { + /* Connection failed; resume advertising */ +#if CONFIG_EXAMPLE_EXTENDED_ADV + ext_ble_cts_prph_advertise(); +#else + ble_cts_prph_advertise(); +#endif + + } + break; + + case BLE_GAP_EVENT_DISCONNECT: + MODLOG_DFLT(INFO, "disconnect; reason=%d\n", event->disconnect.reason); + + /* Connection terminated; resume advertising */ +#if CONFIG_EXAMPLE_EXTENDED_ADV + ext_ble_cts_prph_advertise(); +#else + ble_cts_prph_advertise(); +#endif + + break; + + case BLE_GAP_EVENT_ADV_COMPLETE: + MODLOG_DFLT(INFO, "adv complete\n"); +#if CONFIG_EXAMPLE_EXTENDED_ADV + ext_ble_cts_prph_advertise(); +#else + ble_cts_prph_advertise(); +#endif + break; + + case BLE_GAP_EVENT_SUBSCRIBE: + MODLOG_DFLT(INFO, "subscribe event; cur_notify=%d\n value handle; " + "val_handle=%d\n", + event->subscribe.cur_notify, event->subscribe.attr_handle); + + break; + + case BLE_GAP_EVENT_MTU: + MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d mtu=%d\n", + event->mtu.conn_handle, + event->mtu.value); + break; + + } + + return 0; +} + +static void +ble_cts_prph_on_sync(void) +{ + int rc; + + rc = ble_hs_id_infer_auto(0, &ble_cts_prph_addr_type); + assert(rc == 0); + + uint8_t addr_val[6] = {0}; + rc = ble_hs_id_copy_addr(ble_cts_prph_addr_type, addr_val, NULL); + + MODLOG_DFLT(INFO, "Device Address: "); + print_addr(addr_val); + MODLOG_DFLT(INFO, "\n"); + + /* Begin advertising */ +#if CONFIG_EXAMPLE_EXTENDED_ADV + ext_ble_cts_prph_advertise(); +#else + ble_cts_prph_advertise(); +#endif +} + +static void +ble_cts_prph_on_reset(int reason) +{ + MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason); +} + +void ble_cts_prph_host_task(void *param) +{ + ESP_LOGI(tag, "BLE Host Task Started"); + /* This function will return only when nimble_port_stop() is executed */ + nimble_port_run(); + + nimble_port_freertos_deinit(); +} + +void app_main(void) +{ + int rc; + + /* Initialize NVS — it is used to store PHY calibration data */ + esp_err_t ret = nvs_flash_init(); + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + ESP_ERROR_CHECK(ret); + + ret = nimble_port_init(); + if (ret != ESP_OK) { + MODLOG_DFLT(ERROR, "Failed to init nimble %d \n", ret); + return; + } + + /* Initialize the NimBLE host configuration */ + ble_hs_cfg.sync_cb = ble_cts_prph_on_sync; + ble_hs_cfg.reset_cb = ble_cts_prph_on_reset; + + /* Enable bonding */ + ble_hs_cfg.sm_bonding = 1; + ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID; + ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID; + + ble_hs_cfg.sm_sc = 1; + ble_hs_cfg.sm_mitm = 1; + + rc = gatt_svr_init(); + assert(rc == 0); + + /* Set the default device name */ + rc = ble_svc_gap_device_name_set(device_name); + assert(rc == 0); + + /* Start the task */ + nimble_port_freertos_init(ble_cts_prph_host_task); + +} diff --git a/examples/bluetooth/nimble/ble_cts/cts_prph/sdkconfig.defaults b/examples/bluetooth/nimble/ble_cts/cts_prph/sdkconfig.defaults new file mode 100644 index 00000000000..c829fc5c002 --- /dev/null +++ b/examples/bluetooth/nimble/ble_cts/cts_prph/sdkconfig.defaults @@ -0,0 +1,12 @@ +# Override some defaults so BT stack is enabled +# in this example + +# +# BT config +# +CONFIG_BT_ENABLED=y +CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y +CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n +CONFIG_BTDM_CTRL_MODE_BTDM=n +CONFIG_BT_BLUEDROID_ENABLED=n +CONFIG_BT_NIMBLE_ENABLED=y