device-envoy-rp 0.1.0

Build Pico applications with LED panels, easy Wi-Fi, and composable device abstractions
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
//! A device abstraction for WiFi connectivity used internally by [`crate::wifi_auto::WifiAutoRp`].
//!
//! See the [WifiAutoRp struct example](crate::wifi_auto::WifiAutoRp) for usage.

#![allow(clippy::future_not_send, reason = "single-threaded")]
#![allow(
    unsafe_code,
    reason = "StackStorage uses UnsafeCell in single-threaded context"
)]

use core::cell::{RefCell, UnsafeCell};
use cyw43::JoinOptions;
use cyw43_pio::{DEFAULT_CLOCK_DIVIDER, PioSpi};
use defmt::*;
use embassy_executor::Spawner;
use embassy_net::{Config, Stack, StackResources};
use embassy_rp::peripherals;
use embassy_rp::pio::Pio;
use embassy_rp::{
    Peri,
    dma::{Channel as DmaChannel, ChannelInstance},
    gpio::{Level, Output},
    peripherals::{PIN_23, PIN_24, PIN_25, PIN_29},
};
use embassy_sync::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
use embassy_sync::signal::Signal;
use embassy_time::Timer;
use portable_atomic::{AtomicBool, Ordering};
use static_cell::StaticCell;

use super::dhcp::dhcp_server_task;
use crate::flash_block::{FlashBlock as _, FlashBlockRp};
use device_envoy_core::wifi_auto::{WifiCredentials, WifiStartMode};

const CYW43_NVRAM: &[u8; 746] = b"
    NVRAMRev=$Rev$\x00\
    manfid=0x2d0\x00\
    prodid=0x0727\x00\
    vendid=0x14e4\x00\
    devid=0x43e2\x00\
    boardtype=0x0887\x00\
    boardrev=0x1100\x00\
    boardnum=22\x00\
    macaddr=00:A0:50:b5:59:5e\x00\
    sromrev=11\x00\
    boardflags=0x00404001\x00\
    boardflags3=0x04000000\x00\
    xtalfreq=37400\x00\
    nocrc=1\x00\
    ag0=255\x00\
    aa2g=1\x00\
    ccode=ALL\x00\
    pa0itssit=0x20\x00\
    extpagain2g=0\x00\
    pa2ga0=-168,6649,-778\x00\
    AvVmid_c0=0x0,0xc8\x00\
    cckpwroffset0=5\x00\
    maxp2ga0=84\x00\
    txpwrbckof=6\x00\
    cckbw202gpo=0\x00\
    legofdmbw202gpo=0x66111111\x00\
    mcsbw202gpo=0x77711111\x00\
    propbw202gpo=0xdd\x00\
    ofdmdigfilttype=18\x00\
    ofdmdigfilttypebe=18\x00\
    papdmode=1\x00\
    papdvalidtest=1\x00\
    pacalidx2g=45\x00\
    papdepsoffset=-30\x00\
    papdendidx=58\x00\
    ltecxmux=0\x00\
    ltecxpadnum=0x0102\x00\
    ltecxfnsel=0x44\x00\
    ltecxgcigpio=0x01\x00\
    il0macaddr=00:90:4c:c5:12:38\x00\
    wl0id=0x431b\x00\
    deadman_to=0xffffffff\x00\
    muxenab=0x100\x00\
    spurconfig=0x3\x00\
    glitch_based_crsmin=1\x00\
    btc_mode=1\x00\
    \x00";

// ============================================================================
// Types
// ============================================================================

