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
//! A device abstraction that connects a Pico with WiFi to the Internet and, when needed,
//! creates a temporary WiFi network to enter credentials.
//!
//! See [`WifiAutoRp`] for the main struct and usage examples.

#![allow(clippy::future_not_send, reason = "single-threaded")]

use core::convert::Infallible;
use core::{cell::RefCell, future::Future};
use cortex_m::peripheral::SCB;
use defmt::{info, warn};
use embassy_executor::Spawner;
use embassy_net::Ipv4Address;
use embassy_rp::{
    Peri,
    dma::ChannelInstance,
    peripherals::{PIN_23, PIN_24, PIN_25, PIN_29},
};
use embassy_sync::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
use embassy_time::{Duration, Instant, Timer, with_timeout};
use heapless::Vec;
use portable_atomic::{AtomicBool, Ordering};
use static_cell::StaticCell;

use crate::flash_block::FlashBlockRp;
use crate::{Error, Result};
use device_envoy_core::button::Button;
use device_envoy_core::wifi_auto::{WifiCredentials as InnerWifiCredentials, WifiStartMode};

mod dhcp;
mod dns;
pub mod fields;
mod portal;
mod stack;

use dns::dns_server_task;
use stack::WifiStatic as InnerWifiStatic;

pub use stack::WifiPio;
pub(crate) use stack::{Wifi, WifiEvent};

pub use device_envoy_core::wifi_auto::WifiAuto;
pub use device_envoy_core::wifi_auto::WifiAutoEvent;
pub use device_envoy_core::wifi_auto::WifiAutoField;
pub use device_envoy_core::wifi_auto::WifiStack;

const MAX_CONNECT_ATTEMPTS: u8 = 4;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(40);
const RETRY_BASE_DELAY: Duration = Duration::from_secs(3);
const RETRY_JITTER_MAX: Duration = Duration::from_millis(500);

const MAX_WIFI_AUTO_FIELDS: usize = 8;

