freertos_rust/
delays.rs

1use crate::base::*;
2use crate::shim::*;
3use crate::task::*;
4use crate::units::*;
5
6/// Delay the current task by the given duration, minus the
7/// time that was spent processing the last wakeup loop.
8pub struct TaskDelay {
9    last_wake_time: FreeRtosTickType,
10}
11
12impl TaskDelay {
13    /// Create a new helper, marking the current time as the start of the
14    /// next measurement.
15    pub fn new() -> TaskDelay {
16        TaskDelay {
17            last_wake_time: FreeRtosUtils::get_tick_count(),
18        }
19    }
20
21    /// Delay the execution of the current task by the given duration,
22    /// minus the time spent in this task since the last delay.
23    pub fn delay_until<D: DurationTicks>(&mut self, delay: D) {
24        unsafe {
25            freertos_rs_vTaskDelayUntil(
26                &mut self.last_wake_time as *mut FreeRtosTickType,
27                delay.to_ticks(),
28            );
29        }
30    }
31}
32
33/// Periodic delay timer.
34///
35/// Use inside a polling loop, for example: the loop polls this instance every second.
36/// The method `should_run` will return true once 30 seconds or more has elapsed
37/// and it will then reset the timer for that period.
38pub struct TaskDelayPeriodic {
39    last_wake_time: FreeRtosTickType,
40    period_ticks: FreeRtosTickType,
41}
42
43impl TaskDelayPeriodic {
44    /// Create a new timer with the set period.
45    pub fn new<D: DurationTicks>(period: D) -> TaskDelayPeriodic {
46        let l = FreeRtosUtils::get_tick_count();
47
48        TaskDelayPeriodic {
49            last_wake_time: l,
50            period_ticks: period.to_ticks(),
51        }
52    }
53
54    /// Has the set period passed? If it has, resets the internal timer.
55    pub fn should_run(&mut self) -> bool {
56        let c = FreeRtosUtils::get_tick_count();
57        if (c - self.last_wake_time) < (self.period_ticks) {
58            false
59        } else {
60            self.last_wake_time = c;
61            true
62        }
63    }
64
65    /// Set a new delay period
66    pub fn set_period<D: DurationTicks>(&mut self, period: D) {
67        self.period_ticks = period.to_ticks();
68    }
69
70    /// Reset the internal timer to zero.
71    pub fn reset(&mut self) {
72        self.last_wake_time = FreeRtosUtils::get_tick_count();
73    }
74}