/// Events emitted by the WiFi device.
pub enum WifiEvent {
    /// Network stack is initialized in captive portal mode, ready for configuration
    CaptivePortalReady,
    /// Network stack is initialized in client mode and DHCP is configured
    ClientReady,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct WifiStoredState {
    credentials: Option<WifiCredentials>,
    start_mode: WifiStartMode,
}

impl Default for WifiStoredState {
    fn default() -> Self {
        Self {
            credentials: None,
            start_mode: WifiStartMode::CaptivePortal,
        }
    }
}

/// Internal WiFi operating mode used during startup.
#[derive(Clone, PartialEq, Eq)]
#[doc(hidden)]
pub enum WifiMode {
    /// Start in captive portal mode for configuration (no credentials needed)
    CaptivePortal,
    /// Connect to WiFi network using provisioned credentials
    ClientConfigured(WifiCredentials),
}

/// Single-threaded once-storage for network stack
///
/// SAFETY: This is safe in single-threaded Embassy context
pub struct StackStorage {
    initialized: AtomicBool,
    ready: Signal<CriticalSectionRawMutex, ()>,
    value: UnsafeCell<Option<&'static Stack<'static>>>,
}

// SAFETY: We're in a single-threaded context (Embassy on Pico)
unsafe impl Sync for StackStorage {}

impl StackStorage {
    /// Create a new empty StackStorage
    #[must_use]
    pub const fn new() -> Self {
        Self {
            initialized: AtomicBool::new(false),
            ready: Signal::new(),
            value: UnsafeCell::new(None),
        }
    }

    /// Initialize the stack storage (can only be called once)
    pub fn init(&self, stack: &'static Stack<'static>) {
        // SAFETY: This is called once from WiFi device loop
        unsafe {
            *self.value.get() = Some(stack);
        }
        self.initialized.store(true, Ordering::Release);
        self.ready.signal(());
    }

    /// Wait for the stack to be initialized and return it
    pub async fn get(&self) -> &'static Stack<'static> {
        if !self.initialized.load(Ordering::Acquire) {
            self.ready.wait().await;
        }
        // SAFETY: initialized is true, so value is set
        unsafe { (*self.value.get()).unwrap() }
    }
}

// ============================================================================
// WiFi Virtual Device
// ============================================================================

/// Signal type for WiFi events.
pub type WifiEvents = Signal<CriticalSectionRawMutex, WifiEvent>;

/// PIO peripheral used by the WiFi driver.
#[doc(hidden)]
pub trait WifiPio: crate::pio_irqs::PioIrqMap {
    fn spawn_wifi_task(
        spawner: Spawner,
        runner: cyw43::Runner<'static, cyw43::SpiBus<Output<'static>, PioSpi<'static, Self, 0>>>,
    );

    fn spawn_device_loop(
        spawner: Spawner,
        pin_23: Peri<'static, PIN_23>,
        pin_24: Peri<'static, PIN_24>,
        pin_25: Peri<'static, PIN_25>,
        pin_29: Peri<'static, PIN_29>,
        pio: Peri<'static, Self>,
        dma: DmaChannel<'static>,
        mode: WifiMode,
        captive_portal_ssid: &'static str,
        wifi_events: &'static WifiEvents,
        stack_storage: &'static StackStorage,
    );
}

/// Resources needed by the WiFi device.
pub struct WifiStatic {
    events: WifiEvents,
    stack: StackStorage,
    wifi_cell: StaticCell<Wifi>,
}

/// A device abstraction that manages WiFi connectivity and network stack in both captive portal and client modes.
///
/// See the [WifiAutoRp struct example](crate::wifi_auto::WifiAutoRp) for usage.
pub struct Wifi {
    events: &'static WifiEvents,
    stack: &'static StackStorage,
    credential_store: Mutex<CriticalSectionRawMutex, RefCell<FlashBlockRp>>,
}

impl Wifi {
    /// Create WiFi resources (events + storage).
    ///
    /// This must be called once to create a static `WifiStatic` that will be passed to
    /// [`Wifi::new_with_captive_portal_ssid`].
    ///
    /// See the [WifiAutoRp struct example](crate::wifi_auto::WifiAutoRp) for usage.
    #[must_use]
    pub const fn new_static() -> WifiStatic {
        WifiStatic {
            events: Signal::new(),
            stack: StackStorage::new(),
            wifi_cell: StaticCell::new(),
        }
    }