/// Static for [`WifiAutoRp`]. See [`WifiAutoRp`] for usage example.
pub(crate) struct WifiAutoStatic {
    wifi: InnerWifiStatic,
    wifi_auto_cell: StaticCell<WifiAutoInner>,
    force_captive_portal: AtomicBool,
    defaults: Mutex<CriticalSectionRawMutex, RefCell<Option<InnerWifiCredentials>>>,
    fields_storage: StaticCell<
        Vec<&'static (dyn WifiAutoField<Error = crate::Error> + Sync), MAX_WIFI_AUTO_FIELDS>,
    >,
}
/// A device abstraction that connects a Pico with WiFi to the Internet and, when needed,
/// creates a temporary WiFi network to enter credentials.
///
/// `WifiAutoRp` handles WiFi connections end-to-end. It normally connects using
/// a saved WiFi network name (SSID) and password. If those values are missing
/// or invalid, it temporarily creates its own WiFi network (a “captive
/// portal”) and hosts a web form where the user can enter the local WiFi
/// ssid and password.
///
/// `WifiAutoRp` works on the Pico 1 W and Pico 2 W, which include the CYW43 WiFi chip.
///
/// The typical usage pattern is:
///
/// 1. Ensure your hardware includes a button wired to a GPIO. The button can be used during boot to force captive-portal mode.
/// 2. Construct a [`ButtonWatch`](macro@crate::button::button_watch) to control the physical button.
/// 3. Construct a [`FlashBlockRp`] to store WiFi credentials.
/// 4. Use [`WifiAutoRp::new`] to construct a `WifiAutoRp`.
/// 5. Use [`WifiAuto::connect`] to connect to WiFi while optionally showing status.
///
/// Let’s look at an example. Following the example, we’ll explain the details.
/// (For additional examples, see the [wifi_auto::fields module example](crate::wifi_auto::fields)
/// and the [`WifiAuto::connect`] docs.)
///
/// ## Example: Connect with logging
///
/// This example connects to WiFi and logs progress.
///
/// ```rust,no_run
/// # #![no_std]
/// # #![no_main]
/// # use panic_probe as _;
/// # use defmt::info;
/// use device_envoy_rp::{
///     Result,
///     button::PressedTo,
///     button_watch,
///     flash_block::FlashBlockRp,
///     wifi_auto::{WifiAuto as _, WifiAutoEvent, WifiAutoRp},
/// };
/// use embassy_time::Duration;
///
/// button_watch! {
///     ButtonWatch13 {
///         pin: PIN_13,
///     }
/// }
///
/// async fn connect_wifi(
///     spawner: embassy_executor::Spawner,
///     p: embassy_rp::Peripherals,
/// ) -> Result<()> {
///     // Set up ButtonWatch to control the physical button.
///     let button_watch13 = ButtonWatch13::new(p.PIN_13, PressedTo::Ground, spawner).await?;
///
///     // Set up flash storage for WiFi credentials.
///     let [wifi_flash] = FlashBlockRp::new_array::<1>(p.FLASH)?;
///
///     // Construct WifiAutoRp
///     let wifi_auto = WifiAutoRp::new(
///         p.PIN_23,          // CYW43 power
///         p.PIN_24,  // CYW43 data
///         p.PIN_25,          // CYW43 chip select
///         p.PIN_29,  // CYW43 clock
///         p.PIO0,            // WiFi PIO
///         p.DMA_CH0,         // WiFi DMA
///         wifi_flash,
///         "DeviceEnvoySetup", // Captive-portal SSID
///         [],                // Any extra fields
///         spawner,
///     )?;
///
///     // Connect (logging status as we go)
///     let stack = wifi_auto
///         .connect(&mut *button_watch13, |event| async move {
///             match event {
///                 WifiAutoEvent::CaptivePortalReady =>
///                     info!("Captive portal ready"),
///                 WifiAutoEvent::Connecting { .. } =>
///                     info!("Connecting to WiFi"),
///                 WifiAutoEvent::ConnectionFailed =>
///                     info!("WiFi connection failed"),
///             }
///             Ok(())
///         })
///         .await?;
///
///     info!("WiFi connected");
///
///     loop {
///         if let Ok(addresses) = stack.dns_query("google.com", embassy_net::dns::DnsQueryType::A).await {
///             info!("google.com: {:?}", addresses);
///         } else {
///             info!("google.com: lookup failed");
///         }
///         embassy_time::Timer::after(Duration::from_secs(15)).await;
///     }
/// }
/// ```
///
/// ## What happens during connection
///
/// While `connect` is running:
///
/// - The WiFi chip may reset as it switches between normal WiFi operation and
///   hosting its own temporary WiFi network.
/// - Your code should tolerate these resets.
///   Initializing LEDs or displays before WiFi is fine; just be aware they may be
///   momentarily disrupted during mode changes.
///
/// ## WiFi limitations
///
/// - Only standard SSID/password 2.4 GHz WiFi networks are supported.
///
/// ## Hardware model
///
/// On the Pico W, the CYW43 WiFi chip is wired to fixed GPIOs.
pub struct WifiAutoRp {
    wifi_auto: &'static WifiAutoInner,
}

struct WifiAutoInner {
    wifi: &'static Wifi,
    spawner: Spawner,
    force_captive_portal: &'static AtomicBool,
    defaults: &'static Mutex<CriticalSectionRawMutex, RefCell<Option<InnerWifiCredentials>>>,
    fields: &'static [&'static (dyn WifiAutoField<Error = crate::Error> + Sync)],
}

impl WifiAutoStatic {
    #[must_use]
    pub const fn new() -> Self {
        WifiAutoStatic {
            wifi: Wifi::new_static(),
            wifi_auto_cell: StaticCell::new(),
            force_captive_portal: AtomicBool::new(false),
            defaults: Mutex::new(RefCell::new(None)),
            fields_storage: StaticCell::new(),
        }
    }

    fn force_captive_portal_flag(&'static self) -> &'static AtomicBool {
        &self.force_captive_portal
    }

    fn defaults(
        &'static self,
    ) -> &'static Mutex<CriticalSectionRawMutex, RefCell<Option<InnerWifiCredentials>>> {
        &self.defaults
    }
}

