|
| 1 | +//! Example of using async wifi. |
| 2 | +//! |
| 3 | +//! Add your own ssid and password |
| 4 | +//! |
| 5 | +//! Note: Requires `nightly` and `experimental` cargo feature to be enabled |
| 6 | +
|
| 7 | +use embedded_svc::wifi::{AuthMethod, ClientConfiguration, Configuration}; |
| 8 | +use esp_idf_hal::prelude::Peripherals; |
| 9 | +use esp_idf_svc::log::EspLogger; |
| 10 | +use esp_idf_svc::timer::EspTaskTimerService; |
| 11 | +use esp_idf_svc::wifi::{AsyncWifi, EspWifi}; |
| 12 | +use esp_idf_svc::{eventloop::EspSystemEventLoop, nvs::EspDefaultNvsPartition}; |
| 13 | +use esp_idf_sys::{self as _}; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported |
| 14 | +use futures::executor::block_on; |
| 15 | +use log::info; |
| 16 | + |
| 17 | +const SSID: &'static str = env!("WIFI_SSID"); |
| 18 | +const PASSWORD: &'static str = env!("WIFI_PASS"); |
| 19 | + |
| 20 | +fn main() -> anyhow::Result<()> { |
| 21 | + EspLogger::initialize_default(); |
| 22 | + |
| 23 | + let peripherals = Peripherals::take().unwrap(); |
| 24 | + let sys_loop = EspSystemEventLoop::take()?; |
| 25 | + let timer_service = EspTaskTimerService::new()?; |
| 26 | + let nvs = EspDefaultNvsPartition::take()?; |
| 27 | + |
| 28 | + let mut wifi = AsyncWifi::wrap( |
| 29 | + EspWifi::new(peripherals.modem, sys_loop.clone(), Some(nvs))?, |
| 30 | + sys_loop, |
| 31 | + timer_service.clone(), |
| 32 | + )?; |
| 33 | + |
| 34 | + block_on(connect_wifi(&mut wifi))?; |
| 35 | + |
| 36 | + let ip_info = wifi.wifi().sta_netif().get_ip_info()?; |
| 37 | + |
| 38 | + info!("Wifi DHCP info: {:?}", ip_info); |
| 39 | + |
| 40 | + info!("Shutting down in 5s..."); |
| 41 | + |
| 42 | + std::thread::sleep(core::time::Duration::from_secs(5)); |
| 43 | + |
| 44 | + Ok(()) |
| 45 | +} |
| 46 | + |
| 47 | +async fn connect_wifi(wifi: &mut AsyncWifi<EspWifi<'static>>) -> anyhow::Result<()> { |
| 48 | + let wifi_configuration: Configuration = Configuration::Client(ClientConfiguration { |
| 49 | + ssid: SSID.into(), |
| 50 | + bssid: None, |
| 51 | + auth_method: AuthMethod::WPA2Personal, |
| 52 | + password: PASSWORD.into(), |
| 53 | + channel: None, |
| 54 | + }); |
| 55 | + |
| 56 | + wifi.set_configuration(&wifi_configuration)?; |
| 57 | + |
| 58 | + wifi.start().await?; |
| 59 | + info!("Wifi started"); |
| 60 | + |
| 61 | + wifi.connect().await?; |
| 62 | + info!("Wifi connected"); |
| 63 | + |
| 64 | + wifi.wait_netif_up().await?; |
| 65 | + info!("Wifi netif up"); |
| 66 | + |
| 67 | + Ok(()) |
| 68 | +} |
0 commit comments