# BLE Dynamic Service Example Walkthrough

## Introduction

In this tutorial, the ble_dynamic_service example code for the espressif chipsets is reviewed. This example creates GATT server and then starts advertising, waiting to be connected to a GATT client.
In the main thread it keeps on adding and deleting one custom service in the gatt server. When any of the connected clients subscribes for the Service Changed Characteristic(0x2a05) in gatt service, then whenever the gatt database is altered due to additition or deletion of the service the service changed indication is sent to the subscribed clients.


## Includes

This example is located in the examples folder of the ESP-IDF under the [ble_dynamic_service/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 "ble_dynamic_service.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_dynamic_service.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_dynamic_service.h`: Defines the example specific macros and functions.

## Main Entry Point

The program’s 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) {
        ESP_LOGE(tag, "Failed to init nimble %d ", ret);
        return;
    }
    /* Initialize the NimBLE host configuration. */
    ble_hs_cfg.reset_cb = dynamic_service_on_reset;
    ble_hs_cfg.sync_cb = dynamic_service_on_sync;
    ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
    ble_hs_cfg.store_status_cb = ble_store_util_status_rr;

    rc = gatt_svr_init();
    assert(rc == 0);

    /* Set the default device name. */
    rc = ble_svc_gap_device_name_set("ble-dynamic-service");
    assert(rc == 0);

    nimble_port_freertos_init(dynamic_service_host_task);

    while(1) {
        vTaskDelay(15000 / portTICK_PERIOD_MS);
        MODLOG_DFLT(INFO, "Adding Dynamic service");
        /* add services defined in gatt_svr_svcs */
        dynamic_service(BLE_DYNAMIC_SERVICE_ADD, gatt_svr_svcs, NULL);
        /* 15 seconds delay before deleting the service */
        vTaskDelay(15000 / portTICK_PERIOD_MS);
        MODLOG_DFLT(INFO, "Deleting service");
        /* Delete the first service in the list */
        dynamic_service(BLE_DYNAMIC_SERVICE_DELETE, NULL, gatt_svr_svcs[0].uuid);
    }
}
```

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 = dynamic_service_on_reset;
 ble_hs_cfg.sync_cb = dynamic_service_on_sync;
 ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
 ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
```

The main function then calls `ble_svc_gap_device_name_set()` to set the default device name. 'ble-dynamic-service' is passed as the default device name to this function.
```c
static const char *device_name = "ble-dynamic-service"
rc = ble_svc_gap_device_name_set(device_name);
```

The main function then creates 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(dynamic_service_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.


In the while loop, main thread keeps adding a custom service defined in struct `gatt_svr_svcs` and deleting it after 15 seconds.

```c
while(1) {
    vTaskDelay(15000 / portTICK_PERIOD_MS);
    MODLOG_DFLT(INFO, "Adding Dynamic service");
    /* add services defined in gatt_svr_svcs */
    dynamic_service(BLE_DYNAMIC_SERVICE_ADD, gatt_svr_svcs, NULL);
    /* 15 seconds delay before deleting the service */
    vTaskDelay(15000 / portTICK_PERIOD_MS);
    MODLOG_DFLT(INFO, "Deleting service");
    /* Delete the first service in the list */
    dynamic_service(BLE_DYNAMIC_SERVICE_DELETE, NULL, gatt_svr_svcs[0].uuid);
}
```
>Service change indication will be sent to all the subscribed clients after addition or deletion of service as the gatt database is altered.

## Conclusion

This Walkthrough covers the code explanation of the BLE_DYNAMIC_SERVICE example. The following points are concluded through this walkthrough.
 1. Gatt server keeps advertising and connections are allowed.
 2. The addition and deletion of custom service happens asynchronously and the service change indication is sent to the subscribed clients.
