esp-csi-rs 0.10.1

ESP CSI Driver for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
//! Node role/configuration types and the [`CSINode`] orchestrator.
//!
//! This module owns the user-facing description of a CSI node — its role
//! ([`NodeRole`], and for a collector its capture path [`CollectorMode`]), the
//! per-mode configs ([`EmitterConfig`], [`WifiSnifferConfig`],
//! [`WifiStationConfig`], [`WifiApConfig`]), and the TX/RX toggles — plus
//! [`CSINode`], whose `run` / `run_duration` wire up Wi-Fi, CSI, and the
//! role-specific tasks. It also holds the shared stop signal and the per-run
//! lifecycle helpers.
//!
//! There are exactly two roles. An **emitter** puts known RF energy into the
//! channel and never captures; a **collector** captures the channel's response
//! and delivers it. Everything else — station, softAP, promiscuous sniffer — is a
//! *way of collecting*, not a role of its own.

#[cfg(any(feature = "async-print", feature = "auto"))]
use embassy_time::with_timeout;

use embassy_futures::join::{join, join3};
use embassy_futures::select::{Either, select};
use embassy_time::{Duration, Timer};
use enumset::EnumSet;
#[cfg(feature = "esp32c5")]
use esp_radio::wifi::BandMode;
use esp_radio::wifi::sta::StationConfig;
use esp_radio::wifi::{Interfaces, Protocol, Protocols, SecondaryChannel, WifiController};

use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use portable_atomic::Ordering;

use crate::collector::ap::{ap_init, run_ap};
use crate::collector::sta::{run_sta_connect, sta_init};
use crate::config::CsiConfig as CsiConfiguration;
use crate::central::esp_now::run_esp_now_central;
use crate::central::esp_now_fast::run_esp_now_fast_collector;
use crate::central_peripheral::{CentralOpMode, PeripheralOpMode};
use crate::emitter::{EmitterConfig, run_emitter};
use crate::peripheral::esp_now::run_esp_now_peripheral;
use crate::peripheral::esp_now_fast::run_esp_now_fast_source;
use crate::profile::{RadioProfile, StandardProfile};

use crate::csi::delivery::{
    CSINodeClient, CSI_OUTPUT_ENABLED, build_csi_config, run_process_csi_packet, set_csi,
};
use crate::log_ln;
use crate::radio::{apply_ht40_channel, suppress_espnow_rx};
#[cfg(feature = "esp32c5")]
use crate::radio::{apply_band_auto, apply_band_for_channel};
use crate::stats::set_seq_drop_detection;

// Signals
pub(crate) static STOP_SIGNAL: Signal<CriticalSectionRawMutex, ()> = Signal::new();

/// Per-mutation radio-quiesce delay on C5 dual-band bring-up.
///
/// The C5 Wi-Fi ISR can wedge if a MAC interrupt fires mid-reconfiguration
/// (`set_protocols` / `set_config` STA restart / `set_csi` / `set_channel`),
/// tripping the interrupt watchdog (`handle_interrupts` backtrace at boot) or
/// hard-freezing before any task runs. Dropping the ESP-NOW receive callback at
/// bring-up (see [`crate::radio::suppress_espnow_rx`]) already shrinks that
/// window; inserting a short settle *between* the mutations lets the MAC drain any
/// pending interrupt before the next driver call, shrinking it further. This is a
/// probabilistic mitigation, not a guarantee — the radio restart still races the
/// MAC IRQ — so keeping the air quiet during a node's bring-up remains the most
/// effective measure.
#[cfg(feature = "esp32c5")]
const C5_RADIO_SETTLE_MS: u64 = 60;

/// Await a brief radio-settle delay on C5; no-op on every other chip.
/// See [`C5_RADIO_SETTLE_MS`].
async fn c5_radio_settle() {
    #[cfg(feature = "esp32c5")]
    Timer::after(Duration::from_millis(C5_RADIO_SETTLE_MS)).await;
}

async fn csi_data_collection(client: &mut CSINodeClient, duration: u64) {
    #[cfg(any(feature = "async-print", feature = "auto"))]
    if crate::logging::logging::is_async_logging_active() {
        with_timeout(Duration::from_secs(duration), async {
            loop {
                client.print_csi_w_metadata().await;
            }
        })
        .await
        .unwrap_err();
        client.send_stop().await;
        return;
    }

    #[cfg(not(any(feature = "async-print", feature = "auto")))]
    {
        let _ = client;
    }
    Timer::after(Duration::from_secs(duration)).await;
    client.send_stop().await;
}

async fn wait_for_stop() {
    STOP_SIGNAL.wait().await;
    STOP_SIGNAL.signal(());
}

async fn stop_after_duration(duration: u64) {
    match select(
        STOP_SIGNAL.wait(),
        Timer::after(Duration::from_secs(duration)),
    )
    .await
    {
        Either::First(_) | Either::Second(_) => STOP_SIGNAL.signal(()),
    }
}

/// Configuration for Wi-Fi Promiscuous Sniffer mode.
///
/// Construct with `WifiSnifferConfig::default()` then chain `with_channel`
/// to override defaults.
#[derive(Debug, Clone)]
pub struct WifiSnifferConfig {
    /// Optional MAC source filter (reserved — not yet wired into the
    /// promiscuous filter setup).
    #[allow(dead_code)]
    mac_filter: Option<[u8; 6]>,
    channel: u8,
}

impl Default for WifiSnifferConfig {
    fn default() -> Self {
        Self {
            mac_filter: None,
            // Channel 1 is typically less congested than 11 in dense
            // residential / office environments.
            channel: 1,
        }
    }
}

