6  Creating a GATT service and notifying

In Step 3 (firmware/step3_notify), we create one custom service with one characteristic and notify a counter value every second.

6.1 The whole code

/*
 * Step 3: create a GATT service and Notify every second
 *
 * Service : c0a60001-18ff-4cd1-afce-4832ee44bcb7
 *   Counter (Read / Notify) : c0a60002-...  uint32 little-endian
 */
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "host/ble_hs.h"
#include "host/util/util.h"
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"

#define TAG "STEP3"

/* c0a60001-18ff-4cd1-afce-4832ee44bcb7 (bytes are written in reverse = little-endian) */
static const ble_uuid128_t svc_uuid =
    BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
                     0xd1, 0x4c, 0xff, 0x18, 0x01, 0x00, 0xa6, 0xc0);
static const ble_uuid128_t counter_chr_uuid =
    BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
                     0xd1, 0x4c, 0xff, 0x18, 0x02, 0x00, 0xa6, 0xc0);

static uint8_t own_addr_type;
static char device_name[20];
static uint16_t conn_handle = BLE_HS_CONN_HANDLE_NONE;
static uint16_t counter_val_handle; // written by ble_gatts_add_svcs()
static bool counter_notify_enabled;
static uint32_t counter;

static void start_advertising(void);

/* ---------------- GATT ---------------- */

static int gatt_access_cb(uint16_t conn, uint16_t attr_handle,
                          struct ble_gatt_access_ctxt *ctxt, void *arg)
{
    if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR && attr_handle == counter_val_handle) {
        // Read request: append the value to the response buffer (mbuf)
        int rc = os_mbuf_append(ctxt->om, &counter, sizeof(counter));
        return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
    }
    return BLE_ATT_ERR_UNLIKELY;
}

static const struct ble_gatt_svc_def gatt_svcs[] = {
    {
        .type = BLE_GATT_SVC_TYPE_PRIMARY,
        .uuid = &svc_uuid.u,
        .characteristics = (struct ble_gatt_chr_def[]) {
            {
                .uuid = &counter_chr_uuid.u,
                .access_cb = gatt_access_cb,
                .val_handle = &counter_val_handle,
                .flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_NOTIFY,
            },
            { 0 }, // terminator
        },
    },
    { 0 }, // terminator
};

/* ---------------- GAP events ---------------- */

static int gap_event_cb(struct ble_gap_event *event, void *arg)
{
    switch (event->type) {
    case BLE_GAP_EVENT_CONNECT:
        ESP_LOGI(TAG, "connect %s status=%d",
                 event->connect.status == 0 ? "ok" : "failed", event->connect.status);
        if (event->connect.status == 0) {
            conn_handle = event->connect.conn_handle;
        } else {
            start_advertising();
        }
        return 0;

    case BLE_GAP_EVENT_DISCONNECT:
        ESP_LOGI(TAG, "disconnect reason=0x%x", event->disconnect.reason);
        conn_handle = BLE_HS_CONN_HANDLE_NONE;
        counter_notify_enabled = false;
        start_advertising();
        return 0;

    case BLE_GAP_EVENT_ADV_COMPLETE:
        start_advertising();
        return 0;

    case BLE_GAP_EVENT_SUBSCRIBE:
        // the central wrote to a CCCD (start / stop Notify subscription)
        ESP_LOGI(TAG, "subscribe attr_handle=%d notify=%d",
                 event->subscribe.attr_handle, event->subscribe.cur_notify);
        if (event->subscribe.attr_handle == counter_val_handle) {
            counter_notify_enabled = event->subscribe.cur_notify;
        }
        return 0;

    case BLE_GAP_EVENT_MTU:
        ESP_LOGI(TAG, "mtu=%d", event->mtu.value);
        return 0;

    default:
        return 0;
    }
}

/* ---------------- Advertising ---------------- */

static void start_advertising(void)
{
    struct ble_hs_adv_fields fields = { 0 };
    struct ble_hs_adv_fields rsp_fields = { 0 };
    struct ble_gap_adv_params adv_params = { 0 };
    const char *name = ble_svc_gap_device_name();

    // advertisement: flags + 128-bit service UUID (3 + 18 = 21 bytes)
    fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
    fields.uuids128 = &svc_uuid;
    fields.num_uuids128 = 1;
    fields.uuids128_is_complete = 1;
    ble_gap_adv_set_fields(&fields);

    // the name doesn't fit, so put it in the scan response
    rsp_fields.name = (uint8_t *)name;
    rsp_fields.name_len = strlen(name);
    rsp_fields.name_is_complete = 1;
    ble_gap_adv_rsp_set_fields(&rsp_fields);

    adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
    adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
    adv_params.itvl_min = BLE_GAP_ADV_ITVL_MS(100);
    adv_params.itvl_max = BLE_GAP_ADV_ITVL_MS(150);
    int rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
                               &adv_params, gap_event_cb, NULL);
    if (rc != 0) {
        ESP_LOGE(TAG, "ble_gap_adv_start rc=%d", rc);
        return;
    }
    ESP_LOGI(TAG, "advertising as \"%s\"", name);
}

