Skip to main content

esp_csi_rs/
lib.rs

1//! # A crate for CSI collection on ESP devices
2//! ## Overview
3//! This crate builds on the low level Espressif abstractions to enable the collection of Channel State Information (CSI) on ESP devices with ease.
4//! Currently this crate supports only the ESP `no-std` development framework.
5//!
6//! ### Choosing a device
7//! In terms of hardware, you need to make sure that the device you choose supports WiFi and CSI collection.
8//! Currently supported devices include:
9//! - ESP32
10//! - ESP32-C3
11//! - ESP32-C5 (dual-band 2.4/5 GHz)
12//! - ESP32-C6 (WiFi 6)
13//! - ESP32-S3
14//!
15//! In terms of project and software toolchain setup, you will need to specify the hardware you will be using. To minimize headache, it is recommended that you generate a project using `esp-generate` as explained next.
16//!
17//! ### Creating a project
18//! To use this crate you would need to create and setup a project for your ESP device then import the crate. This crate is compatible with the `no-std` ESP development framework. You should also select the corresponding device by activating it in the crate features.
19//!
20//! To create a projects it is highly recommended to refer the to instructions in [The Rust on ESP Book](https://docs.esp-rs.org/book/) before proceeding. The book explains the full esp-rs ecosystem, how to get started, and how to generate projects for both `std` and `no-std`.
21//!
22//! Espressif has developed a project generation tool, `esp-generate`, to ease this process and is recommended for new projects. As an example, you can create a `no-std` project for the ESP32-C3 device as follows:
23//!
24//! ```bash
25//! cargo install esp-generate
26//! esp-generate --chip=esp32c3 [project-name]
27//! ```
28//!
29//! ## Feature Flags
30#![doc = document_features::document_features!()]
31//! ## Logging Backends
32//!
33//! Two logging backends are supported and they are mutually exclusive:
34//!
35//! - **`println` (default)** — plain text via `esp-println`. Decoded by any serial monitor.
36//! - **`defmt`** — compact binary frames via `esp-println`'s `defmt-espflash` backend, decoded by `espflash --monitor --log-format defmt`. The `build.rs` adds `-Tdefmt.x` automatically when this feature is on, so no manual linker-script edits are needed.
37//!
38//! Per-chip cargo aliases ship in `.cargo/config.toml` for both flavors:
39//!
40//! ```bash
41//! cargo esp32c3 --example sniffer_wifi          # println
42//! cargo esp32c3-defmt --example sniffer_wifi    # defmt
43//! ```
44//!
45//! Replace `esp32c3` with any of: `esp32`, `esp32c3`, `esp32c5`, `esp32c6`, `esp32s3`. `-build` and `-build-defmt` variants compile without flashing.
46//!
47//! ## Using the Crate
48//!
49//! Each ESP device is represented as a node in a collection network. For each node, we need to configure its role in the network, the mode of operation, and the CSI collection behavior. The node role determines how the node participates in the network and interacts with other nodes, while the collection mode determines how the node handles CSI data.
50//!
51//! ### Node Roles
52//! 1) **Central Node**: This type of node is one that generates traffic, also can connect to one or more peripheral nodes.
53//! 2) **Peripheral Node**: This type of node does not generate traffic, also can optionally connect to one central node at most.
54//!
55//! ### Node Operation Modes
56//! The operation mode determines how the node operates in terms of Wi-Fi features and interactions with other nodes. The supported operation modes are:
57//! 1) **ESP-NOW**
58//! 2) **Wi-Fi Station** (Central only)
59//! 3) **Wi-Fi Sniffer** (Peripheral only)
60//!
61//! ### Collection Modes
62//! 1) **Collector**: A collector node collects and provides CSI data output from one or more devices.
63//! 2) **Listener**: A listener is a passive node. It only enables CSI collection and does not provide any CSI output.
64//!
65//! A collector node typically is the one that actively processes CSI data. A listener on the other hand typically keeps CSI traffic flowing but does not process CSI data.
66//!
67//! ## Collection Network Architechtures
68//! As ahown earlier, `esp-csi-rs` allows you to configure a device to one several operational modes including ESP-NOW, WiFi station, or WiFi sniffer. As such, `esp-csi-rs` supports several network setups allowing for flexibility in collecting CSI data. Some possible setups including the following:
69//!
70//! 1. ***Single Node:***  This is the simplest setup where only one ESP device (CSI Node) is needed. The node is configured to "sniff" packets in surrounding networks and collect CSI data. The WiFi Sniffer Peripheral Collector is the only configuration that supports this topology.
71//! 2. ***Point-to-Point:*** This set up uses two CSI Nodes, a central and a peripheral. One of them can be a collector and the other a listener. Alternatively, both can be collectors as well. Some configuration examples include
72//!     - **WiFi Station Central Collector <-> Access Point/Commercial Router**: In this configuration the CSI node can connect to any WiFi Access Point like an ESP AP or a commercial router. The node in turn sends traffic to the Access Point to acquire CSI data.
73//!     - **ESP-NOW Central Listener/Collector <-> ESP-NOW Peripheral Listener/Collector**: In this configuration a CSI central node connects to one other ESP-NOW peripheral node. Both ESP-NOW peripheral and central nodes can operate either as listeners or collectors.
74//! 3. ***Star:*** In this architechture a central node connects to several peripheral nodes. The central node triggers traffic and aggregates CSI sent back from peripheral nodes. Alternatively, CSI can be collected by the individual peripherals. Only the ESP-NOW operation mode supports this architechture. The ESP-NOW peripheral and central nodes can also operate either as listeners or collectors.
75//!
76//! ## Output Formats & Logging Modes
77//! `esp-csi-rs` is able to print CSI data in several formats. The output format can be configured when initializing the logger. The supported formats include:
78//! - **LogMode::ArrayList**: This prints CSI data as an array, where the array represents the CSI values for a received packet. This format is more compact and easier to read for large volumes of CSI data.
79//!
80//! Example output:
81//! ```
82//! [3916,-93,11,157,1,1815804,256,0,260,2,0,1,1,128,0,1,1,0,1,0,0,0,256,128,[...]]
83//! ```
84//! The array fields map to the [`CSIDataPacket`] struct fields in the following order:
85//!
86//! | Index | Field | Description |
87//! |-------|-------|-------------|
88//! | 0 | `sequence_number` | Sequence number of the packet that triggered the CSI capture |
89//! | 1 | `rssi` | Received Signal Strength Indicator (dBm) |
90//! | 2 | `rate` | PHY rate encoding (valid for non-HT / 802.11b/g packets) |
91//! | 3 | `noise_floor` | Noise floor of the RF module (dBm) |
92//! | 4 | `channel` | Primary channel on which the packet was received |
93//! | 5 | `timestamp` | Local timestamp when the packet was received (microseconds) |
94//! | 6 | `sig_len` | Length of the packet including Frame Check Sequence (FCS) |
95//! | 7 | `rx_state` | Reception state: `0` = no error, non-zero = error code |
96//! | 8 | `secondary_channel` | Secondary channel: `0` = none, `1` = above, `2` = below *(non-ESP32-C6 only)* |
97//! | 9 | `sgi` | Short Guard Interval: `0` = Long GI, `1` = Short GI *(non-ESP32-C6 only)* |
98//! | 10 | `antenna` | Antenna number: `0` = antenna 0, `1` = antenna 1 *(non-ESP32-C6 only)* |
99//! | 11 | `ampdu_cnt` | Number of subframes aggregated in AMPDU *(non-ESP32-C6 only)* |
100//! | 12 | `sig_mode` | Protocol: `0` = non-HT (11b/g), `1` = HT (11n), `3` = VHT (11ac) *(non-ESP32-C6 only)* |
101//! | 13 | `mcs` | Modulation Coding Scheme; for HT packets ranges from 0 (MCS0) to 76 (MCS76) *(non-ESP32-C6 only)* |
102//! | 14 | `bandwidth` | Channel bandwidth: `0` = 20 MHz, `1` = 40 MHz *(non-ESP32-C6 only)* |
103//! | 15 | `smoothing` | Channel estimate smoothing: `0` = unsmoothed, `1` = smoothing recommended *(non-ESP32-C6 only)* |
104//! | 16 | `not_sounding` | Sounding PPDU flag: `0` = sounding PPDU, `1` = not a sounding PPDU *(non-ESP32-C6 only)* |
105//! | 17 | `aggregation` | Aggregation type: `0` = MPDU, `1` = AMPDU *(non-ESP32-C6 only)* |
106//! | 18 | `stbc` | Space-Time Block Code: `0` = non-STBC, `1` = STBC *(non-ESP32-C6 only)* |
107//! | 19 | `fec_coding` | Forward Error Correction / LDPC flag; set for 11n LDPC packets *(non-ESP32-C6 only)* |
108//! | 20 | `sig_len` | Packet length including FCS (repeated) |
109//! | 21 | `csi_data_len` | Length of the raw CSI data (number of `i8` samples) |
110//! | 22 | `[csi_data]` | Inner array of raw CSI `i8` samples |
111//!
112//! - **LogMode::Text**: This output prints CSI data in a more verbose, human-readable format. This includes additional metadata and explanations alongside the raw CSI values, making it easier to understand the context of each packet's CSI data.
113//!
114//! Example output:
115//! ```rust
116//! mac: 56:6C:EB:6F:BC:3D
117//! sequence number: 426
118//! rssi: -82
119//! rate: 11
120//! noise floor: 165
121//! channel: 1
122//! timestamp: 2424915
123//! sig len: 332
124//! rx state: 0
125//! dump len: 336
126//! he sigb len: 2
127//! cur single mpdu: 0
128//! cur bb format: 1
129//! rx channel estimate info vld: 1
130//! rx channel estimate len: 128
131//! time seconds: 0
132//! channel: 1
133//! is group: 1
134//! rxend state: 0
135//! rxmatch3: 1
136//! rxmatch2: 0
137//! rxmatch1: 0
138//! rxmatch0: 0
139//! sig_len: 332
140//! data length: 128
141//! csi raw data: [0, 0, 0, 0, 0, 0, 0, 0, -6, 0, 6, 0, -24, 10, -23, 9, -23, 8, -23, 7, -22, 6, -22, 5, -22, 6, -23, 5, -22, 6, -22, 6, -22, 7, -20, 7, -19, 9, -19, 10, -19, 12, -19, 12, -18, 14, -19, 14, -19, 16, -20, 17, -21, 18, -20, 18, -19, 18, -16, 18, -14, 19, -13, 18, 0, 0, -19, 22, -20, 22, -20, 22, -20, 21, -21, 19, -22, 18, -20, 16, -18, 16, -17, 15, -16, 15, -14, 15, -13, 13, -12, 13, -9, 13, -7, 14, -6, 14, -5, 13, -3, 12, 0, 13, 2, 12, 3, 12, 5, 12, 7, 13, 8, 13, 10, 13, 12, 14, 9, 1, -5, -4, 0, 0, 0, 0, 0, 0]
142//! ```
143//! - **LogMode::Serialized**: This mode serializes the `CSIDataPacket` structure and prints it in a serialized COBS format. This is a compact binary format that can be parsed by and serde compatible crate like [postcard](https://crates.io/crates/postcard). It is not human-readable but is efficient for logging large amounts of CSI data on the host without overwhelming the console output.
144//!
145//!
146//!
147//! ### On-Device CSI Processing
148//!
149//! Register a `fn(&CSIDataPacket)` with [`set_csi_callback`] to process
150//! every captured CSI packet inline in the WiFi-task callback. Zero
151//! channel hops, lowest possible latency. The callback runs on the WiFi
152//! hot path so it must be fast and non-blocking — no heap allocation,
153//! no locking, no UART I/O. Heavier work belongs in your own task; copy
154//! what you need out of the borrowed packet and post it via atomics or
155//! a queue. See `examples/csi_callback_test.rs` for a working demo.
156//!
157//! ```rust,ignore
158//! use esp_csi_rs::{set_csi_callback, csi::CSIDataPacket};
159//!
160//! fn on_csi(packet: &CSIDataPacket) {
161//!     // your processing — keep it fast
162//! }
163//!
164//! set_csi_callback(on_csi);
165//! ```
166//!
167//! ### Example for creating WiFi Station Central Collector
168//! There are more examples in the repository. The example below demonstrates how to collect CSI data with an ESP configured in WIFI Station mode.
169//!
170//! #### Step 1: Initialize Logger
171//! ```rust
172//! init_logger(spawner, LogMode::ArrayList);
173//! ```
174//! #### Step 2: Create a Hardware Instance for the CSI Node
175//! ```rust
176//! let csi_hardware = CSINodeHardware::new(&mut interfaces, controller);
177//! ```
178//! #### Step 3: Create a Station Configuration
179//! ```rust
180//! use esp_radio::wifi::sta::StationConfig;
181//! use esp_radio::wifi::AuthenticationMethod;
182//!
183//! let client_config = StationConfig::default()
184//!     .with_ssid("SSID")
185//!     .with_password("PASS".to_string())
186//!     .with_auth_method(AuthenticationMethod::Wpa2Personal);
187//!
188//! let station_config = WifiStationConfig {
189//!    client_config,  // Pass the config we created above
190//! };
191//! ```
192//!
193//! `StationConfig` was renamed from `ClientConfig`, and `AuthMethod` was renamed to `AuthenticationMethod` in `esp-radio` 0.18. `with_ssid` now takes `impl Into<Ssid>`, so a `&str` literal works directly without `.to_string()`.
194//! #### Step 4: Create a CSI Collection Node Instance with the Desired Configuration
195//! ```rust
196//! let mut node = CSINode::new(
197//!     esp_csi_rs::Node::Central(esp_csi_rs::CentralOpMode::WifiStation(station_config)),
198//!     CollectionMode::Collector,
199//!     Some(CsiConfig::default()),
200//!     Some(100),
201//!     csi_hardware,
202//! );
203//! ```
204//! #### Step 5: (Optional) Register an On-Device CSI Callback
205//! ```rust
206//! set_csi_callback(|packet| {
207//!     // process `packet` inline — keep it fast
208//! });
209//! ```
210//! #### Step 6: Create a CSI Node Client to Control the Node
211//! ```rust
212//! let mut node_handle = CSINodeClient::new();
213//! ```
214//! #### Step 7: Run the Node for a Fixed Duration
215//! ```rust
216//! node.run_duration(1000, &mut node_handle).await;
217//! ```
218//!
219
220#![no_std]
221
222#[cfg(feature = "async-print")]
223use embassy_time::with_timeout;
224#[cfg(feature = "statistics")]
225use portable_atomic::AtomicI64;
226
227use embassy_futures::join::{join, join3};
228use embassy_futures::select::{select, select3, Either, Either3};
229
230use embassy_time::{Duration, Instant, Timer};
231use enumset::EnumSet;
232use esp_radio::esp_now::WifiPhyRate;
233use esp_radio::wifi::csi::CsiConfig;
234use esp_radio::wifi::sta::StationConfig;
235use esp_radio::wifi::{Interfaces, Protocol, Protocols, SecondaryChannel, WifiController};
236#[cfg(feature = "esp32c5")]
237use esp_radio::wifi::BandMode;
238
239use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
240use embassy_sync::signal::Signal;
241use embassy_sync::waitqueue::AtomicWaker;
242
243#[cfg(feature = "statistics")]
244use heapless::LinearMap;
245use heapless::Vec;
246extern crate alloc;
247use serde::{Deserialize, Serialize};
248
249pub mod central;
250pub mod config;
251pub mod csi;
252pub mod esp_now_pool;
253pub mod logging;
254pub mod peripheral;
255pub mod time;
256
257use crate::central::esp_now::run_esp_now_central;
258use crate::central::sta::{run_sta_connect, sta_init};
259use crate::config::CsiConfig as CsiConfiguration;
260use crate::csi::{CSIDataPacket, RxCSIFmt};
261use crate::peripheral::esp_now::run_esp_now_peripheral;
262
263#[cfg(feature = "statistics")]
264const MAX_TRACKED_PEERS: usize = 16;
265
266/// Lock-free 32-slot MPMC ring used by the WiFi callback to deliver
267/// captured `CSIDataPacket`s to user code via
268/// [`CSINodeClient::next_csi_packet`]. Mirrors the `esp_now_pool`
269/// pattern (`src/lib/esp_now_pool.rs`): the producer is the WiFi-task
270/// callback, the consumer is one async task, and the queue is
271/// **lock-free** — no critical section on enqueue, so the WiFi-task
272/// hot path is never delayed.
273///
274/// 32 × `sizeof(CSIDataPacket)` ≈ 20 KB BSS. Drop-on-full; drops are
275/// counted via `STATS.rx_drop_count`.
276static CSI_QUEUE: heapless::mpmc::Q32<CSIDataPacket> = heapless::mpmc::Q32::new();
277/// Single-slot waker for the CSI consumer. Registered by
278/// [`CSINodeClient::next_csi_packet`] and woken from the WiFi callback
279/// after a successful `CSI_QUEUE.enqueue`.
280static CSI_WAKER: AtomicWaker = AtomicWaker::new();
281
282static IS_COLLECTOR: AtomicBool = AtomicBool::new(false);
283// CSI publish gate. The WiFi callback checks this in a single relaxed load
284// to decide whether to build and emit a CSIDataPacket.
285//
286// Decoupled from `IS_COLLECTOR` on purpose: `CollectionMode` controls the
287// ESP-NOW responder/initiator behavior (Listener stays passive on TX), but
288// it must NOT block a `CSINodeClient` from reading CSI — that conflation
289// silently breaks sniffer + Listener configurations where the user wants
290// to passively read CSI without participating in any control protocol.
291static CSI_PUBLISH_ENABLED: AtomicBool = AtomicBool::new(false);
292static COLLECTION_MODE_CHANGED: Signal<CriticalSectionRawMutex, ()> = Signal::new();
293
294/// CSI delivery mode — single-atomic dispatch in the WiFi callback.
295///
296/// Per-packet, the callback loads `CSI_DELIVERY_MODE` once and branches
297/// on it. Exactly one of the user-facing delivery paths runs, so users
298/// pay only for what they asked for:
299/// - `Off`: nothing past the publish gate (apart from seq-drop tracking).
300/// - `Callback`: dispatch to the `fn` stored in `CSI_CALLBACK` with a
301///   `&CSIDataPacket` borrow. Lowest latency, runs on the WiFi-task
302///   hot path. **Picked by [`set_csi_callback`].**
303/// - `Async`: move the packet into the lock-free `CSI_QUEUE` and wake
304///   the consumer registered via [`CSI_WAKER`]. Doesn't block the WiFi
305///   task. **Picked lazily by the first
306///   [`CSINodeClient::next_csi_packet`].`**
307///
308/// The two are **mutually exclusive** so the WiFi callback never pays
309/// for both a callback dispatch and a 640 B memcpy on the same packet.
310/// Toggle explicitly with [`set_csi_delivery_mode`].
311#[repr(u8)]
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313#[cfg_attr(feature = "defmt", derive(defmt::Format))]
314pub enum CsiDeliveryMode {
315    /// No user delivery. Inline `log_csi` may still run if its gate is
316    /// open (controlled by [`set_csi_logging_enabled`]).
317    Off = 0,
318    /// Dispatch to the `fn` registered with [`set_csi_callback`] inline
319    /// in the WiFi callback context.
320    Callback = 1,
321    /// Move the packet into the lock-free `CSI_QUEUE` and wake the
322    /// async consumer awaiting [`CSINodeClient::next_csi_packet`].
323    Async = 2,
324}
325
326/// Single-atomic dispatch select for the WiFi callback. Read once per
327/// CSI event in `capture_csi_info`. See [`CsiDeliveryMode`] for the
328/// branch semantics.
329static CSI_DELIVERY_MODE: portable_atomic::AtomicU8 = portable_atomic::AtomicU8::new(0);
330
331/// User CSI callback registered via [`set_csi_callback`]. Loaded only
332/// when `CSI_DELIVERY_MODE == Callback`, so callers in `Off` / `Async`
333/// modes don't pay for an extra atomic load.
334static CSI_CALLBACK: core::sync::atomic::AtomicPtr<()> =
335    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());
336
337/// Inline-logging gate. Independent of [`CSI_DELIVERY_MODE`] so the
338/// per-packet UART/JTAG `log_csi` path is controlled separately
339/// (toggle with [`set_csi_logging_enabled`]).
340static CSI_INLINE_LOG_ENABLED: AtomicBool = AtomicBool::new(false);
341
342/// Enable or disable inline CSI **logging** (per-packet UART/JTAG output).
343///
344/// This controls only the inline `log_csi` path inside the WiFi callback.
345/// It does **not** disable a [`set_csi_callback`] hook — registering a
346/// callback opens an independent publish gate, and that gate stays open
347/// regardless of this flag. So a typical "process inline, no UART flood"
348/// setup is:
349///
350/// ```ignore
351/// init_logger(spawner, LogMode::Text);   // publish gate + log gate ON
352/// set_csi_logging_enabled(false);        // log gate OFF (callback still fires)
353/// set_csi_callback(on_csi);              // publish gate ON, log gate untouched
354/// ```
355///
356/// Defaults / who flips this for you:
357/// - `init_logger` enables it automatically in sync mode (the WiFi
358///   callback writes CSI lines inline).
359/// - In `async-print` mode `CSINodeClient::get_csi_data` enables the
360///   publish gate (separate from the log gate) lazily on first await.
361/// - [`set_csi_callback`] enables only the publish gate — it does not
362///   touch this log-output flag.
363pub fn set_csi_logging_enabled(enabled: bool) {
364    CSI_INLINE_LOG_ENABLED.store(enabled, Ordering::Release);
365    // Keep the master publish gate paired with logging by default so
366    // existing callers that only flip `set_csi_logging_enabled(true)` to
367    // get UART output still work. A registered `set_csi_callback` keeps
368    // the publish gate open independently when this is later disabled.
369    CSI_PUBLISH_ENABLED.store(enabled, Ordering::Release);
370}
371
372/// Returns whether inline CSI logging is currently enabled (i.e. whether
373/// the per-packet UART/JTAG `log_csi` path will run).
374pub fn csi_logging_enabled() -> bool {
375    CSI_INLINE_LOG_ENABLED.load(Ordering::Relaxed)
376}
377
378/// Set the active CSI delivery mode (callback / async / off).
379///
380/// The WiFi callback dispatches to **exactly one** path per packet —
381/// callers pay no overhead for the path they didn't pick. Switching
382/// with this fn is a single relaxed atomic store; the next CSI event
383/// follows the new mode.
384///
385/// You normally don't call this directly:
386/// - [`set_csi_callback`] sets the mode to [`CsiDeliveryMode::Callback`].
387/// - First await of [`CSINodeClient::next_csi_packet`] sets it to
388///   [`CsiDeliveryMode::Async`].
389/// - [`clear_csi_callback`] sets it to [`CsiDeliveryMode::Off`].
390///
391/// Use this fn when you want to **switch** between paths at runtime
392/// without re-registering, or to fully disable user delivery while
393/// leaving inline logging running.
394pub fn set_csi_delivery_mode(mode: CsiDeliveryMode) {
395    CSI_DELIVERY_MODE.store(mode as u8, Ordering::Release);
396}
397
398/// Returns the active CSI delivery mode.
399pub fn csi_delivery_mode() -> CsiDeliveryMode {
400    match CSI_DELIVERY_MODE.load(Ordering::Relaxed) {
401        1 => CsiDeliveryMode::Callback,
402        2 => CsiDeliveryMode::Async,
403        _ => CsiDeliveryMode::Off,
404    }
405}
406
407/// Register a user callback invoked inline for every captured CSI packet.
408///
409/// The callback runs in the WiFi task context (the same context that
410/// formats and writes CSI lines), with a borrow of the [`CSIDataPacket`]
411/// *before* it is consumed by the logging path. This is the supported
412/// path for **on-device CSI processing** — zero channel hops, lowest
413/// possible latency.
414///
415/// **Constraints**: the callback runs on the WiFi task hot path and MUST
416/// be fast and non-blocking. Avoid heap allocation, locking, and long
417/// format/write work. For heavier processing, copy what you need out of
418/// the packet and post to your own task.
419///
420/// Registering opens the master publish gate and switches the
421/// delivery mode to [`CsiDeliveryMode::Callback`]. Any prior async
422/// drain mode is replaced — the WiFi callback only runs the inline
423/// callback path from this point. The inline-logging gate
424/// ([`set_csi_logging_enabled`]) is left untouched so `init_logger`'s
425/// UART output (or its absence) is preserved.
426///
427/// Call [`clear_csi_callback`] to remove the hook and return to
428/// [`CsiDeliveryMode::Off`].
429pub fn set_csi_callback(cb: fn(&CSIDataPacket)) {
430    // Store the fn pointer first so the WiFi callback never sees the
431    // mode flipped to `Callback` while `CSI_CALLBACK` is still null.
432    CSI_CALLBACK.store(cb as *mut (), core::sync::atomic::Ordering::Release);
433    CSI_DELIVERY_MODE.store(CsiDeliveryMode::Callback as u8, Ordering::Release);
434    CSI_PUBLISH_ENABLED.store(true, Ordering::Release);
435}
436
437/// Remove the user CSI callback registered via [`set_csi_callback`]
438/// and switch to [`CsiDeliveryMode::Off`].
439///
440/// The publish gate and inline-logging gate are left untouched — call
441/// `set_csi_logging_enabled(false)` if you also want to suppress
442/// logging output, or `set_csi_delivery_mode(CsiDeliveryMode::Async)`
443/// to swap to async drain without re-driving lazy initialization.
444pub fn clear_csi_callback() {
445    CSI_DELIVERY_MODE.store(CsiDeliveryMode::Off as u8, Ordering::Release);
446    CSI_CALLBACK.store(core::ptr::null_mut(), core::sync::atomic::Ordering::Release);
447}
448
449// Signals run_process_csi_packet to clear PEER_SEQ_TRACKER on the next ISR entry.
450#[cfg(feature = "statistics")]
451static RESET_SEQ_TRACKER: AtomicBool = AtomicBool::new(false);
452static CENTRAL_MAGIC_NUMBER: u32 = 0xA8912BF0;
453static PERIPHERAL_MAGIC_NUMBER: u32 = !CENTRAL_MAGIC_NUMBER;
454#[cfg(feature = "statistics")]
455static SEQ_DROP_DETECTION_ENABLED: AtomicBool = AtomicBool::new(false);
456
457use portable_atomic::{AtomicBool, Ordering};
458#[cfg(feature = "statistics")]
459use portable_atomic::{AtomicU32, AtomicU64};
460/// Global statistics counters (enabled with the `statistics` feature).
461#[cfg(feature = "statistics")]
462struct GlobalStats {
463    /// Total transmitted packets.
464    tx_count: AtomicU64,
465    /// Total received packets.
466    rx_count: AtomicU64,
467    /// Estimated number of dropped RX packets.
468    rx_drop_count: AtomicU32,
469    /// Capture start time (ticks).
470    capture_start_time: AtomicU64,
471    /// Current TX packet rate (Hz).
472    tx_rate_hz: AtomicU32,
473    /// Current RX packet rate (Hz).
474    rx_rate_hz: AtomicU32,
475    /// One-way latency (microseconds).
476    one_way_latency: AtomicI64,
477    /// Two-way latency (microseconds).
478    two_way_latency: AtomicI64,
479}
480
481#[cfg(feature = "statistics")]
482static STATS: GlobalStats = GlobalStats {
483    tx_count: AtomicU64::new(0),
484    rx_count: AtomicU64::new(0),
485    rx_drop_count: AtomicU32::new(0),
486    capture_start_time: AtomicU64::new(0),
487    tx_rate_hz: AtomicU32::new(0),
488    rx_rate_hz: AtomicU32::new(0),
489    one_way_latency: AtomicI64::new(0),
490    two_way_latency: AtomicI64::new(0),
491};
492// static GLOBAL_PACKET_RX_DROP_COUNT: AtomicU32 = AtomicU32::new(0);
493// static GLOBAL_PACKET_TX_COUNT: AtomicU64 = AtomicU64::new(0);
494// static GLOBAL_PACKET_RX_COUNT: AtomicU64 = AtomicU64::new(0);
495// static GLOBAL_CAPTURE_START_TIME: AtomicU64 = AtomicU64::new(0);
496// static TX_RATE_HZ: AtomicU32 = AtomicU32::new(0);
497// static RX_RATE_HZ: AtomicU32 = AtomicU32::new(0);
498// static TWO_WAY_LATENCY: AtomicI64 = AtomicI64::new(0);
499// static ONE_WAY_LATENCY: AtomicI64 = AtomicI64::new(0);
500
501// Signals
502static STOP_SIGNAL: Signal<CriticalSectionRawMutex, ()> = Signal::new();
503
504/// Internal fucntion to change collection mode at runtime (e.g. Central can signal Peripheral to start/stop collecting CSI).
505fn set_runtime_collection_mode(is_collector: bool) {
506    IS_COLLECTOR.store(is_collector, Ordering::Relaxed);
507    COLLECTION_MODE_CHANGED.signal(());
508}
509
510fn set_seq_drop_detection(enabled: bool) {
511    #[cfg(feature = "statistics")]
512    {
513        SEQ_DROP_DETECTION_ENABLED.store(enabled, Ordering::Relaxed);
514    }
515
516    #[cfg(not(feature = "statistics"))]
517    {
518        let _ = enabled;
519    }
520}
521
522#[cfg(feature = "statistics")]
523fn seq_drop_detection_enabled() -> bool {
524    SEQ_DROP_DETECTION_ENABLED.load(Ordering::Relaxed)
525}
526
527// Drives the per-`run_duration` lifecycle. In async-print mode this is the
528// loop that pulls packets out of `CSI_PACKET` and forwards them to the
529// logger task — without it, the channel would fill and packets would drop.
530// In sync mode the WiFi callback writes inline, so we just wait for the
531// duration and then signal stop.
532#[cfg(feature = "async-print")]
533async fn csi_data_collection(client: &mut CSINodeClient, duration: u64) {
534    with_timeout(Duration::from_secs(duration), async {
535        loop {
536            client.print_csi_w_metadata().await;
537        }
538    })
539    .await
540    .unwrap_err();
541    client.send_stop().await;
542}
543
544#[cfg(not(feature = "async-print"))]
545async fn csi_data_collection(client: &mut CSINodeClient, duration: u64) {
546    Timer::after(Duration::from_secs(duration)).await;
547    client.send_stop().await;
548}
549
550async fn wait_for_stop() {
551    STOP_SIGNAL.wait().await;
552    STOP_SIGNAL.signal(());
553}
554
555async fn stop_after_duration(duration: u64) {
556    match select(STOP_SIGNAL.wait(), Timer::after(Duration::from_secs(duration))).await {
557        Either::First(_) | Either::Second(_) => STOP_SIGNAL.signal(()),
558    }
559}
560
561/// Configuration for ESP-NOW traffic generation.
562///
563/// Used by both Central and Peripheral nodes when operating in ESP-NOW mode.
564/// Construct with `EspNowConfig::default()` then chain `with_channel` /
565/// `with_phy_rate` to override defaults — both nodes must agree on the
566/// channel for ESP-NOW frames to be received.
567pub struct EspNowConfig {
568    phy_rate: WifiPhyRate,
569    channel: u8,
570}
571
572impl Default for EspNowConfig {
573    fn default() -> Self {
574        Self {
575            phy_rate: WifiPhyRate::RateMcs0Lgi,
576            // Channel 1 is empirically less congested than 11 in most
577            // residential / office environments — APs on auto-select tend
578            // to bias toward 11 because it's the upper bound in US/EU.
579            // Override with `with_channel` if your environment differs.
580            channel: 1,
581        }
582    }
583}
584
585impl EspNowConfig {
586    /// Override the 2.4 GHz channel (1–14). Both central and peripheral
587    /// must be configured with the same channel.
588    pub fn with_channel(mut self, channel: u8) -> Self {
589        self.channel = channel;
590        self
591    }
592
593    /// Override the ESP-NOW PHY rate.
594    pub fn with_phy_rate(mut self, phy_rate: WifiPhyRate) -> Self {
595        self.phy_rate = phy_rate;
596        self
597    }
598
599    /// Configured 2.4 GHz channel.
600    pub fn channel(&self) -> u8 {
601        self.channel
602    }
603
604    /// Configured PHY rate.
605    pub fn phy_rate(&self) -> &WifiPhyRate {
606        &self.phy_rate
607    }
608}
609
610/// Configuration for Wi-Fi Promiscuous Sniffer mode.
611///
612/// Construct with `WifiSnifferConfig::default()` then chain `with_channel`
613/// to override defaults.
614#[derive(Debug, Clone)]
615pub struct WifiSnifferConfig {
616    /// Optional MAC source filter (reserved — not yet wired into the
617    /// promiscuous filter setup).
618    #[allow(dead_code)]
619    mac_filter: Option<[u8; 6]>,
620    channel: u8,
621}
622
623impl Default for WifiSnifferConfig {
624    fn default() -> Self {
625        Self {
626            mac_filter: None,
627            // Match `EspNowConfig` default — channel 1 is typically less
628            // congested than 11 in dense residential / office environments.
629            channel: 1,
630        }
631    }
632}
633
634impl WifiSnifferConfig {
635    /// Override the channel the sniffer locks to.
636    ///
637    /// Must be a valid IEEE 802.11 **primary** channel number — pass the
638    /// primary, not the wider-channel center notation that routers
639    /// commonly display:
640    ///
641    /// - **2.4 GHz**: `1`–`14`
642    /// - **5 GHz**: `36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112,
643    ///   116, 120, 124, 128, 132, 136, 140, 144, 149, 153, 157, 161, 165`
644    ///   (regulatory-domain dependent — some restricted by `country_info`)
645    ///
646    /// Center-channel labels (`38, 46, ...` for HT40; `42, 58, 106, ...`
647    /// for VHT80; `50, 114` for VHT160; `154` for the 153/157 HT40 pair)
648    /// are **not** accepted here — `esp_wifi_set_channel` panics with
649    /// `InvalidArguments`. For example, a router showing "channel 154"
650    /// is using primary `153` (or `157`); pass that primary and the chip
651    /// will sniff the full 40 MHz block automatically per 802.11.
652    ///
653    /// On dual-band chips (currently ESP32-C5), the band is auto-selected
654    /// from the channel number — channels `>= 36` switch the radio to
655    /// `BandMode::_5G`, otherwise `BandMode::_2_4G`. On 2.4-GHz-only
656    /// chips, passing any 5 GHz channel will fail at runtime.
657    pub fn with_channel(mut self, channel: u8) -> Self {
658        self.channel = channel;
659        self
660    }
661
662    /// Configured channel (2.4 GHz: 1–14, 5 GHz: 36–165).
663    pub fn channel(&self) -> u8 {
664        self.channel
665    }
666}
667
668/// Configuration for Wi-Fi Station mode.
669#[derive(Debug, Clone)]
670pub struct WifiStationConfig {
671    /// Underlying esp-radio station configuration (SSID, auth, etc.).
672    pub client_config: StationConfig,
673}
674
675#[cfg(feature = "defmt")]
676impl defmt::Format for WifiStationConfig {
677    fn format(&self, fmt: defmt::Formatter<'_>) {
678        defmt::write!(fmt, "WifiStationConfig {{ client_config: <opaque> }}");
679    }
680}
681
682// Enum for Central modes, each wrapping its specific config.
683
684/// Central node operational modes.
685pub enum CentralOpMode {
686    /// Drive an ESP-NOW exchange with a peripheral node.
687    EspNow(EspNowConfig),
688    /// Associate as a Wi-Fi station to harvest CSI from received frames.
689    WifiStation(WifiStationConfig),
690}
691
692// Enum for Peripheral modes, each wrapping its specific config.
693/// Peripheral node operational modes.
694pub enum PeripheralOpMode {
695    /// Reply to a central's ESP-NOW control frames.
696    EspNow(EspNowConfig),
697    /// Run as a Wi-Fi promiscuous sniffer; CSI is captured from every
698    /// frame received on the locked channel.
699    WifiSniffer(WifiSnifferConfig),
700}
701
702/// High-level node type and mode.
703pub enum Node {
704    /// Run as the peripheral side of the chosen [`PeripheralOpMode`].
705    Peripheral(PeripheralOpMode),
706    /// Run as the central side of the chosen [`CentralOpMode`].
707    Central(CentralOpMode),
708}
709
710/// CSI collection behavior for the node.
711///
712/// Use `Listener` to keep CSI traffic flowing without processing packets,
713/// or `Collector` to actively process CSI data. Note: `Listener` combined with
714/// a sniffer node makes the sniffer effectively useless because no CSI data is
715/// processed.
716#[derive(PartialEq, Eq, Clone, Copy)]
717pub enum CollectionMode {
718    /// Enables CSI collection and processes CSI data.
719    Collector,
720    /// Enables CSI collection but does not process CSI data.
721    Listener,
722}
723
724/// Controls whether TX and RX tasks are active for a node.
725///
726/// Defaults to both TX and RX enabled.
727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
728pub struct IOTaskConfig {
729    /// Enable transmit-side task work for the selected operation mode.
730    pub tx_enabled: bool,
731    /// Enable receive/process-side task work for the selected operation mode.
732    pub rx_enabled: bool,
733}
734
735impl IOTaskConfig {
736    /// Create a task configuration with explicit TX/RX state.
737    pub const fn new(tx_enabled: bool, rx_enabled: bool) -> Self {
738        Self {
739            tx_enabled,
740            rx_enabled,
741        }
742    }
743}
744
745impl Default for IOTaskConfig {
746    fn default() -> Self {
747        Self::new(true, true)
748    }
749}
750
751/// Hardware handles required to operate a CSI node.
752pub struct CSINodeHardware<'a> {
753    interfaces: &'a mut Interfaces<'static>,
754    controller: &'a mut WifiController<'static>,
755}
756
757impl<'a> CSINodeHardware<'a> {
758    /// Create a hardware bundle from the Wi-Fi `Interfaces` and `WifiController`.
759    pub fn new(
760        interfaces: &'a mut Interfaces<'static>,
761        controller: &'a mut WifiController<'static>,
762    ) -> Self {
763        Self {
764            interfaces,
765            controller,
766        }
767    }
768}
769
770/// Handle for controlling a running [`CSINode`] from user code.
771///
772/// CSI packets are delivered to user code via [`set_csi_callback`] (the
773/// preferred path: zero channel hops, lowest latency) or — under the
774/// `async-print` feature — by awaiting [`Self::get_csi_data`] /
775/// [`Self::print_csi_w_metadata`]. The client also signals the running
776/// node to stop early via [`Self::send_stop`].
777pub struct CSINodeClient {
778    _private: (),
779}
780
781impl CSINodeClient {
782    /// Create a new CSI node client.
783    ///
784    /// Constructing a client does not by itself open the publish gate.
785    /// In async-print mode the gate is opened lazily on the first
786    /// `get_csi_data()` await; in sync mode it is opened by
787    /// `init_logger` or `set_csi_callback`. Use `set_csi_logging_enabled`
788    /// to override.
789    pub fn new() -> Self {
790        Self { _private: () }
791    }
792
793    /// Await the next CSI packet captured by the WiFi callback.
794    ///
795    /// Drains the lock-free `CSI_QUEUE`. Available in **both** sync and
796    /// `async-print` modes — same API, same delivery path. Mirrors
797    /// `crate::esp_now_pool::receive_async`: dequeue → register waker
798    /// → re-check (closes the lost-wakeup window).
799    ///
800    /// The first call lazily switches [`CsiDeliveryMode`] to
801    /// [`CsiDeliveryMode::Async`] and opens the master publish gate so
802    /// the WiFi callback starts enqueueing. **This replaces any prior
803    /// `set_csi_callback`** — the two delivery paths are mutually
804    /// exclusive so the WiFi callback only ever runs one of them per
805    /// packet (no double-dispatch overhead).
806    ///
807    /// **Single consumer**: the underlying `AtomicWaker` is single-slot.
808    /// Awaiting `next_csi_packet` from two different tasks at once will
809    /// cause one of them to miss wake-ups — register exactly one
810    /// drainer task per node.
811    pub async fn next_csi_packet(&mut self) -> CSIDataPacket {
812        // Conservative lazy init: only flip into `Async` mode if no
813        // delivery path is currently active (`Off`). If the user has
814        // already set `Callback` mode, we don't disrupt it — the
815        // drainer just parks on the waker until the user explicitly
816        // switches via `set_csi_delivery_mode(CsiDeliveryMode::Async)`.
817        // This lets the two APIs coexist as runtime-toggleable choices
818        // without one clobbering the other.
819        if CSI_DELIVERY_MODE.load(Ordering::Relaxed) == CsiDeliveryMode::Off as u8 {
820            CSI_DELIVERY_MODE.store(CsiDeliveryMode::Async as u8, Ordering::Release);
821            CSI_PUBLISH_ENABLED.store(true, Ordering::Release);
822        }
823        core::future::poll_fn(|cx| {
824            if let Some(p) = CSI_QUEUE.dequeue() {
825                return core::task::Poll::Ready(p);
826            }
827            CSI_WAKER.register(cx.waker());
828            // Re-check after register to close the lost-wakeup window:
829            // the WiFi callback could have enqueued + woken between our
830            // first dequeue and `register` if we hadn't checked again.
831            if let Some(p) = CSI_QUEUE.dequeue() {
832                core::task::Poll::Ready(p)
833            } else {
834                core::task::Poll::Pending
835            }
836        })
837        .await
838    }
839
840    /// Back-compat alias for [`Self::next_csi_packet`]. Older code paths
841    /// (and the `async-print` feature) referred to this name.
842    pub async fn get_csi_data(&mut self) -> CSIDataPacket {
843        self.next_csi_packet().await
844    }
845
846    /// Receive the next CSI packet and emit it via the crate logging
847    /// backend (`log_csi`). Convenience wrapper for "drain + log to
848    /// UART/JTAG" loops:
849    /// ```ignore
850    /// loop { client.print_csi_w_metadata().await; }
851    /// ```
852    pub async fn print_csi_w_metadata(&mut self) {
853        let packet = self.next_csi_packet().await;
854        crate::logging::logging::log_csi(packet);
855        embassy_futures::yield_now().await;
856    }
857
858    /// Signal the running node to stop.
859    pub async fn send_stop(&self) {
860        STOP_SIGNAL.signal(());
861    }
862}
863
864/// Control packet sent from Central to Peripheral.
865#[derive(Serialize, Deserialize, Debug, PartialEq)]
866pub struct ControlPacket {
867    magic_number: u32,
868    /// Whether the central is currently in collector mode; the peripheral
869    /// mirrors this flag to keep the pair in sync.
870    pub is_collector: bool,
871    /// Microseconds-since-boot timestamp captured when the central queued
872    /// this packet for transmit.
873    pub central_send_uptime: u64,
874    /// Latency offset (μs) the central has observed for this peer; sent
875    /// so the peripheral can compensate when stamping its reply.
876    pub latency_offset: i64,
877    /// Monotonic sequence number used to detect drops/reordering.
878    pub sequence_number: u32,
879}
880
881impl ControlPacket {
882    /// Create a new control packet with collector flag, latency offset, and sequence number.
883    pub fn new(is_collector: bool, latency_offset: i64, sequence_number: u32) -> Self {
884        Self {
885            magic_number: CENTRAL_MAGIC_NUMBER.into(),
886            is_collector,
887            central_send_uptime: Instant::now().as_micros(),
888            latency_offset,
889            sequence_number,
890        }
891    }
892}
893
894/// Peripheral reply packet for latency/telemetry exchange.
895#[derive(Serialize, Deserialize, Debug, PartialEq)]
896pub struct PeripheralPacket {
897    magic_number: u32,        // Magic number to identify packet type
898    recv_uptime: u64,         // When Peripheral received the Control Packet
899    send_uptime: u64, // When Peripheral sent the Peripheral Packet (after receiving Control Packet)
900    central_send_uptime: u64, // When Central sent the Control Packet
901}
902
903impl PeripheralPacket {
904    /// Create a new peripheral packet using timestamps captured locally.
905    pub fn new(recv_uptime: u64, central_send_uptime: u64) -> Self {
906        Self {
907            magic_number: PERIPHERAL_MAGIC_NUMBER,
908            recv_uptime,
909            send_uptime: Instant::now().as_micros(),
910            central_send_uptime,
911        }
912    }
913}
914
915fn reset_globals() {
916    // Close all CSI delivery gates so any late-firing WiFi callback runs
917    // are no-ops. The CSI callback stays registered with esp-radio after
918    // stop (the radio itself is still up), but with the gates closed the
919    // callback short-circuits before it touches the log channel or the
920    // user's callback. Without this, sniffer/ESP-NOW/STA nodes keep
921    // emitting CSI lines on the serial port well after `send_stop()`.
922    CSI_INLINE_LOG_ENABLED.store(false, Ordering::Release);
923    CSI_PUBLISH_ENABLED.store(false, Ordering::Release);
924    CSI_DELIVERY_MODE.store(CsiDeliveryMode::Off as u8, Ordering::Release);
925    CSI_CALLBACK.store(core::ptr::null_mut(), core::sync::atomic::Ordering::Release);
926
927    #[cfg(feature = "statistics")]
928    {
929        STATS.tx_count.store(0, Ordering::Relaxed);
930        STATS.rx_count.store(0, Ordering::Relaxed);
931        STATS.rx_drop_count.store(0, Ordering::Relaxed);
932        STATS.tx_rate_hz.store(0, Ordering::Relaxed);
933        STATS.rx_rate_hz.store(0, Ordering::Relaxed);
934        STATS.one_way_latency.store(0, Ordering::Relaxed);
935        STATS.two_way_latency.store(0, Ordering::Relaxed);
936    }
937    #[cfg(feature = "statistics")]
938    reset_global_log_drops();
939}
940
941/// Primary orchestration object for CSI collection.
942///
943/// Construct a node with `CSINode::new` or `CSINode::new_central_node`, configure
944/// optional protocol/rate/traffic frequency, then call `run()`.
945pub struct CSINode<'a> {
946    kind: Node,
947    collection_mode: CollectionMode,
948    io_tasks: IOTaskConfig,
949    /// CSI Configuration
950    csi_config: Option<CsiConfiguration>,
951    /// Traffic Generation Frequency
952    traffic_freq_hz: Option<u16>,
953    hardware: CSINodeHardware<'a>,
954    protocol: Option<Protocol>,
955    rate: Option<WifiPhyRate>,
956}
957
958impl<'a> CSINode<'a> {
959    /// Create a new node with explicit `Node` kind.
960    pub fn new(
961        kind: Node,
962        collection_mode: CollectionMode,
963        csi_config: Option<CsiConfiguration>,
964        traffic_freq_hz: Option<u16>,
965        hardware: CSINodeHardware<'a>,
966    ) -> Self {
967        Self {
968            kind,
969            collection_mode,
970            io_tasks: IOTaskConfig::default(),
971            csi_config,
972            traffic_freq_hz,
973            hardware,
974            protocol: None,
975            rate: Some(WifiPhyRate::RateMcs7Lgi),
976        }
977    }
978
979    /// Convenience constructor for a central node.
980    pub fn new_central_node(
981        op_mode: CentralOpMode,
982        collection_mode: CollectionMode,
983        csi_config: Option<CsiConfiguration>,
984        traffic_freq_hz: Option<u16>,
985        hardware: CSINodeHardware<'a>,
986    ) -> Self {
987        Self {
988            kind: Node::Central(op_mode),
989            collection_mode,
990            io_tasks: IOTaskConfig::default(),
991            csi_config,
992            traffic_freq_hz,
993            hardware,
994            protocol: None,
995            rate: Some(WifiPhyRate::RateMcs7Lgi),
996        }
997    }
998
999    /// Get the node type and operation mode.
1000    pub fn get_node_type(&self) -> &Node {
1001        &self.kind
1002    }
1003
1004    /// Get the current collection mode.
1005    pub fn get_collection_mode(&self) -> CollectionMode {
1006        self.collection_mode
1007    }
1008
1009    /// If central, return the active central op mode.
1010    pub fn get_central_op_mode(&self) -> Option<&CentralOpMode> {
1011        match &self.kind {
1012            Node::Central(mode) => Some(mode),
1013            Node::Peripheral(_) => None,
1014        }
1015    }
1016
1017    /// If peripheral, return the active peripheral op mode.
1018    pub fn get_peripheral_op_mode(&self) -> Option<&PeripheralOpMode> {
1019        match &self.kind {
1020            Node::Peripheral(mode) => Some(mode),
1021            Node::Central(_) => None,
1022        }
1023    }
1024
1025    /// Update CSI configuration.
1026    pub fn set_csi_config(&mut self, config: CsiConfiguration) {
1027        self.csi_config = Some(config);
1028    }
1029
1030    /// Update Wi-Fi Station configuration (only applies to central station mode).
1031    pub fn set_station_config(&mut self, config: WifiStationConfig) {
1032        if let Node::Central(CentralOpMode::WifiStation(_)) = &mut self.kind {
1033            self.kind = Node::Central(CentralOpMode::WifiStation(config));
1034        }
1035    }
1036
1037    /// Set traffic generation frequency in Hz (ESP-NOW modes).
1038    pub fn set_traffic_frequency(&mut self, freq_hz: u16) {
1039        self.traffic_freq_hz = Some(freq_hz);
1040    }
1041
1042    /// Set collection mode for the node.
1043    pub fn set_collection_mode(&mut self, mode: CollectionMode) {
1044        self.collection_mode = mode;
1045    }
1046
1047    /// Set TX/RX task enablement for the node.
1048    pub fn set_io_tasks(&mut self, io_tasks: IOTaskConfig) {
1049        self.io_tasks = io_tasks;
1050    }
1051
1052    /// Enable or disable TX task work.
1053    pub fn set_tx_enabled(&mut self, enabled: bool) {
1054        self.io_tasks.tx_enabled = enabled;
1055    }
1056
1057    /// Enable or disable RX task work.
1058    pub fn set_rx_enabled(&mut self, enabled: bool) {
1059        self.io_tasks.rx_enabled = enabled;
1060    }
1061
1062    /// Get current TX/RX task configuration.
1063    pub fn get_io_tasks(&self) -> IOTaskConfig {
1064        self.io_tasks
1065    }
1066
1067    /// Replace the node kind/mode.
1068    pub fn set_op_mode(&mut self, mode: Node) {
1069        self.kind = mode;
1070    }
1071
1072    /// Set Wi-Fi protocol (overrides default).
1073    pub fn set_protocol(&mut self, protocol: Protocol) {
1074        self.protocol = Some(protocol);
1075    }
1076
1077    /// Set Wi-Fi PHY data rate for ESP-NOW traffic.
1078    pub fn set_rate(&mut self, rate: WifiPhyRate) {
1079        self.rate = Some(rate);
1080    }
1081
1082    /// Run the node until duration in seconds with internal collection.
1083    ///
1084    /// This initializes Wi-Fi, configures CSI, and starts mode-specific tasks.
1085    pub async fn run_duration(&mut self, duration: u64, client: &mut CSINodeClient) {
1086        let interfaces = &mut self.hardware.interfaces;
1087        let controller = &mut self.hardware.controller;
1088
1089        // Tasks Necessary for Central Station & Sniffer
1090        let sta_interface = if let Node::Central(CentralOpMode::WifiStation(config)) = &self.kind {
1091            Some(sta_init(&mut interfaces.station, config, controller))
1092        } else {
1093            None
1094        };
1095
1096        // Build CSI Configuration
1097        let config = match self.csi_config {
1098            Some(ref config) => {
1099                log_ln!("CSI Configuration Set: {:?}", config);
1100                build_csi_config(config)
1101            }
1102            None => {
1103                let default_config = CsiConfiguration::default();
1104                log_ln!(
1105                    "No CSI Configuration Provided. Going with defaults: {:?}",
1106                    default_config
1107                );
1108                build_csi_config(&default_config)
1109            }
1110        };
1111
1112        // Apply Protocol if specified
1113        if let Some(protocol) = self.protocol.take() {
1114            let old_protocol = reconstruct_protocol(&protocol);
1115            let protocols = Protocols::default().with_2_4(EnumSet::only(protocol));
1116            controller.set_protocols(protocols).unwrap();
1117            self.protocol = Some(old_protocol);
1118        }
1119
1120        log_ln!("Wi-Fi Controller Started");
1121        let is_collector = self.collection_mode == CollectionMode::Collector;
1122        IS_COLLECTOR.store(is_collector, Ordering::Relaxed);
1123        set_seq_drop_detection(matches!(
1124            &self.kind,
1125            Node::Peripheral(PeripheralOpMode::EspNow(_))
1126                | Node::Central(CentralOpMode::EspNow(_))
1127        ));
1128
1129        // Replace esp-radio's heap-allocating ESP-NOW receive dispatcher with
1130        // our static-pool variant *before* CSI starts. If we waited until the
1131        // mode-specific arm runs (after `set_csi`), the CSI callback could
1132        // already have begun its UART spin and a vendor frame arriving in
1133        // that window would still hit esp-radio's `rcv_cb` and risk the
1134        // 384 B grow panic. Doing it here covers all peripheral/central
1135        // EspNow modes; sniffer modes also call `esp_now_unregister_recv_cb`
1136        // later which overrides this — also fine.
1137        crate::esp_now_pool::install();
1138
1139        // Set Peripheral/Central to Collect CSI. Keep a clone so the STA
1140        // recovery path in run_sta_connect can re-apply after a stop/start
1141        // cycle (stop clears the CSI filter/callback).
1142        //
1143        // Only register the CSI callback when RX is actually enabled —
1144        // otherwise the radio fires `capture_csi_info` for every overheard
1145        // 802.11 frame (beacons, neighbour ESP-NOW, retries) on the WiFi
1146        // task hot path, stealing cycles from the central TX-completion
1147        // ISR for no purpose.
1148        let csi_config_for_recovery = config.clone();
1149        let is_sniffer = matches!(
1150            &self.kind,
1151            Node::Peripheral(PeripheralOpMode::WifiSniffer(_))
1152        );
1153        if self.io_tasks.rx_enabled && !is_sniffer {
1154            set_csi(controller, config.clone());
1155        }
1156        // The `run_duration` path doesn't use `interfaces.sniffer` — the
1157        // WifiSniffer arm binds its own local. Only `run()` keeps an
1158        // outer binding so its WifiStation arm can clear promiscuous
1159        // mode on shutdown.
1160
1161        // Initialize Nodes based on type
1162        match &self.kind {
1163            Node::Peripheral(op_mode) => match op_mode {
1164                PeripheralOpMode::EspNow(esp_now_config) => {
1165                    // Initialize as Peripheral node with EspNowConfig
1166                    if let Some(rate) = self.rate.take() {
1167                        let old_rate = reconstruct_wifi_rate(&rate);
1168                        let _ = interfaces.esp_now.set_rate(rate);
1169                        self.rate = Some(old_rate);
1170                    }
1171
1172                    let main_task = run_esp_now_peripheral(
1173                        &mut interfaces.esp_now,
1174                        esp_now_config,
1175                        self.traffic_freq_hz,
1176                        self.io_tasks,
1177                    );
1178                    if self.io_tasks.rx_enabled {
1179                        join3(
1180                            main_task,
1181                            run_process_csi_packet(),
1182                            csi_data_collection(client, duration),
1183                        )
1184                        .await;
1185                    } else {
1186                        join3(main_task, wait_for_stop(), stop_after_duration(duration)).await;
1187                    }
1188                }
1189                PeripheralOpMode::WifiSniffer(sniffer_config) => {
1190                    #[cfg(feature = "esp32c5")]
1191                    {
1192                        let band = if sniffer_config.channel() >= 36 {
1193                            BandMode::_5G
1194                        } else {
1195                            BandMode::_2_4G
1196                        };
1197                        controller.set_band_mode(band).unwrap();
1198                    }
1199                    let sniffer = &interfaces.sniffer;
1200                    sniffer.set_promiscuous_mode(true).unwrap();
1201                    controller
1202                        .set_channel(sniffer_config.channel(), SecondaryChannel::None)
1203                        .unwrap();
1204                    if self.io_tasks.rx_enabled {
1205                        set_csi(controller, config.clone());
1206                    }
1207                    // Drop the ESP-NOW receive callback at the C layer.
1208                    // Rationale: in Rust esp-radio, `rcv_cb` runs for every
1209                    // ESP-NOW vendor action frame the 802.11 MAC sees and
1210                    // unconditionally `Box::new`s the payload + push_back's
1211                    // to a heap-backed VecDeque. While the sync CSI callback
1212                    // CPU-spins UART for ~11 ms per line, those frames pile
1213                    // up inside the WiFi task; once the spin returns, rcv_cb
1214                    // burst-fires hundreds of allocs back-to-back, fragmenting
1215                    // the heap until a 384 B VecDeque grow fails → panic.
1216                    // Hernandez never hits this because in C, no recv_cb is
1217                    // registered → frames are silently dropped at the C layer
1218                    // with zero allocation. Replicate that here for sniffer
1219                    // mode (we don't consume ESP-NOW data anyway).
1220                    unsafe extern "C" {
1221                        fn esp_now_unregister_recv_cb() -> i32;
1222                    }
1223                    unsafe {
1224                        let _ = esp_now_unregister_recv_cb();
1225                    }
1226                    if self.io_tasks.rx_enabled {
1227                        join(
1228                            run_process_csi_packet(),
1229                            csi_data_collection(client, duration),
1230                        )
1231                        .await;
1232                        run_process_csi_packet().await;
1233                    } else {
1234                        stop_after_duration(duration).await;
1235                    }
1236                    sniffer.set_promiscuous_mode(false).unwrap();
1237                }
1238            },
1239            Node::Central(op_mode) => match op_mode {
1240                CentralOpMode::EspNow(esp_now_config) => {
1241                    // Initialize as Central node with EspNowConfig
1242                    if let Some(rate) = self.rate.take() {
1243                        let old_rate = reconstruct_wifi_rate(&rate);
1244                        let _ = interfaces.esp_now.set_rate(rate);
1245                        self.rate = Some(old_rate);
1246                    }
1247
1248                    let main_task = run_esp_now_central(
1249                        &mut interfaces.esp_now,
1250                        interfaces.station.mac_address(),
1251                        esp_now_config,
1252                        self.traffic_freq_hz,
1253                        is_collector,
1254                        self.io_tasks,
1255                    );
1256                    if self.io_tasks.rx_enabled {
1257                        join3(
1258                            main_task,
1259                            run_process_csi_packet(),
1260                            csi_data_collection(client, duration),
1261                        )
1262                        .await;
1263                    } else {
1264                        join3(main_task, wait_for_stop(), stop_after_duration(duration)).await;
1265                    }
1266                }
1267                CentralOpMode::WifiStation(_sta_config) => {
1268                    // Initialize as Wifi Station Collector with WifiStationConfig
1269                    // 1. Connect to Wi-Fi network, etc.
1270                    // 2. Run DHCP, NTP sync if enabled in config, etc.
1271                    // 3. Spawn STA Connection Handling Task
1272                    // 4. Spawn STA Network Operation Task
1273                    let (sta_stack, sta_runner) = sta_interface.unwrap();
1274
1275                    let main_task = run_sta_connect(
1276                        controller,
1277                        self.traffic_freq_hz,
1278                        sta_stack,
1279                        sta_runner,
1280                        csi_config_for_recovery,
1281                        self.io_tasks,
1282                    );
1283                    if self.io_tasks.rx_enabled {
1284                        join3(
1285                            main_task,
1286                            run_process_csi_packet(),
1287                            csi_data_collection(client, duration),
1288                        )
1289                        .await;
1290                    } else {
1291                        join3(main_task, wait_for_stop(), stop_after_duration(duration)).await;
1292                    }
1293                }
1294            },
1295        }
1296
1297        STOP_SIGNAL.reset();
1298        reset_globals();
1299    }
1300
1301    /// Run the node until stopped.
1302    ///
1303    /// This initializes Wi-Fi, configures CSI, and starts mode-specific tasks.
1304    pub async fn run(&mut self) {
1305        let interfaces = &mut self.hardware.interfaces;
1306        let controller = &mut self.hardware.controller;
1307
1308        // Tasks Necessary for Central Station & Sniffer
1309        let sta_interface = if let Node::Central(CentralOpMode::WifiStation(config)) = &self.kind {
1310            Some(sta_init(&mut interfaces.station, config, controller))
1311        } else {
1312            None
1313        };
1314
1315        // Build CSI Configuration
1316        let config = match self.csi_config {
1317            Some(ref config) => {
1318                log_ln!("CSI Configuration Set: {:?}", config);
1319                build_csi_config(config)
1320            }
1321            None => {
1322                let default_config = CsiConfiguration::default();
1323                log_ln!(
1324                    "No CSI Configuration Provided. Going with defaults: {:?}",
1325                    default_config
1326                );
1327                build_csi_config(&default_config)
1328            }
1329        };
1330
1331        // Apply Protocol if specified
1332        if let Some(protocol) = self.protocol.take() {
1333            let old_protocol = reconstruct_protocol(&protocol);
1334            let protocols = Protocols::default().with_2_4(EnumSet::only(protocol));
1335            controller.set_protocols(protocols).unwrap();
1336            self.protocol = Some(old_protocol);
1337        }
1338
1339        log_ln!("Wi-Fi Controller Started");
1340        let is_collector = self.collection_mode == CollectionMode::Collector;
1341        IS_COLLECTOR.store(is_collector, Ordering::Relaxed);
1342        set_seq_drop_detection(matches!(
1343            &self.kind,
1344            Node::Peripheral(PeripheralOpMode::EspNow(_))
1345                | Node::Central(CentralOpMode::EspNow(_))
1346        ));
1347
1348        // Replace esp-radio's heap-allocating ESP-NOW receive dispatcher with
1349        // our static-pool variant *before* CSI starts. If we waited until the
1350        // mode-specific arm runs (after `set_csi`), the CSI callback could
1351        // already have begun its UART spin and a vendor frame arriving in
1352        // that window would still hit esp-radio's `rcv_cb` and risk the
1353        // 384 B grow panic. Doing it here covers all peripheral/central
1354        // EspNow modes; sniffer modes also call `esp_now_unregister_recv_cb`
1355        // later which overrides this — also fine.
1356        crate::esp_now_pool::install();
1357
1358        // Set Peripheral/Central to Collect CSI. Keep a clone so the STA
1359        // recovery path in run_sta_connect can re-apply after a stop/start
1360        // cycle (stop clears the CSI filter/callback).
1361        //
1362        // Only register the CSI callback when RX is actually enabled —
1363        // otherwise the radio fires `capture_csi_info` for every overheard
1364        // 802.11 frame (beacons, neighbour ESP-NOW, retries) on the WiFi
1365        // task hot path, stealing cycles from the central TX-completion
1366        // ISR for no purpose.
1367        let csi_config_for_recovery = config.clone();
1368        let is_sniffer = matches!(
1369            &self.kind,
1370            Node::Peripheral(PeripheralOpMode::WifiSniffer(_))
1371        );
1372        if self.io_tasks.rx_enabled && !is_sniffer {
1373            set_csi(controller, config.clone());
1374        }
1375        let sniffer: &esp_radio::wifi::sniffer::Sniffer<'_> = &interfaces.sniffer;
1376
1377        // Initialize Nodes based on type
1378        match &self.kind {
1379            Node::Peripheral(op_mode) => match op_mode {
1380                PeripheralOpMode::EspNow(esp_now_config) => {
1381                    // Initialize as Peripheral node with EspNowConfig
1382                    if let Some(rate) = self.rate.take() {
1383                        let old_rate = reconstruct_wifi_rate(&rate);
1384                        let _ = interfaces.esp_now.set_rate(rate);
1385                        self.rate = Some(old_rate);
1386                    }
1387
1388                    let main_task = run_esp_now_peripheral(
1389                        &mut interfaces.esp_now,
1390                        esp_now_config,
1391                        self.traffic_freq_hz,
1392                        self.io_tasks,
1393                    );
1394                    if self.io_tasks.rx_enabled {
1395                        join(main_task, run_process_csi_packet()).await;
1396                    } else {
1397                        join(main_task, wait_for_stop()).await;
1398                    }
1399                }
1400                PeripheralOpMode::WifiSniffer(sniffer_config) => {
1401                    #[cfg(feature = "esp32c5")]
1402                    {
1403                        let band = if sniffer_config.channel() >= 36 {
1404                            BandMode::_5G
1405                        } else {
1406                            BandMode::_2_4G
1407                        };
1408                        controller.set_band_mode(band).unwrap();
1409                    }
1410                    sniffer.set_promiscuous_mode(true).unwrap();
1411                    controller
1412                        .set_channel(sniffer_config.channel(), SecondaryChannel::None)
1413                        .unwrap();
1414                    if self.io_tasks.rx_enabled {
1415                        set_csi(controller, config.clone());
1416                    }
1417                    // See the sniffer-Collector arm above for rationale.
1418                    unsafe extern "C" {
1419                        fn esp_now_unregister_recv_cb() -> i32;
1420                    }
1421                    unsafe {
1422                        let _ = esp_now_unregister_recv_cb();
1423                    }
1424                    if self.io_tasks.rx_enabled {
1425                        run_process_csi_packet().await;
1426                    } else {
1427                        wait_for_stop().await;
1428                    }
1429                    sniffer.set_promiscuous_mode(false).unwrap();
1430                }
1431            },
1432            Node::Central(op_mode) => match op_mode {
1433                CentralOpMode::EspNow(esp_now_config) => {
1434                    // Initialize as Central node with EspNowConfig
1435                    if let Some(rate) = self.rate.take() {
1436                        let old_rate = reconstruct_wifi_rate(&rate);
1437                        let _ = interfaces.esp_now.set_rate(rate);
1438                        self.rate = Some(old_rate);
1439                    }
1440
1441                    let main_task = run_esp_now_central(
1442                        &mut interfaces.esp_now,
1443                        interfaces.station.mac_address(),
1444                        esp_now_config,
1445                        self.traffic_freq_hz,
1446                        is_collector,
1447                        self.io_tasks,
1448                    );
1449                    if self.io_tasks.rx_enabled {
1450                        join(main_task, run_process_csi_packet()).await;
1451                    } else {
1452                        join(main_task, wait_for_stop()).await;
1453                    }
1454                }
1455                CentralOpMode::WifiStation(_sta_config) => {
1456                    // Initialize as Wifi Station Collector with WifiStationConfig
1457                    // 1. Connect to Wi-Fi network, etc.
1458                    // 2. Run DHCP, NTP sync if enabled in config, etc.
1459                    // 3. Spawn STA Connection Handling Task
1460                    // 4. Spawn STA Network Operation Task
1461                    let (sta_stack, sta_runner) = sta_interface.unwrap();
1462
1463                    let main_task = run_sta_connect(
1464                        controller,
1465                        self.traffic_freq_hz,
1466                        sta_stack,
1467                        sta_runner,
1468                        csi_config_for_recovery,
1469                        self.io_tasks,
1470                    );
1471                    if self.io_tasks.rx_enabled {
1472                        join(main_task, run_process_csi_packet()).await;
1473                    } else {
1474                        join(main_task, wait_for_stop()).await;
1475                    }
1476                    sniffer.set_promiscuous_mode(false).unwrap();
1477                }
1478            },
1479        }
1480
1481        STOP_SIGNAL.reset();
1482        reset_globals();
1483    }
1484}
1485
1486#[cfg(feature = "esp32c5")]
1487fn build_csi_config(csi_config: &CsiConfiguration) -> CsiConfig {
1488    CsiConfig {
1489        enable: csi_config.enable,
1490        acquire_csi_legacy: csi_config.acquire_csi_legacy,
1491        acquire_csi_force_lltf: csi_config.acquire_csi_force_lltf,
1492        acquire_csi_ht20: csi_config.acquire_csi_ht20,
1493        acquire_csi_ht40: csi_config.acquire_csi_ht40,
1494        acquire_csi_vht: csi_config.acquire_csi_vht,
1495        acquire_csi_su: csi_config.acquire_csi_su,
1496        acquire_csi_mu: csi_config.acquire_csi_mu,
1497        acquire_csi_dcm: csi_config.acquire_csi_dcm,
1498        acquire_csi_beamformed: csi_config.acquire_csi_beamformed,
1499        acquire_csi_he_stbc: csi_config.acquire_csi_he_stbc,
1500        val_scale_cfg: csi_config.val_scale_cfg,
1501        dump_ack_en: csi_config.dump_ack_en,
1502        reserved: csi_config.reserved,
1503    }
1504}
1505
1506#[cfg(feature = "esp32c6")]
1507fn build_csi_config(csi_config: &CsiConfiguration) -> CsiConfig {
1508    CsiConfig {
1509        enable: csi_config.enable,
1510        acquire_csi_legacy: csi_config.acquire_csi_legacy,
1511        acquire_csi_ht20: csi_config.acquire_csi_ht20,
1512        acquire_csi_ht40: csi_config.acquire_csi_ht40,
1513        acquire_csi_su: csi_config.acquire_csi_su,
1514        acquire_csi_mu: csi_config.acquire_csi_mu,
1515        acquire_csi_dcm: csi_config.acquire_csi_dcm,
1516        acquire_csi_beamformed: csi_config.acquire_csi_beamformed,
1517        acquire_csi_he_stbc: csi_config.acquire_csi_he_stbc,
1518        val_scale_cfg: csi_config.val_scale_cfg,
1519        dump_ack_en: csi_config.dump_ack_en,
1520        reserved: csi_config.reserved,
1521    }
1522}
1523
1524#[cfg(not(any(feature = "esp32c5", feature = "esp32c6")))]
1525fn build_csi_config(csi_config: &CsiConfiguration) -> CsiConfig {
1526    CsiConfig {
1527        lltf_en: csi_config.lltf_en,
1528        htltf_en: csi_config.htltf_en,
1529        stbc_htltf2_en: csi_config.stbc_htltf2_en,
1530        ltf_merge_en: csi_config.ltf_merge_en,
1531        channel_filter_en: csi_config.channel_filter_en,
1532        manu_scale: csi_config.manu_scale,
1533        shift: csi_config.shift,
1534        dump_ack_en: csi_config.dump_ack_en,
1535    }
1536}
1537
1538/// Total received CSI packets (statistics feature).
1539#[cfg(feature = "statistics")]
1540pub fn get_total_rx_packets() -> u64 {
1541    STATS.rx_count.load(Ordering::Relaxed)
1542}
1543
1544/// Total transmitted packets (statistics feature).
1545#[cfg(feature = "statistics")]
1546pub fn get_total_tx_packets() -> u64 {
1547    STATS.tx_count.load(Ordering::Relaxed)
1548}
1549
1550/// Current RX packet rate in Hz (statistics feature).
1551#[cfg(feature = "statistics")]
1552pub fn get_rx_rate_hz() -> u32 {
1553    STATS.rx_rate_hz.load(Ordering::Relaxed)
1554}
1555
1556/// Current TX packet rate in Hz (statistics feature).
1557#[cfg(feature = "statistics")]
1558pub fn get_tx_rate_hz() -> u32 {
1559    STATS.tx_rate_hz.load(Ordering::Relaxed)
1560}
1561
1562/// Packets per second received since capture start (statistics feature).
1563#[cfg(feature = "statistics")]
1564pub fn get_pps_rx() -> u64 {
1565    let start_time = Instant::from_ticks(STATS.capture_start_time.load(Ordering::Relaxed));
1566    let elapsed_secs = start_time.elapsed().as_secs() as u64;
1567    let total_packets = STATS.rx_count.load(Ordering::Relaxed);
1568    if elapsed_secs == 0 {
1569        return total_packets;
1570    }
1571    total_packets / elapsed_secs
1572}
1573
1574/// Packets per second transmitted since capture start (statistics feature).
1575#[cfg(feature = "statistics")]
1576pub fn get_pps_tx() -> u64 {
1577    let start_time = Instant::from_ticks(STATS.capture_start_time.load(Ordering::Relaxed));
1578    let elapsed_secs = start_time.elapsed().as_secs() as u64;
1579    let total_packets = STATS.tx_count.load(Ordering::Relaxed);
1580    if elapsed_secs == 0 {
1581        return total_packets;
1582    }
1583    total_packets / elapsed_secs
1584}
1585
1586/// Dropped RX packets estimate (statistics feature).
1587#[cfg(feature = "statistics")]
1588pub fn get_dropped_packets_rx() -> u32 {
1589    STATS.rx_drop_count.load(Ordering::Relaxed)
1590}
1591
1592/// One-way latency (statistics feature).
1593#[cfg(feature = "statistics")]
1594pub fn get_one_way_latency() -> i64 {
1595    STATS.one_way_latency.load(Ordering::Relaxed)
1596}
1597
1598/// Two-way latency (statistics feature).
1599#[cfg(feature = "statistics")]
1600pub fn get_two_way_latency() -> i64 {
1601    STATS.two_way_latency.load(Ordering::Relaxed)
1602}
1603
1604/// Sets CSI Configuration.
1605pub(crate) fn set_csi(controller: &mut WifiController, config: CsiConfig) {
1606    // Set CSI Configuration with callback
1607    controller
1608        .set_csi(config, |info: esp_radio::wifi::csi::WifiCsiInfo<'_>| {
1609            capture_csi_info(info);
1610        })
1611        .unwrap();
1612}
1613
1614// Function to capture CSI info from callback and publish to channel
1615fn capture_csi_info(info: esp_radio::wifi::csi::WifiCsiInfo<'_>) {
1616    // Count every CSI report regardless of mode so `rx_count` / `rx_rate_hz`
1617    // / `pps_rx` reflect actual radio CSI throughput. This is the only path
1618    // that fires for sniffer / STA / ESP-NOW collection — counting here keeps
1619    // the metric consistent across all node modes.
1620    #[cfg(feature = "statistics")]
1621    STATS.rx_count.fetch_add(1, Ordering::Relaxed);
1622
1623    // Single-atomic fast path: returns immediately in Listener mode and in
1624    // Collector mode when no CSINodeClient subscriber exists. Building the
1625    // CSIDataPacket and calling publish_immediate acquires CriticalSectionRawMutex
1626    // and on `riscv32imc` every other atomic op also takes a critical section,
1627    // so additional gate atomics in the hot ISR path delay the Embassy timer ISR.
1628    if !CSI_PUBLISH_ENABLED.load(Ordering::Relaxed) {
1629        return;
1630    }
1631
1632    // No CS-locked early-drop pre-check: the lock-free `CSI_QUEUE`
1633    // returns `Err` from `enqueue` when full, so we do drop accounting at
1634    // the enqueue site below. The 640 B `CSIDataPacket` build still has
1635    // to run unconditionally — there's no cheaper way to know if the
1636    // packet is interesting until it's parsed.
1637
1638    let rssi = info.rssi();
1639
1640    let mut csi_data = Vec::<i8, 612>::new();
1641    let csi_slice = info.buf();
1642    let csi_buf_len = csi_slice.len() as u16;
1643    match csi_data.extend_from_slice(csi_slice) {
1644        Ok(_) => {}
1645        Err(_) => {
1646            #[cfg(feature = "statistics")]
1647            STATS.rx_drop_count.fetch_add(1, Ordering::Relaxed);
1648            return;
1649        }
1650    }
1651
1652    let mac_arr = *info.mac();
1653    let timestamp_us = info.timestamp().duration_since_epoch().as_micros() as u32;
1654
1655    #[cfg(not(any(feature = "esp32c5", feature = "esp32c6")))]
1656    let csi_packet = CSIDataPacket {
1657        sequence_number: info.rx_sequence(),
1658        data_format: RxCSIFmt::Undefined,
1659        date_time: None,
1660        mac: mac_arr,
1661        rssi: rssi as i32,
1662        bandwidth: info.cwb() as u32,
1663        antenna: info.antenna() as u32,
1664        rate: info.rate() as u32,
1665        sig_mode: info.packet_mode() as u32,
1666        mcs: info.modulation_coding_scheme() as u32,
1667        smoothing: info.smoothing() as u32,
1668        not_sounding: info.not_sounding() as u32,
1669        aggregation: info.aggregation() as u32,
1670        stbc: info.space_time_block_code() as u32,
1671        fec_coding: info.forward_error_correction_coding() as u32,
1672        sgi: info.short_guide_interval() as u32,
1673        noise_floor: info.noise_floor() as i32,
1674        ampdu_cnt: info.ampdu_count() as u32,
1675        channel: info.channel() as u32,
1676        secondary_channel: info.secondary_channel() as u32,
1677        timestamp: timestamp_us,
1678        rx_state: info.rx_state() as u32,
1679        sig_len: info.signal_length() as u32,
1680        csi_data_len: csi_buf_len,
1681        csi_data,
1682    };
1683
1684    #[cfg(any(feature = "esp32c5", feature = "esp32c6"))]
1685    let csi_packet = CSIDataPacket {
1686        mac: mac_arr,
1687        rssi: rssi as i32,
1688        timestamp: timestamp_us,
1689        rate: info.rate() as u32,
1690        noise_floor: info.noise_floor() as i32,
1691        sig_len: info.signal_length() as u32,
1692        rx_state: info.rx_state() as u32,
1693        dump_len: info.dump_length(),
1694        #[cfg(feature = "esp32c6")]
1695        he_sigb_len: info.he_sigb_length() as u32,
1696        #[cfg(feature = "esp32c6")]
1697        cur_single_mpdu: info.cur_single_mpdu() as u32,
1698        cur_bb_format: info.cur_bb_format() as u32,
1699        rx_channel_estimate_info_vld: info.rx_channel_estimate_info_valid() as u32,
1700        rx_channel_estimate_len: info.rx_channel_estimate_length(),
1701        second: info.secondary_channel() as u32,
1702        channel: info.channel() as u32,
1703        is_group: info.is_group() as u32,
1704        rxend_state: info.rx_end_state() as u32,
1705        rxmatch3: info.rx_match3() as u32,
1706        rxmatch2: info.rx_match2() as u32,
1707        rxmatch1: info.rx_match1() as u32,
1708        #[cfg(feature = "esp32c6")]
1709        rxmatch0: info.rx_match0() as u32,
1710        date_time: None,
1711        sequence_number: info.rx_sequence(),
1712        data_format: RxCSIFmt::Undefined,
1713        csi_data_len: csi_buf_len,
1714        csi_data,
1715    };
1716
1717    #[cfg(feature = "statistics")]
1718    #[allow(static_mut_refs)] // single writer (WiFi callback) by construction
1719    {
1720        if seq_drop_detection_enabled() {
1721            static mut PEER_SEQ_TRACKER: LinearMap<[u8; 6], u16, MAX_TRACKED_PEERS> =
1722                LinearMap::new();
1723            unsafe {
1724                if RESET_SEQ_TRACKER.swap(false, Ordering::Relaxed) {
1725                    PEER_SEQ_TRACKER.clear();
1726                }
1727                let current_seq = csi_packet.sequence_number;
1728                if let Some(&last_seq) = PEER_SEQ_TRACKER.get(&csi_packet.mac) {
1729                    let diff = (current_seq.wrapping_sub(last_seq)) & 0x0FFF;
1730                    if diff > 1 {
1731                        let lost = (diff - 1) as u32;
1732                        if lost < 500 {
1733                            STATS.rx_drop_count.fetch_add(lost, Ordering::Relaxed);
1734                        }
1735                    }
1736                }
1737                if PEER_SEQ_TRACKER.insert(csi_packet.mac, current_seq).is_err() {
1738                    PEER_SEQ_TRACKER.clear();
1739                    let _ = PEER_SEQ_TRACKER.insert(csi_packet.mac, current_seq);
1740                }
1741            }
1742        }
1743    }
1744
1745    // Single-atomic delivery dispatch. One relaxed load, one branch.
1746    // Exactly one of Callback / Async / Off runs — the WiFi callback
1747    // never pays for both a fn-pointer dispatch and a 640 B memcpy on
1748    // the same packet. See `CsiDeliveryMode` for semantics.
1749    match CSI_DELIVERY_MODE.load(Ordering::Relaxed) {
1750        m if m == CsiDeliveryMode::Callback as u8 => {
1751            // Inline callback: zero-copy `&CSIDataPacket` borrow.
1752            let cb_ptr = CSI_CALLBACK.load(core::sync::atomic::Ordering::Relaxed);
1753            if !cb_ptr.is_null() {
1754                let cb: fn(&CSIDataPacket) =
1755                    unsafe { core::mem::transmute::<*mut (), fn(&CSIDataPacket)>(cb_ptr) };
1756                cb(&csi_packet);
1757            }
1758            return;
1759        }
1760        m if m == CsiDeliveryMode::Async as u8 => {
1761            // Lock-free MPMC enqueue + wake. No critical section, no
1762            // IRQ disable — the WiFi-task hot path is never blocked by
1763            // the user's async drainer.
1764            if CSI_QUEUE.enqueue(csi_packet).is_err() {
1765                #[cfg(feature = "statistics")]
1766                STATS.rx_drop_count.fetch_add(1, Ordering::Relaxed);
1767            } else {
1768                CSI_WAKER.wake();
1769            }
1770            return;
1771        }
1772        _ => {}
1773    }
1774
1775    // Off mode: fall through to the inline-log path. In sync mode
1776    // `log_csi` writes the CSI line directly to UART/JTAG here in the
1777    // WiFi callback (matches ESP32-CSI-Tool's `_wifi_csi_cb`); in
1778    // async-print mode it enqueues to the logger backend's own channel
1779    // (`logging::logging::CSI_CHANNEL`, drained by `logger_backend`).
1780    // Either way the packet is consumed.
1781    if CSI_INLINE_LOG_ENABLED.load(Ordering::Relaxed) {
1782        crate::logging::logging::log_csi(csi_packet);
1783    }
1784}
1785
1786/// Internal task that handles collection-mode changes and rate statistics.
1787///
1788/// Seq drop detection runs inside `capture_csi_info` (ISR context) so this task
1789/// never drains `CSI_PACKET`, leaving the channel exclusively for `CSINodeClient`.
1790pub async fn run_process_csi_packet() {
1791    #[cfg(feature = "statistics")]
1792    STATS
1793        .capture_start_time
1794        .store(Instant::now().as_ticks(), Ordering::Relaxed);
1795    #[cfg(feature = "statistics")]
1796    let mut last_rate_update = Instant::now();
1797    #[cfg(feature = "statistics")]
1798    let mut last_rx_count = STATS.rx_count.load(Ordering::Relaxed);
1799    #[cfg(feature = "statistics")]
1800    let mut last_tx_count = STATS.tx_count.load(Ordering::Relaxed);
1801
1802    loop {
1803        match select3(
1804            STOP_SIGNAL.wait(),
1805            COLLECTION_MODE_CHANGED.wait(),
1806            Timer::after_millis(500),
1807        )
1808        .await
1809        {
1810            Either3::First(_) => {
1811                STOP_SIGNAL.signal(());
1812                break;
1813            }
1814            Either3::Second(_) => {
1815                COLLECTION_MODE_CHANGED.reset();
1816                reset_globals();
1817                #[cfg(feature = "statistics")]
1818                {
1819                    STATS
1820                        .capture_start_time
1821                        .store(Instant::now().as_ticks(), Ordering::Relaxed);
1822                    last_rate_update = Instant::now();
1823                    last_rx_count = STATS.rx_count.load(Ordering::Relaxed);
1824                    last_tx_count = STATS.tx_count.load(Ordering::Relaxed);
1825                    RESET_SEQ_TRACKER.store(true, Ordering::Relaxed);
1826                }
1827            }
1828            Either3::Third(_) => {
1829                #[cfg(feature = "statistics")]
1830                {
1831                    let elapsed_secs = last_rate_update.elapsed().as_secs() as u64;
1832                    if elapsed_secs >= 1 {
1833                        let current_rx = STATS.rx_count.load(Ordering::Relaxed);
1834                        let current_tx = STATS.tx_count.load(Ordering::Relaxed);
1835
1836                        let rx_rate = ((current_rx.saturating_sub(last_rx_count))
1837                            / elapsed_secs) as u32;
1838                        let tx_rate = ((current_tx.saturating_sub(last_tx_count))
1839                            / elapsed_secs) as u32;
1840
1841                        STATS.rx_rate_hz.store(rx_rate, Ordering::Relaxed);
1842                        STATS.tx_rate_hz.store(tx_rate, Ordering::Relaxed);
1843
1844                        last_rx_count = current_rx;
1845                        last_tx_count = current_tx;
1846                        last_rate_update = Instant::now();
1847                    }
1848                }
1849            }
1850        }
1851    }
1852}
1853
1854#[cfg(feature = "statistics")]
1855use crate::logging::logging::reset_global_log_drops;
1856
1857fn reconstruct_wifi_rate(rate: &WifiPhyRate) -> WifiPhyRate {
1858    match rate {
1859        WifiPhyRate::Rate1mL => WifiPhyRate::Rate1mL,
1860        WifiPhyRate::Rate2m => WifiPhyRate::Rate2m,
1861        WifiPhyRate::Rate5mL => WifiPhyRate::Rate5mL,
1862        WifiPhyRate::Rate11mL => WifiPhyRate::Rate11mL,
1863        WifiPhyRate::Rate2mS => WifiPhyRate::Rate2mS,
1864        WifiPhyRate::Rate5mS => WifiPhyRate::Rate5mS,
1865        WifiPhyRate::Rate11mS => WifiPhyRate::Rate11mS,
1866        WifiPhyRate::Rate48m => WifiPhyRate::Rate48m,
1867        WifiPhyRate::Rate24m => WifiPhyRate::Rate24m,
1868        WifiPhyRate::Rate12m => WifiPhyRate::Rate12m,
1869        WifiPhyRate::Rate6m => WifiPhyRate::Rate6m,
1870        WifiPhyRate::Rate54m => WifiPhyRate::Rate54m,
1871        WifiPhyRate::Rate36m => WifiPhyRate::Rate36m,
1872        WifiPhyRate::Rate18m => WifiPhyRate::Rate18m,
1873        WifiPhyRate::Rate9m => WifiPhyRate::Rate9m,
1874        WifiPhyRate::RateMcs0Lgi => WifiPhyRate::RateMcs0Lgi,
1875        WifiPhyRate::RateMcs1Lgi => WifiPhyRate::RateMcs1Lgi,
1876        WifiPhyRate::RateMcs2Lgi => WifiPhyRate::RateMcs2Lgi,
1877        WifiPhyRate::RateMcs3Lgi => WifiPhyRate::RateMcs3Lgi,
1878        WifiPhyRate::RateMcs4Lgi => WifiPhyRate::RateMcs4Lgi,
1879        WifiPhyRate::RateMcs5Lgi => WifiPhyRate::RateMcs5Lgi,
1880        WifiPhyRate::RateMcs6Lgi => WifiPhyRate::RateMcs6Lgi,
1881        WifiPhyRate::RateMcs7Lgi => WifiPhyRate::RateMcs7Lgi,
1882        WifiPhyRate::RateMcs0Sgi => WifiPhyRate::RateMcs0Sgi,
1883        WifiPhyRate::RateMcs1Sgi => WifiPhyRate::RateMcs1Sgi,
1884        WifiPhyRate::RateMcs2Sgi => WifiPhyRate::RateMcs2Sgi,
1885        WifiPhyRate::RateMcs3Sgi => WifiPhyRate::RateMcs3Sgi,
1886        WifiPhyRate::RateMcs4Sgi => WifiPhyRate::RateMcs4Sgi,
1887        WifiPhyRate::RateMcs5Sgi => WifiPhyRate::RateMcs5Sgi,
1888        WifiPhyRate::RateMcs6Sgi => WifiPhyRate::RateMcs6Sgi,
1889        WifiPhyRate::RateMcs7Sgi => WifiPhyRate::RateMcs7Sgi,
1890        WifiPhyRate::RateLora250k => WifiPhyRate::RateLora250k,
1891        WifiPhyRate::RateLora500k => WifiPhyRate::RateLora500k,
1892        WifiPhyRate::RateMax => WifiPhyRate::RateMax,
1893    }
1894}
1895
1896fn reconstruct_protocol(protocol: &Protocol) -> Protocol {
1897    match protocol {
1898        Protocol::B => Protocol::B,
1899        Protocol::G => Protocol::G,
1900        Protocol::N => Protocol::N,
1901        Protocol::LR => Protocol::LR,
1902        Protocol::A => Protocol::A,
1903        Protocol::AC => Protocol::AC,
1904        Protocol::AX => Protocol::AX,
1905        _ => Protocol::N,
1906    }
1907}