impl WifiSnifferConfig {
    /// Override the channel the sniffer locks to.
    ///
    /// Must be a valid IEEE 802.11 **primary** channel number — pass the
    /// primary, not the wider-channel center notation that routers
    /// commonly display:
    ///
    /// - **2.4 GHz**: `1`–`14`
    /// - **5 GHz**: `36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112,
    ///   116, 120, 124, 128, 132, 136, 140, 144, 149, 153, 157, 161, 165`
    ///   (regulatory-domain dependent — some restricted by `country_info`)
    ///
    /// Center-channel labels (`38, 46, ...` for HT40; `42, 58, 106, ...`
    /// for VHT80; `50, 114` for VHT160; `154` for the 153/157 HT40 pair)
    /// are **not** accepted here — `esp_wifi_set_channel` panics with
    /// `InvalidArguments`. For example, a router showing "channel 154"
    /// is using primary `153` (or `157`); pass that primary and the chip
    /// will sniff the full 40 MHz block automatically per 802.11.
    ///
    /// On dual-band chips (currently ESP32-C5), the band is auto-selected
    /// from the channel number — channels `>= 36` switch the radio to
    /// `BandMode::_5G`, otherwise `BandMode::_2_4G`. On 2.4-GHz-only
    /// chips, passing any 5 GHz channel will fail at runtime.
    pub fn with_channel(mut self, channel: u8) -> Self {
        self.channel = channel;
        self
    }

    /// Configured channel (2.4 GHz: 1–14, 5 GHz: 36–165).
    pub fn channel(&self) -> u8 {
        self.channel
    }
}

/// Configuration for Wi-Fi Station mode.
#[derive(Debug, Clone)]
pub struct WifiStationConfig {
    /// Underlying esp-radio station configuration (SSID, auth, etc.).
    pub client_config: StationConfig,
    /// Primary channel of the target AP. On dual-band ESP32-C5 this selects
    /// 2.4 vs 5 GHz (`set_band_mode`) before scan/association.
    pub channel_hint: Option<u8>,
}

impl WifiStationConfig {
    /// Build a station config from esp-radio's [`StationConfig`].
    pub fn new(client_config: StationConfig) -> Self {
        Self {
            client_config,
            channel_hint: None,
        }
    }

