10  Restructuring as event-driven

With Step 5, all the target features (Notify, commands, pairing) are in place. However, main.c exceeds 300 lines, and the situation is that

The more features you add, the harder it becomes to follow what happens where. In Step 6 (firmware/step6_event_driven), we restructure this into an event queue + state transition table design.

10.1 Design

flowchart LR
  subgraph D["drivers/ (event sources)"]
    GAP["app_gap.c<br/>connect, disconnect, encryption"]
    GATT["app_gatt.c<br/>command Writes"]
    TMR["app_timer.c<br/>1-second timer"]
  end
  GAP -->|"enqueue()"| Q[("Event queue<br/>(FreeRTOS Queue)")]
  GATT -->|"enqueue()"| Q
  TMR -->|"enqueue()"| Q
  Q -->|"dequeue()"| L["main.c<br/>event loop"]
  L --> T["handlers/handler.c<br/>state_handler_table[state][event]"]
  T --> H["handler_idle.c<br/>handler_connected.c"]
  H -->|"send Notify"| GATT
  H -->|"next state"| L

Layer Role Rule
drivers/ Boundary with the outside world: BLE, timers, etc. Only convert occurrences into events and post them. They don’t decide what to do
common/ Event type and queue, state type, timer Hardware-independent foundation
handlers/ “What to do when this event arrives in this state” Selected via the state transition table; return the next state
main.c Event loop The only place the state is rewritten

10.1.1 File layout

step6_event_driven/main/
├── CMakeLists.txt
├── main.c                       initialization + event loop
├── include/
│   ├── common/   app_event.h  app_state.h  app_timer.h
│   ├── drivers/  app_ble.h    app_gap.h    app_gatt.h
│   └── handlers/ handler.h    handler_idle.h  handler_connected.h
└── src/
    ├── common/   app_event.c  app_timer.c
    ├── drivers/  app_ble.c    app_gap.c    app_gatt.c
    └── handlers/ handler.c    handler_idle.c  handler_connected.c
idf_component_register(SRCS "main.c"
                            "src/common/app_event.c"
                            "src/common/app_timer.c"
                            "src/drivers/app_ble.c"
                            "src/drivers/app_gap.c"
                            "src/drivers/app_gatt.c"
                            "src/handlers/handler.c"
                            "src/handlers/handler_idle.c"
                            "src/handlers/handler_connected.c"
                    INCLUDE_DIRS "include/common"
                                 "include/drivers"
                                 "include/handlers"
                    PRIV_REQUIRES bt nvs_flash esp_timer)

Because the three folders are listed in INCLUDE_DIRS, any file can include headers without the folder name, like #include "app_event.h".

TipPrefix your header names

Common names like event.h, gap.h and timer.h easily collide with ESP-IDF and NimBLE headers. NimBLE also has host/ble_gap.h. Adding a prefix such as app_ is the safe choice.

10.2 State transition table

First, design the behaviour as a table.

State  Event BLE_CONNECTED BLE_DISCONNECTED BLE_PAIRED CMD_PING CMD_STATUS CMD_UNKNOWN TIMER_1S
IDLE (not connected) → CONNECTED — — — — — counter +1
CONNECTED — → IDLE log return PONG return status return error counter +1, Notify

“—” means ignore that event. Making it a table also settles “what if a command arrives while not connected?” (which cannot happen given how BLE works, but could if it was left in the queue, etc.) as ignore.

10.3 Events and the queue

#pragma once

#include <stddef.h>
#include <stdint.h>

#define EVENT_PAYLOAD_SIZE 20
#define EVENT_QUEUE_SIZE   32

typedef enum {
    EVT_NOP,
    EVT_BLE_CONNECTED,
    EVT_BLE_DISCONNECTED,
    EVT_BLE_PAIRED,       // encryption (pairing / bond restoration) complete
    EVT_BLE_CMD_PING,     // command 0x00
    EVT_BLE_CMD_STATUS,   // command 0x01
    EVT_BLE_CMD_UNKNOWN,  // undefined command (payload[0] = command value)
    EVT_TIMER_1S,         // 1-second periodic timer
    EVT_MAX,
} app_event_id_t;

// struct holding event information
typedef struct {
    app_event_id_t id;
    uint8_t payload[EVENT_PAYLOAD_SIZE];
    size_t length;
    uint32_t timestamp; // ms
} app_event_t;