    /// Wait for the network stack to be ready and return a reference to it.
    ///
    /// This provides access to the Embassy network stack for TCP/UDP operations.
    /// The stack will be configured differently depending on the WiFi mode:
    /// - In captive portal mode: static IP 192.168.4.1
    /// - In client mode: DHCP-assigned IP
    ///
    /// See the [WifiAutoRp struct example](crate::wifi_auto::WifiAutoRp) for usage.
    pub async fn wait_for_stack(&self) -> &'static Stack<'static> {
        self.stack.get().await
    }

    /// Wait for and return the next WiFi event.
    ///
    /// This will block until the next [`WifiEvent`] occurs, such as:
    /// - [`WifiEvent::CaptivePortalReady`] when captive portal mode is initialized
    /// - [`WifiEvent::ClientReady`] when connected to WiFi and DHCP is configured
    ///
    /// See the [WifiAutoRp struct example](crate::wifi_auto::WifiAutoRp) for usage.
    pub async fn wait_for_wifi_event(&self) -> WifiEvent {
        self.events.wait().await
    }

    pub fn new_with_captive_portal_ssid<PIO: WifiPio, DMA: ChannelInstance>(
        wifi_static: &'static WifiStatic,
        pin_23: Peri<'static, PIN_23>,
        pin_24: Peri<'static, PIN_24>,
        pin_25: Peri<'static, PIN_25>,
        pin_29: Peri<'static, PIN_29>,
        pio: Peri<'static, PIO>,
        dma: Peri<'static, DMA>,
        credential_store: FlashBlockRp,
        captive_portal_ssid: &'static str,
        spawner: Spawner,
    ) -> &'static Self
    where
        crate::pio_irqs::DmaAllIrqs: embassy_rp::interrupt::typelevel::Binding<
                DMA::Interrupt,
                embassy_rp::dma::InterruptHandler<DMA>,
            >,
    {
        let mut store_block = credential_store;
        let stored_state = load_state_from_block(&mut store_block);
        let mode = match stored_state.start_mode {
            WifiStartMode::CaptivePortal => WifiMode::CaptivePortal,
            WifiStartMode::Client => {
                if let Some(wifi_credentials) = stored_state.credentials.clone() {
                    WifiMode::ClientConfigured(wifi_credentials)
                } else {
                    WifiMode::CaptivePortal
                }
            }
        };
        let dma = DmaChannel::new(dma, crate::pio_irqs::DmaAllIrqs);
        PIO::spawn_device_loop(
            spawner,
            pin_23,
            pin_24,
            pin_25,
            pin_29,
            pio,
            dma,
            mode,
            captive_portal_ssid,
            &wifi_static.events,
            &wifi_static.stack,
        );
        wifi_static.wifi_cell.init(Self {
            events: &wifi_static.events,
            stack: &wifi_static.stack,
            credential_store: Mutex::new(RefCell::new(store_block)),
        })
    }

    fn update_state<F>(&self, f: F) -> Result<(), &'static str>
    where
        F: FnOnce(&mut WifiStoredState),
    {
        self.credential_store.lock(|cell| {
            let mut block = cell.borrow_mut();
            let mut state = load_state_from_block(&mut block);
            f(&mut state);
            save_state_to_block(&mut block, &state)
        })
    }

    fn read_state<R>(&self, f: impl FnOnce(&WifiStoredState) -> R) -> R {
        self.credential_store.lock(|cell| {
            let mut block = cell.borrow_mut();
            let state = load_state_from_block(&mut block);
            f(&state)
        })
    }

    /// Persist credentials into the configured flash store.
    pub fn persist_credentials(&self, credentials: &WifiCredentials) -> Result<(), &'static str> {
        let cloned = credentials.clone();
        self.update_state(|state| {
            state.credentials = Some(cloned.clone());
            state.start_mode = WifiStartMode::Client;
        })
    }

    /// Load stored credentials if available.
    pub fn load_persisted_credentials(&self) -> Option<WifiCredentials> {
        self.read_state(|state| state.credentials.clone())
    }

    /// Return the currently configured start mode.
    pub fn current_start_mode(&self) -> WifiStartMode {
        self.read_state(|state| state.start_mode)
    }