    /// Pin the radio band from the AP's primary channel (C5 dual-band only).
    pub fn with_channel_hint(mut self, channel: u8) -> Self {
        self.channel_hint = Some(channel);
        self
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for WifiStationConfig {
    fn format(&self, fmt: defmt::Formatter<'_>) {
        defmt::write!(fmt, "WifiStationConfig {{ client_config: <opaque> }}");
    }
}

/// Configuration for self-contained softAP CSI collector mode.
///
/// Wraps esp-radio's [`AccessPointConfig`] (SSID, channel, auth, secondary
/// channel) and the static IPv4 addressing used by the built-in DHCP server.
/// The AP hands associating stations addresses from a lease pool in the AP's /24
/// subnet with the gateway set to the AP itself.
///
/// `channel`/`secondary_channel` are duplicated here because esp-radio's
/// `AccessPointConfig` fields are not externally readable; [`CSINode`] needs them
/// for band/HT40 setup.
///
/// [`AccessPointConfig`]: esp_radio::wifi::ap::AccessPointConfig
pub struct WifiApConfig {
    /// Underlying esp-radio access-point configuration.
    pub ap_config: esp_radio::wifi::ap::AccessPointConfig,
    /// Primary channel the AP operates on (mirror of `ap_config`'s channel).
    pub channel: u8,
    /// Optional HT40 secondary channel (mirror of `ap_config`'s secondary).
    pub secondary_channel: Option<SecondaryChannel>,
    /// AP's static IPv4 address; also the gateway and DHCP server identifier.
    pub ap_ipv4: core::net::Ipv4Addr,
    /// First IPv4 address in the DHCP lease pool (typically `.2`).
    pub lease_ipv4: core::net::Ipv4Addr,
    /// Number of consecutive lease addresses starting at [`Self::lease_ipv4`]
    /// (e.g. `3` → `.2`, `.3`, `.4`). Default `1` preserves the original
    /// single-client behaviour.
    pub lease_count: u8,
    /// Whether to run the built-in DHCP server. When `false`, the AP only starts
    /// + collects CSI (clients must self-assign IPs).
    pub serve_dhcp: bool,
    /// When `true`, every flood tick fires one unicast frame back-to-back to
    /// **all** active leases instead of advancing one lease per tick (round-robin).
    /// All associated stations then receive their downlink PPDU within tens of
    /// microseconds of each other — temporally-synchronized multi-receiver CSI —
    /// instead of being spread across the whole tick interval.
    ///
    /// This is the workable path to synchronized multi-receiver CSI. A single
    /// group-addressed broadcast frame does *not* work on an ESP32 softAP:
    /// broadcast/multicast is DTIM-buffered, dropped under a high-rate flood, and
    /// only ever sent at the legacy basic rate — so it mostly never leaves the
    /// radio and never honours a forced high-throughput TX rate. Only unicast
    /// transmits immediately and honours the configured TX rate, so N unicast
    /// frames per tick keep near-simultaneous arrival across receivers. Stations
    /// must be **associated** — an unassociated receiver does not reliably
    /// produce CSI from overheard frames.
    ///
    /// Per-receiver rate is the configured ping rate; total offered rate is
    /// `rate * lease_count`, so lower the rate if airtime saturates. Default
    /// `false` preserves per-lease round-robin. Set by [`Self::with_sync_burst`].
    pub sync_burst: bool,
}

impl WifiApConfig {
    /// Create a config from an [`AccessPointConfig`], its primary `channel`, and
    /// optional HT40 `secondary` channel. Defaults the AP to `192.168.13.1/24`,
    /// leases `192.168.13.2`, and enables the DHCP server.
    ///
    /// [`AccessPointConfig`]: esp_radio::wifi::ap::AccessPointConfig
    pub fn new(
        ap_config: esp_radio::wifi::ap::AccessPointConfig,
        channel: u8,
        secondary: Option<SecondaryChannel>,
    ) -> Self {
        Self {
            ap_config,
            channel,
            secondary_channel: secondary,
            ap_ipv4: core::net::Ipv4Addr::new(192, 168, 13, 1),
            lease_ipv4: core::net::Ipv4Addr::new(192, 168, 13, 2),
            lease_count: 1,
            serve_dhcp: true,
            sync_burst: false,
        }
    }

    /// Override the AP/lease IPv4 addresses (must share a /24).
    pub fn with_ipv4(mut self, ap: core::net::Ipv4Addr, lease: core::net::Ipv4Addr) -> Self {
        self.ap_ipv4 = ap;
        self.lease_ipv4 = lease;
        self
    }

    /// Set the DHCP lease pool size (consecutive addresses from `lease_ipv4`).
    pub fn with_lease_pool(mut self, count: u8) -> Self {
        self.lease_count = count.max(1);
        self
    }

    /// Lease address at `index` (`0` = `lease_ipv4`, `1` = next host, …).
    pub fn lease_ip_at(&self, index: u8) -> core::net::Ipv4Addr {
        let idx = index.min(self.lease_count.saturating_sub(1));
        let mut oct = self.lease_ipv4.octets();
        oct[3] = oct[3].saturating_add(idx);
        core::net::Ipv4Addr::from(oct)
    }

    /// All configured pool addresses (up to [`Self::lease_count`]).
    pub fn lease_pool(&self) -> heapless::Vec<core::net::Ipv4Addr, 8> {
        let mut v = heapless::Vec::new();
        for i in 0..self.lease_count.min(8) {
            let _ = v.push(self.lease_ip_at(i));
        }
        v
    }

    /// Enable or disable the built-in DHCP server (default enabled).
    pub fn with_dhcp_server(mut self, enabled: bool) -> Self {
        self.serve_dhcp = enabled;
        self
    }

    /// Fire one unicast frame back-to-back to every active lease per flood tick,
    /// instead of unicasting round-robin (one lease per tick).
    ///
    /// All associated stations then receive their downlink PPDU within
    /// microseconds of each other — synchronized multi-receiver CSI without the
    /// round-robin spread. This is the workable substitute for a single broadcast
    /// PPDU, which an ESP32 softAP can't reliably deliver (see [`Self::sync_burst`]).
    /// Keep the DHCP server / lease pool enabled so stations associate as genuine
    /// BSS members; only the per-tick transmit pattern changes.
    pub fn with_sync_burst(mut self, enabled: bool) -> Self {
        self.sync_burst = enabled;
        self
    }

    /// Configured primary channel.
    pub fn channel(&self) -> u8 {
        self.channel
    }

    /// Configured HT40 secondary channel, or `None` for HT20.
    pub fn secondary_channel(&self) -> Option<SecondaryChannel> {
        self.secondary_channel
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for WifiApConfig {
    fn format(&self, fmt: defmt::Formatter<'_>) {
        defmt::write!(fmt, "WifiApConfig {{ ap_config: <opaque> }}");
    }
}

/// How a collector obtains the frames it measures.
///
/// These are capture paths, not roles: each one ends with this node holding CSI.
/// Which one to use depends on what traffic is available to measure.
pub enum CollectorMode {
    /// Lock a channel in promiscuous mode and measure every frame overheard.
    ///
    /// This is the capture path that pairs with an [`NodeRole::Emitter`]: the
    /// emitter injects unassociated frames and the sniffer measures them, with no
    /// association or handshake between the two.
    Sniffer(WifiSnifferConfig),
    /// Associate as a Wi-Fi station and measure CSI from received frames.
    Station(WifiStationConfig),
    /// Run a self-contained softAP: start an access point (plus a minimal DHCP
    /// server) so a [`CollectorMode::Station`] node can associate and generate
    /// steady uplink traffic, measured as CSI here.
    AccessPoint(WifiApConfig),
}

/// What this node is for.
///
/// A CSI measurement needs energy in the channel and something to measure the
/// channel's response. [`Emitter`](Self::Emitter) and [`Collector`](Self::Collector) are that
/// split, and they are how every 802.11 capture path in this crate is expressed.
///
/// [`Central`](Self::Central) and [`Peripheral`](Self::Peripheral) are the older ESP-NOW taxonomy,
/// restored alongside rather than folded into the two above. They are not a different spelling of
/// emitter/collector: an ESP-NOW pair is a two-way exchange in which both ends transmit and the
/// central also measures, so neither end maps onto a role defined by which direction it faces.
/// Collapsing them was what removed ESP-NOW from the crate in the first place (b069331).
pub enum NodeRole {
    /// Transmit-only: force a TX PHY and loop-inject sounding frames. Never
    /// captures CSI. See [`crate::emitter`].
    Emitter(EmitterConfig),
    /// Capture the channel response and deliver it, via the chosen capture path.
    /// See [`crate::collector`].
    Collector(CollectorMode),
    /// Drive an ESP-NOW exchange, or one of the Wi-Fi modes that predate the emitter/collector
    /// split. See [`crate::central`].
    Central(CentralOpMode),
    /// Respond to a central's ESP-NOW exchange. See [`crate::peripheral`].
    Peripheral(PeripheralOpMode),
}

/// Placeholder for the central driver's unused `_mac_addr` parameter. See its call site.
const UNSET_MAC: [u8; 6] = [0; 6];

/// The ESP-NOW-era spelling of [`NodeRole`], kept so `Node::Central(..)` resolves for callers
/// written against it. One type, two names — not a conversion.
pub use NodeRole as Node;

/// Controls whether TX and RX tasks are active for a node.
///
/// Defaults to both TX and RX enabled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IOTaskConfig {
    /// Enable transmit-side task work for the selected operation mode.
    pub tx_enabled: bool,
    /// Enable receive/process-side task work for the selected operation mode.
    pub rx_enabled: bool,
}

impl IOTaskConfig {
    /// Create a task configuration with explicit TX/RX state.
    pub const fn new(tx_enabled: bool, rx_enabled: bool) -> Self {
        Self {
            tx_enabled,
            rx_enabled,
        }
    }
}

impl Default for IOTaskConfig {
    fn default() -> Self {
        Self::new(true, true)
    }
}

/// Hardware handles required to operate a node in either role.
pub struct NodeHardware<'a> {
    interfaces: &'a mut Interfaces<'static>,
    controller: &'a mut WifiController<'static>,
}

impl<'a> NodeHardware<'a> {
    /// Create a hardware bundle from the Wi-Fi `Interfaces` and `WifiController`.
    pub fn new(
        interfaces: &'a mut Interfaces<'static>,
        controller: &'a mut WifiController<'static>,
    ) -> Self {
        Self {
            interfaces,
            controller,
        }
    }
}

pub(crate) fn reset_globals() {
    // Close all CSI delivery gates so any late-firing WiFi callback runs
    // are no-ops. The CSI callback stays registered with esp-radio after stop
    // (the radio itself is still up), but with the gates closed the callback
    // short-circuits before it touches the log channel or the user's callback.
    // Without this, a collector keeps emitting CSI lines on the serial port
    // well after `send_stop()`.
    //
    // The statistics counters are deliberately NOT cleared here. This runs at the END of
    // `run_inner`, so clearing them destroyed the run's numbers at the moment the run finished —
    // every post-collection `show-stats` on the classic AP/STA path reported `RX Total Packets: 0`
    // however many frames the callback had counted, which reads as "the radio received nothing"
    // when the truth was "the radio received plenty and the log path could not keep up". The
    // counters are the only evidence a user has that captured CSI was dropped rather than never
    // captured, and this was throwing that evidence away.
    //
    // `stats::reset` now runs at the START of a run instead (see `run_inner`), which is both what
    // the README already documents ("counters reset on the start of each new `start` collection")
    // and what the HE20 path already did via `stats_begin_run`.
    crate::csi::delivery::reset();
}

/// Primary orchestration object for a CSI node.
///
/// Construct with [`CSINode::new`] (or [`CSINode::new_collector`] for the common
/// case), configure optional protocol / traffic frequency, then call `run()`.
pub struct CSINode<'a> {
    role: NodeRole,
    /// Whether captured CSI is delivered off-device. See
    /// [`CSINode::set_csi_output_enabled`].
    csi_output_enabled: bool,
    io_tasks: IOTaskConfig,
    /// CSI Configuration
    csi_config: Option<CsiConfiguration>,
    /// Traffic Generation Frequency
    traffic_freq_hz: Option<u16>,
    hardware: NodeHardware<'a>,
    protocol: Option<Protocol>,
    /// ICMP flood sends unsolicited echo replies (one-directional traffic)
    /// instead of echo requests. See [`CSINode::set_flood_unsolicited_reply`].
    flood_unsolicited_reply: bool,
    /// Pluggable Wi-Fi bring-up back-end. Defaults to [`StandardProfile`];
    /// override with [`CSINode::set_radio_profile`].
    profile: &'static dyn RadioProfile,
    /// How much this node does with the CSI it collects. Restored with the central/peripheral
    /// taxonomy; see [`CollectionMode`](crate::CollectionMode).
    collection_mode: crate::CollectionMode,
    /// Forced ESP-NOW peer PHY rate, set by [`CSINode::set_rate`].
    esp_now_rate: Option<esp_radio::esp_now::WifiPhyRate>,
}

impl<'a> CSINode<'a> {
    /// Create a node in the given role.
    ///
    /// CSI output is enabled by default. An [`NodeRole::Emitter`] captures no CSI,
    /// so the setting has no effect there.
    pub fn new(
        role: NodeRole,
        csi_config: Option<CsiConfiguration>,
        traffic_freq_hz: Option<u16>,
        hardware: NodeHardware<'a>,
    ) -> Self {
        Self {
            role,
            csi_output_enabled: true,
            io_tasks: IOTaskConfig::default(),
            csi_config,
            traffic_freq_hz,
            hardware,
            collection_mode: crate::CollectionMode::Collector,
            esp_now_rate: None,
            protocol: None,
            flood_unsolicited_reply: false,
            profile: &StandardProfile,
        }
    }