void event_queue_init(void);

// add an event to the queue (from either a task or an ISR)
void enqueue(app_event_id_t id, const uint8_t *payload, size_t length);

// take an event from the queue (blocks if empty)
app_event_t dequeue(void);

const char *event_name(app_event_id_t id);
  • An event is ID + payload (copied value) + length + timestamp
  • The payload is held as an array, with the value copied. If you put a pointer to the BLE receive buffer, by the time it is taken out the contents may have changed or been freed
  • The trailing EVT_MAX gives the number of event kinds and can be used as the number of table columns
#include "app_event.h"

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "esp_timer.h"

#define TAG "EVENT"

static QueueHandle_t event_queue = NULL;

void event_queue_init(void)
{
    if (event_queue == NULL) {
        event_queue = xQueueCreate(EVENT_QUEUE_SIZE, sizeof(app_event_t));
        configASSERT(event_queue);
    }
}

void enqueue(app_event_id_t id, const uint8_t *payload, size_t length)
{
    app_event_t event = { 0 };

    if (length > EVENT_PAYLOAD_SIZE) {
        length = EVENT_PAYLOAD_SIZE;
    }
    event.id = id;
    if (payload != NULL && length > 0) {
        memcpy(event.payload, payload, length);
    }
    event.length = length;
    event.timestamp = (uint32_t)(esp_timer_get_time() / 1000);

    if (xPortInIsrContext()) {
        BaseType_t woken = pdFALSE;
        xQueueSendToBackFromISR(event_queue, &event, &woken);
        portYIELD_FROM_ISR(woken);
    } else if (xQueueSendToBack(event_queue, &event, 0) != pdPASS) {
        // drop if full so as not to stall the NimBLE host task etc.
        ESP_LOGW(TAG, "queue full, drop %s", event_name(id));
    }
}

app_event_t dequeue(void)
{
    app_event_t event;

    // block indefinitely until an event arrives
    if (xQueueReceive(event_queue, &event, portMAX_DELAY) == pdPASS) {
        return event;
    }

    // fallback
    memset(&event, 0, sizeof(event));
    event.id = EVT_NOP;
    return event;
}

const char *event_name(app_event_id_t id)
{
    switch (id) {
    case EVT_NOP:              return "EVT_NOP";
    case EVT_BLE_CONNECTED:    return "EVT_BLE_CONNECTED";
    case EVT_BLE_DISCONNECTED: return "EVT_BLE_DISCONNECTED";
    case EVT_BLE_PAIRED:       return "EVT_BLE_PAIRED";
    case EVT_BLE_CMD_PING:     return "EVT_BLE_CMD_PING";
    case EVT_BLE_CMD_STATUS:   return "EVT_BLE_CMD_STATUS";
    case EVT_BLE_CMD_UNKNOWN:  return "EVT_BLE_CMD_UNKNOWN";
    case EVT_TIMER_1S:         return "EVT_TIMER_1S";
    default:                   return "UNKNOWN_EVENT";
    }
}

10.3.1 From an ISR or from a task

enqueue() checks whether it is inside an interrupt with xPortInIsrContext() and uses

  • xQueueSendToBackFromISR() inside an interrupt
  • xQueueSendToBack() (wait time 0) inside a task

accordingly. The event sources in this hands-on (NimBLE’s host task and the esp_timer task) are both tasks, but if in future you post button events from a GPIO interrupt, the same enqueue() can be used.

10.3.2 Drop without waiting

The reason we don’t wait when posting from a task is that the caller is NimBLE’s host task. Waiting when the queue is full would stop all BLE processing in the meantime. If full, drop the event and emit a warning; the fundamental fix is to make the handlers fast (don’t let the queue clog).

10.3.3 Retrieval waits forever

dequeue() sleeps until an event arrives with portMAX_DELAY. While the queue is empty, the main task uses no CPU.

10.4 States and the state transition table

#pragma once

typedef enum {
    STATE_IDLE,      // not connected (advertising)
    STATE_CONNECTED, // connected (Notify every second)
    STATE_MAX,
} app_state_t;

const char *state_name(app_state_t state);
#pragma once

#include <stdint.h>
#include "app_event.h"
#include "app_state.h"

typedef app_state_t (*event_handler_t)(const app_event_t *event);

