diff options
Diffstat (limited to 'embassy-executor/src')
| -rw-r--r-- | embassy-executor/src/arch/cortex_m.rs (renamed from embassy-executor/src/executor/arch/cortex_m.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/arch/riscv32.rs (renamed from embassy-executor/src/executor/arch/riscv32.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/arch/std.rs (renamed from embassy-executor/src/executor/arch/std.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/arch/wasm.rs (renamed from embassy-executor/src/executor/arch/wasm.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/arch/xtensa.rs (renamed from embassy-executor/src/executor/arch/xtensa.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/executor/mod.rs | 44 | ||||
| -rw-r--r-- | embassy-executor/src/fmt.rs | 3 | ||||
| -rw-r--r-- | embassy-executor/src/lib.rs | 42 | ||||
| -rw-r--r-- | embassy-executor/src/raw/mod.rs (renamed from embassy-executor/src/executor/raw/mod.rs) | 45 | ||||
| -rw-r--r-- | embassy-executor/src/raw/run_queue.rs (renamed from embassy-executor/src/executor/raw/run_queue.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/raw/timer_queue.rs (renamed from embassy-executor/src/executor/raw/timer_queue.rs) | 2 | ||||
| -rw-r--r-- | embassy-executor/src/raw/util.rs (renamed from embassy-executor/src/executor/raw/util.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/raw/waker.rs (renamed from embassy-executor/src/executor/raw/waker.rs) | 2 | ||||
| -rw-r--r-- | embassy-executor/src/spawner.rs (renamed from embassy-executor/src/executor/spawner.rs) | 0 | ||||
| -rw-r--r-- | embassy-executor/src/time/delay.rs | 98 | ||||
| -rw-r--r-- | embassy-executor/src/time/driver.rs | 170 | ||||
| -rw-r--r-- | embassy-executor/src/time/driver_std.rs | 208 | ||||
| -rw-r--r-- | embassy-executor/src/time/driver_wasm.rs | 134 | ||||
| -rw-r--r-- | embassy-executor/src/time/duration.rs | 184 | ||||
| -rw-r--r-- | embassy-executor/src/time/instant.rs | 159 | ||||
| -rw-r--r-- | embassy-executor/src/time/mod.rs | 91 | ||||
| -rw-r--r-- | embassy-executor/src/time/timer.rs | 151 |
22 files changed, 57 insertions, 1276 deletions
diff --git a/embassy-executor/src/executor/arch/cortex_m.rs b/embassy-executor/src/arch/cortex_m.rs index d6e758dfb..d6e758dfb 100644 --- a/embassy-executor/src/executor/arch/cortex_m.rs +++ b/embassy-executor/src/arch/cortex_m.rs | |||
diff --git a/embassy-executor/src/executor/arch/riscv32.rs b/embassy-executor/src/arch/riscv32.rs index 7a7d5698c..7a7d5698c 100644 --- a/embassy-executor/src/executor/arch/riscv32.rs +++ b/embassy-executor/src/arch/riscv32.rs | |||
diff --git a/embassy-executor/src/executor/arch/std.rs b/embassy-executor/src/arch/std.rs index b93ab8a79..b93ab8a79 100644 --- a/embassy-executor/src/executor/arch/std.rs +++ b/embassy-executor/src/arch/std.rs | |||
diff --git a/embassy-executor/src/executor/arch/wasm.rs b/embassy-executor/src/arch/wasm.rs index 9d5aa31ed..9d5aa31ed 100644 --- a/embassy-executor/src/executor/arch/wasm.rs +++ b/embassy-executor/src/arch/wasm.rs | |||
diff --git a/embassy-executor/src/executor/arch/xtensa.rs b/embassy-executor/src/arch/xtensa.rs index 20bd7b8a5..20bd7b8a5 100644 --- a/embassy-executor/src/executor/arch/xtensa.rs +++ b/embassy-executor/src/arch/xtensa.rs | |||
diff --git a/embassy-executor/src/executor/mod.rs b/embassy-executor/src/executor/mod.rs deleted file mode 100644 index 45d00c568..000000000 --- a/embassy-executor/src/executor/mod.rs +++ /dev/null | |||
| @@ -1,44 +0,0 @@ | |||
| 1 | //! Async task executor. | ||
| 2 | //! | ||
| 3 | //! This module provides an async/await executor designed for embedded usage. | ||
| 4 | //! | ||
| 5 | //! - No `alloc`, no heap needed. Task futures are statically allocated. | ||
| 6 | //! - No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning. | ||
| 7 | //! - Integrated timer queue: sleeping is easy, just do `Timer::after(Duration::from_secs(1)).await;`. | ||
| 8 | //! - No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or `WFE/SEV`. | ||
| 9 | //! - Efficient polling: a wake will only poll the woken task, not all of them. | ||
| 10 | //! - Fair: a task can't monopolize CPU time even if it's constantly being woken. All other tasks get a chance to run before a given task gets polled for the second time. | ||
| 11 | //! - Creating multiple executor instances is supported, to run tasks with multiple priority levels. This allows higher-priority tasks to preempt lower-priority tasks. | ||
| 12 | |||
| 13 | cfg_if::cfg_if! { | ||
| 14 | if #[cfg(cortex_m)] { | ||
| 15 | #[path="arch/cortex_m.rs"] | ||
| 16 | mod arch; | ||
| 17 | pub use arch::*; | ||
| 18 | } | ||
| 19 | else if #[cfg(target_arch="riscv32")] { | ||
| 20 | #[path="arch/riscv32.rs"] | ||
| 21 | mod arch; | ||
| 22 | pub use arch::*; | ||
| 23 | } | ||
| 24 | else if #[cfg(all(target_arch="xtensa", feature = "nightly"))] { | ||
| 25 | #[path="arch/xtensa.rs"] | ||
| 26 | mod arch; | ||
| 27 | pub use arch::*; | ||
| 28 | } | ||
| 29 | else if #[cfg(feature="wasm")] { | ||
| 30 | #[path="arch/wasm.rs"] | ||
| 31 | mod arch; | ||
| 32 | pub use arch::*; | ||
| 33 | } | ||
| 34 | else if #[cfg(feature="std")] { | ||
| 35 | #[path="arch/std.rs"] | ||
| 36 | mod arch; | ||
| 37 | pub use arch::*; | ||
| 38 | } | ||
| 39 | } | ||
| 40 | |||
| 41 | pub mod raw; | ||
| 42 | |||
| 43 | mod spawner; | ||
| 44 | pub use spawner::*; | ||
diff --git a/embassy-executor/src/fmt.rs b/embassy-executor/src/fmt.rs index f8bb0a035..066970813 100644 --- a/embassy-executor/src/fmt.rs +++ b/embassy-executor/src/fmt.rs | |||
| @@ -195,9 +195,6 @@ macro_rules! unwrap { | |||
| 195 | } | 195 | } |
| 196 | } | 196 | } |
| 197 | 197 | ||
| 198 | #[cfg(feature = "defmt-timestamp-uptime")] | ||
| 199 | defmt::timestamp! {"{=u64:us}", crate::time::Instant::now().as_micros() } | ||
| 200 | |||
| 201 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] | 198 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] |
| 202 | pub struct NoneError; | 199 | pub struct NoneError; |
| 203 | 200 | ||
diff --git a/embassy-executor/src/lib.rs b/embassy-executor/src/lib.rs index 69e4aeb4b..9328a7378 100644 --- a/embassy-executor/src/lib.rs +++ b/embassy-executor/src/lib.rs | |||
| @@ -1,22 +1,44 @@ | |||
| 1 | #![cfg_attr(not(any(feature = "std", feature = "wasm")), no_std)] | 1 | #![cfg_attr(not(any(feature = "std", feature = "wasm")), no_std)] |
| 2 | #![cfg_attr(feature = "nightly", feature(generic_associated_types, type_alias_impl_trait))] | ||
| 3 | #![cfg_attr(all(feature = "nightly", target_arch = "xtensa"), feature(asm_experimental_arch))] | 2 | #![cfg_attr(all(feature = "nightly", target_arch = "xtensa"), feature(asm_experimental_arch))] |
| 4 | #![allow(clippy::new_without_default)] | 3 | #![allow(clippy::new_without_default)] |
| 5 | #![doc = include_str!("../../README.md")] | 4 | #![doc = include_str!("../README.md")] |
| 6 | #![warn(missing_docs)] | 5 | #![warn(missing_docs)] |
| 7 | 6 | ||
| 8 | // This mod MUST go first, so that the others see its macros. | 7 | // This mod MUST go first, so that the others see its macros. |
| 9 | pub(crate) mod fmt; | 8 | pub(crate) mod fmt; |
| 10 | 9 | ||
| 11 | pub mod executor; | ||
| 12 | #[cfg(feature = "time")] | ||
| 13 | pub mod time; | ||
| 14 | |||
| 15 | #[cfg(feature = "nightly")] | 10 | #[cfg(feature = "nightly")] |
| 16 | pub use embassy_macros::{main, task}; | 11 | pub use embassy_macros::{main, task}; |
| 17 | 12 | ||
| 18 | #[doc(hidden)] | 13 | cfg_if::cfg_if! { |
| 19 | /// Implementation details for embassy macros. DO NOT USE. | 14 | if #[cfg(cortex_m)] { |
| 20 | pub mod export { | 15 | #[path="arch/cortex_m.rs"] |
| 21 | pub use atomic_polyfill as atomic; | 16 | mod arch; |
| 17 | pub use arch::*; | ||
| 18 | } | ||
| 19 | else if #[cfg(target_arch="riscv32")] { | ||
| 20 | #[path="arch/riscv32.rs"] | ||
| 21 | mod arch; | ||
| 22 | pub use arch::*; | ||
| 23 | } | ||
| 24 | else if #[cfg(all(target_arch="xtensa", feature = "nightly"))] { | ||
| 25 | #[path="arch/xtensa.rs"] | ||
| 26 | mod arch; | ||
| 27 | pub use arch::*; | ||
| 28 | } | ||
| 29 | else if #[cfg(feature="wasm")] { | ||
| 30 | #[path="arch/wasm.rs"] | ||
| 31 | mod arch; | ||
| 32 | pub use arch::*; | ||
| 33 | } | ||
| 34 | else if #[cfg(feature="std")] { | ||
| 35 | #[path="arch/std.rs"] | ||
| 36 | mod arch; | ||
| 37 | pub use arch::*; | ||
| 38 | } | ||
| 22 | } | 39 | } |
| 40 | |||
| 41 | pub mod raw; | ||
| 42 | |||
| 43 | mod spawner; | ||
| 44 | pub use spawner::*; | ||
diff --git a/embassy-executor/src/executor/raw/mod.rs b/embassy-executor/src/raw/mod.rs index fb4cc6288..afe67decb 100644 --- a/embassy-executor/src/executor/raw/mod.rs +++ b/embassy-executor/src/raw/mod.rs | |||
| @@ -8,7 +8,7 @@ | |||
| 8 | //! executor wrappers in [`executor`](crate::executor) and the [`embassy_executor::task`](embassy_macros::task) macro, which are fully safe. | 8 | //! executor wrappers in [`executor`](crate::executor) and the [`embassy_executor::task`](embassy_macros::task) macro, which are fully safe. |
| 9 | 9 | ||
| 10 | mod run_queue; | 10 | mod run_queue; |
| 11 | #[cfg(feature = "time")] | 11 | #[cfg(feature = "integrated-timers")] |
| 12 | mod timer_queue; | 12 | mod timer_queue; |
| 13 | pub(crate) mod util; | 13 | pub(crate) mod util; |
| 14 | mod waker; | 14 | mod waker; |
| @@ -22,22 +22,22 @@ use core::{mem, ptr}; | |||
| 22 | 22 | ||
| 23 | use atomic_polyfill::{AtomicU32, Ordering}; | 23 | use atomic_polyfill::{AtomicU32, Ordering}; |
| 24 | use critical_section::CriticalSection; | 24 | use critical_section::CriticalSection; |
| 25 | #[cfg(feature = "integrated-timers")] | ||
| 26 | use embassy_time::driver::{self, AlarmHandle}; | ||
| 27 | #[cfg(feature = "integrated-timers")] | ||
| 28 | use embassy_time::Instant; | ||
| 25 | 29 | ||
| 26 | use self::run_queue::{RunQueue, RunQueueItem}; | 30 | use self::run_queue::{RunQueue, RunQueueItem}; |
| 27 | use self::util::UninitCell; | 31 | use self::util::UninitCell; |
| 28 | pub use self::waker::task_from_waker; | 32 | pub use self::waker::task_from_waker; |
| 29 | use super::SpawnToken; | 33 | use super::SpawnToken; |
| 30 | #[cfg(feature = "time")] | ||
| 31 | use crate::time::driver::{self, AlarmHandle}; | ||
| 32 | #[cfg(feature = "time")] | ||
| 33 | use crate::time::Instant; | ||
| 34 | 34 | ||
| 35 | /// Task is spawned (has a future) | 35 | /// Task is spawned (has a future) |
| 36 | pub(crate) const STATE_SPAWNED: u32 = 1 << 0; | 36 | pub(crate) const STATE_SPAWNED: u32 = 1 << 0; |
| 37 | /// Task is in the executor run queue | 37 | /// Task is in the executor run queue |
| 38 | pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 1; | 38 | pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 1; |
| 39 | /// Task is in the executor timer queue | 39 | /// Task is in the executor timer queue |
| 40 | #[cfg(feature = "time")] | 40 | #[cfg(feature = "integrated-timers")] |
| 41 | pub(crate) const STATE_TIMER_QUEUED: u32 = 1 << 2; | 41 | pub(crate) const STATE_TIMER_QUEUED: u32 = 1 << 2; |
| 42 | 42 | ||
| 43 | /// Raw task header for use in task pointers. | 43 | /// Raw task header for use in task pointers. |
| @@ -50,9 +50,9 @@ pub struct TaskHeader { | |||
| 50 | pub(crate) executor: Cell<*const Executor>, // Valid if state != 0 | 50 | pub(crate) executor: Cell<*const Executor>, // Valid if state != 0 |
| 51 | pub(crate) poll_fn: UninitCell<unsafe fn(NonNull<TaskHeader>)>, // Valid if STATE_SPAWNED | 51 | pub(crate) poll_fn: UninitCell<unsafe fn(NonNull<TaskHeader>)>, // Valid if STATE_SPAWNED |
| 52 | 52 | ||
| 53 | #[cfg(feature = "time")] | 53 | #[cfg(feature = "integrated-timers")] |
| 54 | pub(crate) expires_at: Cell<Instant>, | 54 | pub(crate) expires_at: Cell<Instant>, |
| 55 | #[cfg(feature = "time")] | 55 | #[cfg(feature = "integrated-timers")] |
| 56 | pub(crate) timer_queue_item: timer_queue::TimerQueueItem, | 56 | pub(crate) timer_queue_item: timer_queue::TimerQueueItem, |
| 57 | } | 57 | } |
| 58 | 58 | ||
| @@ -64,9 +64,9 @@ impl TaskHeader { | |||
| 64 | executor: Cell::new(ptr::null()), | 64 | executor: Cell::new(ptr::null()), |
| 65 | poll_fn: UninitCell::uninit(), | 65 | poll_fn: UninitCell::uninit(), |
| 66 | 66 | ||
| 67 | #[cfg(feature = "time")] | 67 | #[cfg(feature = "integrated-timers")] |
| 68 | expires_at: Cell::new(Instant::from_ticks(0)), | 68 | expires_at: Cell::new(Instant::from_ticks(0)), |
| 69 | #[cfg(feature = "time")] | 69 | #[cfg(feature = "integrated-timers")] |
| 70 | timer_queue_item: timer_queue::TimerQueueItem::new(), | 70 | timer_queue_item: timer_queue::TimerQueueItem::new(), |
| 71 | } | 71 | } |
| 72 | } | 72 | } |
| @@ -267,9 +267,9 @@ pub struct Executor { | |||
| 267 | signal_fn: fn(*mut ()), | 267 | signal_fn: fn(*mut ()), |
| 268 | signal_ctx: *mut (), | 268 | signal_ctx: *mut (), |
| 269 | 269 | ||
| 270 | #[cfg(feature = "time")] | 270 | #[cfg(feature = "integrated-timers")] |
| 271 | pub(crate) timer_queue: timer_queue::TimerQueue, | 271 | pub(crate) timer_queue: timer_queue::TimerQueue, |
| 272 | #[cfg(feature = "time")] | 272 | #[cfg(feature = "integrated-timers")] |
| 273 | alarm: AlarmHandle, | 273 | alarm: AlarmHandle, |
| 274 | } | 274 | } |
| 275 | 275 | ||
| @@ -281,9 +281,9 @@ impl Executor { | |||
| 281 | /// | 281 | /// |
| 282 | /// See [`Executor`] docs for details on `signal_fn`. | 282 | /// See [`Executor`] docs for details on `signal_fn`. |
| 283 | pub fn new(signal_fn: fn(*mut ()), signal_ctx: *mut ()) -> Self { | 283 | pub fn new(signal_fn: fn(*mut ()), signal_ctx: *mut ()) -> Self { |
| 284 | #[cfg(feature = "time")] | 284 | #[cfg(feature = "integrated-timers")] |
| 285 | let alarm = unsafe { unwrap!(driver::allocate_alarm()) }; | 285 | let alarm = unsafe { unwrap!(driver::allocate_alarm()) }; |
| 286 | #[cfg(feature = "time")] | 286 | #[cfg(feature = "integrated-timers")] |
| 287 | driver::set_alarm_callback(alarm, signal_fn, signal_ctx); | 287 | driver::set_alarm_callback(alarm, signal_fn, signal_ctx); |
| 288 | 288 | ||
| 289 | Self { | 289 | Self { |
| @@ -291,9 +291,9 @@ impl Executor { | |||
| 291 | signal_fn, | 291 | signal_fn, |
| 292 | signal_ctx, | 292 | signal_ctx, |
| 293 | 293 | ||
| 294 | #[cfg(feature = "time")] | 294 | #[cfg(feature = "integrated-timers")] |
| 295 | timer_queue: timer_queue::TimerQueue::new(), | 295 | timer_queue: timer_queue::TimerQueue::new(), |
| 296 | #[cfg(feature = "time")] | 296 | #[cfg(feature = "integrated-timers")] |
| 297 | alarm, | 297 | alarm, |
| 298 | } | 298 | } |
| 299 | } | 299 | } |
| @@ -346,13 +346,13 @@ impl Executor { | |||
| 346 | /// somehow schedule for `poll()` to be called later, at a time you know for sure there's | 346 | /// somehow schedule for `poll()` to be called later, at a time you know for sure there's |
| 347 | /// no `poll()` already running. | 347 | /// no `poll()` already running. |
| 348 | pub unsafe fn poll(&'static self) { | 348 | pub unsafe fn poll(&'static self) { |
| 349 | #[cfg(feature = "time")] | 349 | #[cfg(feature = "integrated-timers")] |
| 350 | self.timer_queue.dequeue_expired(Instant::now(), |task| wake_task(task)); | 350 | self.timer_queue.dequeue_expired(Instant::now(), |task| wake_task(task)); |
| 351 | 351 | ||
| 352 | self.run_queue.dequeue_all(|p| { | 352 | self.run_queue.dequeue_all(|p| { |
| 353 | let task = p.as_ref(); | 353 | let task = p.as_ref(); |
| 354 | 354 | ||
| 355 | #[cfg(feature = "time")] | 355 | #[cfg(feature = "integrated-timers")] |
| 356 | task.expires_at.set(Instant::MAX); | 356 | task.expires_at.set(Instant::MAX); |
| 357 | 357 | ||
| 358 | let state = task.state.fetch_and(!STATE_RUN_QUEUED, Ordering::AcqRel); | 358 | let state = task.state.fetch_and(!STATE_RUN_QUEUED, Ordering::AcqRel); |
| @@ -369,11 +369,11 @@ impl Executor { | |||
| 369 | task.poll_fn.read()(p as _); | 369 | task.poll_fn.read()(p as _); |
| 370 | 370 | ||
| 371 | // Enqueue or update into timer_queue | 371 | // Enqueue or update into timer_queue |
| 372 | #[cfg(feature = "time")] | 372 | #[cfg(feature = "integrated-timers")] |
| 373 | self.timer_queue.update(p); | 373 | self.timer_queue.update(p); |
| 374 | }); | 374 | }); |
| 375 | 375 | ||
| 376 | #[cfg(feature = "time")] | 376 | #[cfg(feature = "integrated-timers")] |
| 377 | { | 377 | { |
| 378 | // If this is already in the past, set_alarm will immediately trigger the alarm. | 378 | // If this is already in the past, set_alarm will immediately trigger the alarm. |
| 379 | // This will cause `signal_fn` to be called, which will cause `poll()` to be called again, | 379 | // This will cause `signal_fn` to be called, which will cause `poll()` to be called again, |
| @@ -418,8 +418,9 @@ pub unsafe fn wake_task(task: NonNull<TaskHeader>) { | |||
| 418 | }) | 418 | }) |
| 419 | } | 419 | } |
| 420 | 420 | ||
| 421 | #[cfg(feature = "time")] | 421 | #[cfg(feature = "integrated-timers")] |
| 422 | pub(crate) unsafe fn register_timer(at: Instant, waker: &core::task::Waker) { | 422 | #[no_mangle] |
| 423 | unsafe fn _embassy_time_schedule_wake(at: Instant, waker: &core::task::Waker) { | ||
| 423 | let task = waker::task_from_waker(waker); | 424 | let task = waker::task_from_waker(waker); |
| 424 | let task = task.as_ref(); | 425 | let task = task.as_ref(); |
| 425 | let expires_at = task.expires_at.get(); | 426 | let expires_at = task.expires_at.get(); |
diff --git a/embassy-executor/src/executor/raw/run_queue.rs b/embassy-executor/src/raw/run_queue.rs index ed8c82a5c..ed8c82a5c 100644 --- a/embassy-executor/src/executor/raw/run_queue.rs +++ b/embassy-executor/src/raw/run_queue.rs | |||
diff --git a/embassy-executor/src/executor/raw/timer_queue.rs b/embassy-executor/src/raw/timer_queue.rs index 62fcfc531..24c31892a 100644 --- a/embassy-executor/src/executor/raw/timer_queue.rs +++ b/embassy-executor/src/raw/timer_queue.rs | |||
| @@ -4,9 +4,9 @@ use core::ptr; | |||
| 4 | use core::ptr::NonNull; | 4 | use core::ptr::NonNull; |
| 5 | 5 | ||
| 6 | use atomic_polyfill::Ordering; | 6 | use atomic_polyfill::Ordering; |
| 7 | use embassy_time::Instant; | ||
| 7 | 8 | ||
| 8 | use super::{TaskHeader, STATE_TIMER_QUEUED}; | 9 | use super::{TaskHeader, STATE_TIMER_QUEUED}; |
| 9 | use crate::time::Instant; | ||
| 10 | 10 | ||
| 11 | pub(crate) struct TimerQueueItem { | 11 | pub(crate) struct TimerQueueItem { |
| 12 | next: Cell<*mut TaskHeader>, | 12 | next: Cell<*mut TaskHeader>, |
diff --git a/embassy-executor/src/executor/raw/util.rs b/embassy-executor/src/raw/util.rs index ed5822188..ed5822188 100644 --- a/embassy-executor/src/executor/raw/util.rs +++ b/embassy-executor/src/raw/util.rs | |||
diff --git a/embassy-executor/src/executor/raw/waker.rs b/embassy-executor/src/raw/waker.rs index 6b9c03a62..5765259f2 100644 --- a/embassy-executor/src/executor/raw/waker.rs +++ b/embassy-executor/src/raw/waker.rs | |||
| @@ -40,7 +40,7 @@ pub fn task_from_waker(waker: &Waker) -> NonNull<TaskHeader> { | |||
| 40 | // TODO use waker_getters when stable. https://github.com/rust-lang/rust/issues/96992 | 40 | // TODO use waker_getters when stable. https://github.com/rust-lang/rust/issues/96992 |
| 41 | let hack: &WakerHack = unsafe { mem::transmute(waker) }; | 41 | let hack: &WakerHack = unsafe { mem::transmute(waker) }; |
| 42 | if hack.vtable != &VTABLE { | 42 | if hack.vtable != &VTABLE { |
| 43 | panic!("Found waker not created by the Embassy executor. `embassy_executor::time::Timer` only works with the Embassy executor.") | 43 | panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.") |
| 44 | } | 44 | } |
| 45 | 45 | ||
| 46 | // safety: we never create a waker with a null data pointer. | 46 | // safety: we never create a waker with a null data pointer. |
diff --git a/embassy-executor/src/executor/spawner.rs b/embassy-executor/src/spawner.rs index 25a0d7dbb..25a0d7dbb 100644 --- a/embassy-executor/src/executor/spawner.rs +++ b/embassy-executor/src/spawner.rs | |||
diff --git a/embassy-executor/src/time/delay.rs b/embassy-executor/src/time/delay.rs deleted file mode 100644 index d76ed32eb..000000000 --- a/embassy-executor/src/time/delay.rs +++ /dev/null | |||
| @@ -1,98 +0,0 @@ | |||
| 1 | use super::{Duration, Instant}; | ||
| 2 | |||
| 3 | /// Blocks for at least `duration`. | ||
| 4 | pub fn block_for(duration: Duration) { | ||
| 5 | let expires_at = Instant::now() + duration; | ||
| 6 | while Instant::now() < expires_at {} | ||
| 7 | } | ||
| 8 | |||
| 9 | /// Type implementing async delays and blocking `embedded-hal` delays. | ||
| 10 | /// | ||
| 11 | /// The delays are implemented in a "best-effort" way, meaning that the cpu will block for at least | ||
| 12 | /// the amount provided, but accuracy can be affected by many factors, including interrupt usage. | ||
| 13 | /// Make sure to use a suitable tick rate for your use case. The tick rate is defined by the currently | ||
| 14 | /// active driver. | ||
| 15 | pub struct Delay; | ||
| 16 | |||
| 17 | #[cfg(feature = "unstable-traits")] | ||
| 18 | mod eh1 { | ||
| 19 | use super::*; | ||
| 20 | |||
| 21 | impl embedded_hal_1::delay::blocking::DelayUs for Delay { | ||
| 22 | type Error = core::convert::Infallible; | ||
| 23 | |||
| 24 | fn delay_us(&mut self, us: u32) -> Result<(), Self::Error> { | ||
| 25 | Ok(block_for(Duration::from_micros(us as u64))) | ||
| 26 | } | ||
| 27 | |||
| 28 | fn delay_ms(&mut self, ms: u32) -> Result<(), Self::Error> { | ||
| 29 | Ok(block_for(Duration::from_millis(ms as u64))) | ||
| 30 | } | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | cfg_if::cfg_if! { | ||
| 35 | if #[cfg(all(feature = "unstable-traits", feature = "nightly"))] { | ||
| 36 | use crate::time::Timer; | ||
| 37 | use core::future::Future; | ||
| 38 | use futures_util::FutureExt; | ||
| 39 | |||
| 40 | impl embedded_hal_async::delay::DelayUs for Delay { | ||
| 41 | type Error = core::convert::Infallible; | ||
| 42 | |||
| 43 | type DelayUsFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a where Self: 'a; | ||
| 44 | |||
| 45 | fn delay_us(&mut self, micros: u32) -> Self::DelayUsFuture<'_> { | ||
| 46 | Timer::after(Duration::from_micros(micros as _)).map(Ok) | ||
| 47 | } | ||
| 48 | |||
| 49 | type DelayMsFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a where Self: 'a; | ||
| 50 | |||
| 51 | fn delay_ms(&mut self, millis: u32) -> Self::DelayMsFuture<'_> { | ||
| 52 | Timer::after(Duration::from_millis(millis as _)).map(Ok) | ||
| 53 | } | ||
| 54 | } | ||
| 55 | } | ||
| 56 | } | ||
| 57 | |||
| 58 | mod eh02 { | ||
| 59 | use embedded_hal_02::blocking::delay::{DelayMs, DelayUs}; | ||
| 60 | |||
| 61 | use super::*; | ||
| 62 | |||
| 63 | impl DelayMs<u8> for Delay { | ||
| 64 | fn delay_ms(&mut self, ms: u8) { | ||
| 65 | block_for(Duration::from_millis(ms as u64)) | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | impl DelayMs<u16> for Delay { | ||
| 70 | fn delay_ms(&mut self, ms: u16) { | ||
| 71 | block_for(Duration::from_millis(ms as u64)) | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | impl DelayMs<u32> for Delay { | ||
| 76 | fn delay_ms(&mut self, ms: u32) { | ||
| 77 | block_for(Duration::from_millis(ms as u64)) | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | impl DelayUs<u8> for Delay { | ||
| 82 | fn delay_us(&mut self, us: u8) { | ||
| 83 | block_for(Duration::from_micros(us as u64)) | ||
| 84 | } | ||
| 85 | } | ||
| 86 | |||
| 87 | impl DelayUs<u16> for Delay { | ||
| 88 | fn delay_us(&mut self, us: u16) { | ||
| 89 | block_for(Duration::from_micros(us as u64)) | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 93 | impl DelayUs<u32> for Delay { | ||
| 94 | fn delay_us(&mut self, us: u32) { | ||
| 95 | block_for(Duration::from_micros(us as u64)) | ||
| 96 | } | ||
| 97 | } | ||
| 98 | } | ||
diff --git a/embassy-executor/src/time/driver.rs b/embassy-executor/src/time/driver.rs deleted file mode 100644 index 48e2f1c7d..000000000 --- a/embassy-executor/src/time/driver.rs +++ /dev/null | |||
| @@ -1,170 +0,0 @@ | |||
| 1 | //! Time driver interface | ||
| 2 | //! | ||
| 3 | //! This module defines the interface a driver needs to implement to power the `embassy_executor::time` module. | ||
| 4 | //! | ||
| 5 | //! # Implementing a driver | ||
| 6 | //! | ||
| 7 | //! - Define a struct `MyDriver` | ||
| 8 | //! - Implement [`Driver`] for it | ||
| 9 | //! - Register it as the global driver with [`time_driver_impl`]. | ||
| 10 | //! - Enable the Cargo features `embassy-executor/time` and one of `embassy-executor/time-tick-*` corresponding to the | ||
| 11 | //! tick rate of your driver. | ||
| 12 | //! | ||
| 13 | //! If you wish to make the tick rate configurable by the end user, you should do so by exposing your own | ||
| 14 | //! Cargo features and having each enable the corresponding `embassy-executor/time-tick-*`. | ||
| 15 | //! | ||
| 16 | //! # Linkage details | ||
| 17 | //! | ||
| 18 | //! Instead of the usual "trait + generic params" approach, calls from embassy to the driver are done via `extern` functions. | ||
| 19 | //! | ||
| 20 | //! `embassy` internally defines the driver functions as `extern "Rust" { fn _embassy_time_now() -> u64; }` and calls them. | ||
| 21 | //! The driver crate defines the functions as `#[no_mangle] fn _embassy_time_now() -> u64`. The linker will resolve the | ||
| 22 | //! calls from the `embassy` crate to call into the driver crate. | ||
| 23 | //! | ||
| 24 | //! If there is none or multiple drivers in the crate tree, linking will fail. | ||
| 25 | //! | ||
| 26 | //! This method has a few key advantages for something as foundational as timekeeping: | ||
| 27 | //! | ||
| 28 | //! - The time driver is available everywhere easily, without having to thread the implementation | ||
| 29 | //! through generic parameters. This is especially helpful for libraries. | ||
| 30 | //! - It means comparing `Instant`s will always make sense: if there were multiple drivers | ||
| 31 | //! active, one could compare an `Instant` from driver A to an `Instant` from driver B, which | ||
| 32 | //! would yield incorrect results. | ||
| 33 | //! | ||
| 34 | //! # Example | ||
| 35 | //! | ||
| 36 | //! ``` | ||
| 37 | //! use embassy_executor::time::driver::{Driver, AlarmHandle}; | ||
| 38 | //! | ||
| 39 | //! struct MyDriver{}; // not public! | ||
| 40 | //! embassy_executor::time_driver_impl!(static DRIVER: MyDriver = MyDriver{}); | ||
| 41 | //! | ||
| 42 | //! impl Driver for MyDriver { | ||
| 43 | //! fn now(&self) -> u64 { | ||
| 44 | //! todo!() | ||
| 45 | //! } | ||
| 46 | //! unsafe fn allocate_alarm(&self) -> Option<AlarmHandle> { | ||
| 47 | //! todo!() | ||
| 48 | //! } | ||
| 49 | //! fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) { | ||
| 50 | //! todo!() | ||
| 51 | //! } | ||
| 52 | //! fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) { | ||
| 53 | //! todo!() | ||
| 54 | //! } | ||
| 55 | //! } | ||
| 56 | //! ``` | ||
| 57 | |||
| 58 | /// Alarm handle, assigned by the driver. | ||
| 59 | #[derive(Clone, Copy)] | ||
| 60 | pub struct AlarmHandle { | ||
| 61 | id: u8, | ||
| 62 | } | ||
| 63 | |||
| 64 | impl AlarmHandle { | ||
| 65 | /// Create an AlarmHandle | ||
| 66 | /// | ||
| 67 | /// Safety: May only be called by the current global Driver impl. | ||
| 68 | /// The impl is allowed to rely on the fact that all `AlarmHandle` instances | ||
| 69 | /// are created by itself in unsafe code (e.g. indexing operations) | ||
| 70 | pub unsafe fn new(id: u8) -> Self { | ||
| 71 | Self { id } | ||
| 72 | } | ||
| 73 | |||
| 74 | /// Get the ID of the AlarmHandle. | ||
| 75 | pub fn id(&self) -> u8 { | ||
| 76 | self.id | ||
| 77 | } | ||
| 78 | } | ||
| 79 | |||
| 80 | /// Time driver | ||
| 81 | pub trait Driver: Send + Sync + 'static { | ||
| 82 | /// Return the current timestamp in ticks. | ||
| 83 | /// | ||
| 84 | /// Implementations MUST ensure that: | ||
| 85 | /// - This is guaranteed to be monotonic, i.e. a call to now() will always return | ||
| 86 | /// a greater or equal value than earler calls. Time can't "roll backwards". | ||
| 87 | /// - It "never" overflows. It must not overflow in a sufficiently long time frame, say | ||
| 88 | /// in 10_000 years (Human civilization is likely to already have self-destructed | ||
| 89 | /// 10_000 years from now.). This means if your hardware only has 16bit/32bit timers | ||
| 90 | /// you MUST extend them to 64-bit, for example by counting overflows in software, | ||
| 91 | /// or chaining multiple timers together. | ||
| 92 | fn now(&self) -> u64; | ||
| 93 | |||
| 94 | /// Try allocating an alarm handle. Returns None if no alarms left. | ||
| 95 | /// Initially the alarm has no callback set, and a null `ctx` pointer. | ||
| 96 | /// | ||
| 97 | /// # Safety | ||
| 98 | /// It is UB to make the alarm fire before setting a callback. | ||
| 99 | unsafe fn allocate_alarm(&self) -> Option<AlarmHandle>; | ||
| 100 | |||
| 101 | /// Sets the callback function to be called when the alarm triggers. | ||
| 102 | /// The callback may be called from any context (interrupt or thread mode). | ||
| 103 | fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()); | ||
| 104 | |||
| 105 | /// Sets an alarm at the given timestamp. When the current timestamp reaches the alarm | ||
| 106 | /// timestamp, the provided callback function will be called. | ||
| 107 | /// | ||
| 108 | /// If `timestamp` is already in the past, the alarm callback must be immediately fired. | ||
| 109 | /// In this case, it is allowed (but not mandatory) to call the alarm callback synchronously from `set_alarm`. | ||
| 110 | /// | ||
| 111 | /// When callback is called, it is guaranteed that now() will return a value greater or equal than timestamp. | ||
| 112 | /// | ||
| 113 | /// Only one alarm can be active at a time for each AlarmHandle. This overwrites any previously-set alarm if any. | ||
| 114 | fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64); | ||
| 115 | } | ||
| 116 | |||
| 117 | extern "Rust" { | ||
| 118 | fn _embassy_time_now() -> u64; | ||
| 119 | fn _embassy_time_allocate_alarm() -> Option<AlarmHandle>; | ||
| 120 | fn _embassy_time_set_alarm_callback(alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()); | ||
| 121 | fn _embassy_time_set_alarm(alarm: AlarmHandle, timestamp: u64); | ||
| 122 | } | ||
| 123 | |||
| 124 | pub(crate) fn now() -> u64 { | ||
| 125 | unsafe { _embassy_time_now() } | ||
| 126 | } | ||
| 127 | /// Safety: it is UB to make the alarm fire before setting a callback. | ||
| 128 | pub(crate) unsafe fn allocate_alarm() -> Option<AlarmHandle> { | ||
| 129 | _embassy_time_allocate_alarm() | ||
| 130 | } | ||
| 131 | pub(crate) fn set_alarm_callback(alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) { | ||
| 132 | unsafe { _embassy_time_set_alarm_callback(alarm, callback, ctx) } | ||
| 133 | } | ||
| 134 | pub(crate) fn set_alarm(alarm: AlarmHandle, timestamp: u64) { | ||
| 135 | unsafe { _embassy_time_set_alarm(alarm, timestamp) } | ||
| 136 | } | ||
| 137 | |||
| 138 | /// Set the time Driver implementation. | ||
| 139 | /// | ||
| 140 | /// See the module documentation for an example. | ||
| 141 | #[macro_export] | ||
| 142 | macro_rules! time_driver_impl { | ||
| 143 | (static $name:ident: $t: ty = $val:expr) => { | ||
| 144 | static $name: $t = $val; | ||
| 145 | |||
| 146 | #[no_mangle] | ||
| 147 | fn _embassy_time_now() -> u64 { | ||
| 148 | <$t as $crate::time::driver::Driver>::now(&$name) | ||
| 149 | } | ||
| 150 | |||
| 151 | #[no_mangle] | ||
| 152 | unsafe fn _embassy_time_allocate_alarm() -> Option<$crate::time::driver::AlarmHandle> { | ||
| 153 | <$t as $crate::time::driver::Driver>::allocate_alarm(&$name) | ||
| 154 | } | ||
| 155 | |||
| 156 | #[no_mangle] | ||
| 157 | fn _embassy_time_set_alarm_callback( | ||
| 158 | alarm: $crate::time::driver::AlarmHandle, | ||
| 159 | callback: fn(*mut ()), | ||
| 160 | ctx: *mut (), | ||
| 161 | ) { | ||
| 162 | <$t as $crate::time::driver::Driver>::set_alarm_callback(&$name, alarm, callback, ctx) | ||
| 163 | } | ||
| 164 | |||
| 165 | #[no_mangle] | ||
| 166 | fn _embassy_time_set_alarm(alarm: $crate::time::driver::AlarmHandle, timestamp: u64) { | ||
| 167 | <$t as $crate::time::driver::Driver>::set_alarm(&$name, alarm, timestamp) | ||
| 168 | } | ||
| 169 | }; | ||
| 170 | } | ||
diff --git a/embassy-executor/src/time/driver_std.rs b/embassy-executor/src/time/driver_std.rs deleted file mode 100644 index cb66f7c19..000000000 --- a/embassy-executor/src/time/driver_std.rs +++ /dev/null | |||
| @@ -1,208 +0,0 @@ | |||
| 1 | use std::cell::UnsafeCell; | ||
| 2 | use std::mem::MaybeUninit; | ||
| 3 | use std::sync::{Condvar, Mutex, Once}; | ||
| 4 | use std::time::{Duration as StdDuration, Instant as StdInstant}; | ||
| 5 | use std::{mem, ptr, thread}; | ||
| 6 | |||
| 7 | use atomic_polyfill::{AtomicU8, Ordering}; | ||
| 8 | |||
| 9 | use crate::time::driver::{AlarmHandle, Driver}; | ||
| 10 | |||
| 11 | const ALARM_COUNT: usize = 4; | ||
| 12 | |||
| 13 | struct AlarmState { | ||
| 14 | timestamp: u64, | ||
| 15 | |||
| 16 | // This is really a Option<(fn(*mut ()), *mut ())> | ||
| 17 | // but fn pointers aren't allowed in const yet | ||
| 18 | callback: *const (), | ||
| 19 | ctx: *mut (), | ||
| 20 | } | ||
| 21 | |||
| 22 | unsafe impl Send for AlarmState {} | ||
| 23 | |||
| 24 | impl AlarmState { | ||
| 25 | const fn new() -> Self { | ||
| 26 | Self { | ||
| 27 | timestamp: u64::MAX, | ||
| 28 | callback: ptr::null(), | ||
| 29 | ctx: ptr::null_mut(), | ||
| 30 | } | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | struct TimeDriver { | ||
| 35 | alarm_count: AtomicU8, | ||
| 36 | |||
| 37 | once: Once, | ||
| 38 | alarms: UninitCell<Mutex<[AlarmState; ALARM_COUNT]>>, | ||
| 39 | zero_instant: UninitCell<StdInstant>, | ||
| 40 | signaler: UninitCell<Signaler>, | ||
| 41 | } | ||
| 42 | |||
| 43 | const ALARM_NEW: AlarmState = AlarmState::new(); | ||
| 44 | crate::time_driver_impl!(static DRIVER: TimeDriver = TimeDriver { | ||
| 45 | alarm_count: AtomicU8::new(0), | ||
| 46 | |||
| 47 | once: Once::new(), | ||
| 48 | alarms: UninitCell::uninit(), | ||
| 49 | zero_instant: UninitCell::uninit(), | ||
| 50 | signaler: UninitCell::uninit(), | ||
| 51 | }); | ||
| 52 | |||
| 53 | impl TimeDriver { | ||
| 54 | fn init(&self) { | ||
| 55 | self.once.call_once(|| unsafe { | ||
| 56 | self.alarms.write(Mutex::new([ALARM_NEW; ALARM_COUNT])); | ||
| 57 | self.zero_instant.write(StdInstant::now()); | ||
| 58 | self.signaler.write(Signaler::new()); | ||
| 59 | |||
| 60 | thread::spawn(Self::alarm_thread); | ||
| 61 | }); | ||
| 62 | } | ||
| 63 | |||
| 64 | fn alarm_thread() { | ||
| 65 | let zero = unsafe { DRIVER.zero_instant.read() }; | ||
| 66 | loop { | ||
| 67 | let now = DRIVER.now(); | ||
| 68 | |||
| 69 | let mut next_alarm = u64::MAX; | ||
| 70 | { | ||
| 71 | let alarms = &mut *unsafe { DRIVER.alarms.as_ref() }.lock().unwrap(); | ||
| 72 | for alarm in alarms { | ||
| 73 | if alarm.timestamp <= now { | ||
| 74 | alarm.timestamp = u64::MAX; | ||
| 75 | |||
| 76 | // Call after clearing alarm, so the callback can set another alarm. | ||
| 77 | |||
| 78 | // safety: | ||
| 79 | // - we can ignore the possiblity of `f` being unset (null) because of the safety contract of `allocate_alarm`. | ||
| 80 | // - other than that we only store valid function pointers into alarm.callback | ||
| 81 | let f: fn(*mut ()) = unsafe { mem::transmute(alarm.callback) }; | ||
| 82 | f(alarm.ctx); | ||
| 83 | } else { | ||
| 84 | next_alarm = next_alarm.min(alarm.timestamp); | ||
| 85 | } | ||
| 86 | } | ||
| 87 | } | ||
| 88 | |||
| 89 | // Ensure we don't overflow | ||
| 90 | let until = zero | ||
| 91 | .checked_add(StdDuration::from_micros(next_alarm)) | ||
| 92 | .unwrap_or_else(|| StdInstant::now() + StdDuration::from_secs(1)); | ||
| 93 | |||
| 94 | unsafe { DRIVER.signaler.as_ref() }.wait_until(until); | ||
| 95 | } | ||
| 96 | } | ||
| 97 | } | ||
| 98 | |||
| 99 | impl Driver for TimeDriver { | ||
| 100 | fn now(&self) -> u64 { | ||
| 101 | self.init(); | ||
| 102 | |||
| 103 | let zero = unsafe { self.zero_instant.read() }; | ||
| 104 | StdInstant::now().duration_since(zero).as_micros() as u64 | ||
| 105 | } | ||
| 106 | |||
| 107 | unsafe fn allocate_alarm(&self) -> Option<AlarmHandle> { | ||
| 108 | let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| { | ||
| 109 | if x < ALARM_COUNT as u8 { | ||
| 110 | Some(x + 1) | ||
| 111 | } else { | ||
| 112 | None | ||
| 113 | } | ||
| 114 | }); | ||
| 115 | |||
| 116 | match id { | ||
| 117 | Ok(id) => Some(AlarmHandle::new(id)), | ||
| 118 | Err(_) => None, | ||
| 119 | } | ||
| 120 | } | ||
| 121 | |||
| 122 | fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) { | ||
| 123 | self.init(); | ||
| 124 | let mut alarms = unsafe { self.alarms.as_ref() }.lock().unwrap(); | ||
| 125 | let alarm = &mut alarms[alarm.id() as usize]; | ||
| 126 | alarm.callback = callback as *const (); | ||
| 127 | alarm.ctx = ctx; | ||
| 128 | } | ||
| 129 | |||
| 130 | fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) { | ||
| 131 | self.init(); | ||
| 132 | let mut alarms = unsafe { self.alarms.as_ref() }.lock().unwrap(); | ||
| 133 | let alarm = &mut alarms[alarm.id() as usize]; | ||
| 134 | alarm.timestamp = timestamp; | ||
| 135 | unsafe { self.signaler.as_ref() }.signal(); | ||
| 136 | } | ||
| 137 | } | ||
| 138 | |||
| 139 | struct Signaler { | ||
| 140 | mutex: Mutex<bool>, | ||
| 141 | condvar: Condvar, | ||
| 142 | } | ||
| 143 | |||
| 144 | impl Signaler { | ||
| 145 | fn new() -> Self { | ||
| 146 | Self { | ||
| 147 | mutex: Mutex::new(false), | ||
| 148 | condvar: Condvar::new(), | ||
| 149 | } | ||
| 150 | } | ||
| 151 | |||
| 152 | fn wait_until(&self, until: StdInstant) { | ||
| 153 | let mut signaled = self.mutex.lock().unwrap(); | ||
| 154 | while !*signaled { | ||
| 155 | let now = StdInstant::now(); | ||
| 156 | |||
| 157 | if now >= until { | ||
| 158 | break; | ||
| 159 | } | ||
| 160 | |||
| 161 | let dur = until - now; | ||
| 162 | let (signaled2, timeout) = self.condvar.wait_timeout(signaled, dur).unwrap(); | ||
| 163 | signaled = signaled2; | ||
| 164 | if timeout.timed_out() { | ||
| 165 | break; | ||
| 166 | } | ||
| 167 | } | ||
| 168 | *signaled = false; | ||
| 169 | } | ||
| 170 | |||
| 171 | fn signal(&self) { | ||
| 172 | let mut signaled = self.mutex.lock().unwrap(); | ||
| 173 | *signaled = true; | ||
| 174 | self.condvar.notify_one(); | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | pub(crate) struct UninitCell<T>(MaybeUninit<UnsafeCell<T>>); | ||
| 179 | unsafe impl<T> Send for UninitCell<T> {} | ||
| 180 | unsafe impl<T> Sync for UninitCell<T> {} | ||
| 181 | |||
| 182 | impl<T> UninitCell<T> { | ||
| 183 | pub const fn uninit() -> Self { | ||
| 184 | Self(MaybeUninit::uninit()) | ||
| 185 | } | ||
| 186 | |||
| 187 | pub unsafe fn as_ptr(&self) -> *const T { | ||
| 188 | (*self.0.as_ptr()).get() | ||
| 189 | } | ||
| 190 | |||
| 191 | pub unsafe fn as_mut_ptr(&self) -> *mut T { | ||
| 192 | (*self.0.as_ptr()).get() | ||
| 193 | } | ||
| 194 | |||
| 195 | pub unsafe fn as_ref(&self) -> &T { | ||
| 196 | &*self.as_ptr() | ||
| 197 | } | ||
| 198 | |||
| 199 | pub unsafe fn write(&self, val: T) { | ||
| 200 | ptr::write(self.as_mut_ptr(), val) | ||
| 201 | } | ||
| 202 | } | ||
| 203 | |||
| 204 | impl<T: Copy> UninitCell<T> { | ||
| 205 | pub unsafe fn read(&self) -> T { | ||
| 206 | ptr::read(self.as_mut_ptr()) | ||
| 207 | } | ||
| 208 | } | ||
diff --git a/embassy-executor/src/time/driver_wasm.rs b/embassy-executor/src/time/driver_wasm.rs deleted file mode 100644 index 5f585a19a..000000000 --- a/embassy-executor/src/time/driver_wasm.rs +++ /dev/null | |||
| @@ -1,134 +0,0 @@ | |||
| 1 | use std::cell::UnsafeCell; | ||
| 2 | use std::mem::MaybeUninit; | ||
| 3 | use std::ptr; | ||
| 4 | use std::sync::{Mutex, Once}; | ||
| 5 | |||
| 6 | use atomic_polyfill::{AtomicU8, Ordering}; | ||
| 7 | use wasm_bindgen::prelude::*; | ||
| 8 | use wasm_timer::Instant as StdInstant; | ||
| 9 | |||
| 10 | use crate::time::driver::{AlarmHandle, Driver}; | ||
| 11 | |||
| 12 | const ALARM_COUNT: usize = 4; | ||
| 13 | |||
| 14 | struct AlarmState { | ||
| 15 | token: Option<f64>, | ||
| 16 | closure: Option<Closure<dyn FnMut() + 'static>>, | ||
| 17 | } | ||
| 18 | |||
| 19 | unsafe impl Send for AlarmState {} | ||
| 20 | |||
| 21 | impl AlarmState { | ||
| 22 | const fn new() -> Self { | ||
| 23 | Self { | ||
| 24 | token: None, | ||
| 25 | closure: None, | ||
| 26 | } | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | #[wasm_bindgen] | ||
| 31 | extern "C" { | ||
| 32 | fn setTimeout(closure: &Closure<dyn FnMut()>, millis: u32) -> f64; | ||
| 33 | fn clearTimeout(token: f64); | ||
| 34 | } | ||
| 35 | |||
| 36 | struct TimeDriver { | ||
| 37 | alarm_count: AtomicU8, | ||
| 38 | |||
| 39 | once: Once, | ||
| 40 | alarms: UninitCell<Mutex<[AlarmState; ALARM_COUNT]>>, | ||
| 41 | zero_instant: UninitCell<StdInstant>, | ||
| 42 | } | ||
| 43 | |||
| 44 | const ALARM_NEW: AlarmState = AlarmState::new(); | ||
| 45 | crate::time_driver_impl!(static DRIVER: TimeDriver = TimeDriver { | ||
| 46 | alarm_count: AtomicU8::new(0), | ||
| 47 | once: Once::new(), | ||
| 48 | alarms: UninitCell::uninit(), | ||
| 49 | zero_instant: UninitCell::uninit(), | ||
| 50 | }); | ||
| 51 | |||
| 52 | impl TimeDriver { | ||
| 53 | fn init(&self) { | ||
| 54 | self.once.call_once(|| unsafe { | ||
| 55 | self.alarms.write(Mutex::new([ALARM_NEW; ALARM_COUNT])); | ||
| 56 | self.zero_instant.write(StdInstant::now()); | ||
| 57 | }); | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | impl Driver for TimeDriver { | ||
| 62 | fn now(&self) -> u64 { | ||
| 63 | self.init(); | ||
| 64 | |||
| 65 | let zero = unsafe { self.zero_instant.read() }; | ||
| 66 | StdInstant::now().duration_since(zero).as_micros() as u64 | ||
| 67 | } | ||
| 68 | |||
| 69 | unsafe fn allocate_alarm(&self) -> Option<AlarmHandle> { | ||
| 70 | let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| { | ||
| 71 | if x < ALARM_COUNT as u8 { | ||
| 72 | Some(x + 1) | ||
| 73 | } else { | ||
| 74 | None | ||
| 75 | } | ||
| 76 | }); | ||
| 77 | |||
| 78 | match id { | ||
| 79 | Ok(id) => Some(AlarmHandle::new(id)), | ||
| 80 | Err(_) => None, | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) { | ||
| 85 | self.init(); | ||
| 86 | let mut alarms = unsafe { self.alarms.as_ref() }.lock().unwrap(); | ||
| 87 | let alarm = &mut alarms[alarm.id() as usize]; | ||
| 88 | alarm.closure.replace(Closure::new(move || { | ||
| 89 | callback(ctx); | ||
| 90 | })); | ||
| 91 | } | ||
| 92 | |||
| 93 | fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) { | ||
| 94 | self.init(); | ||
| 95 | let mut alarms = unsafe { self.alarms.as_ref() }.lock().unwrap(); | ||
| 96 | let alarm = &mut alarms[alarm.id() as usize]; | ||
| 97 | let timeout = (timestamp - self.now()) as u32; | ||
| 98 | if let Some(token) = alarm.token { | ||
| 99 | clearTimeout(token); | ||
| 100 | } | ||
| 101 | alarm.token = Some(setTimeout(alarm.closure.as_ref().unwrap(), timeout / 1000)); | ||
| 102 | } | ||
| 103 | } | ||
| 104 | |||
| 105 | pub(crate) struct UninitCell<T>(MaybeUninit<UnsafeCell<T>>); | ||
| 106 | unsafe impl<T> Send for UninitCell<T> {} | ||
| 107 | unsafe impl<T> Sync for UninitCell<T> {} | ||
| 108 | |||
| 109 | impl<T> UninitCell<T> { | ||
| 110 | pub const fn uninit() -> Self { | ||
| 111 | Self(MaybeUninit::uninit()) | ||
| 112 | } | ||
| 113 | unsafe fn as_ptr(&self) -> *const T { | ||
| 114 | (*self.0.as_ptr()).get() | ||
| 115 | } | ||
| 116 | |||
| 117 | pub unsafe fn as_mut_ptr(&self) -> *mut T { | ||
| 118 | (*self.0.as_ptr()).get() | ||
| 119 | } | ||
| 120 | |||
| 121 | pub unsafe fn as_ref(&self) -> &T { | ||
| 122 | &*self.as_ptr() | ||
| 123 | } | ||
| 124 | |||
| 125 | pub unsafe fn write(&self, val: T) { | ||
| 126 | ptr::write(self.as_mut_ptr(), val) | ||
| 127 | } | ||
| 128 | } | ||
| 129 | |||
| 130 | impl<T: Copy> UninitCell<T> { | ||
| 131 | pub unsafe fn read(&self) -> T { | ||
| 132 | ptr::read(self.as_mut_ptr()) | ||
| 133 | } | ||
| 134 | } | ||
diff --git a/embassy-executor/src/time/duration.rs b/embassy-executor/src/time/duration.rs deleted file mode 100644 index dc4f16bd4..000000000 --- a/embassy-executor/src/time/duration.rs +++ /dev/null | |||
| @@ -1,184 +0,0 @@ | |||
| 1 | use core::fmt; | ||
| 2 | use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; | ||
| 3 | |||
| 4 | use super::{GCD_1K, GCD_1M, TICKS_PER_SECOND}; | ||
| 5 | |||
| 6 | #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] | ||
| 7 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] | ||
| 8 | /// Represents the difference between two [Instant](struct.Instant.html)s | ||
| 9 | pub struct Duration { | ||
| 10 | pub(crate) ticks: u64, | ||
| 11 | } | ||
| 12 | |||
| 13 | impl Duration { | ||
| 14 | /// The smallest value that can be represented by the `Duration` type. | ||
| 15 | pub const MIN: Duration = Duration { ticks: u64::MIN }; | ||
| 16 | /// The largest value that can be represented by the `Duration` type. | ||
| 17 | pub const MAX: Duration = Duration { ticks: u64::MAX }; | ||
| 18 | |||
| 19 | /// Tick count of the `Duration`. | ||
| 20 | pub const fn as_ticks(&self) -> u64 { | ||
| 21 | self.ticks | ||
| 22 | } | ||
| 23 | |||
| 24 | /// Convert the `Duration` to seconds, rounding down. | ||
| 25 | pub const fn as_secs(&self) -> u64 { | ||
| 26 | self.ticks / TICKS_PER_SECOND | ||
| 27 | } | ||
| 28 | |||
| 29 | /// Convert the `Duration` to milliseconds, rounding down. | ||
| 30 | pub const fn as_millis(&self) -> u64 { | ||
| 31 | self.ticks * (1000 / GCD_1K) / (TICKS_PER_SECOND / GCD_1K) | ||
| 32 | } | ||
| 33 | |||
| 34 | /// Convert the `Duration` to microseconds, rounding down. | ||
| 35 | pub const fn as_micros(&self) -> u64 { | ||
| 36 | self.ticks * (1_000_000 / GCD_1M) / (TICKS_PER_SECOND / GCD_1M) | ||
| 37 | } | ||
| 38 | |||
| 39 | /// Creates a duration from the specified number of clock ticks | ||
| 40 | pub const fn from_ticks(ticks: u64) -> Duration { | ||
| 41 | Duration { ticks } | ||
| 42 | } | ||
| 43 | |||
| 44 | /// Creates a duration from the specified number of seconds, rounding up. | ||
| 45 | pub const fn from_secs(secs: u64) -> Duration { | ||
| 46 | Duration { | ||
| 47 | ticks: secs * TICKS_PER_SECOND, | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Creates a duration from the specified number of milliseconds, rounding up. | ||
| 52 | pub const fn from_millis(millis: u64) -> Duration { | ||
| 53 | Duration { | ||
| 54 | ticks: div_ceil(millis * (TICKS_PER_SECOND / GCD_1K), 1000 / GCD_1K), | ||
| 55 | } | ||
| 56 | } | ||
| 57 | |||
| 58 | /// Creates a duration from the specified number of microseconds, rounding up. | ||
| 59 | /// NOTE: Delays this small may be inaccurate. | ||
| 60 | pub const fn from_micros(micros: u64) -> Duration { | ||
| 61 | Duration { | ||
| 62 | ticks: div_ceil(micros * (TICKS_PER_SECOND / GCD_1M), 1_000_000 / GCD_1M), | ||
| 63 | } | ||
| 64 | } | ||
| 65 | |||
| 66 | /// Creates a duration from the specified number of seconds, rounding down. | ||
| 67 | pub const fn from_secs_floor(secs: u64) -> Duration { | ||
| 68 | Duration { | ||
| 69 | ticks: secs * TICKS_PER_SECOND, | ||
| 70 | } | ||
| 71 | } | ||
| 72 | |||
| 73 | /// Creates a duration from the specified number of milliseconds, rounding down. | ||
| 74 | pub const fn from_millis_floor(millis: u64) -> Duration { | ||
| 75 | Duration { | ||
| 76 | ticks: millis * (TICKS_PER_SECOND / GCD_1K) / (1000 / GCD_1K), | ||
| 77 | } | ||
| 78 | } | ||
| 79 | |||
| 80 | /// Creates a duration from the specified number of microseconds, rounding down. | ||
| 81 | /// NOTE: Delays this small may be inaccurate. | ||
| 82 | pub const fn from_micros_floor(micros: u64) -> Duration { | ||
| 83 | Duration { | ||
| 84 | ticks: micros * (TICKS_PER_SECOND / GCD_1M) / (1_000_000 / GCD_1M), | ||
| 85 | } | ||
| 86 | } | ||
| 87 | |||
| 88 | /// Adds one Duration to another, returning a new Duration or None in the event of an overflow. | ||
| 89 | pub fn checked_add(self, rhs: Duration) -> Option<Duration> { | ||
| 90 | self.ticks.checked_add(rhs.ticks).map(|ticks| Duration { ticks }) | ||
| 91 | } | ||
| 92 | |||
| 93 | /// Subtracts one Duration to another, returning a new Duration or None in the event of an overflow. | ||
| 94 | pub fn checked_sub(self, rhs: Duration) -> Option<Duration> { | ||
| 95 | self.ticks.checked_sub(rhs.ticks).map(|ticks| Duration { ticks }) | ||
| 96 | } | ||
| 97 | |||
| 98 | /// Multiplies one Duration by a scalar u32, returning a new Duration or None in the event of an overflow. | ||
| 99 | pub fn checked_mul(self, rhs: u32) -> Option<Duration> { | ||
| 100 | self.ticks.checked_mul(rhs as _).map(|ticks| Duration { ticks }) | ||
| 101 | } | ||
| 102 | |||
| 103 | /// Divides one Duration a scalar u32, returning a new Duration or None in the event of an overflow. | ||
| 104 | pub fn checked_div(self, rhs: u32) -> Option<Duration> { | ||
| 105 | self.ticks.checked_div(rhs as _).map(|ticks| Duration { ticks }) | ||
| 106 | } | ||
| 107 | } | ||
| 108 | |||
| 109 | impl Add for Duration { | ||
| 110 | type Output = Duration; | ||
| 111 | |||
| 112 | fn add(self, rhs: Duration) -> Duration { | ||
| 113 | self.checked_add(rhs).expect("overflow when adding durations") | ||
| 114 | } | ||
| 115 | } | ||
| 116 | |||
| 117 | impl AddAssign for Duration { | ||
| 118 | fn add_assign(&mut self, rhs: Duration) { | ||
| 119 | *self = *self + rhs; | ||
| 120 | } | ||
| 121 | } | ||
| 122 | |||
| 123 | impl Sub for Duration { | ||
| 124 | type Output = Duration; | ||
| 125 | |||
| 126 | fn sub(self, rhs: Duration) -> Duration { | ||
| 127 | self.checked_sub(rhs).expect("overflow when subtracting durations") | ||
| 128 | } | ||
| 129 | } | ||
| 130 | |||
| 131 | impl SubAssign for Duration { | ||
| 132 | fn sub_assign(&mut self, rhs: Duration) { | ||
| 133 | *self = *self - rhs; | ||
| 134 | } | ||
| 135 | } | ||
| 136 | |||
| 137 | impl Mul<u32> for Duration { | ||
| 138 | type Output = Duration; | ||
| 139 | |||
| 140 | fn mul(self, rhs: u32) -> Duration { | ||
| 141 | self.checked_mul(rhs) | ||
| 142 | .expect("overflow when multiplying duration by scalar") | ||
| 143 | } | ||
| 144 | } | ||
| 145 | |||
| 146 | impl Mul<Duration> for u32 { | ||
| 147 | type Output = Duration; | ||
| 148 | |||
| 149 | fn mul(self, rhs: Duration) -> Duration { | ||
| 150 | rhs * self | ||
| 151 | } | ||
| 152 | } | ||
| 153 | |||
| 154 | impl MulAssign<u32> for Duration { | ||
| 155 | fn mul_assign(&mut self, rhs: u32) { | ||
| 156 | *self = *self * rhs; | ||
| 157 | } | ||
| 158 | } | ||
| 159 | |||
| 160 | impl Div<u32> for Duration { | ||
| 161 | type Output = Duration; | ||
| 162 | |||
| 163 | fn div(self, rhs: u32) -> Duration { | ||
| 164 | self.checked_div(rhs) | ||
| 165 | .expect("divide by zero error when dividing duration by scalar") | ||
| 166 | } | ||
| 167 | } | ||
| 168 | |||
| 169 | impl DivAssign<u32> for Duration { | ||
| 170 | fn div_assign(&mut self, rhs: u32) { | ||
| 171 | *self = *self / rhs; | ||
| 172 | } | ||
| 173 | } | ||
| 174 | |||
| 175 | impl<'a> fmt::Display for Duration { | ||
| 176 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
| 177 | write!(f, "{} ticks", self.ticks) | ||
| 178 | } | ||
| 179 | } | ||
| 180 | |||
| 181 | #[inline] | ||
| 182 | const fn div_ceil(num: u64, den: u64) -> u64 { | ||
| 183 | (num + den - 1) / den | ||
| 184 | } | ||
diff --git a/embassy-executor/src/time/instant.rs b/embassy-executor/src/time/instant.rs deleted file mode 100644 index 6a4925f47..000000000 --- a/embassy-executor/src/time/instant.rs +++ /dev/null | |||
| @@ -1,159 +0,0 @@ | |||
| 1 | use core::fmt; | ||
| 2 | use core::ops::{Add, AddAssign, Sub, SubAssign}; | ||
| 3 | |||
| 4 | use super::{driver, Duration, GCD_1K, GCD_1M, TICKS_PER_SECOND}; | ||
| 5 | |||
| 6 | #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] | ||
| 7 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] | ||
| 8 | /// An Instant in time, based on the MCU's clock ticks since startup. | ||
| 9 | pub struct Instant { | ||
| 10 | ticks: u64, | ||
| 11 | } | ||
| 12 | |||
| 13 | impl Instant { | ||
| 14 | /// The smallest (earliest) value that can be represented by the `Instant` type. | ||
| 15 | pub const MIN: Instant = Instant { ticks: u64::MIN }; | ||
| 16 | /// The largest (latest) value that can be represented by the `Instant` type. | ||
| 17 | pub const MAX: Instant = Instant { ticks: u64::MAX }; | ||
| 18 | |||
| 19 | /// Returns an Instant representing the current time. | ||
| 20 | pub fn now() -> Instant { | ||
| 21 | Instant { ticks: driver::now() } | ||
| 22 | } | ||
| 23 | |||
| 24 | /// Create an Instant from a tick count since system boot. | ||
| 25 | pub const fn from_ticks(ticks: u64) -> Self { | ||
| 26 | Self { ticks } | ||
| 27 | } | ||
| 28 | |||
| 29 | /// Create an Instant from a microsecond count since system boot. | ||
| 30 | pub const fn from_micros(micros: u64) -> Self { | ||
| 31 | Self { | ||
| 32 | ticks: micros * (TICKS_PER_SECOND / GCD_1M) / (1_000_000 / GCD_1M), | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | /// Create an Instant from a millisecond count since system boot. | ||
| 37 | pub const fn from_millis(millis: u64) -> Self { | ||
| 38 | Self { | ||
| 39 | ticks: millis * (TICKS_PER_SECOND / GCD_1K) / (1000 / GCD_1K), | ||
| 40 | } | ||
| 41 | } | ||
| 42 | |||
| 43 | /// Create an Instant from a second count since system boot. | ||
| 44 | pub const fn from_secs(seconds: u64) -> Self { | ||
| 45 | Self { | ||
| 46 | ticks: seconds * TICKS_PER_SECOND, | ||
| 47 | } | ||
| 48 | } | ||
| 49 | |||
| 50 | /// Tick count since system boot. | ||
| 51 | pub const fn as_ticks(&self) -> u64 { | ||
| 52 | self.ticks | ||
| 53 | } | ||
| 54 | |||
| 55 | /// Seconds since system boot. | ||
| 56 | pub const fn as_secs(&self) -> u64 { | ||
| 57 | self.ticks / TICKS_PER_SECOND | ||
| 58 | } | ||
| 59 | |||
| 60 | /// Milliseconds since system boot. | ||
| 61 | pub const fn as_millis(&self) -> u64 { | ||
| 62 | self.ticks * (1000 / GCD_1K) / (TICKS_PER_SECOND / GCD_1K) | ||
| 63 | } | ||
| 64 | |||
| 65 | /// Microseconds since system boot. | ||
| 66 | pub const fn as_micros(&self) -> u64 { | ||
| 67 | self.ticks * (1_000_000 / GCD_1M) / (TICKS_PER_SECOND / GCD_1M) | ||
| 68 | } | ||
| 69 | |||
| 70 | /// Duration between this Instant and another Instant | ||
| 71 | /// Panics on over/underflow. | ||
| 72 | pub fn duration_since(&self, earlier: Instant) -> Duration { | ||
| 73 | Duration { | ||
| 74 | ticks: self.ticks.checked_sub(earlier.ticks).unwrap(), | ||
| 75 | } | ||
| 76 | } | ||
| 77 | |||
| 78 | /// Duration between this Instant and another Instant | ||
| 79 | pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> { | ||
| 80 | if self.ticks < earlier.ticks { | ||
| 81 | None | ||
| 82 | } else { | ||
| 83 | Some(Duration { | ||
| 84 | ticks: self.ticks - earlier.ticks, | ||
| 85 | }) | ||
| 86 | } | ||
| 87 | } | ||
| 88 | |||
| 89 | /// Returns the duration since the "earlier" Instant. | ||
| 90 | /// If the "earlier" instant is in the future, the duration is set to zero. | ||
| 91 | pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { | ||
| 92 | Duration { | ||
| 93 | ticks: if self.ticks < earlier.ticks { | ||
| 94 | 0 | ||
| 95 | } else { | ||
| 96 | self.ticks - earlier.ticks | ||
| 97 | }, | ||
| 98 | } | ||
| 99 | } | ||
| 100 | |||
| 101 | /// Duration elapsed since this Instant. | ||
| 102 | pub fn elapsed(&self) -> Duration { | ||
| 103 | Instant::now() - *self | ||
| 104 | } | ||
| 105 | |||
| 106 | /// Adds one Duration to self, returning a new `Instant` or None in the event of an overflow. | ||
| 107 | pub fn checked_add(&self, duration: Duration) -> Option<Instant> { | ||
| 108 | self.ticks.checked_add(duration.ticks).map(|ticks| Instant { ticks }) | ||
| 109 | } | ||
| 110 | |||
| 111 | /// Subtracts one Duration to self, returning a new `Instant` or None in the event of an overflow. | ||
| 112 | pub fn checked_sub(&self, duration: Duration) -> Option<Instant> { | ||
| 113 | self.ticks.checked_sub(duration.ticks).map(|ticks| Instant { ticks }) | ||
| 114 | } | ||
| 115 | } | ||
| 116 | |||
| 117 | impl Add<Duration> for Instant { | ||
| 118 | type Output = Instant; | ||
| 119 | |||
| 120 | fn add(self, other: Duration) -> Instant { | ||
| 121 | self.checked_add(other) | ||
| 122 | .expect("overflow when adding duration to instant") | ||
| 123 | } | ||
| 124 | } | ||
| 125 | |||
| 126 | impl AddAssign<Duration> for Instant { | ||
| 127 | fn add_assign(&mut self, other: Duration) { | ||
| 128 | *self = *self + other; | ||
| 129 | } | ||
| 130 | } | ||
| 131 | |||
| 132 | impl Sub<Duration> for Instant { | ||
| 133 | type Output = Instant; | ||
| 134 | |||
| 135 | fn sub(self, other: Duration) -> Instant { | ||
| 136 | self.checked_sub(other) | ||
| 137 | .expect("overflow when subtracting duration from instant") | ||
| 138 | } | ||
| 139 | } | ||
| 140 | |||
| 141 | impl SubAssign<Duration> for Instant { | ||
| 142 | fn sub_assign(&mut self, other: Duration) { | ||
| 143 | *self = *self - other; | ||
| 144 | } | ||
| 145 | } | ||
| 146 | |||
| 147 | impl Sub<Instant> for Instant { | ||
| 148 | type Output = Duration; | ||
| 149 | |||
| 150 | fn sub(self, other: Instant) -> Duration { | ||
| 151 | self.duration_since(other) | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | impl<'a> fmt::Display for Instant { | ||
| 156 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
| 157 | write!(f, "{} ticks", self.ticks) | ||
| 158 | } | ||
| 159 | } | ||
diff --git a/embassy-executor/src/time/mod.rs b/embassy-executor/src/time/mod.rs deleted file mode 100644 index b787a5cf2..000000000 --- a/embassy-executor/src/time/mod.rs +++ /dev/null | |||
| @@ -1,91 +0,0 @@ | |||
| 1 | //! Timekeeping, delays and timeouts. | ||
| 2 | //! | ||
| 3 | //! Timekeeping is done with elapsed time since system boot. Time is represented in | ||
| 4 | //! ticks, where the tick rate is defined by the current driver, usually to match | ||
| 5 | //! the tick rate of the hardware. | ||
| 6 | //! | ||
| 7 | //! Tick counts are 64 bits. At the highest supported tick rate of 1Mhz this supports | ||
| 8 | //! representing time spans of up to ~584558 years, which is big enough for all practical | ||
| 9 | //! purposes and allows not having to worry about overflows. | ||
| 10 | //! | ||
| 11 | //! [`Instant`] represents a given instant of time (relative to system boot), and [`Duration`] | ||
| 12 | //! represents the duration of a span of time. They implement the math operations you'd expect, | ||
| 13 | //! like addition and substraction. | ||
| 14 | //! | ||
| 15 | //! # Delays and timeouts | ||
| 16 | //! | ||
| 17 | //! [`Timer`] allows performing async delays. [`Ticker`] allows periodic delays without drifting over time. | ||
| 18 | //! | ||
| 19 | //! An implementation of the `embedded-hal` delay traits is provided by [`Delay`], for compatibility | ||
| 20 | //! with libraries from the ecosystem. | ||
| 21 | //! | ||
| 22 | //! # Wall-clock time | ||
| 23 | //! | ||
| 24 | //! The `time` module deals exclusively with a monotonically increasing tick count. | ||
| 25 | //! Therefore it has no direct support for wall-clock time ("real life" datetimes | ||
| 26 | //! like `2021-08-24 13:33:21`). | ||
| 27 | //! | ||
| 28 | //! If persistence across reboots is not needed, support can be built on top of | ||
| 29 | //! `embassy_executor::time` by storing the offset between "seconds elapsed since boot" | ||
| 30 | //! and "seconds since unix epoch". | ||
| 31 | //! | ||
| 32 | //! # Time driver | ||
| 33 | //! | ||
| 34 | //! The `time` module is backed by a global "time driver" specified at build time. | ||
| 35 | //! Only one driver can be active in a program. | ||
| 36 | //! | ||
| 37 | //! All methods and structs transparently call into the active driver. This makes it | ||
| 38 | //! possible for libraries to use `embassy_executor::time` in a driver-agnostic way without | ||
| 39 | //! requiring generic parameters. | ||
| 40 | //! | ||
| 41 | //! For more details, check the [`driver`] module. | ||
| 42 | |||
| 43 | #![deny(missing_docs)] | ||
| 44 | |||
| 45 | mod delay; | ||
| 46 | pub mod driver; | ||
| 47 | mod duration; | ||
| 48 | mod instant; | ||
| 49 | mod timer; | ||
| 50 | |||
| 51 | #[cfg(feature = "std")] | ||
| 52 | mod driver_std; | ||
| 53 | |||
| 54 | #[cfg(feature = "wasm")] | ||
| 55 | mod driver_wasm; | ||
| 56 | |||
| 57 | pub use delay::{block_for, Delay}; | ||
| 58 | pub use duration::Duration; | ||
| 59 | pub use instant::Instant; | ||
| 60 | pub use timer::{with_timeout, Ticker, TimeoutError, Timer}; | ||
| 61 | |||
| 62 | #[cfg(feature = "time-tick-1000hz")] | ||
| 63 | const TPS: u64 = 1_000; | ||
| 64 | |||
| 65 | #[cfg(feature = "time-tick-32768hz")] | ||
| 66 | const TPS: u64 = 32_768; | ||
| 67 | |||
| 68 | #[cfg(feature = "time-tick-1mhz")] | ||
| 69 | const TPS: u64 = 1_000_000; | ||
| 70 | |||
| 71 | #[cfg(feature = "time-tick-16mhz")] | ||
| 72 | const TPS: u64 = 16_000_000; | ||
| 73 | |||
| 74 | /// Ticks per second of the global timebase. | ||
| 75 | /// | ||
| 76 | /// This value is specified by the `time-tick-*` Cargo features, which | ||
| 77 | /// should be set by the time driver. Some drivers support a fixed tick rate, others | ||
| 78 | /// allow you to choose a tick rate with Cargo features of their own. You should not | ||
| 79 | /// set the `time-tick-*` features for embassy yourself as an end user. | ||
| 80 | pub const TICKS_PER_SECOND: u64 = TPS; | ||
| 81 | |||
| 82 | const fn gcd(a: u64, b: u64) -> u64 { | ||
| 83 | if b == 0 { | ||
| 84 | a | ||
| 85 | } else { | ||
| 86 | gcd(b, a % b) | ||
| 87 | } | ||
| 88 | } | ||
| 89 | |||
| 90 | pub(crate) const GCD_1K: u64 = gcd(TICKS_PER_SECOND, 1_000); | ||
| 91 | pub(crate) const GCD_1M: u64 = gcd(TICKS_PER_SECOND, 1_000_000); | ||
diff --git a/embassy-executor/src/time/timer.rs b/embassy-executor/src/time/timer.rs deleted file mode 100644 index b9cdb1be5..000000000 --- a/embassy-executor/src/time/timer.rs +++ /dev/null | |||
| @@ -1,151 +0,0 @@ | |||
| 1 | use core::future::Future; | ||
| 2 | use core::pin::Pin; | ||
| 3 | use core::task::{Context, Poll}; | ||
| 4 | |||
| 5 | use futures_util::future::{select, Either}; | ||
| 6 | use futures_util::{pin_mut, Stream}; | ||
| 7 | |||
| 8 | use crate::executor::raw; | ||
| 9 | use crate::time::{Duration, Instant}; | ||
| 10 | |||
| 11 | /// Error returned by [`with_timeout`] on timeout. | ||
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
| 13 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] | ||
| 14 | pub struct TimeoutError; | ||
| 15 | |||
| 16 | /// Runs a given future with a timeout. | ||
| 17 | /// | ||
| 18 | /// If the future completes before the timeout, its output is returned. Otherwise, on timeout, | ||
| 19 | /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned. | ||
| 20 | pub async fn with_timeout<F: Future>(timeout: Duration, fut: F) -> Result<F::Output, TimeoutError> { | ||
| 21 | let timeout_fut = Timer::after(timeout); | ||
| 22 | pin_mut!(fut); | ||
| 23 | match select(fut, timeout_fut).await { | ||
| 24 | Either::Left((r, _)) => Ok(r), | ||
| 25 | Either::Right(_) => Err(TimeoutError), | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | /// A future that completes at a specified [Instant](struct.Instant.html). | ||
| 30 | pub struct Timer { | ||
| 31 | expires_at: Instant, | ||
| 32 | yielded_once: bool, | ||
| 33 | } | ||
| 34 | |||
| 35 | impl Timer { | ||
| 36 | /// Expire at specified [Instant](struct.Instant.html) | ||
| 37 | pub fn at(expires_at: Instant) -> Self { | ||
| 38 | Self { | ||
| 39 | expires_at, | ||
| 40 | yielded_once: false, | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | /// Expire after specified [Duration](struct.Duration.html). | ||
| 45 | /// This can be used as a `sleep` abstraction. | ||
| 46 | /// | ||
| 47 | /// Example: | ||
| 48 | /// ``` no_run | ||
| 49 | /// # #![feature(type_alias_impl_trait)] | ||
| 50 | /// # | ||
| 51 | /// # fn foo() {} | ||
| 52 | /// use embassy_executor::time::{Duration, Timer}; | ||
| 53 | /// | ||
| 54 | /// #[embassy_executor::task] | ||
| 55 | /// async fn demo_sleep_seconds() { | ||
| 56 | /// // suspend this task for one second. | ||
| 57 | /// Timer::after(Duration::from_secs(1)).await; | ||
| 58 | /// } | ||
| 59 | /// ``` | ||
| 60 | pub fn after(duration: Duration) -> Self { | ||
| 61 | Self { | ||
| 62 | expires_at: Instant::now() + duration, | ||
| 63 | yielded_once: false, | ||
| 64 | } | ||
| 65 | } | ||
| 66 | } | ||
| 67 | |||
| 68 | impl Unpin for Timer {} | ||
| 69 | |||
| 70 | impl Future for Timer { | ||
| 71 | type Output = (); | ||
| 72 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
| 73 | if self.yielded_once && self.expires_at <= Instant::now() { | ||
| 74 | Poll::Ready(()) | ||
| 75 | } else { | ||
| 76 | unsafe { raw::register_timer(self.expires_at, cx.waker()) }; | ||
| 77 | self.yielded_once = true; | ||
| 78 | Poll::Pending | ||
| 79 | } | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | /// Asynchronous stream that yields every Duration, indefinitely. | ||
| 84 | /// | ||
| 85 | /// This stream will tick at uniform intervals, even if blocking work is performed between ticks. | ||
| 86 | /// | ||
| 87 | /// For instance, consider the following code fragment. | ||
| 88 | /// ``` no_run | ||
| 89 | /// # #![feature(type_alias_impl_trait)] | ||
| 90 | /// # | ||
| 91 | /// use embassy_executor::time::{Duration, Timer}; | ||
| 92 | /// # fn foo() {} | ||
| 93 | /// | ||
| 94 | /// #[embassy_executor::task] | ||
| 95 | /// async fn ticker_example_0() { | ||
| 96 | /// loop { | ||
| 97 | /// foo(); | ||
| 98 | /// Timer::after(Duration::from_secs(1)).await; | ||
| 99 | /// } | ||
| 100 | /// } | ||
| 101 | /// ``` | ||
| 102 | /// | ||
| 103 | /// This fragment will not call `foo` every second. | ||
| 104 | /// Instead, it will call it every second + the time it took to previously call `foo`. | ||
| 105 | /// | ||
| 106 | /// Example using ticker, which will consistently call `foo` once a second. | ||
| 107 | /// | ||
| 108 | /// ``` no_run | ||
| 109 | /// # #![feature(type_alias_impl_trait)] | ||
| 110 | /// # | ||
| 111 | /// use embassy_executor::time::{Duration, Ticker}; | ||
| 112 | /// use futures::StreamExt; | ||
| 113 | /// # fn foo(){} | ||
| 114 | /// | ||
| 115 | /// #[embassy_executor::task] | ||
| 116 | /// async fn ticker_example_1() { | ||
| 117 | /// let mut ticker = Ticker::every(Duration::from_secs(1)); | ||
| 118 | /// loop { | ||
| 119 | /// foo(); | ||
| 120 | /// ticker.next().await; | ||
| 121 | /// } | ||
| 122 | /// } | ||
| 123 | /// ``` | ||
| 124 | pub struct Ticker { | ||
| 125 | expires_at: Instant, | ||
| 126 | duration: Duration, | ||
| 127 | } | ||
| 128 | |||
| 129 | impl Ticker { | ||
| 130 | /// Creates a new ticker that ticks at the specified duration interval. | ||
| 131 | pub fn every(duration: Duration) -> Self { | ||
| 132 | let expires_at = Instant::now() + duration; | ||
| 133 | Self { expires_at, duration } | ||
| 134 | } | ||
| 135 | } | ||
| 136 | |||
| 137 | impl Unpin for Ticker {} | ||
| 138 | |||
| 139 | impl Stream for Ticker { | ||
| 140 | type Item = (); | ||
| 141 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { | ||
| 142 | if self.expires_at <= Instant::now() { | ||
| 143 | let dur = self.duration; | ||
| 144 | self.expires_at += dur; | ||
| 145 | Poll::Ready(Some(())) | ||
| 146 | } else { | ||
| 147 | unsafe { raw::register_timer(self.expires_at, cx.waker()) }; | ||
| 148 | Poll::Pending | ||
| 149 | } | ||
| 150 | } | ||
| 151 | } | ||
