6  GATT サービスを作り、Notify する

Step 3(firmware/step3_notify)では、独自のサービスとキャラクタリスティックを 1 つずつ作り、1 秒ごとにカウンタ値を Notify します。

6.1 全体のコード

/*
 * Step 3: GATT サービスを作り、1 秒ごとに Notify する
 *
 * Service : c0a60001-18ff-4cd1-afce-4832ee44bcb7
 *   Counter (Read / Notify) : c0a60002-...  uint32 リトルエンディアン
 */
#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(バイト列は逆順=リトルエンディアンで書く) */
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; // 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 要求: 応答バッファ (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 }, // 終端
        },
    },
    { 0 }, // 終端
};

/* ---------------- GAP イベント ---------------- */

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:
        // セントラルが CCCD に書き込んだ (Notify の購読開始 / 停止)
        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;
    }
}

/* ---------------- アドバタイズ ---------------- */

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

    // アドバタイズ: フラグ + 128 bit サービス UUID (3 + 18 = 21 バイト)
    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);
}

/* ---------------- ホスト ---------------- */

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

/* ---------------- 1 秒ごとの Notify ---------------- */

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; // 未接続 or 未購読なら送らない
        }
        struct os_mbuf *om = ble_hs_mbuf_from_flat(&counter, sizeof(counter));
        if (om == NULL) {
            continue;
        }
        // om の所有権は NimBLE に移る(成功・失敗にかかわらず解放してくれる)
        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)); // 必要なメモリ量を数える
    ESP_ERROR_CHECK(ble_gatts_add_svcs(gatt_svcs));  // サービスを登録する

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

Step 2 から増えたのは、UUID の定義・GATT のサービス定義・アクセスコールバック・購読イベントの処理・Notify を送るタスク です。

6.2 サービスの定義

NimBLE では、GATT サービスを 構造体の配列(静的な表) で定義します。

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 }, // 終端
        },
    },
    { 0 }, // 終端
};
メンバ 意味
type PRIMARY(主サービス)か SECONDARY(他のサービスから参照される補助サービス)。ふつうは PRIMARY
uuid サービスの UUID。ble_uuid128_t の中の共通部分 .u へのポインタを渡す
characteristics キャラクタリスティックの配列。{ 0 } で終わる
access_cb Read / Write が来たときに呼ばれる関数
val_handle 登録後、値の属性のハンドル が書き込まれる変数へのポインタ
flags プロパティとパーミッション(第 3 章)

この配列が、第 3 章で見た 属性の表(サービス宣言・キャラクタリスティック宣言・値・CCCD)に展開されます。BLE_GATT_CHR_F_NOTIFY を付けると、CCCD は NimBLE が自動で追加 します。

ノート(struct ble_gatt_chr_def[]) { ... }

これは C99 の 複合リテラル で、名前のない配列をその場で作っています。キャラクタリスティックの配列を別の変数として宣言する代わりに、サービス定義の中に直接書けます。ESP-IDF のサンプルもこの書き方をしています。

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

第 3 章で見たとおり、文字列表記の逆順 に書きます。16 bit UUID なら BLE_UUID16_DECLARE(0x180D) のように書けます。

6.2.2 登録

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() で必要な属性の数を数えて領域を確保し、ble_gatts_add_svcs() で登録します。ホストタスクを起動する前 に呼びます。

6.3 アクセスコールバック:Read に応える

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;
}
  • Client が値を読みに来ると、NimBLE は ホストタスクの中で このコールバックを呼ぶ
  • ctxt->op で操作の種類(READ_CHR、WRITE_CHR、ディスクリプタの READ_DSC / WRITE_DSC)がわかる
  • attr_handle で どのキャラクタリスティックか がわかる。登録時に受け取った counter_val_handle と比べる
  • Read の応答は、ctxt->om(mbuf)に 値を追加 して返す
  • 戻り値 0 は成功、BLE_ATT_ERR_* は ATT のエラーコードとして Client に返る

カウンタは uint32_t をそのまま 4 バイトで送っています。ESP32-C3(RISC-V)はリトルエンディアンなので、counter = 5 なら 05 00 00 00 になります。

ヒント1 つのコールバックで複数のキャラクタリスティックを扱う

このサンプルでは、すべてのキャラクタリスティックに同じ gatt_access_cb を設定し、attr_handle で分岐しています。キャラクタリスティックごとに別の関数にしても構いませんし、.arg メンバに識別用の値を入れて、コールバックの arg で受け取る方法もあります。

6.4 購読イベント:誰が聞いているか

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