impl WifiAutoRp {
    /// Initialize WiFi auto-provisioning with custom configuration fields.
    ///
    /// # Parameters
    ///
    /// - `pin_23`, `pin_24`, `pin_25`, `pin_29`: CYW43 power, data, chip-select, and clock pins.
    /// - `pio`: PIO resource used for WiFi.
    /// - `dma`: DMA resource for WiFi.
    /// - `wifi_credentials_flash_block`: a flash block implementing
    ///   [`FlashBlock`](crate::flash_block::FlashBlock) for WiFi credentials.
    /// - `captive_portal_ssid`: SSID shown when the device starts setup mode.
    /// - `custom_fields`: Extra fields collected in the setup page. See the
    ///   [wifi_auto::fields module example](crate::wifi_auto::fields) for usage.
    /// - `spawner`: Embassy task spawner for background work.
    ///
    /// See the [WifiAutoRp struct example](Self) for a complete example.
    #[allow(clippy::too_many_arguments)]
    pub fn new<const N: usize, PIO: WifiPio, DMA: ChannelInstance, FlashBlockType>(
        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>,
        wifi_credentials_flash_block: FlashBlockType,
        captive_portal_ssid: &'static str,
        custom_fields: [&'static (dyn WifiAutoField<Error = crate::Error> + Sync); N],
        spawner: Spawner,
    ) -> Result<Self>
    where
        FlashBlockType: crate::flash_block::FlashBlock<Error = Error> + Into<FlashBlockRp>,
        crate::pio_irqs::DmaAllIrqs: embassy_rp::interrupt::typelevel::Binding<
                DMA::Interrupt,
                embassy_rp::dma::InterruptHandler<DMA>,
            >,
    {
        let mut wifi_credentials_flash_block = wifi_credentials_flash_block.into();
        static WIFI_AUTO_STATIC: WifiAutoStatic = WifiAutoInner::new_static();
        let wifi_auto_static = &WIFI_AUTO_STATIC;

        let stored_credentials = Wifi::peek_credentials(&mut wifi_credentials_flash_block);
        let stored_start_mode = Wifi::peek_start_mode(&mut wifi_credentials_flash_block);
        if matches!(stored_start_mode, WifiStartMode::CaptivePortal) {
            if let Some(credentials) = stored_credentials.clone() {
                wifi_auto_static.defaults.lock(|cell| {
                    *cell.borrow_mut() = Some(credentials);
                });
            }
        }

        // Check if custom fields are satisfied
        let extras_ready = custom_fields
            .iter()
            .all(|field| field.is_satisfied().unwrap_or(false));

        if !extras_ready {
            if let Some(credentials) = stored_credentials.clone() {
                wifi_auto_static.defaults.lock(|cell| {
                    *cell.borrow_mut() = Some(credentials);
                });
            }
            Wifi::prepare_start_mode(
                &mut wifi_credentials_flash_block,
                WifiStartMode::CaptivePortal,
            )
            .map_err(|_| Error::StorageCorrupted)?;
        }

        let wifi = Wifi::new_with_captive_portal_ssid(
            &wifi_auto_static.wifi,
            pin_23,
            pin_24,
            pin_25,
            pin_29,
            pio,
            dma,
            wifi_credentials_flash_block,
            captive_portal_ssid,
            spawner,
        );

        // Store fields array and convert to slice
        let fields_ref: &'static [&'static (dyn WifiAutoField<Error = crate::Error> + Sync)] =
            if N > 0 {
                assert!(
                    N <= MAX_WIFI_AUTO_FIELDS,
                    "WifiAutoRp supports at most {} custom fields",
                    MAX_WIFI_AUTO_FIELDS
                );
                let mut storage: Vec<
                    &'static (dyn WifiAutoField<Error = crate::Error> + Sync),
                    MAX_WIFI_AUTO_FIELDS,
                > = Vec::new();
                for field in custom_fields {
                    storage.push(field).unwrap_or_else(|_| unreachable!());
                }
                let stored_vec = wifi_auto_static.fields_storage.init(storage);
                stored_vec.as_slice()
            } else {
                &[]
            };

        let instance = wifi_auto_static.wifi_auto_cell.init(WifiAutoInner {
            wifi,
            spawner,
            force_captive_portal: wifi_auto_static.force_captive_portal_flag(),
            defaults: wifi_auto_static.defaults(),
            fields: fields_ref,
        });

        Ok(Self {
            wifi_auto: instance,
        })
    }