    /// Change the stored start mode flag.
    pub fn set_start_mode(&self, mode: WifiStartMode) -> Result<(), &'static str> {
        self.update_state(|state| {
            state.start_mode = mode;
        })
    }

    /// Update the start mode flag in a raw flash block before WiFi initialization.
    pub fn prepare_start_mode(
        block: &mut FlashBlockRp,
        mode: WifiStartMode,
    ) -> Result<(), &'static str> {
        let mut state = load_state_from_block(block);
        state.start_mode = mode;
        save_state_to_block(block, &state)
    }

    /// Peek stored credentials directly from a flash block.
    pub fn peek_credentials(block: &mut FlashBlockRp) -> Option<WifiCredentials> {
        load_state_from_block(block).credentials
    }

    /// Peek the stored start mode directly from a flash block.
    pub fn peek_start_mode(block: &mut FlashBlockRp) -> WifiStartMode {
        load_state_from_block(block).start_mode
    }
}

fn load_state_from_block(block: &mut FlashBlockRp) -> WifiStoredState {
    match block.load::<WifiStoredState>() {
        Ok(Some(state)) => state,
        Ok(None) => WifiStoredState::default(),
        Err(_) => {
            warn!("Failed to load stored WiFi state");
            WifiStoredState::default()
        }
    }
}

fn save_state_to_block(
    block: &mut FlashBlockRp,
    state: &WifiStoredState,
) -> Result<(), &'static str> {
    block
        .save(state)
        .map_err(|_| "Failed to save WiFi state to flash")
}

async fn wifi_task_impl<PIO: WifiPio>(
    runner: cyw43::Runner<'static, cyw43::SpiBus<Output<'static>, PioSpi<'static, PIO, 0>>>,
) -> ! {
    runner.run().await
}

async fn wifi_device_loop_impl<PIO: WifiPio>(
    pin_23: Peri<'static, PIN_23>,
    pin_24: Peri<'static, PIN_24>,
    pin_25: Peri<'static, PIN_25>,
    pin_29: Peri<'static, PIN_29>,
    pio: Peri<'static, PIO>,
    dma: DmaChannel<'static>,
    mode: WifiMode,
    captive_portal_ssid: &'static str,
    wifi_events: &'static WifiEvents,
    stack_storage: &'static StackStorage,
    spawner: Spawner,
) -> ! {
    match mode {
        WifiMode::CaptivePortal => {
            wifi_device_loop_captive_portal(
                pin_23,
                pin_24,
                pin_25,
                pin_29,
                pio,
                dma,
                captive_portal_ssid,
                wifi_events,
                stack_storage,
                spawner,
            )
            .await
        }
        WifiMode::ClientConfigured(credentials) => {
            wifi_device_loop_client_configured(
                pin_23,
                pin_24,
                pin_25,
                pin_29,
                pio,
                dma,
                wifi_events,
                stack_storage,
                spawner,
                credentials,
            )
            .await
        }
    }
}

