freertos_next/
delays.rs

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