    /// Connect to Wi-Fi using a caller-provided button reference.
    pub async fn connect<OnEvent, OnEventFuture>(
        self,
        button: &mut impl Button,
        on_event: OnEvent,
    ) -> Result<WifiStack>
    where
        OnEvent: FnMut(WifiAutoEvent) -> OnEventFuture,
        OnEventFuture: Future<Output = Result<()>>,
    {
        <Self as WifiAuto>::connect(self, button, on_event).await
    }
}

impl device_envoy_core::wifi_auto::WifiAuto for WifiAutoRp {
    type Error = Error;

    /// Connects to WiFi (if possible), reports status, and returns the
    /// network stack, consuming the `WifiAutoRp`.
    ///
    /// See the [WifiAutoRp struct example](Self) for a usage example.
    ///
    /// This method does not return until WiFi is connected. It may briefly
    /// restart the Pico while switching between normal WiFi operation
    /// and hosting its temporary setup network.
    ///
    /// This `connect` method reports progress by calling a user-provided async
    /// handler whenever the WiFi state changes.
    /// The handler receives a [`WifiAutoEvent`].
    /// The handler is called sequentially for each event and may `await`.
    ///
    /// The three events are:
    /// - `CaptivePortalReady`: The device is hosting a captive portal and waiting for user input.
    /// - `Connecting`: The device is attempting to connect to the WiFi network.
    /// - `ConnectionFailed`: All connection attempts failed. The device
    ///   will reset and re-enter setup mode (for example, if the password
    ///   is incorrect).
    ///
    /// The first example uses a handler that does nothing.
    /// The second example shows how to use an LED panel to display status messages.
    /// The example on the [`WifiAutoRp`] struct shows simple logging.
    ///
    /// # Example 1: No-op event handler
    /// ```rust,no_run
    /// # // Based on a wifi_auto example.
    /// # #![no_std]
    /// # #![no_main]
    /// # use panic_probe as _;
    /// # use device_envoy_rp::{
    /// #     Result,
    /// #     button::PressedTo,
    /// #     button_watch,
    /// #     flash_block::FlashBlockRp,
    /// #     wifi_auto::{WifiAuto as _, WifiAutoRp},
    /// # };
    /// # use embassy_executor::Spawner;
    /// # use embassy_rp::Peripherals;
    /// # button_watch! {
    /// #     ButtonWatch13 {
    /// #         pin: PIN_13,
    /// #     }
    /// # }
    /// # async fn example(spawner: Spawner, p: Peripherals) -> Result<()> {
    /// # let [wifi_flash] = FlashBlockRp::new_array::<1>(p.FLASH)?;
    /// # let button_watch13 = ButtonWatch13::new(p.PIN_13, PressedTo::Ground, spawner).await?;
    /// # let wifi_auto = WifiAutoRp::new(
    /// #     p.PIN_23,
    /// #     p.PIN_24,
    /// #     p.PIN_25,
    /// #     p.PIN_29,
    /// #     p.PIO0,
    /// #     p.DMA_CH0,
    /// #     wifi_flash,
    /// #     "DeviceEnvoySetup",
    /// #     [],
    /// #     spawner,
    /// # )?;
    /// let _stack = wifi_auto
    ///     .connect(&mut *button_watch13, |_event| async move { Ok(()) })
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Example 2: Using a display to show status
    /// ```rust,no_run
    /// # // Based on demos/f_wifi_auto/f1_dns.rs.
    /// # #![no_std]
    /// # #![no_main]
    /// # use panic_probe as _;
    /// # use device_envoy_rp::{
    /// #     Result,
    /// #     button::PressedTo,
    /// #     button_watch,
    /// #     flash_block::FlashBlockRp,
    /// #     led_strip::colors,
    /// #     wifi_auto::{WifiAuto as _, WifiAutoEvent, WifiAutoRp},
    /// # };
    /// # use smart_leds::RGB8;
    /// # use embassy_executor::Spawner;
    /// # use embassy_rp::Peripherals;
    /// # button_watch! {
    /// #     ButtonWatch13 {
    /// #         pin: PIN_13,
    /// #     }
    /// # }
    /// # struct Led8x12;
    /// # impl Led8x12 {
    /// #     async fn write_text(&self, _text: &str, _colors: &[RGB8]) -> Result<()> { Ok(()) }
    /// # }
    /// # async fn show_animated_dots(_led8x12: &Led8x12) -> Result<()> { Ok(()) }
    /// # const COLORS: &[RGB8] = &[colors::WHITE];
    /// # async fn example(spawner: Spawner, p: Peripherals) -> Result<()> {
    /// # let [wifi_flash] = FlashBlockRp::new_array::<1>(p.FLASH)?;
    /// # let button_watch13 = ButtonWatch13::new(p.PIN_13, PressedTo::Ground, spawner).await?;
    /// # let wifi_auto = WifiAutoRp::new(
    /// #     p.PIN_23,
    /// #     p.PIN_24,
    /// #     p.PIN_25,
    /// #     p.PIN_29,
    /// #     p.PIO0,
    /// #     p.DMA_CH0,
    /// #     wifi_flash,
    /// #     "DeviceEnvoySetup",
    /// #     [],
    /// #     spawner,
    /// # )?;
    /// # let led8x12 = Led8x12;
    /// // Keep a reference so the handler can reuse the display across events.
    /// let led8x12_ref = &led8x12;
    /// let stack = wifi_auto
    ///     .connect(&mut *button_watch13, |event| async move {
    ///         match event {
    ///             WifiAutoEvent::CaptivePortalReady => {
    ///                 led8x12_ref.write_text("JO\nIN", COLORS);
    ///             }
    ///             WifiAutoEvent::Connecting { .. } => {
    ///                 show_animated_dots(led8x12_ref).await?;
    ///             }
    ///             WifiAutoEvent::ConnectionFailed => {
    ///                 led8x12_ref.write_text("FA\nIL", COLORS);
    ///             }
    ///         }
    ///         Ok(())
    ///     })
    ///     .await?;
    /// # let _stack = stack;
    /// # Ok(())
    /// # }
    /// ```
    async fn connect<OnEvent, OnEventFuture>(
        self,
        button: &mut impl Button,
        on_event: OnEvent,
    ) -> Result<WifiStack>
    where
        OnEvent: FnMut(WifiAutoEvent) -> OnEventFuture,
        OnEventFuture: Future<Output = Result<()>>,
    {
        let button_reset_stabilize_cycles: u32 = 300_000;
        cortex_m::asm::delay(button_reset_stabilize_cycles);
        if button.is_pressed() {
            if self.wifi_auto.wifi.current_start_mode() != WifiStartMode::CaptivePortal {
                info!("WifiAutoRp: force-captive-portal requested via button");
                self.wifi_auto
                    .wifi
                    .set_start_mode(WifiStartMode::CaptivePortal)
                    .map_err(|_| Error::StorageCorrupted)?;
                // RP WiFi runtime mode is selected on boot. Reboot so AP mode actually applies.
                info!("WifiAutoRp: rebooting now to apply CaptivePortal startup mode");
                SCB::sys_reset();
            } else {
                info!("WifiAutoRp: force request ignored (already in CaptivePortal mode)");
                self.wifi_auto.force_captive_portal();
            }
        }
        self.wifi_auto.connect(on_event).await
    }
}