    /// Convenience constructor for a collector node.
    pub fn new_collector(
        mode: CollectorMode,
        csi_config: Option<CsiConfiguration>,
        traffic_freq_hz: Option<u16>,
        hardware: NodeHardware<'a>,
    ) -> Self {
        Self::new(
            NodeRole::Collector(mode),
            csi_config,
            traffic_freq_hz,
            hardware,
        )
    }

    /// Convenience constructor for an emitter node.
    pub fn new_emitter(config: EmitterConfig, hardware: NodeHardware<'a>) -> Self {
        Self::new(NodeRole::Emitter(config), None, None, hardware)
    }

    /// Get the node's role.
    pub fn get_role(&self) -> &NodeRole {
        &self.role
    }

    /// Whether captured CSI is currently delivered off-device.
    pub fn csi_output_enabled(&self) -> bool {
        self.csi_output_enabled
    }

    /// If this is a collector, return its capture mode.
    pub fn get_collector_mode(&self) -> Option<&CollectorMode> {
        match &self.role {
            NodeRole::Collector(mode) => Some(mode),
            _ => None,
        }
    }

    /// If this is an emitter, return its configuration.
    pub fn get_emitter_config(&self) -> Option<&EmitterConfig> {
        match &self.role {
            NodeRole::Emitter(config) => Some(config),
            _ => None,
        }
    }

    /// If this is a central, return its operating mode.
    pub fn get_central_mode(&self) -> Option<&CentralOpMode> {
        match &self.role {
            NodeRole::Central(mode) => Some(mode),
            _ => None,
        }
    }

    /// If this is a peripheral, return its operating mode.
    pub fn get_peripheral_mode(&self) -> Option<&PeripheralOpMode> {
        match &self.role {
            NodeRole::Peripheral(mode) => Some(mode),
            _ => None,
        }
    }

    /// Update CSI configuration.
    pub fn set_csi_config(&mut self, config: CsiConfiguration) {
        self.csi_config = Some(config);
    }

    /// Update Wi-Fi Station configuration (only applies to a station collector).
    pub fn set_station_config(&mut self, config: WifiStationConfig) {
        if let NodeRole::Collector(CollectorMode::Station(_)) = &mut self.role {
            self.role = NodeRole::Collector(CollectorMode::Station(config));
        }
    }

    /// Set traffic generation frequency in Hz (station / softAP collectors).
    pub fn set_traffic_frequency(&mut self, freq_hz: u16) {
        self.traffic_freq_hz = Some(freq_hz);
    }

    /// Enable or disable delivery of captured CSI off-device.
    ///
    /// When disabled the radio still captures CSI — keeping the RX path and its
    /// timing identical — but nothing is decoded, logged, or handed to a callback.
    /// Useful for a node whose only job is to keep traffic on air, or for
    /// measuring capture overhead without the delivery cost.
    ///
    /// Has no effect on an [`NodeRole::Emitter`], which captures nothing.
    pub fn set_csi_output_enabled(&mut self, enabled: bool) {
        self.csi_output_enabled = enabled;
    }

