diff --git a/src/main.rs b/src/main.rs index 1a50da7..c8ed644 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ use core::panic; -use std::borrow::Cow; +use std::num::NonZeroU16; +use std::{borrow::Cow, num::NonZero}; use std::str::FromStr; use chrono::{format::Fixed, DateTime, Datelike, Days, FixedOffset, NaiveTime}; @@ -33,6 +34,9 @@ type Timetable = [[Option;8]; 5]; #[link_section = ".rtc.data"] static mut WAKEUP_COUNTER: u64 = 0; +#[link_section = ".rtc.data"] +static mut WIFI_FAIL_COUNTER: Option = None; + #[link_section = ".rtc.data"] static mut ERROR_MSG: Option<[u8; 2048]> = None; @@ -164,14 +168,38 @@ fn main() -> anyhow::Result<()> { }, )) .unwrap(); - wifi.start().unwrap(); - wifi.connect().unwrap(); - wifi.wait_netif_up().unwrap(); + let connected = wifi.start() + .and_then(|_| wifi.connect()) + .and_then(|_| wifi.wait_netif_up()) + .and_then(|_| loop {if wifi.is_connected().unwrap() {break Ok(());}}).is_ok(); - while !wifi.is_connected().unwrap() {} + if !connected{ + let fail_count: u16 = unsafe { + let new_val = match WIFI_FAIL_COUNTER{ + Some(c) => c.saturating_add(1), + None => { + NonZeroU16::new_unchecked(1) + } + }; + WIFI_FAIL_COUNTER = Some(new_val); + new_val + }.into(); + + println!("Failed to connect to wifi for the {}th time", fail_count); + + // Quadratic falloff + let sleep_time = u32::min((fail_count as u32).pow(2u32) * 4, 600); + println!("Going to sleep for {} seconds", sleep_time); + unsafe { + esp_deep_sleep(sleep_time as u64 * 1000_000) + } + } + println!("Connected to wifi"); - let ip_info = wifi.wifi().sta_netif().get_ip_info().unwrap(); + unsafe { + WIFI_FAIL_COUNTER = None; + } let httpconnection = EspHttpConnection::new(&HttpConfig { use_global_ca_store: true,