Files
MicrOBU/obu-firmware/main/simple_ble.cpp
T

638 lines
26 KiB
C++
Raw Normal View History

#include "simple_ble.hpp"
#include "sdkconfig.h"
#include "ble_security_policy.hpp"
#include <algorithm>
#include <atomic>
#include <esp_timer.h>
#include <esp_log.h>
#include <esp_mac.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nvs.h>
#include <nimble/ble.h>
#include <host/ble_att.h>
#include <host/ble_gap.h>
#include <host/ble_gatt.h>
#include <host/ble_hs.h>
#include <host/ble_hs_mbuf.h>
#include <host/ble_sm.h>
#include <host/ble_store.h>
#include <host/ble_uuid.h>
#include <host/util/util.h>
#include <nimble/nimble_port.h>
#include <nimble/nimble_port_freertos.h>
#include <services/gap/ble_svc_gap.h>
#include <services/gatt/ble_svc_gatt.h>
#include <cstdio>
#include <cstring>
extern "C" void ble_store_config_init(void);
namespace microbu::ble {
namespace {
const char* TAG = "cits_ble";
constexpr uint32_t PAIRING_PASSKEY = CONFIG_MICROBU_BLE_PASSKEY;
std::atomic<bool> s_initialized {false};
// Increment whenever the service, characteristic, descriptor, or attribute ordering changes.
// Bonded centrals are allowed to cache the GATT database, so a firmware update must explicitly
// invalidate the old table before the next connection.
constexpr uint32_t GATT_SCHEMA_VERSION = 3;
// Requested connection interval, 1.25 ms units: 20 ms divides the 100 ms VAM period, and the TX guard is
// calibrated for it. The central decides; Windows 11 grants 15 ms for 12..16.
constexpr uint16_t connection_interval = 16; // 20 ms
constexpr uint16_t supervision_timeout = 400; // 4 s, 10 ms units
// Reconnection target: the bonded link usable again within 2 s. After a disconnect the station first
// advertises directed at the bonded central with high duty cycle, which a scanning central connects to at once
// (Core 5.4 Vol 6 Part B clause 4.4.2.4.3: at most 3.75 ms between events, ends after 1.28 s), then undirected in
// the 20-30 ms fast range for 30 s, then at the stack default. With only the default 30-60 ms interval the
// Windows central needed 0.2-8 s to catch an advertisement (measured 2026-10-03).
enum class AdvPhase { directed, fast, normal };
AdvPhase s_adv_phase = AdvPhase::fast;
ble_addr_t s_reconnect_peer = {};
constexpr int32_t directed_duration_ms = 1280;
constexpr int32_t fast_duration_ms = 30000;
constexpr uint16_t fast_interval_min = 32; // 20 ms, 0.625 ms units
constexpr uint16_t fast_interval_max = 48; // 30 ms
// Base UUID: 0000xxxx-ba5e-4c17-8000-00805f9b34fb
// Little-endian byte order for NimBLE (16 bytes, index 15 down to 0):
#define CITS_UUID_BASE(id_lo, id_hi) \
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, \
0x17, 0x4c, 0x5e, 0xba, (id_lo), (id_hi), 0x00, 0x00
static const ble_uuid128_t s_svc_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x75, 0xc1));
static const ble_uuid128_t s_chr_btp_req_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x76, 0xc1));
static const ble_uuid128_t s_chr_btp_ind_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x77, 0xc1));
static const ble_uuid128_t s_chr_poti_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x78, 0xc1));
static const ble_uuid128_t s_chr_access_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x79, 0xc1));
static const ble_uuid128_t s_chr_id_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x7a, 0xc1));
static const ble_uuid128_t s_chr_config_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x7b, 0xc1));
static const ble_uuid128_t s_chr_confirm_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x7c, 0xc1));
enum class ChrId : uintptr_t {
BtpRequest = 1,
BtpIndication = 2,
Poti = 3,
AccessProbe = 4,
IdChange = 5,
Configure = 6,
Confirm = 7,
};
Receiver s_receiver;
Counters statistics;
char s_dev_name[32] = "micrOBU";
uint16_t s_btp_ind_val_handle = 0;
uint16_t s_id_val_handle = 0;
uint16_t s_confirm_val_handle = 0;
volatile uint16_t s_conn_handle = BLE_HS_CONN_HANDLE_NONE;
#if CONFIG_MICROBU_BLE_ADVERTISE_AT_BOOT
volatile bool s_advertising_paused = false;
#else
volatile bool s_advertising_paused = true; // power profile: silent on BLE until a serial RAW_CAPTURE request
#endif
int s_notify_count = 0; // number of characteristics with active CCCD subscription
bool s_subscribed = false;
bool s_interval_requested = false; // the 20 ms connection interval was requested on this connection
uint8_t s_own_addr_type = 0;
std::atomic<std::int64_t> s_last_write_us {0}; // connection-event anchor for the TX guard
// GATT characteristic read/write callback, shared by all characteristics (arg identifies which).
int chr_access(uint16_t conn_handle, uint16_t attr_handle,
struct ble_gatt_access_ctxt *ctxt, void *arg) {
uintptr_t id = reinterpret_cast<uintptr_t>(arg);
if (ctxt->op == BLE_GATT_ACCESS_OP_WRITE_CHR) {
s_last_write_us.store(esp_timer_get_time());
uint16_t total = OS_MBUF_PKTLEN(ctxt->om);
if (total == 0 || total > link::maximum_message) {
ESP_LOGW(TAG, "rx invalid length: %u", (unsigned)total);
++statistics.malformed;
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
}
link::Bytes buf(total);
uint16_t copied = 0;
int rc = ble_hs_mbuf_to_flat(ctxt->om, buf.data(), total, &copied);
if (rc != 0 || copied != total) {
++statistics.malformed;
return BLE_ATT_ERR_UNLIKELY;
}
++statistics.rx_messages;
if (s_receiver) {
// Require valid link header (opcode + flags + seq).
if (total >= link::header_size && buf[0] >= 0x01 && buf[0] <= 0x17) {
ESP_LOGD(TAG, "rx chr %u op=0x%02x len=%u", (unsigned)id, buf[0], (unsigned)total);
s_receiver(std::move(buf));
} else {
ESP_LOGW(TAG, "rx chr %u unframed or invalid op=0x%02x len=%u", (unsigned)id, buf[0], (unsigned)total);
++statistics.malformed;
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
}
}
return 0;
} else if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) {
if (id == static_cast<uintptr_t>(ChrId::AccessProbe)) {
return 0; // authenticated empty read used only to establish link readiness
}
}
return BLE_ATT_ERR_READ_NOT_PERMITTED;
}
#define CHR_FLAG_RW_ENC (BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_READ_AUTHEN | \
BLE_GATT_CHR_F_WRITE_ENC | BLE_GATT_CHR_F_WRITE_AUTHEN)
#define CHR_FLAG_NOTIFY_ENC (BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC | \
BLE_GATT_CHR_F_NOTIFY_INDICATE_AUTHEN)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
static struct ble_gatt_chr_def s_chr_defs[] = {
{
// NF-SAP: BTP-DATA.request (Central -> Station Write). Write Command (no ATT response) is also
.uuid = &s_chr_btp_req_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::BtpRequest),
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_NO_RSP | CHR_FLAG_RW_ENC,
},
{
// NF-SAP: BTP-DATA.indication (Station -> Central Notify)
.uuid = &s_chr_btp_ind_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::BtpIndication),
.flags = BLE_GATT_CHR_F_NOTIFY | CHR_FLAG_NOTIFY_ENC,
.val_handle = &s_btp_ind_val_handle,
},
{
// PoTi: Position & Time Fix Update (Central -> Station Write). Write Command is also accepted:
.uuid = &s_chr_poti_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::Poti),
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_NO_RSP | CHR_FLAG_RW_ENC,
},
{
// Authenticated link-access probe (empty read; no status notification).
.uuid = &s_chr_access_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::AccessProbe),
.flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_READ_AUTHEN,
},
{
// SF-SAP: Identity Change Event (Station -> Central Notify)
.uuid = &s_chr_id_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::IdChange),
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY | CHR_FLAG_RW_ENC | CHR_FLAG_NOTIFY_ENC,
.val_handle = &s_id_val_handle,
},
{
// Station Configure / Credentials (Central -> Station Write)
.uuid = &s_chr_config_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::Configure),
.flags = BLE_GATT_CHR_F_WRITE | CHR_FLAG_RW_ENC,
},
{
// Confirm / Response (Station -> Central Notify). Request sequence numbers correlate the
// response and idempotent lifecycle operations can be retried by the station-link client.
.uuid = &s_chr_confirm_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::Confirm),
.flags = BLE_GATT_CHR_F_NOTIFY | CHR_FLAG_NOTIFY_ENC,
.val_handle = &s_confirm_val_handle,
},
{0}
};
static struct ble_gatt_svc_def s_svc_defs[] = {
{
.type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = &s_svc_uuid.u,
.characteristics = s_chr_defs,
},
{0}
};
#pragma GCC diagnostic pop
int start_advertising();
void on_connect(const decltype(ble_gap_event::connect)& connect) {
struct ble_gap_conn_desc desc;
if (connect.status == 0 && ble_gap_conn_find(connect.conn_handle, &desc) == 0) {
ESP_LOGI(TAG, "connect status=0 handle=%d interval=%u.%02u ms", connect.conn_handle,
unsigned(desc.conn_itvl * 125 / 100), unsigned(desc.conn_itvl * 125 % 100));
} else {
ESP_LOGI(TAG, "connect status=%d handle=%d", connect.status, connect.conn_handle);
}
if (connect.status != 0) { start_advertising(); return; }
if (ble_gap_conn_find(connect.conn_handle, &desc) != 0) {
ble_gap_terminate(connect.conn_handle, BLE_ERR_AUTH_FAIL);
return;
}
ble_addr_t peers[CONFIG_BT_NIMBLE_MAX_BONDS] {};
int count = 0;
const int stored = ble_store_util_bonded_peers(peers, &count, CONFIG_BT_NIMBLE_MAX_BONDS);
const bool owner = std::any_of(peers, peers + count,
[&](const ble_addr_t& peer) { return ble_addr_cmp(&peer, &desc.peer_id_addr) == 0; });
if (stored != 0 || (count != 0 && !owner)) {
ESP_LOGW(TAG, "connection refused: station already belongs to another bonded peer");
ble_gap_terminate(connect.conn_handle, BLE_ERR_AUTH_FAIL);
return;
}
s_conn_handle = connect.conn_handle;
s_subscribed = false;
s_interval_requested = false;
// Connection parameters are requested once the central subscribes (request_connection_interval): started together with
// pairing, the update met the central's own instant procedure and failed with 0x2A Different Transaction
ble_gap_security_initiate(connect.conn_handle);
}
void on_encryption_change(const decltype(ble_gap_event::enc_change)& change) {
ESP_LOGI(TAG, "encryption change status=%d", change.status);
if (change.status != 0) return;
// The link key must have the full 16 octets (128 bits, the Bluetooth maximum, Core 5.4 Vol 3
// Part H clause 2.3.4); the Security Manager would otherwise accept a peer's 7..15-octet maximum.
struct ble_gap_conn_desc desc;
if (ble_gap_conn_find(change.conn_handle, &desc) == 0 && desc.sec_state.key_size < 16) {
ESP_LOGW(TAG, "encryption key of %u octets refused (16 required): disconnecting", unsigned(desc.sec_state.key_size));
ble_gap_terminate(change.conn_handle, BLE_ERR_AUTH_FAIL);
return;
}
// The connection interval is requested once the central subscribes (on_subscribe), not here: requested right
// after encryption it stalled the Windows central's GATT session setup by 0.6-1.7 s on every reconnection and
// sometimes collided with the central's own procedure (status 0x2A, measured 2026-10-03).
}
void request_connection_interval(uint16_t conn_handle) {
if (s_interval_requested) return;
s_interval_requested = true;
struct ble_gap_conn_desc desc;
if (ble_gap_conn_find(conn_handle, &desc) == 0 && desc.conn_itvl == connection_interval) {
return; // a reconnecting central keeps the granted interval: another procedure would only collide (0x2A)
}
struct ble_gap_upd_params params = {};
params.itvl_min = connection_interval;
params.itvl_max = connection_interval;
params.latency = 0;
params.supervision_timeout = supervision_timeout;
const int rc = ble_gap_update_params(conn_handle, &params);
if (rc != 0) ESP_LOGW(TAG, "connection update request rc=%d", rc);
}
// Logs the connection parameters the central actually granted (interval in 1.25 ms units).
void on_connection_update(const decltype(ble_gap_event::conn_update)& update) {
struct ble_gap_conn_desc desc;
if (ble_gap_conn_find(update.conn_handle, &desc) != 0) return;
ESP_LOGI(TAG, "connection update status=%d interval=%u.%02u ms latency=%u timeout=%u ms",
update.status, unsigned(desc.conn_itvl * 125 / 100), unsigned(desc.conn_itvl * 125 % 100),
unsigned(desc.conn_latency), unsigned(desc.supervision_timeout * 10));
}
void on_disconnect(const decltype(ble_gap_event::disconnect)& disconnect) {
ESP_LOGI(TAG, "disconnect reason=%d", disconnect.reason);
s_conn_handle = BLE_HS_CONN_HANDLE_NONE;
s_subscribed = false;
s_notify_count = 0;
if (disconnect.conn.sec_state.bonded) {
s_reconnect_peer = disconnect.conn.peer_id_addr;
s_adv_phase = AdvPhase::directed;
} else {
s_adv_phase = AdvPhase::fast;
}
start_advertising();
}
// A timed advertising phase ended without a connection: continue with the next, slower one.
void on_advertising_complete(int reason) {
if (reason == BLE_HS_ETIMEOUT) {
s_adv_phase = s_adv_phase == AdvPhase::directed ? AdvPhase::fast : AdvPhase::normal;
}
start_advertising();
}
void on_passkey_action(uint16_t conn_handle, uint8_t action) {
if (action != BLE_SM_IOACT_DISP) { ESP_LOGW(TAG, "unhandled passkey action %d", action); return; }
struct ble_sm_io pkey = {};
pkey.action = BLE_SM_IOACT_DISP;
pkey.passkey = PAIRING_PASSKEY;
const int rc = ble_sm_inject_io(conn_handle, &pkey);
if (rc != 0) ESP_LOGW(TAG, "ble_sm_inject_io rc=%d", rc);
}
bool is_notify_handle(uint16_t attr_handle) {
return attr_handle == s_btp_ind_val_handle ||
attr_handle == s_id_val_handle || attr_handle == s_confirm_val_handle;
}
void on_subscribe(const decltype(ble_gap_event::subscribe)& subscribe) {
if (!is_notify_handle(subscribe.attr_handle)) return;
const bool was_subscribed = subscribe.prev_notify || subscribe.prev_indicate;
const bool is_subscribed = subscribe.cur_notify || subscribe.cur_indicate;
if (is_subscribed && !was_subscribed) {
++s_notify_count;
request_connection_interval(subscribe.conn_handle); // the central has finished setting up its session
}
else if (!is_subscribed && was_subscribed) --s_notify_count;
if (s_notify_count < 0) s_notify_count = 0;
s_subscribed = (s_notify_count > 0);
ESP_LOGI(TAG, "subscription handle %u changed: notify=%d indicate=%d count=%d",
subscribe.attr_handle, (int)subscribe.cur_notify,
(int)subscribe.cur_indicate, s_notify_count);
}
// NimBLE GAP callback: connect/disconnect, pairing (fixed-passkey), and notify subscriptions.
int gap_event(struct ble_gap_event *event, void *arg) {
switch (event->type) {
case BLE_GAP_EVENT_CONNECT: on_connect(event->connect); return 0;
case BLE_GAP_EVENT_ENC_CHANGE: on_encryption_change(event->enc_change); return 0;
case BLE_GAP_EVENT_CONN_UPDATE: on_connection_update(event->conn_update); return 0;
case BLE_GAP_EVENT_DISCONNECT: on_disconnect(event->disconnect); return 0;
case BLE_GAP_EVENT_REPEAT_PAIRING:
// Never erase an owner bond in response to an unauthenticated pairing request.
return BLE_GAP_REPEAT_PAIRING_IGNORE;
case BLE_GAP_EVENT_PASSKEY_ACTION: on_passkey_action(event->passkey.conn_handle, event->passkey.params.action); return 0;
case BLE_GAP_EVENT_SUBSCRIBE: on_subscribe(event->subscribe); return 0;
case BLE_GAP_EVENT_ADV_COMPLETE: on_advertising_complete(event->adv_complete.reason); return 0;
case BLE_GAP_EVENT_MTU:
ESP_LOGI(TAG, "mtu %u", unsigned(event->mtu.value));
return 0;
case BLE_GAP_EVENT_PHY_UPDATE_COMPLETE:
ESP_LOGI(TAG, "phy update status=%d tx=%u rx=%u", event->phy_updated.status,
unsigned(event->phy_updated.tx_phy), unsigned(event->phy_updated.rx_phy));
return 0;
default: return 0;
}
}
// (Re)starts undirected advertising with the device name and service UUID.
int start_advertising() {
if (!s_initialized.load() || s_advertising_paused) return 0; // set_advertising(false): a measuring board stays silent on BLE
const char* name = s_dev_name;
size_t name_len = strlen(name);
struct ble_hs_adv_fields adv = {};
adv.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
adv.tx_pwr_lvl_is_present = 1;
adv.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
adv.name = reinterpret_cast<const uint8_t*>(name);
adv.name_len = static_cast<uint8_t>(name_len);
adv.name_is_complete = 1;
int rc = ble_gap_adv_set_fields(&adv);
if (rc != 0) {
ESP_LOGE(TAG, "adv_set_fields rc=%d", rc);
return rc;
}
struct ble_hs_adv_fields rsp = {};
rsp.uuids128 = &s_svc_uuid;
rsp.num_uuids128 = 1;
rsp.uuids128_is_complete = 1;
rc = ble_gap_adv_rsp_set_fields(&rsp);
if (rc != 0) {
ESP_LOGE(TAG, "adv_rsp_set_fields rc=%d", rc);
return rc;
}
struct ble_gap_adv_params params = {};
if (s_adv_phase == AdvPhase::directed) {
params.conn_mode = BLE_GAP_CONN_MODE_DIR;
params.disc_mode = BLE_GAP_DISC_MODE_NON;
params.high_duty_cycle = 1;
rc = ble_gap_adv_start(s_own_addr_type, &s_reconnect_peer, directed_duration_ms, &params, gap_event, nullptr);
if (rc == 0) {
ESP_LOGI(TAG, "BLE advertising directed at the bonded central for %d ms", int(directed_duration_ms));
return 0;
}
ESP_LOGW(TAG, "directed adv_start rc=%d: undirected instead", rc);
s_adv_phase = AdvPhase::fast;
params = {};
}
params.conn_mode = BLE_GAP_CONN_MODE_UND;
params.disc_mode = BLE_GAP_DISC_MODE_GEN;
if (s_adv_phase == AdvPhase::fast) {
params.itvl_min = fast_interval_min;
params.itvl_max = fast_interval_max;
}
rc = ble_gap_adv_start(s_own_addr_type, nullptr, s_adv_phase == AdvPhase::fast ? fast_duration_ms : BLE_HS_FOREVER,
&params, gap_event, nullptr);
if (rc != 0) {
ESP_LOGE(TAG, "adv_start rc=%d", rc);
return rc;
}
ESP_LOGI(TAG, "BLE advertising started as '%s'%s", name, s_adv_phase == AdvPhase::fast ? " (fast, 20-30 ms)" : "");
return 0;
}
// NimBLE host reset callback.
void on_reset(int reason) {
ESP_LOGE(TAG, "NimBLE reset, reason=%d", reason);
}
// Mark the complete attribute table changed once per installed GATT schema. NimBLE persists the
// Service Changed pending bit for bonded, disconnected peers and clears it after their indication
// is acknowledged. This lets Windows and mobile clients rediscover new characteristics after an
// OTA/serial firmware update without requiring the user to remove and recreate the bond.
void invalidate_cached_gatt_schema() {
nvs_handle_t handle = 0;
esp_err_t err = nvs_open("microbu_ble", NVS_READWRITE, &handle);
if (err != ESP_OK) {
ESP_LOGW(TAG, "cannot open GATT schema state: %s", esp_err_to_name(err));
return;
}
uint32_t stored_version = 0;
err = nvs_get_u32(handle, "gatt_schema", &stored_version);
if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
ESP_LOGW(TAG, "cannot read GATT schema state: %s", esp_err_to_name(err));
nvs_close(handle);
return;
}
if (err == ESP_ERR_NVS_NOT_FOUND || stored_version != GATT_SCHEMA_VERSION) {
ble_svc_gatt_changed(0x0001, 0xffff);
err = nvs_set_u32(handle, "gatt_schema", GATT_SCHEMA_VERSION);
if (err == ESP_OK) err = nvs_commit(handle);
if (err == ESP_OK) {
ESP_LOGI(TAG, "GATT schema changed %lu -> %lu; bonded clients will rediscover",
static_cast<unsigned long>(stored_version),
static_cast<unsigned long>(GATT_SCHEMA_VERSION));
} else {
ESP_LOGW(TAG, "cannot persist GATT schema state: %s", esp_err_to_name(err));
}
}
nvs_close(handle);
}
// NimBLE host sync callback: resolves our address and starts advertising.
void on_sync() {
int rc = ble_hs_util_ensure_addr(0);
assert(rc == 0);
rc = ble_hs_id_infer_auto(0, &s_own_addr_type);
if (rc != 0) {
ESP_LOGE(TAG, "ble_hs_id_infer_auto rc=%d", rc);
return;
}
start_advertising();
}
// Select the characteristic for each station->central message. Stream/event data remains on
// notifications, routed to their dedicated characteristics.
uint16_t notify_handle(const link::Bytes& message) {
if (message.size() < link::header_size) return s_confirm_val_handle;
switch (static_cast<link::Opcode>(message[0])) {
case link::Opcode::BTP_DATA_INDICATION: return s_btp_ind_val_handle;
case link::Opcode::SF_IDCHANGE_EVENT: return s_id_val_handle;
default: return s_confirm_val_handle;
}
}
void nimble_host_task(void* param) {
ESP_LOGI(TAG, "NimBLE host task running");
nimble_port_run();
nimble_port_freertos_deinit();
}
} // namespace
bool start(Receiver receiver) {
if (!pairing_allowed(PAIRING_PASSKEY)) {
ESP_LOGW(TAG, "BLE disabled: no station passkey configured");
return false;
}
s_receiver = std::move(receiver);
uint8_t mac[6] = {};
if (esp_read_mac(mac, ESP_MAC_BT) == ESP_OK) {
std::snprintf(s_dev_name, sizeof(s_dev_name), "micrOBU-%02X%02X", mac[4], mac[5]);
}
esp_err_t err = nimble_port_init();
if (err != ESP_OK) {
ESP_LOGE(TAG, "nimble_port_init failed: %d", err);
return false;
}
ble_hs_cfg.reset_cb = on_reset;
ble_hs_cfg.sync_cb = on_sync;
ble_hs_cfg.store_status_cb = [](struct ble_store_status_event*, void*) { return BLE_HS_ESTORE_CAP; };
// Station-specific passkey, authenticated LE Secure Connections and bonding
ble_hs_cfg.sm_io_cap = BLE_HS_IO_DISPLAY_ONLY;
ble_hs_cfg.sm_sc = 1;
ble_hs_cfg.sm_bonding = 1;
ble_hs_cfg.sm_mitm = 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();
ble_svc_gap_device_name_set(s_dev_name);
int rc = ble_gatts_count_cfg(s_svc_defs);
if (rc != 0) {
ESP_LOGE(TAG, "ble_gatts_count_cfg failed: %d", rc);
nimble_port_deinit();
return false;
}
rc = ble_gatts_add_svcs(s_svc_defs);
if (rc != 0) {
ESP_LOGE(TAG, "ble_gatts_add_svcs failed: %d", rc);
nimble_port_deinit();
return false;
}
ble_store_config_init();
invalidate_cached_gatt_schema();
s_initialized.store(true);
nimble_port_freertos_init(nimble_host_task);
ESP_LOGI(TAG, "simple_ble initialized (authenticated pairing)");
return true;
}
bool write(const link::Bytes& message) {
uint16_t conn_handle = s_conn_handle;
if (conn_handle == BLE_HS_CONN_HANDLE_NONE) {
++statistics.tx_failed;
return false;
}
if (message.empty() || message.size() > link::maximum_message) {
++statistics.tx_failed;
return false;
}
// Custom notifications bypass the attribute subscription permission checks.
struct ble_gap_conn_desc desc;
if (ble_gap_conn_find(conn_handle, &desc) != 0 ||
!station_link_security_ready(desc.sec_state.encrypted, desc.sec_state.authenticated, desc.sec_state.key_size)) {
++statistics.tx_failed;
return false;
}
const uint16_t val_handle = notify_handle(message);
struct os_mbuf *om = ble_hs_mbuf_from_flat(message.data(), message.size());
if (!om) {
++statistics.tx_failed;
return false;
}
int rc = ble_gatts_notify_custom(conn_handle, val_handle, om);
if (rc != 0) {
// The custom API consumes the mbuf regardless of the outcome.
if (message.front() != static_cast<std::uint8_t>(link::Opcode::RAW_FRAME)) {
ESP_LOGW(TAG, "notify failed handle=%u op=0x%02x rc=%d", (unsigned)val_handle,
(unsigned)message.front(), rc);
}
++statistics.tx_failed;
return false;
}
++statistics.tx_messages;
return true;
}
std::size_t max_message() {
if (s_conn_handle == BLE_HS_CONN_HANDLE_NONE) return link::maximum_message;
const auto mtu = ble_att_mtu(s_conn_handle);
return mtu > 3 + link::header_size ? std::min<std::size_t>(mtu - 3, link::maximum_message) : link::maximum_message;
}
void set_advertising(bool enabled) {
s_advertising_paused = !enabled;
if (!s_initialized.load()) return;
if (s_conn_handle != BLE_HS_CONN_HANDLE_NONE) return; // connected: not advertising anyway
if (!enabled) {
if (ble_gap_adv_active()) ble_gap_adv_stop();
ESP_LOGI(TAG, "BLE advertising paused (on-air measurement)");
} else if (!ble_gap_adv_active()) {
start_advertising();
}
}
bool connected() {
return s_conn_handle != BLE_HS_CONN_HANDLE_NONE && s_subscribed;
}
bool is_subscribed() {
return s_subscribed;
}
Counters counters() {
return statistics;
}
std::int64_t last_write_us() {
return s_last_write_us.load();
}
std::uint32_t connection_interval_us() {
struct ble_gap_conn_desc desc;
const uint16_t handle = s_conn_handle;
if (handle == BLE_HS_CONN_HANDLE_NONE || ble_gap_conn_find(handle, &desc) != 0) return 0;
return static_cast<std::uint32_t>(desc.conn_itvl) * 1250;
}
} // namespace microbu::ble