ADR-061: 用于固件测试与开发的 QEMU ESP32-S3 仿真¶
| 字段 | 值 |
|---|---|
| 状态 | 已接受 |
| 日期 | 2026-03-13(更新于 2026-03-14) |
| 作者 | RuView 团队 |
| 关联 | ADR-018(二进制帧)、ADR-039(边缘智能)、ADR-040(WASM)、ADR-057(构建保护)、ADR-060(信道/MAC 过滤) |
背景¶
ESP32-S3 CSI 节点固件(firmware/esp32-csi-node/)已扩展到 16 个源文件,涵盖:
| 模块 | 文件 | 可在 QEMU 中测试? |
|---|---|---|
| NVS 配置加载 | nvs_config.c |
是 — 闪存镜像中的 NVS 分区 |
| 边缘处理(DSP) | edge_processing.c |
是 — 纯数学运算,无硬件依赖 |
| ADR-018 帧序列化 | csi_collector.c:csi_serialize_frame() |
是 — 纯缓冲区操作 |
| UDP 流发送器 | stream_sender.c |
是 — QEMU 通过 SLIRP 支持 lwIP |
| WASM 运行时 | wasm_runtime.c |
是 — 仅 CPU |
| OTA 更新 | ota_update.c |
部分 — 需要 HTTP 模拟 |
| 电源管理 | power_mgmt.c |
部分 — 无真实浅睡眠 |
| 显示(OLED) | display_*.c |
否 — I2C 硬件 |
| WiFi CSI 回调 | csi_collector.c:wifi_csi_callback() |
否 — 需要 RF PHY |
| 信道跳变 | csi_collector.c:hop_timer_cb() |
否 — 需要 esp_wifi_set_channel() |
目前,每次代码变更都需要烧录到 COM7 上的物理硬件。这造成了瓶颈:
- 构建 + 烧录周期:约 20 秒
- 串口监视器:手动检查
- 无自动化 CI(GitHub Actions runner 中没有 ESP32-S3)
- 没有硬件的贡献者无法测试固件变更
Espressif 维护着一个官方 QEMU 分支(github.com/espressif/qemu),支持 ESP32-S3 机器,包括双核 Xtensa LX7、闪存映射、UART、GPIO、定时器和 FreeRTOS。
术语表¶
| 术语 | 定义 |
|---|---|
| CSI | 信道状态信息 — 来自 WiFi 的每个子载波幅度/相位 |
| NVS | 非易失性存储 — ESP-IDF 键值闪存分区 |
| TDM | 时分复用 — 节点在分配的时间槽中传输 |
| UART | 通用异步收发器 — 串行控制台输出 |
| SLIRP | 用户态 TCP/IP 协议栈 — 无需 root/TAP 即可实现网络功能 |
| QEMU | 快速模拟器 — 在没有物理硬件的情况下运行 ESP32-S3 固件 |
| QMP | QEMU 机器协议 — 基于 JSON 的控制接口 |
| LFSR | 线性反馈移位寄存器 — 确定性伪随机生成器 |
| SPSC | 单生产者单消费者 — 无锁环形缓冲区模式 |
| FreeRTOS | ESP-IDF 用于任务调度的实时操作系统 |
| gcov/lcov | 用于行/分支分析的 GCC 代码覆盖率工具 |
| libFuzzer | LLVM 覆盖率引导的模糊测试器,用于发现崩溃 |
| ASAN | 地址消毒器 — 检测缓冲区溢出和释放后使用 |
| UBSAN | 未定义行为消毒器 — 检测未定义的 C 行为 |
快速开始¶
前置条件¶
安装所需工具:
# QEMU(支持 ESP32-S3 的 Espressif 分支)
git clone https://github.com/espressif/qemu.git
cd qemu && ./configure --target-list=xtensa-softmmu && make -j$(nproc)
export QEMU_PATH=/path/to/qemu/build/qemu-system-xtensa
# ESP-IDF(用于构建固件)
# 参见 https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/get-started/
# Python 工具
pip install esptool esp-idf-nvs-partition-gen
# 覆盖率工具(可选,第 5 层)
sudo apt install lcov # Debian/Ubuntu
brew install lcov # macOS
# 模糊测试(可选,第 6 层)
sudo apt install clang # Debian/Ubuntu
# 网格测试(可选,第 3 层 — 需要 root 权限)
sudo apt install socat bridge-utils iproute2
运行完整测试套件¶
# 第 2 层:单节点测试(构建 + 运行 + 验证)
bash scripts/qemu-esp32s3-test.sh
# 第 3 层:多节点网格(3 个节点,需要 root 权限)
sudo bash scripts/qemu-mesh-test.sh 3
# 第 6 层:模糊测试(每个目标 60 秒)
cd firmware/esp32-csi-node/test && make all CC=clang
make run_serialize FUZZ_DURATION=60
# 第 7 层:生成 NVS 测试矩阵
python3 scripts/generate_nvs_matrix.py --output-dir build/nvs_matrix
# 第 8 层:快照回归测试
bash scripts/qemu-snapshot-test.sh --create
bash scripts/qemu-snapshot-test.sh --restore csi-streaming
# 第 9 层:混沌/故障注入
bash scripts/qemu-chaos-test.sh --faults all --duration 120
环境变量¶
| 变量 | 默认值 | 描述 |
|---|---|---|
QEMU_PATH |
qemu-system-xtensa |
Espressif QEMU 二进制文件路径 |
QEMU_TIMEOUT |
60(单节点)/ 45(网格)/ 120(混沌) |
测试超时时间(秒) |
SKIP_BUILD |
未设置 | 设置为 1 以跳过固件构建步骤 |
NVS_BIN |
未设置 | 预构建 NVS 分区二进制的路径 |
QEMU_NET |
1 |
设置为 0 以禁用 SLIRP 网络 |
CHAOS_SEED |
当前时间 | 用于可复现混沌测试的种子 |
退出码(所有脚本)¶
| 代码 | 含义 | 操作 |
|---|---|---|
| 0 | 通过 | 所有检查均已通过 |
| 1 | 警告 | 非关键问题;请检查输出 |
| 2 | 失败 | 关键检查失败;请修复后重新运行 |
| 3 | 致命错误 | 构建错误、崩溃或缺少工具;请检查前置条件 |
决策¶
为 ESP32-S3 CSI 节点固件引入一个全面的 QEMU 测试平台,包含九个能力层:
- 模拟 CSI 生成器 — 编译期合成 CSI 帧注入
- QEMU 运行器 — 自动化构建、运行和验证
- 多节点网格模拟 — 跨 QEMU 实例的 TDM 和聚合测试
- GDB 远程调试 — 无需 JTAG 的零成本断点调试
- 代码覆盖率 — 用于路径分析的 gcov/lcov 集成
- 模糊测试 — 针对 CSI 解析器、NVS、WASM 的畸形输入韧性测试
- NVS 配置矩阵 — 穷举配置组合测试
- 快照与重放 — 亚 100ms 状态恢复,实现快速迭代
- 混沌测试 — 用于韧性验证的故障注入
第 1 层:Mock CSI 生成器¶
架构¶
┌─────────────────────────────────────────────────────┐
│ ESP32-S3 Firmware │
│ │
│ ┌─────────────┐ ┌──────────────────────────────┐ │
│ │ Real WiFi │ │ Mock CSI Generator │ │
│ │ CSI Callback │ OR │ (timer → synthetic frames) │ │
│ │ (HW only) │ │ (QEMU + unit tests) │ │
│ └──────┬───────┘ └──────────┬───────────────────┘ │
│ │ │ │
│ └───────────┬───────────┘ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ edge_enqueue_csi() → SPSC ring → DSP Core 1 │ │
│ │ ├── Biquad bandpass (breathing / heart rate) │ │
│ │ ├── Phase unwrapping + Welford stats │ │
│ │ ├── Top-K subcarrier selection │ │
│ │ ├── Presence detection (adaptive threshold) │ │
│ │ ├── Fall detection (phase acceleration) │ │
│ │ └── Multi-person vitals clustering │ │
│ └──────────────────┬───────────────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ csi_serialize_frame() → ADR-018 binary format │ │
│ │ stream_sender_send() → UDP to aggregator │ │
│ │ edge vitals packet → 0xC5110002 (32 bytes) │ │
│ └──────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
Mock CSI 生成器设计¶
当 CONFIG_CSI_MOCK_ENABLED=y(Kconfig 选项)时,构建会用一个周期性定时器替换 esp_wifi_set_csi_config() / esp_wifi_set_csi_rx_cb(),该定时器注入合成 CSI 帧:
// mock_csi.c — synthetic CSI frame generator
#define MOCK_CSI_INTERVAL_MS 50 // 20 Hz (matches real CSI rate)
#define MOCK_N_SUBCARRIERS 52 // HT20 mode
#define MOCK_IQ_LEN (MOCK_N_SUBCARRIERS * 2) // I + Q bytes
typedef struct {
uint8_t scenario; // 0=empty, 1=person_static, 2=person_walking, 3=fall
uint32_t frame_count;
float person_x; // Simulated position [0..1]
float person_speed; // Movement speed per frame
uint8_t breathing_phase; // Simulated breathing cycle
} mock_state_t;
// Generates realistic CSI I/Q data:
// - Empty room: Gaussian noise + stable phase (low variance)
// - Static person: Phase shift proportional to distance, breathing modulation
// - Walking person: Progressive phase drift + Doppler-like amplitude change
// - Fall event: Sudden phase acceleration spike
void mock_generate_csi_frame(mock_state_t *state, wifi_csi_info_t *out_info);
信号模型¶
合成 CSI 生成器将子载波幅度和相位建模为:
A_k(t) = A_base + A_person * exp(-d_k²/σ²) + noise
φ_k(t) = φ_base + (2π * d / λ) + breathing_mod(t) + noise
where:
k = subcarrier index
d_k = simulated distance effect on subcarrier k
A_person = amplitude perturbation from human body (scenario-dependent)
d = simulated person-to-antenna distance
λ = wavelength at subcarrier frequency
breathing_mod(t) = sin(2π * f_breath * t) * amplitude_breath
noise = Gaussian, σ tuned to match real ESP32-S3 CSI noise floor (~-90 dBm)
该模型用于验证:
- 存在检测(幅度方差超过阈值)
- 呼吸率提取(0.1-0.5 Hz 的周期性相位调制)
- 跌倒检测(突然相位加速度超过 fall_thresh)
- 多人分离(具有不同呼吸频率的明显子载波组)
场景¶
| ID | 场景 | 持续时间 | 预期输出 |
|---|---|---|---|
| 0 | 空房间 | 10 秒 | presence=0,motion_energy < thresh |
| 1 | 静止人员 | 10 秒 | presence=1,breathing_rate ∈ [10,25],fall=0 |
| 2 | 行走人员 | 10 秒 | presence=1,motion_energy > 0.5,fall=0 |
| 3 | 跌倒事件 | 5 秒 | fall=1 标志置位,motion_energy 尖峰 |
| 4 | 多人 | 15 秒 | n_persons=2,独立呼吸频率 |
| 5 | 信道扫描 | 5 秒 | 依次在信道 1、6、11 上产生帧 |
| 6 | MAC 过滤测试 | 5 秒 | MAC 错误的帧被丢弃(计数器检查) |
| 7 | 环形缓冲区溢出 | 3 秒 | 100ms 突发 1000 帧,优雅丢弃 |
| 8 | 边界 RSSI | 5 秒 | RSSI 从 -90 到 -10 dBm 扫描,无崩溃 |
| 9 | 零长度帧 | 2 秒 | iq_len=0 帧,序列化返回 0 |
第 2 层:QEMU 运行器与 CI¶
QEMU 运行器脚本¶
#!/bin/bash
# scripts/qemu-esp32s3-test.sh
set -euo pipefail
FIRMWARE_DIR="firmware/esp32-csi-node"
BUILD_DIR="$FIRMWARE_DIR/build"
QEMU_BIN="${QEMU_PATH:-qemu-system-xtensa}"
FLASH_IMAGE="$BUILD_DIR/qemu_flash.bin"
LOG_FILE="$BUILD_DIR/qemu_output.log"
TIMEOUT_SEC="${QEMU_TIMEOUT:-60}"
echo "=== QEMU ESP32-S3 Firmware Test ==="
# 1. Build with mock CSI enabled
echo "[1/4] Building firmware (mock CSI mode)..."
idf.py -C "$FIRMWARE_DIR" \
-D SDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.qemu" \
build
# 2. Merge binaries into single flash image
echo "[2/4] Creating merged flash image..."
esptool.py --chip esp32s3 merge_bin -o "$FLASH_IMAGE" \
--flash_mode dio --flash_freq 80m --flash_size 8MB \
0x0 "$BUILD_DIR/bootloader/bootloader.bin" \
0x8000 "$BUILD_DIR/partition_table/partition-table.bin" \
0xf000 "$BUILD_DIR/ota_data_initial.bin" \
0x20000 "$BUILD_DIR/esp32-csi-node.bin"
# 3. Optionally inject pre-provisioned NVS partition
if [ -f "$BUILD_DIR/nvs_test.bin" ]; then
echo "[2b] Injecting pre-provisioned NVS partition..."
dd if="$BUILD_DIR/nvs_test.bin" of="$FLASH_IMAGE" \
bs=1 seek=$((0x9000)) conv=notrunc
fi
# 4. Run in QEMU with timeout, capture UART output
echo "[3/4] Running QEMU (timeout: ${TIMEOUT_SEC}s)..."
timeout "$TIMEOUT_SEC" "$QEMU_BIN" \
-machine esp32s3 \
-nographic \
-drive file="$FLASH_IMAGE",if=mtd,format=raw \
-serial mon:stdio \
-no-reboot \
2>&1 | tee "$LOG_FILE" || true
# 5. Validate expected output
echo "[4/4] Validating output..."
python3 scripts/validate_qemu_output.py "$LOG_FILE"
QEMU sdkconfig 覆盖层(sdkconfig.qemu)¶
# Enable mock CSI generator (disables real WiFi CSI)
CONFIG_CSI_MOCK_ENABLED=y
# Skip WiFi STA connection (no AP in QEMU)
CONFIG_CSI_MOCK_SKIP_WIFI_CONNECT=y
# Run all scenarios sequentially
CONFIG_CSI_MOCK_SCENARIO=255
# Use loopback for UDP (QEMU SLIRP provides 10.0.2.x network)
CONFIG_CSI_TARGET_IP="10.0.2.2"
# Shorter test durations
CONFIG_CSI_MOCK_SCENARIO_DURATION_MS=5000
# Enable verbose logging for validation
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
CONFIG_CSI_MOCK_LOG_FRAMES=y
输出验证脚本¶
scripts/validate_qemu_output.py 解析 UART 日志并检查:
| 检查项 | 通过标准 | 严重级别 |
|---|---|---|
| 启动 | app_main() 被调用,无 panic/assert |
FATAL |
| NVS 加载 | 存在 nvs_config: 日志行 |
FATAL |
| 模拟 CSI 初始化 | mock_csi: Starting mock CSI generator |
FATAL |
| 帧生成 | mock_csi: Generated N frames,其中 N > 0 |
ERROR |
| 边缘流水线 | edge_processing: DSP task started on Core 1 |
ERROR |
| 生命体征输出 | 至少一条 vitals: 日志行且 BPM 有效 |
ERROR |
| 存在检测 | 在人员场景期间出现 presence=1 |
WARN |
| 跌倒检测 | 在跌倒场景期间出现 fall=1 |
WARN |
| MAC 过滤 | csi_collector: MAC filter dropped N frames,其中 N > 0 |
WARN |
| ADR-018 序列化 | csi_collector: Serialized N frames,其中 N > 0 |
ERROR |
| 无崩溃 | 无 Guru Meditation Error、无 assert failed、无 abort() |
FATAL |
| 正常退出 | 固件到达场景序列末尾 | ERROR |
| 堆正常 | 无 HEAP_ERROR 或 out of memory |
FATAL |
| 栈正常 | 未检测到 Stack overflow |
FATAL |
退出码:0 = 全部通过,1 = 仅 WARN,2 = ERROR,3 = FATAL
CI 工作流¶
# .github/workflows/firmware-qemu.yml
name: Firmware QEMU Tests
on:
push:
paths: ['firmware/**']
pull_request:
paths: ['firmware/**']
jobs:
qemu-test:
runs-on: ubuntu-latest
container:
image: espressif/idf:v5.4
strategy:
matrix:
scenario: [default, nvs-full, nvs-edge-tier0, nvs-tdm-3node]
steps:
- uses: actions/checkout@v4
- name: Install Espressif QEMU
run: |
apt-get update && apt-get install -y libslirp-dev libglib2.0-dev ninja-build
git clone --depth 1 https://github.com/espressif/qemu.git /tmp/qemu
cd /tmp/qemu
./configure --target-list=xtensa-softmmu --enable-slirp
make -j$(nproc)
cp build/qemu-system-xtensa /usr/local/bin/
env:
QEMU_PATH: /usr/local/bin/qemu-system-xtensa
- name: Prepare NVS for scenario
run: |
case "${{ matrix.scenario }}" in
nvs-full)
python firmware/esp32-csi-node/provision.py --dry-run \
--port dummy --ssid "TestWiFi" --password "test1234" \
--target-ip "10.0.2.2" --target-port 5005 \
--channel 6 --filter-mac AA:BB:CC:DD:EE:FF \
--node-id 1 --edge-tier 2
cp nvs_provision.bin firmware/esp32-csi-node/build/nvs_test.bin
;;
nvs-edge-tier0)
python firmware/esp32-csi-node/provision.py --dry-run \
--port dummy --edge-tier 0 --node-id 5
cp nvs_provision.bin firmware/esp32-csi-node/build/nvs_test.bin
;;
nvs-tdm-3node)
python firmware/esp32-csi-node/provision.py --dry-run \
--port dummy --tdm-slot 1 --tdm-total 3 --node-id 1
cp nvs_provision.bin firmware/esp32-csi-node/build/nvs_test.bin
;;
esac
- name: Build firmware (mock CSI mode)
run: |
cd firmware/esp32-csi-node
idf.py -D SDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.qemu" set-target esp32s3
idf.py build
- name: Run QEMU tests
run: bash scripts/qemu-esp32s3-test.sh
env:
QEMU_PATH: /usr/local/bin/qemu-system-xtensa
QEMU_TIMEOUT: 90
- name: Upload QEMU log
if: always()
uses: actions/upload-artifact@v4
with:
name: qemu-output-${{ matrix.scenario }}
path: firmware/esp32-csi-node/build/qemu_output.log
第 3 层:多节点网格模拟¶
使用 TAP 网络运行多个 QEMU 实例,以测试 TDM 时隙协调和多节点聚合。
架构¶
┌──────────┐ ┌──────────┐ ┌──────────┐
│ QEMU #0 │ │ QEMU #1 │ │ QEMU #2 │
│ slot=0 │ │ slot=1 │ │ slot=2 │
│ node_id=0│ │ node_id=1│ │ node_id=2│
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
└──────────┬───┴──────────────┘
▼
┌───────────────┐
│ TAP bridge │
│ (10.0.0.0/24) │
└───────┬───────┘
▼
┌───────────────┐
│ Rust aggregator│
│ (UDP :5005) │
└───────────────┘
多节点运行器¶
#!/bin/bash
# scripts/qemu-mesh-test.sh — run 3 QEMU nodes + Rust aggregator
set -euo pipefail
N_NODES=${1:-3}
AGGREGATOR_PORT=5005
BRIDGE="qemu-br0"
# Create bridge
ip link add "$BRIDGE" type bridge
ip addr add 10.0.0.1/24 dev "$BRIDGE"
ip link set "$BRIDGE" up
# Build flash images with per-node NVS
for i in $(seq 0 $((N_NODES - 1))); do
python firmware/esp32-csi-node/provision.py --dry-run \
--port dummy --node-id "$i" --tdm-slot "$i" --tdm-total "$N_NODES" \
--target-ip 10.0.0.1 --target-port "$AGGREGATOR_PORT"
cp nvs_provision.bin "build/nvs_node${i}.bin"
# Inject NVS into per-node flash image
cp build/qemu_flash.bin "build/qemu_flash_node${i}.bin"
dd if="build/nvs_node${i}.bin" of="build/qemu_flash_node${i}.bin" \
bs=1 seek=$((0x9000)) conv=notrunc
done
# Start Rust aggregator in background
cargo run -p wifi-densepose-hardware --bin aggregator -- \
--listen 0.0.0.0:${AGGREGATOR_PORT} \
--expect-nodes "$N_NODES" \
--output build/mesh_test_results.json &
AGGREGATOR_PID=$!
# Launch QEMU nodes
for i in $(seq 0 $((N_NODES - 1))); do
TAP="tap${i}"
ip tuntap add "$TAP" mode tap
ip link set "$TAP" master "$BRIDGE"
ip link set "$TAP" up
qemu-system-xtensa \
-machine esp32s3 \
-nographic \
-drive file="build/qemu_flash_node${i}.bin",if=mtd,format=raw \
-serial file:"build/qemu_node${i}.log" \
-nic tap,ifname="$TAP",script=no,downscript=no \
-no-reboot &
echo "Started QEMU node $i (PID: $!)"
done
# Wait for test duration
sleep 30
# Validate results
kill $AGGREGATOR_PID 2>/dev/null || true
python3 scripts/validate_mesh_test.py build/mesh_test_results.json --nodes "$N_NODES"
网格验证检查¶
| 检查 | 通过标准 |
|---|---|
| 所有节点已启动 | 接收帧中有 N 个不同的 node_id 值 |
| TDM 排序 | 在每个 TDM 周期内,Slot 0 帧先于 Slot 1 帧到达 |
| 无时隙冲突 | 在 TDM 窗口内,没有来自不同节点且时间戳重叠的两个帧 |
| 帧数均衡 | 每个节点贡献总帧数的 ±10% |
| ADR-018 合规性 | 所有帧都具有有效 magic 0xC5110001 和正确的节点 ID |
| 每节点生命体征 | 每个节点生成独立的生命体征数据包 |
第 4 层:GDB 远程调试¶
QEMU 提供内置 GDB stub,无需 JTAG 硬件即可零成本调试。
用法¶
# Launch QEMU with GDB stub (paused at boot)
qemu-system-xtensa \
-machine esp32s3 \
-nographic \
-drive file=build/qemu_flash.bin,if=mtd,format=raw \
-serial mon:stdio \
-s -S # -s = GDB on :1234, -S = pause at start
# In another terminal: attach GDB
xtensa-esp-elf-gdb build/esp32-csi-node.elf \
-ex "target remote :1234" \
-ex "b edge_processing.c:dsp_task" \
-ex "b csi_collector.c:wifi_csi_callback" \
-ex "b mock_csi.c:mock_generate_csi_frame" \
-ex "watch g_nvs_config.csi_channel" \
-ex "continue"
调试流程¶
1. 使用 GDB stub 启动 QEMU(在复位向量处暂停):
qemu-system-xtensa \
-machine esp32s3 \
-nographic \
-drive file=build/qemu_flash.bin,if=mtd,format=raw \
-serial mon:stdio \
-s -S
# -s opens GDB server on localhost:1234
# -S pauses CPU until GDB sends "continue"
2. 从第二个终端连接:
xtensa-esp-elf-gdb build/esp32-csi-node.elf \
-ex "target remote :1234" \
-ex "b app_main" \
-ex "continue"
3. 在 DSP 处理处设置断点并检查状态:
(gdb) b edge_processing.c:dsp_task
(gdb) continue
# ...breakpoint hit...
(gdb) print g_nvs_config
(gdb) print ring->head - ring->tail
(gdb) continue
4. 从 VS Code 连接 使用下面的 launch.json 配置(在编辑器边栏设置断点,然后按 F5)。
5. 转储 gcov 覆盖率数据(需要 sdkconfig.coverage 覆盖层):
(gdb) monitor gcov dump
# Writes .gcda files to the build directory.
# Then generate the HTML report on the host:
# lcov --capture --directory build --output-file coverage.info
# genhtml coverage.info --output-directory build/coverage_report
关键断点位置¶
| 断点 | 用途 |
|---|---|
edge_processing.c:dsp_task |
DSP 消费者循环入口 |
edge_processing.c:presence_detect |
阈值比较 |
edge_processing.c:fall_detect |
相位加速度检查 |
csi_collector.c:wifi_csi_callback |
帧摄入(或模拟注入点) |
csi_collector.c:csi_serialize_frame |
ADR-018 序列化 |
nvs_config.c:nvs_config_load |
NVS 解析逻辑 |
wasm_runtime.c:wasm_on_csi |
WASM 模块分发 |
mock_csi.c:mock_generate_csi_frame |
合成帧生成 |
VS Code 集成¶
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [{
"name": "QEMU ESP32-S3 Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/firmware/esp32-csi-node/build/esp32-csi-node.elf",
"miDebuggerPath": "xtensa-esp-elf-gdb",
"miDebuggerServerAddress": "localhost:1234",
"setupCommands": [
{ "text": "set remote hardware-breakpoint-limit 2" },
{ "text": "set remote hardware-watchpoint-limit 2" }
]
}]
}
第 5 层:代码覆盖率(gcov/lcov)¶
启用覆盖率构建¶
# sdkconfig.coverage (overlay)
CONFIG_COMPILER_OPTIMIZATION_NONE=y
CONFIG_GCOV_ENABLE=y
CONFIG_APPTRACE_GCOV_ENABLE=y
覆盖率收集¶
# After QEMU run, extract gcov data from flash dump
esptool.py --chip esp32s3 read_flash 0x300000 0x100000 gcov_data.bin
# Or use ESP-IDF's app_trace + gcov integration:
# QEMU + GDB → "monitor gcov dump" → .gcda files
# Generate HTML report
lcov --capture --directory build --output-file coverage.info
lcov --remove coverage.info '*/esp-idf/*' '*/test/*' --output-file coverage_filtered.info
genhtml coverage_filtered.info --output-directory build/coverage_report
覆盖率目标¶
| 模块 | 目标 | 关键路径 |
|---|---|---|
edge_processing.c |
≥80% | dsp_task、biquad_filter、fall_detect、multi_person_cluster |
csi_collector.c |
≥90% | csi_serialize_frame、wifi_csi_callback、MAC 过滤分支 |
nvs_config.c |
≥95% | 每个 NVS 键读取路径、默认回退路径 |
mock_csi.c |
≥95% | 所有场景、所有信号模型分支 |
stream_sender.c |
≥80% | 初始化、发送、错误路径 |
wasm_runtime.c |
≥70% | 模块加载、分发、签名验证 |
第 6 层:模糊测试¶
模糊测试目标¶
| 目标 | 输入 | 变异策略 | 查找目标 |
|---|---|---|---|
csi_serialize_frame() |
随机 wifi_csi_info_t |
极端 len(0、65535)、NULL buf、负 RSSI、信道 255 |
缓冲区溢出、NULL 解引用 |
nvs_config_load() |
构造的 NVS 分区二进制 | 截断字符串、超出范围的 u8/u16、缺失键、损坏头部 | Kconfig 回退、无崩溃 |
edge_enqueue_csi() |
快速发送 10,000 帧 | 变化 iq_len(0 到 EDGE_MAX_IQ_BYTES+1)、随机化 RSSI |
环形缓冲区溢出、无数据损坏 |
rvf_parser.c |
畸形 RVF 网络数据包 | 错误 magic、截断头部、超大负载 | 解析拒绝、无崩溃 |
wasm_upload.c |
损坏的 WASM 数据块 | 无效 magic、超大模块、错误 Ed25519 签名、截断 | 无崩溃拒绝、无代码执行 |
csi_serialize_frame() + edge_enqueue_csi() |
链式:生成 → 序列化 → 入队 | 使用随机数据进行端到端 | 流水线完整性 |
实现方式¶
// test/fuzz_csi_serialize.c — runs on host (not ESP32)
// Compiled with: clang -fsanitize=fuzzer,address
#include "csi_collector.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (size < sizeof(wifi_csi_info_t)) return 0;
wifi_csi_info_t info;
memcpy(&info, data, sizeof(info));
// Point buf at remaining fuzz data
size_t remaining = size - sizeof(info);
uint8_t iq_buf[2048];
if (remaining > sizeof(iq_buf)) remaining = sizeof(iq_buf);
memcpy(iq_buf, data + sizeof(info), remaining);
info.buf = iq_buf;
info.len = (int)remaining;
uint8_t out[4096];
csi_serialize_frame(&info, out, sizeof(out));
return 0;
}
模糊测试 CI 任务¶
fuzz-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build fuzz targets
run: |
cd firmware/esp32-csi-node/test
clang -fsanitize=fuzzer,address -I../main \
fuzz_csi_serialize.c ../main/csi_collector.c \
-o fuzz_serialize
- name: Run fuzz (5 min per target)
run: |
cd firmware/esp32-csi-node/test
timeout 300 ./fuzz_serialize corpus/ || true
- name: Upload crashes
if: failure()
uses: actions/upload-artifact@v4
with:
name: fuzz-crashes
path: firmware/esp32-csi-node/test/crash-*
第 7 层:NVS 配置矩阵¶
配置组合¶
| 配置 | NVS 值 | 验证内容 |
|---|---|---|
default |
(空 NVS) | Kconfig 回退路径 |
wifi-only |
ssid, password | 基础配置 |
full-adr060 |
channel=6, filter_mac=AA:BB:CC:DD:EE:FF | 信道覆盖 + MAC 过滤 |
edge-tier0 |
edge_tier=0 | 原始 CSI 直通(无 DSP) |
edge-tier1 |
edge_tier=1, pres_thresh=100, fall_thresh=2000 | 仅统计模式 |
edge-tier2-custom |
edge_tier=2, vital_win=128, vital_int=500, subk_count=16 | 完整体征数据(自定义参数) |
tdm-3node |
tdm_slot=1, tdm_nodes=3, node_id=1 | TDM 网格时序 |
wasm-signed |
wasm_max=4, wasm_verify=1, wasm_pubkey=<32 bytes> | 带 Ed25519 验证的 WASM |
wasm-unsigned |
wasm_max=2, wasm_verify=0 | 无签名检查的 WASM |
5ghz-channel |
channel=36, filter_mac=... | 5 GHz CSI 采集 |
boundary-max |
target_port=65535, node_id=255, top_k=32, vital_win=256 | 最大范围值 |
boundary-min |
target_port=1, node_id=0, top_k=1, vital_win=32 | 最小范围值 |
power-save |
power_duty=10, edge_tier=0 | 低功耗模式 |
corrupt-nvs |
(手工构造的部分/损坏分区) | 优雅回退到默认值 |
自动化矩阵生成¶
# scripts/generate_nvs_matrix.py
# Generates all 14 NVS partition binaries for CI matrix
CONFIGS = [
{"name": "default", "args": []},
{"name": "wifi-only", "args": ["--ssid", "Test", "--password", "test1234"]},
{"name": "full-adr060", "args": ["--channel", "6", "--filter-mac", "AA:BB:CC:DD:EE:FF",
"--ssid", "Test", "--password", "test"]},
{"name": "edge-tier0", "args": ["--edge-tier", "0"]},
# ... all 14 configs
]
第 8 层:快照与回放¶
QEMU 快照命令¶
# Save snapshot after boot + NVS load (skip 3s boot time)
(qemu) savevm post_boot
# Save after WiFi connect + first CSI frame
(qemu) savevm post_connect
# Save after edge pipeline calibration complete (~60s)
(qemu) savevm post_calibration
# Restore any snapshot (< 100ms)
(qemu) loadvm post_connect
自动化快照流水线¶
# scripts/qemu-snapshot-test.sh
# Phase 1: Create base snapshots (one-time, cached in CI)
qemu-system-xtensa ... -monitor unix:qemu.sock,server,nowait &
sleep 5
echo "savevm post_boot" | socat - UNIX-CONNECT:qemu.sock
sleep 10
echo "savevm post_first_frame" | socat - UNIX-CONNECT:qemu.sock
# Phase 2: Run quick tests from snapshots (< 1s each)
for test in test_presence test_fall test_multi_person; do
echo "loadvm post_first_frame" | socat - UNIX-CONNECT:qemu.sock
echo "cont" | socat - UNIX-CONNECT:qemu.sock
sleep 2 # Run test scenario
# Validate output
done
性能影响¶
| 操作 | 无快照 | 有快照 |
|---|---|---|
| 完整启动 + NVS + WiFi 模拟 | ~5 秒 | ~5 秒(首次运行) |
| 运行单个场景 | ~5 秒启动 + ~5 秒测试 = 10 秒 | ~0.1 秒恢复 + ~5 秒测试 = 5.1 秒 |
| 运行全部 10 个场景 | ~100 秒 | ~51 秒(快 49%) |
| 运行 14 个 NVS 配置 × 10 个场景 | ~23 分钟 | ~12 分钟(快 48%) |
第 9 层:混沌测试¶
故障注入表¶
| 故障 | 注入方法 | 预期行为 | 严重级别 |
|---|---|---|---|
| WiFi 断开 | 定时器在 N 帧后终止模拟 WiFi 连接 | 尝试重连,CSI 暂停并恢复 | HIGH |
| 环形缓冲区溢出 | 100ms 内突发 1000 帧 | 帧丢弃计数器递增,无崩溃,无数据损坏 | HIGH |
| NVS 损坏 | 闪存镜像包含部分写入的 NVS 分区 | 回退到 Kconfig 默认值,记录警告 | MEDIUM |
| 栈溢出 | WASM 模块回调中的深度递归 | 看门狗触发,任务重启,无挂起 | HIGH |
| 堆耗尽 | malloc 在 N 次分配后返回 NULL |
优雅降级,记录 OOM,继续运行 | HIGH |
| 定时器饥饿 | 阻塞 DSP 任务 500ms | 帧从环形缓冲区丢弃,无死锁,可恢复 | MEDIUM |
| UDP 发送失败 | SLIRP 网络中断 | stream_sender_send 返回 -1,错误计数器递增 |
LOW |
| 损坏的 CSI 帧 | 注入 I/Q 数据中魔数无效的帧 | 边缘流水线拒绝,错误计数器递增 | LOW |
| 读取期间写入 NVS | 配置加载时并发打开 NVS 进行写入 | 无损坏,NVS 句柄隔离 | MEDIUM |
混沌测试运行器¶
# scripts/qemu-chaos-test.sh
# Run with fault injection enabled
qemu-system-xtensa ... \
-monitor unix:qemu.sock,server,nowait &
# Inject faults via GDB or monitor commands
for fault in wifi_kill heap_exhaust ring_flood; do
echo "[CHAOS] Injecting: $fault"
python3 scripts/inject_fault.py --socket qemu.sock --fault "$fault"
sleep 5
python3 scripts/check_health.py --log "$LOG_FILE" --after-fault "$fault"
done
实施计划¶
| 阶段 | 层 | 交付物 | 工作量 | 优先级 |
|---|---|---|---|---|
| P1 | L1 + L2 | mock_csi.c, mock_csi.h, Kconfig.projbuild, sdkconfig.qemu, qemu-esp32s3-test.sh, validate_qemu_output.py, firmware-qemu.yml |
2 天 | 关键 |
| P2 | L4 + L5 | GDB 启动配置,sdkconfig.coverage,lcov 集成,覆盖率 CI 任务 |
1 天 | 高 |
| P3 | L7 | generate_nvs_matrix.py、14个NVS配置、CI矩阵扩展 |
1天 | 高 |
| P4 | L6 | fuzz_csi_serialize.c、fuzz_nvs_config.c、fuzz_edge_enqueue.c、模糊测试CI任务 |
2天 | 高 |
| P5 | L3 | qemu-mesh-test.sh、TAP网桥搭建、validate_mesh_test.py、Rust聚合器集成 |
3天 | 高 |
| P6 | L8 | 快照流水线、CI中缓存的基础镜像 | 0.5天 | 中 |
| P7 | L9 | inject_fault.py、check_health.py、qemu-chaos-test.sh、9个故障场景 |
2天 | 中 |
| P8 | 性能 | 指令计数、DSP周期剖析、优化报告 | 1天 | 低 |
总计:8个阶段约12.5天
文件布局¶
firmware/esp32-csi-node/
├── main/
│ ├── mock_csi.c # NEW — synthetic CSI frame generator
│ ├── mock_csi.h # NEW — mock API + scenario definitions
│ ├── Kconfig.projbuild # MODIFIED — CONFIG_CSI_MOCK_* options
│ ├── CMakeLists.txt # MODIFIED — conditional mock_csi.c inclusion
│ └── ... (existing files unchanged)
├── test/
│ ├── fuzz_csi_serialize.c # NEW — libFuzzer target for serialization
│ ├── fuzz_nvs_config.c # NEW — libFuzzer target for NVS parsing
│ ├── fuzz_edge_enqueue.c # NEW — libFuzzer target for ring buffer
│ └── corpus/ # NEW — seed inputs for fuzz targets
├── sdkconfig.qemu # NEW — QEMU-specific sdkconfig overlay
├── sdkconfig.coverage # NEW — gcov-enabled sdkconfig overlay
└── ...
scripts/
├── qemu-esp32s3-test.sh # NEW — single-node QEMU runner
├── qemu-mesh-test.sh # NEW — multi-node mesh runner
├── qemu-chaos-test.sh # NEW — chaos/fault injection runner
├── validate_qemu_output.py # NEW — UART log validation
├── validate_mesh_test.py # NEW — mesh test validation
├── generate_nvs_matrix.py # NEW — NVS config matrix generator
├── inject_fault.py # NEW — QEMU fault injection
└── check_health.py # NEW — post-fault health checker
.vscode/
└── launch.json # MODIFIED — add QEMU GDB debug config
.github/workflows/
└── firmware-qemu.yml # NEW — CI workflow with matrix
影响¶
优势¶
- 无需硬件 — 贡献者可仅使用QEMU验证固件更改
- 自动化CI — 每个涉及
firmware/的PR并行运行14个NVS配置 × 10个场景 - 迭代速度提升10× — 快照恢复<100ms,对比20秒的烧录周期
- 安全加固 — 模糊测试在缓冲区溢出、空指针解引用和解析器缺陷到达硬件之前将其捕获
- Mesh验证 — 无需3块实体ESP32即可测试多节点TDM
- 覆盖率可见性 — lcov报告展示未经测试的边缘处理路径
- 韧性验证 — 混沌测试验证固件能否从WiFi断连、OOM和环形缓冲区溢出中恢复
- GDB调试 — 无需JTAG适配器即可在DSP流水线上设置断点
- 回归检测 — 启动失败、NVS解析错误和FreeRTOS死锁在CI中被捕获
局限性¶
- 无真实WiFi/CSI — QEMU无法模拟ESP32-S3的WiFi射频或CSI提取硬件
- 合成CSI保真度 — 模拟帧仅能近似真实CSI模式,但无法捕获真实环境中的多径、干扰或天线特性
- 时序差异 — QEMU时序并非周期精确;FreeRTOS节拍率可能与硬件不同
- 无外设测试 — I2C显示屏、真实GPIO和浅睡眠电源管理无法测试
- QEMU构建要求 — Espressif的QEMU分支必须从源码构建(不包含在Ubuntu软件包中)
- 覆盖率开销 — 启用gcov的构建在QEMU中约慢2×
QEMU测试覆盖范围与需硬件测试对比¶
| 测试领域 | QEMU | 硬件 |
|---|---|---|
| 启动 + NVS配置(14个配置) | 完整 | 完整 |
| 边缘DSP流水线(双二阶滤波器、Welford、top-K) | 完整 | 完整 |
| ADR-018帧序列化 | 完整 | 完整 |
| 生命体征数据包生成(0xC5110002) | 完整 | 完整 |
| WASM模块加载与执行 | 完整 | 完整 |
| 多节点TDM mesh(3个以上节点) | 完整(TAP) | 完整 |
| 模糊测试(CSI解析器、NVS) | 完整 | 不适用 |
| 代码覆盖率分析 | 完整 | 部分 |
| GDB断点调试 | 完整 | 完整(JTAG) |
| 混沌/故障注入 | 完整 | 手动 |
| OTA更新流程 | 部分(HTTP模拟) | 完整 |
| 真实WiFi连接 | 不支持 | 完整 |
| 真实CSI数据质量 | 不支持 | 完整 |
| RF信道跳变 | 不支持 | 完整 |
| 真实帧上的MAC过滤 | 不支持 | 完整 |
| 电源管理(浅睡眠) | 不支持 | 完整 |
| 显示渲染(OLED) | 不支持 | 完整 |
| 真实网络上的UDP | 不支持 | 完整 |
备选方案¶
1. 主机原生单元测试(无QEMU){#1-host-native-unit-tests-no-qemu}¶
提取纯C函数(csi_serialize_frame、边缘DSP数学计算),并在主机上使用CMock/Unity编译和测试。更简单,但不测试FreeRTOS集成、NVS或启动序列。
结论:互补——两者都做。主机单元测试用于数学计算,QEMU用于集成测试。模糊测试目标(第6层)已使用主机原生编译。
2. 硬件在环CI(在运行器上使用真实ESP32){#2-hardware-in-the-loop-ci-real-esp32-on-runner}¶
使用连接了实体ESP32-S3的自托管GitHub Actions运行器。
结论:有价值,但成本高且脆弱。QEMU覆盖约85%的测试用例(较全部9层方案下的70%有所提升)。后续仅在需要真实CSI验证时添加HIL。
3. 仅基于Docker的ESP-IDF构建(无运行时测试){#3-docker-based-esp-idf-build-only-no-runtime-test}¶
仅验证固件能在CI中编译,而不实际运行。
结论:目前已经可行,但不够充分——编译无法捕获运行时缺陷(栈溢出、NVS解析错误、FreeRTOS死锁)。
4. Renode模拟器¶
QEMU的替代方案,在某些平台上具有更好的外设建模能力。
结论:Renode支持ESP32,但其ESP32-S3支持不如Espressif自家的QEMU分支成熟。如果Renode添加完整的S3支持,可以重新评估。
参考资料¶
- Espressif QEMU fork — 官方ESP32/S3/C3/H2支持
- ESP-IDF QEMU guide
- libFuzzer documentation — 基于LLVM的覆盖率引导模糊测试
- lcov — Linux测试覆盖率可视化
- ADR-018:二进制CSI帧格式(幻数
0xC5110001) - ADR-039:边缘智能流水线(双二阶滤波器、生命体征、跌倒检测)
- ADR-040:WASM可编程感知运行时
- ADR-057:构建时CSI保护(
CONFIG_ESP_WIFI_CSI_ENABLED) - ADR-060:信道覆盖与MAC地址过滤
优化日志(2026-03-14)¶
已修复的缺陷¶
- LFSR 浮点偏差 —
lfsr_float()使用除数 32767.5,产生范围 [-1.0, 1.00002];已修正为 32768.0,以获得精确的 [-1.0, +1.0) - MAC 滤波器初始化 —
gen_mac_filter()比较了frame_count == scenario_start_ms(计数与时间戳);已替换为布尔标志 - 场景无限循环 —
advance_scenario()在全部完成后循环到场景 0;现在设置s_all_done=true,定时器回调提前退出 - 启动检查严重级别 —
validate_qemu_output.py将未启动报告为 ERROR;已升级为 FATAL(没有启动则一切无法工作) - NVS 边界配置 —
boundary-max使用了vital_win=65535,固件会静默拒绝(有效值:32-256);已修正为 256 - NVS boundary-min —
vital_win=1同样无效;已修正为 32(固件最小值) - edge-tier2-custom —
vital_win=512超过固件最大值 256;已修正为 256 - power-save 配置 — 描述为“10% 占空比”,但未设置
power_duty=10;已修正 - wasm 签名/未签名 — 两个配置原本相同;签名配置现在包含公钥 blob,未签名配置设置
wasm_verify=0
已应用的优化¶
- SLIRP 网络 — QEMU 运行器现在传递
-nic user,model=open_eth用于 UDP 测试 - 场景完成跟踪 — 验证器现在检查
All N scenarios complete日志标记(检查 15) - 帧率监控 — 验证器提取
scenario=N frames=M计数器用于速率分析(检查 16) - 看门狗调优 —
sdkconfig.qemu将 WDT 放宽到 30s / INT_WDT 放宽到 800ms,以应对 QEMU 时序差异 - 定时器栈深度 — 增加
FREERTOS_TIMER_TASK_STACK_DEPTH=4096,以防止计算量大的 mock 回调导致溢出 - 显示禁用 — QEMU overlay 中设置
CONFIG_DISPLAY_ENABLE=n(没有 I2C 硬件) - CI 模糊测试任务 — 添加
fuzz-test任务,运行全部 3 个模糊测试目标,每个运行 60s,并上传崩溃工件 - CI NVS 验证 — 添加
nvs-matrix-validate任务,生成全部 14 个二进制文件并验证大小 - CI 矩阵扩展 — 将
edge-tier1、boundary-max、boundary-min添加到 QEMU 测试矩阵(4 → 7 个配置) - QEMU 缓存键 — 使用
github.run_id,并带有 restore-keys 回退,以防止过期的 QEMU 构建
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView