embedded-timers 0.4.0

Softwaretimers and -delays (ms/us) based on a Clock implementation
Documentation
// 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 crate::clock::Clock;
use embedded_hal::delay::DelayNs;

/// 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> {
    /// Creates a new `Delay` for the given underlying clock
    pub fn new(clock: &'a CLOCK) -> Self {
        Delay { clock }
    }

    /// Blocks execution for (at least) the duration of _delay_
    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);
    }
}