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
+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