use embedded_hal::blocking::delay::{DelayMs, DelayUs};
use crate::clock::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);
}
}