freertos_rs/
units.rs

1use crate::prelude::v1::*;
2use crate::shim::*;
3use crate::base::FreeRtosTickType;
4
5pub trait FreeRtosTimeUnits {
6    #[inline]
7    fn get_tick_period_ms() -> u32;
8    #[inline]
9    fn get_max_wait() -> u32;
10}
11
12#[derive(Copy, Clone, Default)]
13pub struct FreeRtosTimeUnitsShimmed;
14impl FreeRtosTimeUnits for FreeRtosTimeUnitsShimmed {
15    #[inline]
16    fn get_tick_period_ms() -> u32 {
17        unsafe { freertos_rs_get_portTICK_PERIOD_MS() }
18    }
19    #[inline]
20    fn get_max_wait() -> u32 {
21        unsafe { freertos_rs_max_wait() }
22    }
23}
24
25pub trait DurationTicks : Copy + Clone {
26    /// Convert to ticks, the internal time measurement unit of FreeRTOS
27    fn to_ticks(&self) -> FreeRtosTickType;
28}
29
30pub type Duration = DurationImpl<FreeRtosTimeUnitsShimmed>;
31
32/// Time unit used by FreeRTOS, passed to the scheduler as ticks.
33#[derive(Debug, Copy, Clone, PartialEq, Eq)]
34pub struct DurationImpl<T> {
35    ticks: u32,
36    _time_units: PhantomData<T>
37}
38
39impl<T> DurationImpl<T> where T: FreeRtosTimeUnits + Copy {
40    /// Milliseconds constructor
41    pub fn ms(milliseconds: u32) -> Self {
42        Self::ticks(milliseconds / T::get_tick_period_ms())
43    }
44
45    pub fn ticks(ticks: u32) -> Self {
46        DurationImpl { ticks: ticks, _time_units: PhantomData }
47    }
48
49    /// An infinite duration
50    pub fn infinite() -> Self {
51        Self::ticks(T::get_max_wait())
52    }
53
54    /// A duration of zero, for non-blocking calls
55    pub fn zero() -> Self {
56        Self::ticks(0)
57    }
58
59    /// Smallest unit of measurement, one tick
60    pub fn eps() -> Self {
61        Self::ticks(1)
62    }
63
64    pub fn to_ms(&self) -> u32 {
65        self.ticks * T::get_tick_period_ms()
66    }
67}
68
69impl<T> DurationTicks for DurationImpl<T> where T: FreeRtosTimeUnits + Copy {
70    fn to_ticks(&self) -> FreeRtosTickType {
71        self.ticks
72    }
73}