aquarium_control/thermal/manage_cycle_time_thermal.rs
1/* Copyright 2024 Uwe Martin
2
3Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
5The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
7THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8*/
9/// A macro to manage the timing of a fixed-duration loop applicable to both thermal control modules.
10///
11/// This macro encapsulates the logic for:
12/// 1. Calculating the loop's execution duration.
13/// 2. Sleeping for the remaining time to meet the target cycle duration.
14/// 3. Logging a "log-once" warning if the execution time exceeds the target.
15/// 4. Resetting the cycle timer and associated flags for the next iteration.
16#[macro_export]
17macro_rules! manage_cycle_time_thermal {
18 (
19 $start_time:expr,
20 $cycle_time_duration:expr,
21 $cycle_time_millis_const:expr,
22 $spin_sleeper:expr,
23 $lock_warn_cycle_time_exceeded:expr,
24 $actuation_mutex_was_blocked:expr,
25 $location:expr
26 ) => {
27 let stop_time = std::time::Instant::now();
28 let execution_duration = stop_time.duration_since($start_time);
29
30 if execution_duration > $cycle_time_duration {
31 if !$lock_warn_cycle_time_exceeded && !$actuation_mutex_was_blocked {
32 #[cfg(not(test))]
33 warn!(target: $location,
34 "execution duration of {} milliseconds exceeds cycle time of {}",
35 execution_duration.as_millis(),
36 $cycle_time_millis_const);
37 $lock_warn_cycle_time_exceeded = true;
38 }
39 } else {
40 let remaining_sleep_time = $cycle_time_duration - execution_duration;
41 $spin_sleeper.sleep(remaining_sleep_time);
42 $lock_warn_cycle_time_exceeded = false;
43 }
44
45 // Reset the actuation block flag for the next cycle.
46 $actuation_mutex_was_blocked = false;
47
48 // Reset the start time for the next cycle.
49 $start_time = std::time::Instant::now();
50 };
51}