From 53e197108bc93b46893c1f284383413b16b3ebb8 Mon Sep 17 00:00:00 2001 From: arosspope Date: Sun, 8 Oct 2023 18:04:36 +1100 Subject: [PATCH] Cleaned up error/bail conditions in wifi driver start function --- src/main.rs | 2 +- src/wifi.rs | 23 +++++++++++------------ 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 72bd897..098fd87 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,7 +41,7 @@ fn main() -> Result<()> { // Associate to network and obtain DHCP IP info!("Loading with credentials, ssid:{:?} psk:{:?}", app_config.wifi_ssid, app_config.wifi_psk); let mut wifi = Wifi::init(peripherals.modem, &app_config.wifi_ssid, &app_config.wifi_psk); - Wifi::start(&mut wifi); + Wifi::start(&mut wifi)?; let ip = wifi.sta_netif().get_ip_info().unwrap(); info!("IP info: {:?}", ip); diff --git a/src/wifi.rs b/src/wifi.rs index 7994928..b98e2b3 100644 --- a/src/wifi.rs +++ b/src/wifi.rs @@ -1,3 +1,4 @@ +use anyhow::{Result, Error, bail}; use embedded_svc::wifi::{AuthMethod, ClientConfiguration, Configuration, Wifi as SvcWifi}; use esp_idf_hal::modem::Modem; use esp_idf_svc::{eventloop::EspSystemEventLoop, nvs::EspDefaultNvsPartition, wifi::EspWifi}; @@ -26,33 +27,31 @@ impl Wifi { wifi_driver } - pub fn start(wifi_driver: &mut EspWifi<'_>) {// TODO: Make it a result type -> Result<()> { - wifi_driver.start().expect("Failed to start wifi driver"); - wifi_driver.is_started().expect("Failed to start wifi driver"); - wifi_driver.connect().expect("Failed to initiate connection"); + pub fn start(wifi_driver: &mut EspWifi<'_>) -> Result<(), Error> { + wifi_driver.start()?; + wifi_driver.is_started()?; + wifi_driver.connect()?; for _ in 0..10 { - if wifi_driver.is_connected().unwrap() { + if wifi_driver.is_connected()? { break; } std::thread::sleep(std::time::Duration::from_secs(1)); } - if !wifi_driver.is_connected().unwrap() { - return; // TODO: Error + if !wifi_driver.is_connected()? { + bail!("Failed to connect to BSS"); } for _ in 0..10 { - if wifi_driver.sta_netif().is_up().unwrap() { - // Ok(()) - break; + if wifi_driver.sta_netif().is_up()? { + return Ok(()); } std::thread::sleep(std::time::Duration::from_secs(1)); } - - // Ok(()) // TODO: Err + bail!("Failed to bring up network interface"); } } \ No newline at end of file