// state transition handler table
extern const event_handler_t state_handler_table[STATE_MAX][EVT_MAX];

// Shared helpers
void counter_increment(void);
void notify_counter(void);
void notify_ping_rsp(void);
void notify_status_rsp(void);
void notify_error_rsp(uint8_t cmd);
typedef app_state_t (*event_handler_t)(const app_event_t *event);

is a function pointer type for “a function that takes an event and returns the next state”.

#include "handler.h"
#include "handler_idle.h"
#include "handler_connected.h"
#include "app_gatt.h"

#include <string.h>
#include "esp_timer.h"

/*
 * Command responses (Notify on the Command characteristic):
 *   0x00 PING   : [0x00, 'P','O','N','G']
 *   0x01 STATUS : [0x01, counter(u32 LE), uptime_sec(u32 LE)]
 *   other       : [cmd, 0xFF]
 */

static uint32_t counter;

void counter_increment(void)
{
    counter++;
}

void notify_counter(void)
{
    app_gatt_notify_counter(counter);
}

void notify_ping_rsp(void)
{
    uint8_t val[5] = { APP_CMD_PING, 'P', 'O', 'N', 'G' };
    app_gatt_notify_cmd_rsp(val, sizeof(val));
}

void notify_status_rsp(void)
{
    uint8_t val[9];
    uint32_t uptime = (uint32_t)(esp_timer_get_time() / 1000000);
    val[0] = APP_CMD_STATUS;
    memcpy(&val[1], &counter, 4); // RISC-V is LE
    memcpy(&val[5], &uptime, 4);
    app_gatt_notify_cmd_rsp(val, sizeof(val));
}

void notify_error_rsp(uint8_t cmd)
{
    uint8_t val[2] = { cmd, 0xFF };
    app_gatt_notify_cmd_rsp(val, sizeof(val));
}

const char *state_name(app_state_t state)
{
    switch (state) {
    case STATE_IDLE:      return "STATE_IDLE";
    case STATE_CONNECTED: return "STATE_CONNECTED";
    default:              return "UNKNOWN_STATE";
    }
}

/*
 * State transition handler table
 * NULL events are ignored (state kept)
 */
const event_handler_t state_handler_table[STATE_MAX][EVT_MAX] = {
    [STATE_IDLE] = {
        [EVT_BLE_CONNECTED] = handler_idle_ble_connected,
        [EVT_TIMER_1S]      = handler_idle_timer_1s,
    },
    [STATE_CONNECTED] = {
        [EVT_BLE_DISCONNECTED] = handler_connected_ble_disconnected,
        [EVT_BLE_PAIRED]       = handler_connected_ble_paired,
        [EVT_BLE_CMD_PING]     = handler_connected_cmd_ping,
        [EVT_BLE_CMD_STATUS]   = handler_connected_cmd_status,
        [EVT_BLE_CMD_UNKNOWN]  = handler_connected_cmd_unknown,
        [EVT_TIMER_1S]         = handler_connected_timer_1s,
    },
};
  • The table is a 2D array [STATE_MAX][EVT_MAX]. Rows are states, columns are events
  • C99 designated initializers [STATE_IDLE] = { [EVT_BLE_CONNECTED] = ... } make explicit what goes in which cell. Cells not written become NULL
  • Processing used by several handlers, such as assembling responses, is gathered into common functions (notify_status_rsp() etc.)

10.4.1 Handlers

#include "handler_idle.h"
#include "handler.h"

app_state_t handler_idle_ble_connected(const app_event_t *event)
{
    return STATE_CONNECTED;
}

app_state_t handler_idle_timer_1s(const app_event_t *event)
{
    // keep counting even while not connected
    counter_increment();
    return STATE_IDLE;
}
#include "handler_connected.h"
#include "handler.h"

#include "esp_log.h"

#define TAG "HANDLER_CONN"

app_state_t handler_connected_ble_disconnected(const app_event_t *event)
{
    return STATE_IDLE;
}

app_state_t handler_connected_ble_paired(const app_event_t *event)
{
    ESP_LOGI(TAG, "link encrypted");
    return STATE_CONNECTED;
}

app_state_t handler_connected_cmd_ping(const app_event_t *event)
{
    notify_ping_rsp();
    return STATE_CONNECTED;
}

app_state_t handler_connected_cmd_status(const app_event_t *event)
{
    notify_status_rsp();
    return STATE_CONNECTED;
}

