flowchart TB S["Service c0a60001-…"] --> CNT["Counter c0a60002-…<br/>Read / Notify<br/>counter every second"] S --> CMD["Command c0a60003-…<br/>Write / Notify<br/>receives commands, returns responses"]
7 Receiving commands and responding
In Step 4 (firmware/step4_command), we add a second characteristic, Command, and return responses via Notify according to commands written from the smartphone.
7.1 Structure
Whether the characteristic you write commands to and the one that returns responses are the same or separate is a design choice.
| Approach | Pros | Cons |
|---|---|---|
| Same characteristic (this sample) | Easy to track which response belongs to which command | Has both Write and Notify properties |
| Separate (RX / TX) | Same shape as the Nordic UART Service. Can be used like a stream | Needs a mechanism to distinguish responses (a leading byte etc.) |
In either case, it is handy to put the command number at the beginning of the response so the receiver can tell which command it answers.
7.2 Protocol
| Command (Write) | Meaning | Response (Notify) |
|---|---|---|
00 |
PING | 00 50 4F 4E 47 (00 + ASCII PONG) |
01 |
STATUS | 9 bytes: 01 + counter (u32 LE) + seconds since boot (u32 LE) |
| Anything else | Undefined | <command> FF |
For example, if the counter is 300 (0x12C) and it has been 305 seconds (0x131) since boot, the STATUS response is
01 2C 01 00 00 31 01 00 00
│ └ counter └ uptime
└ command number
7.3 The whole code
/*
* Step 4: receive commands and respond
*
* Service : c0a60001-18ff-4cd1-afce-4832ee44bcb7
* Counter (Read / Notify) : c0a60002-... uint32 little-endian
* Command (Write / Notify) : c0a60003-... write commands; responses via Notify
*
* Commands:
* 0x00 -> PING : response [0x00, 'P','O','N','G']
* 0x01 -> STATUS : response [0x01, counter(u32 LE), uptime_sec(u32 LE)]
* other : response [cmd, 0xFF]
*/
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_timer.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 "STEP4"
#define CMD_PING 0x00
#define CMD_STATUS 0x01
/* 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 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 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;
static uint16_t cmd_val_handle;
static bool counter_notify_enabled;
static bool cmd_notify_enabled;
static uint32_t counter;
static void start_advertising(void);
/* ---------------- GATT ---------------- */
static int notify(uint16_t attr_handle, const void *data, uint16_t len)
{
if (conn_handle == 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_handle, attr_handle, om);
}
static void handle_command(const uint8_t *buf, uint16_t len)
{
uint8_t rsp[9];
uint16_t rsp_len;
uint8_t cmd = buf[0];
switch (cmd) {
case CMD_PING:
rsp[0] = CMD_PING;
memcpy(&rsp[1], "PONG", 4);
rsp_len = 5;
break;
case CMD_STATUS: {
uint32_t uptime = (uint32_t)(esp_timer_get_time() / 1000000);
rsp[0] = CMD_STATUS;
memcpy(&rsp[1], &counter, 4); // ESP32-C3 (RISC-V) is little-endian
memcpy(&rsp[5], &uptime, 4);
rsp_len = 9;
break;
}
default:
rsp[0] = cmd;
rsp[1] = 0xFF; // undefined command
rsp_len = 2;
break;
}
ESP_LOGI(TAG, "cmd 0x%02x (len=%d) -> rsp len=%d", cmd, len, rsp_len);
if (cmd_notify_enabled) {
notify(cmd_val_handle, rsp, rsp_len);
} else {
ESP_LOGW(TAG, "command notify not enabled, response dropped");
}
}
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, sizeof(counter));
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[20];
uint16_t len = OS_MBUF_PKTLEN(ctxt->om);
if (len == 0 || len > sizeof(buf)) {
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
}
// copy the mbuf (which may be a chain) into a flat array
ble_hs_mbuf_to_flat(ctxt->om, buf, sizeof(buf), &len);
handle_command(buf, len);
return 0; // returning 0 sends a successful Write Response
}
return BLE_ATT_ERR_UNLIKELY;
default:
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,
},
{
.uuid = &cmd_chr_uuid.u,
.access_cb = gatt_access_cb,
.val_handle = &cmd_val_handle,
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY,
},
{ 0 },
},
},
{ 0 },
};
/* ---------------- 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;
cmd_notify_enabled = false;
start_advertising();
return 0;
case BLE_GAP_EVENT_ADV_COMPLETE:
start_advertising();
return 0;
case BLE_GAP_EVENT_SUBSCRIBE:
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;
} else if (event->subscribe.attr_handle == cmd_val_handle) {
cmd_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();
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);
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 (counter_notify_enabled) {
notify(counter_val_handle, &counter, sizeof(counter));
}
}
}
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));
ESP_ERROR_CHECK(ble_gatts_add_svcs(gatt_svcs));
nimble_port_freertos_init(host_task);
xTaskCreate(notify_task, "notify", 3072, NULL, 5, NULL);
}7.4 Receiving a Write
case BLE_GATT_ACCESS_OP_WRITE_CHR:
if (attr_handle == cmd_val_handle) {
uint8_t buf[20];
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);
handle_command(buf, len);
return 0;
}- Check the length of the written data with
OS_MBUF_PKTLEN() - If the length is 0 or longer than expected, reject it by returning
BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN(ATT error0x0D). The client sees it as an error - Copy the mbuf into a plain array with
ble_hs_mbuf_to_flat(). An mbuf may be a chain, so avoid readingctxt->om->om_datadirectly - Process it and return
0; a Write Response (success) is returned
Data received over BLE is external input — you don’t know who will send what. memcpy() without a length check causes buffer overflows. Always check the length and the value range.
7.4.1 Write Request vs. Write Command
BLE_GATT_CHR_F_WRITE accepts a Write Request (with response), BLE_GATT_CHR_F_WRITE_NO_RSP a Write Command (without response). Whichever way it is written, the access callback is called with the same BLE_GATT_ACCESS_OP_WRITE_CHR.
| Write Request | Write Command | |
|---|---|---|
| Response | A Write Response is returned | None |
| Error reporting | Possible (the returned ATT error is sent back) | Not possible (the return value is ignored) |
| Speed | Waits one round trip | Fast (can be sent back to back) |
For uses like commands, where you want to know “did it arrive / was it accepted”, use Write Request.
7.5 Returning responses
static void handle_command(const uint8_t *buf, uint16_t len)
{
...
if (cmd_notify_enabled) {
notify(cmd_val_handle, rsp, rsp_len);
}
}Assemble the response bytes per command and return them via Notify on the Command characteristic. To receive responses, the client must also subscribe to Command’s CCCD. If not subscribed, response dropped appears in the log.
handle_command() is called from gatt_access_cb(), so the Notify is sent inside the host task. NimBLE is designed to call access callbacks with the host lock released (the source contains an assertion checking that the lock is not held), so it is fine to call host APIs such as Notify from inside a callback. ESP-IDF’s bleprph example also sends notifications with ble_gatts_chr_updated() from inside its Write callback.
However, if building the response becomes heavy, it is safer to hand it off to an event queue as in Chapter 10 and return from the host task immediately.
7.5.1 Endianness and memcpy
memcpy(&rsp[1], &counter, 4); // ESP32-C3 (RISC-V) is little-endianBecause the CPU is little-endian, memcpy()-ing a uint32_t as is gives a little-endian byte sequence. If you may port to a big-endian CPU, or want to make the intent explicit, write it with shifts like
rsp[1] = (uint8_t)(counter >> 0);
rsp[2] = (uint8_t)(counter >> 8);
rsp[3] = (uint8_t)(counter >> 16);
rsp[4] = (uint8_t)(counter >> 24);or use NimBLE’s put_le32(&rsp[1], counter).
7.6 Running it
- Connect with nRF Connect and enable Notify on
C0A60003-…(Command) - Press ↑ (Write), set the type to BYTE ARRAY and send
00→(0x) 00-50-4F-4E-47arrives on Command. Switch the display to UTF-8 to readPONG - Send
01→ 9 bytes starting with01arrive. Try reading off the counter and the seconds - Send
05→05-FFarrives - Send
00after disabling Command’s Notify:response droppedappears in the serial monitor
- What happens if you write 21 bytes or more? (nRF Connect can send long data too)
- Add a command
0x02that resets the counter to 0. Make the response02 00(success) - Add a command
0x03 xxthat changes the Notify period to xx seconds. Ifxxis 0 or 61 or more, return03 FF
static uint32_t notify_period_s = 1; // make notify_task use vTaskDelay(pdMS_TO_TICKS(notify_period_s * 1000))
case 0x02:
counter = 0;
rsp[0] = 0x02;
rsp[1] = 0x00;
rsp_len = 2;
break;
case 0x03:
rsp[0] = 0x03;
if (len >= 2 && buf[1] >= 1 && buf[1] <= 60) {
notify_period_s = buf[1];
rsp[1] = 0x00;
} else {
rsp[1] = 0xFF;
}
rsp_len = 2;
break;For 1: if the MTU is still 23, one Write can carry only up to 20 bytes, and nRF Connect may automatically switch to a Long Write (Prepare Write + Execute Write). Either way, the length check returns BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN and nRF Connect shows an error.
- A Write arrives as
BLE_GATT_ACCESS_OP_WRITE_CHR. Check the length before copying into an array - The returned ATT error reaches the client in the case of a Write Request
- Return responses via Notify. Putting the command number at the start of the response makes life easier for the receiver
- To receive responses, the client must subscribe to that characteristic’s CCCD