feat (NimBLE): Add proximity sensor as a service

This commit is contained in:
isha.pardikar@espressif.com 2023-04-11 11:21:15 +05:30
parent 64ba835d05
commit 893967f596
20 changed files with 2166 additions and 1 deletions

View File

@ -531,6 +531,7 @@ if(CONFIG_BT_ENABLED)
host/nimble/nimble/nimble/host/services/ias/include
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/tps/include
host/nimble/nimble/nimble/host/util/include
host/nimble/nimble/nimble/host/store/ram/include
@ -549,6 +550,7 @@ if(CONFIG_BT_ENABLED)
"host/nimble/nimble/nimble/host/services/bas/src/ble_svc_bas.c"
"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/src/ble_hs_conn.c"
"host/nimble/nimble/nimble/host/src/ble_store_util.c"
"host/nimble/nimble/nimble/host/src/ble_sm.c"

@ -1 +1 @@
Subproject commit abc80c36cab77cc47c62b0cdbbcedf53346460c4
Subproject commit 528a67f4e73f9521609879587a1d7d2180e18372

View File

@ -192,6 +192,12 @@ examples/bluetooth/nimble/ble_phy:
temporary: true
reason: The runner doesn't support yet
examples/bluetooth/nimble/ble_proximity_sensor:
enable:
- if: IDF_TARGET in ["esp32", "esp32c2", "esp32c3", "esp32c6", "esp32h2", "esp32h4", "esp32s3"]
temporary: true
reason: the other targets are not tested yet
examples/bluetooth/nimble/ble_spp:
enable:
- if: IDF_TARGET in ["esp32", "esp32c2", "esp32c3", "esp32c6", "esp32h2", "esp32s3" ]

View File

@ -0,0 +1,8 @@
# 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)
set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/bluetooth/nimble/common/nimble_central_utils)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(proximity_sensor_cent)

View File

