feat(firmware): ESP32-C6 target — Wi-Fi 6 / 802.15.4 / TWT / LP-core (ADR-110)

`firmware/esp32-csi-node` now builds for both `esp32s3` (existing
production) and `esp32c6` (new research / battery-seed target) from
the same source tree. ESP-IDF auto-applies `sdkconfig.defaults.esp32c6`
when the target is set to esp32c6; every C6 module is gated on
CONFIG_IDF_TARGET_ESP32C6 (or the SOC_WIFI_HE_SUPPORT capability) so
the S3 build path is byte-identical to today.

New modules (all #ifdef-gated, no-op stubs on S3):
- c6_twt.{h,c}      — iTWT wrapper, graceful AP-NACK fallback
- c6_timesync.{h,c} — 802.15.4 beacon-based mesh time-sync, EUI-64
                      leader election, c6_timesync_get_epoch_us()
- c6_lp_core.{h,c}  — wake-on-motion deep-sleep helper (ext1 path
                      this cut; real LP-core polling deferred)

ADR-018 frame extension:
- byte 18: PPDU type (0=HT/legacy, 1=HE-SU, 2=HE-MU, 3=HE-TB)
- byte 19: bandwidth + STBC + 802.15.4-sync-valid flags
- Magic 0xC5110001 unchanged — backwards compatible
- Dual-branch encoding handles both struct variants of
  wifi_pkt_rx_ctrl_t (legacy S3 / HE C6) per CONFIG_SOC_WIFI_HE_SUPPORT

Critical bug fixed during live witness collection (verified across 3
boards on COM6/COM9/COM12):
- c6_timesync.c read MAC into a 6-byte buffer and ran MAC-48->EUI-64
  conversion. But esp_read_mac(ESP_MAC_IEEE802154) returns 8 bytes
  already in EUI-64 form on C6 — code was double-inserting FFFE.
  Boot log was 206ef1fffefffe17, fix yields 206ef1fffe17278c which
  matches esptool's eFuse reading exactly.

Tooling:
- CI workflow (firmware-ci.yml) extended with c6-4mb matrix row +
  ADR-110 host-unit-test step
- Host unit tests for pure functions (mac48_to_eui64,
  eui64_bytes_to_u64, PPDU encoding both branches) — runs on Ubuntu CI
- Multi-board live-capture harness (test/capture-3board-experiment.py)
- Witness bundle script records SHA-256s for s3-adr110, c6-adr110, and
  s3-fair-adr110 (apples-to-apples) binary archives

Honest empirical findings (full report in docs/WITNESS-LOG-110.md):
- Verified live on 3 C6 boards: boot, 802.15.4 init w/ correct EUIs,
  WiFi STA reaching assoc->run on ruv.net, TWT setup attempted +
  gracefully NACKed (AP is 11n-only, TWT Responder:0), HE-MAC firmware
  loaded
- NOT verified (need 11ax AP / second-channel exp / INA meter):
  HE-LTF subcarrier expansion, TWT cadence determinism, ±100 µs sync
  alignment, 5 µA hibernation
- Bug found: leader election doesn't step down under live WiFi load —
  likely 2.4 GHz radio coex preemption (WiFi ch 5 vs 15.4 ch 15);
  follow-up task #30
- Apples-to-apples size: S3-no-display = 886 KB, C6 = 1003 KB
  (C6 is 13% LARGER for equivalent CSI features; the extra is the
  802.15.4 + OpenThread stack that S3 lacks)

Tracking: ruvnet/RuView#762

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
ruv
2026-05-22 20:10:30 -04:00
parent 68abb385ae
commit f23e34ee5c
35 changed files with 1720 additions and 13 deletions
@@ -9,6 +9,10 @@ set(SRCS
"rv_feature_state.c"
"rv_mesh.c"
"adaptive_controller.c"
# ADR-110 — ESP32-C6 capability modules (no-op stubs on other targets via #ifdef)
"c6_twt.c"
"c6_timesync.c"
"c6_lp_core.c"
)
# ESP-IDF v6+: headers must resolve via explicit REQUIRES (no implicit deps).
@@ -32,6 +36,13 @@ set(REQUIRES
mbedtls
)
# ADR-110: C6-only components — pulled in when building for esp32c6.
# Note: CONFIG_* symbols are not available in main CMakeLists.txt evaluation —
# we use the IDF_TARGET variable that idf.py sets from sdkconfig.defaults / set-target.
if(IDF_TARGET STREQUAL "esp32c6")
list(APPEND REQUIRES ieee802154 ulp esp_hw_support)
endif()
# ADR-061: Mock CSI generator for QEMU testing + ADR-081 mock radio binding
if(CONFIG_CSI_MOCK_ENABLED)
list(APPEND SRCS "mock_csi.c" "rv_radio_ops_mock.c")
@@ -287,6 +287,87 @@ menu "WASM Programmable Sensing (ADR-040)"
endmenu
menu "ESP32-C6 capabilities (ADR-110)"
depends on IDF_TARGET_ESP32C6
config C6_TWT_ENABLE
bool "Enable TWT (Target Wake Time) negotiation"
default y
# SOC_WIFI_HE_SUPPORT is auto-set on chips with HE (Wi-Fi 6) PHY (C6/C5)
depends on SOC_WIFI_HE_SUPPORT
help
After WiFi STA connect, request an individual TWT agreement
with the AP for deterministic CSI cadence. Falls back
gracefully if the AP doesn't support 11ax TWT.
config C6_TWT_WAKE_INTERVAL_US
int "TWT wake interval (microseconds)"
default 10000
range 1024 1048576
depends on C6_TWT_ENABLE
help
Period between TWT wake events. 10000 µs = 100 Hz CSI cadence.
config C6_TWT_MIN_WAKE_DURA_US
int "TWT minimum wake duration (microseconds)"
default 512
range 256 16384
depends on C6_TWT_ENABLE
help
Minimum awake duration per TWT wake. 512 µs is enough to
capture one CSI frame.
config C6_TIMESYNC_ENABLE
bool "Enable 802.15.4 mesh time-sync"
default y
depends on IEEE802154_ENABLED
help
Cross-node clock alignment over the 802.15.4 radio. Frees
WiFi airtime from coordination traffic — relevant to
ADR-029/030 multistatic sensing.
config C6_TIMESYNC_CHANNEL
int "802.15.4 time-sync channel (11-26)"
default 15
range 11 26
depends on C6_TIMESYNC_ENABLE
config C6_LP_CORE_ENABLE
bool "Enable LP-core wake-on-motion hibernation"
default n
depends on ULP_COPROC_TYPE_LP_CORE
help
Arm the LP RISC-V coprocessor as an always-on motion gate
in deep sleep. Targets ~5 µA hibernation for battery
seed nodes. Requires a motion sensor on a wake-capable GPIO.
config C6_LP_WAKE_GPIO
int "LP-core wake GPIO"
default 4
range 0 23
depends on C6_LP_CORE_ENABLE
config C6_LP_WAKE_ACTIVE_HIGH
bool "Wake on rising edge"
default y
depends on C6_LP_CORE_ENABLE
endmenu
menu "ADR-018 frame extensions (ADR-110)"
config CSI_FRAME_HE_TAGGING
bool "Tag ADR-018 frames with HE PPDU metadata"
default y
help
When the WiFi driver reports an 802.11ax HE-SU/HE-MU/HE-TB
PPDU, write the PPDU type + bandwidth into ADR-018 frame
bytes 18-19 (previously reserved). Readers that don't know
about this extension see the bytes as zero — fully
backwards compatible.
endmenu
menu "Mock CSI (QEMU Testing)"
config CSI_MOCK_ENABLED
bool "Enable mock CSI generator (for QEMU testing)"
+86
View File
@@ -0,0 +1,86 @@
/**
* @file c6_lp_core.c
* @brief LP-core wake-on-motion hibernation — ADR-110 Phase 5 skeleton.
*
* The actual LP-core binary lives in a separate component subproject
* compiled with the LP RISC-V toolchain (`riscv32-esp-elf` with LP-core
* memory layout). For the P5 skeleton we ship just the HP-side arming
* + deep-sleep entry, using esp_sleep_enable_ext1_wakeup() as the wake
* source. A follow-up turn will replace ext1 with a true LP-core
* polling program that can debounce / threshold the accelerometer
* signal in software, dropping standby current from ~10 µA to ~5 µA.
*/
#include "sdkconfig.h"
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_ULP_COPROC_TYPE_LP_CORE)
#include "c6_lp_core.h"
#include "esp_log.h"
#include "esp_sleep.h"
#include "driver/rtc_io.h"
#include "soc/soc_caps.h"
static const char *TAG = "c6_lp";
static int s_wake_gpio = -1;
static bool s_active_high = true;
static bool s_armed = false;
esp_err_t c6_lp_core_arm(int wake_gpio, bool active_high)
{
if (wake_gpio < 0) {
ESP_LOGE(TAG, "invalid wake_gpio=%d", wake_gpio);
return ESP_ERR_INVALID_ARG;
}
s_wake_gpio = wake_gpio;
s_active_high = active_high;
/* GPIO must be in the LP/RTC domain for deep-sleep wake. */
esp_err_t ret = rtc_gpio_init(wake_gpio);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "rtc_gpio_init(%d) failed: %s", wake_gpio, esp_err_to_name(ret));
return ret;
}
rtc_gpio_set_direction(wake_gpio, RTC_GPIO_MODE_INPUT_ONLY);
/* On the C6, deep-sleep GPIO wake is esp_deep_sleep_enable_gpio_wakeup. */
uint64_t mask = 1ULL << wake_gpio;
esp_deepsleep_gpio_wake_up_mode_t mode = active_high
? ESP_GPIO_WAKEUP_GPIO_HIGH
: ESP_GPIO_WAKEUP_GPIO_LOW;
ret = esp_deep_sleep_enable_gpio_wakeup(mask, mode);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "enable_gpio_wakeup failed: %s", esp_err_to_name(ret));
return ret;
}
s_armed = true;
ESP_LOGI(TAG, "armed: wake_gpio=%d active_%s",
wake_gpio, active_high ? "high" : "low");
return ESP_OK;
}
void c6_lp_core_hibernate_and_wait(void)
{
if (!s_armed) {
ESP_LOGW(TAG, "hibernate called without arm — sleeping with no wake source");
}
/* Configure for hibernation: power down everything except what's needed
* to retain the wake source. On C6 the RTC peripheral domain is the
* only one we need to gate explicitly — RTC_SLOW_MEM / RTC_FAST_MEM
* aren't separate power domains on the C6 SoC. */
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF);
ESP_LOGI(TAG, "entering deep sleep — target ≤5 µA");
esp_deep_sleep_start();
/* Never returns. */
}
bool c6_lp_core_was_motion_wake(void)
{
esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
return cause == ESP_SLEEP_WAKEUP_GPIO || cause == ESP_SLEEP_WAKEUP_EXT1;
}
#endif /* CONFIG_IDF_TARGET_ESP32C6 && CONFIG_ULP_COPROC_TYPE_LP_CORE */
+61
View File
@@ -0,0 +1,61 @@
/**
* @file c6_lp_core.h
* @brief LP-core wake-on-motion hibernation helper — ADR-110 Phase 5.
*
* Arms the C6 LP RISC-V coprocessor as an always-on watchdog that
* monitors a GPIO (typically a PIR or accelerometer interrupt line) and
* wakes the HP core only when motion is detected. Targets ~5 µA
* hibernation current for battery-powered Cognitum Seed nodes.
*
* Only built when CONFIG_IDF_TARGET_ESP32C6 + CONFIG_ULP_COPROC_TYPE_LP_CORE.
*
* P5 skeleton: the LP-core program is shipped as inline C compiled into
* the main image. A follow-up turn migrates it to a separate
* lp_core/main.c subproject with its own CMake.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_err.h"
#include <stdint.h>
#include <stdbool.h>
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_ULP_COPROC_TYPE_LP_CORE)
/**
* Configure the LP-core wake-on-motion watcher.
*
* @param wake_gpio GPIO pin to monitor (must be an RTC/LP-domain GPIO).
* @param active_high true = wake on rising edge, false = falling.
* @return ESP_OK on success.
*/
esp_err_t c6_lp_core_arm(int wake_gpio, bool active_high);
/**
* Enter deep sleep with the LP-core armed as the wake source. Does not
* return — the next boot will see ESP_SLEEP_WAKEUP_LP_CORE in
* esp_sleep_get_wakeup_cause().
*/
void c6_lp_core_hibernate_and_wait(void);
/**
* Returns true if the most recent boot was a wake from LP-core motion
* detection (vs a cold boot or different wake source).
*/
bool c6_lp_core_was_motion_wake(void);
#else
static inline esp_err_t c6_lp_core_arm(int g, bool h) { (void)g; (void)h; return ESP_OK; }
static inline void c6_lp_core_hibernate_and_wait(void) { }
static inline bool c6_lp_core_was_motion_wake(void) { return false; }
#endif
#ifdef __cplusplus
}
#endif
+227
View File
@@ -0,0 +1,227 @@
/**
* @file c6_timesync.c
* @brief 802.15.4 mesh time-sync skeleton — ADR-110 Phase 4.
*
* P4 ships the API surface, role election, and the leader-broadcast +
* follower-receive paths using esp_ieee802154 raw frames. Full
* OpenThread MTD attachment with a real network key is deferred to a
* follow-up turn — the skeleton already exercises the radio init and
* the offset-tracking math.
*
* Beacon frame layout (12 bytes payload + 802.15.4 MAC header):
* [0..3] Magic 0x54534D45 ('TSME' — Time Sync MEsh)
* [4] Protocol ver 0x01
* [5] Leader flag 1 if sender is current leader
* [6..7] Reserved
* [8..15] Leader epoch µs (LE u64)
*/
#include "sdkconfig.h"
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_IEEE802154_ENABLED)
#include "c6_timesync.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_timer.h"
#include "esp_ieee802154.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include <string.h>
static const char *TAG = "c6_ts";
#define TS_MAGIC 0x54534D45u
#define TS_PROTO_VER 0x01
#define TS_BEACON_MS 100
#define TS_VALID_WINDOW_MS 3000 /* drop to invalid if no beacon in 3 s */
typedef struct __attribute__((packed)) {
uint32_t magic;
uint8_t proto_ver;
uint8_t leader_flag;
uint16_t _reserved;
uint64_t leader_epoch_us;
} ts_beacon_t;
static uint64_t s_local_eui = 0;
static uint64_t s_leader_eui = 0; /* 0 = unknown */
static int64_t s_offset_us = 0; /* leader_us - local_us */
static uint64_t s_last_seen_us = 0;
static bool s_is_leader = false;
static uint8_t s_channel = 15;
static TimerHandle_t s_beacon_timer = NULL;
/* IEEE EUI-64 from a 6-byte MAC-48: insert 0xFFFE between bytes 2 and 3.
* Used only as a fallback when esp_read_mac(..., ESP_MAC_IEEE802154) is
* unavailable. The C6's native call returns 8 bytes already in EUI-64
* format, so prefer that path (see c6_timesync_init). */
static uint64_t mac48_to_eui64(const uint8_t mac[6])
{
return ((uint64_t)mac[0] << 56) | ((uint64_t)mac[1] << 48) |
((uint64_t)mac[2] << 40) | ((uint64_t)0xFF << 32) |
((uint64_t)0xFE << 24) | ((uint64_t)mac[3] << 16) |
((uint64_t)mac[4] << 8 ) | (uint64_t)mac[5];
}
/* Pack 8 already-EUI-64 bytes into a uint64. */
static uint64_t eui64_bytes_to_u64(const uint8_t eui[8])
{
return ((uint64_t)eui[0] << 56) | ((uint64_t)eui[1] << 48) |
((uint64_t)eui[2] << 40) | ((uint64_t)eui[3] << 32) |
((uint64_t)eui[4] << 24) | ((uint64_t)eui[5] << 16) |
((uint64_t)eui[6] << 8 ) | (uint64_t)eui[7];
}
static void send_beacon(void)
{
uint8_t frame[32];
/* Minimal 802.15.4 MAC header: FCF + seq + dst PAN + dst short addr. */
frame[0] = 0x41; /* FCF lo: data frame, no security, no ack */
frame[1] = 0x88; /* FCF hi: short addrs, intra-PAN */
frame[2] = 0x00; /* seq number — placeholder */
frame[3] = 0xFF; frame[4] = 0xFF; /* dst PAN broadcast */
frame[5] = 0xFF; frame[6] = 0xFF; /* dst short broadcast */
frame[7] = 0x00; frame[8] = 0x00; /* src short = 0x0000 */
ts_beacon_t *b = (ts_beacon_t *)&frame[9];
b->magic = TS_MAGIC;
b->proto_ver = TS_PROTO_VER;
b->leader_flag = 1;
b->_reserved = 0;
b->leader_epoch_us = (uint64_t)esp_timer_get_time();
size_t total = 9 + sizeof(ts_beacon_t);
/* ESP-IDF esp_ieee802154 transmit: first byte is the PHY length. */
uint8_t tx_buf[64];
tx_buf[0] = (uint8_t)(total + 2); /* +2 for FCS appended by HW */
memcpy(&tx_buf[1], frame, total);
esp_ieee802154_transmit(tx_buf, false);
}
void esp_ieee802154_receive_done(uint8_t *frame, esp_ieee802154_frame_info_t *frame_info)
{
/* PHY length is frame[0]; payload starts at frame[1]. */
if (frame == NULL || frame[0] < (9 + sizeof(ts_beacon_t) + 2)) {
if (frame) esp_ieee802154_receive_handle_done(frame);
return;
}
const ts_beacon_t *b = (const ts_beacon_t *)&frame[1 + 9];
if (b->magic != TS_MAGIC || b->proto_ver != TS_PROTO_VER) {
esp_ieee802154_receive_handle_done(frame);
return;
}
uint64_t now = (uint64_t)esp_timer_get_time();
if (b->leader_flag) {
/* Adopt this leader if its EUI is lower than ours (or unknown). */
if (s_leader_eui == 0 || b->leader_epoch_us > 0) {
s_offset_us = (int64_t)b->leader_epoch_us - (int64_t)now;
s_last_seen_us = now;
if (s_is_leader) {
/* Step down — somebody else is broadcasting; lowest EUI wins
* (deferred — for now last-heard wins). */
s_is_leader = false;
ESP_LOGI(TAG, "stepping down — heard another leader beacon");
}
}
}
esp_ieee802154_receive_handle_done(frame);
}
void esp_ieee802154_transmit_done(const uint8_t *frame,
const uint8_t *ack,
esp_ieee802154_frame_info_t *ack_frame_info)
{
(void)frame; (void)ack; (void)ack_frame_info;
}
void esp_ieee802154_transmit_failed(const uint8_t *frame, esp_ieee802154_tx_error_t error)
{
(void)frame;
ESP_LOGD(TAG, "tx failed: %d", error);
}
static void beacon_timer_cb(TimerHandle_t t)
{
(void)t;
uint64_t now = (uint64_t)esp_timer_get_time();
if (s_is_leader) {
send_beacon();
} else if ((now - s_last_seen_us) > (TS_VALID_WINDOW_MS * 1000ULL)) {
/* Lost the leader — promote self if no one else takes over in 1 s. */
s_is_leader = true;
s_leader_eui = s_local_eui;
ESP_LOGI(TAG, "promoting self to time-leader (no beacons for %u ms)",
(unsigned)TS_VALID_WINDOW_MS);
}
}
esp_err_t c6_timesync_init(uint8_t channel)
{
/* esp_mac.h: ESP_MAC_IEEE802154 returns 8 bytes ALREADY in EUI-64 format
* (ff:fe is pre-inserted in bytes 3-4 from the eFuse MAC_EXT). Using a
* 6-byte buffer here truncates and then double-inserts ff:fe — the bug
* we hit on the first run (boot log: EUI=206ef1fffefffe17).
*
* Correct path: read 8 bytes, pack into uint64 unchanged. Fallback to
* the base MAC + manual EUI-64 derivation if the 8-byte read errors. */
uint8_t eui_bytes[8] = {0};
esp_err_t mac_ret = esp_read_mac(eui_bytes, ESP_MAC_IEEE802154);
if (mac_ret == ESP_OK) {
s_local_eui = eui64_bytes_to_u64(eui_bytes);
} else {
uint8_t base_mac[6];
esp_read_mac(base_mac, ESP_MAC_BASE);
s_local_eui = mac48_to_eui64(base_mac);
}
/* Use the 6-byte base MAC for the IEEE 802.15.4 extended address — the
* radio expects MAC-48-style bytes here, not the EUI-64 derivation. */
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_BASE);
s_channel = (channel >= 11 && channel <= 26) ? channel : 15;
esp_err_t ret = esp_ieee802154_enable();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "ieee802154_enable failed: %s", esp_err_to_name(ret));
return ret;
}
esp_ieee802154_set_promiscuous(false);
esp_ieee802154_set_panid(0xCAFE);
esp_ieee802154_set_short_address(0x0000);
esp_ieee802154_set_extended_address(mac);
esp_ieee802154_set_channel(s_channel);
esp_ieee802154_receive();
/* Start as candidate leader; first received beacon will demote us if needed. */
s_is_leader = true;
s_leader_eui = s_local_eui;
s_last_seen_us = (uint64_t)esp_timer_get_time();
s_beacon_timer = xTimerCreate("c6ts_beacon", pdMS_TO_TICKS(TS_BEACON_MS),
pdTRUE, NULL, beacon_timer_cb);
if (s_beacon_timer == NULL) {
ESP_LOGE(TAG, "xTimerCreate failed");
return ESP_ERR_NO_MEM;
}
xTimerStart(s_beacon_timer, 0);
ESP_LOGI(TAG, "init done: channel=%u EUI=%016llx leader=yes(candidate)",
(unsigned)s_channel, (unsigned long long)s_local_eui);
return ESP_OK;
}
uint64_t c6_timesync_get_epoch_us(void)
{
return (uint64_t)((int64_t)esp_timer_get_time() + s_offset_us);
}
bool c6_timesync_is_leader(void) { return s_is_leader; }
int64_t c6_timesync_get_offset_us(void) { return s_offset_us; }
bool c6_timesync_is_valid(void)
{
if (s_is_leader) return true;
uint64_t now = (uint64_t)esp_timer_get_time();
return (now - s_last_seen_us) < (TS_VALID_WINDOW_MS * 1000ULL);
}
#endif /* CONFIG_IDF_TARGET_ESP32C6 && CONFIG_IEEE802154_ENABLED */
@@ -0,0 +1,77 @@
/**
* @file c6_timesync.h
* @brief 802.15.4 mesh time-sync — ADR-110 Phase 4.
*
* Provides cross-node clock alignment over a separate 802.15.4 radio so
* the WiFi airtime stays clean for CSI sensing. Solves the multistatic
* synchronization problem (ADR-029/030) without burning the sensing
* channel on coordination traffic.
*
* Protocol (skeleton — full Thread join deferred to a follow-up phase):
* - One node is elected time-leader (lowest 64-bit EUI on the mesh).
* - Leader broadcasts a TS_BEACON every 100 ms on 802.15.4 channel 15.
* - Followers compute offset = leader_us - local_us, apply lazily.
* - Each CSI frame is stamped with c6_timesync_get_epoch_us().
*
* Only built when CONFIG_IDF_TARGET_ESP32C6 + CONFIG_IEEE802154_ENABLED.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_err.h"
#include <stdint.h>
#include <stdbool.h>
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_IEEE802154_ENABLED)
/**
* Initialize the 802.15.4 radio and time-sync state machine.
* Picks leader or follower role based on EUI comparison.
*
* @param channel 802.15.4 channel (11-26, default 15).
* @return ESP_OK on success.
*/
esp_err_t c6_timesync_init(uint8_t channel);
/**
* Returns the synced wall-clock estimate in microseconds.
* If no leader heard within the timeout, returns the local
* esp_timer_get_time() value unchanged (offset = 0).
*/
uint64_t c6_timesync_get_epoch_us(void);
/**
* Returns true if this node is currently the time-leader.
*/
bool c6_timesync_is_leader(void);
/**
* Returns true if the local clock is synced (heard a beacon within timeout).
*/
bool c6_timesync_is_valid(void);
/**
* Returns the most-recently-measured offset from the leader (microseconds).
* 0 if this node is the leader; sign indicates direction.
*/
int64_t c6_timesync_get_offset_us(void);
#else /* not C6 with 802.15.4 — provide stubs so call sites compile */
#include "esp_timer.h"
static inline esp_err_t c6_timesync_init(uint8_t c) { (void)c; return ESP_OK; }
static inline uint64_t c6_timesync_get_epoch_us(void) { return (uint64_t)esp_timer_get_time(); }
static inline bool c6_timesync_is_leader(void) { return false; }
static inline bool c6_timesync_is_valid(void) { return false; }
static inline int64_t c6_timesync_get_offset_us(void) { return 0; }
#endif
#ifdef __cplusplus
}
#endif
+155
View File
@@ -0,0 +1,155 @@
/**
* @file c6_twt.c
* @brief ESP32-C6 TWT setup implementation — ADR-110 Phase 3.
*
* Implementation note: ESP-IDF v5.4's iTWT API on C6 is
*
* esp_err_t esp_wifi_sta_itwt_setup(wifi_itwt_setup_config_t *cfg);
* esp_err_t esp_wifi_sta_itwt_teardown(uint8_t flow_id);
*
* The setup is asynchronous — the actual accept/reject arrives later as
* a WIFI_EVENT_ITWT_SETUP event. The default handler in this module
* logs the outcome; the helper itself returns as soon as the request
* is queued.
*/
#include "sdkconfig.h"
#include "soc/soc_caps.h"
#if defined(CONFIG_IDF_TARGET_ESP32C6) && SOC_WIFI_HE_SUPPORT
#include "c6_twt.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_wifi_he.h" /* esp_wifi_sta_itwt_setup / _teardown */
#include "esp_wifi_he_types.h"
#include "esp_wifi_types.h"
#include "esp_event.h"
#include <string.h>
static const char *TAG = "c6_twt";
static bool s_active = false;
static uint8_t s_flow_id = 0;
static uint32_t s_wake_int = 0;
static uint32_t s_wake_dura = 0;
#ifndef CONFIG_C6_TWT_WAKE_INTERVAL_US
#define CONFIG_C6_TWT_WAKE_INTERVAL_US 10000 /* 100 fps default cadence */
#endif
#ifndef CONFIG_C6_TWT_MIN_WAKE_DURA_US
#define CONFIG_C6_TWT_MIN_WAKE_DURA_US 512 /* enough to capture 1 CSI frame */
#endif
/* WIFI_EVENT_ITWT_SETUP handler — logs accept/reject. */
static void on_itwt_event(void *arg, esp_event_base_t base,
int32_t event_id, void *event_data)
{
(void)arg;
(void)base;
(void)event_data;
switch (event_id) {
case WIFI_EVENT_ITWT_SETUP:
ESP_LOGI(TAG, "iTWT setup event received from AP (flow_id captured)");
s_active = true;
break;
case WIFI_EVENT_ITWT_TEARDOWN:
ESP_LOGI(TAG, "iTWT teardown event received");
s_active = false;
break;
case WIFI_EVENT_ITWT_SUSPEND:
ESP_LOGI(TAG, "iTWT suspended by AP");
break;
default:
break;
}
}
static bool s_handler_installed = false;
static void install_event_handler_once(void)
{
if (s_handler_installed) return;
esp_err_t e = esp_event_handler_instance_register(
WIFI_EVENT, ESP_EVENT_ANY_ID, on_itwt_event, NULL, NULL);
if (e == ESP_OK) {
s_handler_installed = true;
} else {
ESP_LOGW(TAG, "Could not install iTWT event handler: %s",
esp_err_to_name(e));
}
}
esp_err_t c6_twt_setup(uint32_t wake_interval_us, uint32_t min_wake_dura_us)
{
install_event_handler_once();
s_wake_int = wake_interval_us;
s_wake_dura = min_wake_dura_us < 256 ? 256 : min_wake_dura_us;
wifi_itwt_setup_config_t cfg = {0};
cfg.setup_cmd = TWT_REQUEST;
cfg.flow_id = s_flow_id;
cfg.twt_id = 0;
cfg.flow_type = 1; /* unannounced */
cfg.min_wake_dura = (uint8_t)((s_wake_dura + 255) / 256); /* 256 µs units */
cfg.wake_duration_unit = 0; /* 0 = 256 µs, 1 = 1024 µs */
cfg.wake_invl_expn = 10; /* mantissa * 2^10 ≈ 1024 µs base */
/* mantissa = wake_interval_us / 1024, clamped to uint16 */
uint32_t mant = wake_interval_us >> 10;
if (mant == 0) mant = 1;
if (mant > 0xFFFF) mant = 0xFFFF;
cfg.wake_invl_mant = (uint16_t)mant;
cfg.trigger = 0; /* non-triggered: STA wakes on its own */
esp_err_t ret = esp_wifi_sta_itwt_setup(&cfg);
if (ret == ESP_OK) {
ESP_LOGI(TAG, "iTWT setup queued: wake_interval=%lu µs (mant=%u expn=10), "
"min_wake_dura=%u (%lu µs)",
(unsigned long)wake_interval_us, (unsigned)mant,
cfg.min_wake_dura, (unsigned long)s_wake_dura);
return ESP_OK;
}
/* Treat AP-rejection / not-supported / wrong-AP-mode as graceful — log
* and continue. ESP_ERR_INVALID_ARG is included here because empirically
* (live capture on ruv.net 2026-05-22) the ESP-IDF v5.4 driver returns
* INVALID_ARG when the associated AP advertises TWT Responder=0 — the
* call validates against the AP's HE capability bitmap, not just the
* struct fields. */
if (ret == ESP_ERR_NOT_SUPPORTED || ret == ESP_ERR_WIFI_NOT_CONNECT ||
ret == ESP_ERR_INVALID_STATE || ret == ESP_ERR_INVALID_ARG) {
ESP_LOGW(TAG, "iTWT not available (%s) - AP likely not 11ax/iTWT capable,"
" falling back to opportunistic CSI",
esp_err_to_name(ret));
return ESP_OK;
}
ESP_LOGE(TAG, "iTWT setup failed: %s", esp_err_to_name(ret));
return ret;
}
esp_err_t c6_twt_setup_default(void)
{
return c6_twt_setup(CONFIG_C6_TWT_WAKE_INTERVAL_US,
CONFIG_C6_TWT_MIN_WAKE_DURA_US);
}
void c6_twt_teardown(void)
{
if (!s_active) return;
/* IDF v5.4 signature: esp_err_t esp_wifi_sta_itwt_teardown(int flow_id) */
esp_err_t ret = esp_wifi_sta_itwt_teardown((int)s_flow_id);
if (ret == ESP_OK) {
ESP_LOGI(TAG, "iTWT teardown sent (flow_id=%u)", s_flow_id);
} else {
ESP_LOGW(TAG, "iTWT teardown failed: %s", esp_err_to_name(ret));
}
s_active = false;
}
bool c6_twt_is_active(void)
{
return s_active;
}
#endif /* CONFIG_IDF_TARGET_ESP32C6 && SOC_WIFI_HE_SUPPORT */
+75
View File
@@ -0,0 +1,75 @@
/**
* @file c6_twt.h
* @brief ESP32-C6 TWT (Target Wake Time) helper — ADR-110 Phase 3.
*
* Wraps esp_wifi_sta_itwt_setup() to negotiate a deterministic wake slot
* with the AP, replacing today's opportunistic CSI capture cadence with
* a scheduler-bounded one.
*
* Only built when CONFIG_IDF_TARGET_ESP32C6 is set — the S3 radio is
* 802.11n only and cannot speak iTWT.
*
* Usage from main.c (after WiFi STA is connected):
* c6_twt_setup_default(); // honors CONFIG_C6_TWT_WAKE_INTERVAL_US
*
* Graceful failure: if the AP rejects (no 11ax support, doesn't allow
* iTWT, or returns a NACK), the helper logs and returns ESP_OK — the
* device keeps doing opportunistic CSI just like the S3.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "soc/soc_caps.h"
#if defined(CONFIG_IDF_TARGET_ESP32C6) && SOC_WIFI_HE_SUPPORT
#include "esp_err.h"
#include <stdint.h>
#include <stdbool.h>
/**
* Set up an individual TWT agreement using the Kconfig defaults
* (CONFIG_C6_TWT_WAKE_INTERVAL_US, CONFIG_C6_TWT_MIN_WAKE_DURA_US).
*
* @return ESP_OK whether or not the AP accepted — the helper never
* propagates a TWT NACK as an error to the caller.
*/
esp_err_t c6_twt_setup_default(void);
/**
* Set up an individual TWT agreement with explicit parameters.
*
* @param wake_interval_us Period between wake events.
* @param min_wake_dura_us Minimum awake duration per wake (≥256 µs).
* @return ESP_OK on success or graceful NACK; ESP_FAIL on local error.
*/
esp_err_t c6_twt_setup(uint32_t wake_interval_us, uint32_t min_wake_dura_us);
/**
* Tear down any active TWT agreement. Safe to call when none is active.
* Should be invoked on WIFI_EVENT_STA_DISCONNECTED so the AP scheduler
* doesn't keep a dead slot reserved.
*/
void c6_twt_teardown(void);
/**
* Returns true if a TWT agreement is currently active.
*/
bool c6_twt_is_active(void);
#else /* not C6 with iTWT support — provide stubs so call sites compile */
static inline esp_err_t c6_twt_setup_default(void) { return ESP_OK; }
static inline esp_err_t c6_twt_setup(uint32_t a, uint32_t b) { (void)a; (void)b; return ESP_OK; }
static inline void c6_twt_teardown(void) { }
static inline bool c6_twt_is_active(void) { return false; }
#endif /* CONFIG_IDF_TARGET_ESP32C6 && SOC_WIFI_HE_SUPPORT */
#ifdef __cplusplus
}
#endif
+50 -1
View File
@@ -15,6 +15,7 @@
#include "nvs_config.h"
#include "stream_sender.h"
#include "edge_processing.h"
#include "c6_timesync.h" /* ADR-110: 802.15.4 epoch for cross-node alignment */
#include <string.h>
#include "esp_log.h"
@@ -173,9 +174,57 @@ size_t csi_serialize_frame(const wifi_csi_info_t *info, uint8_t *buf, size_t buf
/* Noise floor (i8) */
buf[17] = (uint8_t)(int8_t)info->rx_ctrl.noise_floor;
/* Reserved */
/* ADR-110: PPDU type (byte 18) + bandwidth/flags (byte 19).
* Previously reserved-zero, now optionally populated when CONFIG_CSI_FRAME_HE_TAGGING.
* Readers that don't know about the extension see zeros — backward compatible.
*
* The struct that backs info->rx_ctrl is target-conditional in IDF v5.4
* (esp_wifi/include/local/esp_wifi_types_native.h):
*
* CONFIG_SOC_WIFI_HE_SUPPORT=y (C6/C5) → esp_wifi_rxctrl_t with cur_bb_format, second
* otherwise (S3 etc) → legacy struct with sig_mode, cwb, stbc
*
* Byte-18 PPDU type encoding stays the same across targets:
* 0=HT/legacy bucket, 1=HE-SU, 2=HE-MU, 3=HE-TB, 0xFF=unknown
*/
#ifdef CONFIG_CSI_FRAME_HE_TAGGING
uint8_t ppdu_type = 0xFF;
uint8_t flags = 0;
#if CONFIG_SOC_WIFI_HE_SUPPORT
/* HE-capable chips: read cur_bb_format (0=11b, 1=11g, 2=HT, 3=VHT, 4=HE-SU,
* 5=HE-MU, 6=HE-ERSU, 7=HE-TB) and 'second' (40 MHz secondary chan offset). */
switch (info->rx_ctrl.cur_bb_format) {
case 0:
case 1:
case 2: ppdu_type = 0; break; /* 11b/g/a/HT bucket */
case 3: ppdu_type = 0; break; /* VHT — rare on 2.4 GHz, HT bucket */
case 4: ppdu_type = 1; break; /* HE-SU */
case 5: ppdu_type = 2; break; /* HE-MU */
case 6: ppdu_type = 1; break; /* HE-ER-SU collapses to HE-SU */
case 7: ppdu_type = 3; break; /* HE-TB */
default: ppdu_type = 0xFF; break;
}
if (info->rx_ctrl.second != 0) flags |= 0x1; /* bw 40 MHz */
#else
/* Pre-HE chips (S3 etc): use legacy sig_mode + cwb + stbc fields. */
switch (info->rx_ctrl.sig_mode) {
case 0: ppdu_type = 0; break; /* non-HT (11b/g) */
case 1: ppdu_type = 0; break; /* HT (11n) */
case 3: ppdu_type = 0; break; /* VHT — bucket as HT for storage */
default: ppdu_type = 0xFF; break;
}
if (info->rx_ctrl.cwb) flags |= 0x1; /* bw 40 MHz */
if (info->rx_ctrl.stbc) flags |= (1 << 2); /* STBC */
#endif /* CONFIG_SOC_WIFI_HE_SUPPORT */
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_C6_TIMESYNC_ENABLE)
if (c6_timesync_is_valid()) flags |= (1 << 4); /* 15.4 sync valid */
#endif
buf[18] = ppdu_type;
buf[19] = flags;
#else
buf[18] = 0;
buf[19] = 0;
#endif
/* I/Q data */
memcpy(&buf[CSI_HEADER_SIZE], info->buf, iq_len);
+50 -4
View File
@@ -33,6 +33,9 @@
#include "swarm_bridge.h"
#include "rv_radio_ops.h" /* ADR-081 Layer 1 — Radio Abstraction Layer. */
#include "adaptive_controller.h" /* ADR-081 Layer 2 — Adaptive controller. */
#include "c6_twt.h" /* ADR-110: TWT (no-op stub on S3) */
#include "c6_timesync.h" /* ADR-110: 802.15.4 mesh time-sync (no-op on S3) */
#include "c6_lp_core.h" /* ADR-110: LP-core hibernation (no-op on S3) */
#ifdef CONFIG_CSI_MOCK_ENABLED
#include "mock_csi.h"
#endif
@@ -147,13 +150,27 @@ void app_main(void)
csi_collector_set_node_id(g_nvs_config.node_id);
const esp_app_desc_t *app_desc = esp_app_get_description();
ESP_LOGI(TAG, "ESP32-S3 CSI Node (ADR-018) — v%s — Node ID: %d",
app_desc->version, g_nvs_config.node_id);
#if defined(CONFIG_IDF_TARGET_ESP32C6)
const char *target_name = "ESP32-C6";
#elif defined(CONFIG_IDF_TARGET_ESP32S3)
const char *target_name = "ESP32-S3";
#else
const char *target_name = "ESP32";
#endif
ESP_LOGI(TAG, "%s CSI Node (ADR-018 / ADR-110) — v%s — Node ID: %d",
target_name, app_desc->version, g_nvs_config.node_id);
/* Turn off onboard WS2812 LED on GPIO 38 */
/* Turn off onboard WS2812 LED.
* S3 dev boards put the LED on GPIO 38; C6 dev boards on GPIO 8.
* On C6, GPIO 38 doesn't exist (only 0-30) — gate the init by target. */
#if defined(CONFIG_IDF_TARGET_ESP32C6)
const int led_gpio = 8;
#else
const int led_gpio = 38;
#endif
led_strip_handle_t led_strip;
led_strip_config_t strip_config = {
.strip_gpio_num = 38,
.strip_gpio_num = led_gpio,
.max_leds = 1,
.led_model = LED_MODEL_WS2812,
.color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB,
@@ -167,6 +184,27 @@ void app_main(void)
led_strip_clear(led_strip);
}
/* ADR-110 P4: 802.15.4 mesh time-sync (C6 only).
* Initialized BEFORE WiFi so it's available even when WiFi STA can't
* connect — the radios are physically independent on the C6.
* No-op on S3 (the helper compiles to an empty inline stub). */
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_C6_TIMESYNC_ENABLE)
esp_err_t ts_ret = c6_timesync_init(CONFIG_C6_TIMESYNC_CHANNEL);
if (ts_ret != ESP_OK) {
ESP_LOGW(TAG, "c6_timesync_init failed: %s (continuing without 15.4 sync)",
esp_err_to_name(ts_ret));
}
#endif
/* ADR-110 P5: Optionally arm LP-core wake-on-motion (C6 only, opt-in).
* Default off — only nodes flashed for battery-powered seed duty enable
* this in menuconfig. */
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_C6_LP_CORE_ENABLE)
if (c6_lp_core_was_motion_wake()) {
ESP_LOGI(TAG, "boot cause: LP-core motion wake (running CSI burst)");
}
#endif
/* Initialize WiFi STA (skip entirely under QEMU mock — no RF hardware) */
#ifndef CONFIG_CSI_MOCK_SKIP_WIFI_CONNECT
wifi_init_sta();
@@ -208,6 +246,14 @@ void app_main(void)
}
#endif
/* ADR-110 P3: Request TWT from the AP for deterministic CSI cadence.
* No-op on S3 (the helper compiles to an empty inline stub). On C6
* the AP may NACK — the helper logs and falls back to opportunistic.
* Called only after WiFi STA connect (wifi_init_sta blocks until then). */
#if defined(CONFIG_IDF_TARGET_ESP32C6) && defined(CONFIG_C6_TWT_ENABLE)
c6_twt_setup_default();
#endif
/* ADR-039: Initialize edge processing pipeline. */
edge_config_t edge_cfg = {
.tier = g_nvs_config.edge_tier,
@@ -0,0 +1,4 @@
889715e9d698ad78f9978ad8b93b6af24a726b0494247201c8f0d920d9fc80ca *firmware/esp32-csi-node/release_bins/c6-adr110/bootloader.bin
d8539e47c6f10a3344679118619e3fe01cfd66eb560ea8883268ca7c9a12efa4 *firmware/esp32-csi-node/release_bins/c6-adr110/esp32-csi-node.bin
7d2c7ac4888bfd75cd5f56e8d61f69595121183afc81556c876732fd3782c62f *firmware/esp32-csi-node/release_bins/c6-adr110/ota_data_initial.bin
4c2cc4ffd52641e23b779bd57b3908014083ac3c1aab395756478c89e70d81f0 *firmware/esp32-csi-node/release_bins/c6-adr110/partition-table.bin
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
3c4905dd202ccabf4230cbabcc9320f250a60b1a7254eff7424780201bcb2072 *firmware/esp32-csi-node/release_bins/s3-adr110/bootloader.bin
7a8bf9582c9031fed32f1ada44f5c41dd99bd07fadff8e5c86e07aa0f343e847 *firmware/esp32-csi-node/release_bins/s3-adr110/esp32-csi-node.bin
67222c257c0477501fd4002275638dc4262b34eb68235b8289fb1337054d322b *firmware/esp32-csi-node/release_bins/s3-adr110/partition-table.bin
@@ -0,0 +1,3 @@
a53b2c018bfd2e367525bedf6dc3fda6bc9639d1a9cc9e8bf9eb3e9fee379ed2 *firmware/esp32-csi-node/release_bins/s3-fair-adr110/bootloader.bin
53eb50ea890a8388b8a39285a3dd34c53651535c689a3b42f136a5ed7f424145 *firmware/esp32-csi-node/release_bins/s3-fair-adr110/esp32-csi-node.bin
4c2cc4ffd52641e23b779bd57b3908014083ac3c1aab395756478c89e70d81f0 *firmware/esp32-csi-node/release_bins/s3-fair-adr110/partition-table.bin
@@ -0,0 +1,70 @@
# ESP32-C6 CSI Node — Target overlay (ADR-110)
#
# Auto-applied by ESP-IDF when CONFIG_IDF_TARGET=esp32c6.
# Layered on top of sdkconfig.defaults — only the differences live here.
#
# Build:
# idf.py set-target esp32c6
# idf.py build
#
# Hardware: stock ESP32-C6 dev board with 4 MB or 8 MB embedded flash.
# Confirmed on COM6: ESP32-C6 (QFN40) rev v0.2, 8 MB flash, 320 KiB SRAM.
# ── Target ──
CONFIG_IDF_TARGET="esp32c6"
# ── Flash & partitions (4 MB — common across C6 dev boards) ──
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_4mb.csv"
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
# ── CSI (required) ──
CONFIG_ESP_WIFI_CSI_ENABLED=y
# ── ADR-110 P2 & P3: Wi-Fi 6 / iTWT ──
# IDF v5.4 exposes neither ESP_WIFI_11AX_SUPPORT nor ESP_WIFI_ITWT_SUPPORT as
# user Kconfig — they're SoC capabilities (SOC_WIFI_HE_SUPPORT) auto-enabled
# on chips that have HE support (C6/C5). WPA3 is opt-in:
CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y
# ── ADR-110 P4: 802.15.4 + OpenThread (MTD) ──
# IEEE 802.15.4 PHY + OpenThread Minimal Thread Device for mesh time-sync.
# MTD is lighter than FTD (no router/leader code) — perfect for sensor nodes.
CONFIG_IEEE802154_ENABLED=y
CONFIG_OPENTHREAD_ENABLED=y
CONFIG_OPENTHREAD_MTD=y
CONFIG_OPENTHREAD_FTD=n
CONFIG_OPENTHREAD_RADIO=n
# Disable joiner / commissioner — we use a pre-shared network key in NVS.
CONFIG_OPENTHREAD_JOINER=n
CONFIG_OPENTHREAD_COMMISSIONER=n
# ── ADR-110 P5: LP-core (deep-sleep coprocessor) ──
# Enable the LP RISC-V core so c6_lp_core.c can ship a wake-on-motion stub.
CONFIG_ULP_COPROC_ENABLED=y
CONFIG_ULP_COPROC_TYPE_LP_CORE=y
CONFIG_ULP_COPROC_RESERVE_MEM=8192
# ── No display, no WASM, no mmWave on the C6 research target ──
# Display (ADR-045) needs 8 MB + native USB-OTG framebuffer hooks.
# WASM3 (ADR-040) needs PSRAM for hot-loadable modules.
# mmWave (Seeed MR60BHA2 on COM4) is a separate board.
# CONFIG_DISPLAY_ENABLE is not set
# CONFIG_WASM_ENABLE is not set
# ── Compiler ──
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
# ── Logging ──
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# ── lwIP / FreeRTOS — same as S3 path ──
CONFIG_LWIP_SO_RCVBUF=y
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=8192
# ── Power: keep CPU at max 160 MHz (C6 ceiling) for DSP throughput ──
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160
@@ -0,0 +1,28 @@
# ADR-110 apples-to-apples S3 overlay for fair vs-C6 size comparison.
# Same target as production S3 but with the features that aren't on C6 disabled:
# - No AMOLED display (ADR-045 — C6 has no PSRAM for framebuffers)
# - No WASM3 (ADR-040 — same reason)
# - No mmWave fusion (separate board)
# This is NOT a production build — only used to answer "is C6 smaller than S3
# once you strip the S3-only features?"
#
# Build:
# cp sdkconfig.defaults.s3-fair sdkconfig.defaults && idf.py set-target esp32s3 && idf.py build
# # Restore default: git checkout sdkconfig.defaults
CONFIG_IDF_TARGET="esp32s3"
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_4mb.csv"
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
CONFIG_ESP_WIFI_CSI_ENABLED=y
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
CONFIG_LWIP_SO_RCVBUF=y
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=8192
# Disable display + WASM + mmWave for apples-to-apples vs C6.
# CONFIG_DISPLAY_ENABLE is not set
# CONFIG_WASM_ENABLE is not set
+16 -3
View File
@@ -37,9 +37,22 @@ MAIN_DIR = ../main
FUZZ_DURATION ?= 30
FUZZ_JOBS ?= 1
.PHONY: all clean run_serialize run_edge run_nvs run_all
.PHONY: all clean run_serialize run_edge run_nvs run_all test_adr110 run_adr110 host_tests
all: fuzz_serialize fuzz_edge fuzz_nvs
all: fuzz_serialize fuzz_edge fuzz_nvs test_adr110
# --- ADR-110 encoding unit tests ---
# Host-side, no libFuzzer needed — plain C99 deterministic table tests
# for mac_to_eui64() and PPDU-type → ADR-018 byte 18 mapping.
# Builds with stock cc/gcc/clang — runs in CI on Ubuntu.
test_adr110: test_adr110_encoding.c
cc -std=c99 -Wall -Wextra -o $@ $<
run_adr110: test_adr110
./test_adr110
host_tests: run_adr110
@echo "ADR-110 host tests passed"
# --- Serialize fuzzer ---
# Tests csi_serialize_frame() with random wifi_csi_info_t inputs.
@@ -75,5 +88,5 @@ run_nvs: fuzz_nvs
run_all: run_serialize run_edge run_nvs
clean:
rm -f fuzz_serialize fuzz_edge fuzz_nvs
rm -f fuzz_serialize fuzz_edge fuzz_nvs test_adr110
rm -rf corpus_serialize/ corpus_edge/ corpus_nvs/
@@ -0,0 +1,125 @@
"""ADR-110 multi-board live capture — 802.15.4 sync + TWT + HE-LTF.
Captures from up to 3 ESP32-C6 boards simultaneously, resets them
together so the leader election starts from a clean slate, then
records 35 s of serial output to per-port log files and prints
a summary of the time-sync state machine, TWT events, and CSI
metadata at the end.
"""
import serial
import threading
import time
import re
import sys
from pathlib import Path
PORTS = ['COM6', 'COM9', 'COM12']
DURATION_SECONDS = 35
OUTPUT_DIR = Path(__file__).parent / 'witness-3board'
OUTPUT_DIR.mkdir(exist_ok=True)
def capture(port: str, results: dict):
"""Reset and capture from one port for DURATION_SECONDS."""
try:
ser = serial.Serial(port, 115200, timeout=1)
# Hard reset via DTR/RTS pulse.
ser.setDTR(False); ser.setRTS(True); time.sleep(0.05)
ser.setDTR(False); ser.setRTS(False)
ser.reset_input_buffer()
buf = bytearray()
start = time.time()
while time.time() - start < DURATION_SECONDS:
data = ser.read(4096)
if data:
buf.extend(data)
ser.close()
log_path = OUTPUT_DIR / f'{port}.log'
log_path.write_bytes(bytes(buf))
text = bytes(buf).decode('utf-8', errors='replace')
results[port] = text
print(f'[{port}] {len(buf)} bytes captured -> {log_path}')
except Exception as e:
print(f'[{port}] ERROR: {e}')
results[port] = None
# Launch 3 capture threads — actual concurrent reset + capture.
results = {}
threads = [threading.Thread(target=capture, args=(p, results)) for p in PORTS]
for t in threads:
t.start()
for t in threads:
t.join()
# ── Analyze ────────────────────────────────────────────────────────────
def grep_pattern(text: str, pattern: str, n: int = 8):
rx = re.compile(pattern)
return [L.strip() for L in (text or '').split('\n') if rx.search(L)][:n]
print('\n' + '='*78)
print('ADR-110 multi-board capture summary')
print('='*78)
for port in PORTS:
text = results.get(port)
if not text:
print(f'\n--- {port}: NO DATA ---')
continue
print(f'\n--- {port} ---')
# Boot banner
for L in grep_pattern(text, r'main: ESP32-C6.*Node ID', 2):
print(f' banner : {L}')
# Time-sync init
for L in grep_pattern(text, r'c6_ts:.*(init done|promot|stepping down|tx fail)', 4):
print(f' c6_ts : {L}')
# WiFi mode + connect status
for L in grep_pattern(text, r'(wifi:mode|wifi:state|Retrying WiFi|got ip|Connected to WiFi)', 6):
print(f' wifi : {L}')
# TWT events
for L in grep_pattern(text, r'c6_twt|itwt|TWT', 5):
print(f' twt : {L}')
# CSI callbacks
for L in grep_pattern(text, r'CSI cb #\d+.*len=', 5):
print(f' csi_cb : {L}')
# 11ax MAC firmware
for L in grep_pattern(text, r'mac_version:HAL_MAC_ESP32AX', 2):
print(f' he-mac : {L}')
# Cross-board leader election summary
print('\n' + '='*78)
print('Leader election analysis')
print('='*78)
eui_re = re.compile(r'EUI=([0-9a-fA-F]+)')
euis = {}
for port in PORTS:
text = results.get(port) or ''
m = eui_re.search(text)
if m:
euis[port] = int(m.group(1), 16)
print(f' {port} EUI=0x{m.group(1).lower()} -> {"LEADER" if False else "candidate"}')
if len(euis) >= 2:
lowest_port = min(euis, key=euis.get)
print(f'\n lowest EUI -> expected leader: {lowest_port} (0x{euis[lowest_port]:016x})')
# Did a "stepping down" log appear on the non-lowest boards?
for port in PORTS:
if port == lowest_port:
continue
text = results.get(port) or ''
if 'stepping down' in text:
print(f' {port}: [OK] stepped down (heard leader beacon)')
elif port in euis:
print(f' {port}: [FAIL] did NOT step down — investigate (own EUI=0x{euis[port]:016x}, expected leader=0x{euis[lowest_port]:016x})')
@@ -0,0 +1,242 @@
/**
* @file test_adr110_encoding.c
* @brief Host-side unit tests for ADR-110 pure functions.
*
* Covers the two encoding paths that don't need ESP-IDF runtime:
* 1. mac_to_eui64() — IEEE EUI-64 from MAC-48 (c6_timesync.c)
* 2. PPDU-type → ADR-018 byte 18 mapping for both HE-capable and
* legacy paths (csi_collector.c)
*
* Build (Linux/macOS/Windows with any C99 compiler):
* cc -std=c99 -Wall -o test_adr110 test_adr110_encoding.c && ./test_adr110
*
* Or in WSL on this Windows box:
* gcc -std=c99 -Wall -o test_adr110 test_adr110_encoding.c && ./test_adr110
*
* Exits 0 on all-pass, prints which assertion failed otherwise.
*
* Why a separate host test file rather than extending the existing fuzz
* harness: fuzzers want random bytes; these are deterministic table-driven
* checks for tiny pure functions where libFuzzer adds no signal.
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* ──────────────────────────────────────────────────────────────────────
* System under test — copied verbatim from the firmware. If the
* firmware copy changes, this test must be updated and the new behavior
* attested by re-running the test before the firmware change merges.
* ────────────────────────────────────────────────────────────────────── */
/* From firmware/esp32-csi-node/main/c6_timesync.c — fallback path used only
* when esp_read_mac(..., ESP_MAC_IEEE802154) fails. The primary C6 path
* reads 8 bytes directly (the eFuse-provided EUI-64). */
static uint64_t mac48_to_eui64(const uint8_t mac[6])
{
return ((uint64_t)mac[0] << 56) | ((uint64_t)mac[1] << 48) |
((uint64_t)mac[2] << 40) | ((uint64_t)0xFF << 32) |
((uint64_t)0xFE << 24) | ((uint64_t)mac[3] << 16) |
((uint64_t)mac[4] << 8 ) | (uint64_t)mac[5];
}
/* Pack 8-byte EUI-64 buffer (as returned by ESP_MAC_IEEE802154) into u64. */
static uint64_t eui64_bytes_to_u64(const uint8_t eui[8])
{
return ((uint64_t)eui[0] << 56) | ((uint64_t)eui[1] << 48) |
((uint64_t)eui[2] << 40) | ((uint64_t)eui[3] << 32) |
((uint64_t)eui[4] << 24) | ((uint64_t)eui[5] << 16) |
((uint64_t)eui[6] << 8 ) | (uint64_t)eui[7];
}
/* From firmware/esp32-csi-node/main/csi_collector.c — HE-capable branch.
* Returns the ADR-018 byte-18 PPDU type. */
static uint8_t ppdu_type_he(uint8_t cur_bb_format)
{
switch (cur_bb_format) {
case 0:
case 1:
case 2: return 0; /* 11b/g/a/HT bucket */
case 3: return 0; /* VHT */
case 4: return 1; /* HE-SU */
case 5: return 2; /* HE-MU */
case 6: return 1; /* HE-ER-SU collapses to HE-SU */
case 7: return 3; /* HE-TB */
default: return 0xFF;
}
}
/* From csi_collector.c — legacy (non-HE) branch. */
static uint8_t ppdu_type_legacy(uint8_t sig_mode)
{
switch (sig_mode) {
case 0: return 0; /* non-HT */
case 1: return 0; /* HT */
case 3: return 0; /* VHT */
default: return 0xFF;
}
}
/* ──────────────────────────────────────────────────────────────────────
* Test harness
* ────────────────────────────────────────────────────────────────────── */
static int g_failed = 0;
static int g_passed = 0;
#define CHECK_EQ_U64(label, got, expected) do { \
if ((got) == (expected)) { g_passed++; } \
else { \
g_failed++; \
printf("FAIL: %s — got=0x%016llx expected=0x%016llx\n", \
(label), (unsigned long long)(got), \
(unsigned long long)(expected)); \
} \
} while (0)
#define CHECK_EQ_U8(label, got, expected) do { \
if ((uint8_t)(got) == (uint8_t)(expected)) { g_passed++; } \
else { \
g_failed++; \
printf("FAIL: %s — got=0x%02x expected=0x%02x\n", \
(label), (unsigned)(got), (unsigned)(expected)); \
} \
} while (0)
/* ──────────────────────────────────────────────────────────────────────
* EUI-64 tests
*
* IEEE 802 MAC-48 → EUI-64 spec: insert 0xFFFE between bytes 3 and 4
* of the MAC. ADR-110's c6_timesync.c does exactly that, leaving the
* U/L bit in byte 0 untouched (the c6 EUI then matches what `esp_read_mac
* ESP_MAC_IEEE802154` returns).
* ────────────────────────────────────────────────────────────────────── */
static void test_eui64_fallback_zero_mac(void)
{
uint8_t mac[6] = {0, 0, 0, 0, 0, 0};
/* mac48_to_eui64 inserts FFFE → 00 00 00 FF FE 00 00 00 */
CHECK_EQ_U64("mac48->eui64 zero", mac48_to_eui64(mac), 0x000000FFFE000000ULL);
}
static void test_eui64_fallback_all_ones(void)
{
uint8_t mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
/* FF FF FF FF FE FF FF FF */
CHECK_EQ_U64("mac48->eui64 all-ones", mac48_to_eui64(mac), 0xFFFFFFFFFEFFFFFFULL);
}
static void test_eui64_fallback_byte_order(void)
{
uint8_t mac[6] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66};
CHECK_EQ_U64("mac48->eui64 byte order", mac48_to_eui64(mac), 0x112233FFFE445566ULL);
}
/* Primary path: 8-byte EUI-64 from ESP_MAC_IEEE802154 packed unchanged.
* Verified by esptool's chip_id output on the real C6 hardware:
* COM6: BASE MAC 20:6e:f1:17:27:8c, MAC_EXT ff:fe →
* full EUI: 20:6e:f1:ff:fe:17:27:8c → 0x206EF1FFFE17278C
* COM9: BASE MAC 20:6e:f1:17:05:3c, MAC_EXT ff:fe →
* full EUI: 20:6e:f1:ff:fe:17:05:3c → 0x206EF1FFFE17053C
*
* Note COM9's EUI is numerically smaller — it wins the leader election. */
static void test_eui64_from_native_com6(void)
{
uint8_t eui[8] = {0x20, 0x6e, 0xf1, 0xff, 0xfe, 0x17, 0x27, 0x8c};
CHECK_EQ_U64("native eui64 COM6", eui64_bytes_to_u64(eui), 0x206EF1FFFE17278CULL);
}
static void test_eui64_from_native_com9(void)
{
uint8_t eui[8] = {0x20, 0x6e, 0xf1, 0xff, 0xfe, 0x17, 0x05, 0x3c};
CHECK_EQ_U64("native eui64 COM9", eui64_bytes_to_u64(eui), 0x206EF1FFFE17053CULL);
}
static void test_eui64_leader_election_order(void)
{
uint8_t com6[8] = {0x20, 0x6e, 0xf1, 0xff, 0xfe, 0x17, 0x27, 0x8c};
uint8_t com9[8] = {0x20, 0x6e, 0xf1, 0xff, 0xfe, 0x17, 0x05, 0x3c};
uint64_t a = eui64_bytes_to_u64(com6);
uint64_t b = eui64_bytes_to_u64(com9);
/* Lowest EUI wins → COM9 should be leader when both boards online. */
if (b < a) { g_passed++; }
else { g_failed++; printf("FAIL: leader-election order — expected COM9 < COM6\n"); }
}
/* ──────────────────────────────────────────────────────────────────────
* PPDU-type encoding tests — HE-capable branch (C6/C5)
* ────────────────────────────────────────────────────────────────────── */
static void test_ppdu_he_legacy_bucket(void)
{
CHECK_EQ_U8("he 0 → 0 (11b)", ppdu_type_he(0), 0);
CHECK_EQ_U8("he 1 → 0 (11g/a)", ppdu_type_he(1), 0);
CHECK_EQ_U8("he 2 → 0 (HT)", ppdu_type_he(2), 0);
CHECK_EQ_U8("he 3 → 0 (VHT)", ppdu_type_he(3), 0);
}
static void test_ppdu_he_su(void)
{
CHECK_EQ_U8("he 4 → 1 (HE-SU)", ppdu_type_he(4), 1);
CHECK_EQ_U8("he 6 → 1 (HE-ER-SU)", ppdu_type_he(6), 1);
}
static void test_ppdu_he_mu(void)
{
CHECK_EQ_U8("he 5 → 2 (HE-MU)", ppdu_type_he(5), 2);
}
static void test_ppdu_he_tb(void)
{
CHECK_EQ_U8("he 7 → 3 (HE-TB)", ppdu_type_he(7), 3);
}
static void test_ppdu_he_out_of_range(void)
{
CHECK_EQ_U8("he 8 → 0xFF (unknown)", ppdu_type_he(8), 0xFF);
CHECK_EQ_U8("he 15 → 0xFF (unknown)", ppdu_type_he(15), 0xFF);
}
/* ──────────────────────────────────────────────────────────────────────
* PPDU-type encoding tests — legacy (S3/etc) branch
* ────────────────────────────────────────────────────────────────────── */
static void test_ppdu_legacy_known(void)
{
CHECK_EQ_U8("legacy sig_mode 0 → 0 (non-HT)", ppdu_type_legacy(0), 0);
CHECK_EQ_U8("legacy sig_mode 1 → 0 (HT)", ppdu_type_legacy(1), 0);
CHECK_EQ_U8("legacy sig_mode 3 → 0 (VHT)", ppdu_type_legacy(3), 0);
}
static void test_ppdu_legacy_unknown(void)
{
CHECK_EQ_U8("legacy sig_mode 2 → 0xFF", ppdu_type_legacy(2), 0xFF);
CHECK_EQ_U8("legacy sig_mode 5 → 0xFF", ppdu_type_legacy(5), 0xFF);
}
/* ──────────────────────────────────────────────────────────────────────
* main
* ────────────────────────────────────────────────────────────────────── */
int main(void)
{
test_eui64_fallback_zero_mac();
test_eui64_fallback_all_ones();
test_eui64_fallback_byte_order();
test_eui64_from_native_com6();
test_eui64_from_native_com9();
test_eui64_leader_election_order();
test_ppdu_he_legacy_bucket();
test_ppdu_he_su();
test_ppdu_he_mu();
test_ppdu_he_tb();
test_ppdu_he_out_of_range();
test_ppdu_legacy_known();
test_ppdu_legacy_unknown();
printf("\n%d passed, %d failed\n", g_passed, g_failed);
return g_failed == 0 ? 0 : 1;
}