From 94bd4eb7d5713e4c6e679617a3e6e94671c8ff77 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Mon, 12 Jul 2021 03:10:01 +0200 Subject: embassy/time: refactor module structure --- embassy/src/executor/mod.rs | 1 - embassy/src/executor/timer.rs | 178 ------------------------------------------ embassy/src/time/delay.rs | 70 +++++++++++++++++ embassy/src/time/mod.rs | 58 +------------- embassy/src/time/timer.rs | 153 ++++++++++++++++++++++++++++++++++++ 5 files changed, 227 insertions(+), 233 deletions(-) delete mode 100644 embassy/src/executor/timer.rs create mode 100644 embassy/src/time/delay.rs create mode 100644 embassy/src/time/timer.rs diff --git a/embassy/src/executor/mod.rs b/embassy/src/executor/mod.rs index 598d4e558..d9740d56d 100644 --- a/embassy/src/executor/mod.rs +++ b/embassy/src/executor/mod.rs @@ -4,7 +4,6 @@ use core::{mem, ptr}; pub mod raw; mod run_queue; -pub(crate) mod timer; mod timer_queue; mod util; mod waker; diff --git a/embassy/src/executor/timer.rs b/embassy/src/executor/timer.rs deleted file mode 100644 index 8ee336960..000000000 --- a/embassy/src/executor/timer.rs +++ /dev/null @@ -1,178 +0,0 @@ -use core::future::Future; -use core::marker::PhantomData; -use core::pin::Pin; -use core::task::{Context, Poll}; -use futures::{future::select, future::Either, pin_mut, Stream}; - -use super::raw; -use crate::time::{Duration, Instant}; - -/// Delay abstraction using embassy's clock. -pub struct Delay { - _data: PhantomData, -} - -impl Delay { - pub fn new() -> Self { - Delay { - _data: PhantomData {}, - } - } -} - -impl crate::traits::delay::Delay for Delay { - type DelayFuture<'a> = impl Future + 'a; - - fn delay_ms<'a>(&'a mut self, millis: u64) -> Self::DelayFuture<'a> { - Timer::after(Duration::from_millis(millis)) - } - fn delay_us<'a>(&'a mut self, micros: u64) -> Self::DelayFuture<'a> { - Timer::after(Duration::from_micros(micros)) - } -} - -pub struct TimeoutError; -pub async fn with_timeout(timeout: Duration, fut: F) -> Result { - let timeout_fut = Timer::after(timeout); - pin_mut!(fut); - match select(fut, timeout_fut).await { - Either::Left((r, _)) => Ok(r), - Either::Right(_) => Err(TimeoutError), - } -} - -/// A future that completes at a specified [Instant](struct.Instant.html). -pub struct Timer { - expires_at: Instant, - yielded_once: bool, -} - -impl Timer { - /// Expire at specified [Instant](struct.Instant.html) - pub fn at(expires_at: Instant) -> Self { - Self { - expires_at, - yielded_once: false, - } - } - - /// Expire after specified [Duration](struct.Duration.html). - /// This can be used as a `sleep` abstraction. - /// - /// Example: - /// ``` no_run - /// # #![feature(trait_alias)] - /// # #![feature(min_type_alias_impl_trait)] - /// # #![feature(impl_trait_in_bindings)] - /// # #![feature(type_alias_impl_trait)] - /// # - /// # fn foo() {} - /// use embassy::time::{Duration, Timer}; - /// - /// #[embassy::task] - /// async fn demo_sleep_seconds() { - /// // suspend this task for one second. - /// Timer::after(Duration::from_secs(1)).await; - /// } - /// ``` - pub fn after(duration: Duration) -> Self { - Self { - expires_at: Instant::now() + duration, - yielded_once: false, - } - } -} - -impl Unpin for Timer {} - -impl Future for Timer { - type Output = (); - fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - if self.yielded_once && self.expires_at <= Instant::now() { - Poll::Ready(()) - } else { - unsafe { raw::register_timer(self.expires_at, cx.waker()) }; - self.yielded_once = true; - Poll::Pending - } - } -} - -/// Asynchronous stream that yields every Duration, indefinitely. -/// -/// This stream will tick at uniform intervals, even if blocking work is performed between ticks. -/// -/// For instance, consider the following code fragment. -/// ``` no_run -/// # #![feature(trait_alias)] -/// # #![feature(min_type_alias_impl_trait)] -/// # #![feature(impl_trait_in_bindings)] -/// # #![feature(type_alias_impl_trait)] -/// # -/// use embassy::time::{Duration, Timer}; -/// # fn foo() {} -/// -/// #[embassy::task] -/// async fn ticker_example_0() { -/// loop { -/// foo(); -/// Timer::after(Duration::from_secs(1)).await; -/// } -/// } -/// ``` -/// -/// This fragment will not call `foo` every second. -/// Instead, it will call it every second + the time it took to previously call `foo`. -/// -/// Example using ticker, which will consistently call `foo` once a second. -/// -/// ``` no_run -/// # #![feature(trait_alias)] -/// # #![feature(min_type_alias_impl_trait)] -/// # #![feature(impl_trait_in_bindings)] -/// # #![feature(type_alias_impl_trait)] -/// # -/// use embassy::time::{Duration, Ticker}; -/// use futures::StreamExt; -/// # fn foo(){} -/// -/// #[embassy::task] -/// async fn ticker_example_1() { -/// let mut ticker = Ticker::every(Duration::from_secs(1)); -/// loop { -/// foo(); -/// ticker.next().await; -/// } -/// } -/// ``` -pub struct Ticker { - expires_at: Instant, - duration: Duration, -} - -impl Ticker { - /// Creates a new ticker that ticks at the specified duration interval. - pub fn every(duration: Duration) -> Self { - let expires_at = Instant::now() + duration; - Self { - expires_at, - duration, - } - } -} - -impl Unpin for Ticker {} - -impl Stream for Ticker { - type Item = (); - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - if self.expires_at <= Instant::now() { - let dur = self.duration; - self.expires_at += dur; - Poll::Ready(Some(())) - } else { - unsafe { raw::register_timer(self.expires_at, cx.waker()) }; - Poll::Pending - } - } -} diff --git a/embassy/src/time/delay.rs b/embassy/src/time/delay.rs new file mode 100644 index 000000000..f8b7f8400 --- /dev/null +++ b/embassy/src/time/delay.rs @@ -0,0 +1,70 @@ +use core::future::Future; + +use super::{Duration, Instant, Timer}; + +/// Async or blocking delay. +pub struct Delay; + +impl crate::traits::delay::Delay for Delay { + type DelayFuture<'a> = impl Future + 'a; + + fn delay_ms<'a>(&'a mut self, millis: u64) -> Self::DelayFuture<'a> { + Timer::after(Duration::from_millis(millis)) + } + fn delay_us<'a>(&'a mut self, micros: u64) -> Self::DelayFuture<'a> { + Timer::after(Duration::from_micros(micros)) + } +} + +/// Type used for blocking delays through embedded-hal traits. +/// +/// For this interface to work, the Executor's clock must be correctly initialized before using it. +/// The delays are implemented in a "best-effort" way, meaning that the cpu will block for at least +/// the amount provided, but accuracy can be affected by many factors, including interrupt usage. +/// Make sure to use a suitable tick rate for your use case. The tick rate can be chosen through +/// features flags of this crate. +pub struct BlockingTimer; + +impl embedded_hal::blocking::delay::DelayMs for BlockingTimer { + fn delay_ms(&mut self, ms: u8) { + block_for(Duration::from_millis(ms as u64)) + } +} + +impl embedded_hal::blocking::delay::DelayMs for BlockingTimer { + fn delay_ms(&mut self, ms: u16) { + block_for(Duration::from_millis(ms as u64)) + } +} + +impl embedded_hal::blocking::delay::DelayMs for BlockingTimer { + fn delay_ms(&mut self, ms: u32) { + block_for(Duration::from_millis(ms as u64)) + } +} + +impl embedded_hal::blocking::delay::DelayUs for BlockingTimer { + fn delay_us(&mut self, us: u8) { + block_for(Duration::from_micros(us as u64)) + } +} + +impl embedded_hal::blocking::delay::DelayUs for BlockingTimer { + fn delay_us(&mut self, us: u16) { + block_for(Duration::from_micros(us as u64)) + } +} + +impl embedded_hal::blocking::delay::DelayUs for BlockingTimer { + fn delay_us(&mut self, us: u32) { + block_for(Duration::from_micros(us as u64)) + } +} + +/// Blocks the cpu for at least `duration`. +/// +/// For this interface to work, the Executor's clock must be correctly initialized before using it. +pub fn block_for(duration: Duration) { + let expires_at = Instant::now() + duration; + while Instant::now() < expires_at {} +} diff --git a/embassy/src/time/mod.rs b/embassy/src/time/mod.rs index d50d9ef0d..9b7a4be18 100644 --- a/embassy/src/time/mod.rs +++ b/embassy/src/time/mod.rs @@ -1,13 +1,16 @@ //! Time abstractions //! To use these abstractions, first call `set_clock` with an instance of an [Clock](trait.Clock.html). //! +mod delay; mod duration; mod instant; +mod timer; mod traits; -pub use crate::executor::timer::{with_timeout, Delay, Ticker, TimeoutError, Timer}; +pub use delay::{block_for, Delay}; pub use duration::Duration; pub use instant::Instant; +pub use timer::{with_timeout, Ticker, TimeoutError, Timer}; pub use traits::*; #[cfg(any( @@ -42,56 +45,3 @@ pub unsafe fn set_clock(clock: &'static dyn Clock) { pub(crate) fn now() -> u64 { unsafe { unwrap!(CLOCK, "No clock set").now() } } - -/// Type used for blocking delays through embedded-hal traits. -/// -/// For this interface to work, the Executor's clock must be correctly initialized before using it. -/// The delays are implemented in a "best-effort" way, meaning that the cpu will block for at least -/// the amount provided, but accuracy can be affected by many factors, including interrupt usage. -/// Make sure to use a suitable tick rate for your use case. The tick rate can be chosen through -/// features flags of this crate. -pub struct BlockingTimer; - -impl embedded_hal::blocking::delay::DelayMs for BlockingTimer { - fn delay_ms(&mut self, ms: u8) { - block_for(Duration::from_millis(ms as u64)) - } -} - -impl embedded_hal::blocking::delay::DelayMs for BlockingTimer { - fn delay_ms(&mut self, ms: u16) { - block_for(Duration::from_millis(ms as u64)) - } -} - -impl embedded_hal::blocking::delay::DelayMs for BlockingTimer { - fn delay_ms(&mut self, ms: u32) { - block_for(Duration::from_millis(ms as u64)) - } -} - -impl embedded_hal::blocking::delay::DelayUs for BlockingTimer { - fn delay_us(&mut self, us: u8) { - block_for(Duration::from_micros(us as u64)) - } -} - -impl embedded_hal::blocking::delay::DelayUs for BlockingTimer { - fn delay_us(&mut self, us: u16) { - block_for(Duration::from_micros(us as u64)) - } -} - -impl embedded_hal::blocking::delay::DelayUs for BlockingTimer { - fn delay_us(&mut self, us: u32) { - block_for(Duration::from_micros(us as u64)) - } -} - -/// Blocks the cpu for at least `duration`. -/// -/// For this interface to work, the Executor's clock must be correctly initialized before using it. -pub fn block_for(duration: Duration) { - let expires_at = Instant::now() + duration; - while Instant::now() < expires_at {} -} diff --git a/embassy/src/time/timer.rs b/embassy/src/time/timer.rs new file mode 100644 index 000000000..a2a37f706 --- /dev/null +++ b/embassy/src/time/timer.rs @@ -0,0 +1,153 @@ +use core::future::Future; +use core::pin::Pin; +use core::task::{Context, Poll}; +use futures::{future::select, future::Either, pin_mut, Stream}; + +use crate::executor::raw; +use crate::time::{Duration, Instant}; + +pub struct TimeoutError; +pub async fn with_timeout(timeout: Duration, fut: F) -> Result { + let timeout_fut = Timer::after(timeout); + pin_mut!(fut); + match select(fut, timeout_fut).await { + Either::Left((r, _)) => Ok(r), + Either::Right(_) => Err(TimeoutError), + } +} + +/// A future that completes at a specified [Instant](struct.Instant.html). +pub struct Timer { + expires_at: Instant, + yielded_once: bool, +} + +impl Timer { + /// Expire at specified [Instant](struct.Instant.html) + pub fn at(expires_at: Instant) -> Self { + Self { + expires_at, + yielded_once: false, + } + } + + /// Expire after specified [Duration](struct.Duration.html). + /// This can be used as a `sleep` abstraction. + /// + /// Example: + /// ``` no_run + /// # #![feature(trait_alias)] + /// # #![feature(min_type_alias_impl_trait)] + /// # #![feature(impl_trait_in_bindings)] + /// # #![feature(type_alias_impl_trait)] + /// # + /// # fn foo() {} + /// use embassy::time::{Duration, Timer}; + /// + /// #[embassy::task] + /// async fn demo_sleep_seconds() { + /// // suspend this task for one second. + /// Timer::after(Duration::from_secs(1)).await; + /// } + /// ``` + pub fn after(duration: Duration) -> Self { + Self { + expires_at: Instant::now() + duration, + yielded_once: false, + } + } +} + +impl Unpin for Timer {} + +impl Future for Timer { + type Output = (); + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if self.yielded_once && self.expires_at <= Instant::now() { + Poll::Ready(()) + } else { + unsafe { raw::register_timer(self.expires_at, cx.waker()) }; + self.yielded_once = true; + Poll::Pending + } + } +} + +/// Asynchronous stream that yields every Duration, indefinitely. +/// +/// This stream will tick at uniform intervals, even if blocking work is performed between ticks. +/// +/// For instance, consider the following code fragment. +/// ``` no_run +/// # #![feature(trait_alias)] +/// # #![feature(min_type_alias_impl_trait)] +/// # #![feature(impl_trait_in_bindings)] +/// # #![feature(type_alias_impl_trait)] +/// # +/// use embassy::time::{Duration, Timer}; +/// # fn foo() {} +/// +/// #[embassy::task] +/// async fn ticker_example_0() { +/// loop { +/// foo(); +/// Timer::after(Duration::from_secs(1)).await; +/// } +/// } +/// ``` +/// +/// This fragment will not call `foo` every second. +/// Instead, it will call it every second + the time it took to previously call `foo`. +/// +/// Example using ticker, which will consistently call `foo` once a second. +/// +/// ``` no_run +/// # #![feature(trait_alias)] +/// # #![feature(min_type_alias_impl_trait)] +/// # #![feature(impl_trait_in_bindings)] +/// # #![feature(type_alias_impl_trait)] +/// # +/// use embassy::time::{Duration, Ticker}; +/// use futures::StreamExt; +/// # fn foo(){} +/// +/// #[embassy::task] +/// async fn ticker_example_1() { +/// let mut ticker = Ticker::every(Duration::from_secs(1)); +/// loop { +/// foo(); +/// ticker.next().await; +/// } +/// } +/// ``` +pub struct Ticker { + expires_at: Instant, + duration: Duration, +} + +impl Ticker { + /// Creates a new ticker that ticks at the specified duration interval. + pub fn every(duration: Duration) -> Self { + let expires_at = Instant::now() + duration; + Self { + expires_at, + duration, + } + } +} + +impl Unpin for Ticker {} + +impl Stream for Ticker { + type Item = (); + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.expires_at <= Instant::now() { + let dur = self.duration; + self.expires_at += dur; + Poll::Ready(Some(())) + } else { + unsafe { raw::register_timer(self.expires_at, cx.waker()) }; + Poll::Pending + } + } +} -- cgit