@ -0,0 +1,219 @@
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-S3 |
| ----------------- | ----- | -------- | -------- | -------- | -------- | -------- |
# BLE Central Proximity Sensor 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 Link Loss service (0x1803) as primary service UUID.
It alerts the application when link gets disconnected.
After connection it enables bonding and link encryprion if the `Enable Link Encryption` flag is set in the example config.
It performs following GATT operations against the specified peer:
* Writes the alert level characteristic of link loss service.
* After the write operation is completed, reads the tx power level characteristic.
* It continuously calculated the path loss. If the path loss exceeds high threshold, it writes to alert level characteristic of immediate alert service of peripheral to start alerting.
* If the path loss drops below the low threshold, it writes to alert level characteristic of immediate alert service of peripheral to stop alerting.
If the peer does not support a required service, characteristic, or descriptor, then the peer lied when it claimed support for the Link Loss 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 Link Loss service (0x1803) 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 <chip_name>
```
### Hardware Required
* A development board with ESP32/ESP32-C2/ESP32-C3/ESP32-S3 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 [a186b41]
I (358) phy_init: phy_version 970,1856f88,May 10 2023,17:44:12
I (418) BLE_INIT: Bluetooth MAC: 7c:df:a1:66:a5:c6
I (418) NimBLE_PROX_CENT: BLE Host Task Started
I (418) NimBLE: GAP procedure initiated: stop advertising.
I (418) NimBLE: GAP procedure initiated: discovery;
I (428) NimBLE: own_addr_type=0 filter_policy=0 passive=1 limited=0 filter_duplicates=1
I (438) NimBLE: duration=forever
I (438) NimBLE:
I (448) main_task: Returned from app_main()
I (478) NimBLE: GAP procedure initiated: connect;
I (478) NimBLE: peer_addr_type=0 peer_addr=
I (488) NimBLE: 84:f7:03:05:a5:f6
I (488) 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 (498) NimBLE:
I (548) NimBLE: Connection established
I (548) NimBLE:
I (548) NimBLE: Connection secured
I (558) NimBLE: encryption change event; status=1288
I (558) NimBLE: GATT procedure initiated: discover all services
I (658) NimBLE: GATT procedure initiated: discover all characteristics;
I (658) NimBLE: start_handle=1 end_handle=4
I (858) NimBLE: GATT procedure initiated: discover all characteristics;
I (858) NimBLE: start_handle=5 end_handle=8
I (1058) NimBLE: GATT procedure initiated: discover all characteristics;
I (1058) NimBLE: start_handle=9 end_handle=65535
I (1258) NimBLE: GATT procedure initiated: discover all descriptors;
I (1258) NimBLE: chr_val_handle=3 end_handle=4
I (1358) NimBLE: GATT procedure initiated: discover all descriptors;
I (1358) NimBLE: chr_val_handle=7 end_handle=8
I (1458) NimBLE: GATT procedure initiated: discover all descriptors;
I (1458) NimBLE: chr_val_handle=11 end_handle=65535
I (1558) NimBLE: Service discovery complete; status=0 conn_handle=1
I (1558) NimBLE: GATT procedure initiated: write;
I (1558) NimBLE: att_handle=3 len=1
I (1658) NimBLE: Write alert level char completed; status=0 conn_handle=1
I (3707) NimBLE: Read on tx power level char completed; status=0 conn_handle=1
I (3707) NimBLE: attr_handle=11 value=
I (3707) NimBLE: 0x80
I (5427) NimBLE: Connection handle : 1
I (5427) NimBLE: Current RSSI = -16
I (5427) NimBLE: path loss = -112 pwr lvl = -128 rssi = -16
I (5427) NimBLE: GATT procedure initiated: write no rsp;
I (5427) NimBLE: att_handle=7 len=4
I (5437) NimBLE: Write to alert level characteristis done
I (10447) NimBLE: Connection handle : 1
I (10447) NimBLE: Current RSSI = -16
I (10447) NimBLE: path loss = -112 pwr lvl = -128 rssi = -16
I (10447) NimBLE: GATT procedure initiated: write no rsp;
I (10457) NimBLE: att_handle=7 len=4
I (10457) NimBLE: Write to alert level characteristis done
I (15467) NimBLE: Connection handle : 1
I (15467) NimBLE: Current RSSI = -8
I (15467) NimBLE: path loss = -120 pwr lvl = -128 rssi = -8
I (15467) NimBLE: GATT procedure initiated: write no rsp;
I (15477) NimBLE: att_handle=7 len=4
I (15477) NimBLE: Write to alert level characteristis done
I (20487) NimBLE: Connection handle : 1
I (20487) NimBLE: Current RSSI = -75
I (20487) NimBLE: path loss = -53 pwr lvl = -128 rssi = -75
I (20487) NimBLE: GATT procedure initiated: write no rsp;
I (20497) NimBLE: att_handle=7 len=4
I (20497) NimBLE: Write to alert level characteristis done
I (25507) NimBLE: Connection handle : 1
I (25507) NimBLE: Current RSSI = -38
I (25507) NimBLE: path loss = -90 pwr lvl = -128 rssi = -38
I (25507) NimBLE: GATT procedure initiated: write no rsp;
I (25517) NimBLE: att_handle=7 len=4
I (25517) NimBLE: Write to alert level characteristis done
I (30527) NimBLE: Connection handle : 1
I (30527) NimBLE: Current RSSI = -9
I (30527) NimBLE: path loss = -119 pwr lvl = -128 rssi = -9
I (30527) NimBLE: GATT procedure initiated: write no rsp;
I (30537) NimBLE: att_handle=7 len=4
I (30537) NimBLE: Write to alert level characteristis done
I (35547) NimBLE: Connection handle : 1
I (35547) NimBLE: Current RSSI = -9
I (35547) NimBLE: path loss = -119 pwr lvl = -128 rssi = -9
I (35547) NimBLE: GATT procedure initiated: write no rsp;
I (35557) NimBLE: att_handle=7 len=4
I (35557) NimBLE: Write to alert level characteristis done
I (40567) NimBLE: Connection handle : 1
I (40567) NimBLE: Current RSSI = -9
I (40567) NimBLE: path loss = -119 pwr lvl = -128 rssi = -9
I (40567) NimBLE: GATT procedure initiated: write no rsp;
I (40577) NimBLE: att_handle=7 len=4
I (40577) NimBLE: Write to alert level characteristis done
I (45587) NimBLE: Connection handle : 1
I (45587) NimBLE: Current RSSI = -9
I (45587) NimBLE: path loss = -119 pwr lvl = -128 rssi = -9
I (45587) NimBLE: GATT procedure initiated: write no rsp;
I (45597) NimBLE: att_handle=7 len=4
I (45597) NimBLE: Write to alert level characteristis done
I (50607) NimBLE: Connection handle : 1
I (50607) NimBLE: Current RSSI = -9
I (50607) NimBLE: path loss = -119 pwr lvl = -128 rssi = -9
I (50607) NimBLE: GATT procedure initiated: write no rsp;
I (50617) NimBLE: att_handle=7 len=4
I (50617) NimBLE: Write to alert level characteristis done
I (8957) NimBLE: GAP procedure initiated: discovery;
I (8967) NimBLE: own_addr_type=0 filter_policy=0 passive=1 limited=0 filter_duplicates=1
I (8977) NimBLE: duration=forever
I (8977) NimBLE:
I (10407) NimBLE: Link lost for device with conn_handle 0
I (15407) NimBLE: Link lost for device with conn_handle 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.

View File

@ -0,0 +1,4 @@
set(srcs "main.c")
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS ".")

View File

@ -0,0 +1,24 @@
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
endmenu

View File

@ -0,0 +1,47 @@
/*
* SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef H_BLE_PROX_CENT_
#define H_BLE_PROX_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 Proximity Sensor Service UUID */
#define BLE_SVC_IMMEDIATE_ALERT_UUID16 0x1802
#define BLE_SVC_LINK_LOSS_UUID16 0x1803
#define BLE_SVC_TX_POWER_UUID16 0x1804
/* 16 Bit Proximity Sensor Service Characteristic UUIDs */
#define BLE_SVC_PROX_CHR_UUID16_ALERT_LVL 0x2A06
#define BLE_SVC_PROX_CHR_UUID16_TX_PWR_LVL 0x2A07
#define BLE_ADDR_LEN 6
struct ble_prox_cent_conn_peer {
uint16_t val_handle;
bool calc_path_loss;
};
struct ble_prox_cent_link_lost_peer {
uint8_t *addr;
bool link_lost;
};
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,715 @@
/*
* 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_prox_cent.h"
static const char *tag = "NimBLE_PROX_CENT";
static uint8_t peer_addr[6];
static uint8_t link_supervision_timeout;
static int8_t tx_pwr_lvl;
static struct ble_prox_cent_conn_peer conn_peer[MYNEWT_VAL(BLE_MAX_CONNECTIONS) + 1];
static struct ble_prox_cent_link_lost_peer disconn_peer[MYNEWT_VAL(BLE_MAX_CONNECTIONS) + 1];
/* Note: Path loss is calculated using formula : threshold - RSSI value
* by default threshold is kept -128 as per the spec
* high_threshold and low_threshold are hardcoded after testing and noting
* RSSI values when distance betweeen devices are less and more.
*/
static int8_t high_threshold = -70;
static int8_t low_threshold = -100;
void ble_store_config_init(void);
static void ble_prox_cent_scan(void);
static int ble_prox_cent_gap_event(struct ble_gap_event *event, void *arg);
static int
ble_prox_cent_on_read(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attr,
void *arg)
{
MODLOG_DFLT(INFO, "Read on tx power level char completed; status=%d "
"conn_handle=%d\n",
error->status, conn_handle);
if (error->status == 0) {
MODLOG_DFLT(INFO, " attr_handle=%d value=", attr->handle);
print_mbuf(attr->om);
os_mbuf_copydata(attr->om, 0, attr->om->om_len, &tx_pwr_lvl);
conn_peer[conn_handle].calc_path_loss = true;
}
return 0;
}
/**
* Application callback. Called when the write of alert level char
* characteristic has completed.
*/
static int
ble_prox_cent_on_write(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attr,
void *arg)
{
MODLOG_DFLT(INFO, "Write alert level char completed; status=%d conn_handle=%d",
error->status, conn_handle);
/* Read Tx Power level characteristic. */
const struct peer_chr *chr;
int rc;
const struct peer *peer = peer_find(conn_handle);
chr = peer_chr_find_uuid(peer,
BLE_UUID16_DECLARE(BLE_SVC_TX_POWER_UUID16),
BLE_UUID16_DECLARE(BLE_SVC_PROX_CHR_UUID16_TX_PWR_LVL));
if (chr == NULL) {
MODLOG_DFLT(ERROR, "Error: Peer doesn't support the"
"Tx power level characteristic\n");
goto err;
}
rc = ble_gattc_read(conn_handle, chr->chr.val_handle,
ble_prox_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);
}
/**
* Performs following GATT operations against the specified peer:
* 1. Writes the alert level characteristic.
* 2. After write is completed, it reads the Tx Power Level characteristic.
*
* If the peer does not support a required service, characteristic, or
* descriptor, then the peer lied when it claimed support for the link
* loss service! When this happens, or if a GATT procedure fails,
* this function immediately terminates the connection.
*/
static void
ble_prox_cent_read_write_subscribe(const struct peer *peer)
{
const struct peer_chr *chr;
int rc;
/* Storing the val handle of immediate alert characteristic */
chr = peer_chr_find_uuid(peer,
BLE_UUID16_DECLARE(BLE_SVC_IMMEDIATE_ALERT_UUID16),
BLE_UUID16_DECLARE(BLE_SVC_PROX_CHR_UUID16_ALERT_LVL));
if (chr != NULL) {
conn_peer[peer->conn_handle].val_handle = chr->chr.val_handle;
} else {
MODLOG_DFLT(ERROR, "Error: Peer doesn't support the alert level"
" characteristic of immediate alert loss service\n");
}
/* Write alert level characteristic. */
chr = peer_chr_find_uuid(peer,
BLE_UUID16_DECLARE(BLE_SVC_LINK_LOSS_UUID16),
BLE_UUID16_DECLARE(BLE_SVC_PROX_CHR_UUID16_ALERT_LVL));
if (chr == NULL) {
MODLOG_DFLT(ERROR, "Error: Peer doesn't support the alert level"
" characteristic\n");
goto err;
}
rc = ble_gattc_write_flat(peer->conn_handle, chr->chr.val_handle,
&link_supervision_timeout, sizeof(link_supervision_timeout),
ble_prox_cent_on_write, NULL);
if (rc != 0) {
MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
rc);
goto err;
}
return;
err:
/* Terminate the connection. */
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_prox_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 procedures against the peer: read,
* write.
*/
ble_prox_cent_read_write_subscribe(peer);
}
/**
* Initiates the GAP general discovery procedure.
*/
static void
ble_prox_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_prox_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 Health Thermometer service.
*/
#if CONFIG_EXAMPLE_EXTENDED_ADV
static int
ext_ble_prox_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 Proximity sensor (link loss)
* service (0x1803).
*/
do {
ad_struct_len = disc->data[offset];
if (!ad_struct_len) {
break;
}
/* Search if Proximity Sensor (Link loss) UUID is advertised */
if (disc->data[offset] == 0x03 && disc->data[offset + 1] == 0x03) {
if ( disc->data[offset + 2] == 0x18 && disc->data[offset + 3] == 0x03 ) {
return 1;
}
}
offset += ad_struct_len + 1;
} while ( offset < disc->length_data );
return 0;
}
#else
static int
ble_prox_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 rc;
}
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 Proximity sensor (link loss)
* service (0x1803).
*/
for (i = 0; i < fields.num_uuids16; i++) {
if (ble_uuid_u16(&fields.uuids16[i].u) == BLE_SVC_LINK_LOSS_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 Proximity Sensor service.
*/
static void
ble_prox_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_prox_cent_should_connect((struct ble_gap_ext_disc_desc *)disc)) {
return;
}
#else
if (!ble_prox_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_prox_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_prox_cent uses the same callback for all connections.
*
* @param event The event being signalled.
* @param arg Application-specified argument; unused by
* ble_prox_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_prox_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_prox_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");
link_supervision_timeout = 8 * desc.conn_itvl;
/* 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;
}
/* Check if this device is reconnected */
for (int i = 0; i <= MYNEWT_VAL(BLE_MAX_CONNECTIONS); i++) {
if (disconn_peer[i].addr != NULL) {
if (memcmp(disconn_peer[i].addr, &desc.peer_id_addr.val, BLE_ADDR_LEN)) {
/* Peer reconnected. Stop alert for this peer */
free(disconn_peer[i].addr);
disconn_peer[i].addr = NULL;
disconn_peer[i].link_lost = false;
break;
}
}
}
#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_prox_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_prox_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");
/* Start the link loss alert for this connection handle */
for (int i = 0; i <= MYNEWT_VAL(BLE_MAX_CONNECTIONS); i++) {
if (disconn_peer[i].addr == NULL) {
disconn_peer[i].addr = (uint8_t *)malloc(BLE_ADDR_LEN * sizeof(uint8_t));
if (disconn_peer[i].addr == NULL) {
return BLE_HS_ENOMEM;
}
memcpy(disconn_peer[i].addr, &event->disconnect.conn.peer_id_addr.val,
BLE_ADDR_LEN);
disconn_peer[i].link_lost = true;
break;
}
}
/* Stop calculating path loss, restart once connection is established again */
conn_peer[event->disconnect.conn.conn_handle].calc_path_loss = false;
conn_peer[event->disconnect.conn.conn_handle].val_handle = 0;
/* Forget about peer. */
peer_delete(event->disconnect.conn.conn_handle);
/* Resume scanning. */
ble_prox_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_prox_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;
case BLE_GAP_EVENT_REPEAT_PAIRING:
/* We already have a bond with the peer, but it is attempting to
* establish a new secure link. This app sacrifices security for
* convenience: just throw away the old bond and accept the new link.
*/
/* Delete the old bond. */
rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
assert(rc == 0);
ble_store_util_delete_peer(&desc.peer_id_addr);
/* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
* continue with the pairing operation.
*/
return BLE_GAP_REPEAT_PAIRING_RETRY;
#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_prox_cent_connect_if_interesting(&event->disc);
return 0;
#endif
default:
return 0;
}
}
void
ble_prox_cent_path_loss_task(void *pvParameters)
{
int8_t rssi;
int rc;
int path_loss;
while (1) {
for (int i = 0; i <= MYNEWT_VAL(BLE_MAX_CONNECTIONS); i++) {
if (conn_peer[i].calc_path_loss) {
MODLOG_DFLT(INFO, "Connection handle : %d", i);
rc = ble_gap_conn_rssi(i, &rssi);
if (rc == 0) {
MODLOG_DFLT(INFO, "Current RSSI = %d", rssi);
} else {
MODLOG_DFLT(ERROR, "Failed to get current RSSI");
}
path_loss = tx_pwr_lvl - rssi;
MODLOG_DFLT(INFO, "path loss = %d pwr lvl = %d rssi = %d",
path_loss, tx_pwr_lvl, rssi);
if ((conn_peer[i].val_handle != 0) &&
(path_loss > high_threshold || path_loss < low_threshold)) {
if (path_loss < low_threshold) {
path_loss = 0;
}
rc = ble_gattc_write_no_rsp_flat(i, conn_peer[i].val_handle,
&path_loss, sizeof(path_loss));
if (rc != 0) {
MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
rc);
} else {
MODLOG_DFLT(INFO, "Write to alert level characteristis done");
}
}
}
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void
ble_prox_cent_link_loss_task(void *pvParameters)
{
while (1) {
for (int i = 0; i <= MYNEWT_VAL(BLE_MAX_CONNECTIONS); i++) {
if (disconn_peer[i].link_lost && disconn_peer[i].addr != NULL) {
MODLOG_DFLT(INFO, "Link lost for device with conn_handle %d", i);
}
}
vTaskDelay(5000 / portTICK_PERIOD_MS);
}
}
static void
ble_prox_cent_on_reset(int reason)
{
MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
}
static void
ble_prox_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_prox_cent_scan();
}
void ble_prox_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();
}
static void
ble_prox_cent_init(void)
{
/* Task for calculating path loss */
xTaskCreate(ble_prox_cent_path_loss_task, "ble_prox_cent_path_loss_task", 4096, NULL, 10, NULL);
/* Task for alerting when link is lost */
xTaskCreate(ble_prox_cent_link_loss_task, "ble_prox_cent_link_loss_task", 4096, NULL, 10, NULL);
return;
}
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;
}
/* Initialize a task to keep checking path loss of the link */
ble_prox_cent_init();
for (int i = 0; i <= MYNEWT_VAL(BLE_MAX_CONNECTIONS); i++) {
disconn_peer[i].addr = NULL;
disconn_peer[i].link_lost = true;
}
/* Configure the host. */
ble_hs_cfg.reset_cb = ble_prox_cent_on_reset;
ble_hs_cfg.sync_cb = ble_prox_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-prox-cent");
assert(rc == 0);
/* XXX Need to have template for store */
ble_store_config_init();
nimble_port_freertos_init(ble_prox_cent_host_task);
}

View File

@ -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

View File

@ -0,0 +1,409 @@
# BLE Central Proximity Sensory Example Walkthrough
## Introduction
In this tutorial, the ble_proximity_sensor central example code for the espressif chipsets with BLE5.0 support is reviewed. 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 Link Loss service (0x1803) as primary service UUID. After connection it enables bonding and link encryprion if the `Enable Link Encryption` flag is set in the example config.
## Includes
This example is located in the examples folder of the ESP-IDF under the [ble_proximity_sensor/proximity_sensor_cent/main](../main). The [main.c](../main/main.c) file located in the main folder contains all the functionality that we are going to review. The header files contained in [main.c](../main/main.c) are:
```c
#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_prox_cent.h"
```
These `includes` are required for the FreeRTOS and underlying system components to run, including the logging functionality and a library to store data in non-volatile flash memory. We are interested in `“nimble_port.h”`, `“nimble_port_freertos.h”`, `"ble_hs.h"` and `“ble_svc_gap.h”`, `“ble_prox_cent.h”` which expose the BLE APIs required to implement this example.
* `nimble_port.h`: Includes the declaration of functions required for the initialization of the nimble stack.
* `nimble_port_freertos.h`: Initializes and enables nimble host task.
* `ble_hs.h`: Defines the functionalities to handle the host event.
* `ble_svc_gap.h`:Defines the macros for device name ,device apperance and declare the function to set them.
* `ble_prox_cent.h`: Defines the 16 bit Link Loss SVC UUID.
## Main Entry Point
The programs entry point is the app_main() function:
```c
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);
nimble_port_init();
/* Configure the host. */
ble_hs_cfg.reset_cb = ble_prox_cent_on_reset;
ble_hs_cfg.sync_cb = ble_prox_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-prox-cent");
assert(rc == 0);
/* XXX Need to have template for store */
ble_store_config_init();
nimble_port_freertos_init(ble_prox_cent_host_task);
}
```
The main function starts by initializing the non-volatile storage library. This library allows to save the key-value pairs in flash memory.`nvs_flash_init()` stores the PHY calibration data. In a Bluetooth Low Energy (BLE) device, cryptographic keys used for encryption and authentication are often stored in Non-Volatile Storage (NVS).BLE stores the peer keys, CCCD keys, peer records, etc on NVS.By storing these keys in NVS, the BLE device can quickly retrieve them when needed, without the need for time-consuming key generations.
```c
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 );
```
## BT Controller and Stack Initialization
The main function calls `nimble_port_init()` to initialize BT Controller and nimble stack. This function initializes the BT controller by first creating its configuration structure named `esp_bt_controller_config_t` with default settings generated by the `BT_CONTROLLER_INIT_CONFIG_DEFAULT()` macro. It implements the Host Controller Interface (HCI) on the controller side, the Link Layer (LL), and the Physical Layer (PHY). The BT Controller is invisible to the user applications and deals with the lower layers of the BLE stack. The controller configuration includes setting the BT controller stack size, priority, and HCI baud rate. With the settings created, the BT controller is initialized and enabled with the `esp_bt_controller_init()` and `esp_bt_controller_enable()` functions:
```c
esp_bt_controller_config_t config_opts = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ret = esp_bt_controller_init(&config_opts);
```
Next, the controller is enabled in BLE Mode.
```c
ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
```
>The controller should be enabled in `ESP_BT_MODE_BLE` if you want to use the BLE mode.
There are four Bluetooth modes supported:
1. `ESP_BT_MODE_IDLE`: Bluetooth not running
2. `ESP_BT_MODE_BLE`: BLE mode
3. `ESP_BT_MODE_CLASSIC_BT`: BT Classic mode
4. `ESP_BT_MODE_BTDM`: Dual mode (BLE + BT Classic)
After the initialization of the BT controller, the nimble stack, which includes the common definitions and APIs for BLE, is initialized by using `esp_nimble_init()`:
```c
esp_err_t esp_nimble_init(void)
{
#if !SOC_ESP_NIMBLE_CONTROLLER
/* Initialize the function pointers for OS porting */
npl_freertos_funcs_init();
npl_freertos_mempool_init();
if(esp_nimble_hci_init() != ESP_OK) {
ESP_LOGE(NIMBLE_PORT_LOG_TAG, "hci inits failed\n");
return ESP_FAIL;
}
/* Initialize default event queue */
ble_npl_eventq_init(&g_eventq_dflt);
/* Initialize the global memory pool */
os_mempool_module_init();
os_msys_init();
#endif
/* Initialize the host */
ble_transport_hs_init();
return ESP_OK;
}
```
The host is configured by setting up the callbacks for Stack-reset, Stack-sync, and Storage status
```c
ble_hs_cfg.reset_cb = ble_prox_cent_on_reset;
ble_hs_cfg.sync_cb = ble_prox_cent_on_sync;
ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
```
Further Data Structures are created and initialized to track connected peers using `peer_init()`. This function creates memory buffers to generate the memory pools like `peer_pool`, `peer_svc_pool`, `peer_chr_pool`, and `peer_dsc_pool`.
```c
rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
```
## Structure of Peer
The structure of a peer includes fields such as its connection handle, a pointer to the next peer, a list of discovered gatt services, tracking parameters for the service discovery process, and the callbacks that get executed when service discovery completes.
```c
struct peer {
SLIST_ENTRY(peer) next;
uint16_t conn_handle;
struct peer_svc_list svcs;
uint16_t disc_prev_chr_val;
struct peer_svc *cur_svc;
peer_disc_fn *disc_cb;
void *disc_cb_arg;
};
```
The main function calls `ble_svc_gap_device_name_set()` to set the default device name. 'nimble-prox-cent' is passed as the default device name to this function.
```c
rc = ble_svc_gap_device_name_set("nimble-prox-cent");
```
main function calls `ble_store_config_init()` to configure the host by setting up the storage callbacks which handle the read, write, and deletion of security material.
```c
/* XXX Need to have a template for store */
ble_store_config_init();
```
The main function ends by creating a task where nimble will run using `nimble_port_freertos_init()`. This enables the nimble stack by using `esp_nimble_enable()`.
```c
nimble_port_freertos_init(ble_prox_cent_host_task);
```
`esp_nimble_enable()` create a task where the nimble host will run. It is not strictly necessary to have a separate task for the nimble host, but since something needs to handle the default queue, it is easier to create a separate task.
## Overall code flow.
It performs following GATT operations against the specified peer:
* Writes the alert level characteristic of link loss service.
* After the write operation is completed, reads the tx power level characteristic.
* It continuously calculated the path loss. If the path loss exceeds high threshold, it writes to alert level characteristic of immediate alert service of peripheral to start alerting.
* If the path loss drops below the low threshold, it writes to alert level characteristic of immediate alert service of peripheral to stop alerting.
## Write Operation
`ble_prox_cent_read_write_subscribe` stores the value handle of alert level characteristic of immediate alert service and then writes on the alert level characteristic of link loss service. If the peer does not support a required service, characteristic, or descriptor OR if a GATT procedure fails , then this function immediately terminates the connection.
```c
static void
ble_prox_cent_read_write_subscribe(const struct peer *peer)
{
const struct peer_chr *chr;
int rc;
/* Storing the val handle of immediate alert characteristic */
chr = peer_chr_find_uuid(peer,
BLE_UUID16_DECLARE(BLE_SVC_IMMEDIATE_ALERT_UUID16),
BLE_UUID16_DECLARE(BLE_SVC_PROX_CHR_UUID16_ALERT_LVL));
if (chr != NULL) {
conn_peer[peer->conn_handle].val_handle = chr->chr.val_handle;
} else {
MODLOG_DFLT(ERROR, "Error: Peer doesn't support the alert level"
" characteristic of immediate alert loss service\n");
}
/* Write alert level characteristic. */
chr = peer_chr_find_uuid(peer,
BLE_UUID16_DECLARE(BLE_SVC_LINK_LOSS_UUID16),
BLE_UUID16_DECLARE(BLE_SVC_PROX_CHR_UUID16_ALERT_LVL));
if (chr == NULL) {
MODLOG_DFLT(ERROR, "Error: Peer doesn't support the alert level"
" characteristic\n");
goto err;
}
rc = ble_gattc_write_flat(peer->conn_handle, chr->chr.val_handle,
&link_supervision_timeout, sizeof(link_supervision_timeout),
ble_prox_cent_on_write, NULL);
if (rc != 0) {
MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
rc);
goto err;
}
return;
err:
/* Terminate the connection. */
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
}
```
## Read Operation
`ble_prox_cent_on_write` reads the tx power level after writing on alert level is completed. If the peer does not support a required service, characteristic, or descriptor OR if a GATT procedure fails , then this function immediately terminates the connection.
```c
static int
ble_prox_cent_on_write(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attr,
void *arg)
{
MODLOG_DFLT(INFO, "Write alert level char completed; status=%d conn_handle=%d",
error->status, conn_handle);
/* Read Tx Power level characteristic. */
const struct peer_chr *chr;
int rc;
const struct peer *peer = peer_find(conn_handle);
chr = peer_chr_find_uuid(peer,
BLE_UUID16_DECLARE(BLE_SVC_TX_POWER_UUID16),
BLE_UUID16_DECLARE(BLE_SVC_PROX_CHR_UUID16_TX_PWR_LVL));
if (chr == NULL) {
MODLOG_DFLT(ERROR, "Error: Peer doesn't support the"
"Tx power level characteristic\n");
goto err;
}
rc = ble_gattc_read(conn_handle, chr->chr.val_handle,
ble_prox_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);
}
```
## BLE GAP Connect Event
Once the connection is established `BLE_GAP_EVENT_CONNECT` event occurs. Once connected, it proceeds to perform the service discovery. If the connection attempt is failed then central start scanning again using the `ble_prox_cent_scan` function.
```c
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");
link_supervision_timeout = 6 * desc.conn_itvl;
/* 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;
}
< snip >
} else {
/* Connection attempt failed; resume scanning. */
MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n",
event->connect.status);
ble_prox_cent_scan();
}
return 0;
```
## BLE GAP Disconnect Event
The connection between Central and Peripheral is terminated when the service discovery is failed or the GATT procedure is completed. `ble_gap_terminate` function is used to terminate the connection which results in the event called `BLE_GAP_EVENT_DISCONNECT`.
```c
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");
/* Stop calculating path loss, restart once connection is established again */
conn_peer[event->disconnect.conn.conn_handle].calc_path_loss = false;
conn_peer[event->disconnect.conn.conn_handle].val_handle = 0;
/* Forget about peer. */
peer_delete(event->disconnect.conn.conn_handle);
ble_prox_cent_scan();
return 0;
```
## Central Task
`ble_prox_cent_task` is a task which calculate path loss in intervals for all the connected devices. If the path loss exceeds the `high_threshold`, it performs a `ble_gattc_write_no_rsp` to alert prph with path loss to start alerting. If path loss falls below than `low_threshold`, it performs a `ble_gattc_write_no_rsp` to alert prph with path loss to stop alerting.
```c
while (1) {
for (int i = 0; i <= MYNEWT_VAL(BLE_MAX_CONNECTIONS); i++) {
if (conn_peer[i].calc_path_loss) {
MODLOG_DFLT(INFO, "Connection handle : %d", i);
rc = ble_gap_conn_rssi(i, &rssi);
if (rc == 0) {
MODLOG_DFLT(INFO, "Current RSSI = %d", rssi);
} else {
MODLOG_DFLT(ERROR, "Failed to get current RSSI");
}
path_loss = tx_pwr_lvl - rssi;
MODLOG_DFLT(INFO, "path loss = %d pwr lvl = %d rssi = %d",
path_loss, tx_pwr_lvl, rssi);
if ((conn_peer[i].val_handle != 0) &&
(path_loss > high_threshold || path_loss < low_threshold)) {
rc = ble_gattc_write_no_rsp_flat(i, conn_peer[i].val_handle,
&path_loss, sizeof(path_loss));
if (rc != 0) {
MODLOG_DFLT(ERROR, "Error: Failed to write characteristic; rc=%d\n",
rc);
} else {
MODLOG_DFLT(INFO, "Write to alert level characteristis done");
}
}
}
}
vTaskDelay(500);
}
```
## Threshold
```c
/* Note: Path loss is calculated using formula : threshold - RSSI value
* by default threshold is kept -128 as per the spec
* high_threshold and low_threshold are hardcoded after testing and noting
* RSSI values when distance betweeen devices are less and more.
*/
static int8_t high_threshold = -70;
static int8_t low_threshold = -100;
```
## Conclusion
This Walkthrough covers the code explanation of the BLE_PROX_CENTRAL example. The following points are concluded through this walkthrough.
1. First a connection is made with a device supporting the Link Loss service.
2. Gatt operations are performed on the characteristic and results displayed.

View File

@ -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(proximity_sensor_prph)

View File

@ -0,0 +1,89 @@
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-S3 |
| ----------------- | ----- | -------- | -------- | -------- | -------- | -------- |
# BLE Peripheral Proximity Sensor Example
(See the README.md file in the upper level 'examples' directory for more information about examples.)
This example creates GATT server demonstrating standard Proximity Sensor profile. It notifies the application when the distance between devices increases.
It advertises support for the Link Loss service (0x1803) as primary service UUID.
The `ble_prox_prph_task` start alerting to application as soon as a write command is received from central regarding exceeding path loss. The alert stops when path loss is below low_threshold value.
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 <chip_name>
```
### 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 proximity_sensor_prph is connected to client:
```
I (356) BLE_INIT: BT controller compile version [a186b41]
I (356) phy_init: phy_version 970,1856f88,May 10 2023,17:44:12
I (416) BLE_INIT: Bluetooth MAC: 84:f7:03:05:a5:f6
I (416) NimBLE_PROX_PRPH: BLE Host Task Started
I (416) NimBLE: GAP procedure initiated: stop advertising.
I (426) NimBLE: Device Address:
I (426) NimBLE: 84:f7:03:05:a5:f6
I (436) NimBLE:
I (436) NimBLE: GAP procedure initiated: advertise;
I (446) NimBLE: disc_mode=2
I (446) NimBLE: adv_channel_map=0 own_addr_type=0 adv_filter_policy=0 adv_itvl_min=0 adv_itvl_max=0
I (456) NimBLE:
I (456) main_task: Returned from app_main()
I (4546) NimBLE: connection established; status=0
I (3576) NimBLE: Path loss = -112
I (8576) NimBLE: Path loss = -112
I (13626) NimBLE: Path loss = -120
I (18626) NimBLE: Path loss = -53
I (18626) NimBLE: Path loss exceeded threshold, starting alert for device with conn_handle 1
I (19406) NimBLE: Path loss increased for device connected with conn_handle 1
I (20406) NimBLE: Path loss increased for device connected with conn_handle 1
I (21406) NimBLE: Path loss increased for device connected with conn_handle 1
I (22406) NimBLE: Path loss increased for device connected with conn_handle 1
I (23406) NimBLE: Path loss increased for device connected with conn_handle 1
I (23676) NimBLE: Path loss = -90
I (24406) NimBLE: Path loss increased for device connected with conn_handle 1
I (25406) NimBLE: Path loss increased for device connected with conn_handle 1
I (26406) NimBLE: Path loss increased for device connected with conn_handle 1
I (27406) NimBLE: Path loss increased for device connected with conn_handle 1
I (28406) NimBLE: Path loss increased for device connected with conn_handle 1
I (28676) NimBLE: Path loss = -119
I (28676) NimBLE: Path loss lower than threshold, stopping alert for device with conn_handle 1
I (33676) NimBLE: Path loss = -119
I (38726) NimBLE: Path loss = -119
I (43726) NimBLE: Path loss = -119
```
## 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.

