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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright Open Logistics Foundation
//
// Licensed under the Open Logistics Foundation License 1.3.
// For details on the licensing terms, see the LICENSE file.
// SPDX-License-Identifier: OLFL-1.3

use embedded_hal::blocking::delay::{DelayMs, DelayUs};

use crate::clock::Clock;

/// An instance of a delay tied to a specific Clock.
#[derive(Debug)]
pub struct Delay<'a, CLOCK: Clock> {
    pub(crate) clock: &'a CLOCK,
}

impl<'a, CLOCK: Clock> Delay<'a, CLOCK> {
    fn wait(&mut self, delay: core::time::Duration) {
        use embedded_hal::timer::CountDown;
        let mut timer = super::Timer::new(self.clock);
        timer.start(delay);
        nb::block!(timer.wait()).unwrap();
    }
}

impl<'a, CLOCK, U> DelayMs<U> for Delay<'a, CLOCK>
where
    CLOCK: Clock,
    U: Into<u64>,
{
    fn delay_ms(&mut self, delay: U) {
        self.wait(core::time::Duration::from_millis(delay.into()));
    }
}
impl<'a, CLOCK, U> DelayUs<U> for Delay<'a, CLOCK>
where
    CLOCK: Clock,
    U: Into<u64>,
{
    fn delay_us(&mut self, delay: U) {
        self.wait(core::time::Duration::from_micros(delay.into()));
    }
}

#[cfg(test)]
mod tests {
    use mockall::predicate::*;
    use mockall::*;

    use crate::clock::{Clock, Instant};
    use embedded_hal::blocking::delay::{DelayMs, DelayUs};

    mock!(
        MyClock {}

        impl Clock for MyClock {
            fn try_now(&self) -> Result<Instant, crate::clock::ClockError>;
        }

        impl core::fmt::Debug for MyClock {
            fn fmt<'a>(&self, f: &mut core::fmt::Formatter<'a>) -> Result<(), core::fmt::Error> {
                write!(f, "Clock Debug")
            }
        }
    );

    #[test]
    pub fn delay_ms_basic() {
        let mut clock = MockMyClock::new();
        clock
            .expect_try_now()
            .once()
            .returning(move || Ok(Instant::from_millis(0)));
        clock
            .expect_try_now()
            .once()
            .returning(move || Ok(Instant::from_millis(11)));

        let mut delay = clock.new_delay();
        delay.delay_ms(10_u8);
    }

    #[test]
    pub fn delay_us_basic() {
        let mut clock = MockMyClock::new();
        clock
            .expect_try_now()
            .once()
            .returning(move || Ok(Instant::from_millis(0)));
        clock
            .expect_try_now()
            .once()
            .returning(move || Ok(Instant::from_millis(1)));

        let mut delay = clock.new_delay();
        delay.delay_us(10_u32);
    }
}