app_state_t handler_connected_cmd_unknown(const app_event_t *event)
{
    notify_error_rsp(event->payload[0]);
    return STATE_CONNECTED;
}

app_state_t handler_connected_timer_1s(const app_event_t *event)
{
    counter_increment();
    notify_counter(); // sent only while subscribed
    return STATE_CONNECTED;
}

Handlers just finish quickly and return the next state. If the state does not change, they return the current state.

10.5 The event loop

/*
 * ESP32-C3 BLE sample (NimBLE) - event-driven structure
 *
 * drivers  : interrupts/callbacks of BLE, timers, etc. → only issue events via enqueue()
 * main     : dequeue() → run state_handler_table[state][event] → update state with the return value
 * handlers : event processing per state
 */
#include "esp_log.h"
#include "nvs_flash.h"

#include "app_event.h"
#include "app_state.h"
#include "app_timer.h"
#include "app_ble.h"
#include "handler.h"

#define TAG "MAIN"

static app_state_t state;

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);

    event_queue_init(); // create before the drivers (because callbacks enqueue)
    ESP_ERROR_CHECK(app_ble_init());
    ESP_ERROR_CHECK(timer_initialize());

    state = STATE_IDLE;

    while (1) {
        app_event_t event = dequeue();
        if (state >= STATE_MAX || event.id >= EVT_MAX) {
            continue;
        }

        if (event.id != EVT_TIMER_1S) {
            ESP_LOGI(TAG, "%s <- %s", state_name(state), event_name(event.id));
        }

        // get the handler from the state transition table (ignore if not registered)
        event_handler_t handler = state_handler_table[state][event.id];
        if (handler != NULL) {
            app_state_t next = handler(&event);
            if (next != state) {
                ESP_LOGI(TAG, "%s -> %s", state_name(state), state_name(next));
            }
            state = next;
        }
    }
}
  1. Create the queue first (event_queue_init()), because enqueue() may be called right after BLE or the timer is started
  2. Take out one event (sleep if there is none)
  3. Check the range and look up the handler in the table
  4. Ignore if NULL; otherwise call the handler and update the state with its return value

Unlike up to Step 5, app_main() never returns and keeps looping. This main task becomes “the only task that processes events”.

10.6 drivers: only convert to events

10.6.1 GATT: Writes into command events

#include "app_gatt.h"
#include "app_gap.h"
#include "app_event.h"

#include <string.h>
#include "esp_log.h"
#include "host/ble_hs.h"

#define TAG "APP_GATT"

/* c0a60001-18ff-4cd1-afce-4832ee44bcb7 (little endian) */
const ble_uuid128_t app_gatt_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 const ble_uuid128_t cmd_chr_uuid =
    BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
                     0xd1, 0x4c, 0xff, 0x18, 0x03, 0x00, 0xa6, 0xc0);

static uint16_t counter_val_handle;
static uint16_t cmd_val_handle;
static bool counter_notify_enabled;
static bool cmd_notify_enabled;
static uint32_t counter_value; // latest value for Read

static int notify(uint16_t attr_handle, const void *data, uint16_t len)
{
    uint16_t conn = app_gap_conn_handle();
    if (conn == BLE_HS_CONN_HANDLE_NONE) {
        return BLE_HS_ENOTCONN;
    }
    struct os_mbuf *om = ble_hs_mbuf_from_flat(data, len);
    if (om == NULL) {
        return BLE_HS_ENOMEM;
    }
    return ble_gatts_notify_custom(conn, attr_handle, om);
}

// received command → convert to an event and enqueue (processing is on the handler side)
static void dispatch_command(const uint8_t *buf, uint16_t len)
{
    switch (buf[0]) {
    case APP_CMD_PING:
        enqueue(EVT_BLE_CMD_PING, &buf[1], len - 1);
        break;
    case APP_CMD_STATUS:
        enqueue(EVT_BLE_CMD_STATUS, &buf[1], len - 1);
        break;
    default:
        enqueue(EVT_BLE_CMD_UNKNOWN, buf, len);
        break;
    }
}

