5  Advertising and waiting for a connection

In Step 2 (firmware/step2_advertise), we start NimBLE, advertise, and get to the point where a smartphone can connect. There is no custom service yet.

5.1 The whole code

/*
 * Step 2: advertise and wait for a connection
 *
 * - initialize NimBLE and start the host task
 * - start advertising once the host and controller are synchronized (sync)
 * - log GAP events such as connect and disconnect
 */
#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"

#define TAG "STEP2"

static uint8_t own_addr_type;
static char device_name[20];

static void start_advertising(void);

/* ---------------- 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 conn_handle=%d",
                 event->connect.status == 0 ? "ok" : "failed",
                 event->connect.status, event->connect.conn_handle);
        if (event->connect.status != 0) {
            start_advertising(); // restart advertising if the connection failed
        }
        return 0;

    case BLE_GAP_EVENT_DISCONNECT:
        ESP_LOGI(TAG, "disconnect reason=0x%x", event->disconnect.reason);
        start_advertising(); // restart advertising after a disconnect
        return 0;

    case BLE_GAP_EVENT_CONN_UPDATE:
        ESP_LOGI(TAG, "connection parameters updated status=%d", event->conn_update.status);
        return 0;

    case BLE_GAP_EVENT_ADV_COMPLETE:
        ESP_LOGI(TAG, "advertising complete reason=%d", event->adv_complete.reason);
        start_advertising();
        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_gap_adv_params adv_params = { 0 };
    const char *name = ble_svc_gap_device_name();

    // contents of the advertising packet (max 31 bytes)
    fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
    fields.tx_pwr_lvl_is_present = 1;
    fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
    fields.name = (uint8_t *)name;
    fields.name_len = strlen(name);
    fields.name_is_complete = 1;

    int rc = ble_gap_adv_set_fields(&fields);
    if (rc != 0) {
        ESP_LOGE(TAG, "ble_gap_adv_set_fields rc=%d", rc);
        return;
    }

    adv_params.conn_mode = BLE_GAP_CONN_MODE_UND; // accept connections from anyone
    adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN; // general discoverable
    adv_params.itvl_min = BLE_GAP_ADV_ITVL_MS(100);
    adv_params.itvl_max = BLE_GAP_ADV_ITVL_MS(150);

    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 callbacks ---------------- */

// the host and controller are synchronized (BLE is now usable)
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);

    // append the lower 2 bytes of the address to the name so boards can be told apart even if many are in the same room
    snprintf(device_name, sizeof(device_name), "HANDSON-C3-%02X%02X", addr[1], addr[0]);
    ble_svc_gap_device_name_set(device_name);
    ESP_LOGI(TAG, "address %02X:%02X:%02X:%02X:%02X:%02X",
             addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]);

    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(); // does not return until nimble_port_stop() is called
    nimble_port_freertos_deinit();
}

void app_main(void)
{
    // NimBLE uses NVS for PHY calibration data etc.
    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()); // initialize controller + host

    ble_hs_cfg.reset_cb = on_reset;
    ble_hs_cfg.sync_cb = on_sync;

    ble_svc_gap_init(); // register the GAP service (device name etc.)

    nimble_port_freertos_init(host_task); // start the host task
}

Let’s go through it from the top.

5.2 app_main: initialization

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

This follows the initialization order from Chapter 4. app_main() returns immediately after this, but because the host task keeps running, BLE does not stop.

ESP_ERROR_CHECK() is a macro that prints an error and resets if the return value is not ESP_OK. There is no point continuing after an initialization failure, so we stop with this.

5.3 on_sync: address and name

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);
Function Details
ble_hs_util_ensure_addr(0) Make sure a usable address exists (argument 0 = don’t use a random address for privacy)
ble_hs_id_infer_auto(0, &type) Automatically choose the kind of address to use. The ESP32-C3 has a public address, so it becomes Public
ble_hs_id_copy_addr(type, addr, NULL) Obtain the 6 bytes of the address. addr[0] is the least significant byte (little-endian)

When printing to the log, outputting from addr[5] downwards gives the familiar AA:BB:CC:DD:EE:FF form.

snprintf(device_name, sizeof(device_name), "HANDSON-C3-%02X%02X", addr[1], addr[0]);
ble_svc_gap_device_name_set(device_name);

The device name is the value of the GAP service’s Device Name characteristic (0x2A00). This name is also put in the advertisement. In the hands-on everyone flashes the same firmware, so the lower 2 bytes of the address are appended to the name so you can tell your own board apart.

