Skip to main content

esp_hal/
asynch.rs

1//! Asynchronous utilities.
2use core::{
3    future::poll_fn,
4    task::{Context, Poll, Waker},
5};
6
7use embassy_sync::waitqueue::GenericAtomicWaker;
8use esp_sync::RawMutex;
9
10use crate::time::Instant;
11
12/// Arranges for the task behind `cx` to be polled again no later than `deadline`.
13///
14/// With the `embassy-time-05` feature this schedules a timer wake-up. Without it, the task is woken
15/// immediately, so it keeps busy-polling until the deadline.
16pub(crate) fn wake_at(deadline: Instant, cx: &mut Context<'_>) {
17    cfg_select! {
18        feature = "embassy-time-05" => {
19            use core::future::Future;
20
21            let remaining = deadline.saturating_sub(Instant::now());
22            let mut timer = embassy_time_05::Timer::after_micros(remaining.as_micros());
23            let _ = core::pin::Pin::new(&mut timer).poll(cx);
24        }
25        _ => {
26            let _ = deadline;
27            cx.waker().wake_by_ref();
28        }
29    }
30}
31
32/// Waits until `deadline`. See [`wake_at`].
33pub(crate) async fn wait_until(deadline: Instant) {
34    poll_fn(|cx| {
35        if Instant::now() >= deadline {
36            Poll::Ready(())
37        } else {
38            wake_at(deadline, cx);
39            Poll::Pending
40        }
41    })
42    .await
43}
44
45/// Utility struct to register and wake a waker.
46pub struct AtomicWaker {
47    waker: GenericAtomicWaker<RawMutex>,
48}
49
50impl AtomicWaker {
51    /// Creates a new `AtomicWaker`.
52    #[allow(clippy::new_without_default)]
53    pub const fn new() -> Self {
54        Self {
55            waker: GenericAtomicWaker::new(RawMutex::new()),
56        }
57    }
58
59    /// Registers a waker. Overwrites the previous waker, if any.
60    #[inline]
61    pub fn register(&self, w: &Waker) {
62        self.waker.register(w);
63    }
64
65    /// Wakes the registered waker, if any.
66    #[crate::ram]
67    pub fn wake(&self) {
68        self.waker.wake();
69    }
70}