impl WifiAutoInner {
    #[must_use]
    const fn new_static() -> WifiAutoStatic {
        WifiAutoStatic::new()
    }

    fn force_captive_portal(&self) {
        self.force_captive_portal.store(true, Ordering::Relaxed);
    }

    fn extra_fields_ready(&self) -> Result<bool> {
        for field in self.fields {
            let satisfied = field.is_satisfied().map_err(|_| Error::StorageCorrupted)?;
            if !satisfied {
                info!("WifiAutoRp: custom field not satisfied, forcing captive portal");
                return Ok(false);
            }
        }
        info!(
            "WifiAutoRp: all {} custom fields satisfied",
            self.fields.len()
        );
        Ok(true)
    }

    device_envoy_core::__impl_wifi_auto_connect! {
    fn connect(&self as wifi_auto_inner, on_event) -> Result<WifiStack> {
        wifi_auto_inner.ensure_connected_with(&mut on_event).await?;
        Ok(wifi_auto_inner.wifi.wait_for_stack().await)
    }
    }

    async fn ensure_connected_with<Fut, F>(&self, on_event: &mut F) -> Result<()>
    where
        F: FnMut(WifiAutoEvent) -> Fut,
        Fut: Future<Output = Result<()>>,
    {
        loop {
            let force_captive_portal = self.force_captive_portal.swap(false, Ordering::AcqRel);
            let start_mode = self.wifi.current_start_mode();
            let persisted_wifi_credentials = self.wifi.load_persisted_credentials();
            let has_credentials = persisted_wifi_credentials.is_some();
            let extras_ready = self.extra_fields_ready()?;
            let enter_captive_portal = device_envoy_core::wifi_auto::should_enter_captive_portal(
                start_mode,
                force_captive_portal,
                has_credentials,
                extras_ready,
            );
            info!(
                "WifiAutoRp: force={} has_credentials={} extras_ready={} enter_captive_portal={}",
                force_captive_portal, has_credentials, extras_ready, enter_captive_portal
            );

            struct RpWifiAutoBackend<'a> {
                wifi_auto_inner: &'a WifiAutoInner,
                force_captive_portal: bool,
            }
            impl device_envoy_core::wifi_auto::WifiAutoBackend for RpWifiAutoBackend<'_> {
                type Error = Error;

                fn force_captive_portal(&self) -> bool {
                    self.force_captive_portal
                }

                fn try_count(&self) -> u8 {
                    MAX_CONNECT_ATTEMPTS
                }

                fn load_start_mode(&self) -> Result<WifiStartMode> {
                    Ok(self.wifi_auto_inner.wifi.current_start_mode())
                }

                fn custom_fields_satisfied(&self) -> Result<bool> {
                    self.wifi_auto_inner.extra_fields_ready()
                }

                fn load_persisted_credentials(&self) -> Result<Option<InnerWifiCredentials>> {
                    Ok(self.wifi_auto_inner.wifi.load_persisted_credentials())
                }

                fn persist_credentials(
                    &self,
                    wifi_credentials: &InnerWifiCredentials,
                ) -> Result<()> {
                    self.wifi_auto_inner
                        .wifi
                        .persist_credentials(wifi_credentials)
                        .map_err(|_| Error::StorageCorrupted)
                }

                fn set_start_mode(&self, wifi_start_mode: WifiStartMode) -> Result<()> {
                    self.wifi_auto_inner
                        .wifi
                        .set_start_mode(wifi_start_mode)
                        .map_err(|_| Error::StorageCorrupted)
                }

                fn on_connect_attempt(
                    &mut self,
                    try_index: u8,
                ) -> impl Future<Output = Result<bool>> + '_ {
                    async move {
                        let attempt = try_index + 1;
                        info!(
                            "WifiAutoRp: connection attempt {}/{}",
                            attempt, MAX_CONNECT_ATTEMPTS
                        );
                        if self
                            .wifi_auto_inner
                            .wait_for_client_ready_with_timeout(CONNECT_TIMEOUT)
                            .await
                        {
                            return Ok(true);
                        }
                        warn!("WifiAutoRp: connection attempt {} timed out", attempt);
                        let retry_delay = retry_delay_with_jitter(try_index);
                        info!(
                            "WifiAutoRp: retrying after {} ms (attempt {})",
                            retry_delay.as_millis(),
                            attempt
                        );
                        Timer::after(retry_delay).await;
                        Ok(false)
                    }
                }