View File

@ -0,0 +1,2 @@
idf_component_register(SRCS "main.c"
INCLUDE_DIRS ".")

View File

@ -0,0 +1,11 @@
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
endmenu

View File

@ -0,0 +1,25 @@
/*
* SPDX-FileCopyrightText: 2017-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef H_BLE_PROX_PRPH_
#define H_BLE_PROX_PRPH_
#include "nimble/ble.h"
#include "modlog/modlog.h"
#include "services/prox/ble_svc_prox.h"
#ifdef __cplusplus
extern "C" {
#endif
struct ble_hs_cfg;
struct ble_gatt_register_ctxt;
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,308 @@
/*
* 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_prox_prph.h"
#if CONFIG_EXAMPLE_EXTENDED_ADV
static uint8_t ext_adv_pattern_1[] = {
0x02, 0x01, 0x06,
0x03, 0x03, 0xab, 0xcd,
0x03, 0x03, 0x18, 0x03,
0x13, 0X09, 'n', 'i', 'm', 'b', 'l', 'e', '-', 'p', 'r', 'o', 'x', '-', 'p', 'r', 'p', 'h', '-', 'e',
};
#endif
static const char *tag = "NimBLE_PROX_PRPH";
static const char *device_name = "ble_prox_prph";
static int ble_prox_prph_gap_event(struct ble_gap_event *event, void *arg);
static uint8_t ble_prox_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_prox_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 (&params, 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, &params, NULL,
ble_prox_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_prox_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_LINK_LOSS_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_prox_prph_addr_type, NULL, BLE_HS_FOREVER,
&adv_params, ble_prox_prph_gap_event, NULL);
if (rc != 0) {
MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc);
return;
}
}
#endif
static int
ble_prox_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);
/* resume advertising */
#if CONFIG_EXAMPLE_EXTENDED_ADV
ext_ble_prox_prph_advertise();
#else
ble_prox_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_prox_prph_advertise();
#else
ble_prox_prph_advertise();
#endif
break;
case BLE_GAP_EVENT_ADV_COMPLETE:
MODLOG_DFLT(INFO, "adv complete\n");
#if CONFIG_EXAMPLE_EXTENDED_ADV
ext_ble_prox_prph_advertise();
#else
ble_prox_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_prox_prph_on_sync(void)
{
int rc;
rc = ble_hs_id_infer_auto(0, &ble_prox_prph_addr_type);
assert(rc == 0);
uint8_t addr_val[6] = {0};
rc = ble_hs_id_copy_addr(ble_prox_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_prox_prph_advertise();
#else
ble_prox_prph_advertise();
#endif
}
static void
ble_prox_prph_on_reset(int reason)
{
MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
}
void ble_prox_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 a task to keep checking path loss of the link */
ble_svc_prox_init();
/* Initialize the NimBLE host configuration */
ble_hs_cfg.sync_cb = ble_prox_prph_on_sync;
ble_hs_cfg.reset_cb = ble_prox_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;
/* 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_prox_prph_host_task);
}

View File

@ -0,0 +1,3 @@
CONFIG_FREERTOS_UNICORE=y
CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY=y
CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_IRAM_8BIT=y

View File

@ -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

View File

@ -0,0 +1,263 @@
# BLE Peripheral Proximity Sensor Example Walkthrough
## Introduction
In this tutorial, the ble_prox peripheral example code for the espressif chipsets with BLE5.0 support is reviewed. It notifies the application when the distance between devices increases. It advertises support for the Link Loss service (0x1803) as primary service UUID. The `ble_prox_prph_task` start alerting to application as soon as a write command is received from central regarding exceeding path loss. The alert stops when path loss is below low_threshold value.
## Includes
This example is located in the examples folder of the ESP-IDF under the [ble_proximity_sensor/proximity_sensor_prph/main](../main/). The [main.c](../main/main.c) file located in the main folder contains all the functionality that we are going to review. The header files contained in [main.c](../main/main.c) are:
```c
#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_prox_prph.h"
```
These `includes` are required for the FreeRTOS and underlying system components to run, including the logging functionality and a library to store data in non-volatile flash memory. We are interested in `“nimble_port.h”`, `“nimble_port_freertos.h”`, `"ble_hs.h"` and `“ble_svc_gap.h”`, `“ble_prox_prph.h”` which expose the BLE APIs required to implement this example.
* `nimble_port.h`: Includes the declaration of functions required for the initialization of the nimble stack.
* `nimble_port_freertos.h`: Initializes and enables nimble host task.
* `ble_hs.h`: Defines the functionalities to handle the host event
* `ble_svc_gap.h`:Defines the macros for device name and device appearance and declares the function to set them.
* `ble_prox_prph.h`: Defines the profiles specific macros and functions
## Main Entry Point
The programs entry point is the app_main() function:
```c
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_prox_prph_on_sync;
ble_hs_cfg.reset_cb = ble_prox_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;
/* name, period/time, auto reload, timer ID, callback */
ble_prox_prph_tx_timer = xTimerCreate("ble_prox_prph_tx_timer", pdMS_TO_TICKS(1000), pdTRUE,
(void *)0, ble_prox_prph_tx);
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_prox_prph_host_task);
}
```
The main function starts by initializing the non-volatile storage library. This library allows us to save the key-value pairs in flash memory.`nvs_flash_init()` stores the PHY calibration data. In a Bluetooth Low Energy (BLE) device, cryptographic keys used for encryption and authentication are often stored in Non-Volatile Storage (NVS).BLE stores the peer keys, CCCD keys, peer records, etc on NVS. By storing these keys in NVS, the BLE device can quickly retrieve them when needed, without the need for time-consuming key generations.
```c
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 );
```
## BT Controller and Stack Initialization
The main function calls `nimble_port_init()` to initialize BT Controller and nimble stack. This function initializes the BT controller by first creating its configuration structure named `esp_bt_controller_config_t` with default settings generated by the `BT_CONTROLLER_INIT_CONFIG_DEFAULT()` macro. It implements the Host Controller Interface (HCI) on the controller side, the Link Layer (LL), and the Physical Layer (PHY). The BT Controller is invisible to the user applications and deals with the lower layers of the BLE stack. The controller configuration includes setting the BT controller stack size, priority, and HCI baud rate. With the settings created, the BT controller is initialized and enabled with the `esp_bt_controller_init()` and `esp_bt_controller_enable()` functions:
```c
esp_bt_controller_config_t config_opts = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ret = esp_bt_controller_init(&config_opts);
```
Next, the controller is enabled in BLE Mode.
```c
ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
```
>The controller should be enabled in `ESP_BT_MODE_BLE` if you want to use the BLE mode.
There are four Bluetooth modes supported:
1. `ESP_BT_MODE_IDLE`: Bluetooth not running
2. `ESP_BT_MODE_BLE`: BLE mode
3. `ESP_BT_MODE_CLASSIC_BT`: BT Classic mode
4. `ESP_BT_MODE_BTDM`: Dual mode (BLE + BT Classic)
After the initialization of the BT controller, the nimble stack, which includes the common definitions and APIs for BLE, is initialized by using `esp_nimble_init()`:
```c
esp_err_t esp_nimble_init(void)
{
#if !SOC_ESP_NIMBLE_CONTROLLER
/* Initialize the function pointers for OS porting */
npl_freertos_funcs_init();
npl_freertos_mempool_init();
if(esp_nimble_hci_init() != ESP_OK) {
ESP_LOGE(NIMBLE_PORT_LOG_TAG, "hci inits failed\n");
return ESP_FAIL;
}
/* Initialize default event queue */
ble_npl_eventq_init(&g_eventq_dflt);
/* Initialize the global memory pool */
os_mempool_module_init();
os_msys_init();
#endif
/* Initialize the host */
ble_transport_hs_init();
return ESP_OK;
}
```
The host is configured by setting up the callbacks on Stack-reset, Stack-sync, registration of each GATT resource, and storage status.
```c
ble_hs_cfg.reset_cb = ble_prox_prph_on_reset;
ble_hs_cfg.sync_cb = ble_prox_prph_on_sync;
```
The Security Manager is configured by setting up the following SM's flag and attributes of the host
1. sm_bonding: It represents Security Manager Bond Flag.
2. sm_our_key_dist: It represents Security Manager's local key distribution mask.
3. sm_their_key_dist: It represents Security Manager remote key distribution mask.
4. sm_sc: It represents Security Manager Secure Connections Flag.
5. sm_mitm : It represents the Security Manager MITM Flag which results in requiring Man-In-The-Middle protection while pairing if it is set.
```c
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;
```
The main function then calls `ble_svc_gap_device_name_set()` to set the default device name. 'ble_prox_phy' is passed as the default device name to this function.
```c
static const char *device_name = "ble_prox_prph"
rc = ble_svc_gap_device_name_set(device_name);
```
The main function ends by creating a task where nimble will run using `nimble_port_freertos_init()`. This enables the nimble stack by using `esp_nimble_enable()`.
```c
nimble_port_freertos_init(ble_prox_prph_host_task);
```
`esp_nimble_enable()` create a task where the nimble host will run. It is not strictly necessary to have a separate task for the nimble host, but since something needs to handle the default queue, it is easier to create a separate task.
## Advertisement Functionalities
To support increased messaging, BLE5.0 is added with extended advertising PDUs. These PDUs are broadcast-only events (like electronic beacons). The following function is used to make extended advertisements. In Bluetooth® 4.0, all advertising was done on 3 of the 40 2.4GHz ISM band channels. With Bluetooth 5 there are now two sets of advertising channels: primary and secondary. The primary advertising channels are the original 3 of the 40 advertising channels defined in Bluetooth® 4.0 While the secondary advertising channels use the 37 fixed channels previously reserved for data.
```c
static void
ext_ble_prox_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 (&params, 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, &params, NULL,
ble_prox_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);
}
```
## Threshold
```c
/* Note: Path loss is calculated using formula : threshold - RSSI value
* by default threshold is kept -128 as per the spec
* high_threshold and low_threshold are hardcoded after testing and noting
* RSSI values when distance betweeen devices are less and more.
*/
static int8_t high_threshold = -70;
static int8_t low_threshold = -100;
```
## Conclusion
This Walkthrough covers the code explanation of the BLE_PROX_PRPH example. The following points are concluded through this walkthrough.
1. First a connection is allowed to a device which requests for Proximity Sensor service.
2. Gatt operations are responded on the characteristics and results displayed.