5.4 start_advertising: what to broadcast, and how

5.4.1 Advertising data

fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
fields.tx_pwr_lvl_is_present = 1;
fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
fields.name = (uint8_t *)name;
fields.name_len = strlen(name);
fields.name_is_complete = 1;
ble_gap_adv_set_fields(&fields);

When you fill in the items you want to include in struct ble_hs_adv_fields, ble_gap_adv_set_fields() assembles them into the byte sequence of AD structures from Chapter 2.

Field AD type Bytes
flags 0x01 Flags 3
tx_pwr_lvl 0x0A TX Power Level (AUTO = automatically insert the current transmit power) 3
name (name_is_complete = 1) 0x09 Complete Local Name 2 + 15 = 17
Total 23 / 31

If it exceeds 31 bytes, ble_gap_adv_set_fields() returns BLE_HS_EMSGSIZE.

5.4.2 Advertising parameters

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);
Setting Value Meaning
conn_mode BLE_GAP_CONN_MODE_UND Undirected: accept connections from anyone (NON makes it non-connectable, DIR only a specific peer)
disc_mode BLE_GAP_DISC_MODE_GEN General: discoverable at any time (LTD only for a limited time)
itvl_min / itvl_max 100–150 ms Advertising interval. BLE_GAP_ADV_ITVL_MS() converts to units of 0.625 ms

If itvl_min / itvl_max are left at 0, NimBLE’s defaults (30–60 ms) are used.

5.4.3 Starting

ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER, &adv_params, gap_event_cb, NULL);
Argument Value Meaning
own_addr_type Public Kind of our own address
direct_addr NULL Not an advertisement directed at a specific peer
duration_ms BLE_HS_FOREVER No time limit (if you set a time, BLE_GAP_EVENT_ADV_COMPLETE occurs when it ends)
cb gap_event_cb Function that receives the GAP events of connections born from this advertisement

5.5 gap_event_cb: connect and disconnect

case BLE_GAP_EVENT_DISCONNECT:
    ESP_LOGI(TAG, "disconnect reason=0x%x", event->disconnect.reason);
    start_advertising(); // restart advertising after a disconnect

A BLE peripheral automatically stops advertising when connected (when the maximum number of simultaneous connections is 1). It does not restart automatically when disconnected, so we call start_advertising() again on BLE_GAP_EVENT_DISCONNECT. Forget this, and you get a device that “can never be found again once disconnected”.

5.6 Running it

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

On boot, logs like the following appear (the address differs per board).

I (xxx) STEP2: address 34:85:18:XX:12:34
I (xxx) STEP2: advertising as "HANDSON-C3-1234"

5.6.1 Scanning with nRF Connect

  1. Open nRF Connect on the phone and press SCAN on the SCANNER tab
  2. Find HANDSON-C3-XXXX and tap it to see the contents of the advertisement
    • Flags: GeneralDiscoverable, BrEdrNotSupported
    • Tx Power Level
    • Complete Local Name: HANDSON-C3-XXXX
    • RSSI (received signal strength). It changes as you move closer to or away from the board
  3. Pressing the three lines on the right (or RAW) shows the raw byte sequence of the AD structures. Compare it with the table in Chapter 2
  4. Press CONNECT to connect; connect ok appears in the serial monitor. Only two services are visible: GAP (0x1800) and GATT (0x1801)
  5. Press DISCONNECT: disconnect reason=0x213 (peer disconnected) appears and advertising starts again
TipTry it
  1. Split the RAW byte sequence one by one and decompose it into “length, type, data”
  2. What happens if you put a 25-character name in fields.name? Log the return value of ble_gap_adv_set_fields() to find out
  3. If you set itvl_min / itvl_max to 1000 ms, how does it change how easily the device is found in nRF Connect’s scan list and how often RSSI updates?
  4. While connected, move the board away or remove the antenna and see with which reason it disconnects
  1. Flags (3) + TX Power (3) + name (2 + 25) = 33 bytes, exceeding 31 bytes, so BLE_HS_EMSGSIZE (4) is returned and advertising is not started. Shorten the name or move it to the scan response (as Step 3 does).
  2. Advertising becomes less frequent, so it takes longer to be found and RSSI updates more slowly. In exchange, power consumption goes down.
  3. When the radio can no longer reach and the Supervision Timeout passes, you get reason=0x208 (Connection Timeout).
ImportantKey points
  • Start advertising from inside sync_cb
  • Items written in ble_hs_adv_fields become AD structures. 31 bytes max
  • When disconnected, restart advertising yourself