static int gatt_access_cb(uint16_t conn, uint16_t attr_handle,
                          struct ble_gatt_access_ctxt *ctxt, void *arg)
{
    switch (ctxt->op) {
    case BLE_GATT_ACCESS_OP_READ_CHR:
        if (attr_handle == counter_val_handle) {
            int rc = os_mbuf_append(ctxt->om, &counter_value, sizeof(counter_value));
            return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
        }
        return BLE_ATT_ERR_UNLIKELY;

    case BLE_GATT_ACCESS_OP_WRITE_CHR:
        if (attr_handle == cmd_val_handle) {
            uint8_t buf[EVENT_PAYLOAD_SIZE];
            uint16_t len = OS_MBUF_PKTLEN(ctxt->om);
            if (len == 0 || len > sizeof(buf)) {
                return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
            }
            ble_hs_mbuf_to_flat(ctxt->om, buf, sizeof(buf), &len);
            dispatch_command(buf, len);
            return 0;
        }
        return BLE_ATT_ERR_UNLIKELY;

    default:
        return BLE_ATT_ERR_UNLIKELY;
    }
}

/*
 * *_ENC    : reject unless the connection is encrypted
 * *_AUTHEN : additionally reject unless the key was paired with MITM protection (passkey etc.)
 * NOTIFY_INDICATE_* applies to writes to the CCCD (subscription setting). Without it, even unpaired peers can subscribe
 */
#define SECURE_READ   (BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_READ_AUTHEN)
#define SECURE_WRITE  (BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_ENC | BLE_GATT_CHR_F_WRITE_AUTHEN)
#define SECURE_NOTIFY (BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC | \
                       BLE_GATT_CHR_F_NOTIFY_INDICATE_AUTHEN)

static const struct ble_gatt_svc_def gatt_svcs[] = {
    {
        .type = BLE_GATT_SVC_TYPE_PRIMARY,
        .uuid = &app_gatt_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 = SECURE_READ | SECURE_NOTIFY,
            },
            {
                .uuid = &cmd_chr_uuid.u,
                .access_cb = gatt_access_cb,
                .val_handle = &cmd_val_handle,
                .flags = SECURE_WRITE | SECURE_NOTIFY,
            },
            { 0 },
        },
    },
    { 0 },
};

int app_gatt_init(void)
{
    int rc = ble_gatts_count_cfg(gatt_svcs);
    if (rc != 0) {
        ESP_LOGE(TAG, "ble_gatts_count_cfg rc=%d", rc);
        return rc;
    }
    rc = ble_gatts_add_svcs(gatt_svcs);
    if (rc != 0) {
        ESP_LOGE(TAG, "ble_gatts_add_svcs rc=%d", rc);
    }
    return rc;
}

int app_gatt_notify_counter(uint32_t value)
{
    counter_value = value;
    if (!counter_notify_enabled) {
        return BLE_HS_EDISABLED;
    }
    return notify(counter_val_handle, &value, sizeof(value));
}

int app_gatt_notify_cmd_rsp(const uint8_t *data, uint16_t len)
{
    if (!cmd_notify_enabled) {
        ESP_LOGW(TAG, "command notify not enabled, response dropped");
        return BLE_HS_EDISABLED;
    }
    return notify(cmd_val_handle, data, len);
}

void app_gatt_on_subscribe(uint16_t attr_handle, bool notify_enabled)
{
    if (attr_handle == counter_val_handle) {
        counter_notify_enabled = notify_enabled;
    } else if (attr_handle == cmd_val_handle) {
        cmd_notify_enabled = notify_enabled;
    }
}

void app_gatt_on_disconnect(void)
{
    counter_notify_enabled = false;
    cmd_notify_enabled = false;
}

Step 5’s handle_command() (build and send a response) has become dispatch_command() (convert the kind of command into an event ID and post it).

  • The host task returns immediately after posting, so it doesn’t stall BLE processing
  • “What to return for PING” is decided by the handler. The same command can behave differently depending on the state
  • The functions that send Notify (app_gatt_notify_counter(), app_gatt_notify_cmd_rsp()) are called from handlers. Checking the subscription flags is encapsulated here

10.6.2 GAP: connect, disconnect, encryption into events

#include "app_gap.h"
#include "app_ble.h"
#include "app_gatt.h"
#include "app_event.h"

#include <string.h>
#include "esp_log.h"
#include "host/ble_hs.h"
#include "services/gap/ble_svc_gap.h"

#define TAG "APP_GAP"

static uint16_t conn_handle = BLE_HS_CONN_HANDLE_NONE;