/// WiFi device loop for captive portal mode
async fn wifi_device_loop_captive_portal<PIO: WifiPio>(
    pin_23: Peri<'static, PIN_23>,
    pin_24: Peri<'static, PIN_24>,
    pin_25: Peri<'static, PIN_25>,
    pin_29: Peri<'static, PIN_29>,
    pio: Peri<'static, PIO>,
    dma: DmaChannel<'static>,
    captive_portal_ssid: &'static str,
    wifi_events: &'static WifiEvents,
    stack_storage: &'static StackStorage,
    spawner: Spawner,
) -> ! {
    info!(
        "WiFi device initializing in captive portal mode ({})",
        captive_portal_ssid
    );

    // Initialize WiFi hardware
    static FW: cyw43::Aligned<cyw43::A4, [u8; cyw43_firmware::CYW43_43439A0.len()]> =
        cyw43::Aligned(*cyw43_firmware::CYW43_43439A0);
    let clm = cyw43_firmware::CYW43_43439A0_CLM;
    static NVRAM: cyw43::Aligned<cyw43::A4, [u8; CYW43_NVRAM.len()]> = cyw43::Aligned(*CYW43_NVRAM);

    let pwr = Output::new(pin_23, Level::Low);
    let cs = Output::new(pin_25, Level::High);
    let mut pio = Pio::new(pio, <PIO as crate::pio_irqs::PioIrqMap>::irqs());
    let spi = PioSpi::new(
        &mut pio.common,
        pio.sm0,
        DEFAULT_CLOCK_DIVIDER,
        pio.irq0,
        cs,
        pin_24,
        pin_29,
        dma,
    );

    static STATE: StaticCell<cyw43::State> = StaticCell::new();
    let state = STATE.init(cyw43::State::new());
    let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, &FW, &NVRAM).await;
    PIO::spawn_wifi_task(spawner, runner);

    control.init(clm).await;
    control
        .set_power_management(cyw43::PowerManagementMode::PowerSave)
        .await;

    // Start captive portal mode
    const CAPTIVE_PORTAL_PASSWORD: &str = ""; // Open network

    info!("Starting captive portal mode: {}", captive_portal_ssid);

    // Configure static IP for captive portal mode (we are the gateway)
    let config = Config::ipv4_static(embassy_net::StaticConfigV4 {
        address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(192, 168, 4, 1), 24),
        gateway: Some(embassy_net::Ipv4Address::new(192, 168, 4, 1)),
        dns_servers: heapless::Vec::from_slice(&[embassy_net::Ipv4Address::new(192, 168, 4, 1)])
            .unwrap(),
    });

    let seed = 0x0bad_cafe_dead_beef;

    static RESOURCES: StaticCell<StackResources<5>> = StaticCell::new();
    static STACK: StaticCell<Stack<'static>> = StaticCell::new();
    let (stack_val, runner) = embassy_net::new(
        net_device,
        config,
        RESOURCES.init(StackResources::<5>::new()),
        seed,
    );
    let stack = STACK.init(stack_val);

    let net_task_token = unwrap!(net_task(runner));
    spawner.spawn(net_task_token);

    // Start captive portal network
    if CAPTIVE_PORTAL_PASSWORD.is_empty() {
        control.start_ap_open(captive_portal_ssid, 1).await;
    } else {
        control
            .start_ap_wpa2(captive_portal_ssid, CAPTIVE_PORTAL_PASSWORD, 1)
            .await;
    }

    info!("Captive portal mode started! SSID: {}", captive_portal_ssid);

    stack.wait_config_up().await;

    if let Some(config) = stack.config_v4() {
        info!("Captive portal IP Address: {}", config.address);
    }

    // Start DHCP server for captive portal mode
    let server_ip = embassy_net::Ipv4Address::new(192, 168, 4, 1);
    let netmask = embassy_net::Ipv4Address::new(255, 255, 255, 0);
    let pool_start = embassy_net::Ipv4Address::new(192, 168, 4, 2);
    let pool_size = 253; // 192.168.4.2 - 192.168.4.254

    let dhcp_server_token = unwrap!(dhcp_server_task(
        stack, server_ip, netmask, pool_start, pool_size,
    ));
    spawner.spawn(dhcp_server_token);

    info!("DHCP server started (pool: 192.168.4.2-254)");
    info!(
        "WiFi captive portal ready - connect to '{}'",
        captive_portal_ssid
    );

    // Store stack reference and emit CaptivePortalReady event
    stack_storage.init(stack);
    wifi_events.signal(WifiEvent::CaptivePortalReady);

    // Keep task alive
    loop {
        Timer::after_secs(3600).await;
    }
}