    /// Set TX/RX task enablement for the node.
    /// Set how much this node does with the CSI it collects.
    ///
    /// A separate call rather than a fifth argument to [`CSINode::new`]: the four-argument form is
    /// what the open-source CLI calls, and widening it would break every existing caller to serve
    /// a mode most of them never set.
    pub fn set_collection_mode(&mut self, mode: crate::CollectionMode) {
        self.collection_mode = mode;
    }

    /// Which collection mode this node is running in.
    pub fn collection_mode(&self) -> crate::CollectionMode {
        self.collection_mode
    }

    /// Force the ESP-NOW peer PHY rate.
    ///
    /// ESP-NOW only, by design — a station derives its rate from the AP it associated with, and a
    /// sniffer from whatever it overhears, so neither has a rate to force. Stored here and applied
    /// when the ESP-NOW roles are wired into the run loop; until then it is recorded and unused
    /// rather than silently dropped.
    pub fn set_rate(&mut self, rate: esp_radio::esp_now::WifiPhyRate) {
        self.esp_now_rate = Some(rate);
    }

    pub fn set_io_tasks(&mut self, io_tasks: IOTaskConfig) {
        self.io_tasks = io_tasks;
    }

    /// Enable or disable TX task work.
    pub fn set_tx_enabled(&mut self, enabled: bool) {
        self.io_tasks.tx_enabled = enabled;
    }

    /// Enable or disable RX task work.
    pub fn set_rx_enabled(&mut self, enabled: bool) {
        self.io_tasks.rx_enabled = enabled;
    }

    /// Get current TX/RX task configuration.
    pub fn get_io_tasks(&self) -> IOTaskConfig {
        self.io_tasks
    }

    /// Replace the node's role.
    pub fn set_role(&mut self, role: NodeRole) {
        self.role = role;
    }

    /// Set Wi-Fi protocol (overrides default).
    pub fn set_protocol(&mut self, protocol: Protocol) {
        self.protocol = Some(protocol);
    }

    /// Install a Wi-Fi bring-up profile (overrides the default
    /// [`StandardProfile`]). Pass a reference to a zero-sized profile value,
    /// e.g. `node.set_radio_profile(&MyProfile);`.
    pub fn set_radio_profile(&mut self, profile: &'static dyn RadioProfile) {
        self.profile = profile;
    }

    /// Make the ICMP traffic flood send unsolicited echo **replies** instead
    /// of echo requests.
    ///
    /// The peer's IP stack silently ignores an unsolicited reply, so the
    /// generated traffic becomes strictly one-directional: the peer still
    /// hardware-ACKs every data frame (rate control stays fed) and captures
    /// CSI per frame, but never transmits an IP-level response. This halves
    /// the on-air frame count versus request/reply and stabilizes the offered
    /// rate under CSMA contention. Trade-off: this node receives no CSI back
    /// from the peer's replies.
    pub fn set_flood_unsolicited_reply(&mut self, enabled: bool) {
        self.flood_unsolicited_reply = enabled;
    }

    /// Run the node for `duration` seconds with internal collection.
    ///
    /// This initializes Wi-Fi, configures CSI, and starts mode-specific tasks.
    pub async fn run_duration(&mut self, duration: u64, client: &mut CSINodeClient) {
        self.run_inner(Some(duration), Some(client)).await;
    }

