freertos_rust/
units.rs

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