use crate::clock::Clock;
use embedded_hal::delay::DelayNs;
#[derive(Debug)]
pub struct Delay<'a, CLOCK: Clock> {
pub(crate) clock: &'a CLOCK,
}
impl<'a, CLOCK: Clock> Delay<'a, CLOCK> {
pub fn new(clock: &'a CLOCK) -> Self {
Delay { clock }
}
pub fn delay(&mut self, delay: core::time::Duration) {
let mut timer = crate::timer::Timer::new(self.clock);
timer.start(delay);
nb::block!(timer.wait()).unwrap();
}
}
impl<'a, CLOCK: Clock> DelayNs for Delay<'a, CLOCK> {
fn delay_ns(&mut self, ns: u32) {
self.delay(core::time::Duration::from_nanos(ns.into()));
}
}
#[cfg(test)]
mod tests {
use mockall::predicate::*;
use mockall::*;
use crate::clock::Clock;
use crate::instant::Instant32;
use embedded_hal::delay::DelayNs;
mock!(
MyClock {}
impl Clock for MyClock {
type Instant = Instant32<1000>;
fn now(&self) -> Instant32<1000>;
}
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_now()
.once()
.returning(move || Instant32::new(0));
clock
.expect_now()
.once()
.returning(move || Instant32::new(11));
let mut delay = super::Delay::new(&clock);
delay.delay_ms(10);
}
#[test]
pub fn delay_us_basic() {
let mut clock = MockMyClock::new();
clock
.expect_now()
.once()
.returning(move || Instant32::new(0));
clock
.expect_now()
.once()
.returning(move || Instant32::new(1));
let mut delay = super::Delay::new(&clock);
delay.delay_us(10);
}
}