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