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
// 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

/// Time passed since the start of the application.
pub type Instant = core::time::Duration;

/// Various errors a Clock may return
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum ClockError {
    /// The clock has not been started yet
    NotRunning,
    /// The clocks accumulating variable has overflown
    Overflow,
    /// An unknown error occurred
    Unknown,
}

/// Implement this trait for your Clock(s). The time is measured since the start of the
/// application, using a alias to the [`core::time::Duration`] type.
pub trait Clock: Sized + core::fmt::Debug {
    /// Try to get the time since the application started
    fn try_now(&self) -> Result<Instant, ClockError>;

    /// Generate a new DelayMS + DelayUS Delay
    fn new_delay(&self) -> crate::delay::Delay<Self>
    where
        Self: Sized,
    {
        crate::delay::Delay { clock: self }
    }

    /// Generate a new timer
    fn new_timer(&self) -> crate::Timer<Self> {
        crate::Timer::new(self)
    }

    /// Generate and start a new timer
    fn new_timer_running(&self, duration: core::time::Duration) -> crate::Timer<Self> {
        use embedded_hal::timer::CountDown;
        let mut timer = crate::Timer::new(self);
        timer.start(duration);
        timer
    }
}