62 lines
2 KiB
Rust
62 lines
2 KiB
Rust
use anyhow::Result;
|
|
use esp_idf_svc::{
|
|
eventloop::EspSystemEventLoop,
|
|
hal::{modem::Modem, peripheral::Peripheral},
|
|
wifi::{AuthMethod, BlockingWifi, ClientConfiguration, Configuration, EspWifi},
|
|
};
|
|
use log::{debug, info};
|
|
|
|
use crate::config;
|
|
|
|
/// Start WiFi module and connect to access point. Returns an error if either
|
|
/// of WiFi startup or connection fail.
|
|
pub(crate) fn init(
|
|
modem: impl Peripheral<P = Modem> + 'static,
|
|
sysloop: EspSystemEventLoop,
|
|
) -> Result<Box<EspWifi<'static>>> {
|
|
let auth_method = AuthMethod::WPA2Personal;
|
|
let mut esp_wifi = EspWifi::new(modem, sysloop.clone(), None)?;
|
|
let mut wifi = BlockingWifi::wrap(&mut esp_wifi, sysloop)?;
|
|
wifi.set_configuration(&Configuration::Client(ClientConfiguration::default()))?;
|
|
|
|
info!("Starting wifi...");
|
|
wifi.start()?;
|
|
debug!("Scanning...");
|
|
let ap_infos = wifi.scan()?;
|
|
let ours = ap_infos.into_iter().find(|a| a.ssid == config::WIFI_SSID);
|
|
let channel = if let Some(ours) = ours {
|
|
debug!(
|
|
"Found configured access point {} on channel {}",
|
|
config::WIFI_SSID,
|
|
ours.channel
|
|
);
|
|
Some(ours.channel)
|
|
} else {
|
|
debug!(
|
|
"Configured access point {} not found during scanning, will go with unknown channel",
|
|
config::WIFI_SSID
|
|
);
|
|
None
|
|
};
|
|
wifi.set_configuration(&Configuration::Client(ClientConfiguration {
|
|
ssid: config::WIFI_SSID
|
|
.try_into()
|
|
.expect("Could not parse the given SSID into WiFi config"),
|
|
password: config::WIFI_PASS
|
|
.try_into()
|
|
.expect("Could not parse the given password into WiFi config"),
|
|
channel,
|
|
auth_method,
|
|
..Default::default()
|
|
}))?;
|
|
|
|
debug!("Connecting wifi...");
|
|
wifi.connect()?;
|
|
debug!("Waiting for DHCP lease...");
|
|
wifi.wait_netif_up()?;
|
|
|
|
let ip_info = wifi.wifi().sta_netif().get_ip_info()?;
|
|
info!("Wifi DHCP info: {:?}", ip_info);
|
|
|
|
Ok(Box::new(esp_wifi))
|
|
}
|