/// WiFi device loop for client mode with provisioned credentials
async fn wifi_device_loop_client_configured<PIO: WifiPio>(
    pin_23: Peri<'static, PIN_23>,
    pin_24: Peri<'static, PIN_24>,
    pin_25: Peri<'static, PIN_25>,
    pin_29: Peri<'static, PIN_29>,
    pio: Peri<'static, PIO>,
    dma: DmaChannel<'static>,
    wifi_events: &'static WifiEvents,
    stack_storage: &'static StackStorage,
    spawner: Spawner,
    credentials: WifiCredentials,
) -> ! {
    let WifiCredentials { ssid, password } = credentials;

    wifi_device_loop_client_impl(
        pin_23,
        pin_24,
        pin_25,
        pin_29,
        pio,
        dma,
        wifi_events,
        stack_storage,
        spawner,
        ssid,
        password,
    )
    .await
}

/// Shared client-mode implementation.
async fn wifi_device_loop_client_impl<PIO: WifiPio>(
    pin_23: Peri<'static, PIN_23>,
    pin_24: Peri<'static, PIN_24>,
    pin_25: Peri<'static, PIN_25>,
    pin_29: Peri<'static, PIN_29>,
    pio: Peri<'static, PIO>,
    dma: DmaChannel<'static>,
    wifi_events: &'static WifiEvents,
    stack_storage: &'static StackStorage,
    spawner: Spawner,
    ssid: heapless::String<32>,
    password: heapless::String<64>,
) -> ! {
    info!("WiFi device initializing in client mode");

    let ssid_str = ssid;
    let password_str = password;

    // Initialize WiFi hardware
    static FW: cyw43::Aligned<cyw43::A4, [u8; cyw43_firmware::CYW43_43439A0.len()]> =
        cyw43::Aligned(*cyw43_firmware::CYW43_43439A0);
    let clm = cyw43_firmware::CYW43_43439A0_CLM;
    static NVRAM: cyw43::Aligned<cyw43::A4, [u8; CYW43_NVRAM.len()]> = cyw43::Aligned(*CYW43_NVRAM);

    let pwr = Output::new(pin_23, Level::Low);
    let cs = Output::new(pin_25, Level::High);
    let mut pio = Pio::new(pio, <PIO as crate::pio_irqs::PioIrqMap>::irqs());
    let spi = PioSpi::new(
        &mut pio.common,
        pio.sm0,
        DEFAULT_CLOCK_DIVIDER,
        pio.irq0,
        cs,
        pin_24,
        pin_29,
        dma,
    );

    static STATE: StaticCell<cyw43::State> = StaticCell::new();
    let state = STATE.init(cyw43::State::new());
    let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, &FW, &NVRAM).await;
    PIO::spawn_wifi_task(spawner, runner);

    control.init(clm).await;
    control
        .set_power_management(cyw43::PowerManagementMode::PowerSave)
        .await;

    // Initialize network stack
    let config = Config::dhcpv4(Default::default());
    let seed = 0x7c8f_3a2e_9d14_6b5a;

    static RESOURCES: StaticCell<StackResources<5>> = StaticCell::new();
    static STACK: StaticCell<Stack<'static>> = StaticCell::new();
    let (stack_val, runner) = embassy_net::new(
        net_device,
        config,
        RESOURCES.init(StackResources::<5>::new()),
        seed,
    );
    let stack = STACK.init(stack_val);

    let net_task_token = unwrap!(net_task(runner));
    spawner.spawn(net_task_token);

    // Connect to WiFi
    info!(
        "Connecting to WiFi: {} (password length: {})",
        ssid_str,
        password_str.len()
    );
    // TODO Pico2 WiFi driver has bugs - retrying after join failure causes IOCTL crashes
    // Just try once and let the higher-level timeout in wait_for_client_ready_with_timeout
    // handle retries by restarting the entire WiFi task
    match control
        .join(ssid_str.as_str(), JoinOptions::new(password_str.as_bytes()))
        .await
    {
        Ok(_) => {
            info!("WiFi join succeeded");
        }
        Err(err) => {
            info!("WiFi join failed: {:?}", defmt::Debug2Format(&err));
            info!("Not retrying - letting timeout handle this to avoid driver bugs");
            // Don't signal ClientReady - let the timeout in wait_for_client_ready_with_timeout
            // trigger and the higher-level retry logic will restart this entire task
            loop {
                Timer::after_secs(3600).await;
            }
        }
    }

    info!("WiFi connected! Waiting for DHCP...");
    let mut dhcp_wait_seconds = 0_u32;
    let config = loop {
        if let Some(config) = stack.config_v4() {
            break config;
        }
        if dhcp_wait_seconds % 5 == 0 {
            info!(
                "DHCP wait {}s (link_up={} config_up={})",
                dhcp_wait_seconds,
                stack.is_link_up(),
                stack.is_config_up()
            );
        }
        Timer::after_secs(1).await;
        dhcp_wait_seconds += 1;
    };
    info!("IP Address: {}", config.address);

    info!("WiFi client ready");

    // Store stack reference and emit ClientReady event
    stack_storage.init(stack);
    wifi_events.signal(WifiEvent::ClientReady);

    // Keep task alive (could monitor link status in future)
    loop {
        Timer::after_secs(3600).await;
    }
}