uint16_t app_gap_conn_handle(void)
{
    return conn_handle;
}

static int gap_event_cb(struct ble_gap_event *event, void *arg)
{
    struct ble_gap_conn_desc desc;

    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;
            /* start security right after connecting (pairing request) */
            ble_gap_security_initiate(conn_handle);
            enqueue(EVT_BLE_CONNECTED, NULL, 0);
        } else {
            app_gap_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;
        app_gatt_on_disconnect();
        app_gap_start_advertising();
        enqueue(EVT_BLE_DISCONNECTED, NULL, 0);
        return 0;

    case BLE_GAP_EVENT_ADV_COMPLETE:
        app_gap_start_advertising();
        return 0;

    case BLE_GAP_EVENT_SUBSCRIBE:
        ESP_LOGI(TAG, "subscribe handle=%d notify=%d",
                 event->subscribe.attr_handle, event->subscribe.cur_notify);
        app_gatt_on_subscribe(event->subscribe.attr_handle, event->subscribe.cur_notify);
        return 0;

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

    case BLE_GAP_EVENT_ENC_CHANGE:
        if (ble_gap_conn_find(event->enc_change.conn_handle, &desc) == 0) {
            ESP_LOGI(TAG, "enc change status=%d encrypted=%d authenticated=%d bonded=%d",
                     event->enc_change.status, desc.sec_state.encrypted,
                     desc.sec_state.authenticated, desc.sec_state.bonded);
            if (event->enc_change.status == 0) {
                enqueue(EVT_BLE_PAIRED, NULL, 0);
            }
        }
        return 0;

    case BLE_GAP_EVENT_PASSKEY_ACTION: {
        struct ble_sm_io pkey = { 0 };
        if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
            pkey.action = BLE_SM_IOACT_DISP;
            pkey.passkey = APP_BLE_PAIRING_PASSKEY;
            ESP_LOGI(TAG, "==== Pairing passkey: %06d ====", APP_BLE_PAIRING_PASSKEY);
            int rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
            ESP_LOGI(TAG, "ble_sm_inject_io rc=%d", rc);
        } else {
            ESP_LOGW(TAG, "unsupported passkey action %d", event->passkey.params.action);
        }
        return 0;
    }

    case BLE_GAP_EVENT_REPEAT_PAIRING:
        /* if the peer deleted its bond information: delete the old bond and re-pair */
        if (ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc) == 0) {
            ble_store_util_delete_peer(&desc.peer_id_addr);
        }
        return BLE_GAP_REPEAT_PAIRING_RETRY;

    default:
        return 0;
    }
}

void app_gap_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();
    uint8_t own_addr_type;

    ble_hs_id_infer_auto(0, &own_addr_type);

    fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
    fields.uuids128 = &app_gatt_svc_uuid;
    fields.num_uuids128 = 1;
    fields.uuids128_is_complete = 1;
    ble_gap_adv_set_fields(&fields);

    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, "adv start failed rc=%d", rc);
        return;
    }
    ESP_LOGI(TAG, "advertising as \"%s\"", name);
}

Passkey handling (BLE_GAP_EVENT_PASSKEY_ACTION) is not turned into an event but completed inside the driver. Pairing is a fixed exchange with the SM, and there is no need to change behaviour depending on the app state. How much to turn into events is a design decision; a rule of thumb is to make events of “things whose behaviour changes depending on the state”.

10.6.3 Initialization

#include "app_ble.h"
#include "app_gap.h"
#include "app_gatt.h"

#include <stdio.h>
#include "esp_log.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 "APP_BLE"

void ble_store_config_init(void);

static void on_sync(void)
{
    static char name[20];
    uint8_t addr_type;
    uint8_t addr[6];

    ble_hs_util_ensure_addr(0);
    ble_hs_id_infer_auto(0, &addr_type);
    ble_hs_id_copy_addr(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(name, sizeof(name), APP_BLE_DEVICE_NAME_PREFIX "%02X%02X", addr[1], addr[0]);
    ble_svc_gap_device_name_set(name);

    app_gap_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() */
    nimble_port_freertos_deinit();
}

esp_err_t app_ble_init(void)
{
    esp_err_t ret = nimble_port_init();
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "nimble_port_init failed: %s", esp_err_to_name(ret));
        return ret;
    }

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

    /* security: passkey display (entered on the peer) + MITM + bonding + LE Secure Connections */
    ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_DISP_ONLY;
    ble_hs_cfg.sm_bonding = 1;
    ble_hs_cfg.sm_mitm = 1;
    ble_hs_cfg.sm_sc = 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_svc_gap_init();
    ble_svc_gatt_init();
    if (app_gatt_init() != 0) {
        return ESP_FAIL;
    }

    ble_store_config_init();

    nimble_port_freertos_init(host_task);
    return ESP_OK;
}
#pragma once