Client が CCCD に書き込むと、NimBLE は BLE_GAP_EVENT_SUBSCRIBE を送ってきます。

メンバ 内容
attr_handle どのキャラクタリスティックの CCCD か(値のハンドル が入る)
cur_notify / prev_notify Notify の購読状態(今 / 前)
cur_indicate / prev_indicate Indicate の購読状態
reason 書き込みによるものか、切断・ボンド復元によるものか

購読されていないのに Notify を送ってはいけません。そのため、購読状態をフラグに覚えておき、送る前に確認します。切断されたらフラグを下ろします。

6.5 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);
関数 内容
ble_hs_mbuf_from_flat() 配列から mbuf を作る。メモリ不足なら NULL
ble_gatts_notify_custom(conn, handle, om) om の内容を、指定した接続・ハンドルで Notify する。om は NimBLE が解放する

送る相手を conn_handle で指定するので、BLE_GAP_EVENT_CONNECT で接続ハンドルを覚えておき、切断で BLE_HS_CONN_HANDLE_NONE に戻しています。

ノートble_gatts_chr_updated() という方法も

NimBLE には、ble_gatts_chr_updated(val_handle) という関数もあります。これは「このキャラクタリスティックの値が変わった」とだけ伝え、NimBLE が 購読しているすべての接続 に、アクセスコールバックで Read した値 を Notify / Indicate してくれます。購読の管理まで NimBLE に任せられるので便利ですが、何をいつ送るかが見えにくくなるので、このハンズオンでは ble_gatts_notify_custom() で明示的に送っています。

6.5.1 どのタスクから送るか

notify_task は、app_main() で作った 自分のタスク です。第 4 章のとおり、NimBLE の API は内部でロックを取るので、ホストタスク以外から呼んでも構いません。

ただし、counter_notify_enabled や conn_handle は ホストタスク(GAP コールバック)が書き込み、notify_task が読む 変数です。このサンプルは「1 秒に 1 回読むだけで、多少ずれても困らない」ので素朴に書いていますが、本来は競合に注意が必要です(第 10 章でイベントキューを使って整理します)。

6.6 動かしてみる

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

6.6.1 nRF Connect で確認する

  1. SCAN すると、HANDSON-C3-XXXX の下に サービス UUID c0a60001-… が表示される(アドバタイズに載せたため)。名前はスキャン応答から来ている
  2. CONNECT すると、GAP・GATT に加えて Unknown Service(C0A60001-…) が見える
  3. サービスを開くと Unknown Characteristic(C0A60002-…)、Properties は READ, NOTIFY。その下に Client Characteristic Configuration(0x2902) がある
  4. ↓(Read) を押すと、値が (0x) 05-00-00-00 のように表示される(リトルエンディアンの 32 bit なので、カウンタ 5 は先頭が 05)
  5. ↓↓↓(Notify) を押すと、シリアルモニタに subscribe attr_handle=… notify=1 が出て、値が 1 秒ごとに 更新される
  6. もう一度押すと購読が解除され、notify=0 が出て更新が止まる
ヒントやってみよう
  1. ログに出る attr_handle の値と、nRF Connect の表示を見比べよう。CCCD の書き込みなのに、届くのは 値のハンドル であることを確かめよう
  2. 購読していない状態で、notify_task の if を外して無理に Notify を送るとどうなるか? rc をログで確かめよう
  3. Notify の周期を 10 ms にしてみよう。nRF Connect の表示やログはどうなるか?
  1. NimBLE の ble_gatts_notify_custom() 自体は CCCD を確認しないので、パケットは送られてしまいます(rc = 0)。Client は購読していないキャラクタリスティックの Notify を無視するか、OS によっては受け取ってしまいます。どちらにしても 仕様違反 なので、必ず購読状態を確認します。
  2. 接続間隔(Central が決める。iOS で 15〜30 ms 程度が多い)より短い周期で送ると、送信待ちがたまり、mbuf が足りなくなると ble_hs_mbuf_from_flat() が NULL を返したり、rc が BLE_HS_ENOMEM(6)になったりします。高速にデータを送るには、接続間隔を短くしてもらう・1 回の Notify に複数サンプルをまとめる・MTU を広げる、といった工夫が必要です。
重要キーポイント
  • サービスは ble_gatt_svc_def の静的な表 で定義し、ホスト起動前に登録する
  • val_handle に返る 値のハンドル で、キャラクタリスティックを見分ける
  • Read の応答は ctxt->om に 追加 して返す
  • Notify は BLE_GAP_EVENT_SUBSCRIBE で購読を確認してから ble_gatts_notify_custom() で送る