esp_wifi/wifi/
state.rs

1use core::sync::atomic::Ordering;
2
3use portable_atomic_enum::atomic_enum;
4
5use super::WifiEvent;
6
7/// Wifi interface state
8#[atomic_enum]
9#[derive(PartialEq, Debug)]
10#[cfg_attr(feature = "defmt", derive(defmt::Format))]
11pub enum WifiState {
12    StaStarted,
13    StaConnected,
14    StaDisconnected,
15    StaStopped,
16
17    ApStarted,
18    ApStopped,
19
20    Invalid,
21}
22
23impl From<WifiEvent> for WifiState {
24    fn from(event: WifiEvent) -> WifiState {
25        match event {
26            WifiEvent::StaStart => WifiState::StaStarted,
27            WifiEvent::StaConnected => WifiState::StaConnected,
28            WifiEvent::StaDisconnected => WifiState::StaDisconnected,
29            WifiEvent::StaStop => WifiState::StaStopped,
30            WifiEvent::ApStart => WifiState::ApStarted,
31            WifiEvent::ApStop => WifiState::ApStopped,
32            _ => WifiState::Invalid,
33        }
34    }
35}
36
37pub(crate) static STA_STATE: AtomicWifiState = AtomicWifiState::new(WifiState::Invalid);
38pub(crate) static AP_STATE: AtomicWifiState = AtomicWifiState::new(WifiState::Invalid);
39
40/// Get the current state of the AP
41pub fn ap_state() -> WifiState {
42    AP_STATE.load(Ordering::Relaxed)
43}
44
45/// Get the current state of the STA
46pub fn sta_state() -> WifiState {
47    STA_STATE.load(Ordering::Relaxed)
48}
49
50pub(crate) fn update_state(event: WifiEvent, handled: bool) {
51    match event {
52        WifiEvent::StaConnected
53        | WifiEvent::StaDisconnected
54        | WifiEvent::StaStart
55        | WifiEvent::StaStop => STA_STATE.store(WifiState::from(event), Ordering::Relaxed),
56
57        WifiEvent::ApStart | WifiEvent::ApStop => {
58            AP_STATE.store(WifiState::from(event), Ordering::Relaxed)
59        }
60
61        other => {
62            if !handled {
63                debug!("Unhandled event: {:?}", other)
64            }
65        }
66    }
67}
68
69pub(crate) fn reset_ap_state() {
70    AP_STATE.store(WifiState::Invalid, Ordering::Relaxed)
71}
72
73pub(crate) fn reset_sta_state() {
74    STA_STATE.store(WifiState::Invalid, Ordering::Relaxed)
75}
76
77/// Returns the current state of the WiFi stack.
78///
79/// This does not support AP-STA mode. Use one of `sta_state` or
80/// `ap_state` instead.
81pub fn wifi_state() -> WifiState {
82    use super::WifiMode;
83    match WifiMode::current() {
84        Ok(WifiMode::Sta) => sta_state(),
85        Ok(WifiMode::Ap) => ap_state(),
86        _ => WifiState::Invalid,
87    }
88}