/* ---------------- Host ---------------- */

static void on_sync(void)
{
    uint8_t addr[6];

    ble_hs_util_ensure_addr(0);
    ble_hs_id_infer_auto(0, &own_addr_type);
    ble_hs_id_copy_addr(own_addr_type, addr, NULL);
    snprintf(device_name, sizeof(device_name), "HANDSON-C3-%02X%02X", addr[1], addr[0]);
    ble_svc_gap_device_name_set(device_name);
    start_advertising();
}

static void on_reset(int reason)
{
    ESP_LOGE(TAG, "nimble reset reason=%d", reason);
}

static void host_task(void *param)
{
    nimble_port_run();
    nimble_port_freertos_deinit();
}

/* ---------------- Notify every second ---------------- */

static void notify_task(void *param)
{
    while (1) {
        vTaskDelay(pdMS_TO_TICKS(1000));
        counter++;
        if (conn_handle == BLE_HS_CONN_HANDLE_NONE || !counter_notify_enabled) {
            continue; // don't send if not connected or not subscribed
        }
        struct os_mbuf *om = ble_hs_mbuf_from_flat(&counter, sizeof(counter));
        if (om == NULL) {
            continue;
        }
        // ownership of om passes to NimBLE (it frees it whether it succeeds or fails)
        int rc = ble_gatts_notify_custom(conn_handle, counter_val_handle, om);
        ESP_LOGI(TAG, "notify counter=%lu rc=%d", (unsigned long)counter, rc);
    }
}

void app_main(void)
{
    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);

    ESP_ERROR_CHECK(nimble_port_init());
    ble_hs_cfg.reset_cb = on_reset;
    ble_hs_cfg.sync_cb = on_sync;

    ble_svc_gap_init();
    ble_svc_gatt_init();
    ESP_ERROR_CHECK(ble_gatts_count_cfg(gatt_svcs)); // count the memory needed
    ESP_ERROR_CHECK(ble_gatts_add_svcs(gatt_svcs));  // register the services

    nimble_port_freertos_init(host_task);
    xTaskCreate(notify_task, "notify", 3072, NULL, 5, NULL);
}

What has been added since Step 2: UUID definitions, the GATT service definition, the access callback, handling of the subscribe event, and the task that sends Notify.

6.2 Defining the service

In NimBLE, GATT services are defined as an array of structs (a static table).

static const struct ble_gatt_svc_def gatt_svcs[] = {
    {
        .type = BLE_GATT_SVC_TYPE_PRIMARY,
        .uuid = &svc_uuid.u,
        .characteristics = (struct ble_gatt_chr_def[]) {
            {
                .uuid = &counter_chr_uuid.u,
                .access_cb = gatt_access_cb,
                .val_handle = &counter_val_handle,
                .flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_NOTIFY,
            },
            { 0 }, // terminator
        },
    },
    { 0 }, // terminator
};
Member Meaning
type PRIMARY (primary service) or SECONDARY (an auxiliary service referenced from other services). Usually PRIMARY
uuid The service UUID. Pass a pointer to the common part .u inside the ble_uuid128_t
characteristics Array of characteristics. Ends with { 0 }
access_cb Function called when a Read / Write arrives
val_handle Pointer to a variable into which the handle of the value attribute is written after registration
flags Properties and permissions (Chapter 3)

This array is expanded into the attribute table we saw in Chapter 3 (service declaration, characteristic declaration, value, CCCD). If you set BLE_GATT_CHR_F_NOTIFY, NimBLE adds the CCCD automatically.

Note(struct ble_gatt_chr_def[]) { ... }

This is a C99 compound literal, creating an unnamed array on the spot. Instead of declaring the characteristic array as a separate variable, you can write it directly inside the service definition. The ESP-IDF examples use this style too.

6.2.1 UUID

static const ble_uuid128_t svc_uuid =
    BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
                     0xd1, 0x4c, 0xff, 0x18, 0x01, 0x00, 0xa6, 0xc0);

As we saw in Chapter 3, it is written in reverse order of the string notation. A 16-bit UUID can be written as BLE_UUID16_DECLARE(0x180D).

6.2.2 Registration

ble_svc_gap_init();
ble_svc_gatt_init();
ESP_ERROR_CHECK(ble_gatts_count_cfg(gatt_svcs));
ESP_ERROR_CHECK(ble_gatts_add_svcs(gatt_svcs));

ble_gatts_count_cfg() counts the attributes needed and reserves space, and ble_gatts_add_svcs() registers them. Call these before starting the host task.

6.3 Access callback: answering Reads

static int gatt_access_cb(uint16_t conn, uint16_t attr_handle,
                          struct ble_gatt_access_ctxt *ctxt, void *arg)
{
    if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR && attr_handle == counter_val_handle) {
        int rc = os_mbuf_append(ctxt->om, &counter, sizeof(counter));
        return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
    }
    return BLE_ATT_ERR_UNLIKELY;
}
  • When the client comes to read the value, NimBLE calls this callback inside the host task
  • ctxt->op tells you the kind of operation (READ_CHR, WRITE_CHR, and for descriptors READ_DSC / WRITE_DSC)
  • attr_handle tells you which characteristic it is. Compare it with counter_val_handle received at registration
  • A Read response is returned by appending the value to ctxt->om (an mbuf)
  • A return value of 0 means success; BLE_ATT_ERR_* is returned to the client as an ATT error code