    /// Shared implementation behind [`run`](Self::run) and
    /// [`run_duration`](Self::run_duration).
    ///
    /// `duration`/`client` are `Some` only on the timed `run_duration` path:
    /// when set, each mode arm runs an extra concurrent future that stops the
    /// node after `duration` seconds (and, with RX enabled, drains CSI to the
    /// logger via `client`). When `None` the node runs until externally
    /// stopped via [`CSINodeClient::send_stop`].
    async fn run_inner(&mut self, duration: Option<u64>, client: Option<&mut CSINodeClient>) {
        // Zero the counters and stamp the capture start so `show-stats` describes THIS run, and
        // still describes it after the run ends. Deliberately here rather than in `reset_globals`,
        // which runs at stop — see the note there. Mirrors what the HE20 collector path already
        // does with `stats_begin_run`.
        #[cfg(feature = "statistics")]
        crate::stats::stats_begin_run();

        let interfaces = &mut self.hardware.interfaces;
        let controller = &mut self.hardware.controller;

        // Applied every run (not only when set) so the process-wide flood-kind
        // flag never leaks from a previous, differently-configured run.
        crate::collector::sta::set_icmp_flood_unsolicited(self.flood_unsolicited_reply);

        // Applied every run, for the same reason as the flood flag above: the gate is
        // process-wide, so a node left as a Listener by a previous run would silently stop
        // processing CSI in this one. Read by the ESP-NOW central to decide whether it does
        // anything with what it captures.
        crate::set_runtime_collection_mode(
            self.collection_mode == crate::CollectionMode::Collector,
        );

        // Deal with esp-radio's built-in ESP-NOW receive dispatcher before any other Wi-Fi
        // reconfiguration runs — see `suppress_espnow_rx` for why this must happen this early.
        //
        // WHICH treatment depends on the role, and getting it wrong is silent. `suppress_espnow_rx`
        // permanently UNREGISTERS the callback, which is right for the 802.11 roles — none of them
        // reads ESP-NOW, and the stock dispatcher heap-allocates every overheard vendor action
        // frame into a deque nothing drains. It is exactly wrong for the ESP-NOW roles, which would
        // then be deaf: a peripheral would never see a control frame and a fast source would never
        // hear the discovery beacon, both while looking perfectly healthy.
        //
        // So an ESP-NOW role installs the static-pool dispatcher instead, which replaces the
        // allocating one rather than removing it — same protection against the heap growth, and the
        // frames still arrive.
        if matches!(&self.role, NodeRole::Central(_) | NodeRole::Peripheral(_)) {
            crate::esp_now_pool::install();
        } else {
            suppress_espnow_rx();
        }
        // Let the freshly-constructed radio state settle before the first C5
        // reconfiguration mutation (no-op off C5).
        c5_radio_settle().await;

        let is_ap = matches!(
            &self.role,
            NodeRole::Collector(CollectorMode::AccessPoint(_))
        );
        let is_sniffer = matches!(&self.role, NodeRole::Collector(CollectorMode::Sniffer(_)));
        let is_emitter = matches!(&self.role, NodeRole::Emitter(_));

        // An emitter never captures, so CSI is only ever armed for a collector.
        // Everything downstream keys off this rather than re-testing the role.
        let rx_enabled = self.io_tasks.rx_enabled && !is_emitter;

        // Radio-profile back-end (Copy handle; does not alias `self.hardware`).
        // `bringup` decides whether the profile takes over the extended Wi-Fi
        // bring-up sequence for this role/protocol.
        let profile = self.profile;
        let bringup = profile.wants_bringup(&self.role, self.protocol);

        // Apply protocol ladder before STA bring-up / CSI. Generic chip-level tuning
        // lives in the radio profile; specialised back-ends may rebuild the set
        // entirely. Skipped for an emitter, which pins its own protocol set during
        // bring-up to match its forced TX PHY.
        if let Some(protocol) = self.protocol.take() {
            if !is_emitter {
                let base = Protocols::default().with_2_4(protocol_ladder_2_4(protocol));
                let protocols = profile.tune_protocols(&self.role, protocol, base);
                controller.set_protocols(protocols).unwrap();
                c5_radio_settle().await;
            }
            self.protocol = Some(protocol);
        }

        if bringup && !is_emitter {
            profile.apply_bandwidth(controller);
            c5_radio_settle().await;
        }

        // Tasks necessary for a station collector.
        let sta_interface =
            if let NodeRole::Collector(CollectorMode::Station(config)) = &self.role {
                let ifaces = sta_init(
                    &mut interfaces.station,
                    config,
                    controller,
                    profile,
                    bringup,
                );
                // Band selection comes *after* `sta_init`, which is what configures and
                // starts the interface: `esp_wifi_set_band_mode` requires a started
                // controller, so doing this first failed silently and left the station on
                // whatever band a previous run had selected.
                //
                // With a channel hint, pin the band it implies. Without one, select both
                // bands — pinning a single band would make an access point on the other
                // one invisible, which presents as a bare "no access point found".
                #[cfg(feature = "esp32c5")]
                {
                    match config.channel_hint {
                        Some(channel) => apply_band_for_channel(controller, channel),
                        None => apply_band_auto(controller),
                    }
                    c5_radio_settle().await;
                }
                Some(ifaces)
            } else {
                None
            };
        if bringup && sta_interface.is_some() {
            profile.apply_protocols_post(controller);
            c5_radio_settle().await;
        }

        // Self-contained softAP: bring up the AP-side embassy-net stack (static
        // IP) and apply the AP config to the controller. `interfaces.access_point`
        // is disjoint from `.station`/`.sniffer`, so this borrow is fine.
        let ap_interface = if let NodeRole::Collector(CollectorMode::AccessPoint(config)) =
            &self.role
        {
            #[cfg(feature = "esp32c5")]
            if config.secondary_channel().is_none() {
                apply_band_for_channel(controller, config.channel());
            }
            if let Some(secondary) = config.secondary_channel() {
                apply_ht40_channel(controller, config.channel(), secondary);
                c5_radio_settle().await;
            }
            let ifaces = ap_init(
                &mut interfaces.access_point,
                config,
                controller,
                profile,
                bringup,
            );
            if bringup {
                profile.apply_protocols_post(controller);
            }
            // The AP `set_config` restarts the radio; settle before `set_csi`.
            c5_radio_settle().await;
            Some(ifaces)
        } else {
            None
        };

        // Build CSI Configuration. An emitter captures nothing, so this is only
        // meaningful for a collector — but it is cheap and keeps the flow linear.
        let mut config = match self.csi_config {
            Some(ref config) => {
                log_ln!("CSI Configuration Set: {:?}", config);
                build_csi_config(config)
            }
            None => {
                let default_config = CsiConfiguration::default();
                log_ln!(
                    "No CSI Configuration Provided. Going with defaults: {:?}",
                    default_config
                );
                build_csi_config(&default_config)
            }
        };
        // Let the radio profile enable any extra acquisition modes it needs
        // (default is a no-op) before the config is registered/cloned.
        profile.tune_csi_acquisition(&mut config);

        log_ln!("Wi-Fi Controller Started");
        CSI_OUTPUT_ENABLED.store(self.csi_output_enabled, Ordering::Relaxed);
        // Sequence-drop detection tracks per-source-MAC sequence numbers, so it
        // works for any collector: the emitter's driver-assigned incrementing
        // sequence numbers make gaps in a capture measurable.
        set_seq_drop_detection(!is_emitter);

        // Keep a clone so the STA recovery path in `run_sta_connect` can re-apply
        // after a stop/start cycle (stop clears the CSI filter/callback).
        //
        // Only register the CSI callback when RX is actually enabled — otherwise
        // the radio fires `capture_csi_info` for every overheard 802.11 frame on
        // the WiFi task hot path for no purpose.
        let csi_config_for_recovery = config.clone();
        // The sniffer arm sets CSI after locking its channel; the AP arm sets it
        // inside `run_ap`, because `set_config(AccessPoint)` restarts the radio and
        // clears the CSI filter.
        if rx_enabled && !is_sniffer && !is_ap {
            set_csi(controller, config.clone());
            // Settle after enabling CSI before the role task issues its first
            // set_channel / TX so the run loop doesn't start into a pending IRQ.
            c5_radio_settle().await;
        }
        // Immutable borrow of a *different* `interfaces` field than the station
        // arm touches, so this disjoint borrow is fine. Used by the sniffer arm and
        // to clear promiscuous mode on station shutdown.
        let sniffer = &interfaces.sniffer;

        match &self.role {
            NodeRole::Emitter(emitter_config) => {
                // The emitter owns its whole bring-up (forced TX PHY, unassociated
                // interface start, channel lock) inside `run_emitter`, because the
                // forced rate has to be applied before the interface starts.
                let main_task = run_emitter(controller, interfaces, emitter_config);
                drive_main(main_task, false, duration, client).await;
            }
            NodeRole::Collector(mode) => match mode {
                CollectorMode::Sniffer(sniffer_config) => {
                    #[cfg(feature = "esp32c5")]
                    {
                        let band = if sniffer_config.channel() >= 36 {
                            BandMode::_5G
                        } else {
                            BandMode::_2_4G
                        };
                        controller.set_band_mode(band).unwrap();
                    }
                    sniffer.set_promiscuous_mode(true).unwrap();
                    controller
                        .set_channel(sniffer_config.channel(), SecondaryChannel::None)
                        .unwrap();
                    if bringup {
                        profile.apply_sniffer_radio(controller);
                        c5_radio_settle().await;
                    }
                    if rx_enabled {
                        set_csi(controller, config.clone());
                    }
                    // The sniffer arm has no `main_task`, so it drives CSI
                    // collection directly rather than through `drive_main`.
                    match (duration, rx_enabled) {
                        (Some(d), true) => {
                            join(
                                run_process_csi_packet(),
                                csi_data_collection(client.unwrap(), d),
                            )
                            .await;
                            // `csi_data_collection` signals stop, so the join
                            // returns; this trailing await lets the rate task
                            // observe the stop and exit (preserves prior behavior).
                            run_process_csi_packet().await;
                        }
                        (Some(d), false) => stop_after_duration(d).await,
                        (None, true) => run_process_csi_packet().await,
                        (None, false) => wait_for_stop().await,
                    }
                    sniffer.set_promiscuous_mode(false).unwrap();
                }
                CollectorMode::AccessPoint(ap_config) => {
                    // Start the AP, run the net stack + optional DHCP server, and
                    // collect CSI from associated stations' uplink frames. CSI is
                    // registered inside `run_ap` (after the AP-start radio restart).
                    let (ap_stack, ap_runner) = ap_interface.unwrap();
                    let main_task = run_ap(
                        controller,
                        ap_stack,
                        ap_runner,
                        ap_config,
                        csi_config_for_recovery,
                        self.io_tasks,
                        self.traffic_freq_hz,
                    );
                    drive_main(main_task, rx_enabled, duration, client).await;
                    sniffer.set_promiscuous_mode(false).unwrap();
                }
                CollectorMode::Station(_sta_config) => {
                    // 1. Connect to the Wi-Fi network.
                    // 2. Run DHCP / NTP sync if enabled in config.
                    // 3. Drive STA connection handling and network operations.
                    let (sta_stack, sta_runner) = sta_interface.unwrap();

                    let main_task = run_sta_connect(
                        controller,
                        self.traffic_freq_hz,
                        sta_stack,
                        sta_runner,
                        csi_config_for_recovery,
                        self.io_tasks,
                    );
                    drive_main(main_task, rx_enabled, duration, client).await;
                    // Clear promiscuous mode on shutdown. It is never enabled on
                    // a STA interface, so this is a no-op — kept to match the
                    // unconditional shutdown path the untimed `run()` always took.
                    sniffer.set_promiscuous_mode(false).unwrap();
                }
            },

            // ── ESP-NOW ───────────────────────────────────────────────────────────────────────
            //
            // The four drivers all take `&mut EspNow<'static>`, and this tree already has one:
            // `interfaces.esp_now`, the same handle the emitter uses to transmit over ESP-NOW on
            // classic chips. The pre-refactor loop built its own and threaded it through twenty
            // integration points; none of that is needed here, and reproducing it would have been
            // a second bring-up path to keep in step with this one.
            //
            // Borrowing note: the `sniffer` binding above holds `&interfaces.sniffer`. These arms
            // take `&mut interfaces.esp_now`, a disjoint field, which the borrow checker accepts —
            // and they must not touch `sniffer`, which is why none of them clears promiscuous mode
            // on the way out. ESP-NOW never sets it.
            NodeRole::Central(mode) => match mode {
                CentralOpMode::EspNow(cfg) => {
                    // `is_collector` decides whether the central PROCESSES the CSI it captures or
                    // merely keeps it flowing — the `CollectionMode` distinction. It is read from
                    // the same runtime flag the delivery path uses, so a mode change mid-run is
                    // seen by both.
                    let main_task = run_esp_now_central(
                        &mut interfaces.esp_now,
                        // `run_esp_now_central` takes this as `_mac_addr` and does not read it —
                        // the peer MAC it actually uses comes from `EspNowConfig::peer_mac`. Passed
                        // as an explicit unset value rather than a plausible-looking address, so
                        // that if the driver ever starts reading it the result is obviously wrong
                        // rather than subtly wrong.
                        UNSET_MAC,
                        cfg,
                        self.traffic_freq_hz,
                        crate::IS_COLLECTOR.load(Ordering::Relaxed),
                        self.io_tasks,
                    );
                    drive_main(main_task, rx_enabled, duration, client).await;
                }
                CentralOpMode::EspNowFastCollector(cfg) => {
                    // Asymmetric simplex: this end beacons until it hears a source, then goes
                    // RX-only. All airtime belongs to the one transmitter, which is the whole point
                    // of the mode, so there is no TX task to drive alongside it.
                    let main_task = run_esp_now_fast_collector(
                        &mut interfaces.esp_now,
                        cfg,
                        self.io_tasks,
                    );
                    drive_main(main_task, rx_enabled, duration, client).await;
                }
                // The Wi-Fi modes of the central taxonomy are the SAME code as the collector arms
                // above — `central::{ap, sta}` is a re-export of `collector::{ap, sta}`, not a
                // second copy. Rather than duplicate two long bring-up sequences that would drift,
                // these are rejected at construction; a caller wanting them builds a
                // `NodeRole::Collector`, which is where that path lives now.
                CentralOpMode::WifiStation(_) | CentralOpMode::WifiAccessPoint(_) => {
                    log_ln!(
                        "central Wi-Fi modes are served by NodeRole::Collector — \
                         build CollectorMode::Station / ::AccessPoint instead"
                    );
                }
            },
            NodeRole::Peripheral(mode) => match mode {
                PeripheralOpMode::EspNow(cfg) => {
                    let main_task = run_esp_now_peripheral(
                        &mut interfaces.esp_now,
                        cfg,
                        self.traffic_freq_hz,
                        self.io_tasks,
                    );
                    drive_main(main_task, rx_enabled, duration, client).await;
                }
                PeripheralOpMode::EspNowFastSource(cfg) => {
                    // The source end of asymmetric simplex: a continuous forced-PHY unicast flood.
                    // It captures nothing, so RX is forced off regardless of `rx_enabled` — leaving
                    // the CSI rate task running here would compete for airtime with the flood it
                    // exists to produce.
                    let main_task = run_esp_now_fast_source(
                        &mut interfaces.esp_now,
                        cfg,
                        self.traffic_freq_hz,
                        self.io_tasks,
                    );
                    drive_main(main_task, false, duration, client).await;
                }
                // As above: the sniffer path is `CollectorMode::Sniffer`, not a second
                // implementation living under `peripheral`.
                PeripheralOpMode::WifiSniffer(_) => {
                    log_ln!(
                        "peripheral sniffer is served by NodeRole::Collector — \
                         build CollectorMode::Sniffer instead"
                    );
                }
            },
        }

        STOP_SIGNAL.reset();
        reset_globals();
    }

