diff --git a/examples/deep_sleep.rs b/examples/deep_sleep.rs index b8f39c6cc4b..17b60565a39 100644 --- a/examples/deep_sleep.rs +++ b/examples/deep_sleep.rs @@ -10,7 +10,7 @@ use esp_idf_hal::sleep::DeepSleep; use esp_idf_hal::sleep::Sleep; use esp_idf_hal::sleep::WakeupSource; use std::thread; -use std::time::Duration; +use core::time::Duration; fn main() -> anyhow::Result<()> { esp_idf_sys::link_patches(); diff --git a/examples/light_sleep.rs b/examples/light_sleep.rs index 2d976ce84ef..63093841cdc 100644 --- a/examples/light_sleep.rs +++ b/examples/light_sleep.rs @@ -8,7 +8,7 @@ use esp_idf_hal::sleep::LightSleep; use esp_idf_hal::sleep::Sleep; use esp_idf_hal::sleep::WakeupSource; use std::thread; -use std::time::Duration; +use core::time::Duration; use std::time::Instant; fn print_wakeup_result(time_before: Instant) { diff --git a/src/sleep.rs b/src/sleep.rs index 01a4f0b9dca..38167bafae7 100644 --- a/src/sleep.rs +++ b/src/sleep.rs @@ -3,10 +3,14 @@ //! Currently implemented Timer and UART wakeup sources. use esp_idf_sys::*; -use std::time::Duration; +use core::time::Duration; -#[derive(Debug)] +const MAX_WAKEUP_SOURCES: usize = 10; + +#[derive(Default, Debug)] pub enum WakeupSource { + #[default] + None, Timer { dur: Duration }, Uart { uart_num: i32, threshold: i32 }, // TODO: add more sources @@ -15,6 +19,7 @@ pub enum WakeupSource { impl WakeupSource { pub fn apply(&self) -> Result<(), EspError> { match *self { + WakeupSource::None => {} WakeupSource::Timer { dur } => { esp!(unsafe { esp_sleep_enable_timer_wakeup(dur.as_micros() as u64) })?; } @@ -48,7 +53,8 @@ pub trait Sleep { #[derive(Default, Debug)] pub struct LightSleep { - wakeup_sources: Vec, + wakeup_sources: [WakeupSource; MAX_WAKEUP_SOURCES], + n_wakeup_sources: usize, } impl LightSleep { @@ -63,7 +69,11 @@ impl LightSleep { impl Sleep for LightSleep { fn add_wakeup_source(&mut self, wakeup: WakeupSource) -> Result<(), EspError> { - self.wakeup_sources.push(wakeup); + if self.n_wakeup_sources >= MAX_WAKEUP_SOURCES { + return Err(EspError::from_infallible::()) + } + self.wakeup_sources[self.n_wakeup_sources] = wakeup; + self.n_wakeup_sources += 1; Ok(()) } @@ -77,7 +87,8 @@ impl Sleep for LightSleep { #[derive(Default, Debug)] pub struct DeepSleep { - wakeup_sources: Vec, + wakeup_sources: [WakeupSource; MAX_WAKEUP_SOURCES], + n_wakeup_sources: usize, } impl DeepSleep { @@ -95,12 +106,18 @@ impl Sleep for DeepSleep { if matches!(wakeup, WakeupSource::Uart { .. }) { return Err(EspError::from_infallible::()); } - self.wakeup_sources.push(wakeup); + + if self.n_wakeup_sources >= MAX_WAKEUP_SOURCES { + return Err(EspError::from_infallible::()); + } + self.wakeup_sources[self.n_wakeup_sources] = wakeup; + self.n_wakeup_sources += 1; + Ok(()) } fn sleep(&self) -> Result<(), EspError> { - self.apply_wakeup_sources(&self.wakeup_sources)?; + self.apply_wakeup_sources(&self.wakeup_sources[0..self.n_wakeup_sources])?; unsafe { esp_deep_sleep_start() }; #[allow(unreachable_code)]