#[embassy_executor::task]
async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! {
    runner.run().await
}

// ============================================================================
// WiFi Tasks
// ============================================================================

macro_rules! impl_wifi_pio {
    ($pio:ident, $suffix:ident) => {
        paste::paste! {
            impl WifiPio for peripherals::$pio {
                fn spawn_wifi_task(
                    spawner: Spawner,
                    runner: cyw43::Runner<'static, cyw43::SpiBus<Output<'static>, PioSpi<'static, Self, 0>>>,
                ) {
                    let wifi_task_token = defmt::unwrap!([<wifi_task_ $suffix>](runner));
                    spawner.spawn(wifi_task_token);
                }

                fn spawn_device_loop(
                    spawner: Spawner,
                    pin_23: Peri<'static, PIN_23>,
                    pin_24: Peri<'static, PIN_24>,
                    pin_25: Peri<'static, PIN_25>,
                    pin_29: Peri<'static, PIN_29>,
                    pio: Peri<'static, Self>,
                    dma: DmaChannel<'static>,
                    mode: WifiMode,
                    captive_portal_ssid: &'static str,
                    wifi_events: &'static WifiEvents,
                    stack_storage: &'static StackStorage,
                ) {
                    let wifi_device_loop_token = defmt::unwrap!([<wifi_device_loop_ $suffix>](
                        pin_23,
                        pin_24,
                        pin_25,
                        pin_29,
                        pio,
                        dma,
                        mode,
                        captive_portal_ssid,
                        wifi_events,
                        stack_storage,
                        spawner,
                    ));
                    spawner.spawn(wifi_device_loop_token);
                }
            }

            #[embassy_executor::task]
            async fn [<wifi_device_loop_ $suffix>](
                pin_23: Peri<'static, PIN_23>,
                pin_24: Peri<'static, PIN_24>,
                pin_25: Peri<'static, PIN_25>,
                pin_29: Peri<'static, PIN_29>,
                pio: Peri<'static, peripherals::$pio>,
                dma: DmaChannel<'static>,
                mode: WifiMode,
                captive_portal_ssid: &'static str,
                wifi_events: &'static WifiEvents,
                stack_storage: &'static StackStorage,
                spawner: Spawner,
            ) -> ! {
                wifi_device_loop_impl::<peripherals::$pio>(
                    pin_23,
                    pin_24,
                    pin_25,
                    pin_29,
                    pio,
                    dma,
                    mode,
                    captive_portal_ssid,
                    wifi_events,
                    stack_storage,
                    spawner,
                )
                .await
            }

            #[embassy_executor::task]
            async fn [<wifi_task_ $suffix>](
                runner: cyw43::Runner<'static, cyw43::SpiBus<Output<'static>, PioSpi<'static, peripherals::$pio, 0>>>,
            ) -> ! {
                wifi_task_impl::<peripherals::$pio>(runner).await
            }
        }
    };
}

impl_wifi_pio!(PIO0, pio0);
impl_wifi_pio!(PIO1, pio1);
#[cfg(feature = "pico2")]
impl_wifi_pio!(PIO2, pio2);