    /// Run the node until stopped.
    ///
    /// This initializes Wi-Fi, configures CSI, and starts mode-specific tasks.
    pub async fn run(&mut self) {
        self.run_inner(None, None).await;
    }
}

/// Concurrent driver for a mode's `main_task`.
///
/// Joins `main_task` with the CSI rate task (RX enabled) or a stop waiter, and
/// — on the timed `run_duration` path (`duration`/`client` are `Some`) — a
/// third future that ends the run after `duration` seconds, draining CSI to the
/// logger via `client` when RX is enabled.
async fn drive_main(
    main_task: impl core::future::Future,
    rx_enabled: bool,
    duration: Option<u64>,
    client: Option<&mut CSINodeClient>,
) {
    match (duration, rx_enabled) {
        (Some(d), true) => {
            join3(
                main_task,
                run_process_csi_packet(),
                csi_data_collection(client.unwrap(), d),
            )
            .await;
        }
        (Some(d), false) => {
            join3(main_task, wait_for_stop(), stop_after_duration(d)).await;
        }
        (None, true) => {
            join(main_task, run_process_csi_packet()).await;
        }
        (None, false) => {
            join(main_task, wait_for_stop()).await;
        }
    }
}

/// Expand a single requested 2.4 GHz protocol into the cumulative set the radio needs.
///
/// 802.11 protocol sets on 2.4 GHz are a **ladder**, not a choice: 11n is an extension of
/// 11b/11g and 11ax extends all three, so a station must advertise the rungs beneath the one
/// it wants. Advertising a lone bit (the previous `EnumSet::only(protocol)`) produces a set
/// no real link can use.
///
/// This was measured, not theorised. With an N-only set, an ESP32-C6 `sniffer` collected
/// **zero** HT20 frames from a working emitter — reproduced on both C6 boards, in both role
/// assignments — while ESP32-S3 collectors on the same link and the same config collected
/// normally (their driver tolerates the degenerate set). The emitter never hit this because
/// `emitter::phy` builds `B | G | N` for itself; only the collector path used `only()`.
///
/// `LR` is Espressif's proprietary long-range PHY rather than a rung on the ladder, so it
/// stays on its own. The 5 GHz-only rungs keep the previous one-bit behaviour instead of
/// being given an invented 2.4 GHz meaning — [`RadioProfile::tune_protocols`] owns the
/// 5 GHz set.
fn protocol_ladder_2_4(protocol: Protocol) -> EnumSet<Protocol> {
    match protocol {
        Protocol::B => EnumSet::only(Protocol::B),
        Protocol::G => Protocol::B | Protocol::G,
        Protocol::N => Protocol::B | Protocol::G | Protocol::N,
        Protocol::AX => Protocol::B | Protocol::G | Protocol::N | Protocol::AX,
        // Proprietary long-range, and the 5 GHz-only rungs: not part of the 2.4 GHz ladder.
        other => EnumSet::only(other),
    }
}

#[cfg(test)]
mod protocol_ladder_tests {
    use super::*;

