flowchart LR
subgraph D["drivers/(イベントの発生源)"]
GAP["app_gap.c<br/>接続・切断・暗号化"]
GATT["app_gatt.c<br/>コマンドの Write"]
TMR["app_timer.c<br/>1 秒タイマー"]
end
GAP -->|"enqueue()"| Q[("イベントキュー<br/>(FreeRTOS Queue)")]
GATT -->|"enqueue()"| Q
TMR -->|"enqueue()"| Q
Q -->|"dequeue()"| L["main.c<br/>イベントループ"]
L --> T["handlers/handler.c<br/>state_handler_table[状態][イベント]"]
T --> H["handler_idle.c<br/>handler_connected.c"]
H -->|"Notify の送信"| GATT
H -->|"次の状態"| L
10 イベント駆動に組み直す
Step 5 で、目標の機能(Notify・コマンド・ペアリング)はすべてそろいました。しかし main.c は 300 行を超え、
- GAP コールバック(ホストタスク)と
notify_task(別タスク)が、conn_handleや購読フラグを それぞれ勝手に読み書き している - コマンドの処理が、ホストタスクの中 で行われている
- 「接続中だけ 1 秒ごとに送る」「未接続なら何もしない」といった 状態による振る舞いの違い が、
if文に散らばっている
という状態です。機能を足すほど、どこで何が起きるのか追いにくくなります。Step 6(firmware/step6_event_driven)では、これを イベントキュー + 状態遷移テーブル の構成に組み直します。
10.1 設計
| 層 | 役割 | ルール |
|---|---|---|
| drivers/ | BLE・タイマーなど、外の世界との境界 | 出来事を イベントに変換して積むだけ。何をするかは決めない |
| common/ | イベントの型とキュー、状態の型、タイマー | ハードウェアに依存しない土台 |
| handlers/ | 「この状態でこのイベントが来たら何をするか」 | 状態遷移テーブル で選ばれ、次の状態を返す |
| main.c | イベントループ | 状態を書き換えるのは ここだけ |
10.1.1 ファイル構成
step6_event_driven/main/
├── CMakeLists.txt
├── main.c 初期化 + イベントループ
├── 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)INCLUDE_DIRS に 3 つのフォルダを並べているので、どのファイルからも #include "app_event.h" のようにフォルダ名なしで読み込めます。
event.h、gap.h、timer.h のような一般的な名前は、ESP-IDF や NimBLE のヘッダと衝突しやすい名前です。NimBLE にも host/ble_gap.h があります。app_ のような接頭辞 を付けておくと安全です。
10.2 状態遷移表
まず、振る舞いを表で設計します。
| 状態 \ イベント | BLE_CONNECTED | BLE_DISCONNECTED | BLE_PAIRED | CMD_PING | CMD_STATUS | CMD_UNKNOWN | TIMER_1S |
|---|---|---|---|---|---|---|---|
| IDLE(未接続) | → CONNECTED | — | — | — | — | — | カウンタ +1 |
| CONNECTED | — | → IDLE | ログ | PONG を返す | 状態を返す | エラーを返す | カウンタ +1、Notify |
「—」は そのイベントを無視する という意味です。表にすることで、「未接続のときにコマンドが届いたら?」(BLE の仕組み上は起きないが、キューに残っていた場合など)も 無視 と決まります。
10.3 イベントとキュー
#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, // 暗号化 (ペアリング/ボンド復元) 完了
EVT_BLE_CMD_PING, // コマンド 0x00
EVT_BLE_CMD_STATUS, // コマンド 0x01
EVT_BLE_CMD_UNKNOWN, // 未定義コマンド (payload[0] = コマンド値)
EVT_TIMER_1S, // 1秒周期タイマー
EVT_MAX,
} app_event_id_t;
// イベント情報を格納する構造体
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);
// キューにイベントを追加 (タスク/ISR どちらからでも可)
void enqueue(app_event_id_t id, const uint8_t *payload, size_t length);
// キューからイベントを取り出す (空ならブロック)
app_event_t dequeue(void);
const char *event_name(app_event_id_t id);- イベントは ID + ペイロード(値のコピー)+ 長さ + 時刻
- ペイロードは 配列で持ち、値をコピー する。BLE の受信バッファへのポインタを入れると、取り出したときには中身が変わっている・解放されている可能性がある
- 末尾の
EVT_MAXが イベントの種類の数 になり、テーブルの列数に使える
#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) {
// NimBLE ホストタスク等を止めないよう、満杯なら捨てる
ESP_LOGW(TAG, "queue full, drop %s", event_name(id));
}
}
app_event_t dequeue(void)
{
app_event_t event;
// イベントが入るまで無期限でブロック
if (xQueueReceive(event_queue, &event, portMAX_DELAY) == pdPASS) {
return event;
}
// フォールバック
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 ISR からでも、タスクからでも
enqueue() は、xPortInIsrContext() で 割り込みの中かどうか を調べ、
- 割り込みの中なら
xQueueSendToBackFromISR() - タスクの中なら
xQueueSendToBack()(待ち時間 0)
を使い分けます。このハンズオンの発生源(NimBLE のホストタスク、esp_timer タスク)はどちらもタスクですが、将来 GPIO 割り込みからボタンのイベントを積むときも、同じ enqueue() が使えます。
10.3.2 待たずに捨てる
タスクから積むときに 待たない のは、呼び出し元が NimBLE のホストタスクだから です。キューが満杯のときに待つと、その間 BLE の処理がすべて止まります。満杯なら捨てて警告を出し、根本的にはハンドラを速くする(キューを詰まらせない)ことで対処します。
10.3.3 取り出しは無期限に待つ
dequeue() は portMAX_DELAY で イベントが来るまで眠ります。キューが空の間、main タスクは CPU を使いません。
10.4 状態と状態遷移テーブル
#pragma once
typedef enum {
STATE_IDLE, // 未接続 (アドバタイズ中)
STATE_CONNECTED, // 接続中 (1秒ごとに Notify)
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);
// 状態遷移ハンドラテーブル
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);は、「イベントを受け取って 次の状態 を返す関数」への 関数ポインタ型 です。
#include "handler.h"
#include "handler_idle.h"
#include "handler_connected.h"
#include "app_gatt.h"
#include <string.h>
#include "esp_timer.h"
/*
* コマンド応答 (Command characteristic に Notify):
* 0x00 PING : [0x00, 'P','O','N','G']
* 0x01 STATUS : [0x01, counter(u32 LE), uptime_sec(u32 LE)]
* その他 : [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 は 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";
}
}
/*
* 状態遷移ハンドラテーブル
* NULL のイベントは無視 (状態維持)
*/
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,
},
};- テーブルは
[STATE_MAX][EVT_MAX]の 2 次元配列。行が状態、列がイベント - C99 の 指示付き初期化子
[STATE_IDLE] = { [EVT_BLE_CONNECTED] = ... }で、どのセルに何が入るかを明示している。書かなかったセルはNULLになる - 応答の組み立てなど、複数のハンドラで使う処理は 共通関数(
notify_status_rsp()など)にまとめる
10.4.1 ハンドラ
#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)
{
// 未接続中もカウントは進める
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(); // 購読中のみ送信される
return STATE_CONNECTED;
}ハンドラは 短く終わらせ、次の状態を返す だけです。状態を変えないなら、今の状態を返します。
10.5 イベントループ
/*
* ESP32-C3 BLE sample (NimBLE) - イベント駆動構成
*
* drivers : BLE / タイマー等の割込み・コールバック → enqueue() でイベント発行のみ
* main : dequeue() → state_handler_table[state][event] を実行 → 戻り値で状態更新
* handlers : 状態ごとのイベント処理
*/
#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(); // ドライバより先に作成 (コールバックが 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));
}
// 状態遷移テーブルからハンドラを取得 (未登録なら無視)
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;
}
}
}- キューを最初に作る(
event_queue_init())。BLE やタイマーを起動した直後からenqueue()が呼ばれうるため - イベントを 1 つ取り出す(なければ眠る)
- 範囲をチェックし、テーブルからハンドラを引く
NULLなら無視、あればハンドラを呼んで 戻り値で状態を更新
app_main() は Step 5 までと違い、戻らずにループし続けます。この main タスクが「イベントを処理する唯一のタスク」になります。
10.6 drivers:イベントに変換するだけ
10.6.1 GATT:Write をコマンドイベントに
#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; // 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);
}
// 受信コマンド → イベントに変換して enqueue (処理はハンドラ側)
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 : 暗号化された接続でなければ拒否
* *_AUTHEN : さらに MITM 保護つき(パスキー等)でペアリングした鍵でなければ拒否
* NOTIFY_INDICATE_* は CCCD(購読設定)への書き込みに効く。付けないと未ペアリングでも購読できてしまう
*/
#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 の handle_command()(応答を作って送る)は、dispatch_command()(コマンドの種類をイベント ID に変換して積む)に変わりました。
- ホストタスクは 積んだらすぐ戻る ので、BLE の処理を止めない
- 「PING に何を返すか」は ハンドラ が決める。同じコマンドでも、状態によって振る舞いを変えられる
- Notify を送る関数(
app_gatt_notify_counter()、app_gatt_notify_cmd_rsp())は ハンドラから呼ばれる 側。購読フラグの確認はここに閉じ込めている
10.6.2 GAP:接続・切断・暗号化をイベントに
#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;
/* 接続直後にセキュリティ開始 (ペアリング要求) */
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 (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);
}パスキーの処理(BLE_GAP_EVENT_PASSKEY_ACTION)は、イベントにせず ドライバの中で完結 させています。ペアリングは SM との決まったやりとりで、アプリの状態によって振る舞いを変える必要がないためです。どこまでをイベントにするか は設計の判断で、「状態によって振る舞いが変わるもの」をイベントにするのが目安です。
10.6.3 初期化
#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);
// 同じ部屋に何台あっても区別できるよう、アドレスの下位 2 バイトを名前に付ける
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(); /* 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;
/* セキュリティ: パスキー表示 (相手側で入力) + MITM + ボンディング + 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-" // + BD アドレス下位 2 バイト
#define APP_BLE_PAIRING_PASSKEY 123456 /* ペアリングコード (000000 - 999999) */
/* NimBLE 初期化・セキュリティ設定・GATT 登録・ホストタスク起動 (要 nvs_flash_init 済み) */
esp_err_t app_ble_init(void);Step 5 の app_main() の BLE 部分を、そのまま app_ble_init() に移しています。
10.6.4 1 秒タイマー
#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);
}Step 5 では notify_task が vTaskDelay() で 1 秒ごとに起きていましたが、Step 6 では esp_timer の周期タイマーで EVT_TIMER_1S を積みます。esp_timer のコールバックは、既定で esp_timer タスク の中で呼ばれます(dispatch_method = ESP_TIMER_TASK)。
10.7 シミュレータ:状態機械を動かしてみる
Step 6 と 同じ状態遷移テーブル を、ブラウザの JavaScript で再現しました。
- 「1 秒タイマーを動かす」をオンにし、未接続のまま 数秒待ってから「接続」しよう。カウンタは未接続中も増え、接続後だけ Notify が出ることを確かめよう
- 未接続のまま 「Write 00 (PING)」を押すと何が起きるか? 表のどのセルが引かれたか見よう
- 「ステップ実行」をオンにし、「接続」→「Write 01」→「切断」を素早く押してから、1 つずつ処理しよう。STATUS の応答は送られるか?
- IDLE の行の
BLE_CMD_PINGはNULLなので、何も起きません。実機では未接続の状態で Write が届くことはありませんが、キューに残っていたイベントを切断後に処理する、といった場面で同じことが起きます。 - イベントは 発生した順に 処理されるので、「接続 → STATUS → 切断」の順に処理されます。STATUS を処理する時点ではまだ CONNECTED なので、ハンドラは応答を送ろうとします。ただし実機では、そのときにはもう BLE の接続が切れているので、ドライバの
notify()がBLE_HS_ENOTCONNを返して何も送られません。状態機械の状態 と ハードウェアの実際の状態 には、キューの分だけずれがあることを意識しましょう。
10.8 Step 5 と Step 6 の比較
| Step 5 | Step 6 | |
|---|---|---|
| コマンドの処理 | ホストタスクの中 | main タスク(ホストタスクは積むだけ) |
| 1 秒ごとの処理 | notify_task(独自タスク) |
esp_timer → イベント |
| 状態による違い | if (conn_handle != NONE) などが散在 |
状態遷移テーブル の行で表現 |
| 共有変数 | 複数タスクが読み書き | 状態はループの 1 か所 でだけ変わる |
| 機能の追加 | 関係するコールバックとタスクを全部見直す | イベントを足し、テーブルのセルを埋める |
10.8.1 機能を追加する手順
app_event.hのapp_event_id_tにイベントを追加(EVT_MAXの前)app_event.cのevent_name()に名前を追加- ドライバで、出来事が起きたら
enqueue()する - ハンドラ関数を書く
handler.cのテーブルの すべての行 について、そのイベントをどう扱うか決める
- ドライバ(BLE・タイマー)は イベントを積むだけ。ホストタスクをすぐ返す
- イベントは 値でコピー してキューへ。満杯なら 待たずに捨てる
- 処理は 状態 × イベントの表 で選ぶ。状態を書き換えるのは イベントループの 1 か所
- どこまでをイベントにするかは、状態によって振る舞いが変わるか で決める