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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
// 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
//! This crate provides Softwaretimers and -delays bases on a Clock implementation.
//!
//! Those Timers are implementing the embedded-hal Timer traits to be easily usable for application and driver code.
//!
//! # Usage
//!
//! The user has to provide a Clock implementation like:
//!
//! ```rust,no_run
//! #[derive(Debug)]
//! pub struct MilliSecondClock;
//!
//! impl embedded_timers::clock::Clock for MilliSecondClock {
//! fn try_now(
//! &self,
//! ) -> Result<embedded_timers::clock::Instant, embedded_timers::clock::ClockError> {
//! let now = std::time::SystemTime::now()
//! .duration_since(std::time::UNIX_EPOCH)
//! .unwrap();
//!
//! Ok(now)
//! }
//! }
//! ```
//!
//! The time base of the actual clock implementation will determinate the time base for all delays and timers.
//!
//! ## Delay
//!
//! From the clock, a delay can be crated. This will perform a busy waiting delay.
//!
//! ```rust,no_run
//! use embedded_timers::clock::Clock;
//! use embedded_hal::blocking::delay::DelayMs;
//! #[derive(Debug)]
//! pub struct MilliSecondClock;
//! # impl Clock for MilliSecondClock {
//! # fn try_now(
//! # &self,
//! # ) -> Result<embedded_timers::clock::Instant, embedded_timers::clock::ClockError> {
//! # let now = std::time::SystemTime::now()
//! # .duration_since(std::time::UNIX_EPOCH)
//! # .unwrap();
//!
//! # Ok(now)
//! # }
//! # }
//!
//! let clock = MilliSecondClock;
//! let mut delay = clock.new_delay();
//!
//! loop {
//! println!("This shows every second");
//! delay.delay_ms(1000_u32);
//! }
//! ```
//!
//! ## Timer
//!
//! The crate provides a convenient timer interface with functionality to check if the timer `is_running` or `is_expired` and how much `duration_left`.
//!
//! ```rust,no_run
//! use embedded_timers::clock::Clock;
//! use embedded_timers::Timer;
//! use embedded_hal::timer::CountDown;
//! #[derive(Debug)]
//! pub struct MilliSecondClock;
//! # impl embedded_timers::clock::Clock for MilliSecondClock {
//! # fn try_now(
//! # &self,
//! # ) -> Result<embedded_timers::clock::Instant, embedded_timers::clock::ClockError> {
//! # let now = std::time::SystemTime::now()
//! # .duration_since(std::time::UNIX_EPOCH)
//! # .unwrap();
//!
//! # Ok(now)
//! # }
//! # }
//! let clock = MilliSecondClock;
//! let mut timer = clock.new_timer();
//!
//! timer.start(std::time::Duration::from_secs(1));
//!
//! loop {
//! if let Ok(expired) = timer.is_expired() {
//! if expired {
//! println!("This shows every second");
//! timer.start(std::time::Duration::from_secs(1));
//! }
//! }
//! }
//! ```
//!
//! The `embedded_timers::Timer` also implements `embedded_hal::timer::CountDown` as this is a common interface for embedded timers.
//!
//! ```rust,no_run
//! use embedded_timers::clock::Clock;
//! use embedded_timers::Timer;
//! use embedded_hal::timer::CountDown;
//! use embedded_hal::blocking::delay::DelayMs;
//! #[derive(Debug)]
//! pub struct MilliSecondClock;
//! # impl embedded_timers::clock::Clock for MilliSecondClock {
//! # fn try_now(
//! # &self,
//! # ) -> Result<embedded_timers::clock::Instant, embedded_timers::clock::ClockError> {
//! # let now = std::time::SystemTime::now()
//! # .duration_since(std::time::UNIX_EPOCH)
//! # .unwrap();
//!
//! # Ok(now)
//! # }
//! # }
//! let clock = MilliSecondClock;
//! let mut timer = clock.new_timer();
//! let mut delay = clock.new_delay();
//!
//! timer.start(std::time::Duration::from_secs(1));
//!
//! loop {
//! match timer.wait() {
//! Err(nb::Error::WouldBlock) => {
//! println!("Timer still running");
//! delay.delay_ms(50_u32);
//! }
//! Err(_) => panic!("TIMER ERROR"),
//! Ok(_) => {
//! println!("This shows every second");
//! timer.start(std::time::Duration::from_secs(1));
//! }
//! }
//! }
//! ```
//!
//! # License
//!
//! Open Logistics Foundation License\
//! Version 1.3, January 2023
//!
//! See the LICENSE file in the top-level directory.
//!
//! # Contact
//!
//! Fraunhofer IML Embedded Rust Group - <embedded-rust@iml.fraunhofer.de>
#![cfg_attr(not(test), no_std)]
#![warn(missing_docs)]
use crate::clock::{Clock, Instant};
use embedded_hal::timer::{Cancel, CountDown};
/// Trait for the application to implement to provide a clock.
pub mod clock;
/// Delays based on Clocks
pub mod delay;
/// Errors which can occur when dealing with this module
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum TimerError {
/// A Timer has not been started
NotRunning,
/// The Clock returned an error while trying to get the current Instant
ClockError(clock::ClockError),
}
#[derive(Debug, Clone, Copy)]
struct Timing {
start_time: Instant,
expiration_time: Instant,
}
/// An instance of a timer tied to a specific Clock and Timing Duration type.
#[derive(Debug)]
pub struct Timer<'a, CLOCK>
where
CLOCK: Clock,
{
/// The Clock this timer is working on
clock: &'a CLOCK,
/// The Timing information of this time. Only present when the timer is running
timing: Option<Timing>,
}
impl<'a, CLOCK> Timer<'a, CLOCK>
where
CLOCK: Clock,
{
/// Create a new Timer tied to a specific clock
pub fn new(clock: &'a CLOCK) -> Self {
Self {
clock,
timing: None,
}
}
/// Get the Duration of the current timer, or Err if it is not running
pub fn duration(&self) -> Result<core::time::Duration, TimerError> {
if let Some(t) = &self.timing {
Ok(t.expiration_time - t.start_time)
} else {
Err(TimerError::NotRunning)
}
}
/// If the timer is running, this is true. If not, it is false.
/// It can also return an error from the Clock.
pub fn is_running(&self) -> Result<bool, TimerError> {
if self.timing.is_some() {
self.is_expired().map(|expired| !expired)
} else {
Ok(false)
}
}
/// If the timer is expired, this is true. If not, it is false.
/// It can also return an error from the Clock.
pub fn is_expired(&self) -> Result<bool, TimerError> {
if let Some(timing) = &self.timing {
let expired =
self.clock.try_now().map_err(TimerError::ClockError)? >= timing.expiration_time;
Ok(expired)
} else {
Err(TimerError::NotRunning)
}
}
/// Get the Duration until expire of the current timer, or Err if it is not running
/// or if "now" could not be calculated
pub fn duration_left(&self) -> Result<core::time::Duration, TimerError> {
match self.clock.try_now() {
Ok(now) => {
if let Some(t) = &self.timing {
Ok(t.expiration_time - now)
} else {
Err(TimerError::NotRunning)
}
}
Err(_) => Err(TimerError::ClockError(clock::ClockError::Unknown)),
}
}
/// Try to start the timer. Can fail due to errors from the clock.
pub fn try_start(&mut self, duration: core::time::Duration) -> Result<(), TimerError> {
let now = self.clock.try_now().map_err(TimerError::ClockError)?;
self.timing = Some(Timing {
expiration_time: now + duration,
start_time: now,
});
Ok(())
}
/// Try to wait for the timer, return an error if it is not running.
pub fn try_wait(&mut self) -> nb::Result<(), TimerError> {
if self.timing.is_some() {
if self.is_expired()? {
self.timing = None;
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
} else {
Err(nb::Error::Other(TimerError::NotRunning))
}
}
}
impl<'a, CLOCK> CountDown for Timer<'a, CLOCK>
where
CLOCK: Clock,
{
type Time = core::time::Duration;
fn start<T: Into<Self::Time>>(&mut self, duration: T) {
// As prescribed by the trait, we cannot return an error here, so we panic.
self.try_start(duration.into())
.expect("Could not start timer!");
}
fn wait(&mut self) -> nb::Result<(), void::Void> {
match self.try_wait() {
Err(nb::Error::Other(_)) => {
// panic if the timer is not running, as prescribed in this traits contract
panic!("Error during wait for timer, probably not running!")
}
Ok(()) => Ok(()),
Err(nb::Error::WouldBlock) => Err(nb::Error::WouldBlock),
}
}
}
impl<'a, CLOCK> Cancel for Timer<'a, CLOCK>
where
CLOCK: Clock,
{
type Error = TimerError;
fn cancel(&mut self) -> Result<(), Self::Error> {
if self.timing.is_some() && !self.is_expired()? {
self.timing = None;
Ok(())
} else {
self.timing = None;
Err(TimerError::NotRunning)
}
}
}
#[cfg(test)]
mod tests {
use mockall::predicate::*;
use mockall::*;
use crate::clock::{Clock, Instant};
use embedded_hal::timer::{Cancel, CountDown};
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]
fn test_clock_mock() {
let mut mymock = MockMyClock::new();
mymock
.expect_try_now()
.once()
.return_once(move || Ok(Instant::from_millis(23)));
assert!(mymock.try_now() == Ok(Instant::from_millis(23)));
mymock
.expect_try_now()
.once()
.return_once(move || Err(crate::clock::ClockError::Unknown));
assert!(mymock.try_now() == Err(crate::clock::ClockError::Unknown));
}
#[test]
fn test_timer_basic() {
let mut clock = MockMyClock::new();
clock
.expect_try_now()
.times(5)
.returning(move || Ok(Instant::from_millis(0)));
clock
.expect_try_now()
.times(2)
.returning(move || Ok(Instant::from_millis(10)));
clock
.expect_try_now()
.times(5)
.returning(|| Ok(Instant::from_millis(1000)));
clock
.expect_try_now()
.times(2)
.returning(move || Ok(Instant::from_millis(2001)));
// Test Creation
let mut timer: crate::Timer<'_, _> = crate::Timer::new(&clock);
assert_eq!(timer.is_running(), Ok(false));
assert_eq!(timer.duration(), Err(crate::TimerError::NotRunning));
assert_eq!(
timer.try_wait(),
Err(nb::Error::Other(crate::TimerError::NotRunning))
);
// Test timer Start
timer.start(core::time::Duration::from_millis(10));
assert_eq!(timer.is_running(), Ok(true));
assert_eq!(timer.duration(), Ok(core::time::Duration::from_millis(10)));
assert_eq!(
timer.duration_left(),
Ok(core::time::Duration::from_millis(10))
);
assert_eq!(timer.is_expired(), Ok(false)); // First call should not be expired
assert_eq!(timer.wait(), Err(nb::Error::WouldBlock)); // Same call but different api
assert_eq!(timer.is_expired(), Ok(true)); // but Third call should be expired
assert_eq!(timer.wait(), Ok(())); // Same call but different api
assert_eq!(timer.is_running(), Ok(false)); // Timer should not be running anymore now
// Restart the timer
timer.start(core::time::Duration::from_secs(1));
assert_eq!(timer.is_running(), Ok(true));
assert_eq!(
timer.duration(),
Ok(core::time::Duration::from_millis(1000))
);
assert_eq!(
timer.duration_left(),
Ok(core::time::Duration::from_millis(1000))
);
assert_eq!(timer.is_expired(), Ok(false)); // First call should not be expired
assert_eq!(timer.wait(), Err(nb::Error::WouldBlock)); // Same call but different api
assert_eq!(timer.is_expired(), Ok(true)); // but Third call should be expired
assert_eq!(timer.wait(), Ok(())); // Same call but different api
assert_eq!(timer.is_running(), Ok(false)); // Timer should not be running anymore now
}
#[test]
fn test_timer_cancel() {
let mut clock = MockMyClock::new();
clock
.expect_try_now()
.times(4)
.returning(move || Ok(Instant::from_millis(0)));
let mut timer: crate::Timer<'_, _> = crate::Timer::new(&clock);
assert_eq!(timer.cancel(), Err(crate::TimerError::NotRunning));
timer.start(core::time::Duration::from_millis(10));
assert_eq!(timer.is_running(), Ok(true));
assert_eq!(timer.cancel(), Ok(()));
assert_eq!(timer.is_running(), Ok(false));
assert_eq!(timer.is_expired(), Err(crate::TimerError::NotRunning)); // Not Running
assert_eq!(timer.cancel(), Err(crate::TimerError::NotRunning));
assert_eq!(timer.duration(), Err(crate::TimerError::NotRunning));
assert_eq!(timer.duration_left(), Err(crate::TimerError::NotRunning));
}
}