                fn run_captive_portal(
                    &mut self,
                ) -> impl Future<Output = Result<InnerWifiCredentials>> + '_ {
                    async move {
                        match self.wifi_auto_inner.run_captive_portal().await {
                            Ok(infallible) => match infallible {},
                            Err(error) => Err(error),
                        }
                    }
                }

                fn on_resolved_credentials(
                    &mut self,
                    _wifi_credentials: &InnerWifiCredentials,
                ) -> impl Future<Output = Result<()>> + '_ {
                    async { Ok(()) }
                }
            }

            let mut wifi_auto_backend = RpWifiAutoBackend {
                wifi_auto_inner: self,
                force_captive_portal,
            };
            let connected = device_envoy_core::wifi_auto::connect_with_backend(
                &mut wifi_auto_backend,
                on_event,
            )
            .await?;
            if connected {
                return Ok(());
            }

            info!(
                "WifiAutoRp: failed to connect after {} attempts, returning to captive portal",
                MAX_CONNECT_ATTEMPTS
            );
            if let Some(credentials) = self.wifi.load_persisted_credentials() {
                self.defaults.lock(|cell| {
                    *cell.borrow_mut() = Some(credentials);
                });
            }
            info!("WifiAutoRp: writing CaptivePortal mode to flash");
            self.wifi
                .set_start_mode(WifiStartMode::CaptivePortal)
                .map_err(|_| Error::StorageCorrupted)?;
            info!("WifiAutoRp: flash write complete, waiting 1 second before reset");
            Timer::after_secs(1).await;
            info!("WifiAutoRp: resetting device now");
            SCB::sys_reset();
        }
    }

    async fn wait_for_client_ready_with_timeout(&self, timeout: Duration) -> bool {
        with_timeout(timeout, async {
            loop {
                match self.wifi.wait_for_wifi_event().await {
                    WifiEvent::ClientReady => break,
                    WifiEvent::CaptivePortalReady => {
                        info!(
                            "WifiAutoRp: received captive-portal-ready event while waiting for client mode"
                        );
                    }
                }
            }
        })
        .await
        .is_ok()
    }

    #[allow(unreachable_code)]
    async fn run_captive_portal(&self) -> Result<Infallible> {
        self.wifi.wait_for_wifi_event().await;
        let stack = self.wifi.wait_for_stack().await;

        let captive_portal_ip = Ipv4Address::new(192, 168, 4, 1);
        match dns_server_task(stack, captive_portal_ip) {
            Ok(dns_server_token) => self.spawner.spawn(dns_server_token),
            Err(err) => {
                info!("WifiAutoRp: DNS server task spawn failed: {:?}", err);
            }
        }

        let defaults_owned = self
            .defaults
            .lock(|cell| cell.borrow_mut().take())
            .or_else(|| self.wifi.load_persisted_credentials());
        let submission =
            portal::collect_credentials(stack, self.spawner, defaults_owned.as_ref(), self.fields)
                .await?;
        self.wifi.persist_credentials(&submission).map_err(|err| {
            warn!("{}", err);
            Error::StorageCorrupted
        })?;

        Timer::after_millis(750).await;
        SCB::sys_reset();
        loop {
            cortex_m::asm::nop();
        }
    }
}

fn retry_delay_with_jitter(attempt_index: u8) -> Duration {
    let base_ms = RETRY_BASE_DELAY.as_millis();
    assert!(base_ms > 0, "RETRY_BASE_DELAY must be positive");
    let jitter_max_ms = RETRY_JITTER_MAX.as_millis();
    let multiplier = 1u64
        .checked_shl(u32::from(attempt_index))
        .expect("attempt_index must fit in shift");
    let delay_ms = base_ms
        .checked_mul(multiplier)
        .expect("retry delay must fit in millis");
    let jitter_ms = if jitter_max_ms == 0 {
        0
    } else {
        Instant::now().as_millis() % (jitter_max_ms + 1)
    };
    let total_ms = delay_ms
        .checked_add(jitter_ms)
        .expect("retry delay with jitter must fit in millis");
    Duration::from_millis(total_ms)
}