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

178 lines
8.6 KiB
C++
Raw Normal View History

// 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: ../../docs/station-link.tex.
#include "link_protocol.hpp"
#include "link_service.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"
#include <esp_log.h>
#include <esp_task_wdt.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 {
const char* TAG = "microbu";
/// @brief Represents one frame received from a transport, to be queued for the station task.
struct Incoming {
microbu::LinkTransport transport;
microbu::serial::Frame frame;
};
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.
/// @param transport Transport the frame arrived on.
/// @param frame Decoded frame to take ownership of.
/// @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 {
return new Incoming {transport, std::move(frame)}; // takes the payload buffer over, no byte copy
} catch (const std::bad_alloc&) {
return nullptr;
}
}
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);
} catch (const std::bad_alloc&) {
ESP_LOGE(TAG, "out of memory while handling a frame");
} catch (const std::exception& e) {
ESP_LOGE(TAG, "frame handling failed: %s", e.what());
}
}
/// @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;
config.resume_mv = CONFIG_MICROBU_BATTERY_RESUME_MV;
return config;
}
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;
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();
}
}
/// @brief FreeRTOS task body: owns the station, link service and board controls. Drains the incoming queue.
void station_task(void*) {
microbu::Station station;
microbu::LinkService link(station);
microbu::BoardControls controls;
station.on_disseminated([&controls] { controls.blink(); });
station.on_received([&controls] { controls.blink(); });
microbu::BatteryPolicy battery_policy(battery_config());
std::int64_t next_battery_us = 0;
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 controls
Incoming* incoming = nullptr;
// 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();
controls.tick();
if (esp_timer_get_time() >= next_battery_us) {
next_battery_us = esp_timer_get_time() + battery_interval_us;
check_battery(battery_policy, link);
}
}
}
}
/// @brief Firmware entry point: initializes NVS, watchdog, serial/BLE transports, and starts the station task.
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::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::BatteryMonitor::deep_sleep();
}
ESP_LOGI(TAG, "cell at %u mV, starting", unsigned(millivolts));
}
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);
// Signing and verification take tens of milliseconds each on the C5. This keeps the idle
// watchdog from reporting a busy station task (5 s default) while a credential bundle applies.
esp_task_wdt_config_t watchdog = {};
watchdog.timeout_ms = 30000;
watchdog.idle_core_mask = (1 << portNUM_PROCESSORS) - 1;
watchdog.trigger_panic = false; // log, don't reboot, on timeout
esp_task_wdt_reconfigure(&watchdog);
frames = xQueueCreate(32, sizeof(Incoming*));
microbu::serial::start([](microbu::serial::Frame frame) {
auto* copy = try_new_incoming(microbu::LinkTransport::serial, std::move(frame));
if (!copy) return;
// 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)};
auto* copy = try_new_incoming(microbu::LinkTransport::ble, std::move(frame));
if (!copy) return;
if (xQueueSend(frames, &copy, 0) != pdTRUE) delete copy; // same hand-off as the serial callback above
})) {
ESP_LOGE(TAG, "BLE station link failed to start. USB remains available");
}
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);
}