    /// The rung under test must always be present, and every lower rung with it.
    #[test]
    fn each_rung_carries_the_ones_beneath_it() {
        assert_eq!(protocol_ladder_2_4(Protocol::B), EnumSet::only(Protocol::B));
        assert_eq!(protocol_ladder_2_4(Protocol::G), Protocol::B | Protocol::G);
        assert_eq!(
            protocol_ladder_2_4(Protocol::N),
            Protocol::B | Protocol::G | Protocol::N
        );
        assert_eq!(
            protocol_ladder_2_4(Protocol::AX),
            Protocol::B | Protocol::G | Protocol::N | Protocol::AX
        );
    }

    /// Regression for the measured failure: an N-only 2.4 GHz set made an ESP32-C6
    /// collector capture zero HT20 frames. `N` must never be advertised alone.
    #[test]
    fn n_is_never_advertised_alone() {
        let set = protocol_ladder_2_4(Protocol::N);
        assert!(set.contains(Protocol::N));
        assert!(set.contains(Protocol::G), "11n needs 11g beneath it");
        assert!(set.contains(Protocol::B), "11n needs 11b beneath it");
        assert_ne!(set, EnumSet::only(Protocol::N));
    }

    /// The collector ladder must match what the emitter already builds for itself in
    /// `emitter::phy` (`B | G | N`) — the two ends of an HT link have to agree, and the
    /// mismatch between them is exactly what this bug was.
    #[test]
    fn the_ht_rung_matches_the_emitters_own_set() {
        assert_eq!(
            protocol_ladder_2_4(Protocol::N),
            Protocol::B | Protocol::G | Protocol::N
        );
    }

    /// `LR` is Espressif's proprietary long-range PHY, not a rung: it must stay alone,
    /// or enabling it would silently also advertise b/g/n.
    #[test]
    fn lr_stays_on_its_own() {
        assert_eq!(protocol_ladder_2_4(Protocol::LR), EnumSet::only(Protocol::LR));
    }

    /// 5 GHz-only rungs keep the previous single-bit behaviour; the profile owns that band.
    #[test]
    fn five_ghz_rungs_are_untouched() {
        for p in [Protocol::A, Protocol::AC] {
            assert_eq!(protocol_ladder_2_4(p), EnumSet::only(p));
        }
    }
}