freertos_rust/
units.rs

1use crate::base::FreeRtosTickType;
2use crate::prelude::v1::*;
3use crate::shim::*;
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>
38where
39    T: FreeRtosTimeUnits + Copy,
40{
41    /// Milliseconds constructor
42    pub fn ms(milliseconds: u32) -> Self {
43        Self::ticks(milliseconds / T::get_tick_period_ms())
44    }
45
46    pub fn ticks(ticks: u32) -> Self {
47        DurationImpl {
48            ticks: ticks,
49            _time_units: PhantomData,
50        }
51    }
52
53    /// An infinite duration
54    pub fn infinite() -> Self {
55        Self::ticks(T::get_max_wait())
56    }
57
58    /// A duration of zero, for non-blocking calls
59    pub fn zero() -> Self {
60        Self::ticks(0)
61    }
62
63    /// Smallest unit of measurement, one tick
64    pub fn eps() -> Self {
65        Self::ticks(1)
66    }
67
68    pub fn to_ms(&self) -> u32 {
69        self.ticks * T::get_tick_period_ms()
70    }
71}
72
73impl<T> DurationTicks for DurationImpl<T>
74where
75    T: FreeRtosTimeUnits + Copy,
76{
77    fn to_ticks(&self) -> FreeRtosTickType {
78        self.ticks
79    }
80}