embedded_timers/
delay.rs

1// Copyright Open Logistics Foundation
2//
3// Licensed under the Open Logistics Foundation License 1.3.
4// For details on the licensing terms, see the LICENSE file.
5// SPDX-License-Identifier: OLFL-1.3
6
7use crate::clock::Clock;
8use embedded_hal::delay::DelayNs;
9
10/// An instance of a delay tied to a specific Clock.
11#[derive(Debug)]
12pub struct Delay<'a, CLOCK: Clock> {
13    pub(crate) clock: &'a CLOCK,
14}
15
16impl<'a, CLOCK: Clock> Delay<'a, CLOCK> {
17    /// Creates a new `Delay` for the given underlying clock
18    pub fn new(clock: &'a CLOCK) -> Self {
19        Delay { clock }
20    }
21
22    /// Blocks execution for (at least) the duration of _delay_
23    pub fn delay(&mut self, delay: core::time::Duration) {
24        let mut timer = crate::timer::Timer::new(self.clock);
25        timer.start(delay);
26        nb::block!(timer.wait()).unwrap();
27    }
28}
29
30impl<'a, CLOCK: Clock> DelayNs for Delay<'a, CLOCK> {
31    fn delay_ns(&mut self, ns: u32) {
32        self.delay(core::time::Duration::from_nanos(ns.into()));
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use mockall::predicate::*;
39    use mockall::*;
40
41    use crate::clock::Clock;
42    use crate::instant::Instant32;
43    use embedded_hal::delay::DelayNs;
44
45    mock!(
46        MyClock {}
47
48        impl Clock for MyClock {
49            type Instant = Instant32<1000>;
50            fn now(&self) -> Instant32<1000>;
51        }
52
53        impl core::fmt::Debug for MyClock {
54            fn fmt<'a>(&self, f: &mut core::fmt::Formatter<'a>) -> Result<(), core::fmt::Error> {
55                write!(f, "Clock Debug")
56            }
57        }
58    );
59
60    #[test]
61    pub fn delay_ms_basic() {
62        let mut clock = MockMyClock::new();
63        clock
64            .expect_now()
65            .once()
66            .returning(move || Instant32::new(0));
67        clock
68            .expect_now()
69            .once()
70            .returning(move || Instant32::new(11));
71
72        let mut delay = super::Delay::new(&clock);
73        delay.delay_ms(10);
74    }
75
76    #[test]
77    pub fn delay_us_basic() {
78        let mut clock = MockMyClock::new();
79        clock
80            .expect_now()
81            .once()
82            .returning(move || Instant32::new(0));
83        clock
84            .expect_now()
85            .once()
86            .returning(move || Instant32::new(1));
87
88        let mut delay = super::Delay::new(&clock);
89        delay.delay_us(10);
90    }
91}