Skip to main content

WifiController

Struct WifiController 

pub struct WifiController<'d> { /* private fields */ }
Expand description

Wi-Fi controller.

When the controller is dropped, the Wi-Fi driver is deinitialized and Wi-Fi is stopped unless an ESP-NOW or sniffer instance created from it is still alive. In that case, Wi-Fi keeps running until that instance is dropped too.

Implementations§

§

impl<'d> WifiController<'d>

pub fn new( device: WIFI<'d>, config: ControllerConfig, ) -> Result<WifiController<'d>, WifiError>

Create a Wi-Fi controller. The default initial configuration is [Config::Station]([StationConfig::default()]).

Dropping the controller deinitializes Wi-Fi unless an ESP-NOW or sniffer instance created from it is still alive.

Create [Interface]s separately via [Interface::station()] / [Interface::access_point()].

Make sure to not call this function while interrupts are disabled, or IEEE 802.15.4 is currently in use.

§Example
let controller = esp_radio::wifi::WifiController::new(peripherals.WIFI, Default::default())?;
let sta = esp_radio::wifi::Interface::station();
§

impl WifiController<'_>

pub fn set_protocols(&mut self, protocols: Protocols) -> Result<(), WifiError>

Set the Wi-Fi protocol.

This will set the desired protocols.

§Arguments:
  • protocols - The desired protocols
§Example:
use esp_radio::wifi::Protocols;

let controller_config = ControllerConfig::default().with_initial_config(Config::AccessPoint(
    AccessPointConfig::default().with_ssid("esp-radio".try_into()?),
));
let mut wifi_controller =
    esp_radio::wifi::WifiController::new(peripherals.WIFI, controller_config)?;

wifi_controller.set_protocols(Protocols::default());
§Note

Calling this function before set_config will return an error.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn set_power_saving(&mut self, ps: PowerSaveMode) -> Result<(), WifiError>

Configures modem power saving.

§Example
let mut controller =
    esp_radio::wifi::WifiController::new(peripherals.WIFI, Default::default())?;
controller.set_power_saving(PowerSaveMode::Maximum)?;
§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn rssi(&self) -> Result<i32, WifiError>

Get the RSSI information of access point to which the device is associated with. The value is obtained from the last beacon.

  • Use this API only in Station or AccessPoint-Station mode.
  • This API should be called after the station has connected to an access point.
§Example
// Assume the station has already been started and connected
match controller.rssi() {
    Ok(rssi) => {
        println!("RSSI: {} dBm", rssi);
    }
    Err(e) => {
        println!("Failed to get RSSI: {e:?}");
    }
}
§Errors

This function returns [WifiError::Unsupported] if the Station side isn’t running. For example, when configured for access point only.

pub fn ap_info(&self) -> Result<AccessPointInfo, WifiError>

Get the Access Point information of access point to which the device is associated with. The value is obtained from the last beacon.

  • Use this API only in Station or AccessPoint-Station mode.
  • This API should be called after the station has connected to an access point.
§Example
// Assume the station has already been started and connected
match controller.ap_info() {
    Ok(info) => {
        println!("BSSID: {}", info.bssid);
    }
    Err(e) => {
        println!("Failed to get AP info: {e:?}");
    }
}
§Errors

This function returns [WifiError::Unsupported] if the Station side isn’t running. For example, when configured for access point only.

pub fn set_config(&mut self, conf: &Config) -> Result<(), WifiError>

Set the configuration and (re)start the controller as needed.

This will set the mode accordingly. You need to use Self::connect_async for connecting to an access point.

If you don’t intend to use Wi-Fi anymore at all consider tearing down Wi-Fi completely.

§Errors

If this function returns an error, the Wi-Fi mode is reset to NULL and the controller is stopped.

§Example
let station_config = Config::Station(
    StationConfig::default()
        .with_ssid("SSID".try_into()?)
        .with_authentication(AuthenticationMethodConfig::Wpa2Personal(
            "PASSWORD".try_into()?,
        )),
);

controller.set_config(&station_config)?;

pub fn set_band_mode(&mut self, band_mode: BandMode) -> Result<(), WifiError>

Set Wi-Fi band mode.

When the Wi-Fi band mode is set to [BandMode::_2_4G], it operates exclusively on the 2.4GHz channels. The controller needs to be configured and started before setting the band mode.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn set_bandwidths( &mut self, bandwidths: Bandwidths, ) -> Result<(), WifiError>

Sets the Wi-Fi channel bandwidth for the currently active interface(s).

If the device is operating in station mode, the bandwidth is applied to the Station interface. If operating in access point mode, it is applied to the Access Point interface. In Station+Access Point mode, the bandwidth is set for both interfaces.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn bandwidths(&self) -> Result<Bandwidths, WifiError>

Returns the Wi-Fi channel bandwidth of the active interface.

If the device is operating in station mode, the bandwidth of the Station interface is returned. If operating in access point mode, the bandwidth of the Access Point interface is returned. In Station+Access Point mode, the bandwidth of the Access Point interface is returned.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn channel(&self) -> Result<(u8, SecondaryChannel), WifiError>

Returns the current Wi-Fi channel configuration.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn set_channel( &mut self, primary: u8, secondary: SecondaryChannel, ) -> Result<(), WifiError>

Sets the primary and secondary Wi-Fi channel.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn set_max_tx_power(&mut self, power: i8) -> Result<(), WifiError>

Set maximum transmitting power after WiFi start.

Power unit is 0.25dBm, range is [8, 84] corresponding to 2dBm - 20dBm. The default is 20 (5dBm). Values above roughly 65 (~16dBm) have been reported to cause authentication failures on some hardware. See the module-level troubleshooting section for details.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub fn is_connected(&self) -> bool

Checks if the Wi-Fi controller is currently connected to an access point.

§Example
if controller.is_connected() {
    println!("Station is connected");
} else {
    println!("Station is not connected yet");
}
§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

pub async fn scan_async( &mut self, config: &ScanConfig, ) -> Result<Vec<AccessPointInfo>, WifiError>

An async Wi-Fi network scan with caller-provided scanning options.

Scanning is not supported in AcessPoint-only mode.

§Example
// Create a scan configuration (e.g., scan up to 10 APs)
let scan_config = ScanConfig::default().with_max(10);
let result = controller.scan_async(&scan_config).await.unwrap();
for ap in result {
    println!("{:?}", ap);
}

pub async fn connect_async(&mut self) -> Result<ConnectedInfo, ConnectionError>

Connect Wi-Fi station to the AP.

Use Self::disconnect_async to disconnect.

Calling Self::scan_async will not be effective until connection between device and the AP is established.

If device is scanning and connecting at the same time, it will abort scanning and return a warning message and error.

§Example


match controller.connect_async().await {
    Ok(_) => {
        println!("Wifi connected!");
    }
    Err(e) => {
        println!("Failed to connect to wifi: {e:?}");
    }
}

pub async fn disconnect_async(&mut self) -> Result<DisconnectedInfo, WifiError>

Disconnect Wi-Fi station from the AP.

If a connection attempt is currently in progress, it is aborted.

This function will wait for the connection to be closed before returning.

§Example

match controller.disconnect_async().await {
    Ok(info) => {
        println!("Station disconnected successfully. {info:?}");
    }
    Err(e) => {
        println!("Failed to disconnect: {e:?}");
    }
}

pub async fn wait_for_disconnect_async( &self, ) -> Result<DisconnectedInfo, WifiError>

Wait until the station gets disconnected from the AP.

pub async fn wait_for_access_point_connected_event_async( &self, ) -> Result<EventInfo, WifiError>

Wait for connected / disconnected events.

pub fn subscribe<'a>(&'a self) -> Result<EventSubscriber<'a>, WifiError>

