Skip to main content

m5stack_core/driver/radio/
wifi.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! WiFi sub-function of the shared radio.
3//!
4//! Layered, fully-async surface built on `esp-radio`:
5//!
6//! - **`wifi` feature** — [`Wifi`]: owns the `WifiController` and exposes
7//!   on-demand scanning ([`Wifi::scan`]). No IP stack, no `embassy-net`.
8//! - **`wifi-sta` feature** — [`Wifi::into_sta`]: consumes the handle and returns
9//!   a DHCP/static `embassy_net::Stack`, a [`WifiControl`] command handle, and a
10//!   [`WifiRunner`] you spawn via [`wifi_task`]. The runner owns the single
11//!   controller and manages association (auto-connect + reconnect), so scanning
12//!   while associated is routed through [`WifiControl::scan`] — there is never
13//!   more than one owner of the controller.
14//!
15//! - **`wifi-ap` feature** — [`Wifi::into_ap`]: brings the radio up as a soft-AP
16//!   and returns an [`ApRadio`] that reports stations joining and leaving. It
17//!   stops at the WiFi link on purpose — handing out addresses needs a DHCP
18//!   *server*, which `embassy-net` does not provide.
19//!
20//! ## Mode roadmap
21//!
22//! Station and access point are wired. ESP-NOW / sniffer / CSI are separate
23//! esp-radio features that layer on the same way. AP+STA at once
24//! (`Config::AccessPointStation`) is the one combination still missing, and it
25//! needs the [`wifi_task`] actor to own both halves rather than just the
26//! station.
27//!
28//! ## Variant differences (Fire27 / ESP32 vs CoreS3 / ESP32-S3)
29//!
30//! The esp-radio WiFi API is identical on both chips; the differences are RAM:
31//! - The RX/TX buffer counts in [`controller_config`] are trimmed on Fire27
32//!   (ESP32) where internal SRAM is tighter, and left at the esp-radio defaults
33//!   on CoreS3 (ESP32-S3).
34//! - **Fire27 cannot DMA out of PSRAM** — the application must keep the
35//!   `embassy_net::StackResources` and socket buffers in internal RAM. CoreS3 has
36//!   headroom and may place large app buffers in PSRAM (see [`crate::mem`]).
37//! - With BLE coexistence (`coex`), budget the extra controller heap (~96 KB
38//!   reclaimed on ESP32, less on S3).
39
40use esp_hal::peripherals::WIFI;
41use esp_radio::wifi::{ControllerConfig, WifiController, scan::ScanConfig};
42use thiserror_no_std::Error;
43
44pub use esp_radio::wifi::{
45    AuthenticationMethod, AuthenticationMethodConfig, Password,
46    ap::{ConnectedInfo, DisconnectedInfo, EventInfo},
47    scan::AccessPointInfo,
48};
49
50/// Scan results, capped at 16 access points.
51pub type ScanList = heapless::Vec<AccessPointInfo, 16>;
52
53/// Errors from the WiFi sub-system.
54#[derive(Debug, Error)]
55pub enum WifiError {
56    /// Error reported by the underlying esp-radio WiFi controller.
57    #[error("WiFi controller error")]
58    Controller(#[from] esp_radio::wifi::WifiError),
59    /// The station interface is a process-wide singleton and is already held.
60    #[error("WiFi station interface already taken")]
61    StationTaken,
62    /// The access-point interface is a process-wide singleton and is already held.
63    #[error("WiFi access point interface already taken")]
64    AccessPointTaken,
65}
66
67/// Low-level WiFi handle: owns the controller.
68///
69/// Create with [`Wifi::new`] for scan-only use, or call [`Wifi::into_sta`]
70/// (requires `wifi-sta`) to bring up a station with an `embassy_net::Stack`.
71pub struct Wifi {
72    controller: WifiController<'static>,
73}
74
75impl Wifi {
76    /// Create and start the WiFi controller with a chip-tuned configuration.
77    ///
78    /// `esp_rtos::start(..)` must already be running.
79    pub fn new(wifi: WIFI<'static>) -> Result<Self, WifiError> {
80        Ok(Self {
81            controller: WifiController::new(wifi, controller_config())?,
82        })
83    }
84
85    /// Run a default scan and return up to [`ScanList`]'s capacity of results.
86    pub async fn scan(&mut self) -> Result<ScanList, WifiError> {
87        self.scan_with(&ScanConfig::default()).await
88    }
89
90    /// Run a scan with an explicit [`ScanConfig`].
91    pub async fn scan_with(&mut self, config: &ScanConfig) -> Result<ScanList, WifiError> {
92        Ok(to_scan_list(self.controller.scan_async(config).await?))
93    }
94}
95
96/// Build the `ControllerConfig`, trimming buffers per chip.
97///
98/// Defaults are tuned for CoreS3 (ESP32-S3). Fire27 (ESP32) trims the dynamic RX
99/// buffer count to save internal SRAM — it stays well above `rx_ba_win` (6) so
100/// the controller's validation is satisfied.
101fn controller_config() -> ControllerConfig {
102    let config = ControllerConfig::default();
103    #[cfg(feature = "fire27")]
104    let config = config.with_dynamic_rx_buf_num(16);
105    config
106}
107
108/// Truncate the controller's scan `Vec` into a fixed-capacity [`ScanList`].
109fn to_scan_list(aps: impl IntoIterator<Item = AccessPointInfo>) -> ScanList {
110    let mut out = ScanList::new();
111    for ap in aps.into_iter().take(out.capacity()) {
112        // capacity-bounded by take(): push cannot fail.
113        let _ = out.push(ap);
114    }
115    out
116}
117
118#[cfg(feature = "wifi-ap")]
119pub use ap::*;
120
121/// Soft-AP mode: bring the radio up as an access point other stations join.
122///
123/// Deliberately smaller than [`sta`]: an AP that hands out addresses needs a
124/// DHCP *server*, which `embassy-net` does not provide, so this layer stops at
125/// the WiFi link. That is the useful half for a bring-up or a two-board test —
126/// association is what proves the radio, and an application that wants IP can
127/// add a static-addressed `embassy_net::Stack` over [`ApRadio::interface`].
128#[cfg(feature = "wifi-ap")]
129mod ap {
130    use super::*;
131    use esp_radio::wifi::{Config, Interface, ap::AccessPointConfig};
132
133    /// Access-point settings for [`Wifi::into_ap`].
134    pub struct ApSettings<'a> {
135        /// Network SSID to advertise (at most 32 bytes).
136        pub ssid: &'a str,
137        /// Authentication method, carrying the pre-shared key where one applies.
138        /// Soft-AP rejects WEP, so `Open` or a WPA2 variant.
139        pub auth: AuthenticationMethodConfig,
140        /// 2.4 GHz channel to beacon on.
141        pub channel: u8,
142    }
143
144    /// A running access point: owns the controller and the AP interface.
145    pub struct ApRadio {
146        controller: WifiController<'static>,
147        interface: Interface,
148    }
149
150    impl Wifi {
151        /// Configure soft-AP mode and start beaconing.
152        ///
153        /// `esp_rtos::start(..)` must already be running, as for any radio.
154        pub fn into_ap(self, settings: ApSettings<'_>) -> Result<ApRadio, WifiError> {
155            let Wifi { mut controller } = self;
156            // Singleton since esp-radio 1.0, same as the station side.
157            let interface = Interface::try_access_point().ok_or(WifiError::AccessPointTaken)?;
158
159            let ap = AccessPointConfig::default()
160                .with_ssid(settings.ssid.try_into()?)
161                .with_authentication(settings.auth)
162                .with_channel(settings.channel);
163            controller.set_config(&Config::AccessPoint(ap))?;
164
165            Ok(ApRadio {
166                controller,
167                interface,
168            })
169        }
170    }
171
172    impl ApRadio {
173        /// Wait for the next station connect/disconnect on this AP.
174        ///
175        /// Never completes on its own — an AP with no clients simply waits.
176        pub async fn next_event(&mut self) -> Result<EventInfo, WifiError> {
177            Ok(self
178                .controller
179                .wait_for_access_point_connected_event_async()
180                .await?)
181        }
182
183        /// This AP's own MAC, which is the BSSID stations will report.
184        pub fn mac_address(&self) -> [u8; 6] {
185            self.interface.mac_address()
186        }
187
188        /// The AP netif, for an application that wants to put an IP stack on it.
189        pub fn interface(&mut self) -> &mut Interface {
190            &mut self.interface
191        }
192    }
193}
194
195#[cfg(feature = "wifi-sta")]
196pub use sta::*;
197
198#[cfg(feature = "wifi-sta")]
199mod sta {
200    use super::*;
201    use embassy_futures::{
202        join::join,
203        select::{Either, select},
204    };
205    use embassy_sync::{
206        blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex, signal::Signal,
207    };
208    use embassy_time::{Duration, Timer};
209    use esp_radio::wifi::{Config, Interface, PowerSaveMode, sta::StationConfig};
210
211    /// Station credentials for [`Wifi::into_sta`].
212    pub struct StaCredentials<'a> {
213        /// Network SSID (at most 32 bytes).
214        pub ssid: &'a str,
215        /// Authentication method, carrying the pre-shared key where one
216        /// applies — esp-radio 1.0 pairs the two, so an `Open` network cannot
217        /// be given a password by mistake.
218        pub auth: AuthenticationMethodConfig,
219    }
220
221    /// How the station obtains its IPv4 configuration.
222    pub enum IpSetup {
223        /// Acquire an address via DHCP.
224        Dhcp,
225        /// Use a fixed address/gateway/DNS.
226        Static(embassy_net::StaticConfigV4),
227    }
228
229    enum Command {
230        Scan(ScanConfig),
231        Connect,
232        Disconnect,
233    }
234
235    // Carried through a single static `Signal`, which reserves the max size
236    // regardless; boxing the scan result would only add an allocation.
237    #[allow(clippy::large_enum_variant)]
238    enum Response {
239        Scan(Result<ScanList, WifiError>),
240        Unit(Result<(), WifiError>),
241    }
242
243    // The controller is a single, non-shareable resource owned by `wifi_task`.
244    // `WifiControl` talks to it over these signals; `CTRL_LOCK` keeps at most one
245    // command outstanding so a reply is never clobbered before it is read.
246    static CMD: Signal<CriticalSectionRawMutex, Command> = Signal::new();
247    static RESP: Signal<CriticalSectionRawMutex, Response> = Signal::new();
248    static CTRL_LOCK: Mutex<CriticalSectionRawMutex, ()> = Mutex::new(());
249
250    /// Cloneable-free command handle for the running station.
251    ///
252    /// Association is managed automatically by [`wifi_task`]; use this to scan
253    /// while associated, or to explicitly stop/start association.
254    pub struct WifiControl {
255        _private: (),
256    }
257
258    /// The owned controller + network runner. Hand to [`wifi_task`].
259    pub struct WifiRunner {
260        controller: WifiController<'static>,
261        net: embassy_net::Runner<'static, Interface>,
262        desired_up: bool,
263    }
264
265    impl Wifi {
266        /// Configure station mode and build the `embassy_net` stack.
267        ///
268        /// `seed` should come from the application's TRNG (the BSP deliberately
269        /// does not claim `RNG`). `resources` is typically a
270        /// `static_cell`-allocated `StackResources<N>`. On Fire27 keep it (and
271        /// socket buffers) in internal RAM — that chip cannot DMA from PSRAM.
272        ///
273        /// Returns the `Stack` (await `stack.wait_config_up()` for an IP), the
274        /// [`WifiControl`] handle, and the [`WifiRunner`] to spawn.
275        pub fn into_sta<const N: usize>(
276            self,
277            creds: StaCredentials<'_>,
278            ip: IpSetup,
279            seed: u64,
280            resources: &'static mut embassy_net::StackResources<N>,
281        ) -> Result<(embassy_net::Stack<'static>, WifiControl, WifiRunner), WifiError> {
282            let Wifi { mut controller } = self;
283            // A singleton since esp-radio 1.0: claim it here rather than in
284            // `Wifi::new`, so a scan-only build never holds it.
285            let device = Interface::try_station().ok_or(WifiError::StationTaken)?;
286
287            let station = StationConfig::default()
288                .with_ssid(creds.ssid.try_into()?)
289                .with_authentication(creds.auth);
290            controller.set_config(&Config::Station(station))?;
291            // Favor responsiveness over the blob's default power-save heuristics.
292            controller.set_power_saving(PowerSaveMode::None)?;
293
294            let net_config = match ip {
295                IpSetup::Dhcp => embassy_net::Config::dhcpv4(Default::default()),
296                IpSetup::Static(cfg) => embassy_net::Config::ipv4_static(cfg),
297            };
298            let (stack, net) = embassy_net::new(device, net_config, resources, seed);
299
300            Ok((
301                stack,
302                WifiControl { _private: () },
303                WifiRunner {
304                    controller,
305                    net,
306                    desired_up: true,
307                },
308            ))
309        }
310    }
311
312    impl WifiControl {
313        /// Scan with default settings while the station keeps running.
314        pub async fn scan(&self) -> Result<ScanList, WifiError> {
315            self.scan_with(ScanConfig::default()).await
316        }
317
318        /// Scan with an explicit [`ScanConfig`].
319        pub async fn scan_with(&self, config: ScanConfig) -> Result<ScanList, WifiError> {
320            let _guard = CTRL_LOCK.lock().await;
321            CMD.signal(Command::Scan(config));
322            match RESP.wait().await {
323                Response::Scan(result) => result,
324                Response::Unit(_) => unreachable!("scan command yields a scan response"),
325            }
326        }
327
328        /// Request (re)association to the configured AP.
329        pub async fn connect(&self) -> Result<(), WifiError> {
330            self.unit_command(Command::Connect).await
331        }
332
333        /// Disconnect and stop auto-reconnect until [`WifiControl::connect`].
334        pub async fn disconnect(&self) -> Result<(), WifiError> {
335            self.unit_command(Command::Disconnect).await
336        }
337
338        async fn unit_command(&self, command: Command) -> Result<(), WifiError> {
339            let _guard = CTRL_LOCK.lock().await;
340            CMD.signal(command);
341            match RESP.wait().await {
342                Response::Unit(result) => result,
343                Response::Scan(_) => unreachable!("unit command yields a unit response"),
344            }
345        }
346    }
347
348    /// Drive the network stack and manage station association.
349    ///
350    /// Joins the `embassy_net` runner with the controller actor; neither future
351    /// returns, so this task runs for the lifetime of the program.
352    #[embassy_executor::task]
353    pub async fn wifi_task(runner: WifiRunner) {
354        let WifiRunner {
355            mut controller,
356            mut net,
357            mut desired_up,
358        } = runner;
359        join(net.run(), run_actor(&mut controller, &mut desired_up)).await;
360    }
361
362    /// Single owner of the controller: auto-connects, reconnects on link loss,
363    /// and services [`WifiControl`] commands. Races association progress against
364    /// incoming commands so a scan/disconnect is handled promptly.
365    async fn run_actor(controller: &mut WifiController<'static>, desired_up: &mut bool) {
366        loop {
367            if *desired_up && !controller.is_connected() {
368                let outcome = {
369                    let connect = controller.connect_async();
370                    select(connect, CMD.wait()).await
371                };
372                match outcome {
373                    // Say so: the failure path below warns, so without this a
374                    // successful association is the one outcome that leaves no
375                    // trace — and it is the one a bring-up test wants to assert.
376                    Either::First(Ok(info)) => info!("WiFi associated: {:?}", info),
377                    Either::First(Err(error)) => {
378                        warn!("WiFi connect failed: {:?}", error);
379                        // Back off, but still service commands during the wait.
380                        let backoff =
381                            select(Timer::after(Duration::from_secs(2)), CMD.wait()).await;
382                        if let Either::Second(command) = backoff {
383                            handle(controller, desired_up, command).await;
384                        }
385                    }
386                    Either::Second(command) => handle(controller, desired_up, command).await,
387                }
388            } else if *desired_up {
389                let outcome = {
390                    let disconnect = controller.wait_for_disconnect_async();
391                    select(disconnect, CMD.wait()).await
392                };
393                if let Either::Second(command) = outcome {
394                    handle(controller, desired_up, command).await;
395                }
396                // Either::First => link lost; loop reconnects.
397            } else {
398                let command = CMD.wait().await;
399                handle(controller, desired_up, command).await;
400            }
401        }
402    }
403
404    async fn handle(
405        controller: &mut WifiController<'static>,
406        desired_up: &mut bool,
407        command: Command,
408    ) {
409        match command {
410            Command::Scan(config) => {
411                let result = controller
412                    .scan_async(&config)
413                    .await
414                    .map(to_scan_list)
415                    .map_err(WifiError::from);
416                RESP.signal(Response::Scan(result));
417            }
418            Command::Connect => {
419                *desired_up = true;
420                RESP.signal(Response::Unit(Ok(())));
421            }
422            Command::Disconnect => {
423                *desired_up = false;
424                let result = controller
425                    .disconnect_async()
426                    .await
427                    .map(|_| ())
428                    .map_err(WifiError::from);
429                RESP.signal(Response::Unit(result));
430            }
431        }
432    }
433}