Skip to main content

m5stack_core/io/
pps_plan.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! What each PPS slot does, decided without I/O.
3//!
4//! Hardware-free on purpose: it compiles on the host, where `cargo test` runs
5//! the tests below. [`crate::io::pps`] executes what [`Planner::plan`] picks.
6
7/// Slot length. A slot holds one transaction of at most ~1 ms; the rest is the
8/// gap the module needs before it answers the next one.
9pub const PPS_SLOT_MS: u64 = 25;
10
11/// The least time from the end of one transaction to the start of the next:
12/// the module NACKs one addressed right after another. A slot's transaction
13/// ends ~1 ms in, so on time the slot grid keeps this with room to spare.
14pub const PPS_MIN_GAP_MS: u64 = PPS_SLOT_MS - 2;
15
16/// When the next slot starts, in µs, given when this one started and when its
17/// transaction ended (`end == start` without one). On time that is the next
18/// grid point. Late, a stalled executor, it is a full [`PPS_MIN_GAP_MS`] after
19/// the end: missed slots are skipped, never run back to back to catch up.
20pub fn next_slot_start(start_us: u64, end_us: u64) -> u64 {
21    (start_us + PPS_SLOT_MS * 1000).max(end_us + PPS_MIN_GAP_MS * 1000)
22}
23
24/// Every this many ticks, the tick's second read becomes the [`Slot::Aux`]
25/// transaction: once a second at [`PPS_TICK_MS`] 100 ms.
26pub const AUX_EVERY_TICKS: u32 = 10;
27
28/// The slot at `index` of tick `tick`. With an auxiliary transaction, the
29/// second read of every [`AUX_EVERY_TICKS`]th tick is it, so it is spaced from
30/// the module's traffic like any other slot.
31pub fn slot_at(tick: u32, index: usize, aux: bool) -> Slot {
32    if aux && index == SCHEDULE.len() - 1 && tick.is_multiple_of(AUX_EVERY_TICKS) {
33        Slot::Aux
34    } else {
35        SCHEDULE[index]
36    }
37}
38
39/// What a slot is for. A slot runs at most one transaction.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Slot {
42    /// Deliver the command: the setpoints, or ENABLE = 0 if a disable is due.
43    Command,
44    /// Read the bank back.
45    Read,
46    /// Correct ENABLE if the bank disagrees with the setpoint.
47    Enable,
48    /// Another device on the same bus, at its slot (see [`slot_at`]).
49    Aux,
50}
51
52/// One tick. Every write slot is followed by a read slot, so each write is
53/// verified before the next one, and no slot is ever back to back with
54/// another transaction: they are [`PPS_SLOT_MS`] apart.
55pub const SCHEDULE: [Slot; 4] = [Slot::Command, Slot::Read, Slot::Enable, Slot::Read];
56
57/// A tick: one pass through [`SCHEDULE`].
58pub const PPS_TICK_MS: u64 = PPS_SLOT_MS * SCHEDULE.len() as u64;
59
60/// What the module should hold. Sampled every slot.
61#[derive(Clone, Copy, Debug)]
62pub struct PpsSetpoint {
63    /// Not written while either is NaN: no value is better than a stale one.
64    pub voltage: f32,
65    pub current: f32,
66    /// `None` leaves ENABLE as it is.
67    pub enabled: Option<bool>,
68}
69
70/// The part of a bank read that planning depends on.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct Held {
73    pub enabled: bool,
74    pub voltage_set: f32,
75    pub current_set: f32,
76}
77
78/// The one transaction a slot decided on.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub enum Transaction {
81    Setpoints { voltage: f32, current: f32 },
82    Enable(bool),
83    Read,
84}
85
86impl Transaction {
87    pub fn name(&self) -> &'static str {
88        match self {
89            Transaction::Setpoints { .. } => "setpoints",
90            Transaction::Enable(true) => "enable",
91            Transaction::Enable(false) => "disable",
92            Transaction::Read => "read",
93        }
94    }
95}
96
97/// What the loop knows: the module's last bank read and what it last wrote.
98#[derive(Clone, Copy, Debug, Default)]
99pub struct Planner {
100    held: Option<Held>,
101    written: Option<(f32, f32)>,
102}
103
104impl Planner {
105    pub const fn new() -> Self {
106        Self {
107            held: None,
108            written: None,
109        }
110    }
111
112    /// A setpoint write succeeded.
113    pub fn wrote(&mut self, voltage: f32, current: f32) {
114        self.written = Some((voltage, current));
115    }
116
117    /// A bank read succeeded.
118    pub fn read(&mut self, held: Held) {
119        self.held = Some(held);
120    }
121
122    /// `held` contains exactly the setpoints last written, bit for bit.
123    pub fn holds(&self, held: &Held) -> bool {
124        self.written.is_some_and(|(v, i)| {
125            held.voltage_set.to_bits() == v.to_bits() && held.current_set.to_bits() == i.to_bits()
126        })
127    }
128
129    /// ENABLE = 0 is due whenever it is asked for and not known to be done.
130    fn disable_due(&self, sp: &PpsSetpoint) -> bool {
131        sp.enabled == Some(false) && self.held.is_none_or(|h| h.enabled)
132    }
133
134    /// ENABLE = 1 only once the module holds what was last written. Not the
135    /// latest setpoint: that moves every tick while charging, so it may never
136    /// match.
137    fn enable_due(&self, sp: &PpsSetpoint) -> bool {
138        sp.enabled == Some(true) && self.held.is_some_and(|h| !h.enabled && self.holds(&h))
139    }
140
141    /// The transaction for `slot`, or none if nothing is due.
142    pub fn plan(&self, slot: Slot, sp: &PpsSetpoint) -> Option<Transaction> {
143        match slot {
144            Slot::Read => Some(Transaction::Read),
145            // A disable takes the first write slot it can get.
146            Slot::Command | Slot::Enable if self.disable_due(sp) => {
147                Some(Transaction::Enable(false))
148            }
149            Slot::Command if sp.voltage.is_finite() && sp.current.is_finite() => {
150                Some(Transaction::Setpoints {
151                    voltage: sp.voltage,
152                    current: sp.current,
153                })
154            }
155            Slot::Enable if self.enable_due(sp) => Some(Transaction::Enable(true)),
156            Slot::Command | Slot::Enable | Slot::Aux => None,
157        }
158    }
159}
160
161#[cfg(test)]
162mod spacing_tests {
163    use super::*;
164
165    const MS: u64 = 1000;
166
167    #[test]
168    fn on_time_the_grid_holds() {
169        assert_eq!(next_slot_start(0, MS), PPS_SLOT_MS * MS);
170        assert_eq!(next_slot_start(0, 0), PPS_SLOT_MS * MS, "an empty slot");
171    }
172
173    /// The defect this exists for: a stalled loop used to fire every missed
174    /// tick at once, back to back, which the module NACKs.
175    #[test]
176    fn late_skips_missed_slots_and_keeps_the_gap() {
177        // Woken 100 ms late: the transaction runs at 100 ms, ends at 101 ms.
178        let next = next_slot_start(0, 101 * MS);
179        assert_eq!(next, (101 + PPS_MIN_GAP_MS) * MS);
180        // And the grid resumes from there.
181        assert_eq!(next_slot_start(next, next + MS), next + PPS_SLOT_MS * MS);
182    }
183
184    #[test]
185    fn no_two_transactions_closer_than_the_gap() {
186        let mut start = 0;
187        for stall_ms in [0, 30, 0, 250, 1, 24, 26, 0] {
188            let end = start + stall_ms * MS + MS;
189            let next = next_slot_start(start, end);
190            assert!(next >= end + PPS_MIN_GAP_MS * MS, "stall {stall_ms} ms");
191            start = next;
192        }
193    }
194
195    #[test]
196    fn aux_takes_one_read_a_second_and_only_with_aux() {
197        let aux_slots: std::vec::Vec<(u32, usize)> = (0..20)
198            .flat_map(|tick| (0..SCHEDULE.len()).map(move |i| (tick, i)))
199            .filter(|&(tick, i)| slot_at(tick, i, true) == Slot::Aux)
200            .collect();
201        assert_eq!(aux_slots, [(0, 3), (10, 3)]);
202        assert!((0..20).all(|tick| (0..4).all(|i| slot_at(tick, i, false) != Slot::Aux)));
203        // The tick it replaces still reads once.
204        assert_eq!(slot_at(0, 1, true), Slot::Read);
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    const ON: PpsSetpoint = PpsSetpoint {
213        voltage: 27.0,
214        current: 1.5,
215        enabled: Some(true),
216    };
217    const OFF: PpsSetpoint = PpsSetpoint {
218        voltage: 0.0,
219        current: 0.0,
220        enabled: Some(false),
221    };
222
223    fn held(enabled: bool, voltage_set: f32, current_set: f32) -> Held {
224        Held {
225            enabled,
226            voltage_set,
227            current_set,
228        }
229    }
230
231    #[test]
232    fn every_write_slot_is_followed_by_a_read() {
233        for (i, slot) in SCHEDULE.iter().enumerate() {
234            let next = SCHEDULE[(i + 1) % SCHEDULE.len()];
235            if *slot != Slot::Read {
236                assert_eq!(
237                    next,
238                    Slot::Read,
239                    "slot {i} ({slot:?}) is not verified by the next one"
240                );
241            }
242        }
243        assert_eq!(PPS_TICK_MS, 100);
244    }
245
246    #[test]
247    fn read_slots_always_read() {
248        let p = Planner::new();
249        for sp in [
250            ON,
251            OFF,
252            PpsSetpoint {
253                voltage: f32::NAN,
254                current: f32::NAN,
255                enabled: None,
256            },
257        ] {
258            assert_eq!(p.plan(Slot::Read, &sp), Some(Transaction::Read));
259        }
260    }
261
262    #[test]
263    fn a_disable_takes_both_write_slots_even_before_any_read() {
264        let mut p = Planner::new();
265        assert_eq!(
266            p.plan(Slot::Command, &OFF),
267            Some(Transaction::Enable(false))
268        );
269        assert_eq!(p.plan(Slot::Enable, &OFF), Some(Transaction::Enable(false)));
270        p.read(held(true, 27.0, 1.5));
271        assert_eq!(
272            p.plan(Slot::Command, &OFF),
273            Some(Transaction::Enable(false)),
274            "still enabled"
275        );
276        p.read(held(false, 27.0, 1.5));
277        assert_eq!(
278            p.plan(Slot::Enable, &OFF),
279            None,
280            "done, nothing more to send"
281        );
282        assert_eq!(
283            p.plan(Slot::Command, &OFF),
284            Some(Transaction::Setpoints {
285                voltage: 0.0,
286                current: 0.0
287            }),
288            "once off, the command slot writes the setpoints again"
289        );
290    }
291
292    #[test]
293    fn nan_setpoints_are_never_written() {
294        let p = Planner::new();
295        for (voltage, current) in [
296            (f32::NAN, 1.0),
297            (27.0, f32::NAN),
298            (f32::NAN, f32::NAN),
299            (f32::INFINITY, 1.0),
300        ] {
301            let sp = PpsSetpoint {
302                voltage,
303                current,
304                enabled: None,
305            };
306            assert_eq!(p.plan(Slot::Command, &sp), None, "{voltage} V {current} A");
307        }
308    }
309
310    #[test]
311    fn enable_waits_for_the_bank_to_hold_what_was_written() {
312        let mut p = Planner::new();
313        assert_eq!(p.plan(Slot::Enable, &ON), None, "nothing read yet");
314        p.wrote(27.0, 1.5);
315        p.read(held(false, 0.0, 0.0));
316        assert_eq!(p.plan(Slot::Enable, &ON), None, "the write has not landed");
317        p.read(held(false, 27.0, 1.5));
318        assert_eq!(p.plan(Slot::Enable, &ON), Some(Transaction::Enable(true)));
319        p.read(held(true, 27.0, 1.5));
320        assert_eq!(p.plan(Slot::Enable, &ON), None, "already enabled");
321    }
322
323    /// Charging moves the current every tick; enabling against the latest value
324    /// could wait forever after a module reset.
325    #[test]
326    fn enable_compares_with_the_last_write_not_the_latest_setpoint() {
327        let mut p = Planner::new();
328        p.wrote(27.0, 1.5);
329        p.read(held(false, 27.0, 1.5));
330        let moved = PpsSetpoint { current: 1.6, ..ON };
331        assert_eq!(
332            p.plan(Slot::Enable, &moved),
333            Some(Transaction::Enable(true))
334        );
335    }
336
337    #[test]
338    fn enable_none_never_touches_enable() {
339        let mut p = Planner::new();
340        let hands_off = PpsSetpoint {
341            voltage: 27.0,
342            current: 1.5,
343            enabled: None,
344        };
345        p.wrote(27.0, 1.5);
346        for h in [held(false, 27.0, 1.5), held(true, 27.0, 1.5)] {
347            p.read(h);
348            assert_eq!(p.plan(Slot::Enable, &hands_off), None);
349            assert_eq!(
350                p.plan(Slot::Command, &hands_off),
351                Some(Transaction::Setpoints {
352                    voltage: 27.0,
353                    current: 1.5
354                })
355            );
356        }
357    }
358
359    #[test]
360    fn holds_compares_bits_not_closeness() {
361        let mut p = Planner::new();
362        p.wrote(27.0, 1.5);
363        assert!(p.holds(&held(false, 27.0, 1.5)));
364        assert!(!p.holds(&held(false, 27.0, 1.5 + f32::EPSILON)));
365        assert!(
366            !Planner::new().holds(&held(false, 27.0, 1.5)),
367            "nothing written yet"
368        );
369    }
370}