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
+7 -19
View File
@@ -1,22 +1,10 @@
# C++ station (from microbu-esp32c5/firmware/main) plus the C files of the previous firmware that
# still do a job here:
# gn_unwrap.c - raw receive path: 802.11/LLC-SNAP/GeoNetworking/BTP-B down to the ITS payload,
# for every frame on air, signed or not (station.cpp, forward_raw).
# geonet.c - unsigned transmit path: GN SHB + BTP-B exactly as the previous firmware built it
# (station.cpp, unsecured_request).
#
# Left on disk and NOT built, like cam.c before them:
# main.c, serial_link.c/.h - the previous firmware's entry point and phone link (frame types
# 0x01-0x05). Superseded by app_main.cpp and the station-link protocol.
# dot11p.c/.h - previous 802.11 framing; c5_radio.cpp frames through vanetza-idf now.
# Still compiled by the host tests in test/host.
# tx_custom.c/.h - previous copy of the OpenTrafficMap raw TX; otm_tx_custom.c replaces it.
# denm.c/.h, cam.c/.h, wifi_patches.c - reference only, as before.
idf_component_register(SRCS "app_main.cpp" "board_controls.cpp" "battery.cpp" "simple_ble.cpp" "c5_radio.cpp" "otm_tx_custom.c"
"link_protocol.cpp" "serial_link.cpp" "station.cpp" "station_test.cpp"
"link_service.cpp" "test_channel.cpp"
# MicrOBU, besides Niklas Dathe's sources:
# gn_unwrap.c - raw receive path: 802.11/LLC-SNAP/GeoNetworking/BTP-B down to the ITS payload, for every
# frame on air, signed or not (Station::forward_raw, link opcode V2X_RX).
# geonet.c - unsigned transmit path: GN SHB + BTP-B (Station::unsecured_request).
idf_component_register(SRCS "app_main.cpp" "board_controls.cpp" "battery_monitor.cpp" "simple_ble.cpp" "c5_radio.cpp" "otm_tx_custom.c" "link_protocol.cpp" "serial_link.cpp" "station.cpp" "tx_policy.cpp" "its_clock.cpp" "link_service.cpp" "heap_diagnostics.cpp"
"gn_unwrap.c" "geonet.c"
INCLUDE_DIRS "."
LDFRAGMENTS "linker.lf"
REQUIRES vanetza-idf esp_wifi esp_phy esp_event bt esp_driver_gpio esp_adc esp_driver_usb_serial_jtag nvs_flash esp_timer)
LDFRAGMENTS "linker.lf" "v2x_asn1_tables.lf"
REQUIRES bootloader_support esp_adc microbu_v2x esp_wifi esp_phy esp_event esp_coex bt esp_driver_gpio esp_driver_usb_serial_jtag nvs_flash esp_timer)
target_compile_features(${COMPONENT_LIB} PRIVATE cxx_std_17)
+51 -51
View File
@@ -1,83 +1,83 @@
menu "micrOBU firmware"
config MICROBU_TEST_CHANNEL
bool "Test channel on the serial link (software lower tester, ETSI campaign hooks)"
choice MICROBU_BOARD
prompt "Board"
default MICROBU_BOARD_MAINBOARD_V5
config MICROBU_BOARD_MAINBOARD_V5
bool "micrOBU mainboard v5"
config MICROBU_BOARD_XIAO_C5
bool "Seeed XIAO ESP32-C5"
endchoice
config MICROBU_XIAO_C5_BATTERY
bool "XIAO ESP32-C5 battery voltage monitor (GPIO6/26)"
depends on IDF_TARGET_ESP32C5 && MICROBU_BOARD_XIAO_C5
default y
help
Serves serial frame type 0x11: mirror or divert every AL_DATA.request the stack
makes to the tester, inject AL_DATA.indication, GN-DATA.request for the
Security ATS. Not part of the phone interface; disable for a production image.
config MICROBU_LOG_OVER_LINK
bool "Also carry ESP_LOG output as LOG frames (0x7F) on the native USB link"
Calibrated ADC voltage through the onboard 100k/100k divider.
Disable when building for another board. No percentage or charging state is inferred.
config MICROBU_STATUS_LED
bool "Drive the TX/RX indication LED"
default y if MICROBU_BOARD_XIAO_C5
default n
help
The colleague's single-port board has no other place for its log. This board keeps
the console on UART0 (the CH343 bridge port), so the phone's link carries no text.
config MICROBU_BLE_USB_IDLE_MS
int "USB link idle time before BLE advertising resumes (ms)"
range 1000 60000
default 3000
help
BLE and the 5.9 GHz radio share the C5's single RF front end. While the phone is
using the USB link (any frame received within this window), BLE advertising is
stopped so it cannot take airtime from ITS-G5. An existing BLE connection is left
alone. The phone sends a PoTi update with every GNSS fix, which keeps the window
open for as long as it is connected over USB.
Disable for power measurements and on boards whose GPIO27 is not a plain LED
(ESP32-C5-DevKitC-1: addressable RGB LED and strapping pin). The GPIO is then never touched.
config MICROBU_TX_LED_GPIO
int "Active-low activity LED GPIO (-1: none)"
range -1 28
default -1
int "Active-low transmit LED GPIO"
depends on MICROBU_STATUS_LED
range 0 28
default 27
help
The colleague's XIAO ESP32-C5 has its yellow user LED on GPIO27. On this project's
board GPIO27 is not a plain LED, so the indicator is off unless configured.
GPIO27 drives the on-board yellow user LED on the XIAO ESP32-C5.
config MICROBU_TX_LED_BLINK_MS
int "LED indication pulse (ms)"
range 10 2000
default 100
help
Duration in milliseconds for the LED visual indication (pulse on for TX, pulse off for RX).
config MICROBU_LED_INVERTED_RX
bool "Inverted LED mode for receiver/bridge (normally ON, blink OFF on packet)"
default n
config MICROBU_BENCH_LISTEN
bool "Bench listener: receive from boot and log every V2X_RX on the console"
depends on MICROBU_STATUS_LED
default n
help
For a test board whose PC connection is only the UART0 console (no phone, no USB
Serial/JTAG link): the station configures itself at boot with the radio receive only and
security off, and logs one line per ITS message the raw path (gn_unwrap.c) unwraps: BTP
port, messageID, length, RSSI, signed, GeoBroadcast, and whether it fits a link message.
A phone that configures the station later replaces this configuration. Never enable it in
the production image.
config MICROBU_BATTERY_ADC_GPIO
int "Battery voltage ADC GPIO (-1: no battery monitoring)"
range -1 6
default 6
When enabled, the LED stays constantly ON and blinks OFF briefly whenever a packet is
received (useful for bridge and receiver nodes). When disabled, the LED stays OFF and
blinks ON briefly whenever a packet is disseminated (sender mode).
config MICROBU_BLE_PASSKEY
int "Station BLE pairing passkey (0 disables BLE)"
range 0 999999
default 123456
help
The XIAO ESP32-C5 reads its battery on GPIO6 (BAT_VOLT_PIN) through two 100 k resistors.
config MICROBU_BATTERY_EN_GPIO
int "Battery divider enable GPIO"
range 0 28
default 26
Override the public default with a random six-digit passkey per station.
Supply it to the owner separately. It is never advertised or logged.
BLE does not require secure boot or flash encryption. The bond is kept
in NVS. This firmware rejects build settings that could program eFuses.
config MICROBU_BLE_ADVERTISE_AT_BOOT
bool "Start BLE advertising at boot"
default y
help
XIAO ESP32-C5: GPIO26 (BAT_VOLT_PIN_EN) switches the divider on for the reading.
config MICROBU_BATTERY_SCALE_PERMILLE
int "Battery reading trim (1000 = none)"
range 800 1200
default 1000
Disable for power measurements driven over USB: the board then stays silent on BLE
until a serial RAW_CAPTURE request switches advertising back on.
config MICROBU_TX_BLE_GUARD
bool "Hold ITS-G5 frames out of BLE connection events"
default y
help
Multiplies the reading. Compare the STATUS battery voltage with a multimeter on the cell
and set this to 1000 * multimeter / reading if the divider or ADC is off.
The C5 shares its RF between BLE and ITS-G5: a frame handed to the driver while a BLE
connection event holds the RF is accepted but never sent. The station delays such a frame
to the end of the calibrated connection event window (main/tx_policy.hpp). Disable only
to measure the losses without it.
config MICROBU_BATTERY_WARN_MV
int "Low-battery warning below this cell voltage (mV)"
range 3000 4200
default 3500
config MICROBU_BATTERY_SHUTDOWN_MV
int "Shutdown below this cell voltage (mV), see battery_monitor.hpp"
int "Shutdown below this cell voltage (mV), see battery_policy.hpp"
range 3000 4200
default 3300
help
There is no protection board on the prototype cell, so this is the only guard against
over-discharge. The board shuts down (deep sleep) once the smoothed voltage has stayed below
this for 30 s and no phone is talking over USB; it checks the cell again every
MICROBU_BATTERY_SLEEP_S and runs again from 3600 mV.
MICROBU_BATTERY_SLEEP_S and runs again from MICROBU_BATTERY_RESUME_MV.
config MICROBU_BATTERY_RESUME_MV
int "After a shutdown, run again at or above this cell voltage (mV)"
range 3300 4200
+57 -88
View File
@@ -1,26 +1,27 @@
// micrOBU firmware: the ESP32-C5 half of the VRU ITS-S on vanetza-idf.
// micrOBU firmware: the ESP32-C5 half of the VRU ITS-S on microbu_v2x.
// One station task owns stack, security entity and radio; the serial reader task only
// enqueues frames. Link messages: implementation/station-link/README.md.
// enqueues frames. Link messages: ../../docs/station-link.tex.
#include "link_protocol.hpp"
#include "link_service.hpp"
#include "battery.hpp"
#include "battery_monitor.hpp"
#include "battery_policy.hpp"
#include "board_controls.hpp"
#include "heap_diagnostics.hpp"
#include "simple_ble.hpp"
#include "serial_link.hpp"
#include "station.hpp"
#if CONFIG_MICROBU_TEST_CHANNEL
#include "test_channel.hpp"
#endif
#include <esp_log.h>
#include <esp_task_wdt.h>
#include <esp_timer.h>
#include <nvs_flash.h>
#include <esp_flash_encrypt.h>
#include <esp_partition.h>
#include <mbedtls/platform_util.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/task.h>
#include <algorithm>
#include <cstdio>
#include <esp_timer.h>
#include <new>
namespace {
@@ -32,9 +33,6 @@ struct Incoming {
microbu::serial::Frame frame;
};
constexpr std::int64_t battery_interval_us = 5000000; // one cell sample every 5 s
constexpr std::uint32_t battery_usb_window_ms = 10000; // a USB frame this recently means a phone powers the board
QueueHandle_t frames = nullptr; // FIFO of Incoming* (8 bytes each); frame bytes never enter the queue itself
/// @brief Attempts to heap-allocate an Incoming so it can be pushed onto the frames queue.
@@ -43,25 +41,16 @@ QueueHandle_t frames = nullptr; // FIFO of Incoming* (8 bytes each); frame bytes
/// @return Owning pointer to push onto the queue, or nullptr if allocation failed.
Incoming* try_new_incoming(microbu::LinkTransport transport, microbu::serial::Frame frame) noexcept {
try {
// std::move here steals frame's payload buffer into the heap Incoming (no byte copy);
// it has nothing to do with the queue below, which only ever transports the resulting pointer.
return new Incoming {transport, std::move(frame)};
return new Incoming {transport, std::move(frame)}; // takes the payload buffer over, no byte copy
} catch (const std::bad_alloc&) {
return nullptr;
}
}
/// @brief Dispatches one queued frame to the link service (or the test channel); logs and drops it on failure.
void handle_incoming(microbu::Station& station, microbu::LinkService& link, const Incoming& incoming) {
try {
if (incoming.frame.type == microbu::serial::FrameType::LINK)
link.handle(incoming.frame.payload, incoming.transport);
#if CONFIG_MICROBU_TEST_CHANNEL
else if (incoming.transport == microbu::LinkTransport::serial &&
incoming.frame.type == microbu::serial::FrameType::TEST)
microbu::serial::write(microbu::serial::FrameType::TEST,
microbu::test_channel_execute(station, incoming.frame.payload));
#endif
} catch (const std::bad_alloc&) {
ESP_LOGE(TAG, "out of memory while handling a frame");
} catch (const std::exception& e) {
@@ -69,19 +58,9 @@ void handle_incoming(microbu::Station& station, microbu::LinkService& link, cons
}
}
/// @brief MicrOBU: BLE and ITS-G5 share the C5's one RF front end. While the phone is talking over
/// USB there is no reason for BLE to take airtime, so advertising stops until the USB link has been
/// quiet for CONFIG_MICROBU_BLE_USB_IDLE_MS. A phone already connected over BLE is left connected.
void pause_ble_while_usb_in_use() {
const auto last = microbu::serial::last_frame_ms();
const auto now = static_cast<std::uint32_t>(esp_timer_get_time() / 1000);
const bool usb_in_use = last != 0 && now - last < CONFIG_MICROBU_BLE_USB_IDLE_MS;
microbu::ble::set_advertising_allowed(!usb_in_use);
}
/// @brief MicrOBU: the battery policy with this build's Kconfig thresholds.
microbu::BatteryConfig battery_config() {
microbu::BatteryConfig config;
/// @brief MicrOBU: BatteryPolicy thresholds from Kconfig.
microbu::BatteryPolicyConfig battery_config() {
microbu::BatteryPolicyConfig config;
config.warn_mv = CONFIG_MICROBU_BATTERY_WARN_MV;
config.warn_clear_mv = CONFIG_MICROBU_BATTERY_WARN_MV + 100; // 100 mV of hysteresis
config.shutdown_mv = CONFIG_MICROBU_BATTERY_SHUTDOWN_MV;
@@ -89,23 +68,21 @@ microbu::BatteryConfig battery_config() {
return config;
}
/// @brief MicrOBU: samples the cell, publishes it in STATUS and powers the board down before the
/// unprotected cell is over-discharged. A phone on USB powers the board itself, so the cell does not
/// force a shutdown while one is talking (see BatteryMonitor::update).
void check_battery(microbu::Battery& battery, microbu::BatteryMonitor& monitor, microbu::LinkService& link) {
constexpr std::int64_t battery_interval_us = 5000000; // BatteryPolicy counts 6 samples = 30 s below the threshold
constexpr std::uint32_t battery_usb_window_ms = 5000; // a USB frame this recent: a phone is powering the board
/// @brief MicrOBU: samples the cell and powers the board down before the unprotected cell (no
/// protection board on the prototype) is over-discharged. A phone on USB powers the board itself,
/// so the cell does not force a shutdown while one is talking (see BatteryPolicy::update).
void check_battery(microbu::BatteryPolicy& policy, microbu::LinkService& link) {
const auto now_ms = static_cast<std::uint32_t>(esp_timer_get_time() / 1000);
const auto last_usb = microbu::serial::last_frame_ms();
const bool usb_active = last_usb != 0 && now_ms - last_usb < battery_usb_window_ms;
monitor.update(battery.measure(), usb_active, now_ms);
std::uint8_t flags = 0;
if (monitor.low()) flags |= microbu::link::battery_flag_low;
if (monitor.critical()) flags |= microbu::link::battery_flag_critical;
link.set_battery(monitor.millivolts(), flags);
if (monitor.shutdown_due()) {
ESP_LOGW(TAG, "cell at %u mV and no phone on USB: shutting down", unsigned(monitor.millivolts()));
link.send_status_now(); // the phone sees the critical flag before the link goes away
vTaskDelay(pdMS_TO_TICKS(500));
microbu::Battery::deep_sleep();
policy.update(link.battery_millivolts(), usb_active, now_ms);
if (policy.shutdown_due()) {
ESP_LOGW(TAG, "cell at %u mV and no phone on USB: shutting down", unsigned(policy.millivolts()));
vTaskDelay(pdMS_TO_TICKS(200));
microbu::BatteryMonitor::deep_sleep();
}
}
@@ -116,39 +93,30 @@ void station_task(void*) {
microbu::BoardControls controls;
station.on_disseminated([&controls] { controls.blink(); });
station.on_received([&controls] { controls.blink(); });
microbu::Battery battery;
microbu::BatteryMonitor monitor(battery_config());
microbu::BatteryPolicy battery_policy(battery_config());
std::int64_t next_battery_us = 0;
#if CONFIG_MICROBU_BENCH_LISTEN
{ // MicrOBU: a console-only test board has nothing that would configure it (Kconfig help)
microbu::link::StationConfigure bench;
bench.security = 0;
bench.address_configuration = 0;
bench.beaconing = 0;
bench.radio = 1; // receive only
microbu::link::Bytes detail;
const auto code = station.configure(bench, detail);
ESP_LOGW(TAG, "BENCH LISTEN build: radio receive only, security off, logging every V2X_RX (result %u)",
unsigned(code));
}
#endif
ESP_LOGI(TAG, "station task ready; the phone/PC configures the station over BLE or USB Serial-JTAG");
for (;;) { /// main loop: drain the incoming queue, tick the station and link service, tick the controls
for (;;) { /// main loop: drain the incoming queue, tick the station and controls
Incoming* incoming = nullptr;
// MicrOBU: at least one tick. At CONFIG_FREERTOS_HZ=100 pdMS_TO_TICKS(5) is 0, so the wait
// never blocked: this priority-10 task spun on the single core, starved every lower-priority
// task and the idle task (task watchdog), for as long as the board ran.
if (xQueueReceive(frames, &incoming, std::max<TickType_t>(1, pdMS_TO_TICKS(5))) == pdTRUE && incoming) {
// At CONFIG_FREERTOS_HZ=100, pdMS_TO_TICKS(5) is 0 ticks: the loop never blocked and starved the idle
constexpr TickType_t wait = pdMS_TO_TICKS(5) > 0 ? pdMS_TO_TICKS(5) : 1;
if (xQueueReceive(frames, &incoming, wait) == pdTRUE && incoming) {
handle_incoming(station, link, *incoming);
delete incoming;
// Answer every frame that is already queued before submitting (bounded, so ticks still run): requests
// written back to back are all acknowledged first, and a VAM superseded meanwhile is replaced, not sent
// (latest state only).
for (int more = 0; more < 8 && xQueueReceive(frames, &incoming, 0) == pdTRUE && incoming; ++more) {
handle_incoming(station, link, *incoming);
delete incoming;
}
}
station.submit_pending(); // after the CONFIRM went out (reply first)
station.tick();
link.tick();
controls.tick();
pause_ble_while_usb_in_use();
if (esp_timer_get_time() >= next_battery_us) {
next_battery_us = esp_timer_get_time() + battery_interval_us;
check_battery(battery, monitor, link);
check_battery(battery_policy, link);
}
}
}
@@ -158,19 +126,25 @@ void station_task(void*) {
extern "C" void app_main() {
// MicrOBU: woken from a low-battery shutdown. Judge the cell before anything else starts, and
// go back to sleep unless it has recovered (charged over USB).
if (microbu::Battery::woke_from_battery_sleep()) {
microbu::Battery battery;
const auto millivolts = battery.measure();
if (!microbu::BatteryMonitor(battery_config()).resume_ok(millivolts)) {
if (microbu::BatteryMonitor::woke_from_battery_sleep()) {
const auto millivolts = microbu::BatteryMonitor().sample_millivolts();
if (!microbu::BatteryPolicy(battery_config()).resume_ok(millivolts)) {
ESP_LOGW(TAG, "cell still at %u mV, back to sleep", unsigned(millivolts));
microbu::Battery::deep_sleep();
microbu::BatteryMonitor::deep_sleep();
}
ESP_LOGI(TAG, "cell at %u mV, starting", unsigned(millivolts));
}
// NVS: the credential store (and the Wi-Fi driver's calibration data)
esp_err_t nvs = nvs_flash_init();
if (nvs == ESP_ERR_NVS_NO_FREE_PAGES || nvs == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
microbu::heap_diagnostics::install(); // failed allocations are recorded across a reset
// Encrypted NVS only on a chip whose flash encryption is already active, with existing keys.
// No key generation or eFuse programming is performed.
esp_err_t nvs;
if (esp_get_flash_encryption_mode() != ESP_FLASH_ENC_MODE_DISABLED) {
const auto* keys = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS, "nvs_keys");
nvs_sec_cfg_t cfg {};
nvs = keys && keys->encrypted ? nvs_flash_read_security_cfg(keys, &cfg) : ESP_ERR_NOT_FOUND;
if (nvs == ESP_OK) nvs = nvs_flash_secure_init(&cfg);
mbedtls_platform_zeroize(&cfg, sizeof(cfg));
} else {
nvs = nvs_flash_init();
}
ESP_ERROR_CHECK(nvs);
@@ -186,9 +160,8 @@ extern "C" void app_main() {
microbu::serial::start([](microbu::serial::Frame frame) {
auto* copy = try_new_incoming(microbu::LinkTransport::serial, std::move(frame));
if (!copy) return;
// xQueueSend copies the 8-byte pointer value into the queue, not *copy itself.
// station_task then pops pointers FIFO and owns/deletes whatever it receives.
if (xQueueSend(frames, &copy, 0) != pdTRUE) delete copy; // the phone retries on a missing RESULT
// the queue holds the pointer; the station task owns and deletes what it takes out
if (xQueueSend(frames, &copy, 0) != pdTRUE) delete copy; // the phone retries on a missing CONFIRM
});
if (!microbu::ble::start([](microbu::link::Bytes message) {
microbu::serial::Frame frame {microbu::serial::FrameType::LINK, std::move(message)};
@@ -198,11 +171,7 @@ extern "C" void app_main() {
})) {
ESP_LOGE(TAG, "BLE station link failed to start. USB remains available");
}
ESP_LOGI(TAG, "MicrOBU obu-firmware on vanetza-idf, station-link v1 + V2X_RX, console on UART0%s",
#if CONFIG_MICROBU_TEST_CHANNEL
", test channel enabled");
#else
"");
#endif
ESP_LOGI(TAG, "MicrOBU obu-firmware on microbu_v2x, station-link + V2X_RX (0x90)");
microbu::heap_diagnostics::report_boot(); // reset reason and the last failed allocation before it
xTaskCreate(station_task, "station", 12288, nullptr, 10, nullptr);
}
-100
View File
@@ -1,100 +0,0 @@
#include "battery.hpp"
#include "sdkconfig.h"
#include <algorithm>
#include <driver/gpio.h>
#include <esp_adc/adc_cali.h>
#include <esp_adc/adc_cali_scheme.h>
#include <esp_adc/adc_oneshot.h>
#include <esp_log.h>
#include <esp_rom_sys.h>
#include <esp_sleep.h>
namespace microbu {
namespace {
const char* TAG = "battery";
constexpr int samples = 16;
constexpr std::uint32_t settle_us = 2000; // the load switch and the divider's RC settle in well under this
constexpr int divider = 2; // two equal 100 k resistors on the XIAO ESP32-C5
}
Battery::Battery() {
#if CONFIG_MICROBU_BATTERY_ADC_GPIO < 0
ESP_LOGI(TAG, "battery monitoring disabled");
return;
#endif
gpio_config_t enable = {};
enable.pin_bit_mask = 1ULL << CONFIG_MICROBU_BATTERY_EN_GPIO;
enable.mode = GPIO_MODE_OUTPUT;
if (gpio_config(&enable) != ESP_OK) { ESP_LOGE(TAG, "enable GPIO %d unusable", CONFIG_MICROBU_BATTERY_EN_GPIO); return; }
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 0);
adc_unit_t unit;
adc_channel_t channel;
if (adc_oneshot_io_to_channel(CONFIG_MICROBU_BATTERY_ADC_GPIO, &unit, &channel) != ESP_OK) {
ESP_LOGE(TAG, "GPIO %d is not an ADC pin", CONFIG_MICROBU_BATTERY_ADC_GPIO);
return;
}
adc_oneshot_unit_init_cfg_t unit_config = {};
unit_config.unit_id = unit;
adc_oneshot_unit_handle_t adc = nullptr;
if (adc_oneshot_new_unit(&unit_config, &adc) != ESP_OK) { ESP_LOGE(TAG, "ADC unit init failed"); return; }
adc_oneshot_chan_cfg_t channel_config = {};
channel_config.atten = ADC_ATTEN_DB_12; // the divided cell is at most about 2.1 V
channel_config.bitwidth = ADC_BITWIDTH_DEFAULT;
if (adc_oneshot_config_channel(adc, channel, &channel_config) != ESP_OK) {
ESP_LOGE(TAG, "ADC channel config failed");
adc_oneshot_del_unit(adc);
return;
}
#if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
adc_cali_curve_fitting_config_t cali_config = {};
cali_config.unit_id = unit;
cali_config.chan = channel;
cali_config.atten = ADC_ATTEN_DB_12;
cali_config.bitwidth = ADC_BITWIDTH_DEFAULT;
adc_cali_handle_t cali = nullptr;
if (adc_cali_create_scheme_curve_fitting(&cali_config, &cali) == ESP_OK) cali_ = cali;
#endif
if (!cali_) ESP_LOGW(TAG, "no ADC calibration: readings are approximate");
adc_ = adc;
channel_ = static_cast<int>(channel);
}
std::uint16_t Battery::measure() {
if (!adc_) return 0;
auto* adc = static_cast<adc_oneshot_unit_handle_t>(adc_);
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 1);
esp_rom_delay_us(settle_us);
int values[samples];
int count = 0;
for (int i = 0; i < samples; ++i) {
int raw = 0;
if (adc_oneshot_read(adc, static_cast<adc_channel_t>(channel_), &raw) != ESP_OK) continue;
int millivolts = 0;
if (cali_) {
if (adc_cali_raw_to_voltage(static_cast<adc_cali_handle_t>(cali_), raw, &millivolts) != ESP_OK) continue;
} else {
millivolts = raw * 3100 / 4095; // uncalibrated 12 dB full scale, roughly
}
values[count++] = millivolts;
}
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 0);
if (count < samples / 2) return 0;
std::sort(values, values + count);
const int median = values[count / 2];
const long cell_mv = static_cast<long>(median) * divider * CONFIG_MICROBU_BATTERY_SCALE_PERMILLE / 1000;
return static_cast<std::uint16_t>(std::clamp(cell_mv, 0L, 65535L));
}
void Battery::deep_sleep() {
ESP_LOGW(TAG, "deep sleep for %d s", CONFIG_MICROBU_BATTERY_SLEEP_S);
esp_sleep_enable_timer_wakeup(static_cast<std::uint64_t>(CONFIG_MICROBU_BATTERY_SLEEP_S) * 1000000ULL);
esp_deep_sleep_start();
}
bool Battery::woke_from_battery_sleep() {
return esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER;
}
} // namespace microbu
-28
View File
@@ -1,28 +0,0 @@
#pragma once
// Cell voltage of the XIAO ESP32-C5's battery, read through the board's own divider: GPIO6 (ADC1)
// behind two 100 k resistors, switched on by GPIO26 (a load switch that keeps the divider from
// draining the cell between readings). The policy (warning, shutdown) is in battery_monitor.hpp.
#include <cstdint>
namespace microbu {
class Battery {
public:
/// @brief Configures the enable GPIO and the ADC channel. On failure measure() returns 0.
Battery();
/// @brief Takes one measurement: enables the divider, samples, disables it again. Blocks for a few ms.
/// @return Cell voltage in millivolts, or 0 if the ADC could not be set up or read.
std::uint16_t measure();
/// @brief Puts the board into deep sleep and wakes it after CONFIG_MICROBU_BATTERY_SLEEP_S seconds.
/// Does not return.
[[noreturn]] static void deep_sleep();
/// @return true if this boot is the end of such a sleep (the only timer wake-up the firmware arms).
static bool woke_from_battery_sleep();
private:
void* adc_ = nullptr; // adc_oneshot_unit_handle_t
void* cali_ = nullptr; // adc_cali_handle_t, null when the chip has no calibration
int channel_ = -1;
};
} // namespace microbu
+72
View File
@@ -0,0 +1,72 @@
#include "battery_monitor.hpp"
#include <driver/gpio.h>
#include <esp_adc/adc_cali_scheme.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_log.h>
#include <esp_sleep.h>
namespace microbu {
BatteryMonitor::BatteryMonitor() {
#if (CONFIG_MICROBU_XIAO_C5_BATTERY || CONFIG_MICROBU_BOARD_MAINBOARD_V5) && CONFIG_IDF_TARGET_ESP32C5
adc_unit_t unit;
#if CONFIG_MICROBU_BOARD_MAINBOARD_V5
constexpr int battery_gpio = 1;
#else
constexpr int battery_gpio = 6;
#endif
if (adc_oneshot_io_to_channel(battery_gpio, &unit, &channel_) != ESP_OK) return;
adc_oneshot_unit_init_cfg_t config = {};
config.unit_id = unit;
if (adc_oneshot_new_unit(&config, &adc_) != ESP_OK) return;
adc_oneshot_chan_cfg_t input = {};
input.atten = ADC_ATTEN_DB_12;
input.bitwidth = ADC_BITWIDTH_DEFAULT;
if (adc_oneshot_config_channel(adc_, channel_, &input) != ESP_OK) return;
adc_cali_curve_fitting_config_t calibration = {};
calibration.unit_id = unit;
calibration.chan = channel_;
calibration.atten = input.atten;
calibration.bitwidth = input.bitwidth;
if (adc_cali_create_scheme_curve_fitting(&calibration, &calibration_) != ESP_OK) {
ESP_LOGW("battery", "Calibration unavailable; battery voltage stays unavailable");
return;
}
#if CONFIG_MICROBU_XIAO_C5_BATTERY
gpio_set_direction(GPIO_NUM_26, GPIO_MODE_OUTPUT);
gpio_set_level(GPIO_NUM_26, 0);
#endif
#endif
}
void BatteryMonitor::deep_sleep() {
ESP_LOGW("battery", "deep sleep for %d s", CONFIG_MICROBU_BATTERY_SLEEP_S);
esp_sleep_enable_timer_wakeup(static_cast<std::uint64_t>(CONFIG_MICROBU_BATTERY_SLEEP_S) * 1000000ULL);
esp_deep_sleep_start();
}
bool BatteryMonitor::woke_from_battery_sleep() {
return esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER;
}
std::uint16_t BatteryMonitor::sample_millivolts() {
if (!adc_ || !calibration_) return 0;
#if CONFIG_MICROBU_XIAO_C5_BATTERY
gpio_set_level(GPIO_NUM_26, 1);
#endif
vTaskDelay(pdMS_TO_TICKS(5)); // settle the switched 100k/100k divider
int sum = 0;
bool valid = true;
for (unsigned i = 0; i < 16; ++i) {
int raw = 0, mv = 0;
if (adc_oneshot_read(adc_, channel_, &raw) != ESP_OK ||
adc_cali_raw_to_voltage(calibration_, raw, &mv) != ESP_OK) { valid = false; break; }
sum += mv;
}
#if CONFIG_MICROBU_XIAO_C5_BATTERY
gpio_set_level(GPIO_NUM_26, 0);
#endif
const int voltage = (sum * 2 + 8) / 16;
return valid && voltage >= 2500 && voltage <= 4500 ? voltage : 0;
}
}
+13 -62
View File
@@ -1,70 +1,21 @@
#pragma once
// Cell-voltage policy for the XIAO ESP32-C5's LiPo: smoothing, the low-battery warning with
// hysteresis, and the decision to shut down. Pure logic with no ESP-IDF dependency, so the host
// tests (test/host/test_battery.cpp) compile this header unmodified.
#include <cstdint>
#include <esp_adc/adc_oneshot.h>
#include <esp_adc/adc_cali.h>
namespace microbu {
/// @brief Thresholds and timing of the battery policy. Millivolts at the cell, not at the ADC pin.
struct BatteryConfig {
std::uint16_t warn_mv = 3500; ///< low-battery warning below this
std::uint16_t warn_clear_mv = 3600;///< ... and cleared again at or above this (hysteresis)
std::uint16_t shutdown_mv = 3300; ///< shut down below this ...
unsigned shutdown_samples = 6; ///< ... for this many consecutive samples (6 x 5 s = 30 s: rides out TX sag)
std::uint32_t grace_ms = 60000; ///< no shutdown in the first minute after boot
std::uint16_t resume_mv = 3600; ///< after a shutdown the board only runs again at or above this
std::uint16_t valid_min_mv = 2500; ///< a reading outside valid_min..valid_max is "no cell / no sensor"
std::uint16_t valid_max_mv = 4500;
};
/// @brief Turns raw cell-voltage samples into a smoothed value, a warning flag and a shutdown decision.
// Calibrated divider voltage for the selected board.
class BatteryMonitor {
public:
/// @param config Thresholds; the defaults suit a single LiPo cell.
explicit BatteryMonitor(BatteryConfig config = {}) : config_(config) {}
/// @brief Feeds one sample, taken every few seconds.
/// @param mv Cell voltage in millivolts, or 0 when the measurement failed.
/// @param usb_active A phone is talking over USB, so the board is powered from the phone and
/// the cell cannot be the reason it would stop.
/// @param uptime_ms Milliseconds since boot.
void update(std::uint16_t mv, bool usb_active, std::uint32_t uptime_ms) {
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) {
// No cell (or no sensor): report "not measured" and never shut down on it.
valid_ = false; ema_ = 0; low_ = false; below_ = 0;
return;
}
if (!valid_) { valid_ = true; ema_ = mv; } // first sample after a gap: no ramp from zero
else ema_ = static_cast<std::uint16_t>(ema_ + (static_cast<int>(mv) - static_cast<int>(ema_)) / 4);
if (ema_ < config_.warn_mv) low_ = true;
else if (ema_ >= config_.warn_clear_mv) low_ = false;
if (ema_ < config_.shutdown_mv && !usb_active && uptime_ms >= config_.grace_ms) ++below_;
else below_ = 0;
}
/// @return Smoothed cell voltage in millivolts, 0 while there is no valid reading.
std::uint16_t millivolts() const { return valid_ ? ema_ : 0; }
/// @return true once the cell fell below the warning threshold, until it is back above the clear threshold.
bool low() const { return low_; }
/// @return true while the smoothed voltage is below the shutdown threshold (not yet sustained).
bool critical() const { return valid_ && ema_ < config_.shutdown_mv; }
/// @return true once the cell has stayed below the shutdown threshold with no USB link for long enough.
bool shutdown_due() const { return below_ >= config_.shutdown_samples; }
/// @param mv A single reading taken right after a wake-up.
/// @return true if the board may run: the cell recovered, or there is no valid reading to judge by.
bool resume_ok(std::uint16_t mv) const {
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) return true;
return mv >= config_.resume_mv;
}
BatteryMonitor();
std::uint16_t sample_millivolts(); // 0 means unavailable, never an invented percentage
/// MicrOBU: powers the board down for CONFIG_MICROBU_BATTERY_SLEEP_S seconds (timer wake-up).
[[noreturn]] static void deep_sleep();
/// MicrOBU: true when this boot is the timer wake-up of deep_sleep().
static bool woke_from_battery_sleep();
private:
BatteryConfig config_;
std::uint16_t ema_ = 0;
bool valid_ = false;
bool low_ = false;
unsigned below_ = 0;
adc_oneshot_unit_handle_t adc_ = nullptr;
adc_cali_handle_t calibration_ = nullptr;
adc_channel_t channel_ = ADC_CHANNEL_0;
};
} // namespace microbu
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
// Cell-voltage policy for the XIAO ESP32-C5's LiPo: smoothing, the low-battery warning with
// hysteresis, and the decision to shut down. Pure logic with no ESP-IDF dependency, so the host
// tests (test/host/test_battery.cpp) compile this header unmodified. Kept out of BatteryMonitor, which
// only samples the cell.
#include <cstdint>
namespace microbu {
/// @brief Thresholds and timing of the battery policy. Millivolts at the cell, not at the ADC pin.
struct BatteryPolicyConfig {
std::uint16_t warn_mv = 3500; ///< low-battery warning below this
std::uint16_t warn_clear_mv = 3600;///< ... and cleared again at or above this (hysteresis)
std::uint16_t shutdown_mv = 3300; ///< shut down below this ...
unsigned shutdown_samples = 6; ///< ... for this many consecutive samples (6 x 5 s = 30 s: rides out TX sag)
std::uint32_t grace_ms = 60000; ///< no shutdown in the first minute after boot
std::uint16_t resume_mv = 3600; ///< after a shutdown the board only runs again at or above this
std::uint16_t valid_min_mv = 2500; ///< a reading outside valid_min..valid_max is "no cell / no sensor"
std::uint16_t valid_max_mv = 4500;
};
/// @brief Turns raw cell-voltage samples into a smoothed value, a warning flag and a shutdown decision.
class BatteryPolicy {
public:
/// @param config Thresholds; the defaults suit a single LiPo cell.
explicit BatteryPolicy(BatteryPolicyConfig config = {}) : config_(config) {}
/// @brief Feeds one sample, taken every few seconds.
/// @param mv Cell voltage in millivolts, or 0 when the measurement failed.
/// @param usb_active A phone is talking over USB, so the board is powered from the phone and
/// the cell cannot be the reason it would stop.
/// @param uptime_ms Milliseconds since boot.
void update(std::uint16_t mv, bool usb_active, std::uint32_t uptime_ms) {
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) {
// No cell (or no sensor): report "not measured" and never shut down on it.
valid_ = false; ema_ = 0; low_ = false; below_ = 0;
return;
}
if (!valid_) { valid_ = true; ema_ = mv; } // first sample after a gap: no ramp from zero
else ema_ = static_cast<std::uint16_t>(ema_ + (static_cast<int>(mv) - static_cast<int>(ema_)) / 4);
if (ema_ < config_.warn_mv) low_ = true;
else if (ema_ >= config_.warn_clear_mv) low_ = false;
if (ema_ < config_.shutdown_mv && !usb_active && uptime_ms >= config_.grace_ms) ++below_;
else below_ = 0;
}
/// @return Smoothed cell voltage in millivolts, 0 while there is no valid reading.
std::uint16_t millivolts() const { return valid_ ? ema_ : 0; }
/// @return true once the cell fell below the warning threshold, until it is back above the clear threshold.
bool low() const { return low_; }
/// @return true while the smoothed voltage is below the shutdown threshold (not yet sustained).
bool critical() const { return valid_ && ema_ < config_.shutdown_mv; }
/// @return true once the cell has stayed below the shutdown threshold with no USB link for long enough.
bool shutdown_due() const { return below_ >= config_.shutdown_samples; }
/// @param mv A single reading taken right after a wake-up.
/// @return true if the board may run: the cell recovered, or there is no valid reading to judge by.
bool resume_ok(std::uint16_t mv) const {
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) return true;
return mv >= config_.resume_mv;
}
private:
BatteryPolicyConfig config_;
std::uint16_t ema_ = 0;
bool valid_ = false;
bool low_ = false;
unsigned below_ = 0;
};
} // namespace microbu
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <cstdint>
namespace microbu::ble {
// BLE needs a configured six-digit station passkey (0 disables BLE). It does not depend on
// secure boot, flash encryption or encrypted NVS: none of them may be enabled by this firmware.
constexpr bool pairing_allowed(std::uint32_t passkey) {
return passkey > 0 && passkey <= 999999;
}
constexpr bool station_link_security_ready(bool encrypted, bool authenticated, std::uint8_t key_size) {
return encrypted && authenticated && key_size == 16;
}
}
+7 -3
View File
@@ -7,12 +7,14 @@
namespace microbu {
namespace {
const char* TAG = "board";
#if CONFIG_MICROBU_STATUS_LED
constexpr std::int64_t blink_us = CONFIG_MICROBU_TX_LED_BLINK_MS * 1000LL;
#endif
}
BoardControls::BoardControls() {
#if CONFIG_MICROBU_TX_LED_GPIO < 0
ESP_LOGI(TAG, "no activity LED configured");
#if !CONFIG_MICROBU_STATUS_LED
ESP_LOGI(TAG, "status LED disabled; its GPIO is not driven");
#else
gpio_config_t led = {};
led.pin_bit_mask = 1ULL << CONFIG_MICROBU_TX_LED_GPIO;
@@ -33,7 +35,7 @@ BoardControls::BoardControls() {
}
void BoardControls::apply_led_state() {
#if CONFIG_MICROBU_TX_LED_GPIO >= 0
#if CONFIG_MICROBU_STATUS_LED
// The XIAO ESP32-C5 user LED is wired active-low (0 = ON, 1 = OFF).
// In normal_tx mode: default OFF (1), pulsing ON (0).
// In inverted_rx mode: default ON (0), pulsing OFF (1).
@@ -48,11 +50,13 @@ void BoardControls::apply_led_state() {
}
void BoardControls::blink() {
#if CONFIG_MICROBU_STATUS_LED
pulse_until_us_ = esp_timer_get_time() + blink_us;
if (!pulsing_) {
pulsing_ = true;
apply_led_state();
}
#endif
}
void BoardControls::tick() {
+161 -217
View File
@@ -1,6 +1,8 @@
#include "c5_radio.hpp"
#include "otm_tx_custom.h"
#include <vanetza_idf/its_g5_frame.hpp>
#include "radio_policy.hpp"
#include "cca_window.hpp"
#include <microbu_v2x/its_g5_frame.hpp>
#include <esp_event.h>
#include <esp_log.h>
#include <esp_wifi.h>
@@ -44,9 +46,21 @@ void phy_disable_cca(void);
int phy_get_noise_floor(void);
}
namespace microbu {
void arm_cca_counters();
}
namespace microbu {
namespace {
const char* TAG = "c5_radio";
// Driver TX completion of esp_wifi_80211_tx_custom frames (Wi-Fi task): the MAC finished the frame, which says
// nothing about its reception.
std::atomic<std::uint32_t> tx_completed {0}, tx_completion_failed {0};
void tx_done(const esp_80211_tx_info_t* info) {
if (!info) return;
if (info->tx_status == WIFI_SEND_SUCCESS) ++tx_completed;
else ++tx_completion_failed;
}
}
@@ -54,47 +68,98 @@ class C5Radio::Impl {
public:
/// @brief Raw received frame metadata and bytes from the promiscuous RX callback.
struct Raw {
std::uint16_t length;
std::uint16_t length; // sig_len, including FCS (stack path)
std::uint16_t capture_length; // dump_len, MPDU without FCS (raw capture); 0 = not captured
bool for_stack; // data frame for the ITS-G5 stack
std::int8_t rssi;
std::uint32_t timestamp;
std::uint8_t bytes[2346]; // max 802.11 frame size
};
// Reserve the normal RX queue before runtime allocations fragment the heap.
// Sixteen maximum-sized frames need more than 37 kB in one block; a late
// xQueueCreate failed despite 141 kB free (largest block 36 kB).
static constexpr unsigned reserved_rx_frames = 16;
static StaticQueue_t rx_control;
alignas(portBYTE_ALIGNMENT) static std::uint8_t rx_storage[reserved_rx_frames * sizeof(Raw)];
C5RadioConfig config;
QueueHandle_t queue = nullptr;
bool initialized = false, started = false, own_event_loop = false;
std::uint16_t sequence = 0;
std::atomic<std::uint32_t> dropped {0};
std::atomic<std::uint8_t> capture_mode {0};
Transmitted transmitted;
std::uint32_t submitted = 0, no_mem = 0;
std::int64_t last_tx_report_us = 0;
static Impl* active;
static std::mutex callback_mutex;
explicit Impl(C5RadioConfig c) : config(c) {}
static void receive(void* buffer, wifi_promiscuous_pkt_type_t type) {
if (!buffer || type != WIFI_PKT_DATA) return;
// Like the OTM receiver (cmd_sniffer.c wifi_sniffer_cb): no MISC frames, only rx_state 0.
if (!buffer || type == WIFI_PKT_MISC) return;
const auto* packet = static_cast<const wifi_promiscuous_pkt_t*>(buffer);
if (packet->rx_ctrl.rx_state != 0) return;
const auto length = packet->rx_ctrl.sig_len;
std::lock_guard<std::mutex> lock(callback_mutex);
if (!active || !active->queue) return;
// MicrOBU: a frame too short to hold any GN packet is not ITS traffic, so it is ignored
// rather than counted; dropped_frames() then means what the phone shows it as: lost frames.
if (length < 38) return;
if (length > sizeof(Raw::bytes)) { ++active->dropped; return; }
const auto mode = active->capture_mode.load();
bool stack = type == WIFI_PKT_DATA;
// MicrOBU: a frame too short to hold any GN packet is not ITS traffic, so it is ignored rather
// than counted; dropped_frames() then means what the phone shows it as: lost frames.
if (stack && length < 38) stack = false;
else if (stack && length > sizeof(Raw::bytes)) { ++active->dropped; stack = false; }
#if CONFIG_SOC_WIFI_HE_SUPPORT
std::uint16_t capture_length = packet->rx_ctrl.dump_len; // MPDU without FCS (OTM: HE chips)
#else
std::uint16_t capture_length = length > 4 ? length - 4 : 0;
#endif
if (!(mode & capture_on) || capture_length > sizeof(Raw::bytes)) capture_length = 0;
if (capture_length && (mode & capture_broadcast_only) &&
(capture_length < 4 + 6 || std::memcmp(&packet->payload[4], "\xFF\xFF\xFF\xFF\xFF\xFF", 6) != 0)) {
capture_length = 0; // OTM only_capture_broadcast: address 1 must be the broadcast address
}
if (!stack && !capture_length) return;
// MicrOBU: static, not a local. Raw is ~2.4 KB and this runs on the Wi-Fi driver's own task,
// several frames deep, on a stack of roughly 3.5 KB: the previous firmware hit exactly this
// with an 800-byte buffer (obu-firmware commit 04b0076). Safe as a static because only that
// one task calls this, and xQueueSend copies it out before the next call.
// several frames deep, on a stack of roughly 3.5 KB (the previous firmware hit exactly this
// with an 800-byte buffer, commit 04b0076). Safe as a static because only that one task calls
// this, and xQueueSend copies it out before the next call.
static Raw raw;
raw.length = length;
raw.capture_length = capture_length;
raw.for_stack = stack;
raw.rssi = packet->rx_ctrl.rssi;
raw.timestamp = packet->rx_ctrl.timestamp;
std::memcpy(raw.bytes, packet->payload, length);
std::memcpy(raw.bytes, packet->payload, std::min<std::size_t>(std::max<std::size_t>(length, capture_length), sizeof(Raw::bytes)));
if (xQueueSend(active->queue, &raw, 0) != pdTRUE) ++active->dropped;
}
};
C5Radio::Impl* C5Radio::Impl::active = nullptr;
std::mutex C5Radio::Impl::callback_mutex;
StaticQueue_t C5Radio::Impl::rx_control;
alignas(portBYTE_ALIGNMENT) std::uint8_t C5Radio::Impl::rx_storage[reserved_rx_frames * sizeof(Raw)];
namespace {
// A transmitting radio only on a declared operating point (channel and power cap, power
// in the driver's 0.25 dB steps); a receive-only radio on any ITS-G5 carrier. The laboratory test
// burst (transmit_burst) retunes past this on purpose.
bool valid_config(const C5RadioConfig& c) {
const bool point = c.laboratory_transmission
? radio_policy::operating_point_allowed(c.channel_number, c.transmit_power_dbm)
: radio_policy::receive_channel_allowed(c.channel_number) && std::isfinite(c.transmit_power_dbm);
return point && c.receive_queue_length > 0 && c.receive_queue_length <= 32;
}
// 10 MHz channel bandwidth (ITS-G5 / 802.11p) on the channel, and the hardware CCA counters for DCC
// (40 MHz baseband clock timebase) armed.
void tune_its_g5_phy(unsigned channel_number) {
phy_11p_set(1, 0);
phy_change_channel(5000 + 5 * channel_number, 1, 0, 0); // channel 180 = 5900 MHz
phy_enable_cca();
phy_set_cca_cnt(0x07FFFFFF, true);
}
} // namespace
C5Radio::C5Radio(C5RadioConfig c) : impl_(std::make_unique<Impl>(c)) {}
C5Radio::~C5Radio() { stop(); }
@@ -103,18 +168,14 @@ esp_err_t C5Radio::start() {
auto& p = *impl_;
const auto& c = p.config;
if (p.initialized) return ESP_ERR_INVALID_STATE;
// Reject channel/power/queue config outside the supported ITS-G5 range
if (c.channel_number < 172 || c.channel_number > 184 || c.channel_number % 2 ||
!std::isfinite(c.transmit_power_dbm) || c.transmit_power_dbm < 2 || c.transmit_power_dbm > 23 ||
std::floor(c.transmit_power_dbm * 4) != c.transmit_power_dbm * 4 ||
c.receive_queue_length == 0 || c.receive_queue_length > 32) {
return ESP_ERR_INVALID_ARG;
}
if (!valid_config(c)) return ESP_ERR_INVALID_ARG;
{
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
if (Impl::active) return ESP_ERR_INVALID_STATE;
p.queue = xQueueCreate(c.receive_queue_length, sizeof(Impl::Raw));
p.queue = c.receive_queue_length <= Impl::reserved_rx_frames
? xQueueCreateStatic(c.receive_queue_length, sizeof(Impl::Raw), Impl::rx_storage, &Impl::rx_control)
: xQueueCreate(c.receive_queue_length, sizeof(Impl::Raw));
if (!p.queue) return ESP_ERR_NO_MEM;
Impl::active = &p;
}
@@ -152,9 +213,8 @@ esp_err_t C5Radio::start() {
// MicrOBU, from the previous firmware: under the default WIFI_COUNTRY_POLICY_AUTO the driver's
// 5 GHz table does not authorise transmission on the ITS band, which there left RX working and
// TX silent. The colleague's board transmits without this (esp_wifi_80211_tx_custom goes around
// that gate), so it is belt and braces here: manual policy, every 5 GHz channel enabled. Not
// fatal if refused.
// TX silent. The raw TX path goes around that gate, so this is belt and braces: manual policy,
// every 5 GHz channel enabled. Not fatal if refused.
wifi_country_t country = {};
country.cc[0] = 'U'; country.cc[1] = 'S';
country.schan = 1;
@@ -171,20 +231,15 @@ esp_err_t C5Radio::start() {
filter.filter_mask = WIFI_PROMIS_FILTER_MASK_DATA;
attempt(esp_wifi_set_promiscuous_filter(&filter));
attempt(esp_wifi_set_promiscuous_rx_cb(Impl::receive));
tx_completed = 0;
tx_completion_failed = 0;
attempt(esp_wifi_register_80211_tx_cb(tx_done));
attempt(esp_wifi_set_promiscuous(true));
if (result != ESP_OK) {
stop();
return result;
}
// 10 MHz channel bandwidth (ITS-G5 / 802.11p)
phy_11p_set(1, 0);
phy_change_channel(5000 + 5 * c.channel_number, 1, 0, 0); // = 5900 MHz
// Enable and arm hardware CCA counters (40 MHz baseband clock timebase) for DCC
phy_enable_cca();
phy_set_cca_cnt(0x07FFFFFF, true);
// MicrOBU, from the previous firmware: the power request is a ceiling, not a promise. The driver
// clamps it to its calibrated table, and 5900 MHz is above the chip's rated range, so log what
// the driver admits to rather than what was asked for.
@@ -194,8 +249,11 @@ esp_err_t C5Radio::start() {
power_q, power_q / 4, (power_q % 4) * 25, c.transmit_power_dbm);
}
ESP_LOGI(TAG, "ITS-G5 802.11p radio started on channel %u (5900 MHz), %s",
unsigned(c.channel_number), c.laboratory_transmission ? "TX/RX" : "RX only");
tune_its_g5_phy(c.channel_number);
arm_cca_counters(); // the DCC LCBR source (Station::sample_dcc_channel_load); off until armed
ESP_LOGI(TAG, "ITS-G5 802.11p radio started on channel %u (%u MHz) at %.2f dBm, %s",
unsigned(c.channel_number), 5000u + 5u * c.channel_number, c.transmit_power_dbm,
c.laboratory_transmission ? "TX/RX" : "RX only");
return ESP_OK;
}
@@ -203,6 +261,7 @@ void C5Radio::stop() {
if (!impl_) return;
auto& p = *impl_;
if (p.started) esp_wifi_set_promiscuous(false);
if (p.initialized) esp_wifi_register_80211_tx_cb(nullptr);
{
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
if (Impl::active == &p) Impl::active = nullptr;
@@ -217,15 +276,15 @@ void C5Radio::stop() {
p.started = p.initialized = p.own_event_loop = false;
}
vanetza_idf::Result C5Radio::request(vanetza_idf::AlDataRequest request) {
microbu_v2x::Result C5Radio::request(microbu_v2x::AlDataRequest request) {
auto& p = *impl_;
if (!p.started) return vanetza_idf::Result::rejected;
if (!p.config.laboratory_transmission) return vanetza_idf::Result::unsupported;
if (!p.started) return microbu_v2x::Result::rejected;
if (!p.config.laboratory_transmission) return microbu_v2x::Result::unsupported;
if (request.bandwidth_mhz != 10 || request.channel_number != p.config.channel_number ||
request.transceiver_id != 0 || request.transceiver_mode || request.datastream_id ||
request.transmit_power_dbm != p.config.transmit_power_dbm) {
return vanetza_idf::Result::unsupported;
return microbu_v2x::Result::unsupported;
}
constexpr wifi_phy_rate_t rates[] = {
@@ -234,11 +293,11 @@ vanetza_idf::Result C5Radio::request(vanetza_idf::AlDataRequest request) {
WIFI_PHY_RATE_48M, WIFI_PHY_RATE_54M
};
const auto index = static_cast<unsigned>(request.mcs);
if (index >= std::size(rates)) return vanetza_idf::Result::invalid_argument;
if (index >= std::size(rates)) return microbu_v2x::Result::invalid_argument;
vanetza::ByteBuffer bytes;
const auto encoded = vanetza_idf::its_g5::encode_frame(request, p.sequence, bytes);
if (encoded != vanetza_idf::Result::accepted) {
const auto encoded = microbu_v2x::its_g5::encode_frame(request, p.sequence, bytes);
if (encoded != microbu_v2x::Result::accepted) {
ESP_LOGE(TAG, "encode_frame failed: %d", int(encoded));
return encoded;
}
@@ -248,201 +307,96 @@ vanetza_idf::Result C5Radio::request(vanetza_idf::AlDataRequest request) {
rate.phymode = WIFI_PHY_MODE_11A;
rate.rate = rates[index];
// Transmit frame via 802.11p driver
const auto result = esp_wifi_80211_tx_custom(
// Transmit frame via 802.11p driver. ESP_ERR_NO_MEM means the driver's TX buffers are momentarily all in use
// (frames waiting for the shared radio, e.g. a BLE connection event); the frame is still well inside its
// lifetime, so it is offered again after a tick, at most twice (2026-09-29: 1 of 470 BLE-path VAMs lost).
auto result = esp_wifi_80211_tx_custom(
WIFI_IF_STA, bytes.data(), bytes.size(), false,
&rate, WIFI_BAND_5G, WIFI_BW20);
if (result == ESP_ERR_NO_MEM) ++p.no_mem;
for (int retry = 0; result == ESP_ERR_NO_MEM && retry < 2; ++retry) {
vTaskDelay(std::max<TickType_t>(1, pdMS_TO_TICKS(2)));
result = esp_wifi_80211_tx_custom(WIFI_IF_STA, bytes.data(), bytes.size(), false, &rate, WIFI_BAND_5G, WIFI_BW20);
if (result == ESP_ERR_NO_MEM) ++p.no_mem;
}
if (result == ESP_OK) ++p.submitted;
if (result != ESP_OK) {
ESP_LOGW(TAG, "esp_wifi_80211_tx_custom failed: %s (0x%x)", esp_err_to_name(result), result);
} else if ((p.capture_mode.load() & (capture_on | capture_own_tx)) == (capture_on | capture_own_tx) && p.transmitted) {
p.transmitted(bytes.data(), bytes.size());
}
return result == ESP_OK ? vanetza_idf::Result::accepted :
result == ESP_ERR_NO_MEM ? vanetza_idf::Result::resource_limit :
vanetza_idf::Result::rejected;
return result == ESP_OK ? microbu_v2x::Result::accepted :
result == ESP_ERR_NO_MEM ? microbu_v2x::Result::resource_limit :
microbu_v2x::Result::rejected;
}
void C5Radio::poll(const Receive& receive, const Capture& capture) {
void C5Radio::poll(const Receive& receive, const Capture& capture, const Forward& forward) {
auto& p = *impl_;
if (!p.queue) return;
const auto now_us = esp_timer_get_time();
if (p.submitted && now_us - p.last_tx_report_us >= 1000000) {
ESP_LOGI(TAG, "TX observation: submitted=%u completed=%u completion_failed=%u no_mem=%u",
unsigned(p.submitted), unsigned(tx_completed.load()),
unsigned(tx_completion_failed.load()), unsigned(p.no_mem));
p.last_tx_report_us = now_us;
}
Impl::Raw raw {};
for (unsigned i = 0; i < p.config.receive_queue_length && xQueueReceive(p.queue, &raw, 0) == pdTRUE; ++i) {
if (capture) {
capture(vanetza::ByteBuffer(raw.bytes, raw.bytes + raw.length), raw.rssi, raw.timestamp);
if (raw.for_stack && forward) forward(vanetza::ByteBuffer(raw.bytes, raw.bytes + raw.length), raw.rssi);
if (raw.for_stack && receive) {
microbu_v2x::AlDataIndication ind;
if (microbu_v2x::its_g5::decode_frame(raw.bytes, raw.length, true, ind) == microbu_v2x::Result::accepted) {
ind.channel_number = p.config.channel_number;
ind.received_power_dbm = raw.rssi;
receive(std::move(ind));
}
}
vanetza_idf::AlDataIndication ind;
if (vanetza_idf::its_g5::decode_frame(raw.bytes, raw.length, true, ind) != vanetza_idf::Result::accepted) {
continue;
// The raw tap uses the same queued frame and runs after normal delivery.
if (capture && raw.capture_length) {
capture(vanetza::ByteBuffer(raw.bytes, raw.bytes + raw.capture_length), raw.rssi, raw.timestamp);
}
ind.channel_number = p.config.channel_number;
ind.received_power_dbm = raw.rssi;
if (receive) receive(std::move(ind));
}
}
void C5Radio::set_capture(std::uint8_t mode) {
auto& p = *impl_;
p.capture_mode.store(mode);
if (!p.started) return;
wifi_promiscuous_filter_t filter {};
// OTM receiver default: WIFI_PROMIS_FILTER_MASK_ALL without FCSFAIL; the stack alone needs data frames.
filter.filter_mask = (mode & capture_on) ? (WIFI_PROMIS_FILTER_MASK_ALL & ~WIFI_PROMIS_FILTER_MASK_FCSFAIL)
: WIFI_PROMIS_FILTER_MASK_DATA;
esp_wifi_set_promiscuous_filter(&filter);
ESP_LOGI(TAG, "raw capture %s (mode 0x%02x)", (mode & capture_on) ? "on" : "off", unsigned(mode));
}
void C5Radio::on_transmitted(Transmitted tap) {
impl_->transmitted = std::move(tap);
}
std::uint32_t C5Radio::dropped_frames() const {
return impl_->dropped.load();
}
#if CONFIG_MICROBU_TEST_CHANNEL
esp_err_t C5Radio::transmit_burst(std::uint16_t channel, double power_dbm, unsigned mcs,
unsigned count, unsigned interval_ms, std::size_t payload_len) {
auto& p = *impl_;
if (!p.started) return ESP_ERR_INVALID_STATE;
if (channel < 172 || channel > 184 || channel % 2 != 0) return ESP_ERR_INVALID_ARG;
if (power_dbm < 2.0 || power_dbm > 20.0) return ESP_ERR_INVALID_ARG;
if (mcs > 7) return ESP_ERR_INVALID_ARG;
if (count == 0) return ESP_OK;
constexpr wifi_phy_rate_t rates[] = {
WIFI_PHY_RATE_6M, WIFI_PHY_RATE_9M, WIFI_PHY_RATE_12M,
WIFI_PHY_RATE_18M, WIFI_PHY_RATE_24M, WIFI_PHY_RATE_36M,
WIFI_PHY_RATE_48M, WIFI_PHY_RATE_54M
};
// Dynamically retune channel or adjust TX power if different from running config
if (channel != p.config.channel_number) {
phy_11p_set(1, 0);
phy_change_channel(5000 + 5 * channel, 1, 0, 0);
p.config.channel_number = channel;
}
const auto power_quarter_db = static_cast<std::int8_t>(std::round(power_dbm * 4.0)); // esp_wifi power is in 0.25 dBm units
esp_wifi_set_max_tx_power(power_quarter_db);
p.config.transmit_power_dbm = power_dbm;
wifi_tx_rate_config_t rate {};
rate.phymode = WIFI_PHY_MODE_11A;
rate.rate = rates[mcs];
// Assemble a standard IEEE 802.11 QoS data / LLC frame (EtherType 0x8947 GeoNetworking)
// Header: Frame Control (0x0088 QoS Data), Duration (0x0000), Addr1 (Broadcast FF..FF),
// Addr2 (Source 02:00:00:00:00:01), Addr3 (BSSID FF..FF), Sequence, QoS Control (0x0000),
// LLC/SNAP header (AA AA 03 00 00 00 89 47).
std::vector<std::uint8_t> frame;
const std::size_t actual_payload = std::clamp<std::size_t>(payload_len, 32, 1400);
frame.reserve(34 + actual_payload);
// MAC Header (26 bytes with QoS)
frame.push_back(0x88); frame.push_back(0x00); // Frame Control: QoS Data
frame.push_back(0x00); frame.push_back(0x00); // Duration
for (int i = 0; i < 6; ++i) frame.push_back(0xFF); // RA / Destination: Broadcast
frame.push_back(0x02); frame.push_back(0x00); frame.push_back(0x00);
frame.push_back(0x00); frame.push_back(0x00); frame.push_back(0x01); // TA / Source
for (int i = 0; i < 6; ++i) frame.push_back(0xFF); // BSSID: Broadcast
frame.push_back(0x00); frame.push_back(0x00); // Sequence (updated per frame)
frame.push_back(0x00); frame.push_back(0x00); // QoS Control
// LLC/SNAP header (8 bytes)
frame.push_back(0xAA); frame.push_back(0xAA); frame.push_back(0x03);
frame.push_back(0x00); frame.push_back(0x00); frame.push_back(0x00);
frame.push_back(0x89); frame.push_back(0x47); // EtherType 0x8947 (GeoNetworking)
// Test payload with identifiable sequence numbers
const std::size_t header_len = frame.size();
frame.resize(header_len + actual_payload, 0x5A);
esp_err_t last_err = ESP_OK;
for (unsigned i = 0; i < count; ++i) {
p.sequence = (p.sequence + 1) & 4095;
frame[22] = static_cast<std::uint8_t>((p.sequence << 4) & 0xF0);
frame[23] = static_cast<std::uint8_t>((p.sequence >> 4) & 0xFF);
// Put burst counter inside payload
frame[header_len + 0] = static_cast<std::uint8_t>(i & 0xFF);
frame[header_len + 1] = static_cast<std::uint8_t>((i >> 8) & 0xFF);
esp_err_t err = esp_wifi_80211_tx_custom(
WIFI_IF_STA, frame.data(), frame.size(), false,
&rate, WIFI_BAND_5G, WIFI_BW20);
if (err == ESP_ERR_NO_MEM) {
// Buffer briefly full: yield task to allow DMA descriptors to clear
vTaskDelay(pdMS_TO_TICKS(2));
err = esp_wifi_80211_tx_custom(
WIFI_IF_STA, frame.data(), frame.size(), false,
&rate, WIFI_BAND_5G, WIFI_BW20);
}
if (err != ESP_OK) {
last_err = err;
}
const auto delay_ms = std::max<unsigned>(interval_ms, 2);
if (i + 1 < count) {
vTaskDelay(pdMS_TO_TICKS(delay_ms));
}
}
return last_err;
}
CcaSampleResult C5Radio::sample_cca(unsigned duration_ms) {
CcaSampleResult result;
auto& p = *impl_;
if (!p.started) return result;
result.noise_floor_dbm = phy_get_noise_floor();
// Enable CCA hardware and arm the 27-bit cycle counters with full window (0x07FFFFFF).
phy_enable_cca();
// The CCA cycle counters count one window of up to 2^27 cycles (3.36 s at 40 MHz) after an enable edge on bits
// [28:27] of 0x600a7c58, then latch bit 27 ("done") and stop; a board whose window has completed reads constant
// counters (2026-09-29: total 0, status 1). Arming therefore always clears the enable bits first.
void arm_cca_counters() {
phy_enable_cca(); // required: without it the counters stay at zero (2026-09-29, COM21)
phy_set_cca_cnt(0, false);
phy_set_cca_cnt(0x07FFFFFF, true);
std::int32_t cca_cnt_before[2] = {};
phy_get_cca_cnt(cca_cnt_before);
const auto t_start = esp_timer_get_time();
const auto t_deadline = t_start + static_cast<std::int64_t>(duration_ms) * 1000;
std::int64_t last_t = t_start;
result.min_delta_us = std::numeric_limits<std::uint32_t>::max();
while (esp_timer_get_time() < t_deadline) {
std::int32_t cur_cnt[2] = {};
const auto status = phy_get_cca_cnt(cur_cnt);
const auto cca_threshold = phy_get_cca();
const auto now = esp_timer_get_time();
if (result.samples == 0) {
result.first_cca = cca_threshold;
} else {
const auto delta = static_cast<std::uint32_t>(now - last_t);
result.min_delta_us = std::min(result.min_delta_us, delta);
result.max_delta_us = std::max(result.max_delta_us, delta);
}
last_t = now;
result.last_cca = cca_threshold;
if (status) ++result.busy_count;
++result.samples;
// Cooperative yielding: prevent starving IDLE task, esp_timer, and bb_wdt
// on the single-core C5 during multi-millisecond polling windows.
if ((result.samples & 0x3F) == 0) {
taskYIELD();
}
}
result.duration_us = static_cast<std::uint32_t>(esp_timer_get_time() - t_start);
std::int32_t cca_cnt_after[2] = {};
result.cca_status = phy_get_cca_cnt(cca_cnt_after);
// Both words are 27-bit hardware counters (mask 0x07FFFFFF).
constexpr std::int32_t mask27 = 0x07FFFFFF;
auto delta27 = [](std::int32_t after, std::int32_t before) -> std::int32_t {
std::int32_t diff = (after & mask27) - (before & mask27);
if (diff < 0) diff += (mask27 + 1);
return diff;
};
result.cca_total_cycles_delta = delta27(cca_cnt_after[0], cca_cnt_before[0]);
result.cca_busy_cycles_delta = delta27(cca_cnt_after[1], cca_cnt_before[1]);
if (result.samples < 2) result.min_delta_us = 0;
return result;
}
#endif // CONFIG_MICROBU_TEST_CHANNEL
CcaCounters C5Radio::read_cca_counters() const {
CcaCounters c;
std::int32_t out[2] = {};
phy_get_cca_cnt(out);
if (phy_get_cca_cnt(out)) { // window complete: restart it; the caller takes the next reading as a baseline
arm_cca_counters();
c.restarted = true;
}
constexpr std::int32_t mask27 = 0x07FFFFFF; // remomve the busy/status bit (bit 27) from the 27-bit hardware counters
c.total_cycles = static_cast<std::uint32_t>(out[0] & mask27);
c.busy_cycles = static_cast<std::uint32_t>(out[1] & mask27);
@@ -450,18 +404,8 @@ CcaCounters C5Radio::read_cca_counters() const {
}
double C5Radio::calculate_cbr(const CcaCounters& current, const CcaCounters& previous) {
constexpr std::uint32_t counter_range = 1u << 27;
auto delta27 = [](std::uint32_t after, std::uint32_t before) -> std::uint32_t {
if (after >= before) {
return after - before;
}
// Counter wrapped from 2^27 - 1 back to zero.
return after + counter_range - before;
};
const std::uint32_t dt = delta27(current.total_cycles, previous.total_cycles);
const std::uint32_t db = delta27(current.busy_cycles, previous.busy_cycles);
const std::uint32_t dt = cca::delta27(current.total_cycles, previous.total_cycles);
const std::uint32_t db = cca::delta27(current.busy_cycles, previous.busy_cycles);
if (dt == 0) return 0.0;
return static_cast<double>(db) / static_cast<double>(dt);
}
+27 -41
View File
@@ -1,5 +1,5 @@
#pragma once
#include <vanetza_idf/access.hpp>
#include <microbu_v2x/access.hpp>
#include <esp_err.h>
#include <functional>
#include <memory>
@@ -13,24 +13,6 @@ struct C5RadioConfig {
bool laboratory_transmission = true;
};
#if CONFIG_MICROBU_TEST_CHANNEL
/// Result of polling the PHY's own (undocumented) CCA state as fast as possible for a
/// fixed window (feasibility probe for EN 303 797 clause 4.6.2)
/// to determine if the platform can observe channel-busy state at >=1 kHz at all.
struct CcaSampleResult {
std::uint32_t samples = 0;
std::uint32_t duration_us = 0;
std::uint32_t min_delta_us = 0;
std::uint32_t max_delta_us = 0;
std::uint32_t busy_count = 0;
std::int32_t first_cca = 0;
std::int32_t last_cca = 0;
std::int32_t noise_floor_dbm = 0;
std::int32_t cca_total_cycles_delta = 0; // out[0]/0x600a7c5c: 40 MHz free-running counter
std::int32_t cca_busy_cycles_delta = 0; // out[1]/0x600a7c60: increments while channel busy
std::int32_t cca_status = 0;
};
#endif
/// Snapshot of the ESP32-C5 27-bit hardware PHY counters for ETSI TS 102 687 / EN 303 797 DCC.
/// total_cycles: 40 MHz FE clock cycles (register 0x600a7c5c[26:0]).
@@ -38,6 +20,9 @@ struct CcaSampleResult {
struct CcaCounters {
std::uint32_t total_cycles = 0;
std::uint32_t busy_cycles = 0;
/// The counter window had completed (bit 27) and was re-armed by this read: the next reading starts a new
/// baseline, this one closes no valid window.
bool restarted = false;
};
/**
@@ -45,10 +30,20 @@ struct CcaCounters {
* Direct Wi-Fi promiscuous RX mode on 5.9 GHz (ITS-G5 Channel 180, 10 MHz BW)
* and 802.11p frame transmission via esp_wifi_80211_tx_custom.
*/
class C5Radio final : public vanetza_idf::Access {
class C5Radio final : public microbu_v2x::Access {
public:
using Receive = std::function<void(vanetza_idf::AlDataIndication)>;
using Receive = std::function<void(microbu_v2x::AlDataIndication)>;
/// Raw frame tap: MPDU bytes without FCS, RSSI (dBm) and the local receive time in microseconds.
using Capture = std::function<void(const vanetza::ByteBuffer&, int, std::uint32_t)>;
/// MicrOBU: every received 802.11 data frame (FCS included) and its RSSI, before the stack sees it.
using Forward = std::function<void(const vanetza::ByteBuffer&, int)>;
/// Transmit tap: the exact 802.11 frame handed to the driver.
using Transmitted = std::function<void(const std::uint8_t*, std::size_t)>;
/// Raw capture mode bits (RAW_CAPTURE, ../../docs/station-link.tex).
static constexpr std::uint8_t capture_on = 0x01; ///< every valid frame, like the OTM receiver
static constexpr std::uint8_t capture_broadcast_only = 0x02; ///< OTM's broadcast filter (address 1 = FF..FF)
static constexpr std::uint8_t capture_own_tx = 0x04; ///< also the frames this radio transmits
/// @brief Constructs a radio adapter with the given configuration (not yet started).
/// @param config Radio configuration; defaults to channel 180, 10 dBm, 16-deep RX queue.
@@ -64,35 +59,26 @@ public:
/// @brief Stops the radio and releases all resources.
void stop();
// vanetza_idf::Access
// microbu_v2x::Access
/// @brief Encodes and transmits an ITS-G5 frame requested by the access layer.
/// @param request Frame and transmit parameters from the access layer.
/// @return Result of the transmit attempt.
vanetza_idf::Result request(vanetza_idf::AlDataRequest request) override;
microbu_v2x::Result request(microbu_v2x::AlDataRequest request) override;
/// @brief Dispatches queued received frames to the owning task callback.
/// @param receive Invoked once per queued frame with its decoded indication.
/// @param capture Optional; invoked with the raw frame bytes, RSSI and timestamp for diagnostics.
void poll(const Receive& receive, const Capture& capture = {});
/// @param forward Optional MicrOBU tap: called for every data frame, independent of `receive`.
void poll(const Receive& receive, const Capture& capture = {}, const Forward& forward = {});
#if CONFIG_MICROBU_TEST_CHANNEL
/// @brief Sends a burst of raw 802.11p test frames for RF characterization.
/// @param channel ITS-G5 channel number to transmit on.
/// @param power_dbm Transmit power in dBm.
/// @param mcs 802.11p modulation and coding scheme index.
/// @param count Number of frames to send.
/// @param interval_ms Interval between frames in milliseconds.
/// @param payload_len Length of each frame's payload in bytes.
/// @return ESP_OK if all frames were sent, otherwise the last transmit error.
esp_err_t transmit_burst(std::uint16_t channel, double power_dbm, unsigned mcs,
unsigned count, unsigned interval_ms, std::size_t payload_len);
/// @brief Switches the raw capture tap. While on, the promiscuous filter admits every frame class
/// except bad FCS (as the OpenTrafficMap receiver firmware does); only data frames reach the stack.
/// @param mode Combination of capture_on, capture_broadcast_only and capture_own_tx (0 = off).
void set_capture(std::uint8_t mode);
/// @brief Registers the tap invoked for every successfully submitted frame while capture_own_tx is set.
void on_transmitted(Transmitted tap);
/// @brief Polls the CCA state as fast as possible for a fixed window (see CcaSampleResult); requires start().
/// @note This is a diagnostic tool/ feasibility probe for EN 303 797 clause 4.6.2 to determine if the platform can observe channel-busy state at >=1 kHz at all.
/// @param duration_ms Duration of the sampling window in milliseconds.
/// @return Sampling statistics and counter deltas over the window.
CcaSampleResult sample_cca(unsigned duration_ms);
#endif
/// @brief Non-blocking read of the hardware CCA counters for periodic DCC evaluation.
/// Continuous 40 MHz hardware integration satisfies EN 303 797 Profile-1 (>=1 kHz) with zero CPU busy-wait.
-146
View File
@@ -1,146 +0,0 @@
// NOT COMPILED - deliberately absent from main/CMakeLists.txt's SRCS. This firmware no longer
// encodes CAM at all: the phone builds and UPER-encodes it and sends the bytes down serial_link,
// and this side only GeoNetworking-wraps opaque payloads. The file is kept as the byte-exact
// reference the Kotlin encoder (app CamUperCodec.kt) was ported from, so fixes must be applied
// here too or the next person porting from it reintroduces the bug.
#include "cam.h"
#include <string.h>
// MSB-first bit packer - identical approach to denm.c (ASN.1 UPER is a
// bitstream, not a byte stream).
typedef struct {
uint8_t *buf;
size_t buf_len;
size_t bit_pos;
} bitwriter_t;
static void bw_init(bitwriter_t *bw, uint8_t *buf, size_t len)
{
bw->buf = buf;
bw->buf_len = len;
bw->bit_pos = 0;
memset(buf, 0, len);
}
static void bw_put_bits(bitwriter_t *bw, uint64_t value, int nbits)
{
for (int i = nbits - 1; i >= 0; i--) {
size_t byte_idx = bw->bit_pos / 8;
int bit_idx = 7 - (int)(bw->bit_pos % 8);
if (byte_idx >= bw->buf_len) {
return; // overflow guard - check return value of cam_encode
}
uint8_t bit = (value >> i) & 1;
bw->buf[byte_idx] = (uint8_t)(bw->buf[byte_idx] | (bit << bit_idx));
bw->bit_pos++;
}
}
static size_t bw_byte_len(const bitwriter_t *bw)
{
return (bw->bit_pos + 7) / 8;
}
int cam_encode(const cam_fields_t *f, uint8_t *buf, size_t buf_len)
{
bitwriter_t bw;
bw_init(&bw, buf, buf_len);
// ---- ItsPduHeader ---- (SEQUENCE, no OPTIONALs, no "..." -> no preamble)
bw_put_bits(&bw, 2, 8); // protocolVersion INTEGER(0..255) = 2
bw_put_bits(&bw, 2, 8); // messageID INTEGER(0..255) = cam(2)
bw_put_bits(&bw, f->station_id, 32); // stationID StationID INTEGER(0..4294967295)
// ---- CoopAwareness ---- (SEQUENCE, no OPTIONALs, no "...")
// generationDeltaTime GenerationDeltaTime INTEGER(0..65535) -> 16 bits
bw_put_bits(&bw, f->generation_delta_time, 16);
// ---- CamParameters ---- (SEQUENCE, EXTENSIBLE "...", 2 OPTIONALs:
// lowFrequencyContainer, specialVehicleContainer)
bw_put_bits(&bw, 0, 1); // extension bit: no extension additions
bw_put_bits(&bw, 1, 1); // lowFrequencyContainer present
bw_put_bits(&bw, 0, 1); // specialVehicleContainer absent
// ---- BasicContainer ---- (SEQUENCE, EXTENSIBLE "...", no OPTIONALs)
bw_put_bits(&bw, 0, 1); // extension bit: none
bw_put_bits(&bw, f->station_type, 8); // stationType StationType INTEGER(0..255)
// ReferencePosition (SEQUENCE, no OPTIONALs/"..."), identical widths to
// DENM eventPosition (see denm.c for the constraint derivations):
// Latitude INTEGER(-900000000..900000001) -> 31 bits, offset from -900000000
uint32_t lat_offset = (uint32_t)((int64_t)f->latitude_tenmicrodeg - (-900000000));
bw_put_bits(&bw, lat_offset, 31);
// Longitude INTEGER(-1800000000..1800000001) -> 32 bits, offset from -1800000000
uint32_t lon_offset = (uint32_t)((int64_t)f->longitude_tenmicrodeg - (-1800000000));
bw_put_bits(&bw, lon_offset, 32);
// PosConfidenceEllipse: SemiAxisLength(0..4095)->12, HeadingValue(0..3601)->12
bw_put_bits(&bw, 4095, 12); // semiMajorConfidence: unavailable
bw_put_bits(&bw, 4095, 12); // semiMinorConfidence: unavailable
bw_put_bits(&bw, 3601, 12); // semiMajorOrientation: unavailable
// Altitude: AltitudeValue(-100000..800001)->20 (offset from -100000),
// AltitudeConfidence ENUM 16 values -> 4 bits
bw_put_bits(&bw, 900001, 20); // 800001 ("unavailable") - (-100000) = 900001
bw_put_bits(&bw, 15, 4); // altitudeConfidence: unavailable(15)
// ---- HighFrequencyContainer ---- CHOICE { basicVehicleContainerHighFrequency,
// rsuContainerHighFrequency, ... } - EXTENSIBLE, 2 root alternatives.
bw_put_bits(&bw, 0, 1); // CHOICE extension bit: value is in root
bw_put_bits(&bw, 0, 1); // index: 0 = basicVehicleContainerHighFrequency (1 bit for 2 alts)
// BasicVehicleContainerHighFrequency (SEQUENCE, NOT extensible, 7 OPTIONALs
// accelerationControl..cenDsrcTollingZone - all absent).
bw_put_bits(&bw, 0, 7); // 7 optional-presence bits, all absent
// Heading: HeadingValue(0..3601)->12, HeadingConfidence(1..127)->7 (offset from 1)
bw_put_bits(&bw, f->heading_ddeg, 12);
bw_put_bits(&bw, 127 - 1, 7); // headingConfidence: unavailable(127)
// Speed: SpeedValue(0..16383)->14, SpeedConfidence(1..127)->7 (offset from 1)
bw_put_bits(&bw, f->speed_cm_s, 14);
bw_put_bits(&bw, 127 - 1, 7); // speedConfidence: unavailable(127)
// DriveDirection ENUM {forward,backward,unavailable} -> 2 bits
bw_put_bits(&bw, 2, 2); // unavailable
// VehicleLength: VehicleLengthValue(1..1023)->10 (offset from 1),
// VehicleLengthConfidenceIndication ENUM 5 values -> 3 bits
bw_put_bits(&bw, (uint32_t)f->vehicle_length_dm - 1, 10);
bw_put_bits(&bw, 4, 3); // vehicleLengthConfidenceIndication: unavailable(4)
// VehicleWidth INTEGER(1..62) -> 6 bits (offset from 1)
bw_put_bits(&bw, (uint32_t)f->vehicle_width_dm - 1, 6);
// LongitudinalAcceleration: value(-160..161)->9 (offset from -160),
// AccelerationConfidence(0..102)->7
bw_put_bits(&bw, 161 - (uint32_t)(-160), 9); // longitudinalAccelerationValue: unavailable(161)
bw_put_bits(&bw, 102, 7); // confidence: unavailable(102)
// Curvature: CurvatureValue(-1023..1023)->11 (offset from -1023),
// CurvatureConfidence ENUM 8 values -> 3 bits
bw_put_bits(&bw, 1023 - (uint32_t)(-1023), 11); // curvatureValue: unavailable(1023)
bw_put_bits(&bw, 7, 3); // curvatureConfidence: unavailable(7)
// CurvatureCalculationMode ENUM {yawRateUsed,yawRateNotUsed,unavailable, ...} - note the
// extension marker: UPER encodes an extensible ENUMERATED as an extension bit followed by
// the root-list index, so this is 1 + 2 = 3 bits, NOT 2. This file previously wrote only the
// 2-bit index, which shifted yawRate and the entire low-frequency container one bit early for
// any standards-compliant receiver. Harmless between this project's own encoder and decoder
// (both had the same error); wrong against every third-party station.
bw_put_bits(&bw, 0, 1); // extension bit: value is in the root list
bw_put_bits(&bw, 2, 2); // unavailable(2)
// YawRate: YawRateValue(-32766..32767)->16 (offset from -32766),
// YawRateConfidence ENUM with NINE values, degSec-000-01(0) .. unavailable(8)
// (cdd_1_3_1_1.asn) -> 4 bits. This wrote 3 bits with value 7, one bit short and the
// wrong symbol (7 is outOfRange), so every field after it shifted for any
// standards-compliant receiver. The app's CamUperCodec.kt fixed the same line on
// 2026-08-20; this reference copy was missed until 2026-09-11.
bw_put_bits(&bw, 32767 - (uint32_t)(-32766), 16); // yawRateValue: unavailable(32767)
bw_put_bits(&bw, 8, 4); // yawRateConfidence: unavailable(8)
// ---- LowFrequencyContainer ---- CHOICE { basicVehicleContainerLowFrequency,
// ... } - EXTENSIBLE, 1 root alternative (index needs 0 bits).
bw_put_bits(&bw, 0, 1); // CHOICE extension bit: value is in root
// BasicVehicleContainerLowFrequency (SEQUENCE, no OPTIONALs/"...")
// vehicleRole VehicleRole ENUM 16 values -> 4 bits
bw_put_bits(&bw, 0, 4); // default(0)
// exteriorLights ExteriorLights BIT STRING(SIZE(8)) -> 8 bits, all off
bw_put_bits(&bw, 0, 8);
// pathHistory PathHistory ::= SEQUENCE(SIZE(0..40)) OF PathPoint -> count 0..40 = 6 bits
bw_put_bits(&bw, 0, 6); // empty path history
return (int)bw_byte_len(&bw);
}
-35
View File
@@ -1,35 +0,0 @@
#ifndef CAM_H
#define CAM_H
#include <stdint.h>
#include <stddef.h>
// Minimal CAM (Cooperative Awareness Message) per ETSI EN 302 637-2 v1.4.1
// (CAM-PDU-Descriptions) + TS 102 894-2 v1.3.1 (CDD / ITS-Container), matching
// the field set the working Rust reference (esp32-c_its-companion, feat/tx-cam,
// src/applogic/cam_tx.rs) transmits:
// - ItsPduHeader (protocolVersion 2, messageID 2 = cam)
// - CoopAwareness { generationDeltaTime, camParameters }
// - CamParameters {
// basicContainer { stationType, referencePosition },
// highFrequencyContainer = basicVehicleContainerHighFrequency { ... },
// lowFrequencyContainer = basicVehicleContainerLowFrequency { ... }
// }
// All vehicle-dynamics fields we don't measure are encoded as their ASN.1
// "unavailable" value. Speed is a real 0 (correct for a stationary station).
typedef struct {
uint32_t station_id;
uint8_t station_type; // StationType(0..255): 5 = passengerCar
uint16_t generation_delta_time; // TimestampIts mod 65536 (ms); 0 until a real clock is wired
int32_t latitude_tenmicrodeg; // Latitude, 1/10 microdegree
int32_t longitude_tenmicrodeg; // Longitude, 1/10 microdegree
uint16_t speed_cm_s; // SpeedValue, 0.01 m/s units (0 = stationary)
uint16_t heading_ddeg; // HeadingValue, 0.1 deg units (0..3600), 3601 = unavailable
uint16_t vehicle_length_dm; // VehicleLengthValue(1..1023), 10cm steps
uint8_t vehicle_width_dm; // VehicleWidth(1..62), 10cm steps
} cam_fields_t;
// Encodes the CAM as ASN.1 UPER. Returns bytes written, or -1 if buf too small.
int cam_encode(const cam_fields_t *f, uint8_t *buf, size_t buf_len);
#endif
+30
View File
@@ -0,0 +1,30 @@
// Channel busy ratio of one window of the ESP32-C5 CCA counters (EN 303 797 / TS 102 687 LCBR).
#pragma once
#include <cstdint>
#include <optional>
namespace microbu::cca {
/// The PHY counters are 27 bits wide and count 40 MHz cycles: they wrap every 2^27 / 40 MHz = 3.36 s.
constexpr std::uint32_t counter_range = std::uint32_t {1} << 27;
constexpr std::int64_t wrap_us = (std::int64_t {1} << 27) * 1000000 / 40000000;
/// Cycles between two readings of a 27-bit counter, across at most one wrap.
constexpr std::uint32_t delta27(std::uint32_t after, std::uint32_t before) {
return after >= before ? after - before : after + counter_range - before;
}
/// Busy ratio of the window between two readings taken `elapsed_us` apart (monotonic clock), or nothing when the
/// window cannot be measured: read at or beyond one wrap period (the counters may have wrapped more than once), or
/// no cycle elapsed. Never a made-up 0.0, which would read as an idle channel and open the DCC gate.
inline std::optional<double> window_cbr(std::uint32_t total_now, std::uint32_t busy_now, std::uint32_t total_before,
std::uint32_t busy_before, std::int64_t elapsed_us) {
if (elapsed_us <= 0 || elapsed_us >= wrap_us) return std::nullopt;
const std::uint32_t total = delta27(total_now, total_before);
if (total == 0) return std::nullopt;
const std::uint32_t busy = delta27(busy_now, busy_before);
return busy >= total ? 1.0 : static_cast<double>(busy) / static_cast<double>(total);
}
} // namespace microbu::cca
-153
View File
@@ -1,153 +0,0 @@
#include "denm.h"
#include <string.h>
// Minimal MSB-first bit packer - ASN.1 UPER is a bitstream, not a byte
// stream, so we can't just memcpy structs.
typedef struct {
uint8_t *buf;
size_t buf_len;
size_t bit_pos;
} bitwriter_t;
static void bw_init(bitwriter_t *bw, uint8_t *buf, size_t len)
{
bw->buf = buf;
bw->buf_len = len;
bw->bit_pos = 0;
memset(buf, 0, len);
}
static void bw_put_bits(bitwriter_t *bw, uint64_t value, int nbits)
{
for (int i = nbits - 1; i >= 0; i--) {
size_t byte_idx = bw->bit_pos / 8;
int bit_idx = 7 - (int)(bw->bit_pos % 8);
if (byte_idx >= bw->buf_len) {
return; // overflow guard - silently truncates, check return value of denm_encode
}
uint8_t bit = (value >> i) & 1;
bw->buf[byte_idx] = (uint8_t)(bw->buf[byte_idx] | (bit << bit_idx));
bw->bit_pos++;
}
}
static size_t bw_byte_len(const bitwriter_t *bw)
{
return (bw->bit_pos + 7) / 8;
}
int denm_encode(const denm_fields_t *f, uint8_t *buf, size_t buf_len)
{
bitwriter_t bw;
bw_init(&bw, buf, buf_len);
// ---- ItsPduHeader ---- (SEQUENCE, no OPTIONALs, no "..." -> no preamble at all)
bw_put_bits(&bw, 2, 8); // protocolVersion INTEGER(0..255) = 2
bw_put_bits(&bw, 1, 8); // messageID INTEGER(0..255) = denm(1)
bw_put_bits(&bw, f->station_id, 32); // stationID = StationID INTEGER(0..4294967295) = 32 bits
// ---- DenmPayload (DecentralizedEnvironmentalNotificationMessage) ----
// No "..." on this SEQUENCE -> no extension bit, just the 3-bit
// optional-component preamble in declared order: situation, location,
// alacarte. "No additional parameters" means location/alacarte stay
// absent.
bw_put_bits(&bw, 1, 1); // situation present
bw_put_bits(&bw, 0, 1); // location absent
bw_put_bits(&bw, 0, 1); // alacarte absent
// ---- ManagementContainer ----
// This SEQUENCE ends in "..." in the real ASN.1 module -> extensible,
// so it needs a leading 1-bit extension flag (0 = no extension
// additions used) BEFORE the 5-bit optional/default preamble
// (termination, relevanceDistance, relevanceTrafficDirection,
// validityDuration, transmissionInterval, in that declared order). An
// earlier version of this code omitted the extension bit entirely,
// which would shift every single bit after it and corrupt the whole
// rest of the message for any spec-compliant decoder.
bw_put_bits(&bw, 0, 1); // ManagementContainer extension bit: none used
bw_put_bits(&bw, f->terminate ? 1 : 0, 1); // termination present only when cancelling
bw_put_bits(&bw, 0, 1); // relevanceDistance absent
bw_put_bits(&bw, 0, 1); // relevanceTrafficDirection absent
bw_put_bits(&bw, 0, 1); // validityDuration absent -> default 600s applies
bw_put_bits(&bw, 0, 1); // transmissionInterval absent
// actionID = ActionID{ originatingStationID StationID(32), sequenceNumber
// SequenceNumber(0..65535, 16 bits) } - no OPTIONALs/"..." -> no preamble.
// Keep sequenceNumber constant across repeats of the SAME event - it's
// the caller's job (see main.c) to only bump it on a genuinely new event
// and reuse it for that event's eventual termination message.
bw_put_bits(&bw, f->station_id, 32);
bw_put_bits(&bw, f->sequence_number, 16);
// detectionTime / referenceTime: TimestampIts INTEGER(0..4398046511103)
// = exactly 42 bits (2^42), ms since 2004-01-01T00:00:00Z. NOT WIRED UP
// YET - there's no RTC/NTP sync in this skeleton, so this is 0 (decodes
// as 2004-01-01). Wire in SNTP or a GNSS UTC fix before this is real.
bw_put_bits(&bw, 0, 42);
bw_put_bits(&bw, 0, 42);
// termination VALUE - only emitted when present (per the preamble bit
// above - UPER never encodes a value for an absent optional component).
// Termination ::= ENUMERATED{isCancellation(0), isNegation(1)}, no
// "...", 2 values -> 1 bit.
if (f->terminate) {
bw_put_bits(&bw, 0, 1); // isCancellation
}
// eventPosition (ReferencePosition ::= SEQUENCE{latitude, longitude,
// positionConfidenceEllipse, altitude} - no OPTIONALs/"..." -> no
// preamble, straight concatenation). Widths below are each field's
// exact constrained-INTEGER range size from ITS-Container.asn, encoded
// as an unsigned offset from the type's declared minimum - NOT assumed
// to match neighboring fields (latitude and longitude are different
// widths, which is easy to miss).
// Latitude ::= INTEGER(-900000000..900000001) -> range 1800000002 -> 31 bits
uint32_t lat_offset = (uint32_t)(f->latitude_tenmicrodeg - (-900000000));
bw_put_bits(&bw, lat_offset, 31);
// Longitude ::= INTEGER(-1800000000..1800000001) -> range 3600000002 -> 32 bits
uint32_t lon_offset = (uint32_t)(f->longitude_tenmicrodeg - (-1800000000));
bw_put_bits(&bw, lon_offset, 32);
// PosConfidenceEllipse ::= SEQUENCE{semiMajorConfidence, semiMinorConfidence,
// semiMajorOrientation} - no preamble.
// SemiAxisLength ::= INTEGER(0..4095) -> 12 bits (not 16 - this was wrong before)
bw_put_bits(&bw, 4095, 12); // semiMajorConfidence: unavailable
bw_put_bits(&bw, 4095, 12); // semiMinorConfidence: unavailable
// HeadingValue ::= INTEGER(0..3601) -> 12 bits (not 16 - this was wrong before)
bw_put_bits(&bw, 3601, 12); // semiMajorOrientation: unavailable
// Altitude ::= SEQUENCE{altitudeValue, altitudeConfidence} - no preamble.
// AltitudeValue ::= INTEGER(-100000..800001) -> range 900002 -> 20 bits
// (not 24 - this was wrong before), offset-encoded from -100000.
bw_put_bits(&bw, 900001, 20); // 800001 ("unavailable") - (-100000) = 900001
// AltitudeConfidence ::= ENUMERATED, 16 named values, no "..." -> 4 bits
bw_put_bits(&bw, 15, 4); // unavailable
// stationType: StationType INTEGER(0..255) -> 8 bits fixed regardless of
// how sparse the named values are.
bw_put_bits(&bw, f->station_type, 8);
// ---- SituationContainer ----
// This SEQUENCE also ends in "..." -> its own 1-bit extension flag,
// THEN the 2-bit preamble (linkedCause, eventHistory), THEN the
// mandatory field values. An earlier version of this code put the
// linkedCause/eventHistory bits at the END instead of the start, and
// had no extension bit at all - both are structural bugs that would
// desync any spec-compliant decoder from this point on.
bw_put_bits(&bw, 0, 1); // SituationContainer extension bit: none used
bw_put_bits(&bw, 0, 1); // linkedCause absent
bw_put_bits(&bw, 0, 1); // eventHistory absent
// informationQuality: InformationQuality INTEGER(0..7) -> 3 bits
bw_put_bits(&bw, 1, 3); // low quality - no real sensor input, just the hazard-light GPIO
// eventType: CauseCode ::= SEQUENCE{causeCode, subCauseCode, ...} - this
// inner SEQUENCE is ALSO extensible ("..."), so it gets its own leading
// extension bit before its two mandatory fields.
bw_put_bits(&bw, 0, 1); // CauseCode extension bit: none used
bw_put_bits(&bw, f->cause_code, 8); // CauseCodeType INTEGER(0..255) -> 8 bits
bw_put_bits(&bw, f->sub_cause_code, 8); // SubCauseCodeType INTEGER(0..255) -> 8 bits
// linkedCause / eventHistory: both absent, already signalled in the
// preamble above - UPER writes no value bits for them.
return (int)bw_byte_len(&bw);
}
-67
View File
@@ -1,67 +0,0 @@
#ifndef DENM_H
#define DENM_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
// Full CauseCodeType enumeration, straight from the authoritative source:
// ETSI TS 102 894-2 (CDD) ITS-Container.asn, CauseCodeType definition.
// (Values 1/2/3/14/26/27/91/94/95/97 were already cross-checked earlier
// against a real captured DENM; the rest are now confirmed the same way,
// from the actual ASN.1 module rather than guessed.)
#define DENM_CAUSE_RESERVED 0
#define DENM_CAUSE_TRAFFIC_CONDITION 1
#define DENM_CAUSE_ACCIDENT 2
#define DENM_CAUSE_ROADWORKS 3
#define DENM_CAUSE_IMPASSABILITY 5
#define DENM_CAUSE_ADVERSE_WEATHER_ADHESION 6
#define DENM_CAUSE_AQUAPLANNING 7
#define DENM_CAUSE_HAZARDOUS_LOCATION_SURFACE_CONDITION 9
#define DENM_CAUSE_HAZARDOUS_LOCATION_OBSTACLE_ON_ROAD 10
#define DENM_CAUSE_HAZARDOUS_LOCATION_ANIMAL_ON_ROAD 11
#define DENM_CAUSE_HUMAN_PRESENCE_ON_ROAD 12
#define DENM_CAUSE_WRONG_WAY_DRIVING 14
#define DENM_CAUSE_RESCUE_AND_RECOVERY_WORK_IN_PROGRESS 15
#define DENM_CAUSE_ADVERSE_WEATHER_EXTREME 17
#define DENM_CAUSE_ADVERSE_WEATHER_VISIBILITY 18
#define DENM_CAUSE_ADVERSE_WEATHER_PRECIPITATION 19
#define DENM_CAUSE_SLOW_VEHICLE 26
#define DENM_CAUSE_DANGEROUS_END_OF_QUEUE 27
#define DENM_CAUSE_VEHICLE_BREAKDOWN 91
#define DENM_CAUSE_POST_CRASH 92
#define DENM_CAUSE_HUMAN_PROBLEM 93
#define DENM_CAUSE_STATIONARY_VEHICLE 94
#define DENM_CAUSE_EMERGENCY_VEHICLE_APPROACHING 95
#define DENM_CAUSE_HAZARDOUS_LOCATION_DANGEROUS_CURVE 96
#define DENM_CAUSE_COLLISION_RISK 97
#define DENM_CAUSE_SIGNAL_VIOLATION 98
#define DENM_CAUSE_DANGEROUS_SITUATION 99
typedef struct {
uint32_t station_id;
uint16_t sequence_number; // keep constant across repeats of the SAME event; only bump on a genuinely new event
uint8_t cause_code; // e.g. 94 = stationaryVehicle
uint8_t sub_cause_code; // 0 = unspecified
uint8_t station_type; // StationType, e.g. 5 = passengerCar - match geonet_wrap_shb's station_type param
int32_t latitude_tenmicrodeg; // 1/10 microdegree; 0 = placeholder/unavailable
int32_t longitude_tenmicrodeg; // 1/10 microdegree; 0 = placeholder/unavailable
bool terminate; // true = encode this as a Termination(isCancellation) message instead of a normal update
} denm_fields_t;
// Encodes a minimal DENM (ItsPduHeader + ManagementContainer +
// SituationContainer only - no location/alacarte containers) as ASN.1 UPER,
// per the actual ETSI EN 302 637-3 / TS 102 894-2 ASN.1 modules (fetched
// from forge.etsi.org, not reconstructed from memory). Returns bytes
// written, or -1 if buf too small.
//
// Two things worth knowing if you're reading this against the modules
// yourself: ManagementContainer, SituationContainer, and CauseCode are all
// declared with a trailing "..." (extensible), which means each needs its
// own leading extension bit in the UPER encoding - easy to miss, and this
// code got it wrong in an earlier version. Field bit-widths below (e.g.
// latitude=31 bits, longitude=32 bits, position-confidence fields=12 bits,
// altitudeValue=20 bits) are derived directly from each type's declared
// INTEGER constraint range, not assumed to match neighboring fields.
int denm_encode(const denm_fields_t *f, uint8_t *buf, size_t buf_len);
#endif
-57
View File
@@ -1,57 +0,0 @@
#include "dot11p.h"
#include <string.h>
int dot11p_build_frame(const uint8_t *gn_payload, int gn_len,
const uint8_t src_mac[6],
uint8_t *out, size_t out_len, bool qos)
{
static const uint8_t broadcast[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
static const uint8_t llc_snap[8] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00, 0x89, 0x47};
int hdr_len = qos ? 26 : 24; // QoS Data adds a 2-byte QoS Control field
int total = hdr_len + 8 /* LLC/SNAP */ + gn_len;
if ((size_t)total > out_len) {
return -1;
}
uint8_t *p = out;
// Frame Control: version=0, type=Data(2), subtype=QoS Data(8) -> bytes
// 0x88 0x00. This is what real ITS-G5 hardware actually transmits.
//
// Back on QoS Data again (previously downgraded to non-QoS, subtype 0,
// as a working-but-nonstandard fallback - see git history / old comments
// here for that whole detour). What changed: main.c no longer calls
// esp_wifi_80211_tx() at all - it now goes through
// esp_wifi_80211_tx_custom() (tx_custom.c, pulled from
// opentrafficmap/its-g5-receiver-firmware_txenabled), which bypasses the
// frame-type sanity check entirely by never calling the code path that
// contains it. Frame subtype is no longer gated, so there's no reason
// left to avoid matching real hardware here.
// Frame Control byte 0: version=0, type=Data(2). Subtype: QoS Data(8)=0x88
// for the tx_custom path, or plain Data(0)=0x08 for the standard
// esp_wifi_80211_tx() path (which rejects QoS Data outright).
*p++ = qos ? 0x88 : 0x08; *p++ = 0x00;
// Duration
*p++ = 0x00; *p++ = 0x00;
// Addr1 = destination = broadcast
memcpy(p, broadcast, 6); p += 6;
// Addr2 = source (our pseudonym)
memcpy(p, src_mac, 6); p += 6;
// Addr3 = BSSID = broadcast (no BSS exists in OCB mode)
memcpy(p, broadcast, 6); p += 6;
// Sequence control - left at 0; en_sys_seq=true fills this in for us
*p++ = 0x00; *p++ = 0x00;
// QoS Control field - only present in QoS Data frames
if (qos) {
*p++ = 0x00; *p++ = 0x00; // best-effort access category
}
// LLC/SNAP (Ethertype 0x8947 = GeoNetworking)
memcpy(p, llc_snap, 8); p += 8;
// GeoNetworking + BTP + DENM payload
memcpy(p, gn_payload, gn_len); p += gn_len;
return (int)(p - out);
}
-31
View File
@@ -1,31 +0,0 @@
#ifndef DOT11P_H
#define DOT11P_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
// Wraps a GeoNetworking-layer payload in an 802.11 OCB frame: QoS Data
// (subtype 8, 26-byte header), matching real ITS-G5 hardware, broadcast, no
// BSS (Addr1=Addr3=broadcast), LLC/SNAP with Ethertype 0x8947
// (GeoNetworking's registered Ethertype). Output is ready to hand straight
// to esp_wifi_80211_tx_custom() (tx_custom.c) - NOT esp_wifi_80211_tx(),
// which rejects this frame type outright. `src_mac` is used as Addr2 - pass
// the same 6 bytes you gave geonet_wrap_shb, since GN_ADDR's MID field is
// defined to be this same link-layer address. Returns bytes written, or -1
// if out buffer too small.
//
// History: this used to be downgraded to non-QoS Data (subtype 0) because
// esp_wifi_80211_tx() rejects QoS Data ("unsupport QoS frame type" / esp_err
// 258) and an attempted linker-override bypass (old main/wifi_patches.c)
// didn't work. Restored to QoS Data now that main.c transmits via
// esp_wifi_80211_tx_custom() instead, which bypasses that gate entirely
// (see tx_custom.c) - so there's no longer a reason to deviate from the
// real frame format.
// qos=true -> QoS Data (subtype 8, 26-byte header) for esp_wifi_80211_tx_custom()
// qos=false -> plain Data (subtype 0, 24-byte header) which the STANDARD
// esp_wifi_80211_tx() accepts (used for the standard-TX isolation test)
int dot11p_build_frame(const uint8_t *gn_payload, int gn_len,
const uint8_t src_mac[6],
uint8_t *out, size_t out_len, bool qos);
#endif
+94
View File
@@ -0,0 +1,94 @@
// a station build that runs out of heap resets the board without a word on the framed log (the panic text
// goes to the raw console only). The failed-allocation hook records each failure in RTC memory that survives a
// software reset, and the next boot reports it with the reset reason. The hook must not allocate: it only writes
// the record and prints with esp_rom_printf.
#include "heap_diagnostics.hpp"
#include <esp_attr.h>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_rom_sys.h>
#include <esp_system.h>
#include <cstdint>
namespace microbu::heap_diagnostics {
namespace {
const char* TAG = "heap";
constexpr std::uint32_t kMagic = 0x48454150; // "HEAP"
struct Record {
std::uint32_t magic;
std::uint32_t failures; // failed allocations since the record was last reported
std::uint32_t size; // of the last failed allocation
std::uint32_t caps;
std::uint32_t free; // free heap of those caps at that moment
std::uint32_t largest; // largest free block of those caps at that moment
char function[32];
std::uint32_t first_size, first_free, first_largest; // the first failure since the last report
};
RTC_NOINIT_ATTR Record record;
volatile unsigned failed_since_boot = 0;
void on_failed_allocation(size_t size, uint32_t caps, const char* function_name) {
failed_since_boot = failed_since_boot + 1;
if (record.magic != kMagic) { record = {}; record.magic = kMagic; }
if (record.failures++ == 0) {
record.first_size = size;
record.first_free = heap_caps_get_free_size(caps);
record.first_largest = heap_caps_get_largest_free_block(caps);
}
record.size = size;
record.caps = caps;
record.free = heap_caps_get_free_size(caps);
record.largest = heap_caps_get_largest_free_block(caps);
std::size_t i = 0;
for (; function_name && function_name[i] && i + 1 < sizeof(record.function); ++i) record.function[i] = function_name[i];
record.function[i] = '\0';
esp_rom_printf("heap: allocation of %u bytes (caps 0x%x) failed in %s: free %u, largest block %u\n",
unsigned(size), unsigned(caps), function_name ? function_name : "?", unsigned(record.free),
unsigned(record.largest));
}
const char* reason_name(esp_reset_reason_t reason) {
switch (reason) {
case ESP_RST_POWERON: return "power-on";
case ESP_RST_EXT: return "external pin";
case ESP_RST_SW: return "software (esp_restart)";
case ESP_RST_PANIC: return "panic/exception (abort, std::terminate)";
case ESP_RST_INT_WDT: return "interrupt watchdog";
case ESP_RST_TASK_WDT: return "task watchdog";
case ESP_RST_WDT: return "other watchdog";
case ESP_RST_DEEPSLEEP: return "deep sleep";
case ESP_RST_BROWNOUT: return "brownout";
case ESP_RST_SDIO: return "SDIO";
case ESP_RST_USB: return "USB peripheral";
case ESP_RST_JTAG: return "JTAG";
default: return "unknown";
}
}
} // namespace
unsigned failed_allocations() { return failed_since_boot; }
void install() {
heap_caps_register_failed_alloc_callback(on_failed_allocation);
}
void report_boot() {
const auto reason = esp_reset_reason();
ESP_LOGI(TAG, "reset reason: %s (%d)", reason_name(reason), int(reason));
if (reason == ESP_RST_POWERON || record.magic != kMagic) { // RTC memory is random after power-on
record = {};
record.magic = kMagic;
return;
}
if (record.failures) {
ESP_LOGW(TAG, "before this reset %u allocation(s) failed; first: %u bytes, free %u, largest block %u; "
"last: %u bytes (caps 0x%x) in %s, free %u, largest block %u",
unsigned(record.failures), unsigned(record.first_size), unsigned(record.first_free),
unsigned(record.first_largest), unsigned(record.size), unsigned(record.caps), record.function,
unsigned(record.free), unsigned(record.largest));
}
record.failures = 0;
}
} // namespace microbu::heap_diagnostics
+17
View File
@@ -0,0 +1,17 @@
// Heap diagnostics that survive a reset : the reset reason and the allocations that failed before it.
#pragma once
namespace microbu::heap_diagnostics {
/// Registers the failed-allocation hook. Call once, early in app_main.
void install();
/// Failed allocations since boot (every heap, every size). A difference across an operation shows whether it ran
/// out of memory, which asn1c and the Wi-Fi driver otherwise report as a decoding error or ESP_ERR_NO_MEM.
unsigned failed_allocations();
/// Logs the reset reason and, if the previous run recorded failed allocations, the last one of them.
/// Call once the log transport is up.
void report_boot();
} // namespace microbu::heap_diagnostics
+41
View File
@@ -0,0 +1,41 @@
#include "its_clock.hpp"
#include <cstdlib>
namespace microbu::its_clock {
namespace {
constexpr std::int64_t stale_after_us = 1000000; // further behind than this: not a small drift
constexpr std::int64_t consistent_within_us = 200000; // backward offsets agreeing to this belong together
constexpr int restart_after_updates = 5;
constexpr std::int64_t restart_after_us = 2000000;
bool continues(const Regression& regression, std::int64_t drift_us) {
return regression.count > 0 && std::llabs(drift_us - regression.offset_us) <= consistent_within_us;
}
} // namespace
Step next_step(bool synchronised, std::int64_t drift_us, std::int64_t local_us, Regression& regression, Lag& lag) {
if (!synchronised) { lag = {}; return Step::start; }
if (drift_us > -stale_after_us) {
regression = {};
if (drift_us >= 0) { lag = {}; return Step::forward; }
if (lag.count == 0) lag = {1, drift_us, local_us, 0};
else { ++lag.count; if (drift_us > lag.freshest_us) lag.freshest_us = drift_us; }
if (lag.count >= restart_after_updates && local_us - lag.first_local_us >= restart_after_us) {
const std::int64_t ahead_us = -lag.freshest_us;
lag = {};
if (ahead_us > slew_deadband_us) { lag.slew_us = ahead_us; return Step::slew_back; }
}
return Step::hold;
}
if (continues(regression, drift_us)) ++regression.count;
else regression = {1, drift_us, local_us};
const bool consistent = regression.count >= restart_after_updates &&
local_us - regression.first_local_us >= restart_after_us;
if (!consistent) return Step::refuse_stale;
regression = {};
return Step::restart;
}
} // namespace microbu::its_clock
+56
View File
@@ -0,0 +1,56 @@
#pragma once
// How a PoTi time reference from the phone moves the micrOBU's ITS clock. Honest: the caller passes the
// measured drift and local time and applies the returned step.
#include <cstdint>
namespace microbu::its_clock {
/// @brief What a PoTi update does to the station's ITS clock.
enum class Step {
start, ///< first reference: synchronise the clock (and restart the station at real time)
forward, ///< the reference is ahead: step the clock forward to it
hold, ///< less than 1 s behind: keep the local clock, later updates catch up
refuse_stale, ///< more than 1 s behind: a late-delivered update, refuse it and keep the clock
restart, ///< consistently behind over >= 5 updates and >= 2 s: the reference really moved back
slew_back, ///< even the freshest reference of >= 5 updates over >= 2 s is behind: the clock runs ahead,
///< slow it down by Lag::slew_us (monotonic, EN 302 890-2 clause 6.3.4 |error| < 20 ms)
};
/// @brief Backward offsets below 1 s seen while holding (state owned by the caller). The freshest one (the largest
/// drift) is the reference least delayed by the link: if even it is behind, the clock itself is ahead.
struct Lag {
int count = 0;
std::int64_t freshest_us = 0;
std::int64_t first_local_us = 0;
std::int64_t slew_us = 0; ///< set with Step::slew_back: how far to slow the clock down
};
/// @brief Clock ahead by less than this is left alone (well inside pPoTiMaxTimeDiff = 20 ms).
constexpr std::int64_t slew_deadband_us = 5000;
/// @brief Slew rate: the clock runs 1/slew_divisor slower until a pending correction is applied (10 %).
constexpr std::int64_t slew_divisor = 10;
/// @brief Part of a pending slew applied after `elapsed_us` of local time.
constexpr std::int64_t slew_applied_us(std::int64_t pending_us, std::int64_t elapsed_us) {
const std::int64_t possible = elapsed_us / slew_divisor;
return possible < pending_us ? possible : pending_us;
}
/// @brief Backward offsets seen so far (state owned by the caller).
struct Regression {
int count = 0;
std::int64_t offset_us = 0;
std::int64_t first_local_us = 0;
};
/// @brief Decide the clock step for one PoTi update. Over BLE, updates delivered late (10-15 s observed)
/// arrive in bursts with a shrinking offset and never look like a consistent backward move.
/// @param synchronised Whether the clock already follows a reference.
/// @param drift_us Reference time minus the station's ITS time.
/// @param local_us Local monotonic time of this update.
/// @param regression Backward-offset tracker, updated in place.
/// @param lag Freshest-backward-offset tracker for Step::slew_back, updated in place.
Step next_step(bool synchronised, std::int64_t drift_us, std::int64_t local_us, Regression& regression, Lag& lag);
} // namespace microbu::its_clock
+57 -15
View File
@@ -1,4 +1,5 @@
#include "link_protocol.hpp"
#include <algorithm>
namespace microbu::link {
@@ -37,15 +38,43 @@ DestinationArea get_area(Reader& r) {
// STATION_CONFIGURE
Bytes encode(const StationConfigure& c) {
Writer w;
w.u8(c.station_type); w.u8(c.security); w.u8(c.address_configuration); w.bytes(c.mid, 6); w.u8(c.beaconing);
w.u16(c.channel_number); w.u8(c.transmit_power_dbm); w.u8(c.radio); w.u8(c.default_traffic_class); w.u8(c.default_lifetime);
const StationConfigure defaults;
if (c.radio != 2 || c.address_configuration != 1 || c.default_traffic_class != 2 || c.default_lifetime != 0x05 ||
!std::equal(c.mid, c.mid + 6, defaults.mid)) {
w.u8(c.station_type); w.u8(c.security); w.u8(c.address_configuration); w.bytes(c.mid, 6); w.u8(c.beaconing);
w.u16(c.channel_number); w.u8(c.transmit_power_dbm); w.u8(c.radio); w.u8(c.default_traffic_class); w.u8(c.default_lifetime);
return w.out;
}
// Streamlined 6-octet operational format
w.u8(c.station_type);
w.u16(c.channel_number);
w.u8(c.transmit_power_dbm);
w.u8(c.security);
w.u8(c.beaconing);
return w.out;
}
bool decode(const Bytes& body, StationConfigure& c) {
Reader r(body);
c.station_type = r.u8(); c.security = r.u8(); c.address_configuration = r.u8(); r.bytes(c.mid, 6); c.beaconing = r.u8();
c.channel_number = r.u16(); c.transmit_power_dbm = r.u8(); c.radio = r.u8(); c.default_traffic_class = r.u8(); c.default_lifetime = r.u8();
return r.done() && c.security <= 1 && c.address_configuration <= 1 && c.beaconing <= 1 && c.radio <= 2;
if (body.size() == 6) {
c = StationConfigure{};
Reader r(body);
c.station_type = r.u8();
c.channel_number = r.u16();
c.transmit_power_dbm = r.u8();
c.security = r.u8();
c.beaconing = r.u8();
c.address_configuration = 1;
c.radio = 2;
c.default_traffic_class = 2;
c.default_lifetime = 0x05;
return r.done() && c.security <= 1 && c.beaconing <= 1;
}
if (body.size() == 16) {
Reader r(body);
c.station_type = r.u8(); c.security = r.u8(); c.address_configuration = r.u8(); r.bytes(c.mid, 6); c.beaconing = r.u8();
c.channel_number = r.u16(); c.transmit_power_dbm = r.u8(); c.radio = r.u8(); c.default_traffic_class = r.u8(); c.default_lifetime = r.u8();
return r.done() && c.security <= 1 && c.address_configuration <= 1 && c.beaconing <= 1 && c.radio <= 2;
}
return false;
}
// POTI_UPDATE
@@ -72,6 +101,7 @@ Bytes encode(const BtpDataRequest& q) {
w.u8(static_cast<std::uint8_t>(q.context.size())); w.bytes(q.context);
if (q.gn_packet_transport_type == 3) put_area(w, q.area.value_or(DestinationArea {}));
w.u16(static_cast<std::uint16_t>(q.fl_sdu.size())); w.bytes(q.fl_sdu);
if (q.generated_at_ms) w.u64(*q.generated_at_ms);
return w.out;
}
bool decode(const Bytes& body, BtpDataRequest& q) {
@@ -84,6 +114,8 @@ bool decode(const Bytes& body, BtpDataRequest& q) {
q.area.reset();
if (q.gn_packet_transport_type == 3) q.area = get_area(r);
q.fl_sdu = r.bytes(r.u16());
q.generated_at_ms.reset();
if (r.ok() && r.remaining() == 8) q.generated_at_ms = r.u64();
return r.done() && q.btp_type <= 1 && q.permissions.size() <= 31;
}
@@ -157,11 +189,15 @@ Bytes encode(const Status& s) {
w.u32(s.radio_submitted); w.u32(s.radio_failed); w.u32(s.radio_received); w.u32(s.radio_dropped);
w.u32(s.link_rx_frames); w.u32(s.link_crc_errors); w.u32(s.link_malformed); w.u32(s.poti_updates);
w.u64(s.its_time_ms);
w.u16(s.battery_mv); w.u8(s.battery_flags);
w.u16(s.cbr_local); w.u16(s.cbr_global); w.u16(s.dcc_delta); w.u16(s.t_gen_vam_dcc_ms);
w.u32(s.heap_free); w.u32(s.heap_minimum_free); w.u32(s.heap_largest_block); w.u32(s.dma_largest_block);
w.u16(static_cast<std::uint16_t>(s.board_temperature_deci_deg));
w.u16(s.battery_mv);
return w.out;
}
bool decode(const Bytes& body, Status& s) {
if (body.size() != status_size_base && body.size() < status_size_battery) return false;
if (body.size() != 111 && body.size() != 127 && body.size() != 129 && body.size() != 131 && body.size() != 132) return false;
s = Status{};
Reader r(body);
s.uptime_ms = r.u32(); s.configured = r.u8(); r.bytes(s.gn_address, 8); r.bytes(s.identifier, 8); s.change_pending = r.u8(); s.tickets = r.u8();
s.signed_messages = r.u32(); s.refused_no_ticket = r.u32(); s.refused_change_pending = r.u32(); s.refused_permission = r.u32();
@@ -170,19 +206,25 @@ bool decode(const Bytes& body, Status& s) {
s.radio_submitted = r.u32(); s.radio_failed = r.u32(); s.radio_received = r.u32(); s.radio_dropped = r.u32();
s.link_rx_frames = r.u32(); s.link_crc_errors = r.u32(); s.link_malformed = r.u32(); s.poti_updates = r.u32();
s.its_time_ms = r.u64();
if (!r.ok()) return false;
s.battery_mv = 0; s.battery_flags = 0;
if (r.remaining() >= 3) { s.battery_mv = r.u16(); s.battery_flags = r.u8(); }
return r.ok(); // octets beyond the known fields belong to a later extension
s.cbr_local = r.u16(); s.cbr_global = r.u16(); s.dcc_delta = r.u16(); s.t_gen_vam_dcc_ms = r.u16();
if (r.remaining() == 0) return r.ok(); // a 111-octet STATUS from firmware before the heap diagnostics
s.heap_free = r.u32(); s.heap_minimum_free = r.u32(); s.heap_largest_block = r.u32(); s.dma_largest_block = r.u32();
if (r.remaining() == 0) return r.ok(); // 127-octet form before temperature
s.board_temperature_deci_deg = static_cast<std::int16_t>(r.u16());
if (r.remaining() == 0) return r.ok(); // 129-octet form before battery
if (body.size() == 132) (void)r.u8(); // Former status format included a battery flag byte.
s.battery_mv = r.u16();
return r.done();
}
// RESULT
Bytes encode(const Result& res) {
// CONFIRM
Bytes encode(const Confirm& res) {
Writer w;
w.u8(static_cast<std::uint8_t>(res.code)); w.u8(static_cast<std::uint8_t>(res.detail.size())); w.bytes(res.detail);
return w.out;
}
bool decode(const Bytes& body, Result& res) {
bool decode(const Bytes& body, Confirm& res) {
Reader r(body);
res.code = static_cast<Code>(r.u8()); res.detail = r.bytes(r.u8());
return r.done();
+64 -35
View File
@@ -1,5 +1,5 @@
#pragma once
// micrOBU station-internal link, message layer version 1 (implementation/station-link/README.md).
// micrOBU station-internal link, message layer (../../docs/station-link.tex).
// Transport independent: the same octets are one GATT attribute value later and one serial
// frame payload today. Little-endian integers; ETSI payloads inside stay opaque.
#include <cstddef>
@@ -30,23 +30,38 @@ enum class Opcode : std::uint8_t {
SF_ID_LOCK = 0x0A,
SF_ID_UNLOCK = 0x0B,
STATUS_REQUEST = 0x0C,
RAW_CAPTURE = 0x0D, // debug path: u8 mode (0x01 on, 0x02 broadcast only, 0x04 own TX)
// TS 102 941 V2.2.1 on the device : the phone relays, the micrOBU builds and answers
PKI_IDENTITY = 0x0E, // -> CONFIRM detail: u8 id length, canonical identifier, u8[65] canonical public key
PKI_ENROL_REQUEST = 0x0F, // u8[8] EA HashedId8 -> CONFIRM, then PKI_REQUEST_DATA
PKI_AUTH_REQUEST = 0x10, // u8[8] EA, u8[8] AA HashedId8 -> CONFIRM, then PKI_REQUEST_DATA
PKI_RETRY = 0x13, // u8 kind (1 only), returns the retained encrypted enrolment request
PKI_TRUST_BOOTSTRAP = 0x16, // USB only, independently pinned TLM certificate
PKI_TRUST_UPDATE = 0x17, // u16 total, u16 offset, snapshot segment
PKI_STATUS = 0x15, // device time, EC and CAM/VAM validity ends, managed trust deadline
PKI_CANCEL = 0x14, // u8 kind, erase the pending transaction and session key
PKI_RESPONSE = 0x11, // u8 kind, u16 total, u16 offset, segment[] -> CONFIRM (last segment: u8 code, u8[8] digest)
// ESP32-C5 -> phone
RESULT = 0x80,
CONFIRM = 0x80,
BTP_DATA_INDICATION = 0x81,
SF_IDCHANGE_EVENT = 0x82,
STATUS = 0x84,
// MicrOBU extension, not in the colleague's station-link v1: every ITS message heard on air,
// unwrapped by gn_unwrap.c whether or not the security entity could verify it. Body is the
// previous firmware's SERIAL_MSG_V2X_RX payload unchanged: [u16 btp_dest_port][i8 rssi]
// [u8 flags: bit0 geo area valid, bit1 signed but not verified][i32 area_lat][i32 area_lon]
// [u16 area_distance_a], then the UPER bytes. See obu-firmware/NOTES.md.
V2X_RX = 0x85,
// 0x84 retired: STATUS_REQUEST returns its snapshot in CONFIRM.detail.
RAW_FRAME = 0x85, // u32 counter, u8 flags, i8 RSSI, ITS5 record (may be fragmented)
// 0x86 reserved: retired DCC_T_GEN_VAM (T_GenVam carried directly in STATUS)
PKI_REQUEST_DATA = 0x87, // u8 kind (1 enrolment, 2 authorization), encoded request (fragmented)
// MicrOBU extension, not in station-link.tex: every ITS message heard on air, verified or not
// (Station::forward_raw). 0x86 is reserved by Niklas Dathe (retired DCC_T_GEN_VAM), so 0x90.
V2X_RX = 0x90, // u16 port, i8 RSSI, u8 flags, i32 lat, i32 lon, u16 dist, ITS payload
BATTERY_STATE = 0x88, // legacy voltage record: u8 version=1, u8 calibrated flag, u16 mV
// 0x89 reserved: retired IMU_TELEMETRY (not streamed over link; reserved for wake interrupts)
};
constexpr std::uint8_t flag_fragment_first = 0x01;
constexpr std::uint8_t flag_fragment_more = 0x02;
constexpr std::uint8_t flag_fragment_middle = 0x02;
constexpr std::uint8_t flag_fragment_last = 0x03;
constexpr std::size_t fragment_header_size = 4; // u16 total body size, u16 body offset (little-endian)
// RESULT codes: vanetza_idf::Result values first (same numbering), then link codes.
// CONFIRM codes: microbu_v2x::Result values first (same numbering), then link codes.
enum class Code : std::uint8_t {
accepted = 0, invalid_argument = 1, unsupported = 2, wrong_entry_point = 3, security_unavailable = 4,
resource_limit = 5, rejected = 6, time_regression = 7, identity_change_pending = 8,
@@ -83,15 +98,20 @@ bool decode(const Bytes& octets, Message& out);
// constants itsGnSecurity, itsGnLocalAddrConfMethod, itsGnDefaultTrafficClass and
// itsGnDefaultPacketLifetime of ETSI TS 103 836-4-1 (GeoNetworking) annex H; channel_number,
// transmit_power_dbm and radio are ITS-G5 access-layer parameters (ETSI EN 303 797).
// STATION_CONFIGURE (0x01): Streamlined 6-octet operational format.
// Active fields: station_type (u8), channel_number (u16), transmit_power_dbm (u8), security (u8), beaconing (u8).
// Retired parameters (radio, address_configuration, mid, default_traffic_class, default_lifetime)
// are fixed to standard defaults: radio=2 (transmit and receive), address_configuration=1 (anonymous),
// default_traffic_class=2 (DP2), default_lifetime=0x05 (1 s).
struct StationConfigure {
std::uint8_t station_type = 2; // TS 102 894-2 StationType (2 = cyclist)
std::uint8_t security = 1; // itsGnSecurity
std::uint8_t address_configuration = 1; // 0 AUTO (mid below), 1 ANONYMOUS (ticket digest)
std::uint8_t mid[6] = {2, 0, 0, 0, 0, 1};
std::uint8_t beaconing = 1;
std::uint16_t channel_number = 180;
std::uint8_t transmit_power_dbm = 10;
std::uint8_t radio = 0; // 0 off, 1 receive only, 2 transmit and receive
std::uint8_t security = 1; // itsGnSecurity (0 off, 1 on)
std::uint8_t beaconing = 1; // 0 off, 1 on
std::uint8_t address_configuration = 1; // 0 AUTO (mid below), 1 ANONYMOUS (ticket digest)
std::uint8_t mid[6] = {2, 0, 0, 0, 0, 1};
std::uint8_t radio = 2; // 0 off, 1 receive only, 2 transmit and receive
std::uint8_t default_traffic_class = 2;
std::uint8_t default_lifetime = 0x05; // 1 s (base One_Second, multiplier 1)
};
@@ -171,6 +191,8 @@ struct BtpDataRequest {
Bytes context;
std::optional<DestinationArea> area; // present for GBC
Bytes fl_sdu;
// Optional trailing u64: ITS time (TimestampIts, ms) at which the phone generated the request. The
std::optional<std::uint64_t> generated_at_ms;
};
/// @param body Raw message body bytes.
@@ -270,6 +292,7 @@ Bytes encode(const IdChangeEvent& value);
// The link's encoding of the SN-IDCHANGE-EVENT.response primitive (ETSI TS 103 836-4-1
// clause 10.2.1.4), acknowledging an IdChangeEvent.
// Correlated by subscription only. Send zero in the unused response-header sequence.
struct IdChangeEventResponse { std::uint64_t subscription = 0; std::uint8_t return_code = 0; };
/// @param body Raw message body bytes.
/// @param out Receives the decoded response.
@@ -292,41 +315,47 @@ struct Status {
std::uint32_t radio_submitted = 0, radio_failed = 0, radio_received = 0, radio_dropped = 0;
std::uint32_t link_rx_frames = 0, link_crc_errors = 0, link_malformed = 0, poti_updates = 0;
std::uint64_t its_time_ms = 0;
// MicrOBU extension, appended after the colleague's 103 octets: [103] battery_mv u16 (0: not
// measured, no cell or no sensor), [105] battery_flags u8. A 103-octet body (the colleague's
// layout, and this firmware before the battery) still decodes, with these two left at 0.
std::uint16_t battery_mv = 0;
std::uint8_t battery_flags = 0;
// DCC diagnostics (units of 1e-4; 0xFFFF = not available) and the value passed to the VBS
std::uint16_t cbr_local = 0xFFFF, cbr_global = 0xFFFF, dcc_delta = 0xFFFF;
std::uint16_t t_gen_vam_dcc_ms = 0; // 0 = none provided (the VBS then uses T_GenVamMin)
// Heap diagnostics (octets): free and lowest-ever free heap, the largest block one allocation can get,
// and the largest DMA-capable block (the Wi-Fi driver's TX buffers). Appended: a 111-octet STATUS still decodes.
std::uint32_t heap_free = 0, heap_minimum_free = 0, heap_largest_block = 0, dma_largest_block = 0;
// Onboard temperature (0.1 deg C; 0x7FFF = not available; TMP112 on mainboard v5)
std::int16_t board_temperature_deci_deg = 0x7FFF;
std::uint16_t battery_mv = 0; // Calibrated battery voltage in mV (0 if unavailable)
};
/// battery_flags bits of Status.
constexpr std::uint8_t battery_flag_low = 0x01; ///< cell below the warning threshold
constexpr std::uint8_t battery_flag_critical = 0x02; ///< cell below the shutdown threshold: the board powers down unless a phone is on USB
/// Octets of the STATUS body without / with the MicrOBU battery extension.
constexpr std::size_t status_size_base = 103;
constexpr std::size_t status_size_battery = 106;
// BATTERY_STATE (0x88)
struct BatteryState {
std::uint8_t version = 1;
std::uint8_t flags = 0; // bit0: calibrated battery-voltage reading
std::uint16_t battery_mv = 0;
bool calibrated() const { return flags & 1; }
};
bool decode(const Bytes& body, BatteryState& out);
Bytes encode(const BatteryState& value);
/// @param body Raw message body bytes.
/// @param out Receives the decoded status. Accepts the 103-octet base body and any body of at
/// least 106 octets (trailing octets after the known fields are ignored, so a later
/// extension does not break this decoder); 104 or 105 octets are malformed.
/// @param out Receives the decoded status.
/// @return false if malformed.
bool decode(const Bytes& body, Status& out);
/// @param value Status to encode.
/// @return Encoded body bytes.
Bytes encode(const Status& value);
struct Result {
struct Confirm {
Code code = Code::accepted;
Bytes detail;
};
/// @param body Raw message body bytes.
/// @param out Receives the decoded result.
/// @return false if malformed.
bool decode(const Bytes& body, Result& out);
/// @param value Result to encode.
bool decode(const Bytes& body, Confirm& out);
/// @param value Confirmation to encode.
/// @return Encoded body bytes.
Bytes encode(const Result& value);
Bytes encode(const Confirm& value);
// ---- little-endian helpers shared with the test channel ----------------------------------
/// @note All multi-byte values are written little-endian.
class Writer {
public:
+176 -44
View File
@@ -13,31 +13,59 @@ LinkService::LinkService(Station& station) : station_(station) {
station_.on_indication([this](const link::BtpDataIndication& indication) {
broadcast(link::Opcode::BTP_DATA_INDICATION, ++own_sequence_, link::encode(indication));
});
station_.on_raw_frame([this](const link::Bytes& body) {
if (raw_transport_ == LinkTransport::ble && !ble::connected()) return;
send_fragmented(raw_transport_, link::Opcode::RAW_FRAME, ++own_sequence_, body);
});
// MicrOBU: every ITS message heard on air, verified or not (Station::on_raw_its).
station_.on_raw_its([this](const link::Bytes& body) {
broadcast(link::Opcode::V2X_RX, ++own_sequence_, body);
});
// T_GenVam is included in the status snapshot returned on request.
station_.on_id_event([this](const link::IdChangeEvent& event) {
// PREPARE/COMMIT expect SF_IDCHANGE_EVENT_RESPONSE with this sequence
// PREPARE/COMMIT responses match the subscription; their header sequence is unused.
broadcast(link::Opcode::SF_IDCHANGE_EVENT, ++own_sequence_, link::encode(event));
});
}
void LinkService::send(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) {
bool LinkService::send(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body,
std::uint8_t flags) {
link::Bytes octets;
link::Message message {{opcode, 0, sequence}, body};
if (!link::encode(message, octets)) { ESP_LOGE(TAG, "message 0x%02x too long (%u)", unsigned(opcode), unsigned(body.size())); return; }
if (transport == LinkTransport::serial) serial::write(serial::FrameType::LINK, octets);
else ble::write(octets);
link::Message message {{opcode, flags, sequence}, body};
if (!link::encode(message, octets)) { ESP_LOGE(TAG, "message 0x%02x too long (%u)", unsigned(opcode), unsigned(body.size())); return false; }
if (transport == LinkTransport::serial) {
if (opcode == link::Opcode::RAW_FRAME) return serial::try_write(serial::FrameType::LINK, octets);
return serial::write(serial::FrameType::LINK, octets);
}
return ble::write(octets);
}
bool LinkService::send_fragmented(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) {
const std::size_t limit = transport == LinkTransport::ble ? ble::max_message() : link::maximum_message;
const std::size_t chunk = limit - link::header_size;
if (body.size() <= chunk) return send(transport, opcode, sequence, body);
if (body.size() > 65535 || chunk <= link::fragment_header_size) return false;
const std::size_t capacity = chunk - link::fragment_header_size;
for (std::size_t offset = 0; offset < body.size(); offset += capacity) {
const std::size_t n = std::min(capacity, body.size() - offset);
const std::uint8_t flags = offset == 0 ? link::flag_fragment_first :
(offset + n == body.size() ? link::flag_fragment_last : link::flag_fragment_middle);
link::Bytes part {std::uint8_t(body.size()), std::uint8_t(body.size() >> 8),
std::uint8_t(offset), std::uint8_t(offset >> 8)};
part.insert(part.end(), body.begin() + offset, body.begin() + offset + n);
if (!send(transport, opcode, sequence, part, flags)) return false;
}
return true;
}
void LinkService::broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) {
send(LinkTransport::serial, opcode, sequence, body);
if (ble::connected()) send(LinkTransport::ble, opcode, sequence, body);
// Fragmented when needed: a MAPEM indication is larger than one message on either transport.
send_fragmented(LinkTransport::serial, opcode, sequence, body);
if (ble::connected()) send_fragmented(LinkTransport::ble, opcode, sequence, body);
}
void LinkService::reply(LinkTransport transport, std::uint16_t sequence, link::Code code, const link::Bytes& detail) {
send(transport, link::Opcode::RESULT, sequence, link::encode(link::Result {code, detail}));
send_fragmented(transport, link::Opcode::CONFIRM, sequence, link::encode(link::Confirm {code, detail}));
}
link::Status LinkService::status() {
@@ -47,14 +75,58 @@ link::Status LinkService::status() {
value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages;
value.link_crc_errors = serial_counters.crc_errors;
value.link_malformed += ble_counters.malformed;
value.battery_mv = battery_mv_;
value.battery_flags = battery_flags_;
value.battery_mv = battery_millivolts();
return value;
}
link::Code LinkService::provision_segment(const link::CredentialsProvision& c, link::Bytes& detail) {
if (c.offset == 0) { bundle_.clear(); bundle_total_ = c.total_length; }
if (c.total_length != bundle_total_ || c.offset != bundle_.size() || c.total_length > 8192) {
bundle_.clear();
return link::Code::malformed;
}
bundle_.insert(bundle_.end(), c.segment.begin(), c.segment.end());
if (bundle_.size() < bundle_total_) return link::Code::accepted;
link::ApplyReport report;
link::Code result = link::Code::accepted;
try {
result = station_.provision(bundle_, report);
} catch (const std::exception& e) {
ESP_LOGE(TAG, "provision exception: %s", e.what());
result = link::Code::invalid_argument;
}
bundle_.clear();
detail = {static_cast<std::uint8_t>(report.roots), static_cast<std::uint8_t>(report.authorities),
static_cast<std::uint8_t>(report.tickets)};
return result;
}
void LinkService::handle(const link::Bytes& octets, LinkTransport origin) {
link::Message m;
if (!link::decode(octets, m)) return;
auto joined = request_reassembly_.feed(m, unsigned(origin), esp_timer_get_time() / 1000);
if (request_reassembly_.take_overflow()) {
// Every request gets a CONFIRM, also one too large to join.
ESP_LOGW(TAG, "request 0x%02x exceeds %u octets", unsigned(m.header.opcode), unsigned(link::maximum_request_body));
reply(origin, m.header.sequence, link::Code::resource_limit);
return;
}
if (!joined) return;
m = std::move(*joined);
// Every request gets a CONFIRM: an exception below (e.g. a certificate the codec cannot read) is answered with
// rejected instead of leaving the phone waiting for a reply that never comes.
try {
dispatch(m, origin);
} catch (const std::bad_alloc&) {
ESP_LOGE(TAG, "out of memory handling opcode 0x%02x", unsigned(m.header.opcode));
reply(origin, m.header.sequence, link::Code::resource_limit);
} catch (const std::exception& e) {
ESP_LOGE(TAG, "opcode 0x%02x failed: %s", unsigned(m.header.opcode), e.what());
reply(origin, m.header.sequence, link::Code::rejected);
}
}
void LinkService::dispatch(const link::Message& m, LinkTransport origin) {
const auto seq = m.header.sequence;
using link::Opcode; using link::Code;
switch (m.header.opcode) {
@@ -81,23 +153,8 @@ void LinkService::handle(const link::Bytes& octets, LinkTransport origin) {
case Opcode::CREDENTIALS_PROVISION: {
link::CredentialsProvision c;
if (!link::decode(m.body, c)) return reply(origin, seq, Code::malformed);
if (c.offset == 0) { bundle_.clear(); bundle_total_ = c.total_length; }
if (c.total_length != bundle_total_ || c.offset != bundle_.size() || c.total_length > 8192) { bundle_.clear(); return reply(origin, seq, Code::malformed); }
bundle_.insert(bundle_.end(), c.segment.begin(), c.segment.end());
if (bundle_.size() < bundle_total_) return reply(origin, seq, Code::accepted);
link::ApplyReport report;
link::Code result = Code::accepted;
try {
result = station_.provision(bundle_, report);
} catch (const std::exception& e) {
ESP_LOGE(TAG, "provision exception: %s", e.what());
result = Code::invalid_argument;
}
bundle_.clear();
link::Bytes detail;
detail.push_back(static_cast<std::uint8_t>(report.roots));
detail.push_back(static_cast<std::uint8_t>(report.authorities));
detail.push_back(static_cast<std::uint8_t>(report.tickets));
const auto result = provision_segment(c, detail);
return reply(origin, seq, result, detail);
}
case Opcode::CREDENTIALS_ERASE:
@@ -145,27 +202,102 @@ void LinkService::handle(const link::Bytes& octets, LinkTransport origin) {
return reply(origin, seq, station_.unlock(handle));
}
case Opcode::STATUS_REQUEST:
return send(origin, link::Opcode::STATUS, seq, link::encode(status()));
if (!m.body.empty()) return reply(origin, seq, Code::malformed);
return reply(origin, seq, Code::accepted, link::encode(status()));
case Opcode::RAW_CAPTURE: {
link::Reader r(m.body);
const auto mode = r.u8();
if (!r.done()) return reply(origin, seq, Code::malformed);
const auto result = station_.raw_capture(mode);
if (result == Code::accepted) raw_transport_ = origin; // frames go back over the requesting transport
// measuring over USB: no BLE advertising events while capturing (they blind the shared radio)
if (result == Code::accepted && origin == LinkTransport::serial) ble::set_advertising(!(mode & 0x01));
ESP_LOGI(TAG, "RAW_CAPTURE mode 0x%02x over %s: %d", unsigned(mode), origin == LinkTransport::ble ? "BLE" : "serial", int(result));
return reply(origin, seq, result);
}
case Opcode::PKI_TRUST_BOOTSTRAP:
if (origin != LinkTransport::serial) return reply(origin, seq, Code::rejected);
return reply(origin, seq, station_.pki_trust_bootstrap(m.body));
case Opcode::PKI_TRUST_UPDATE: {
link::Reader reader(m.body);
const auto total = reader.u16(), offset = reader.u16();
const auto segment = reader.rest();
if (!reader.ok() || !total || total > 60000 || segment.empty() || segment.size() > total)
return reply(origin, seq, Code::malformed);
if (offset == 0) { trust_update_.clear(); trust_total_ = total; }
if (total != trust_total_ || offset != trust_update_.size() || segment.size() > total - offset) {
trust_update_.clear();
return reply(origin, seq, Code::malformed);
}
trust_update_.insert(trust_update_.end(), segment.begin(), segment.end());
if (trust_update_.size() < total) return reply(origin, seq, Code::accepted);
const auto result = station_.pki_trust_update(trust_update_);
trust_update_.clear(); trust_update_.shrink_to_fit();
return reply(origin, seq, result);
}
case Opcode::PKI_STATUS: {
if (!m.body.empty()) return reply(origin, seq, Code::malformed);
link::Bytes detail;
const auto result = station_.pki_status(detail);
return reply(origin, seq, result, detail);
}
case Opcode::PKI_IDENTITY: {
link::Bytes detail;
const auto result = station_.pki_identity(detail);
return reply(origin, seq, result, detail);
}
case Opcode::PKI_ENROL_REQUEST:
case Opcode::PKI_AUTH_REQUEST: {
const std::uint8_t kind = m.header.opcode == Opcode::PKI_ENROL_REQUEST ? 1 : 2;
link::Bytes request;
const auto result = station_.pki_request(kind, m.body, request);
reply(origin, seq, result);
if (result == Code::accepted) { // the encrypted request for the phone to relay, same sequence
link::Bytes body {kind};
body.insert(body.end(), request.begin(), request.end());
send_fragmented(origin, Opcode::PKI_REQUEST_DATA, seq, body);
}
return;
}
case Opcode::PKI_CANCEL: {
if (m.body.size() != 1) return reply(origin, seq, Code::malformed);
return reply(origin, seq, station_.pki_cancel(m.body[0]));
}
case Opcode::PKI_RETRY: {
if (m.body.size() != 1) return reply(origin, seq, Code::malformed);
link::Bytes request;
const auto result = station_.pki_retry(m.body[0], request);
reply(origin, seq, result);
if (result == Code::accepted) {
link::Bytes body {m.body[0]};
body.insert(body.end(), request.begin(), request.end());
send_fragmented(origin, Opcode::PKI_REQUEST_DATA, seq, body);
}
return;
}
case Opcode::PKI_RESPONSE: {
link::Reader r(m.body);
const auto kind = r.u8();
const auto total = r.u16();
const auto offset = r.u16();
const auto segment = r.rest();
if (!r.ok() || total == 0 || total > 4096) return reply(origin, seq, Code::malformed);
if (offset == 0) { pki_response_.clear(); pki_total_ = total; pki_kind_ = kind; }
if (total != pki_total_ || kind != pki_kind_ || offset != pki_response_.size()) {
pki_response_.clear();
return reply(origin, seq, Code::malformed);
}
pki_response_.insert(pki_response_.end(), segment.begin(), segment.end());
if (pki_response_.size() < pki_total_) return reply(origin, seq, Code::accepted);
link::Bytes detail;
const auto result = station_.pki_response(kind, pki_response_, detail);
pki_response_.clear();
return reply(origin, seq, result, detail);
}
default:
return reply(origin, seq, Code::unknown_opcode);
}
}
void LinkService::set_battery(std::uint16_t millivolts, std::uint8_t flags) {
battery_mv_ = millivolts;
battery_flags_ = flags;
}
void LinkService::send_status_now() {
last_status_us_ = esp_timer_get_time();
broadcast(link::Opcode::STATUS, ++own_sequence_, link::encode(status()));
}
void LinkService::tick() {
const auto now = esp_timer_get_time();
if (now - last_status_us_ < 1000000) return;
last_status_us_ = now;
broadcast(link::Opcode::STATUS, ++own_sequence_, link::encode(status()));
}
} // namespace microbu
+25 -14
View File
@@ -1,8 +1,10 @@
#pragma once
// Dispatches station-link messages (phone -> micrOBU) to the station and sends the
// micrOBU -> phone messages (results, indications, identifier-change events, status).
// micrOBU -> phone messages (confirmations, indications and identifier-change events).
#include "link_protocol.hpp"
#include "request_reassembly.hpp"
#include "station.hpp"
#include "battery_monitor.hpp"
namespace microbu {
@@ -18,42 +20,51 @@ public:
/// @param message Raw message bytes as received from the transport.
/// @param origin Transport the message arrived on; replies go back on the same transport.
void handle(const link::Bytes& message, LinkTransport origin);
/// @brief Periodic work: broadcasts STATUS once a second.
void tick();
/// @brief Sets the battery fields of every following STATUS.
/// @param millivolts Cell voltage, 0 if not measured.
/// @param flags link::battery_flag_* bits.
void set_battery(std::uint16_t millivolts, std::uint8_t flags);
/// @brief Broadcasts a STATUS now instead of waiting for the next second.
void send_status_now();
/// @brief MicrOBU: one calibrated cell reading in mV (0: not measured), for the battery guard.
std::uint16_t battery_millivolts() { return battery_.sample_millivolts(); }
private:
void dispatch(const link::Message& message, LinkTransport origin);
/// @brief Encodes and writes one message on the given transport.
/// @param transport Transport to write to.
/// @param opcode Message opcode.
/// @param sequence Sequence number to stamp on the header.
/// @param body Encoded message body.
void send(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body);
bool send(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body,
std::uint8_t flags = 0);
/// @brief Sends a body of any size, split into fragments of the transport's message size
/// (README "Fragmentation": full header and sequence on each fragment).
bool send_fragmented(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body);
/// @brief Sends a message on serial, and also on BLE when a phone is connected.
/// @param opcode Message opcode.
/// @param sequence Sequence number to stamp on the header.
/// @param body Encoded message body.
void broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body);
/// @brief Sends a RESULT reply to the message's origin transport.
/// @brief Sends a CONFIRM reply to the message's origin transport.
/// @param origin Transport to reply on.
/// @param sequence Sequence number of the message being replied to.
/// @param code Result code to report.
/// @param detail Optional result detail bytes.
void reply(LinkTransport origin, std::uint16_t sequence, link::Code code, const link::Bytes& detail = {});
/// @brief Appends one CREDENTIALS_PROVISION segment and provisions the bundle once it is complete.
/// @param segment Decoded segment.
/// @param detail Receives the applied root/authority/ticket counts after the last segment.
/// @return accepted for a stored segment, else the malformed or provisioning result.
link::Code provision_segment(const link::CredentialsProvision& segment, link::Bytes& detail);
/// @brief Builds a STATUS snapshot from the station and transport counters.
/// @return Current status.
link::Status status();
Station& station_;
BatteryMonitor battery_;
link::RequestReassembly request_reassembly_;
std::uint16_t own_sequence_ = 0;
link::Bytes trust_update_;
std::uint16_t trust_total_ = 0;
link::Bytes bundle_; // credentials being provisioned
std::uint16_t bundle_total_ = 0;
std::int64_t last_status_us_ = 0;
std::uint16_t battery_mv_ = 0;
std::uint8_t battery_flags_ = 0;
link::Bytes pki_response_; // an EA/AA response arriving in segments (PKI_RESPONSE)
std::uint16_t pki_total_ = 0;
std::uint8_t pki_kind_ = 0;
LinkTransport raw_transport_ = LinkTransport::serial; // where RAW_CAPTURE was switched on
};
} // namespace microbu
-429
View File
@@ -1,429 +0,0 @@
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "hal/modem_syscon_ll.h" // modem_syscon_ll_enable_fe_40m_clock() - see initialize_wifi
#include "denm.h"
#include "geonet.h"
#include "dot11p.h"
#include "tx_custom.h" // not called below - kept available for the QoS-Data/tx_custom path if
// esp_wifi_80211_tx's non-QoS frame ever proves insufficient again
#include "serial_link.h"
#include "gn_unwrap.h"
static const char *TAG = "obu-tx";
// Phase 03: CAM is no longer built on this chip. The phone fuses its own GNSS+IMU, UPER-encodes
// CAM itself, and hands the finished bytes down over serial_link (SERIAL_MSG_CAM_TX_PV, together
// with the GeoNetworking position vector to send them under; plain SERIAL_MSG_CAM_TX from an app
// that predates it) - this
// firmware's job on transmit shrinks to "GeoNetworking/BTP-wrap + 802.11-wrap + key the PA the
// instant a CAM arrives." There is no on-chip transmit timer anymore; the phone's send cadence
// (1 Hz baseline, faster near intersections/events - all decided app-side) IS the air cadence.
// See cam.c/.h - no longer built (removed from CMakeLists), kept on disk for field-layout
// reference only, since the phone's Kotlin encoder is a byte-exact port of it.
//
// On receive, this firmware now also runs a promiscuous callback (gn_unwrap.c strips
// 802.11/LLC-SNAP/GeoNetworking/BTP-B down to the raw CAM UPER payload) and forwards every CAM
// it hears over the same serial link (SERIAL_MSG_CAM_RX), for the phone's detection engine.
// Single half-duplex radio doing both jobs, same as real ITS-G5 hardware.
// Target frequency: 5900 MHz (ITS-G5 G5-CCH, channel 180). This is what the
// working Rust reference transmits on, proving the C5 PA reaches it despite the
// 5885 datasheet max. The reference sets band-mode 5G, then phy_11p_set +
// phy_change_channel(5900) directly - it does NOT call esp_wifi_set_channel at
// all, so we don't either (channel 180 isn't a normal Wi-Fi channel anyway).
#define TX_FREQ_MHZ 5900
// ---- CAM beacon profile (used for the GeoNetworking layer only now - see below) ----
#define STATION_TYPE 2 // cyclist (TS 102 894-2 StationType), legacy CAM_TX path only - see legacy_lpv()
#define BTP_PORT_CAM 2001 // BTP-B destination port for CAM (ETSI TS 103 248)
// Bench location, 53°33'16.8"N 10°01'20.6"E, in 1/10-microdegree units. Used only by the legacy
// SERIAL_MSG_CAM_TX path (see legacy_lpv), which carries no position of its own. A current app
// sends SERIAL_MSG_CAM_TX_PV instead, and the GN Source Position Vector then comes from the
// phone's real fix, the same one the CAM payload's own referencePosition is built from.
#define BENCH_LATITUDE_TENMICRODEG 535546667
#define BENCH_LONGITUDE_TENMICRODEG 100223889
// Link-layer address for the legacy SERIAL_MSG_CAM_TX path only. Locally-administered bit set
// (0x02), per normal MAC convention.
//
// This reverses the Phase 03 decision that the pseudonym is owned entirely by this firmware. That
// was simplest while the address never changed, but a pseudonym only protects anyone if the
// 802.11 address, the GN_ADDR MID and the CAM's stationID all change together, and the phone owns
// the stationID. One identity needs one owner, so with CAM_TX_PV the phone sends the address with
// every frame and rotates it, and this constant is only what the legacy path falls back to.
static const uint8_t LEGACY_MAC[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01};
// Undocumented libphy.a calls that push the radio into 802.11p OCB mode on
// the 5.9 GHz ITS-G5 band. See docs/04-transmit-setup.md for source + what
// to do if the linker can't find these symbols in your ESP-IDF version.
extern void phy_11p_set(int enable, int unused);
extern void phy_change_channel(int freq_mhz, int bw_mode, int sec_chan_offset, int unused);
// ============================================================================
// ---- TX path: phone -> serial_link -> queue -> radio task -> air ----------
// ============================================================================
// One CAM-to-transmit item. Fixed-size (no malloc) since SERIAL_LINK_MAX_PAYLOAD bounds it -
// simplest safe option for a queue this small and this hot.
typedef struct {
uint8_t data[SERIAL_LINK_MAX_PAYLOAD];
int len;
gn_lpv_t lpv; // the Source Position Vector this CAM goes out under
} cam_tx_item_t;
static QueueHandle_t s_tx_queue;
// Called directly from serial_link's UART RX task the instant a checksummed SERIAL_MSG_CAM_TX
// frame arrives - MUST be fast (documented in serial_link.h), so this only copies into a queue
// item and returns; the actual GeoNetworking-wrap + 802.11-wrap + radio TX happens in
// tx_radio_task below, off the UART parsing path entirely. xQueueSend with 0 timeout: if the
// radio task is somehow behind, drop this CAM rather than stall UART frame parsing - the next
// one is only ~1s (or less, at elevated rate) away regardless.
// Source Position Vector for the legacy SERIAL_MSG_CAM_TX path, which carries no position of its
// own. Everything here describes the bench, not the rider: a fixed point, standing still, at an
// unknown time, under a fixed address. That is exactly why the phone now sends CAM_TX_PV. Kept so
// an app that predates it still transmits what it always did, except that the station type now
// says cyclist to agree with the CAM inside.
static void legacy_lpv(gn_lpv_t *lpv)
{
memcpy(lpv->mac, LEGACY_MAC, sizeof(lpv->mac));
lpv->station_type = STATION_TYPE;
lpv->pai = false;
lpv->tst_ms = 0;
lpv->lat_tenmicrodeg = BENCH_LATITUDE_TENMICRODEG;
lpv->lon_tenmicrodeg = BENCH_LONGITUDE_TENMICRODEG;
lpv->speed_cms = 0;
lpv->heading_decideg = 0;
}
static void on_cam_tx_from_phone(const uint8_t *cam_uper, int cam_len)
{
if (cam_len <= 0 || cam_len > SERIAL_LINK_MAX_PAYLOAD) {
ESP_LOGW(TAG, "on_cam_tx_from_phone: bad length %d", cam_len);
return;
}
cam_tx_item_t item;
item.len = cam_len;
memcpy(item.data, cam_uper, (size_t)cam_len);
legacy_lpv(&item.lpv);
if (xQueueSend(s_tx_queue, &item, 0) != pdTRUE) {
ESP_LOGW(TAG, "tx queue full, dropping CAM from phone");
}
}
static uint16_t le16(const uint8_t *p)
{
return (uint16_t)(p[0] | (p[1] << 8));
}
static uint32_t le32(const uint8_t *p)
{
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
// SERIAL_MSG_CAM_TX_PV: the phone's CAM plus the position vector to send it under. The prefix
// layout is documented at SERIAL_MSG_CAM_TX_PV in serial_link.h. Same speed constraint as
// on_cam_tx_from_phone: decode, queue, return.
static void on_cam_tx_pv_from_phone(const uint8_t *prefix, const uint8_t *cam_uper, int cam_len)
{
if (cam_len <= 0 || cam_len > SERIAL_LINK_MAX_PAYLOAD) {
ESP_LOGW(TAG, "on_cam_tx_pv_from_phone: bad length %d", cam_len);
return;
}
cam_tx_item_t item;
item.len = cam_len;
memcpy(item.data, cam_uper, (size_t)cam_len);
memcpy(item.lpv.mac, prefix, sizeof(item.lpv.mac));
item.lpv.station_type = prefix[6];
item.lpv.pai = (prefix[7] & 0x01) != 0;
item.lpv.tst_ms = le32(prefix + 8);
item.lpv.lat_tenmicrodeg = (int32_t)le32(prefix + 12);
item.lpv.lon_tenmicrodeg = (int32_t)le32(prefix + 16);
item.lpv.speed_cms = (int16_t)le16(prefix + 20);
item.lpv.heading_decideg = le16(prefix + 22);
if (xQueueSend(s_tx_queue, &item, 0) != pdTRUE) {
ESP_LOGW(TAG, "tx queue full, dropping CAM from phone");
}
}
static void tx_radio_task(void *arg)
{
(void)arg;
cam_tx_item_t item;
while (1) {
if (xQueueReceive(s_tx_queue, &item, portMAX_DELAY) != pdTRUE) {
continue;
}
// static, not stack: these are sized off SERIAL_LINK_MAX_PAYLOAD (raised to 512), so on
// the stack they'd be ~1.2 KB of this task's 4 KB. Safe as statics - tx_radio_task is a
// singleton, created once in app_main. Both wrap functions bounds-check against the size
// passed in and return <= 0 on overflow, so an oversized CAM is rejected, not written past.
static uint8_t gn_payload[SERIAL_LINK_MAX_PAYLOAD + 64];
int gn_len = geonet_wrap_shb(item.data, item.len, &item.lpv,
BTP_PORT_CAM, gn_payload, sizeof(gn_payload));
if (gn_len <= 0) {
ESP_LOGW(TAG, "geonet_wrap_shb failed (cam_len=%d)", item.len);
continue;
}
static uint8_t frame[SERIAL_LINK_MAX_PAYLOAD + 192];
// Source address from the same lpv the GN header was built from, so the 802.11 and
// GeoNetworking layers always name the same sender, including across a pseudonym change.
int frame_len = dot11p_build_frame(gn_payload, gn_len, item.lpv.mac, frame,
sizeof(frame), false);
if (frame_len <= 0) {
ESP_LOGW(TAG, "dot11p_build_frame failed (gn_len=%d)", gn_len);
continue;
}
// Standard, well-tested raw-TX API with a non-QoS Data frame - same path validated
// during Phase 2 bring-up (see git history for the tx_custom.c A/B test that led here).
esp_err_t err = esp_wifi_80211_tx(WIFI_IF_STA, frame, frame_len, true);
if (err != ESP_OK) {
// Also counted into the heartbeat so the phone can see it - from the app's side a CAM
// that reached the radio but didn't go out otherwise looks identical to one that did.
serial_link_note_tx_failure();
ESP_LOGW(TAG, "esp_wifi_80211_tx failed: %d", err);
} else {
ESP_LOGI(TAG, "CAM sent (%d bytes) @ %d MHz", frame_len, TX_FREQ_MHZ);
}
}
}
// ============================================================================
// ---- RX path: air -> promiscuous cb -> queue -> forward task -> serial_link
// ============================================================================
// Promiscuous RX callbacks run in the WiFi driver's own task context and must stay short - so,
// same pattern as the TX side and as the reference sniffer firmware (cmd_sniffer.c's
// queue_packet), this just copies the frame and queues it; gn_unwrap_cam() and the serial write
// both happen in rx_forward_task instead.
// Capture buffer per queued frame. 800 bytes because real traffic is much larger than our own
// TX: a CiT One CAM measures 286-355 bytes on air and its GeoBroadcast DENM measures 528
// (measured 2026-08-17). The previous 400 silently truncated every DENM mid-payload, which no
// amount of correct unwrapping downstream could have recovered from. Raise this before adding
// MAPEM, which is larger again.
#define RX_FRAME_MAX_LEN 800
typedef struct {
uint8_t data[RX_FRAME_MAX_LEN];
int len;
int8_t rssi;
} rx_item_t;
static QueueHandle_t s_rx_queue;
static void wifi_promisc_rx_cb(void *recv_buf, wifi_promiscuous_pkt_type_t type)
{
if (type == WIFI_PKT_MISC) {
return; // no payload of interest, mirrors cmd_sniffer.c's handling
}
wifi_promiscuous_pkt_t *packet = (wifi_promiscuous_pkt_t *)recv_buf;
if (packet->rx_ctrl.rx_state) {
return; // frame had an error (mirrors cmd_sniffer.c)
}
#if CONFIG_SOC_WIFI_HE_SUPPORT
int length = packet->rx_ctrl.dump_len;
#else
int length = packet->rx_ctrl.sig_len - 4 /* FCS */;
#endif
if (length <= 0) {
return;
}
// static, NOT a local: at RX_FRAME_MAX_LEN this struct is ~800 bytes, and this callback runs
// on the WiFi driver's own task - already several frames deep in the driver's call chain, on a
// stack of roughly 3.5 KB (CONFIG_ESP_WIFI_TASK_STACK_SIZE, left at its default). Putting
// ~23% of that stack in one local is a stack-overflow risk that only bites under real traffic,
// i.e. in front of an RSU rather than on the bench.
//
// Safe as a static because the promiscuous callback is only ever invoked from that one task,
// so there is no re-entrancy to guard against - the same reasoning serial_link.c uses for its
// static send buffers. rx_forward_task has its own separate copy below.
static rx_item_t s_cb_item;
s_cb_item.len = length > (int)sizeof(s_cb_item.data) ? (int)sizeof(s_cb_item.data) : length;
memcpy(s_cb_item.data, packet->payload, (size_t)s_cb_item.len);
s_cb_item.rssi = packet->rx_ctrl.rssi;
// 0 timeout: never block the WiFi driver's own task waiting for queue space. xQueueSend copies
// the struct out before returning, so reusing s_cb_item on the next callback is fine. The
// return value used to go unchecked, so a full queue (rx_forward_task still draining a
// previous burst) silently ate frames with no counter anywhere - see
// serial_link_note_rx_queue_drop()'s KDoc.
if (xQueueSend(s_rx_queue, &s_cb_item, 0) != pdTRUE) {
serial_link_note_rx_queue_drop();
}
}
static void rx_forward_task(void *arg)
{
(void)arg;
// Same reasoning as the callback: ~800 bytes is a fifth of this task's 4 KB stack. Only this
// task touches it, and it is fully overwritten by xQueueReceive before every use.
static rx_item_t item;
while (1) {
if (xQueueReceive(s_rx_queue, &item, portMAX_DELAY) != pdTRUE) {
continue;
}
// Most promiscuously-captured frames are NOT ITS traffic we handle (management/control
// frames, other message types, our own loopback if the driver echoes it) - gn_unwrap_its
// returning false here is the common case, not an error, so it isn't logged per frame.
gn_rx_t rx;
if (gn_unwrap_its(item.data, item.len, &rx)) {
if (rx.truncated) {
// Longer than the RX_FRAME_MAX_LEN bytes captured above, so it cannot be forwarded
// whole - and at that size it could not cross the serial link either. Counted as
// an oversize drop, as it was when the cut-off frame still reached
// serial_link_send_v2x_rx() and failed the size check there.
serial_link_note_oversize_drop(rx.btp_dest_port);
continue;
}
serial_link_send_v2x_rx(rx.btp_dest_port, item.rssi,
rx.has_geo_area, rx.signed_unverified,
rx.geo_area_lat_tenmicrodeg,
rx.geo_area_lon_tenmicrodeg,
rx.geo_area_distance_a_m,
rx.payload, rx.payload_len);
}
}
}
// ============================================================================
void app_main(void)
{
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
s_tx_queue = xQueueCreate(4, sizeof(cam_tx_item_t));
s_rx_queue = xQueueCreate(8, sizeof(rx_item_t));
if (!s_tx_queue || !s_rx_queue) {
ESP_LOGE(TAG, "queue creation failed - halting");
return;
}
// Enable the modem FRONT-END 40 MHz clock BEFORE esp_wifi_init(). This is
// the one step the proven-working receiver firmware
// (its-g5-receiver-firmware_txenabled, main/main.c -> initialize_wifi())
// performs that this OBU was missing. Without the FE clock enabled the
// 5 GHz front-end / transmit chain is not fully clocked - which matches the
// exact symptom here: the radio calibrates (boot RF ping) and receives
// fine, but data frames are accepted by the API and never actually key the
// PA. This is a low-level modem_syscon register write via the HAL LL layer,
// copied verbatim from the reference firmware.
modem_syscon_ll_enable_fe_40m_clock(&MODEM_SYSCON, 1);
wifi_init_config_t wifi_cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&wifi_cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); // match reference initialize_wifi()
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_start());
// ---- Regulatory / TX-authorization override -----------------------------
// THE fix for "RX works but TX is silent". By default the driver uses
// WIFI_COUNTRY_POLICY_AUTO, whose 5 GHz regulatory table does NOT authorize
// transmit on the 5.9 GHz ITS band (and treats DFS channels as no-IR /
// radar-gated). Receiving is never gated - which is exactly why the sniffer
// hears traffic but our own frames never key the PA, and why the only RF
// seen from this board is the uninhibited PHY-calibration burst at boot.
//
// Switching to WIFI_COUNTRY_POLICY_MANUAL with an explicit 5 GHz channel
// mask (wifi_5g_channel_mask, which only takes effect under manual policy)
// tells the driver these channels are permitted and lifts the transmit
// gate. Manual policy = the operator asserts regulatory responsibility, which is
// appropriate for licensed/university research on the ITS band.
wifi_country_t ctry = {
.cc = "US", // nominal under manual policy
.schan = 1,
.nchan = 11,
.policy = WIFI_COUNTRY_POLICY_MANUAL,
.wifi_5g_channel_mask = 0x1FFFFFFE, // all 5 GHz channels, bits 1..28 (incl. 140 and 177)
};
esp_err_t ctry_err = esp_wifi_set_country(&ctry);
if (ctry_err != ESP_OK) {
ESP_LOGW(TAG, "esp_wifi_set_country(MANUAL) failed: %d (continuing)", ctry_err);
}
// Ensure the PA runs at full configured power (not a reduced regulatory
// default). Units are 0.25 dBm; 80 = 20 dBm, which is also the build's own
// ceiling (CONFIG_ESP_PHY_MAX_TX_POWER=20).
//
// Read back and logged, because the request is a ceiling and not a promise: the driver clamps
// it to its own calibrated power table, and our 5900 MHz is above the frequency range this
// chip is rated for (see docs/04-transmit-setup.md), so the table in use there is the one for
// channel 177. What the request alone tells you about radiated power is therefore nothing;
// this at least records what the driver admits to.
esp_err_t pw_err = esp_wifi_set_max_tx_power(80);
int8_t tx_power_q = 0;
if (pw_err != ESP_OK || esp_wifi_get_max_tx_power(&tx_power_q) != ESP_OK) {
ESP_LOGW(TAG, "tx power: set/read back failed (set returned %d), level unknown", pw_err);
} else {
ESP_LOGI(TAG, "tx power: %d quarter-dBm = %d.%02d dBm (20.00 requested)",
tx_power_q, tx_power_q / 4, (tx_power_q % 4) * 25);
}
// -------------------------------------------------------------------------
// Force the dual-band C5 onto its 5 GHz PHY. This MUST be called after
// esp_wifi_start() - calling it before returns ESP_ERR_WIFI_NOT_STARTED
// (0x3002 / 12290). Locking the band to 5G explicitly keeps the driver
// from ever falling back to 2.4 GHz ch1 (the old "stuck at primary=1"
// symptom), which would key the wrong PHY and make us inaudible to a
// 5.9 GHz sniffer/peer. Valid 5 GHz channels on the C5 are 36..177. Not
// ESP_ERROR_CHECK'd: log and continue if a given IDF build differs.
esp_err_t band_err = esp_wifi_set_band_mode(WIFI_BAND_MODE_5G_ONLY);
if (band_err != ESP_OK) {
ESP_LOGW(TAG, "esp_wifi_set_band_mode(5G_ONLY) failed: %d (continuing)", band_err);
}
// Disable Wi-Fi power save. An unassociated STA with the default
// WIFI_PS_MIN_MODEM power save sleeps its radio between beacons it will
// never receive (we're not joined to any AP), and drops outbound raw
// frames while asleep. Also matters for RX now: a sleeping radio misses
// incoming CAMs just as easily as it drops outbound ones. Must be called
// after esp_wifi_start().
ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
// Register the promiscuous RX callback BEFORE enabling promiscuous mode, so there's no
// window where promiscuous mode is on but nothing is registered to receive frames from it.
ESP_ERROR_CHECK(esp_wifi_set_promiscuous_rx_cb(wifi_promisc_rx_cb));
// Enable promiscuous mode. Doubles as the fix for raw-TX being silently dropped
// (ESP-IDF only actually emits raw frames when the MAC is promiscuous or associated to an
// AP - plain unassociated STA is neither) AND as what makes RX possible at all outside a
// joined BSS. One radio, one mode, both jobs - see file header comment.
ESP_ERROR_CHECK(esp_wifi_set_promiscuous(true));
// Force 802.11p OCB mode on the ITS-G5 channel, exactly like the working
// Rust reference (esp32-c_its-companion, src/radio.rs setup_wifi_sniffer):
// enable 802.11p, then jump straight to the target frequency. With band-mode
// already locked to 5 GHz above, NO esp_wifi_set_channel priming is needed -
// channel 180 (5900 MHz) isn't a normal Wi-Fi channel anyway. phy_change_channel
// takes the frequency in MHz.
ESP_LOGI(TAG, "about to call phy_11p_set...");
phy_11p_set(1, 0);
ESP_LOGI(TAG, "phy_11p_set returned, about to call phy_change_channel(%d)...", TX_FREQ_MHZ);
phy_change_channel(TX_FREQ_MHZ, 1, 0, 0);
ESP_LOGI(TAG, "phy_change_channel returned");
xTaskCreate(tx_radio_task, "tx_radio", 4096, NULL, 6, NULL);
xTaskCreate(rx_forward_task, "rx_forward", 4096, NULL, 5, NULL);
serial_link_init(on_cam_tx_from_phone, on_cam_tx_pv_from_phone);
ESP_LOGW(TAG, "OCB @ %d MHz - TX/RX armed, driven by serial_link (no on-chip TX timer)",
TX_FREQ_MHZ);
}
+1 -1
View File
@@ -1,7 +1,7 @@
// Sourced from OpenTrafficMap's its-g5-receiver-firmware_txenabled, main/tx_custom.c
// (https://codeberg.org/opentrafficmap/its-g5-receiver-firmware_txenabled, pinned commit
// 674e34128279235ba34c9f8d778f43cf1d075397, no stated license). Reproduced here as generated by
// implementation/external/vanetza-idf/ports/esp_idf/radio_c5.cmake (which hashes the upstream file
// implementation/firmware/components/microbu_v2x/radio_c5.cmake (which hashes the upstream file
// so this copy cannot silently drift) and checked in for readability. The struct layouts
// (x_eb_txdesc_t, x_middle_data_t, x_ebuf_t) and the bit-level manipulation of esp_wifi's private
// tx descriptor are OTM's own reverse engineering of the closed esp_wifi/libphy internals -- not
+41
View File
@@ -0,0 +1,41 @@
#pragma once
// ITS-G5 operating points from EN 302 571 conducted measurements on 2026-09-29.
#include <cmath>
#include <cstdint>
#include <optional>
namespace microbu::radio_policy {
/// Highest power setting (dBm, esp_wifi_set_max_tx_power) per declared carrier at which the
/// EN 302 571 Table 6 mask passed at MCS 2. Channels 172 and 184 are not declared: they exceed the
/// Table 5 out-of-band limit next to the band edge by about 20 dB at useful power.
struct Carrier {
std::uint16_t channel;
double max_power_dbm;
};
inline constexpr Carrier kDeclaredCarriers[] = {
{174, 18.0}, {176, 16.5}, {178, 18.0}, {180, 20.0}, {182, 16.5},
};
inline constexpr std::uint16_t kOperatingChannel = 180; // ITS-G5A CCH
inline constexpr double kMinPowerDbm = 2.0; // lowest esp_wifi power setting
/// The cap of a declared carrier; nothing for an undeclared channel.
inline std::optional<double> max_power_dbm(std::uint16_t channel) {
for (const auto& c : kDeclaredCarriers)
if (c.channel == channel) return c.max_power_dbm;
return std::nullopt;
}
/// True when the channel is declared and the power is a driver step (0.25 dB) within its range.
inline bool operating_point_allowed(std::uint16_t channel, double power_dbm) {
const auto cap = max_power_dbm(channel);
return cap && std::isfinite(power_dbm) && power_dbm >= kMinPowerDbm && power_dbm <= *cap &&
std::floor(power_dbm * 4) == power_dbm * 4;
}
/// Receiving emits nothing, so a receive-only radio may tune any ITS-G5 carrier (Table 2: 172-184).
inline bool receive_channel_allowed(std::uint16_t channel) {
return channel >= 172 && channel <= 184 && channel % 2 == 0;
}
} // namespace microbu::radio_policy
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <cstdint>
namespace microbu::capture_policy {
constexpr bool valid_mode(std::uint8_t mode) {
return !(mode & 0xF0);
}
constexpr std::uint8_t effective_mode(std::uint8_t mode) {
// Older clients may set bit 3. Capture never bypasses the receive stack.
return mode & 0x07;
}
}
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include "link_protocol.hpp"
#include <array>
#include <optional>
namespace microbu::link {
constexpr std::size_t maximum_request_body = 1536;
class RequestReassembly {
struct Stream {
bool used = false; unsigned origin = 0; Header header {};
Bytes bytes; std::size_t total = 0; std::uint64_t time = 0;
};
std::array<Stream, 8> streams_ {};
bool overflowed_ = false;
public:
bool take_overflow() { const bool was = overflowed_; overflowed_ = false; return was; }
std::optional<Message> feed(const Message& message, unsigned origin, std::uint64_t now_ms) {
for (auto& stream : streams_) if (stream.used && now_ms - stream.time > 2000) stream = {};
Stream* current = nullptr;
for (auto& stream : streams_) if (stream.used && stream.origin == origin &&
stream.header.opcode == message.header.opcode && stream.header.sequence == message.header.sequence) current = &stream;
const auto reject = [&]() -> std::optional<Message> { if (current) *current = {}; return {}; };
const auto flags = message.header.flags;
if (flags == 0) {
if (current) *current = {};
if (message.body.size() > maximum_request_body) { overflowed_ = true; return {}; }
return message;
}
if (flags > flag_fragment_last || message.body.size() <= fragment_header_size) return reject();
const auto& b = message.body;
const std::size_t total = b[0] | (std::size_t(b[1]) << 8);
const std::size_t offset = b[2] | (std::size_t(b[3]) << 8);
const std::size_t length = b.size() - fragment_header_size;
if (total > maximum_request_body) { overflowed_ = true; return reject(); }
if (total == 0 || offset + length > total ||
((flags == flag_fragment_last) != (offset + length == total))) return reject();
if (flags == flag_fragment_first) {
if (offset != 0) return reject();
if (!current) for (auto& stream : streams_) if (!stream.used) { current = &stream; break; }
if (!current) return {};
*current = {true, origin, message.header, {}, total, now_ms};
} else if (!current) return {};
if (current->total != total || current->bytes.size() != offset) return reject();
current->bytes.insert(current->bytes.end(), b.begin() + fragment_header_size, b.end());
current->time = now_ms;
if (flags != flag_fragment_last) return {};
Message complete {current->header, std::move(current->bytes)};
complete.header.flags = 0; *current = {};
return complete;
}
};
}
-337
View File
@@ -1,337 +0,0 @@
#include "serial_link.h"
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/usb_serial_jtag.h"
#include "esp_log.h"
static const char *TAG = "serial_link";
#define SYNC0 0xAA
#define SYNC1 0x55
static serial_link_cam_tx_cb_t s_on_cam_tx;
static serial_link_cam_tx_pv_cb_t s_on_cam_tx_pv;
// ---- Counters reported to the phone in every heartbeat (see SERIAL_MSG_STATUS in the header).
// Saturating rather than wrapping: "65535 drops" reads as "lots and still going", whereas a wrap
// back to a small number during a long bench run reads as "the problem went away".
static uint16_t s_oversize_drops;
static uint16_t s_tx_failures;
static uint16_t s_rx_crc_errors;
static uint16_t s_rx_queue_drops;
// Serializes send_frame(): it writes a frame as four separate usb_serial_jtag_write_bytes() calls
// and shares one static CRC scratch buffer, and it's now called from three tasks (rx_forward for
// CAM_RX, the heartbeat task for STATUS, and potentially others). Without this, two frames could
// interleave on the wire and both would be discarded by the phone's framer.
static SemaphoreHandle_t s_tx_mutex;
static inline void bump(uint16_t *counter)
{
if (*counter < 0xFFFF) (*counter)++;
}
void serial_link_note_tx_failure(void)
{
bump(&s_tx_failures);
}
void serial_link_note_oversize_drop(uint16_t btp_dest_port)
{
bump(&s_oversize_drops);
ESP_LOGW(TAG, "port %u message larger than the RX capture buffer, total oversize drops %u",
btp_dest_port, s_oversize_drops);
}
void serial_link_note_rx_queue_drop(void)
{
bump(&s_rx_queue_drops);
ESP_LOGW(TAG, "rx queue full, dropped a captured frame, total rx queue drops %u", s_rx_queue_drops);
}
// ---- CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflect, no xorout) ----
// Bytewise (no table) - frames here are at most SERIAL_LINK_MAX_PAYLOAD + 3 bytes, so table
// lookup isn't worth the flash/RAM tradeoff. MUST match the Kotlin-side implementation exactly
// (see app SerialFrame.kt) or every frame will be silently rejected as corrupt.
static uint16_t crc16_ccitt_false(const uint8_t *data, size_t len)
{
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < len; i++) {
crc ^= (uint16_t)data[i] << 8;
for (int b = 0; b < 8; b++) {
crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
}
}
return crc;
}
static bool send_frame(uint8_t type, const uint8_t *payload, int len)
{
if (len < 0 || len > SERIAL_LINK_MAX_PAYLOAD) {
ESP_LOGW(TAG, "send_frame: payload too large (%d)", len);
return false;
}
// type(1) + length(2) + payload(len) is what the CRC covers.
uint8_t head[3];
head[0] = type;
head[1] = (uint8_t)(len & 0xFF);
head[2] = (uint8_t)((len >> 8) & 0xFF);
// Concatenate head+payload to CRC them in one pass. static, not stack: at
// SERIAL_LINK_MAX_PAYLOAD = 512 this buffer is 515 bytes, which is a meaningful bite out of a
// 4 KB task stack, and send_frame() is called from several tasks. Guarded by s_tx_mutex below
// so the shared buffer (and the four-part write) can't interleave between callers.
static uint8_t s_crc_buf[3 + SERIAL_LINK_MAX_PAYLOAD];
// No host on the other end: the TX buffer never drains, so every write below would block its
// full timeout and this frame is going nowhere regardless. Bail before taking the mutex -
// otherwise a burst of promiscuously-captured CAMs holds the lock for hundreds of ms each and
// starves the heartbeat, which is exactly what "tx mutex timeout, dropping frame" was.
if (!usb_serial_jtag_is_connected()) {
return false;
}
// Timeout must exceed the worst-case hold below (4 writes x SERIAL_LINK_WRITE_TIMEOUT_MS),
// or a legitimately slow-but-working host makes contending senders drop frames instead of
// waiting their turn.
if (s_tx_mutex && xSemaphoreTake(s_tx_mutex, pdMS_TO_TICKS(SERIAL_LINK_TX_LOCK_TIMEOUT_MS)) != pdTRUE) {
ESP_LOGW(TAG, "send_frame: tx mutex timeout, dropping frame");
return false;
}
memcpy(s_crc_buf, head, 3);
if (len > 0) memcpy(s_crc_buf + 3, payload, (size_t)len);
uint16_t crc = crc16_ccitt_false(s_crc_buf, (size_t)(3 + len));
uint8_t sync[2] = {SYNC0, SYNC1};
uint8_t crc_bytes[2] = {(uint8_t)(crc & 0xFF), (uint8_t)((crc >> 8) & 0xFF)};
// Four separate writes rather than one assembled buffer - simplest given payload is
// already wherever the caller has it (avoids a second copy of up to 160 bytes).
// usb_serial_jtag_write_bytes() blocks up to the given tick timeout if the host isn't
// reading fast enough; generous for a single frame at USB full-speed, and keeps a wedged
// host from hanging the radio TX/RX tasks indefinitely.
const TickType_t write_timeout = pdMS_TO_TICKS(SERIAL_LINK_WRITE_TIMEOUT_MS);
int wrote = 0;
wrote += usb_serial_jtag_write_bytes(sync, sizeof(sync), write_timeout);
wrote += usb_serial_jtag_write_bytes(head, sizeof(head), write_timeout);
if (len > 0) wrote += usb_serial_jtag_write_bytes(payload, (size_t)len, write_timeout);
wrote += usb_serial_jtag_write_bytes(crc_bytes, sizeof(crc_bytes), write_timeout);
if (s_tx_mutex) xSemaphoreGive(s_tx_mutex);
return wrote == (int)(sizeof(sync) + sizeof(head) + len + sizeof(crc_bytes));
}
bool serial_link_send_v2x_rx(uint16_t btp_dest_port, int8_t rssi,
bool has_geo_area, bool signed_unverified,
int32_t geo_area_lat_tenmicrodeg,
int32_t geo_area_lon_tenmicrodeg,
uint16_t geo_area_distance_a_m,
const uint8_t *uper, int uper_len)
{
if (uper_len < 0 || uper_len > SERIAL_LINK_MAX_PAYLOAD - SERIAL_V2X_RX_PREFIX_LEN) {
// Counted, not just logged: this log line goes to the flashing port, which nobody is
// watching during a phone bench session - so the symptom would be "that station just
// never shows up in the app" with no visible cause.
bump(&s_oversize_drops);
ESP_LOGW(TAG, "send_v2x_rx: port %u payload too large (%d), total oversize drops %u",
btp_dest_port, uper_len, s_oversize_drops);
return false;
}
// static, not stack (526 bytes at MAX_PAYLOAD 512); only rx_forward_task calls this, and
// send_frame's mutex covers the handoff onto the wire.
static uint8_t s_v2x_payload[SERIAL_LINK_MAX_PAYLOAD];
// Little-endian prefix, layout documented in serial_link.h - keep in lockstep with the app's
// SerialFrame.kt.
s_v2x_payload[0] = (uint8_t)(btp_dest_port & 0xFF);
s_v2x_payload[1] = (uint8_t)((btp_dest_port >> 8) & 0xFF);
s_v2x_payload[2] = (uint8_t)rssi;
s_v2x_payload[3] = (uint8_t)((has_geo_area ? 0x01 : 0x00) | (signed_unverified ? 0x02 : 0x00));
uint32_t lat = (uint32_t)geo_area_lat_tenmicrodeg;
uint32_t lon = (uint32_t)geo_area_lon_tenmicrodeg;
s_v2x_payload[4] = (uint8_t)(lat & 0xFF);
s_v2x_payload[5] = (uint8_t)((lat >> 8) & 0xFF);
s_v2x_payload[6] = (uint8_t)((lat >> 16) & 0xFF);
s_v2x_payload[7] = (uint8_t)((lat >> 24) & 0xFF);
s_v2x_payload[8] = (uint8_t)(lon & 0xFF);
s_v2x_payload[9] = (uint8_t)((lon >> 8) & 0xFF);
s_v2x_payload[10] = (uint8_t)((lon >> 16) & 0xFF);
s_v2x_payload[11] = (uint8_t)((lon >> 24) & 0xFF);
s_v2x_payload[12] = (uint8_t)(geo_area_distance_a_m & 0xFF);
s_v2x_payload[13] = (uint8_t)((geo_area_distance_a_m >> 8) & 0xFF);
if (uper_len > 0) memcpy(s_v2x_payload + SERIAL_V2X_RX_PREFIX_LEN, uper, (size_t)uper_len);
return send_frame(SERIAL_MSG_V2X_RX, s_v2x_payload, SERIAL_V2X_RX_PREFIX_LEN + uper_len);
}
bool serial_link_send_status(uint8_t status)
{
// [status:1][oversize_drops:2 LE][tx_failures:2 LE][rx_crc_errors:2 LE][capabilities:1]
// [rx_queue_drops:2 LE] - keep in lockstep with EspLinkStatus.parse() in the app's
// SerialFrame.kt.
uint8_t payload[10];
payload[0] = status;
payload[1] = (uint8_t)(s_oversize_drops & 0xFF);
payload[2] = (uint8_t)((s_oversize_drops >> 8) & 0xFF);
payload[3] = (uint8_t)(s_tx_failures & 0xFF);
payload[4] = (uint8_t)((s_tx_failures >> 8) & 0xFF);
payload[5] = (uint8_t)(s_rx_crc_errors & 0xFF);
payload[6] = (uint8_t)((s_rx_crc_errors >> 8) & 0xFF);
// What this firmware accepts. The app reads it to decide whether it may send CAM_TX_PV, which
// is what lets a new app keep working against firmware that predates that message.
payload[7] = SERIAL_CAP_CAM_TX_PV;
payload[8] = (uint8_t)(s_rx_queue_drops & 0xFF);
payload[9] = (uint8_t)((s_rx_queue_drops >> 8) & 0xFF);
return send_frame(SERIAL_MSG_STATUS, payload, sizeof(payload));
}
// 1 Hz heartbeat. This is what lets the phone tell "link alive, radio quiet" from "link dead" -
// the app's watchdog (UsbSerialTransport.kt) marks the link ERROR after 3 missed beats. Keep the
// period in step with LINK_TIMEOUT_MS over there.
static void status_task(void *arg)
{
(void)arg;
while (1) {
serial_link_send_status(0);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
// ---- RX framing state machine ----
// Runs in its own task, byte-at-a-time off the USB Serial/JTAG driver's RX ring buffer (via
// usb_serial_jtag_read_bytes with a short timeout, not raw ISR access - simplest correct option
// for a link this slow/small; revisit if CAM traffic volume ever makes this a bottleneck).
typedef enum {
WAIT_SYNC0,
WAIT_SYNC1,
WAIT_TYPE,
WAIT_LEN_LO,
WAIT_LEN_HI,
WAIT_PAYLOAD,
WAIT_CRC_LO,
WAIT_CRC_HI,
} rx_state_t;
static void rx_task(void *arg)
{
(void)arg;
rx_state_t state = WAIT_SYNC0;
uint8_t type = 0;
uint16_t len = 0;
uint16_t payload_idx = 0;
uint16_t crc_recv = 0;
// static, not stack: at SERIAL_LINK_MAX_PAYLOAD = 512 these two are >1 KB together, a quarter
// of this task's 4 KB stack. Safe as statics because rx_task is a singleton - one instance,
// created once in serial_link_init().
static uint8_t payload[SERIAL_LINK_MAX_PAYLOAD];
static uint8_t crc_buf[3 + SERIAL_LINK_MAX_PAYLOAD];
uint8_t byte;
while (1) {
int n = usb_serial_jtag_read_bytes(&byte, 1, pdMS_TO_TICKS(50));
if (n <= 0) continue;
switch (state) {
case WAIT_SYNC0:
state = (byte == SYNC0) ? WAIT_SYNC1 : WAIT_SYNC0;
break;
case WAIT_SYNC1:
state = (byte == SYNC1) ? WAIT_TYPE : (byte == SYNC0 ? WAIT_SYNC1 : WAIT_SYNC0);
break;
case WAIT_TYPE:
type = byte;
state = WAIT_LEN_LO;
break;
case WAIT_LEN_LO:
len = byte;
state = WAIT_LEN_HI;
break;
case WAIT_LEN_HI:
len |= (uint16_t)byte << 8;
if (len > SERIAL_LINK_MAX_PAYLOAD) {
ESP_LOGW(TAG, "rx: length %u exceeds max, resyncing", len);
state = WAIT_SYNC0; // can't trust this frame boundary at all - drop to resync
} else if (len == 0) {
payload_idx = 0;
state = WAIT_CRC_LO;
} else {
payload_idx = 0;
state = WAIT_PAYLOAD;
}
break;
case WAIT_PAYLOAD:
payload[payload_idx++] = byte;
if (payload_idx >= len) state = WAIT_CRC_LO;
break;
case WAIT_CRC_LO:
crc_recv = byte;
state = WAIT_CRC_HI;
break;
case WAIT_CRC_HI: {
crc_recv |= (uint16_t)byte << 8;
crc_buf[0] = type;
crc_buf[1] = (uint8_t)(len & 0xFF);
crc_buf[2] = (uint8_t)((len >> 8) & 0xFF);
if (len > 0) memcpy(crc_buf + 3, payload, len);
uint16_t crc_calc = crc16_ccitt_false(crc_buf, (size_t)(3 + len));
if (crc_calc == crc_recv) {
if (type == SERIAL_MSG_CAM_TX) {
if (s_on_cam_tx) s_on_cam_tx(payload, len);
} else if (type == SERIAL_MSG_CAM_TX_PV) {
// A frame that is all prefix has nothing to transmit.
if (len > SERIAL_CAM_TX_PV_PREFIX_LEN) {
if (s_on_cam_tx_pv) {
s_on_cam_tx_pv(payload, payload + SERIAL_CAM_TX_PV_PREFIX_LEN,
len - SERIAL_CAM_TX_PV_PREFIX_LEN);
}
} else {
ESP_LOGW(TAG, "rx: CAM_TX_PV of %u bytes carries no CAM, ignoring", len);
}
} else {
ESP_LOGW(TAG, "rx: unexpected frame type 0x%02x from phone, ignoring", type);
}
} else {
bump(&s_rx_crc_errors);
ESP_LOGW(TAG, "rx: CRC mismatch (got %04x want %04x), dropping frame (total %u)",
crc_recv, crc_calc, s_rx_crc_errors);
}
state = WAIT_SYNC0;
break;
}
}
}
}
void serial_link_init(serial_link_cam_tx_cb_t on_cam_tx,
serial_link_cam_tx_pv_cb_t on_cam_tx_pv)
{
s_on_cam_tx = on_cam_tx;
s_on_cam_tx_pv = on_cam_tx_pv;
s_tx_mutex = xSemaphoreCreateMutex();
if (!s_tx_mutex) {
// Fail loudly rather than silently running unserialized: interleaved frames would look
// like random CRC errors on the phone, which is a miserable thing to debug.
ESP_LOGE(TAG, "failed to create tx mutex");
abort();
}
usb_serial_jtag_driver_config_t cfg = {
.tx_buffer_size = SERIAL_LINK_USB_BUF_SIZE,
.rx_buffer_size = SERIAL_LINK_USB_BUF_SIZE,
};
ESP_ERROR_CHECK(usb_serial_jtag_driver_install(&cfg));
xTaskCreate(rx_task, "serial_link_rx", 4096, NULL, 6, NULL);
xTaskCreate(status_task, "serial_link_status", 2560, NULL, 4, NULL);
ESP_LOGI(TAG, "serial_link up on native USB Serial/JTAG (VID 0x303A / PID 0x1001), "
"max payload %d, 1 Hz heartbeat", SERIAL_LINK_MAX_PAYLOAD);
}
+36 -20
View File
@@ -1,14 +1,14 @@
#include "serial_link.hpp"
#include "sdkconfig.h"
#include <driver/usb_serial_jtag.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <algorithm>
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <atomic>
#include <cstring>
namespace microbu::serial {
@@ -77,25 +77,26 @@ namespace {
SemaphoreHandle_t writer_lock = nullptr;
Counters the_counters;
Decoder::Handler frame_handler;
std::atomic<std::uint32_t> last_frame_at_ms {0}; // 32-bit: no libatomic needed on RV32
#if CONFIG_MICROBU_LOG_OVER_LINK
vprintf_like_t previous_vprintf = nullptr;
#endif
bool write_all(const Bytes& frame) {
// A host that has the port enumerated but does not read lets the TX buffer fill. Waiting 500 ms per
// frame then stalled every logging task, the BLE host included, and delayed the phone's requests by a
// minute (2026-10-05). After a timeout the serial side counts as stalled: frames are dropped at once,
// one short probe per second finds a host that reads again, and any received byte ends the stall.
std::atomic<bool> stalled {false};
std::atomic<std::uint32_t> last_frame_at_ms {0}; // MicrOBU: 32-bit, no libatomic needed on RV32
std::atomic<std::int64_t> next_probe_us {0};
bool write_all(const Bytes& frame, TickType_t timeout) {
std::size_t sent = 0;
while (sent < frame.size()) {
// MicrOBU: 50 ms, not the colleague's 500. A phone that is plugged in but not reading (app
// not running) fills the driver's buffer, and every write then waits out this timeout on
// the station task, which also serves BLE and the radio.
const int count = usb_serial_jtag_write_bytes(frame.data() + sent, frame.size() - sent, pdMS_TO_TICKS(50));
const int count = usb_serial_jtag_write_bytes(frame.data() + sent, frame.size() - sent, timeout);
if (count <= 0) return false; // the host detects an incomplete frame by CRC
sent += count;
}
return true;
}
#if CONFIG_MICROBU_LOG_OVER_LINK
// ESP_LOG sink: one LOG frame per call, never a raw write into the frame stream.
int log_to_frame(const char* format, va_list args) {
char line[256];
@@ -104,11 +105,10 @@ int log_to_frame(const char* format, va_list args) {
std::size_t n = static_cast<std::size_t>(length) < sizeof line ? length : sizeof line - 1;
while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) --n;
if (n == 0) return length;
// esp_log colour escapes are stripped by the emulator; keep the line verbatim otherwise.
// esp_log colour escapes are stripped by the host; keep the line verbatim otherwise.
write(FrameType::LOG, Bytes(line, line + n));
return length;
}
#endif
void reader_task(void*) {
Decoder decoder;
@@ -116,6 +116,7 @@ void reader_task(void*) {
for (;;) {
const int count = usb_serial_jtag_read_bytes(buffer, sizeof buffer, pdMS_TO_TICKS(20));
if (count > 0) {
stalled = false;
decoder.feed(buffer, static_cast<std::size_t>(count), [](Frame frame) {
last_frame_at_ms = static_cast<std::uint32_t>(esp_timer_get_time() / 1000);
frame_handler(std::move(frame));
@@ -134,25 +135,40 @@ void start(const Decoder::Handler& on_frame) {
config.rx_buffer_size = 8192;
config.tx_buffer_size = 8192;
ESP_ERROR_CHECK(usb_serial_jtag_driver_install(&config));
#if CONFIG_MICROBU_LOG_OVER_LINK
previous_vprintf = esp_log_set_vprintf(log_to_frame);
#endif
xTaskCreate(reader_task, "link_rx", 6144, nullptr, 12, nullptr);
}
bool write(FrameType type, const Bytes& payload) {
if (payload.size() > maximum_payload || !writer_lock) return false;
// MicrOBU: nothing on the native port (phone on BLE, or unplugged). Without this check every
// write, the 1 Hz STATUS included, would block the station task until the timeout.
if (!usb_serial_jtag_is_connected()) { ++the_counters.not_connected; return false; }
// MicrOBU: nothing on the native port (phone on BLE, or unplugged): do not even try, or the first
// write after every pause waits out the timeout on the station task.
if (!usb_serial_jtag_is_connected()) { ++the_counters.write_failures; return false; }
TickType_t timeout = pdMS_TO_TICKS(500);
if (stalled) {
const auto now = esp_timer_get_time();
if (now < next_probe_us) { ++the_counters.write_failures; return false; }
next_probe_us = now + 1000000;
timeout = std::max<TickType_t>(1, pdMS_TO_TICKS(20));
}
const auto frame = encode_frame(type, payload);
if (xSemaphoreTake(writer_lock, pdMS_TO_TICKS(1000)) != pdTRUE) { ++the_counters.write_failures; return false; }
const bool ok = write_all(frame);
if (xSemaphoreTake(writer_lock, stalled ? 0 : pdMS_TO_TICKS(1000)) != pdTRUE) { ++the_counters.write_failures; return false; }
const bool ok = write_all(frame, timeout);
stalled = !ok;
xSemaphoreGive(writer_lock);
if (!ok) ++the_counters.write_failures;
return ok;
}
bool try_write(FrameType type, const Bytes& payload) {
if (payload.size() > maximum_payload || !writer_lock || stalled) return false;
const auto frame = encode_frame(type, payload);
if (xSemaphoreTake(writer_lock, 0) != pdTRUE) return false;
const bool queued = usb_serial_jtag_write_bytes(frame.data(), frame.size(), 0) == static_cast<int>(frame.size());
xSemaphoreGive(writer_lock);
return queued;
}
Counters counters() { return the_counters; }
std::uint32_t last_frame_ms() { return last_frame_at_ms.load(); }
-180
View File
@@ -1,180 +0,0 @@
#ifndef SERIAL_LINK_H
#define SERIAL_LINK_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
// Binary framing for the phone <-> ESP32-C5 link (Phase 03). This runs over the ESP32-C5's
// native USB Serial/JTAG peripheral (driver/usb_serial_jtag.h) - the same physical USB-C port
// used for JTAG, exposed to the host as a fixed-VID/PID (0x303A/0x1001) USB CDC-ACM device.
// Deliberately NOT the same wire as the ESP-IDF console/ESP_LOG output, which stays on the
// OTHER USB-C port (the UART-bridge one, UART0, see sdkconfig CONFIG_ESP_CONSOLE_UART_NUM=0) -
// mixing binary frames with human-readable log text on one wire would corrupt both, and this
// way they're physically separate ports so there's no risk of that regardless.
//
// On the Android side, connect the phone (via USB-OTG) to the board's NATIVE USB-C port, not
// the UART-bridge/flashing port. The usb-serial-for-android library's default prober doesn't
// know Espressif's 0x303A/0x1001 VID/PID, so UsbSerialTransport.kt registers it manually via a
// custom ProbeTable pointed at CdcAcmSerialDriver - see that file's KDoc.
//
// Frame format (both directions, symmetric):
// [0xAA][0x55][type:1][length:2 LE][payload: length bytes][crc16:2 LE]
// CRC16 is CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflect, no xorout), computed over
// type + length + payload only (not the two sync bytes). Same algorithm must be used on the
// Kotlin side (see app SerialFrame.kt) - frames that don't checksum are silently dropped.
//
// Direction / types:
// SERIAL_MSG_CAM_TX (0x01), phone -> ESP32: payload is a raw CAM UPER byte string, already
// built by the phone (position/speed/heading/yaw rate baked in). On receipt the ESP32
// immediately GeoNetworking-wraps and transmits it - this IS the transmit clock now, there
// is no independent on-chip timer. See main.c's rx-driven tx path.
// SERIAL_MSG_CAM_RX (0x02), ESP32 -> phone: SUPERSEDED by SERIAL_MSG_V2X_RX, no longer sent.
// The constant is kept so the numbering is not silently reused by a future message type.
// SERIAL_MSG_V2X_RX (0x04), ESP32 -> phone: any ITS message received over the air, already
// stripped of its 802.11/LLC-SNAP/GeoNetworking/BTP-B framing by gn_unwrap.c - the phone
// never sees raw 802.11 frames. Payload is a fixed 14-byte prefix followed by the UPER bytes:
//
// [0..1] btp_dest_port uint16 LE 2001 = CAM, 2002 = DENM (ETSI TS 103 248)
// [2] rssi int8 dBm, from the promiscuous RX metadata
// [3] flags uint8 bit0: geo area fields below are valid
// bit1: arrived signed (TS 103 097), signature NOT
// verified. An app that tests only bit0 ignores it.
// [4..7] geo_area_lat int32 LE 1/10 microdegree, GeoBroadcast destination area
// [8..11] geo_area_lon int32 LE 1/10 microdegree
// [12..13] geo_area_dist uint16 LE Distance A, metres (relevance radius for a circle)
// [14..] UPER message bytes - exactly the message. Before 2026-09-11 they were followed by
// the 8 bytes the chip's promiscuous RX appends (gn_unwrap.h, "Payload bounds").
//
// All prefix fields are LITTLE-endian, matching this framing's own length field - note the
// GeoNetworking wire format they came from is big-endian, so gn_unwrap.c converts.
// Generic on purpose: adding MAPEM/SPATEM later needs a decoder on the phone and one port in
// gn_unwrap.c, but no change to this protocol. No station id is carried separately - each
// message's own ItsPduHeader.stationID is the meaningful identifier.
// SERIAL_MSG_STATUS (0x03), ESP32 -> phone: heartbeat + counters, sent at 1 Hz so the phone can
// distinguish "link idle" from "link dead" independent of CAM traffic (the app's watchdog in
// UsbSerialTransport.kt declares the link dead after 3 missed beats). Payload is 10 bytes:
// [status:1][oversize_drops:2 LE][tx_failures:2 LE][rx_crc_errors:2 LE][capabilities:1]
// [rx_queue_drops:2 LE]
// status 0 = ok. The counters are free-running totals since boot, saturating at 0xFFFF.
// capabilities is a bitmask of the SERIAL_CAP_* flags below. It was appended as byte 7 rather
// than inserted, so an app that predates it, and reads only the first 7 bytes, is unaffected;
// rx_queue_drops (bytes 8-9) follows the same rule for an app that predates it. Either side
// reading a payload shorter than the field it wants should treat that field as 0, not error.
// They exist because the alternative - ESP_LOGW on the flashing port - is invisible to the
// phone, which is the only thing watching during a bench session. Mirrored by EspLinkStatus
// in the app's SerialFrame.kt.
#define SERIAL_MSG_CAM_TX 0x01
#define SERIAL_MSG_CAM_RX 0x02
#define SERIAL_MSG_STATUS 0x03
#define SERIAL_MSG_V2X_RX 0x04
#define SERIAL_MSG_CAM_TX_PV 0x05
// Size of the V2X_RX prefix documented above. Must match the app's SerialFrame.kt.
#define SERIAL_V2X_RX_PREFIX_LEN 14
// SERIAL_MSG_CAM_TX_PV (0x05), phone -> ESP32: a CAM together with the GeoNetworking Source
// Position Vector to transmit it under. Payload is a fixed 24-byte prefix, then the CAM UPER:
//
// [0..5] mac 6 bytes pseudonym: the 802.11 source address AND the GN_ADDR MID
// [6] station_type uint8 TS 102 894-2 StationType (2 = cyclist)
// [7] flags uint8 bit0: PAI, position accuracy indicator
// [8..11] tst uint32 LE ms at which lat/lon were acquired, TimestampIts mod 2^32
// [12..15] lat int32 LE 1/10 microdegree
// [16..19] lon int32 LE 1/10 microdegree
// [20..21] speed int16 LE 0.01 m/s
// [22..23] heading uint16 LE 0.1 degree from north, clockwise, 0..3599
// [24..] CAM UPER bytes
//
// Little-endian like the rest of this framing; geonet.c converts to GeoNetworking's big-endian.
// Every prefix field is something the phone already has when it builds the CAM, and none of it
// can be known on this chip, which has no GNSS and no clock source on the OCB channel. Before
// this message existed the GN header carried fixed placeholders instead (see main.c).
//
// A new type rather than a redefined CAM_TX, so app and firmware can be updated independently:
// - old app, new firmware: the app sends CAM_TX, which is handled exactly as before.
// - new app, old firmware: the app sends CAM_TX_PV only once the heartbeat advertises
// SERIAL_CAP_CAM_TX_PV, and an old heartbeat carries no such bit, so it stays on CAM_TX.
// Redefining CAM_TX would instead have double-wrapped every frame in one of those combinations
// and sent one with no GN header in the other, silently, since neither side checks versions.
#define SERIAL_CAM_TX_PV_PREFIX_LEN 24
// Capability bits, carried in byte 7 of the SERIAL_MSG_STATUS payload.
#define SERIAL_CAP_CAM_TX_PV 0x01
// USB Serial/JTAG has no baud rate or GPIO pins to configure - it's a fixed on-chip USB device
// controller wired directly to the native USB-C port's D+/D- lines in silicon. RX/TX buffer
// sizes for usb_serial_jtag_driver_install() (see serial_link.c) are sized generously relative
// to SERIAL_LINK_MAX_PAYLOAD below.
#define SERIAL_LINK_USB_BUF_SIZE 1024
// Per-write block ceiling, and the mutex acquire timeout that must comfortably exceed the
// worst case of one frame (4 writes: sync, head, payload, crc). Keep that relationship if you
// change either number - a lock timeout below the max hold turns normal contention into
// dropped frames, which is how the heartbeat was being starved by forwarded CAM_RX traffic.
#define SERIAL_LINK_WRITE_TIMEOUT_MS 100
#define SERIAL_LINK_TX_LOCK_TIMEOUT_MS 600
// Max CAM payload this link will carry. MUST match SERIAL_LINK_MAX_PAYLOAD in the app's
// SerialFrame.kt - a mismatch means every frame above the smaller of the two is rejected by that
// side's "length exceeds max, resync" branch, silently.
//
// Raised from 160 to 512: 160 was reasoned from cam.c's 96-byte encode buffer, which only ever
// described OUR OWN minimal CAM. A third-party CAM off the air carrying a path-history or
// special-vehicle container comfortably exceeds it, and those stations would then never reach the
// phone at all. 512 clears any realistic CAM. Our own CAM is 43 bytes of UPER.
//
// This, not the radio side, is the ceiling on the RX path. main.c captures up to RX_FRAME_MAX_LEN
// (800) bytes per frame, sized for the CiT One's 528-byte DENM, so a larger ITS payload
// does arrive here. serial_link_send_v2x_rx() then drops anything above this minus its 14-byte
// prefix and counts it in the heartbeat's oversize-drop counter.
#define SERIAL_LINK_MAX_PAYLOAD 512
// Initializes the USB Serial/JTAG driver and its background RX-framing and 1 Hz heartbeat tasks.
// Call once from app_main, after nvs/event loop init. Both callbacks run in the RX task's context,
// so keep them fast: they block the next frame's parsing.
// on_cam_tx a complete, checksummed SERIAL_MSG_CAM_TX frame: bare CAM UPER.
// on_cam_tx_pv a complete, checksummed SERIAL_MSG_CAM_TX_PV frame, already checked to carry at
// least one CAM byte after its prefix: the 24-byte prefix, then the CAM UPER.
typedef void (*serial_link_cam_tx_cb_t)(const uint8_t *cam_uper, int cam_len);
typedef void (*serial_link_cam_tx_pv_cb_t)(const uint8_t *prefix,
const uint8_t *cam_uper, int cam_len);
void serial_link_init(serial_link_cam_tx_cb_t on_cam_tx,
serial_link_cam_tx_pv_cb_t on_cam_tx_pv);
// Sends a SERIAL_MSG_V2X_RX frame: the metadata prefix plus the UPER bytes gn_unwrap.c extracted
// from an over-the-air frame. Pass has_geo_area=false and zeroes for the area fields when the
// source frame carried no destination area (i.e. it was single-hop broadcast, not GeoBroadcast).
// signed_unverified is gn_rx_t's flag of the same name; it sets bit1 of the prefix flags.
// Returns true if the frame was written to the USB endpoint - not an end-to-end ack, the phone
// may still drop it.
bool serial_link_send_v2x_rx(uint16_t btp_dest_port, int8_t rssi,
bool has_geo_area, bool signed_unverified,
int32_t geo_area_lat_tenmicrodeg,
int32_t geo_area_lon_tenmicrodeg,
uint16_t geo_area_distance_a_m,
const uint8_t *uper, int uper_len);
// Sends one SERIAL_MSG_STATUS heartbeat frame immediately (status byte + the current counters).
// Normally unnecessary to call by hand - serial_link_init() starts a task that does this at 1 Hz.
bool serial_link_send_status(uint8_t status);
// Records a failed esp_wifi_80211_tx() so it shows up in the next heartbeat's tx_failures
// counter. Called from main.c's tx_radio_task - a CAM that reached the radio but didn't go out is
// otherwise indistinguishable, from the phone's side, from one that transmitted fine.
void serial_link_note_tx_failure(void);
// Counts an ITS message that cannot be forwarded because it is too large, in the same heartbeat
// counter serial_link_send_v2x_rx() uses for its own size check. For main.c's rx_forward_task,
// whose capture buffer is smaller than the largest frames on air.
void serial_link_note_oversize_drop(uint16_t btp_dest_port);
// Counts a promiscuously-captured frame that main.c's wifi_promisc_rx_cb() could not hand to
// rx_forward_task because s_rx_queue was full - i.e. frames arrived faster than the forward task
// (gn_unwrap + a blocking USB write, up to SERIAL_LINK_WRITE_TIMEOUT_MS x 4 per frame under
// contention) could drain them. Unlike oversize_drop this is not about one frame's size; it is
// about a burst of otherwise-forwardable frames. Previously silent - xQueueSend's return value
// was not even checked - so a run of these had no visible symptom beyond "that station's CAM
// count looked a little low."
void serial_link_note_rx_queue_drop(void);
#endif
+11 -11
View File
@@ -1,9 +1,9 @@
#pragma once
// Serial transport of the station-internal link over the ESP32-C5 native USB Serial/JTAG port.
// Framing is the app's Phase 03 one: [AA][55][type][len LE][payload][crc16 LE] with
// CRC-16/CCITT-FALSE over type+len+payload (implementation/station-link/README.md, "Serial").
// One writer serialises complete frames. The byte stream never carries plain text: ESP_LOG stays on
// UART0 here, or travels as LOG frames with CONFIG_MICROBU_LOG_OVER_LINK.
// CRC-16/CCITT-FALSE over type+len+payload (../../docs/station-link.tex, "Serial").
// One writer serialises complete frames; ESP_LOG output travels as LOG frames so the byte
// stream never mixes text with a binary frame.
#include <cstddef>
#include <cstdint>
#include <functional>
@@ -14,8 +14,7 @@ namespace microbu::serial {
/// @brief Byte buffer type for frame payloads.
using Bytes = std::vector<std::uint8_t>;
/// @brief The type of a frame. Either Link (link protocol), Test (test channel), or Log (ESP_LOG output).
enum class FrameType : std::uint8_t { LINK = 0x10, TEST = 0x11, LOG = 0x7F };
enum class FrameType : std::uint8_t { LINK = 0x10, LOG = 0x7F };
constexpr std::size_t maximum_payload = 1536;
@@ -54,22 +53,23 @@ private:
std::uint32_t crc_errors_ = 0, frames_ = 0;
};
struct Counters { std::uint32_t frames = 0, crc_errors = 0, write_failures = 0, not_connected = 0; };
struct Counters { std::uint32_t frames = 0, crc_errors = 0, write_failures = 0; };
/// @brief Installs the USB Serial/JTAG driver and starts the reader task. ESP_LOG goes into LOG frames
/// only with CONFIG_MICROBU_LOG_OVER_LINK; on this board it stays on the UART0 console.
/// @brief Installs the USB Serial/JTAG driver, starts the reader task and routes ESP_LOG into LOG frames.
/// @param on_frame Invoked once per complete, CRC-valid frame.
/// @note The handler runs on the reader task; it must only enqueue, never block.
void start(const Decoder::Handler& on_frame);
/// @brief Writes one complete frame (blocking, mutex-protected). Safe from any task.
/// @brief Writes one complete frame (mutex-protected; dropped while the host does not read). Safe from any task.
/// @param type Frame type tag.
/// @param payload Payload bytes; must not exceed maximum_payload.
/// @return false on a full payload, missing driver, lock timeout, or write failure.
bool write(FrameType type, const Bytes& payload);
/// Queues a complete debug frame if the writer and USB buffer are immediately available.
bool try_write(FrameType type, const Bytes& payload);
/// @return Current frame/error counters.
Counters counters();
/// @return esp_timer time in ms (wrapping) at which the last CRC-valid frame arrived from the host,
/// 0 if none yet. MicrOBU: app_main pauses BLE advertising while this is recent.
/// MicrOBU: milliseconds since boot at which the last valid frame arrived on the native port,
/// 0 if none yet. The battery guard reads it to tell a phone on USB (which powers the board).
std::uint32_t last_frame_ms();
} // namespace microbu::serial
+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
+14 -9
View File
@@ -23,13 +23,13 @@ struct Counters {
* BTP-DATA.request: 0000C176-BA5E-4C17-8000-00805F9B34FB (Write, Authenticated/Encrypted)
* BTP-DATA.indication: 0000C177-BA5E-4C17-8000-00805F9B34FB (Notify, Authenticated/Encrypted)
* PoTi Fix Update: 0000C178-BA5E-4C17-8000-00805F9B34FB (Write, Authenticated/Encrypted)
* Station Status: 0000C179-BA5E-4C17-8000-00805F9B34FB (Read / Notify, Authenticated/Encrypted)
* Access probe: 0000C179-BA5E-4C17-8000-00805F9B34FB (Empty Read, Authenticated/Encrypted)
* SF-SAP Identity: 0000C17A-BA5E-4C17-8000-00805F9B34FB (Notify, Authenticated/Encrypted)
* Station Configure: 0000C17B-BA5E-4C17-8000-00805F9B34FB (Write, Authenticated/Encrypted)
* Result: 0000C17C-BA5E-4C17-8000-00805F9B34FB (Notify, Authenticated/Encrypted)
* Confirm: 0000C17C-BA5E-4C17-8000-00805F9B34FB (Notify, Authenticated/Encrypted)
*
* Fixed passkey bonding: 123456.
* Single ATT message transmission/reception up to 512 bytes without fragmentation chunk delays.
* Station-specific compile-time passkey and one pinned owner bond, stored in NVS.
* Each GATT value carries one message or fragment, up to the negotiated ATT limit.
* @param receiver Invoked with each decoded station-link message written by the phone.
* @return false if the NimBLE host or GATT service failed to start.
*/
@@ -45,14 +45,19 @@ bool write(const link::Bytes& message);
/// @return true if a phone is connected.
bool connected();
/// @brief MicrOBU: allows or stops advertising (an existing connection is never dropped). Called
/// with false while the phone uses the USB link, so BLE takes no airtime from ITS-G5.
void set_advertising_allowed(bool allowed);
/// @return true while advertising is allowed (see set_advertising_allowed).
bool advertising_allowed();
/// @brief Pauses (false) or resumes (true) advertising while no phone is connected. The C5 shares one radio
/// between BLE and ITS-G5: each advertising event leaves the 5.9 GHz receiver deaf, so a board measuring on air
/// (raw capture over USB) stops advertising (2026-09-29: 2-4 % of the frames missed by the receiving board).
void set_advertising(bool enabled);
/// @return Largest link message one notification carries: min(ATT MTU - 3, maximum_message).
std::size_t max_message();
/// @return true if the phone has subscribed to notifications.
bool is_subscribed();
/// @return Current message/error counters.
Counters counters();
/// @return esp_timer time (us) of the last GATT write from the phone, a connection-event anchor; 0 if none.
std::int64_t last_write_us();
/// @return Current connection interval in us; 0 if not connected.
std::uint32_t connection_interval_us();
} // namespace microbu::ble
File diff suppressed because it is too large Load Diff
+151 -84
View File
@@ -3,11 +3,12 @@
// security entity with the station's provisioned credentials, and the ITS-G5 access adapter.
// Everything here runs on one task (the station task).
#include "c5_radio.hpp"
#include "its_clock.hpp"
#include "link_protocol.hpp"
#include <vanetza_idf/stack.hpp>
#include <vanetza_idf/security.hpp>
#include <vanetza_idf/credentials.hpp>
#include <vanetza_idf/backend_mbedtls.hpp>
#include <microbu_v2x/stack.hpp>
#include <microbu_v2x/security.hpp>
#include <microbu_v2x/credentials.hpp>
#include <microbu_v2x/security_backend.hpp>
#include <vanetza/common/manual_runtime.hpp>
#include <vanetza/common/position_provider.hpp>
#include <deque>
@@ -15,23 +16,24 @@
#include <map>
#include <memory>
#include <optional>
#include <utility>
namespace microbu {
#if CONFIG_MICROBU_TEST_CHANNEL
/// Records the software lower tester collects (test channel, test firmware only).
struct TestRecord { std::uint8_t kind; link::Bytes bytes; };
#endif
/// @note All public members except the on_*() callback setters must be called from the station task.
class Station final : public vanetza_idf::Access, public vanetza::PositionProvider {
class Station final : public microbu_v2x::Access, public vanetza::PositionProvider {
public:
using Indication = std::function<void(const link::BtpDataIndication&)>;
using IdEvent = std::function<void(const link::IdChangeEvent&)>;
using Disseminated = std::function<void()>;
using Received = std::function<void()>;
/// RAW_FRAME body (u32 counter, u8 flags, i8 RSSI, ITS5 record) for the link service.
using RawFrame = std::function<void(const link::Bytes&)>;
/// MicrOBU: body of one link V2X_RX message (see link_protocol.hpp).
using RawIts = std::function<void(const link::Bytes&)>;
/// DCC_T_GEN_VAM body for the link service (TS 103 300-3 clause 6.2: T_GenVam from management).
using DccUpdate = std::function<void(const link::Bytes&)>;
/// @brief Constructs an unconfigured station (call configure() before use).
Station();
@@ -50,11 +52,16 @@ public:
/// @return Result code.
link::Code poti(const link::PotiUpdate& fix);
/// @brief Submits a BTP data request to the stack.
/// @param request Request to submit.
/// @return Result code.
/// @brief Validates a BTP data request and queues it; signing and submission follow in
/// submit_pending(), so the CONFIRM does not wait for them. A request whose generated_at_ms lies more
/// than one packet lifetime in the past is refused as stale.
/// @param request Request to queue.
/// @return Result code (accepted = validated and queued).
link::Code btp_request(const link::BtpDataRequest& request);
/// @brief Signs and submits the queued BTP requests; call from the station task loop after replying.
void submit_pending();
/// @brief Decodes and stores a credential bundle, rebuilding the security entity if configured.
/// @param bundle Raw credential bundle bytes.
/// @param report Receives the applied root/authority/ticket counts.
@@ -65,6 +72,22 @@ public:
/// @return Result code.
link::Code erase_credentials();
// ---- TS 102 941 V2.2.1 on the device : the micrOBU is the ITS-S security entity. It keeps its
// canonical key, generates its enrolment and ticket key pairs itself and builds the encrypted requests; the
// phone only relays the opaque requests and responses to the EA/AA. kind: 1 enrolment, 2 authorization.
/// @brief Canonical identifier and canonical public key (uncompressed point), generated once on the device.
link::Code pki_identity(link::Bytes& detail);
link::Code pki_status(link::Bytes& detail);
link::Code pki_trust_bootstrap(const link::Bytes&);
link::Code pki_trust_update(const link::Bytes&);
/// @brief Builds an EnrolmentRequest (body: EA HashedId8) or an AuthorizationRequest (body: EA and AA
/// HashedId8); `request` receives the encoded EtsiTs103097Data-Encrypted.
link::Code pki_request(std::uint8_t kind, const link::Bytes& body, link::Bytes& request);
/// @brief Decrypts and checks the EA/AA response of the outstanding request; stores the EC or the new ticket.
link::Code pki_retry(std::uint8_t kind, link::Bytes& request);
link::Code pki_cancel(std::uint8_t kind);
link::Code pki_response(std::uint8_t kind, const link::Bytes& response, link::Bytes& detail);
/// @brief Subscribes to pseudonym-change events.
/// @param subscriber_data Opaque data echoed back with events for this subscription.
/// @param subscription Receives the assigned subscription handle.
@@ -119,61 +142,31 @@ public:
/// @param f Callback to invoke; replaces any previously registered callback.
void on_received(Received f) { received_ = std::move(f); }
/// @brief Switches the raw capture debug path (RAW_CAPTURE): every valid 802.11 frame the radio
/// receives (and, with C5Radio::capture_own_tx, transmits) goes to the phone as an ITS5 record,
/// like the OpenTrafficMap / V2X2Map receiver firmware. Needs a started radio unless mode is 0.
/// @param mode C5Radio capture mode bits; 0 switches it off.
/// @return Result code.
link::Code raw_capture(std::uint8_t mode);
/// @brief MicrOBU: registers the callback for every ITS message heard on air, unwrapped by
/// gn_unwrap.c before (and independently of) the stack's security checks. The stack drops
/// what it cannot verify (itsGnSnDecapResultHandling is STRICT in vanetza-idf): unsigned
/// traffic, and anything signed under a root other than the provisioned demo root, i.e. every
/// RSU. This path is how those still reach the phone, exactly as with the previous firmware.
/// gn_unwrap.c before (and independently of) the stack's security checks. The stack drops what
/// it cannot verify (decapsulation is strict): unsigned traffic, and anything signed under a root
/// other than the provisioned one, i.e. every RSU. This path is how those still reach the phone.
/// @param f Callback to invoke with a V2X_RX body; replaces any previously registered callback.
void on_raw_its(RawIts f) { raw_its_ = std::move(f); }
#if CONFIG_MICROBU_TEST_CHANNEL
// ---- test channel (software lower tester; not part of the phone interface -- see test_channel.hpp) ----
enum class Mirror : std::uint8_t { off = 0, mirror = 1, divert = 2 };
/// @brief Sets whether requests/indications are mirrored to, or diverted through, the test channel.
/// @param mode Off, mirror (copy) or divert (intercept) mode.
void test_mirror(Mirror mode);
/// @brief Registers the callback that sends one RAW_FRAME body to the phone.
void on_raw_frame(RawFrame f) { raw_frame_ = std::move(f); }
/// @brief Injects a raw GN PDU as if received over the air.
/// @param source Source MAC address to report for the injected frame.
/// @param destination Destination MAC address to report for the injected frame.
/// @param gnpdu Raw GeoNetworking PDU bytes.
/// @return Result code.
link::Code test_inject(const vanetza::MacAddress& source, const vanetza::MacAddress& destination, link::Bytes gnpdu);
/// @brief Submits a raw GeoNetworking request bypassing BTP.
/// @param traffic_class GeoNetworking traffic class to submit with.
/// @param payload Raw payload bytes.
/// @return Result code.
link::Code test_gn_request(std::uint8_t traffic_class, link::Bytes payload);
/// @brief Pops queued mirror/divert records fitting into budget octets (3 per record header); the rest stays queued.
/// @param overflow Receives true if records were dropped because the queue budget was exceeded.
/// @param budget Maximum number of octets of records to drain.
/// @return Drained records.
std::deque<TestRecord> test_drain(bool& overflow, std::size_t budget);
/// @brief Clears mirror mode and any queued records.
void test_reset();
/// @brief Starts the radio if needed and sends a burst of raw test frames.
/// @param channel ITS-G5 channel number to transmit on.
/// @param power_dbm Transmit power in dBm.
/// @param mcs 802.11p modulation and coding scheme index.
/// @param count Number of frames to send.
/// @param interval_ms Interval between frames in milliseconds.
/// @param payload_len Length of each frame's payload in bytes.
/// @return Result code.
link::Code test_radio_burst(std::uint16_t channel, double power_dbm, unsigned mcs,
unsigned count, unsigned interval_ms, std::size_t payload_len);
/// @brief Starts the radio if needed and samples the CCA state for duration_ms.
/// @param duration_ms Sampling window duration in milliseconds.
/// @param detail Receives the sampling statistics.
/// @return Result code.
link::Code test_cca_sample(unsigned duration_ms, link::Bytes& detail);
#endif
/// @brief Registers the callback that sends T_GenVam_DCC (DCC_T_GEN_VAM) to the phone's VBS.
void on_dcc_update(DccUpdate f) { dcc_update_ = std::move(f); }
// vanetza_idf::Access
/// @brief Submits a frame to the radio (through DCC_ACC when enabled), mirroring/diverting for the test channel.
// microbu_v2x::Access
/// @param request Frame and transmit parameters from the access layer.
/// @return Result code.
vanetza_idf::Result request(vanetza_idf::AlDataRequest request) override;
microbu_v2x::Result request(microbu_v2x::AlDataRequest request) override;
// vanetza::PositionProvider
/// @return The most recently applied position fix.
@@ -185,7 +178,9 @@ private:
bool synchronised = false;
std::int64_t base_its_us = 0; // ITS time at base_esp_us
std::int64_t base_esp_us = 0;
std::int64_t slew_us = 0; // correction applied from base_esp_us on at 1/its_clock::slew_divisor
std::int64_t now_us() const;
std::int64_t remaining_slew_us() const;
};
/// @brief (Re)builds the stack and security entity from config_, stored credentials and the clock.
@@ -198,69 +193,141 @@ private:
/// @brief Maps a station configuration onto the GeoNetworking MIB.
/// @param mib MIB to populate.
/// @param config Station configuration to map from.
void apply_mib(vanetza_idf::StackConfig& mib, const link::StationConfigure& config) const;
void apply_mib(microbu_v2x::StackConfig& mib, const link::StationConfigure& config) const;
/// @brief Re-subscribes existing pseudonym-change handles to a freshly built security entity.
void resubscribe_id_change();
/// @brief Subscribes one link handle to the identity manager's change events.
/// @param handle Link subscription handle echoed in every SF_IDCHANGE_EVENT.
/// @param subscriber_data Opaque data passed back with the events.
/// @return The identity manager's service handle.
std::uint64_t subscribe_id_change(std::uint64_t handle, const link::Bytes& subscriber_data);
/// @brief The security module holding the station's keys, created on first use.
/// @return nullptr when it cannot be opened (logged); secured operation is then refused.
microbu_v2x::security::SecurityModule* module();
/// @brief Loads the stored credentials into a fresh security entity (station task, NVS access).
/// @return false without a security module.
bool load_security();
/// @brief Builds the security entity on the loaded set and carries the subscriptions over.
void new_entity();
/// @brief Replaces the stored credentials; destroys the module keys only the old set referenced.
microbu_v2x::Result store_credentials(const microbu_v2x::security::StoredCredentials& next);
/// @brief The canonical key (TS 102 941 clause 6.2.3.2.1), generated in the module on first use.
/// @return none without a module, or when the module no longer holds the stored key.
std::optional<microbu_v2x::security::KeyId> canonical_key();
/// @brief The stored enrolment credential and the KeyId of its key, none if there is none.
std::optional<std::pair<vanetza::security::v3::Certificate, microbu_v2x::security::KeyId>> enrolment_credential();
/// @brief Replaces the radio for a new configuration (radio_ stays empty for radio = 0).
/// @return Result code.
link::Code start_radio(const link::StationConfigure& config);
/// @return CONFIGURE detail: GN address, identifier, credentials-loaded flag and ticket count.
link::Bytes configuration_detail() const;
/// @brief Moves the ITS clock by one PoTi time reference (restarting the station if it must).
/// @param its_us Reference time from the phone.
/// @return The step applied.
its_clock::Step apply_time_reference(std::int64_t its_us);
/// @brief Holds the calling task while a frame's hand-off would collide with a BLE connection event.
/// @return The applied delay in microseconds.
std::int64_t hold_for_ble_guard() const;
/// @brief Counts a radio result and signals a disseminated frame.
void count_radio_result(microbu_v2x::Result result);
/// @brief Pushes the current position fix into the stack, clamped to not precede the station clock.
void apply_position();
/// @brief Samples the hardware CCA counters at the DCC cadence and feeds both DCC entities.
void sample_dcc_channel_load();
#if CONFIG_MICROBU_TEST_CHANNEL
/// @brief Queues bytes for the test channel, subject to the mirror-buffer budget.
/// @param kind Record kind tag.
/// @param bytes Record payload bytes.
void record(std::uint8_t kind, link::Bytes bytes);
#endif
/// @brief MicrOBU: unwraps one raw received frame with gn_unwrap.c and hands it to raw_its_.
/// @param indication Indication received from the stack.
void deliver(microbu_v2x::BtpIndication indication);
/// @brief MicrOBU: unwraps one received frame with gn_unwrap.c and hands it to raw_its_.
/// @param frame Complete 802.11 frame as captured (FCS included; gn_unwrap reads declared lengths).
/// @param rssi Received signal strength, dBm.
void forward_raw(const vanetza::ByteBuffer& frame, int rssi);
/// @brief MicrOBU: transmits an unsecured BTP-B/SHB request the way the previous firmware did,
/// with geonet.c's GN header and the Source Position Vector of the last PoTi, through request().
/// @param request The phone's request (already checked: configured, clock and fix present).
/// @brief MicrOBU: transmits an unsecured BTP-B/SHB request with geonet.c's GN header and the
/// Source Position Vector of the last PoTi. The stack only signs, so this bypasses it.
/// @param request The phone's request.
/// @return Result code.
link::Code unsecured_request(const link::BtpDataRequest& request);
/// @brief Translates and forwards a stack BTP indication to the link service and test channel.
/// @param indication Indication received from the stack.
void deliver(vanetza_idf::BtpIndication indication);
/// @brief Wraps one captured frame as a RAW_FRAME body and hands it to the link service.
/// @param data MPDU without FCS.
/// @param size Octets in data.
/// @param rssi Received signal strength (0 for own transmissions).
/// @param local_us Local receive/submit time in microseconds (rx_ctrl.timestamp base, 32 bit).
/// @param own_tx true for a frame this radio transmitted.
void emit_raw(const std::uint8_t* data, std::size_t size, int rssi, std::uint32_t local_us, bool own_tx);
link::Status counters_;
std::optional<link::StationConfigure> config_;
Clock clock_;
its_clock::Regression regression_; // backward PoTi references: stale (late-delivered) vs. a real correction
its_clock::Lag lag_; // backward references below 1 s: the clock may run ahead (slew back)
vanetza::PositionFix fix_;
bool have_fix_ = false;
link::PotiUpdate last_poti_; // MicrOBU: the GN Source Position Vector of unsecured_request()
link::PotiUpdate last_poti_; // MicrOBU: the GN Source Position Vector of unsecured_request()
std::uint8_t unsecured_mid_[6] = {2, 0, 0, 0, 0, 1}; // MicrOBU: random per configure(); MAC of unsecured frames
std::uint32_t raw_forwarded_ = 0, raw_oversize_ = 0;
// declared before everything that refers to its keys (security_, pki_pending_), so it is destroyed last
std::unique_ptr<microbu_v2x::security::SecurityModule> module_;
std::unique_ptr<vanetza::ManualRuntime> runtime_;
std::unique_ptr<Security> security_;
std::unique_ptr<vanetza_idf::Stack> stack_;
// the decoded trust set and ticket pool outlive station builds; they are decoded from NVS again only
// after the stored credentials changed (provision, erase) or were never loaded.
bool credentials_stale_ = true;
std::uint32_t managed_trust_deadline_ = 0;
bool managed_trust_expired_ = false;
std::unique_ptr<microbu_v2x::Stack> stack_;
std::unique_ptr<C5Radio> radio_;
std::unique_ptr<vanetza_idf::AccessStack> access_stack_; // DCC_ACC gate in front of radio_
vanetza_idf::AlDataRequest radio_parameters_;
std::unique_ptr<microbu_v2x::AccessStack> access_stack_; // DCC_ACC gate in front of radio_
microbu_v2x::AlDataRequest radio_parameters_;
std::optional<CcaCounters> dcc_cca_last_; // previous read_cca_counters() sample, for the 100 ms LCBR delta
std::int64_t dcc_last_sample_its_us_ = 0;
std::int64_t dcc_last_sample_mono_us_ = 0; // esp_timer time of that sample (window length, never steps)
std::uint32_t dcc_invalid_windows_ = 0; // windows skipped: delayed beyond a counter wrap, or no elapsed cycles
Indication indication_;
IdEvent id_event_;
Disseminated disseminated_;
Received received_;
RawFrame raw_frame_;
RawIts raw_its_;
std::map<std::uint64_t, std::shared_ptr<vanetza_idf::security::IdChangeResponder>> pending_responders_;
DccUpdate dcc_update_;
/// @brief Derives T_GenVam_DCC from the Adaptive DCC state and notifies the VBS on change.
void update_t_gen_vam(std::int64_t its_us);
std::optional<double> cbr_local_, cbr_global_;
std::uint32_t vam_ton_us_ = 0; // airtime of the most recent VAM frame
bool vam_pending_ = false; // the BTP request in progress carries a VAM (ITS-AID 638)
std::uint16_t t_gen_vam_ms_ = 0; // last computed T_GenVam_DCC
std::uint16_t t_gen_vam_sent_ms_ = 0;
std::int64_t t_gen_vam_sent_us_ = 0;
// BTP requests validated and answered, waiting for signing and submission (submit_pending()).
struct Pending;
struct PkiPending; // the outstanding enrolment (0) and authorization (1) request: context and new key
std::unique_ptr<PkiPending> pki_pending_[2];
/// @brief Hands one prepared request to the stack (signing happens inside).
void submit(Pending& pending);
std::deque<std::unique_ptr<Pending>> pending_;
std::uint8_t raw_mode_ = 0;
std::uint32_t raw_counter_ = 0;
std::map<std::uint64_t, std::shared_ptr<microbu_v2x::security::IdChangeResponder>> pending_responders_;
std::map<std::uint64_t, std::uint64_t> link_subscriptions_; // subscription -> service handle (identity)
bool rebuilding_ = false;
#if CONFIG_MICROBU_TEST_CHANNEL
Mirror mirror_ = Mirror::off;
std::deque<TestRecord> records_;
std::size_t record_bytes_ = 0;
bool overflow_ = false;
#endif
};
} // namespace microbu
-130
View File
@@ -1,130 +0,0 @@
// Station's test-channel API (software lower tester; not part of the phone interface, see
// test_channel.hpp). Kept in its own translation unit so the productive station.cpp stays free
// of test-only code; compiles to nothing when CONFIG_MICROBU_TEST_CHANNEL is off.
#include "station.hpp"
#if CONFIG_MICROBU_TEST_CHANNEL
#include <vanetza_idf/nf_sap.hpp>
#include <vanetza_idf/sf_sap.hpp>
#include <esp_log.h>
#include "c5_radio.hpp"
namespace microbu {
using namespace vanetza_idf;
namespace gn = vanetza::geonet;
namespace {
const char* TAG = "station";
link::Code code(Result result) { return static_cast<link::Code>(result); }
}
void Station::test_mirror(Mirror mode) { mirror_ = mode; }
link::Code Station::test_inject(const vanetza::MacAddress& source, const vanetza::MacAddress& destination, link::Bytes gnpdu) {
if (!stack_) return link::Code::not_configured;
tick();
AlDataIndication indication;
indication.source = source;
indication.destination = destination;
indication.channel_number = radio_parameters_.channel_number;
indication.data = std::move(gnpdu);
return code(stack_->indicate(std::move(indication)));
}
link::Code Station::test_gn_request(std::uint8_t traffic_class, link::Bytes payload) {
if (!stack_) return link::Code::not_configured;
if (!clock_.synchronised || !have_fix_) return link::Code::rejected;
tick();
GnRequest request;
request.traffic_class = gn::TrafficClass(traffic_class);
request.data = std::move(payload);
return code(stack_->request(std::move(request)));
}
std::deque<TestRecord> Station::test_drain(bool& overflow, std::size_t budget) {
std::deque<TestRecord> out;
std::size_t used = 0;
while (!records_.empty() && used + records_.front().bytes.size() + 3 <= budget) {
used += records_.front().bytes.size() + 3;
record_bytes_ -= records_.front().bytes.size();
out.push_back(std::move(records_.front()));
records_.pop_front();
}
overflow = overflow_ && records_.empty();
if (records_.empty()) overflow_ = false;
return out;
}
void Station::test_reset() {
mirror_ = Mirror::off;
records_.clear();
record_bytes_ = 0;
overflow_ = false;
}
link::Code Station::test_radio_burst(std::uint16_t channel, double power_dbm, unsigned mcs,
unsigned count, unsigned interval_ms, std::size_t payload_len) {
if (!radio_) {
// Automatically start the radio for testing if not yet started
C5RadioConfig rc;
rc.channel_number = channel;
rc.transmit_power_dbm = power_dbm;
rc.laboratory_transmission = true;
radio_ = std::make_unique<C5Radio>(rc);
const auto error = radio_->start();
if (error != ESP_OK) {
ESP_LOGE(TAG, "radio start failed for test burst: %s", esp_err_to_name(error));
radio_.reset();
return link::Code::rejected;
}
}
const auto err = radio_->transmit_burst(channel, power_dbm, mcs, count, interval_ms, payload_len);
if (err == ESP_OK) {
counters_.radio_submitted += count;
if (disseminated_) disseminated_();
return link::Code::accepted;
}
if (err == ESP_ERR_INVALID_ARG) return link::Code::invalid_argument;
if (err == ESP_ERR_NO_MEM) return link::Code::resource_limit;
return link::Code::rejected;
}
link::Code Station::test_cca_sample(unsigned duration_ms, link::Bytes& detail) {
// Capped: this busy-loops with interrupts otherwise free, so keep it short enough that
// the task watchdog and the WiFi/BLE stack's own housekeeping are not starved for long.
duration_ms = std::min(duration_ms, 500u);
if (!radio_) {
C5RadioConfig rc; // default channel 180 / 10 dBm is fine: this probes PHY polling
rc.laboratory_transmission = true; // capability, not a specific channel's RF content
radio_ = std::make_unique<C5Radio>(rc);
const auto error = radio_->start();
if (error != ESP_OK) {
ESP_LOGE(TAG, "radio start failed for CCA sample: %s", esp_err_to_name(error));
radio_.reset();
return link::Code::rejected;
}
}
const auto result = radio_->sample_cca(duration_ms);
link::Writer w;
w.u32(result.samples);
w.u32(result.duration_us);
w.u32(result.min_delta_us);
w.u32(result.max_delta_us);
w.u32(result.busy_count);
w.i32(result.first_cca);
w.i32(result.last_cca);
w.i32(result.noise_floor_dbm);
w.i32(result.cca_total_cycles_delta);
w.i32(result.cca_busy_cycles_delta);
w.i32(result.cca_status);
detail = w.out;
return result.samples > 0 ? link::Code::accepted : link::Code::rejected;
}
void Station::record(std::uint8_t kind, link::Bytes bytes) {
if (mirror_ == Mirror::off) return;
if (record_bytes_ + bytes.size() > 8192 || records_.size() >= 32) { overflow_ = true; return; }
record_bytes_ += bytes.size();
records_.push_back(TestRecord {kind, std::move(bytes)});
}
} // namespace microbu
#endif // CONFIG_MICROBU_TEST_CHANNEL
-79
View File
@@ -1,79 +0,0 @@
#include "test_channel.hpp"
#if CONFIG_MICROBU_TEST_CHANNEL
#include <algorithm>
namespace microbu {
link::Bytes test_channel_execute(Station& station, const link::Bytes& request) {
using link::Code;
Code result = Code::malformed;
std::deque<TestRecord> records;
link::Bytes extra;
if (!request.empty()) {
link::Reader r(request, 1);
switch (request[0]) {
case 0x01: { // MIRROR mode
const auto mode = r.u8();
if (r.done() && mode <= 2) { station.test_mirror(static_cast<Station::Mirror>(mode)); result = Code::accepted; }
break;
}
case 0x02: { // INJECT source destination gnpdu
vanetza::MacAddress source, destination;
r.bytes(source.octets.data(), 6);
r.bytes(destination.octets.data(), 6);
auto gnpdu = r.rest();
if (r.ok() && !gnpdu.empty()) result = station.test_inject(source, destination, std::move(gnpdu));
break;
}
case 0x03: { // GN_REQUEST traffic class payload
const auto tc = r.u8();
auto payload = r.rest();
if (r.ok() && !payload.empty()) result = station.test_gn_request(tc, std::move(payload));
break;
}
case 0x04: { // DRAIN
bool overflow = false;
records = station.test_drain(overflow, 1536 - 2);
result = overflow ? Code::resource_limit : Code::accepted;
break;
}
case 0x05: // RESET
station.test_reset();
result = Code::accepted;
break;
case 0x06: { // RADIO_BURST [channel u16 LE][power_quarter_db u8][mcs u8][count u16 LE][interval_ms u16 LE][payload_len u16 LE]
const auto channel = r.u16();
const auto power_quarter_db = r.u8();
const auto mcs = r.u8();
const auto count = r.u16();
const auto interval_ms = r.u16();
const auto payload_len = r.u16();
if (r.done()) {
const double power_dbm = power_quarter_db / 4.0;
result = station.test_radio_burst(channel, power_dbm, mcs, count, interval_ms, payload_len);
}
break;
}
case 0x07: { // CCA_SAMPLE [duration_ms u16 LE] -- CCA polling feasibility probe
const auto duration_ms = r.u16();
if (r.done()) result = station.test_cca_sample(duration_ms, extra);
break;
}
default:
result = Code::unknown_opcode;
}
}
link::Writer w;
w.u8(static_cast<std::uint8_t>(result));
w.u8(static_cast<std::uint8_t>(std::min<std::size_t>(records.size(), 255)));
for (const auto& record : records) {
w.u8(record.kind);
w.u16(static_cast<std::uint16_t>(record.bytes.size()));
w.bytes(record.bytes);
}
w.bytes(extra);
return w.out;
}
} // namespace microbu
#endif // CONFIG_MICROBU_TEST_CHANNEL
-15
View File
@@ -1,15 +0,0 @@
#pragma once
// Test channel (serial frame type 0x11, test firmware only): software lower tester and the
// diagnostic hooks the ETSI campaigns need. Not part of the phone interface, never on BLE.
#include "link_protocol.hpp"
#include "station.hpp"
namespace microbu {
/// @brief Executes one software-lower-tester request against the station.
/// @param station Station to execute the request against.
/// @param request Raw test-channel request bytes.
/// @return Reply bytes: [result][record count]{[kind][length u16 LE][bytes]}.
link::Bytes test_channel_execute(Station& station, const link::Bytes& request);
} // namespace microbu
-196
View File
@@ -1,196 +0,0 @@
// Copied verbatim (no logic changes) from opentrafficmap/its-g5-receiver-firmware_txenabled,
// main/tx_custom.c (https://codeberg.org/opentrafficmap/its-g5-receiver-firmware_txenabled),
// same authors as the receiver firmware (V2X2MAP) already used on the RX side of this
// project. Same chip (ESP32-C5), same class of problem (getting a raw 802.11 frame past
// esp_wifi_80211_tx()'s built-in frame-type gate), and a proven-different approach from our
// own abandoned main/wifi_patches.c attempt - see docs/04-transmit-setup.md for why that one
// didn't work and why this one is expected to.
//
// WHAT THIS DOES DIFFERENTLY FROM esp_wifi_80211_tx(): it doesn't call the public API at all.
// It reaches one layer deeper into the closed WiFi driver - ic_ebuf_alloc() (allocates an
// internal driver buffer), ieee80211_post_hmac_tx() (submits that buffer straight to the MAC
// for transmission) - and never goes through the code path that contains the QoS-frame-type
// sanity check that was rejecting us. Notice line "esp_err_t result = 0;//ieee80211_raw_frame_
// sanity_check(...)" below: the upstream authors don't override that check (like our old
// wifi_patches.c tried to), they just never call the function that calls it.
//
// REAL RISK, carried over from upstream, not introduced by us: this skips ALL frame-type and
// sanity validation, same caveat as our old override attempt. A malformed frame from a bug
// elsewhere in our own code could behave worse (silent corruption, crash) than a clean
// rejection.
//
// UNVERIFIED FOR OUR EXACT TOOLCHAIN - things worth checking before trusting this blindly:
// 1. The symbols this depends on (ieee80211_post_hmac_tx, ic_ebuf_alloc, ic_get_default_sched,
// g_osi_funcs_p, g_wifi_global_lock) are undocumented/internal. We confirmed via `nm`
// earlier that ieee80211_raw_frame_sanity_check exists in OUR esp32c5/IDF libnet80211.a -
// we have NOT yet independently confirmed these other four/five symbols exist in our
// exact ESP-IDF version (as opposed to whatever version the upstream repo's pinned
// esp-idf submodule uses). If the linker can't find one of these, that's the first thing
// to check - see docs/04-transmit-setup.md for the nm command.
// 2. x_eb_txdesc_t / x_middle_data_t / x_ebuf_t below are REVERSE-ENGINEERED struct layouts
// of closed-source internal WiFi driver types, pinned only by a sizeof() static_assert -
// that assert catches a total-size mismatch but NOT a field-order/semantic mismatch if a
// different IDF version shuffled internal fields while keeping the same total size. If our
// ESP-IDF version differs meaningfully from upstream's, this could compile and link fine
// but write to the wrong offsets internally. Worth checking `idf.py --version` against
// whatever esp-idf commit opentrafficmap's repo has pinned as a submodule, as a rough
// compatibility signal (not a guarantee either way).
#include "esp_private/wifi_os_adapter.h"
#include "esp_wifi.h"
#include "tx_custom.h"
esp_err_t ieee80211_raw_frame_sanity_check(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq);
esp_err_t ieee80211_post_hmac_tx(void *ebuf);
void *ic_ebuf_alloc(const void *packet, uint32_t unknown, uint32_t len);
void *ic_get_default_sched(void);
extern wifi_osi_funcs_t *g_osi_funcs_p;
extern void *g_wifi_global_lock;
typedef struct x_eb_txdesc
{
uint32_t flags;
uint32_t field_4;
uint32_t field_8;
uint8_t rate;
uint8_t field_d;
uint8_t field_e;
uint8_t field_f;
uint32_t field_10;
uint32_t field_14;
uint32_t timestamp;
void* sched;
uint32_t field_20;
uint32_t field_24;
uint32_t field_28;
union {
uint32_t field_2c_32;
struct {
uint8_t field_2c;
uint8_t field_2d;
uint8_t field_2e;
uint8_t field_2f;
};
};
union {
uint32_t field_30_32;
struct {
uint8_t field_30;
uint8_t field_31;
uint8_t field_32;
uint8_t field_33;
};
};
uint32_t field_34;
uint32_t field_38;
uint32_t field_3c;
uint32_t field_40;
uint32_t field_44;
} x_eb_txdesc_t;
static_assert(sizeof(x_eb_txdesc_t) == 0x48);
typedef struct x_middle_data
{
uint32_t field_40;
uint8_t* buf;
uint32_t field_48;
uint32_t field_4c;
} x_middle_data_t;
static_assert(sizeof(x_middle_data_t) == 0x10);
typedef struct x_ebuf
{
uint32_t field_0;
x_middle_data_t* ds_head;
x_middle_data_t* ds_tail;
uint16_t field_c;
uint16_t field_e;
uint32_t extra_data_start;
uint16_t header_length;
uint32_t data_length;
uint16_t field_1c;
uint8_t alloc_type;
uint8_t field_1f;
uint32_t field_20;
uint8_t field_24;
uint8_t field_25;
uint8_t field_26;
uint8_t field_27;
uint32_t field_28;
uint8_t field_2c;
uint32_t field_30;
uint32_t next_free;
x_eb_txdesc_t* txdesc;
uint16_t field_3c;
uint8_t field_3e;
uint8_t field_3f;
} x_ebuf_t;
static_assert(sizeof(x_ebuf_t) == 0x40);
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq, wifi_tx_rate_config_t *tx_rate_config, wifi_band_t band, wifi_bandwidth_t bw)
{
esp_err_t result = 0;//ieee80211_raw_frame_sanity_check(ifx, buffer, len, en_sys_seq);
if (!result)
{
g_osi_funcs_p->_mutex_lock(g_wifi_global_lock);
x_ebuf_t* eb = ic_ebuf_alloc(buffer, 1, len);
if (eb)
{
//eb->data_length = len - 0x1a;
eb->data_length = 0;
x_eb_txdesc_t *txdesc_1 = eb->txdesc;
//eb->header_length = 0x1a;
eb->header_length = len;
txdesc_1->flags |= 0x4000;
txdesc_1->sched = ic_get_default_sched();
wifi_phy_rate_t rate = tx_rate_config->rate;
x_eb_txdesc_t *txdesc = eb->txdesc;
if (rate)
txdesc->rate = (char)rate;
else if (band != WIFI_BAND_5G)
txdesc->rate = 0;
else
txdesc->rate = (char)WIFI_PHY_RATE_6M;
wifi_phy_mode_t phymode = tx_rate_config->phymode;
if (phymode == WIFI_PHY_MODE_HE20)
{
txdesc->flags |= 0x80000000;
txdesc->field_2f =
(char)((((uint32_t)tx_rate_config->ersu + 6) & 0xf) << 3)
| (txdesc->field_2f & 0x87);
if ((uint32_t)tx_rate_config->dcm)
txdesc->field_31 |= 0x80;
}
else if (phymode == WIFI_PHY_MODE_VHT20)
txdesc->flags |= 0x1000000;
// No idea if this is correct, but this is what the original code does...
uint32_t bw_is_bw40 = bw == WIFI_BW40;
txdesc->field_8 = (bw_is_bw40 << 0xf) | (txdesc->field_8 & 0xffff7fff);
if (en_sys_seq)
txdesc->flags |= 1;
txdesc->field_10 =
(txdesc->field_10 & 0xfff3ffff) | ((ifx & WIFI_IF_MAX) << 0x12);
txdesc->field_14 = 0x100;
ieee80211_post_hmac_tx(eb);
g_osi_funcs_p->_mutex_unlock(g_wifi_global_lock);
}
else
{
result = ESP_ERR_NO_MEM;
g_osi_funcs_p->_mutex_unlock(g_wifi_global_lock);
}
}
return result;
}
-15
View File
@@ -1,15 +0,0 @@
// Copied from opentrafficmap/its-g5-receiver-firmware_txenabled, main/tx_custom.h.
// See tx_custom.c for what this does and why we pulled it in.
#pragma once
#include "esp_wifi.h"
#ifdef __cplusplus
extern "C" {
#endif
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq, wifi_tx_rate_config_t *tx_rate_config, wifi_band_t band, wifi_bandwidth_t bw);
#ifdef __cplusplus
}
#endif
+37
View File
@@ -0,0 +1,37 @@
#include "tx_policy.hpp"
#include <array>
namespace microbu::tx_policy {
namespace {
// Lossy hand-off phases measured with the guard off (TX phase sweeps, 10 Hz signed VAMs), widened outwards
// to 0.5 ms steps and started earlier to cover the frame's airtime (~0.5 ms) and the phase-logging offset:
// 20 ms: loss at 13.75-15.75 ms (3,448 frames, 106 lost), window verified live with 0 of 8,847 lost.
// No 15 ms entry: windows calibrated there with scheduled releases (1.0-2.95 and 4.2-5.8 ms) made live
// transmission worse (217 of 1,583 lost vs 0.5 % unguarded), presumably because the live CONFIRM notification
// shifts the BLE activity (not yet measured). An interval without an entry transmits unguarded.
constexpr std::array<PhaseWindow, 1> windows_20ms {{{12500, 16000}}};
} // namespace
std::span<const PhaseWindow> guard_windows(std::int64_t interval_us) {
switch (interval_us) {
case 20000: return windows_20ms;
default: return {};
}
}
std::int64_t guard_delay_us(std::int64_t since_anchor_us, std::int64_t interval_us) {
if (interval_us <= 0 || since_anchor_us < 0) return 0;
const auto phase = since_anchor_us % interval_us;
for (const auto& window : guard_windows(interval_us)) {
if (phase >= window.start_us && phase < window.end_us) return window.end_us - phase;
}
return 0;
}
bool is_stale(std::int64_t generated_at_us, std::int64_t now_us, std::int64_t lifetime_us) {
return now_us - generated_at_us > lifetime_us;
}
} // namespace microbu::tx_policy
+34
View File
@@ -0,0 +1,34 @@
#pragma once
// Transmission timing policy of the micrOBU. Honest functions only: no clock, no radio, no global state.
#include <cstdint>
#include <optional>
#include <span>
namespace microbu::tx_policy {
/// @brief Span of the BLE connection interval, as time since the last GATT write from the phone
/// (the host's view of a connection event), in microseconds: [start_us, end_us).
struct PhaseWindow {
std::int64_t start_us = 0;
std::int64_t end_us = 0;
};
/// @brief Hand-off phases at which an ITS-G5 frame collides with a BLE connection event and is dropped by
/// the ESP32-C5's coexistence arbitration. Measured per connection interval on the bench (2026-09-25).
/// @param interval_us Current BLE connection interval.
/// @return The windows; empty for an interval without calibration.
std::span<const PhaseWindow> guard_windows(std::int64_t interval_us);
/// @brief How long to hold a frame so that its hand-off to the driver leaves every guard window.
/// @param since_anchor_us Time since the last GATT write (>= 0).
/// @param interval_us Current BLE connection interval (> 0).
/// @return Delay in microseconds; 0 outside the windows or for an interval without calibration.
std::int64_t guard_delay_us(std::int64_t since_anchor_us, std::int64_t interval_us);
/// @brief A request generated more than one packet lifetime ago is stale: a BLE write delayed in the link
/// @param generated_at_us ITS time at which the phone generated the request.
/// @param now_us Current ITS time of the station.
/// @param lifetime_us Maximum packet lifetime (1 s for a VAM, TS 103 300-3 Table 4).
bool is_stale(std::int64_t generated_at_us, std::int64_t now_us, std::int64_t lifetime_us);
} // namespace microbu::tx_policy
+411
View File
@@ -0,0 +1,411 @@
# ASN.1 descriptor tables in flash.
# The asn1c runtime and generated code never write them; see the generator for the reasoning.
[sections:v2x_asn1_data]
entries:
.data+
[scheme:v2x_asn1_tables_in_flash]
entries:
v2x_asn1_data -> flash_rodata
[mapping:v2x_asn1_tables]
archive: libvanetza.a
entries:
ANY (v2x_asn1_tables_in_flash)
ANY_aper (v2x_asn1_tables_in_flash)
ANY_ber (v2x_asn1_tables_in_flash)
ANY_jer (v2x_asn1_tables_in_flash)
ANY_uper (v2x_asn1_tables_in_flash)
ANY_xer (v2x_asn1_tables_in_flash)
AaEntry (v2x_asn1_tables_in_flash)
AcaEeCertResponseCubkSpdu (v2x_asn1_tables_in_flash)
AcaEeCertResponsePlainSpdu (v2x_asn1_tables_in_flash)
AcaEeCertResponsePrivateSpdu (v2x_asn1_tables_in_flash)
AcaRaCertResponse (v2x_asn1_tables_in_flash)
AcaResponse (v2x_asn1_tables_in_flash)
AcpcTreeId (v2x_asn1_tables_in_flash)
AdditionalParams (v2x_asn1_tables_in_flash)
AppExtension (v2x_asn1_tables_in_flash)
AuthorizationResponseCode (v2x_asn1_tables_in_flash)
AuthorizationValidationRequest (v2x_asn1_tables_in_flash)
AuthorizationValidationResponse (v2x_asn1_tables_in_flash)
AuthorizationValidationResponseCode (v2x_asn1_tables_in_flash)
BIT_STRING (v2x_asn1_tables_in_flash)
BIT_STRING_jer (v2x_asn1_tables_in_flash)
BIT_STRING_oer (v2x_asn1_tables_in_flash)
BIT_STRING_print (v2x_asn1_tables_in_flash)
BIT_STRING_rfill (v2x_asn1_tables_in_flash)
BIT_STRING_uper (v2x_asn1_tables_in_flash)
BIT_STRING_xer (v2x_asn1_tables_in_flash)
BMPString (v2x_asn1_tables_in_flash)
BMPString_jer (v2x_asn1_tables_in_flash)
BMPString_print (v2x_asn1_tables_in_flash)
BMPString_xer (v2x_asn1_tables_in_flash)
BOOLEAN (v2x_asn1_tables_in_flash)
BOOLEAN_aper (v2x_asn1_tables_in_flash)
BOOLEAN_ber (v2x_asn1_tables_in_flash)
BOOLEAN_jer (v2x_asn1_tables_in_flash)
BOOLEAN_oer (v2x_asn1_tables_in_flash)
BOOLEAN_print (v2x_asn1_tables_in_flash)
BOOLEAN_rfill (v2x_asn1_tables_in_flash)
BOOLEAN_uper (v2x_asn1_tables_in_flash)
BOOLEAN_xer (v2x_asn1_tables_in_flash)
BasePublicEncryptionKey (v2x_asn1_tables_in_flash)
BitmapSsp (v2x_asn1_tables_in_flash)
BitmapSspRange (v2x_asn1_tables_in_flash)
ButterflyExpansion (v2x_asn1_tables_in_flash)
ButterflyParamsOriginal (v2x_asn1_tables_in_flash)
CaCertificateRequest (v2x_asn1_tables_in_flash)
CertIssueExtension (v2x_asn1_tables_in_flash)
CertRequestExtension (v2x_asn1_tables_in_flash)
Certificate (v2x_asn1_tables_in_flash)
CertificateBase (v2x_asn1_tables_in_flash)
CertificateFormat (v2x_asn1_tables_in_flash)
CertificateId (v2x_asn1_tables_in_flash)
CertificateSubjectAttributes (v2x_asn1_tables_in_flash)
CertificateType (v2x_asn1_tables_in_flash)
CircularRegion (v2x_asn1_tables_in_flash)
ContributedExtensionBlock (v2x_asn1_tables_in_flash)
ContributedExtensionBlocks (v2x_asn1_tables_in_flash)
CountryAndRegions (v2x_asn1_tables_in_flash)
CountryAndSubregions (v2x_asn1_tables_in_flash)
CrlEntry (v2x_asn1_tables_in_flash)
CrlSeries (v2x_asn1_tables_in_flash)
CtlCommand (v2x_asn1_tables_in_flash)
CtlDelete (v2x_asn1_tables_in_flash)
CtlEntry (v2x_asn1_tables_in_flash)
CtlFormat (v2x_asn1_tables_in_flash)
DcDelete (v2x_asn1_tables_in_flash)
DcEntry (v2x_asn1_tables_in_flash)
Duration (v2x_asn1_tables_in_flash)
ENUMERATED (v2x_asn1_tables_in_flash)
ENUMERATED_aper (v2x_asn1_tables_in_flash)
ENUMERATED_jer (v2x_asn1_tables_in_flash)
ENUMERATED_oer (v2x_asn1_tables_in_flash)
ENUMERATED_uper (v2x_asn1_tables_in_flash)
EaEntry (v2x_asn1_tables_in_flash)
EcSignature (v2x_asn1_tables_in_flash)
EccP256CurvePoint (v2x_asn1_tables_in_flash)
EccP384CurvePoint (v2x_asn1_tables_in_flash)
EcdsaP256Signature (v2x_asn1_tables_in_flash)
EcdsaP384Signature (v2x_asn1_tables_in_flash)
EcencP256EncryptedKey (v2x_asn1_tables_in_flash)
EciesP256EncryptedKey (v2x_asn1_tables_in_flash)
EcsigP256Signature (v2x_asn1_tables_in_flash)
EeRaCertRequest (v2x_asn1_tables_in_flash)
EeRaDownloadRequest (v2x_asn1_tables_in_flash)
Elevation (v2x_asn1_tables_in_flash)
EncryptedData (v2x_asn1_tables_in_flash)
EncryptedDataEncryptionKey (v2x_asn1_tables_in_flash)
EncryptedIndividualPLV (v2x_asn1_tables_in_flash)
EncryptionKey (v2x_asn1_tables_in_flash)
EndEntityType (v2x_asn1_tables_in_flash)
EnrolmentResponseCode (v2x_asn1_tables_in_flash)
EtsiOriginatingHeaderInfoExtension (v2x_asn1_tables_in_flash)
EtsiTs102941ButterflyAuthorizationRequest-X509Signed (v2x_asn1_tables_in_flash)
EtsiTs102941CrlRequest (v2x_asn1_tables_in_flash)
EtsiTs102941CtlRequest (v2x_asn1_tables_in_flash)
EtsiTs102941Data (v2x_asn1_tables_in_flash)
EtsiTs102941DataContent (v2x_asn1_tables_in_flash)
EtsiTs102941DeltaCtlRequest (v2x_asn1_tables_in_flash)
EtsiTs102941FullCtlRequest (v2x_asn1_tables_in_flash)
EtsiTs103097Certificate (v2x_asn1_tables_in_flash)
EtsiTs103097Data (v2x_asn1_tables_in_flash)
EtsiTs103097Data-Encrypted (v2x_asn1_tables_in_flash)
EtsiTs103097Data-Signed (v2x_asn1_tables_in_flash)
EtsiTs103097Data-SignedExternalPayload (v2x_asn1_tables_in_flash)
ExtId (v2x_asn1_tables_in_flash)
GeneralString (v2x_asn1_tables_in_flash)
GeneralizedTime (v2x_asn1_tables_in_flash)
GeneralizedTime_ber (v2x_asn1_tables_in_flash)
GeneralizedTime_jer (v2x_asn1_tables_in_flash)
GeneralizedTime_print (v2x_asn1_tables_in_flash)
GeneralizedTime_rfill (v2x_asn1_tables_in_flash)
GeneralizedTime_xer (v2x_asn1_tables_in_flash)
GeographicRegion (v2x_asn1_tables_in_flash)
GraphicString (v2x_asn1_tables_in_flash)
GroupLinkageValue (v2x_asn1_tables_in_flash)
HashAlgorithm (v2x_asn1_tables_in_flash)
HashedData (v2x_asn1_tables_in_flash)
HashedId3 (v2x_asn1_tables_in_flash)
HashedId32 (v2x_asn1_tables_in_flash)
HashedId48 (v2x_asn1_tables_in_flash)
HashedId8 (v2x_asn1_tables_in_flash)
HeaderInfo (v2x_asn1_tables_in_flash)
HeaderInfoContributorId (v2x_asn1_tables_in_flash)
Hostname (v2x_asn1_tables_in_flash)
IA5String (v2x_asn1_tables_in_flash)
INTEGER (v2x_asn1_tables_in_flash)
INTEGER_aper (v2x_asn1_tables_in_flash)
INTEGER_ber (v2x_asn1_tables_in_flash)
INTEGER_jer (v2x_asn1_tables_in_flash)
INTEGER_oer (v2x_asn1_tables_in_flash)
INTEGER_print (v2x_asn1_tables_in_flash)
INTEGER_rfill (v2x_asn1_tables_in_flash)
INTEGER_uper (v2x_asn1_tables_in_flash)
INTEGER_xer (v2x_asn1_tables_in_flash)
ISO646String (v2x_asn1_tables_in_flash)
IValue (v2x_asn1_tables_in_flash)
IdentifiedRegion (v2x_asn1_tables_in_flash)
Ieee1609ContributedHeaderInfoExtension (v2x_asn1_tables_in_flash)
Ieee1609Dot2Content (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data-Encrypted (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data-EncryptedSigned (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data-Signed (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data-SignedX509AuthenticatedCertRequest (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data-SymmEncryptedSingleRecipient (v2x_asn1_tables_in_flash)
Ieee1609Dot2Data-Unsecured (v2x_asn1_tables_in_flash)
IeeeExtension (v2x_asn1_tables_in_flash)
InnerAtRequest (v2x_asn1_tables_in_flash)
InnerAtResponse (v2x_asn1_tables_in_flash)
InnerEcRequest (v2x_asn1_tables_in_flash)
InnerEcRequestSignedForPop (v2x_asn1_tables_in_flash)
InnerEcResponse (v2x_asn1_tables_in_flash)
IssuerIdentifier (v2x_asn1_tables_in_flash)
LaId (v2x_asn1_tables_in_flash)
Latitude (v2x_asn1_tables_in_flash)
LinkageData (v2x_asn1_tables_in_flash)
LinkageInfo (v2x_asn1_tables_in_flash)
LinkageValue (v2x_asn1_tables_in_flash)
Longitude (v2x_asn1_tables_in_flash)
MissingCrlIdentifier (v2x_asn1_tables_in_flash)
NULL (v2x_asn1_tables_in_flash)
NULL_aper (v2x_asn1_tables_in_flash)
NULL_ber (v2x_asn1_tables_in_flash)
NULL_jer (v2x_asn1_tables_in_flash)
NULL_oer (v2x_asn1_tables_in_flash)
NULL_print (v2x_asn1_tables_in_flash)
NULL_rfill (v2x_asn1_tables_in_flash)
NULL_uper (v2x_asn1_tables_in_flash)
NULL_xer (v2x_asn1_tables_in_flash)
NativeEnumerated (v2x_asn1_tables_in_flash)
NativeEnumerated_aper (v2x_asn1_tables_in_flash)
NativeEnumerated_ber (v2x_asn1_tables_in_flash)
NativeEnumerated_jer (v2x_asn1_tables_in_flash)
NativeEnumerated_oer (v2x_asn1_tables_in_flash)
NativeEnumerated_uper (v2x_asn1_tables_in_flash)
NativeEnumerated_xer (v2x_asn1_tables_in_flash)
NativeInteger (v2x_asn1_tables_in_flash)
NativeInteger_aper (v2x_asn1_tables_in_flash)
NativeInteger_ber (v2x_asn1_tables_in_flash)
NativeInteger_jer (v2x_asn1_tables_in_flash)
NativeInteger_oer (v2x_asn1_tables_in_flash)
NativeInteger_print (v2x_asn1_tables_in_flash)
NativeInteger_rfill (v2x_asn1_tables_in_flash)
NativeInteger_uper (v2x_asn1_tables_in_flash)
NativeInteger_xer (v2x_asn1_tables_in_flash)
NativeReal (v2x_asn1_tables_in_flash)
NativeReal_aper (v2x_asn1_tables_in_flash)
NativeReal_ber (v2x_asn1_tables_in_flash)
NativeReal_jer (v2x_asn1_tables_in_flash)
NativeReal_oer (v2x_asn1_tables_in_flash)
NativeReal_print (v2x_asn1_tables_in_flash)
NativeReal_rfill (v2x_asn1_tables_in_flash)
NativeReal_uper (v2x_asn1_tables_in_flash)
NativeReal_xer (v2x_asn1_tables_in_flash)
NinetyDegreeInt (v2x_asn1_tables_in_flash)
NumericString (v2x_asn1_tables_in_flash)
OBJECT_IDENTIFIER (v2x_asn1_tables_in_flash)
OBJECT_IDENTIFIER_jer (v2x_asn1_tables_in_flash)
OBJECT_IDENTIFIER_print (v2x_asn1_tables_in_flash)
OBJECT_IDENTIFIER_rfill (v2x_asn1_tables_in_flash)
OBJECT_IDENTIFIER_xer (v2x_asn1_tables_in_flash)
OCTET_STRING (v2x_asn1_tables_in_flash)
OCTET_STRING_aper (v2x_asn1_tables_in_flash)
OCTET_STRING_ber (v2x_asn1_tables_in_flash)
OCTET_STRING_jer (v2x_asn1_tables_in_flash)
OCTET_STRING_oer (v2x_asn1_tables_in_flash)
OCTET_STRING_print (v2x_asn1_tables_in_flash)
OCTET_STRING_rfill (v2x_asn1_tables_in_flash)
OCTET_STRING_uper (v2x_asn1_tables_in_flash)
OCTET_STRING_xer (v2x_asn1_tables_in_flash)
OPEN_TYPE (v2x_asn1_tables_in_flash)
OPEN_TYPE_aper (v2x_asn1_tables_in_flash)
OPEN_TYPE_ber (v2x_asn1_tables_in_flash)
OPEN_TYPE_jer (v2x_asn1_tables_in_flash)
OPEN_TYPE_oer (v2x_asn1_tables_in_flash)
OPEN_TYPE_uper (v2x_asn1_tables_in_flash)
OPEN_TYPE_xer (v2x_asn1_tables_in_flash)
ObjectDescriptor (v2x_asn1_tables_in_flash)
One28BitCcmCiphertext (v2x_asn1_tables_in_flash)
OneEightyDegreeInt (v2x_asn1_tables_in_flash)
Opaque (v2x_asn1_tables_in_flash)
OperatingOrganizationId (v2x_asn1_tables_in_flash)
PKRecipientInfo (v2x_asn1_tables_in_flash)
PduFunctionalType (v2x_asn1_tables_in_flash)
PolygonalRegion (v2x_asn1_tables_in_flash)
PreSharedKeyRecipientInfo (v2x_asn1_tables_in_flash)
PrintableString (v2x_asn1_tables_in_flash)
Psid (v2x_asn1_tables_in_flash)
PsidGroupPermissions (v2x_asn1_tables_in_flash)
PsidSsp (v2x_asn1_tables_in_flash)
PsidSspRange (v2x_asn1_tables_in_flash)
PublicEncryptionKey (v2x_asn1_tables_in_flash)
PublicKeys (v2x_asn1_tables_in_flash)
PublicVerificationKey (v2x_asn1_tables_in_flash)
REAL (v2x_asn1_tables_in_flash)
REAL_aper (v2x_asn1_tables_in_flash)
REAL_jer (v2x_asn1_tables_in_flash)
REAL_oer (v2x_asn1_tables_in_flash)
REAL_print (v2x_asn1_tables_in_flash)
REAL_rfill (v2x_asn1_tables_in_flash)
REAL_uper (v2x_asn1_tables_in_flash)
REAL_xer (v2x_asn1_tables_in_flash)
RELATIVE-OID (v2x_asn1_tables_in_flash)
RELATIVE-OID_jer (v2x_asn1_tables_in_flash)
RELATIVE-OID_print (v2x_asn1_tables_in_flash)
RELATIVE-OID_rfill (v2x_asn1_tables_in_flash)
RELATIVE-OID_xer (v2x_asn1_tables_in_flash)
RaAcaCertRequest (v2x_asn1_tables_in_flash)
RaAcaCertRequestFlags (v2x_asn1_tables_in_flash)
RaEeCertInfo (v2x_asn1_tables_in_flash)
RcaSingleSignedLinkCertificateMessage (v2x_asn1_tables_in_flash)
RecipientInfo (v2x_asn1_tables_in_flash)
RectangularRegion (v2x_asn1_tables_in_flash)
RegionAndSubregions (v2x_asn1_tables_in_flash)
RootCaEntry (v2x_asn1_tables_in_flash)
SequenceOfAppExtensions (v2x_asn1_tables_in_flash)
SequenceOfCertIssueExtensions (v2x_asn1_tables_in_flash)
SequenceOfCertRequestExtensions (v2x_asn1_tables_in_flash)
SequenceOfCertificate (v2x_asn1_tables_in_flash)
SequenceOfHashedId3 (v2x_asn1_tables_in_flash)
SequenceOfIdentifiedRegion (v2x_asn1_tables_in_flash)
SequenceOfOctetString (v2x_asn1_tables_in_flash)
SequenceOfPsidGroupPermissions (v2x_asn1_tables_in_flash)
SequenceOfPsidSsp (v2x_asn1_tables_in_flash)
SequenceOfPsidSspRange (v2x_asn1_tables_in_flash)
SequenceOfRecipientInfo (v2x_asn1_tables_in_flash)
SequenceOfRectangularRegion (v2x_asn1_tables_in_flash)
SequenceOfRegionAndSubregions (v2x_asn1_tables_in_flash)
SequenceOfUint16 (v2x_asn1_tables_in_flash)
SequenceOfUint8 (v2x_asn1_tables_in_flash)
ServiceSpecificPermissions (v2x_asn1_tables_in_flash)
SharedAtRequest (v2x_asn1_tables_in_flash)
Signature (v2x_asn1_tables_in_flash)
SignedData (v2x_asn1_tables_in_flash)
SignedDataPayload (v2x_asn1_tables_in_flash)
SignerIdentifier (v2x_asn1_tables_in_flash)
SspRange (v2x_asn1_tables_in_flash)
SubjectAssurance (v2x_asn1_tables_in_flash)
SubjectPermissions (v2x_asn1_tables_in_flash)
SymmAlgorithm (v2x_asn1_tables_in_flash)
SymmRecipientInfo (v2x_asn1_tables_in_flash)
SymmetricCiphertext (v2x_asn1_tables_in_flash)
SymmetricEncryptionKey (v2x_asn1_tables_in_flash)
T61String (v2x_asn1_tables_in_flash)
TeletexString (v2x_asn1_tables_in_flash)
ThreeDLocation (v2x_asn1_tables_in_flash)
Time32 (v2x_asn1_tables_in_flash)
Time64 (v2x_asn1_tables_in_flash)
TlmEntry (v2x_asn1_tables_in_flash)
ToBeSignedCertificate (v2x_asn1_tables_in_flash)
ToBeSignedCrl (v2x_asn1_tables_in_flash)
ToBeSignedData (v2x_asn1_tables_in_flash)
ToBeSignedLinkCertificate (v2x_asn1_tables_in_flash)
ToBeSignedLinkCertificateRca (v2x_asn1_tables_in_flash)
ToBeSignedLinkCertificateTlm (v2x_asn1_tables_in_flash)
ToBeSignedRcaCtl (v2x_asn1_tables_in_flash)
ToBeSignedTlmCtl (v2x_asn1_tables_in_flash)
TwoDLocation (v2x_asn1_tables_in_flash)
UTCTime (v2x_asn1_tables_in_flash)
UTCTime_jer (v2x_asn1_tables_in_flash)
UTCTime_print (v2x_asn1_tables_in_flash)
UTCTime_rfill (v2x_asn1_tables_in_flash)
UTCTime_xer (v2x_asn1_tables_in_flash)
UTF8String (v2x_asn1_tables_in_flash)
UTF8String_print (v2x_asn1_tables_in_flash)
UTF8String_rfill (v2x_asn1_tables_in_flash)
Uint16 (v2x_asn1_tables_in_flash)
Uint32 (v2x_asn1_tables_in_flash)
Uint64 (v2x_asn1_tables_in_flash)
Uint8 (v2x_asn1_tables_in_flash)
UnCountryId (v2x_asn1_tables_in_flash)
UniversalString (v2x_asn1_tables_in_flash)
UniversalString_jer (v2x_asn1_tables_in_flash)
UniversalString_print (v2x_asn1_tables_in_flash)
UniversalString_xer (v2x_asn1_tables_in_flash)
Url (v2x_asn1_tables_in_flash)
ValidityPeriod (v2x_asn1_tables_in_flash)
VerificationKeyIndicator (v2x_asn1_tables_in_flash)
Version (v2x_asn1_tables_in_flash)
VideotexString (v2x_asn1_tables_in_flash)
VisibleString (v2x_asn1_tables_in_flash)
aper_decoder (v2x_asn1_tables_in_flash)
aper_encoder (v2x_asn1_tables_in_flash)
aper_opentype (v2x_asn1_tables_in_flash)
aper_support (v2x_asn1_tables_in_flash)
asn_SEQUENCE_OF (v2x_asn1_tables_in_flash)
asn_SET_OF (v2x_asn1_tables_in_flash)
asn_application (v2x_asn1_tables_in_flash)
asn_bit_data (v2x_asn1_tables_in_flash)
asn_codecs_prim (v2x_asn1_tables_in_flash)
asn_codecs_prim_ber (v2x_asn1_tables_in_flash)
asn_codecs_prim_jer (v2x_asn1_tables_in_flash)
asn_codecs_prim_xer (v2x_asn1_tables_in_flash)
asn_internal (v2x_asn1_tables_in_flash)
asn_random_fill (v2x_asn1_tables_in_flash)
ber_decoder (v2x_asn1_tables_in_flash)
ber_tlv_length (v2x_asn1_tables_in_flash)
ber_tlv_tag (v2x_asn1_tables_in_flash)
constr_CHOICE (v2x_asn1_tables_in_flash)
constr_CHOICE_aper (v2x_asn1_tables_in_flash)
constr_CHOICE_ber (v2x_asn1_tables_in_flash)
constr_CHOICE_jer (v2x_asn1_tables_in_flash)
constr_CHOICE_oer (v2x_asn1_tables_in_flash)
constr_CHOICE_print (v2x_asn1_tables_in_flash)
constr_CHOICE_rfill (v2x_asn1_tables_in_flash)
constr_CHOICE_uper (v2x_asn1_tables_in_flash)
constr_CHOICE_xer (v2x_asn1_tables_in_flash)
constr_SEQUENCE (v2x_asn1_tables_in_flash)
constr_SEQUENCE_OF (v2x_asn1_tables_in_flash)
constr_SEQUENCE_OF_aper (v2x_asn1_tables_in_flash)
constr_SEQUENCE_OF_ber (v2x_asn1_tables_in_flash)
constr_SEQUENCE_OF_jer (v2x_asn1_tables_in_flash)
constr_SEQUENCE_OF_uper (v2x_asn1_tables_in_flash)
constr_SEQUENCE_OF_xer (v2x_asn1_tables_in_flash)
constr_SEQUENCE_aper (v2x_asn1_tables_in_flash)
constr_SEQUENCE_ber (v2x_asn1_tables_in_flash)
constr_SEQUENCE_jer (v2x_asn1_tables_in_flash)
constr_SEQUENCE_oer (v2x_asn1_tables_in_flash)
constr_SEQUENCE_print (v2x_asn1_tables_in_flash)
constr_SEQUENCE_rfill (v2x_asn1_tables_in_flash)
constr_SEQUENCE_uper (v2x_asn1_tables_in_flash)
constr_SEQUENCE_xer (v2x_asn1_tables_in_flash)
constr_SET (v2x_asn1_tables_in_flash)
constr_SET_OF (v2x_asn1_tables_in_flash)
constr_SET_OF_aper (v2x_asn1_tables_in_flash)
constr_SET_OF_ber (v2x_asn1_tables_in_flash)
constr_SET_OF_jer (v2x_asn1_tables_in_flash)
constr_SET_OF_oer (v2x_asn1_tables_in_flash)
constr_SET_OF_print (v2x_asn1_tables_in_flash)
constr_SET_OF_rfill (v2x_asn1_tables_in_flash)
constr_SET_OF_uper (v2x_asn1_tables_in_flash)
constr_SET_OF_xer (v2x_asn1_tables_in_flash)
constr_SET_ber (v2x_asn1_tables_in_flash)
constr_SET_jer (v2x_asn1_tables_in_flash)
constr_SET_print (v2x_asn1_tables_in_flash)
constr_SET_rfill (v2x_asn1_tables_in_flash)
constr_SET_xer (v2x_asn1_tables_in_flash)
constr_TYPE (v2x_asn1_tables_in_flash)
constraints (v2x_asn1_tables_in_flash)
der_encoder (v2x_asn1_tables_in_flash)
jer_decoder (v2x_asn1_tables_in_flash)
jer_encoder (v2x_asn1_tables_in_flash)
jer_support (v2x_asn1_tables_in_flash)
memory (v2x_asn1_tables_in_flash)
oer_decoder (v2x_asn1_tables_in_flash)
oer_encoder (v2x_asn1_tables_in_flash)
oer_support (v2x_asn1_tables_in_flash)
otm_tx_custom (v2x_asn1_tables_in_flash)
per_decoder (v2x_asn1_tables_in_flash)
per_encoder (v2x_asn1_tables_in_flash)
per_opentype (v2x_asn1_tables_in_flash)
per_support (v2x_asn1_tables_in_flash)
uper_decoder (v2x_asn1_tables_in_flash)
uper_encoder (v2x_asn1_tables_in_flash)
uper_opentype (v2x_asn1_tables_in_flash)
uper_support (v2x_asn1_tables_in_flash)
xer_decoder (v2x_asn1_tables_in_flash)
xer_encoder (v2x_asn1_tables_in_flash)
xer_support (v2x_asn1_tables_in_flash)
+37
View File
@@ -0,0 +1,37 @@
#pragma once
// MicrOBU extension: body of the link message V2X_RX (opcode 0x90, docs/station-link.tex, "MicrOBU
// extensions"). Header-only and free of ESP-IDF, so the host tests (test/host) compile it unmodified.
#include "link_protocol.hpp"
extern "C" {
#include "gn_unwrap.h"
}
#include <algorithm>
namespace microbu::link {
/// Octets before the ITS payload in a V2X_RX body: u16 port, i8 rssi, u8 flags, i32 lat, i32 lon, u16 distance_a.
constexpr std::size_t v2x_rx_prefix = 14;
/// Largest ITS payload that fits one link message (512 - 4 - 14).
constexpr std::size_t v2x_rx_max_payload = maximum_message - header_size - v2x_rx_prefix;
/// @brief Whether an unwrapped message fits one link message. A truncated or empty one never does.
inline bool v2x_rx_fits(const gn_rx_t& rx) {
return !rx.truncated && rx.payload_len > 0 && static_cast<std::size_t>(rx.payload_len) <= v2x_rx_max_payload;
}
/// @brief Builds the V2X_RX body. The caller checks v2x_rx_fits first.
/// @param rx Message unwrapped by gn_unwrap_its (its payload pointer must still be valid).
/// @param rssi Received signal strength, dBm.
inline Bytes encode_v2x_rx(const gn_rx_t& rx, int rssi) {
Writer w;
w.u16(rx.btp_dest_port);
w.u8(static_cast<std::uint8_t>(static_cast<std::int8_t>(std::clamp(rssi, -128, 127))));
w.u8((rx.has_geo_area ? 0x01 : 0) | (rx.signed_unverified ? 0x02 : 0));
w.i32(rx.geo_area_lat_tenmicrodeg);
w.i32(rx.geo_area_lon_tenmicrodeg);
w.u16(rx.geo_area_distance_a_m);
w.bytes(rx.payload, static_cast<std::size_t>(rx.payload_len));
return w.out;
}
} // namespace microbu::link
-49
View File
@@ -1,49 +0,0 @@
#include <stdint.h>
// RETIRED - no longer built (removed from main/CMakeLists.txt SRCS), kept only
// for history. Confirmed not to work: linked cleanly with -Wl,-zmuldefs but
// the QoS-frame rejection persisted identically. Also turned out to be based
// on the wrong function signature - the real ieee80211_raw_frame_sanity_check
// takes (wifi_interface_t ifx, const void *buffer, int32_t len, bool
// en_sys_seq), confirmed from opentrafficmap/its-g5-receiver-firmware_txenabled's
// main/tx_custom.c, not the 3x int32_t guessed below. Superseded by
// tx_custom.c, which bypasses esp_wifi_80211_tx() (and the function that
// calls this check) entirely instead of trying to neutralize the check.
// See docs/04-transmit-setup.md.
// Overrides a function inside the closed-source WiFi library that gates
// which raw 802.11 frame types esp_wifi_80211_tx() will accept. By default
// it only allows beacon/probe-request/probe-response/action and non-QoS
// data frames - it explicitly rejects QoS Data (subtype 8), which is what
// real ITS-G5/802.11p hardware actually transmits and expects.
//
// This is the same technique used by ESP32 WiFi-security tools (deauther/
// injection projects) to unlock raw frame injection: define a function with
// the exact same name as the library's gate, and link with -Wl,-zmuldefs
// (see CMakeLists.txt) so the linker accepts having two definitions of the
// same symbol instead of erroring with "multiple definition of
// `ieee80211_raw_frame_sanity_check'" - and takes this one instead of the
// library's.
//
// Confirmed present for THIS target/IDF version: `nm` on
// components/esp_wifi/lib/esp32c5/libnet80211.a (IDF v5.5.4) shows
// `ieee80211_raw_frame_sanity_check` as a normal (non-weak) global text
// symbol in ieee80211_node.o. The exact argument count/meaning is
// reverse-engineered from community ESP32 (Xtensa) deauther tools, not
// confirmed byte-for-byte against esp32c5's actual implementation - if
// frames still get rejected, or this crashes, the real signature may take
// different arguments than assumed here.
//
// Real risk, not just an inconvenience: this disables ALL sanity checking
// on raw frames going through esp_wifi_80211_tx(), not just the QoS-type
// gate. Whatever else that check validates (frame length bounds, etc.) is
// now unchecked. Malformed frames from a bug elsewhere in this codebase
// could behave worse (silent corruption, crash) than they would have with
// the check in place, where they'd have just been rejected cleanly.
int ieee80211_raw_frame_sanity_check(int32_t arg1, int32_t arg2, int32_t arg3)
{
(void)arg1;
(void)arg2;
(void)arg3;
return 0; // 0 = "frame is sane" - always pass
}