Rebuild obu-firmware on Niklas Dathe's microbu-firmware

Replace the vanetza-idf port with his current station firmware (microbu-firmware
e4e4bd8: main/, components/microbu_v2x, components/vanetza, external/vanetza) and
re-apply the MicrOBU additions, each marked "MicrOBU:" in the sources:

- V2X_RX (opcode 0x90): every received ITS message, signed or not, through
  gn_unwrap.c, because the stack drops unsigned and foreign-root traffic. 0x85 is
  the spec's RAW_FRAME and 0x86 is reserved. The body is built in v2x_rx.hpp.
- Unsigned transmission (geonet.c) for security profile 1 or station security 0,
  from a random MAC per configuration.
- Radio polled from STATION_CONFIGURE on; manual country policy, TX power
  read-back, static RX buffer, short frames ignored.
- Battery guard (battery_policy.hpp): deep sleep below 3.30 V with no phone on USB.
- No USB writes without a host; last_frame_ms() for the guard.
- 80 KB NVS with the app at 0x20000, 8 MB flash, XIAO ESP32-C5 board, 20 dBm.

Remove the old C firmware, the bench listener and the old vanetza-idf copy. Add
docs/station-link.tex as revision 2 of the interface reference (V2X_RX, unsigned
sending, battery rule, revision history). Add 39 host unit tests (make firmware in
test/host) next to the existing chain, replay, fuzz and battery tests, and point
tools/station_status_watch.py at the new CONFIRM-based status.
This commit is contained in:
Ashin Walpola
2026-11-11 00:13:57 +01:00
parent 1c3a66e4da
commit 50bbf6552d
10307 changed files with 53622 additions and 850451 deletions
+308 -164
View File
@@ -1,10 +1,15 @@
#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>
@@ -30,7 +35,31 @@ namespace microbu::ble {
namespace {
const char* TAG = "cits_ble";
constexpr uint32_t FIXED_PASSKEY = 123456;
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):
@@ -42,40 +71,45 @@ static const ble_uuid128_t s_svc_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(
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_status_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x79, 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_result_uuid = BLE_UUID128_INIT(CITS_UUID_BASE(0x7c, 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,
Status = 4,
AccessProbe = 4,
IdChange = 5,
Configure = 6,
Result = 7,
Confirm = 7,
};
Receiver s_receiver;
Counters statistics;
char s_dev_name[32] = "micrOBU";
uint16_t s_btp_ind_val_handle = 0;
uint16_t s_status_val_handle = 0;
uint16_t s_id_val_handle = 0;
uint16_t s_result_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;
volatile bool s_synced = false;
volatile bool s_adv_allowed = true;
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);
@@ -92,8 +126,7 @@ int chr_access(uint16_t conn_handle, uint16_t attr_handle,
++statistics.rx_messages;
if (s_receiver) {
// Require valid link header (opcode + flags + seq).
// Host->station opcodes are 0x01..0x0F; station->host are 0x80+.
if (total >= link::header_size && buf[0] >= 0x01 && buf[0] <= 0x0F) {
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 {
@@ -104,8 +137,8 @@ int chr_access(uint16_t conn_handle, uint16_t attr_handle,
}
return 0;
} else if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) {
if (id == static_cast<uintptr_t>(ChrId::Status)) {
return 0; // empty read; status is pushed via notify
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;
@@ -121,11 +154,11 @@ int chr_access(uint16_t conn_handle, uint16_t attr_handle,
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
static struct ble_gatt_chr_def s_chr_defs[] = {
{
// NF-SAP: BTP-DATA.request (Central -> Station Write)
// 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 | CHR_FLAG_RW_ENC,
.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)
@@ -136,19 +169,18 @@ static struct ble_gatt_chr_def s_chr_defs[] = {
.val_handle = &s_btp_ind_val_handle,
},
{
// PoTi: Position & Time Fix Update (Central -> Station Write)
// 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 | CHR_FLAG_RW_ENC,
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_NO_RSP | CHR_FLAG_RW_ENC,
},
{
// Station Status (Station -> Central Read/Notify)
.uuid = &s_chr_status_uuid.u,
// Authenticated link-access probe (empty read; no status notification).
.uuid = &s_chr_access_uuid.u,
.access_cb = chr_access,
.arg = reinterpret_cast<void*>(ChrId::Status),
.flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_NOTIFY | CHR_FLAG_RW_ENC | CHR_FLAG_NOTIFY_ENC,
.val_handle = &s_status_val_handle,
.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)
@@ -166,12 +198,13 @@ static struct ble_gatt_chr_def s_chr_defs[] = {
.flags = BLE_GATT_CHR_F_WRITE | CHR_FLAG_RW_ENC,
},
{
// Result / Response (Station -> Central Notify)
.uuid = &s_chr_result_uuid.u,
// 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::Result),
.arg = reinterpret_cast<void*>(ChrId::Confirm),
.flags = BLE_GATT_CHR_F_NOTIFY | CHR_FLAG_NOTIFY_ENC,
.val_handle = &s_result_val_handle,
.val_handle = &s_confirm_val_handle,
},
{0}
};
@@ -188,104 +221,157 @@ static struct ble_gatt_svc_def s_svc_defs[] = {
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) {
struct ble_gap_conn_desc desc;
switch (event->type) {
case BLE_GAP_EVENT_CONNECT:
ESP_LOGI(TAG, "connect status=%d handle=%d", event->connect.status, event->connect.conn_handle);
if (event->connect.status == 0) {
s_conn_handle = event->connect.conn_handle;
s_subscribed = false;
struct ble_gap_upd_params params = {};
params.itvl_min = 12; // 15 ms
params.itvl_max = 16; // 20 ms
params.latency = 0;
params.supervision_timeout = 400; // 4 s
params.min_ce_len = 0;
params.max_ce_len = 0;
ble_gap_update_params(event->connect.conn_handle, &params);
ble_gap_security_initiate(event->connect.conn_handle);
} else {
start_advertising();
}
return 0;
case BLE_GAP_EVENT_DISCONNECT:
ESP_LOGI(TAG, "disconnect reason=%d", event->disconnect.reason);
s_conn_handle = BLE_HS_CONN_HANDLE_NONE;
s_subscribed = false;
s_notify_count = 0;
start_advertising();
return 0;
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:
// MicrOBU: logged, since a phone that pairs again while we hold its bond means one side
// lost the keys; the phone's side then usually needs "forget device" as well.
ESP_LOGW(TAG, "phone started pairing again although bonded: dropping the old bond");
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;
case BLE_GAP_EVENT_ENC_CHANGE:
// MicrOBU: the one place the board side says whether the link got secure. 0 = encrypted.
if (ble_gap_conn_find(event->enc_change.conn_handle, &desc) == 0) {
ESP_LOGI(TAG, "encryption 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);
} else {
ESP_LOGI(TAG, "encryption change status=%d", event->enc_change.status);
}
return 0;
// 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, "ATT MTU %u", unsigned(event->mtu.value));
ESP_LOGI(TAG, "mtu %u", unsigned(event->mtu.value));
return 0;
case BLE_GAP_EVENT_PASSKEY_ACTION:
if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
struct ble_sm_io pkey = {};
pkey.action = BLE_SM_IOACT_DISP;
pkey.passkey = FIXED_PASSKEY;
ESP_LOGW(TAG, "BLE PAIRING FIXED PASSKEY: %06lu", static_cast<unsigned long>(FIXED_PASSKEY));
int rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
if (rc != 0) {
ESP_LOGW(TAG, "ble_sm_inject_io rc=%d", rc);
}
} else {
ESP_LOGW(TAG, "unhandled passkey action %d", event->passkey.params.action);
}
return 0;
case BLE_GAP_EVENT_SUBSCRIBE:
if (event->subscribe.attr_handle == s_btp_ind_val_handle ||
event->subscribe.attr_handle == s_status_val_handle ||
event->subscribe.attr_handle == s_id_val_handle ||
event->subscribe.attr_handle == s_result_val_handle) {
if (event->subscribe.cur_notify && !event->subscribe.prev_notify)
++s_notify_count;
else if (!event->subscribe.cur_notify && event->subscribe.prev_notify)
--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 count=%d",
event->subscribe.attr_handle, (int)event->subscribe.cur_notify, s_notify_count);
}
return 0;
case BLE_GAP_EVENT_ADV_COMPLETE:
start_advertising();
return 0;
default:
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, unless paused.
// (Re)starts undirected advertising with the device name and service UUID.
int start_advertising() {
if (!s_adv_allowed || !s_synced || s_conn_handle != BLE_HS_CONN_HANDLE_NONE || ble_gap_adv_active()) return 0;
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);
@@ -315,16 +401,32 @@ int start_advertising() {
}
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;
rc = ble_gap_adv_start(s_own_addr_type, nullptr, BLE_HS_FOREVER,
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'", name);
ESP_LOGI(TAG, "BLE advertising started as '%s'%s", name, s_adv_phase == AdvPhase::fast ? " (fast, 20-30 ms)" : "");
return 0;
}
@@ -333,6 +435,41 @@ 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);
@@ -342,14 +479,20 @@ void on_sync() {
ESP_LOGE(TAG, "ble_hs_id_infer_auto rc=%d", rc);
return;
}
s_synced = true;
// MicrOBU: a bond that did not persist (full NVS) looks like "the phone has to pair every time".
int bonds = 0;
if (ble_store_util_count(BLE_STORE_OBJ_TYPE_OUR_SEC, &bonds) == 0)
ESP_LOGI(TAG, "%d bonded phone(s) in NVS", bonds);
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();
@@ -359,6 +502,10 @@ void nimble_host_task(void* param) {
} // 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] = {};
@@ -374,9 +521,9 @@ bool start(Receiver receiver) {
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;
ble_hs_cfg.store_status_cb = [](struct ble_store_status_event*, void*) { return BLE_HS_ESTORE_CAP; };
// Fixed passkey LE Secure Connections + Bonding
// 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;
@@ -402,8 +549,10 @@ bool start(Receiver receiver) {
}
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 (fixed passkey %06lu)", static_cast<unsigned long>(FIXED_PASSKEY));
ESP_LOGI(TAG, "simple_ble initialized (authenticated pairing)");
return true;
}
@@ -417,34 +566,14 @@ bool write(const link::Bytes& message) {
++statistics.tx_failed;
return false;
}
uint16_t val_handle = s_result_val_handle;
if (message.size() >= link::header_size) {
link::Opcode op = static_cast<link::Opcode>(message[0]);
switch (op) {
case link::Opcode::V2X_RX:
case link::Opcode::BTP_DATA_INDICATION:
val_handle = s_btp_ind_val_handle;
break;
case link::Opcode::SF_IDCHANGE_EVENT:
val_handle = s_id_val_handle;
break;
case link::Opcode::STATUS:
// Route unsolicited or requested STATUS over the subscribed result/reply characteristic
val_handle = s_result_val_handle;
break;
case link::Opcode::RESULT:
default:
val_handle = s_result_val_handle;
break;
}
}
// MicrOBU: one notification is one whole message (no fragmentation on this GATT layout), and
// NimBLE cuts a value longer than ATT_MTU - 3 short without an error. The phone asks for an
// MTU of 517; until it has, drop rather than deliver a truncated message.
if (message.size() + 3 > ble_att_mtu(conn_handle)) {
// 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;
@@ -452,8 +581,11 @@ bool write(const link::Bytes& message) {
}
int rc = ble_gatts_notify_custom(conn_handle, val_handle, om);
if (rc != 0) {
ESP_LOGW(TAG, "notify failed handle=%u op=0x%02x rc=%d", (unsigned)val_handle, (unsigned)(message.empty() ? 0 : message[0]), rc);
if (rc == BLE_HS_ENOTSUP) os_mbuf_free_chain(om);
// 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;
}
@@ -461,25 +593,26 @@ bool write(const link::Bytes& message) {
return true;
}
bool connected() {
return s_conn_handle != BLE_HS_CONN_HANDLE_NONE && s_subscribed;
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_allowed(bool allowed) {
if (s_adv_allowed == allowed) return;
s_adv_allowed = allowed;
if (!s_synced) return;
if (allowed) {
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();
ESP_LOGI(TAG, "USB link idle: BLE advertising resumed");
} else if (ble_gap_adv_active()) {
ble_gap_adv_stop();
ESP_LOGI(TAG, "USB link in use: BLE advertising paused");
}
}
bool advertising_allowed() {
return s_adv_allowed;
bool connected() {
return s_conn_handle != BLE_HS_CONN_HANDLE_NONE && s_subscribed;
}
bool is_subscribed() {
@@ -490,4 +623,15 @@ 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