The counter is sent as the raw 4 bytes of a uint32_t. The ESP32-C3 (RISC-V) is little-endian, so counter = 5 becomes 05 00 00 00.

TipHandling several characteristics with one callback

In this sample, every characteristic is given the same gatt_access_cb, and it branches on attr_handle. You can also use a separate function per characteristic, or put an identifying value in the .arg member and receive it via the callback’s arg.

6.4 The subscribe event: who is listening

case BLE_GAP_EVENT_SUBSCRIBE:
    if (event->subscribe.attr_handle == counter_val_handle) {
        counter_notify_enabled = event->subscribe.cur_notify;
    }

When the client writes to a CCCD, NimBLE sends BLE_GAP_EVENT_SUBSCRIBE.

Member Details
attr_handle Which characteristic’s CCCD (contains the value handle)
cur_notify / prev_notify Notify subscription state (now / before)
cur_indicate / prev_indicate Indicate subscription state
reason Whether it was due to a write, or due to disconnection / bond restoration

You must not send Notify when not subscribed. So remember the subscription state in a flag and check it before sending. Clear the flag on disconnect.

6.5 Sending Notify

struct os_mbuf *om = ble_hs_mbuf_from_flat(&counter, sizeof(counter));
int rc = ble_gatts_notify_custom(conn_handle, counter_val_handle, om);
Function Details
ble_hs_mbuf_from_flat() Create an mbuf from an array. NULL if out of memory
ble_gatts_notify_custom(conn, handle, om) Notify the contents of om on the given connection and handle. om is freed by NimBLE

The recipient is specified by conn_handle, so the connection handle is remembered on BLE_GAP_EVENT_CONNECT and reset to BLE_HS_CONN_HANDLE_NONE on disconnect.

NoteThere is also ble_gatts_chr_updated()

NimBLE also has a function ble_gatts_chr_updated(val_handle). It only says “this characteristic’s value has changed”, and NimBLE then sends Notify / Indicate of the value read via the access callback to all subscribed connections. It is convenient since you can leave even subscription management to NimBLE, but it makes it harder to see what is sent when, so this hands-on sends explicitly with ble_gatts_notify_custom().

6.5.1 Which task to send from

notify_task is our own task created in app_main(). As described in Chapter 4, NimBLE APIs take a lock internally, so they may be called from tasks other than the host task.

However, counter_notify_enabled and conn_handle are variables written by the host task (GAP callback) and read by notify_task. This sample is written naively because “it only reads once per second and a small discrepancy doesn’t matter”, but properly you need to watch out for races (Chapter 10 tidies this up using an event queue).

6.6 Running it

cd firmware/step3_notify
idf.py set-target esp32c3
idf.py build
idf.py -p PORT flash monitor

6.6.1 Checking with nRF Connect

  1. When you SCAN, the service UUID c0a60001-… is shown under HANDSON-C3-XXXX (because it is in the advertisement). The name comes from the scan response
  2. When you CONNECT, you see an Unknown Service (C0A60001-…) in addition to GAP and GATT
  3. Open the service: Unknown Characteristic (C0A60002-…) with Properties READ, NOTIFY. Below it is a Client Characteristic Configuration (0x2902)
  4. Press ↓ (Read) and the value is shown like (0x) 05-00-00-00 (a little-endian 32-bit value, so counter 5 starts with 05)
  5. Press ↓↓↓ (Notify): subscribe attr_handle=… notify=1 appears in the serial monitor and the value updates every second
  6. Press it again to unsubscribe: notify=0 appears and the updates stop
TipTry it
  1. Compare the attr_handle value in the log with what nRF Connect shows. Confirm that although it is a CCCD write, what arrives is the value handle
  2. What happens if, while not subscribed, you remove the if in notify_task and force a Notify? Check rc in the log
  3. Try a Notify period of 10 ms. What happens to nRF Connect’s display and the log?
  1. NimBLE’s ble_gatts_notify_custom() itself does not check the CCCD, so the packet does get sent (rc = 0). The client either ignores the Notify for a characteristic it hasn’t subscribed to or, depending on the OS, accepts it. Either way it is a violation of the specification, so always check the subscription state.
  2. If you send at a period shorter than the connection interval (decided by the Central; often around 15–30 ms on iOS), pending transmissions pile up, and when mbufs run out ble_hs_mbuf_from_flat() returns NULL or rc becomes BLE_HS_ENOMEM (6). To send data quickly, you need measures such as asking for a shorter connection interval, bundling several samples into one Notify, or widening the MTU.
ImportantKey points
  • Define services as a static table of ble_gatt_svc_def and register them before starting the host
  • Distinguish characteristics by the value handle returned in val_handle
  • Return Read responses by appending to ctxt->om
  • Send Notify with ble_gatts_notify_custom() after confirming the subscription via BLE_GAP_EVENT_SUBSCRIBE