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