Subscribe to events.

§Errors

This returns [WifiError::Other] if no more subscriptions are available. Consider increasing the internal event channel subscriber count in this case.

§Stability

This API is marked as unstable and is only available when the unstable crate feature is enabled. This comes with no stability guarantees, and could be changed or removed at any time.

Trait Implementations§

§

impl<'d> Debug for WifiController<'d>

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'d> Format for WifiController<'d>
where WifiRefGuard: Format, PhantomData<&'d ()>: Format,

§

fn format(&self, f: Formatter<'_>)

Writes the defmt representation of self to fmt.

Auto Trait Implementations§

§

impl<'d> Freeze for WifiController<'d>

§

impl<'d> RefUnwindSafe for WifiController<'d>

§

impl<'d> Send for WifiController<'d>

§

impl<'d> Sync for WifiController<'d>

§

impl<'d> Unpin for WifiController<'d>

§

impl<'d> UnsafeUnpin for WifiController<'d>

§

impl<'d> UnwindSafe for WifiController<'d>

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Az for T

Source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

Source§

fn cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> CheckedAs for T

Source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

Source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

Source§

impl<T> OverflowingAs for T

Source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

Source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> SaturatingAs for T

Source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

Source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> UnwrappedAs for T

Source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

Source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> WrappingAs for T

Source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

Source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,