1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use super::DelayMs;
use crate::Scheduler;
use core::{
    pin::Pin,
    task::{Context, Poll},
};
use embedded_hal::timer::{Cancel, CountDown};
use fugit::MillisDurationU32;

pub struct Timer<T, S> {
    timer: T,
    scheduler: S,
}

impl<T, S> Timer<T, S> {
    pub const fn new(timer: T, scheduler: S) -> Self {
        Self { timer, scheduler }
    }
}

impl<T, S> DelayMs for Timer<T, S>
where
    T: CountDown + Cancel + Unpin,
    T::Time: From<MillisDurationU32>,
    S: Scheduler + Unpin,
{
    type Delay = u32;
    type Error = T::Error;

    fn start(&mut self, ms: Self::Delay) -> Result<(), Self::Error> {
        self.timer.start(MillisDurationU32::millis(ms));
        Ok(())
    }

    fn cancel(&mut self) -> Result<(), Self::Error> {
        self.timer.cancel()
    }

    fn poll_delay_ms(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        match self.timer.wait() {
            Ok(()) => Poll::Ready(Ok(())),
            Err(nb::Error::Other(_void)) => unreachable!(),
            Err(nb::Error::WouldBlock) => {
                self.scheduler.schedule(cx.waker());
                Poll::Pending
            }
        }
    }
}