#include "esp_err.h"

#define APP_BLE_DEVICE_NAME_PREFIX "HANDSON-C3-" // + lower 2 bytes of the BD address
#define APP_BLE_PAIRING_PASSKEY 123456 /* pairing code (000000 - 999999) */

/* NimBLE init, security config, GATT registration, host task start (requires nvs_flash_init done) */
esp_err_t app_ble_init(void);

The BLE part of Step 5’s app_main() has been moved as is into app_ble_init().

10.6.4 The 1-second timer

#include "app_timer.h"
#include "app_event.h"

#include "esp_timer.h"

static esp_timer_handle_t timer_1s;

static void timer_1s_cb(void *arg)
{
    enqueue(EVT_TIMER_1S, NULL, 0);
}

esp_err_t timer_initialize(void)
{
    const esp_timer_create_args_t args = {
        .callback = timer_1s_cb,
        .name = "timer_1s",
    };
    esp_err_t ret = esp_timer_create(&args, &timer_1s);
    if (ret != ESP_OK) {
        return ret;
    }
    return esp_timer_start_periodic(timer_1s, TIMER_1S_INTERVAL_MS * 1000);
}

In Step 5, notify_task woke up every second with vTaskDelay(); in Step 6 a periodic esp_timer posts EVT_TIMER_1S. By default, esp_timer callbacks are called inside the esp_timer task (dispatch_method = ESP_TIMER_TASK).

10.7 Simulator: running the state machine

The same state transition table as Step 6 is reproduced here in JavaScript in the browser.

Current state
IDLE
Counter
0
Queue
0 / 32
Generate events
Queue contents (head → tail)
State transition table (last looked-up cell highlighted)
Log (also shows the bytes sent via Notify)

TipTry it
  1. Turn on “Run the 1-second timer”, wait a few seconds while still disconnected, then press “Connect”. Confirm that the counter increases even while disconnected and that Notify appears only after connecting
  2. What happens if you press “Write 00 (PING)” while disconnected? See which cell of the table was looked up
  3. Turn on “Step mode”, quickly press “Connect” → “Write 01” → “Disconnect”, then process them one at a time. Is the STATUS response sent?
  1. BLE_CMD_PING in the IDLE row is NULL, so nothing happens. On real hardware a Write never arrives while disconnected, but the same thing happens when, for example, an event left in the queue is processed after a disconnect.
  2. Events are processed in the order they occurred, so they are processed as “connect → STATUS → disconnect”. When STATUS is processed the state is still CONNECTED, so the handler tries to send a response. On real hardware, however, the BLE connection is already gone by then, so the driver’s notify() returns BLE_HS_ENOTCONN and nothing is sent. Be aware that the state machine’s state and the actual hardware state can differ by whatever is in the queue.

10.8 Comparing Step 5 and Step 6

Step 5 Step 6
Command processing Inside the host task main task (the host task only posts)
Per-second processing notify_task (own task) esp_timer → event
Differences by state if (conn_handle != NONE) etc. scattered around Expressed by rows of the state transition table
Shared variables Read and written by several tasks The state changes in only one place in the loop
Adding a feature Review every related callback and task Add an event and fill in the table cells

10.8.1 Steps to add a feature

  1. Add the event to app_event_id_t in app_event.h (before EVT_MAX)
  2. Add its name to event_name() in app_event.c
  3. In the driver, enqueue() it when the occurrence happens
  4. Write the handler function
  5. For every row of the table in handler.c, decide how to handle that event
ImportantKey points
  • Drivers (BLE, timer) only post events. Return from the host task immediately
  • Events go into the queue copied by value. If full, drop without waiting
  • Processing is chosen via the state × event table. The state is rewritten in one place in the event loop
  • Decide how much to turn into events by whether the behaviour changes depending on the state