Skip to main content

m5stack_core/io/
pps.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The PPS link: one transaction per 25 ms slot, so a tick never skips a beat.
3//!
4//! The module NACKs a transaction addressed right after another one ended, so
5//! no two transactions ever run back to back. [`SCHEDULE`] gives each 25 ms
6//! slot one purpose; per 100 ms tick:
7//!
8//! | Slot | Purpose | Transaction |
9//! |---|---|---|
10//! | 0 | [`Slot::Command`] | write the setpoints (or ENABLE = 0, if a disable is due) |
11//! | 1 | [`Slot::Read`] | read the bank `0x04..=0x1F` |
12//! | 2 | [`Slot::Enable`] | write ENABLE, only if the bank disagrees with the setpoint |
13//! | 3 | [`Slot::Read`] | read the bank |
14//!
15//! So a command reaches the module within one tick, a reading is never older
16//! than 50 ms, and every write is verified by the next read. The spacing is
17//! enforced, not assumed: a stalled executor skips slots ([`next_slot_start`])
18//! instead of running them back to back, and the board's power read, which
19//! shares the bus, takes a slot of its own once a second ([`Slot::Aux`]). The output is only
20//! enabled once the bank shows the commanded setpoints: the module applies them
21//! whether or not it is enabled, so enabling first would run the old ones.
22//!
23//! The loop never stops. A failing link is reported as an episode (first error,
24//! then once a second, then recovery); a module that never answered is probed
25//! once a second rather than at the slot rate.
26use embassy_time::{Duration, Instant, Timer};
27
28use crate::driver::pps::{ADDRESS, PpsBank, PpsDriver};
29pub use crate::driver::pps::{PpsError, PpsRunningMode};
30use crate::io::pps_plan::{Held, Planner, Transaction};
31use crate::io::pps_plan::{PPS_MIN_GAP_MS, next_slot_start, slot_at};
32pub use crate::io::pps_plan::{PPS_SLOT_MS, PPS_TICK_MS, PpsSetpoint, SCHEDULE, Slot};
33use crate::io::shared_i2c::SharedI2cBus;
34
35/// One bank read, as the consumer sees it.
36pub struct PpsReadings {
37    pub voltage: f32,
38    pub current: f32,
39    pub temperature: f32,
40    pub input_voltage: f32,
41    pub running_mode: PpsRunningMode,
42    /// ENABLE and the setpoints as the module holds them.
43    pub enabled: bool,
44    pub voltage_set: f32,
45    pub current_set: f32,
46    /// The module holds exactly the setpoints this loop last wrote. False
47    /// after a module reset (they read 0) until the next write lands.
48    pub delivered: bool,
49    /// The module refreshed its measurements since the previous read. A read
50    /// that is not fresh repeats old measurements.
51    pub fresh: bool,
52    /// Readings rejected as implausible since boot.
53    pub rejected: u32,
54}
55
56pub struct PpsResources {
57    pub i2c: &'static SharedI2cBus,
58    /// The board's USB-power read ([`crate::board::usb_powered`]) on the same
59    /// bus, once a second in its own slot: `Some(on_usb)`, or `None` when the
60    /// PMIC did not answer. Store it and return; it runs inside the PPS loop.
61    pub on_usb_power: Option<fn(Option<bool>)>,
62}
63
64/// Period of the probe while the module has never answered.
65const PROBE_PERIOD: Duration = Duration::from_secs(1);
66/// How often an ongoing error episode is reported.
67const EPISODE_REPORT: Duration = Duration::from_secs(1);
68/// How often the link reports its transaction count, so a quiet log proves a
69/// live link rather than a stopped loop.
70const SUMMARY_PERIOD: Duration = Duration::from_secs(60);
71
72/// Error episodes: every error is counted, the first and the end are logged
73/// at once, an ongoing one once a second.
74struct Link {
75    errors: u32,
76    since: Instant,
77    reported: Instant,
78    /// Transactions and failures in the current summary window.
79    done: u32,
80    failed: u32,
81    window: Instant,
82}
83
84impl Link {
85    fn new() -> Self {
86        Self {
87            errors: 0,
88            since: Instant::now(),
89            reported: Instant::now(),
90            done: 0,
91            failed: 0,
92            window: Instant::now(),
93        }
94    }
95
96    fn summarize(&mut self) {
97        let span = self.window.elapsed();
98        if span >= SUMMARY_PERIOD {
99            info!(
100                "PPS link: {} transactions, {} failed in {} s",
101                self.done,
102                self.failed,
103                span.as_secs()
104            );
105            self.done = 0;
106            self.failed = 0;
107            self.window = Instant::now();
108        }
109    }
110
111    fn ok(&mut self) {
112        self.done += 1;
113        if self.errors > 0 {
114            warn!(
115                "PPS link recovered: {} errors over {} ms",
116                self.errors,
117                self.since.elapsed().as_millis()
118            );
119            self.errors = 0;
120        }
121    }
122
123    fn failed(&mut self, op: &str, err: &PpsError) {
124        self.done += 1;
125        self.failed += 1;
126        let now = Instant::now();
127        if self.errors == 0 {
128            warn!("PPS link: {} failed: {}", op, err);
129            self.since = now;
130            self.reported = now;
131        } else if now - self.reported >= EPISODE_REPORT {
132            warn!(
133                "PPS link failing: {} errors in {} ms, last {}: {}",
134                self.errors + 1,
135                (now - self.since).as_millis(),
136                op,
137                err
138            );
139            self.reported = now;
140        }
141        self.errors += 1;
142    }
143}
144
145/// The planner plus what the consumer needs beyond it: the last bank (for
146/// FLAG) and the rejected-reading count.
147struct Mirror {
148    planner: Planner,
149    bank: Option<PpsBank>,
150    rejected: u32,
151}
152
153impl Mirror {
154    const fn new() -> Self {
155        Self {
156            planner: Planner::new(),
157            bank: None,
158            rejected: 0,
159        }
160    }
161
162    /// Run `t` and fold its outcome in. A rejected reading is not a link
163    /// failure: the module answered, the sample did not pass.
164    async fn run(
165        &mut self,
166        pps: &mut PpsDriver,
167        t: Transaction,
168        on_read: fn(&PpsReadings),
169    ) -> Result<(), PpsError> {
170        match t {
171            Transaction::Setpoints { voltage, current } => {
172                pps.write_setpoints(voltage, current).await?;
173                self.planner.wrote(voltage, current);
174            }
175            Transaction::Enable(on) => pps.write_enable(on).await?,
176            Transaction::Read => match pps.read_bank().await {
177                Ok(b) => {
178                    let held = Held {
179                        enabled: b.enabled,
180                        voltage_set: b.voltage_set,
181                        current_set: b.current_set,
182                    };
183                    on_read(&PpsReadings {
184                        voltage: b.voltage,
185                        current: b.current,
186                        temperature: b.temperature,
187                        input_voltage: b.input_voltage,
188                        running_mode: b.running_mode,
189                        enabled: b.enabled,
190                        voltage_set: b.voltage_set,
191                        current_set: b.current_set,
192                        delivered: self.planner.holds(&held),
193                        fresh: self.bank.is_none_or(|prev| prev.flag != b.flag),
194                        rejected: self.rejected,
195                    });
196                    self.planner.read(held);
197                    self.bank = Some(b);
198                }
199                Err(e) if e.is_transient() => {
200                    self.rejected = self.rejected.saturating_add(1);
201                    warn!("PPS reading rejected ({} total): {}", self.rejected, e);
202                }
203                Err(e) => return Err(e),
204            },
205        }
206        Ok(())
207    }
208}
209
210pub async fn pps_loop(
211    resources: PpsResources,
212    on_read: fn(&PpsReadings),
213    get_setpoint: fn() -> PpsSetpoint,
214) -> ! {
215    let mut pps = PpsDriver::new(resources.i2c, ADDRESS);
216    let mut link = Link::new();
217
218    loop {
219        match pps.probe().await {
220            Ok(id) => {
221                info!("PPS module id {:#06x} at address {:#04x}", id, ADDRESS);
222                break;
223            }
224            Err(e) => link.failed("probe", &e),
225        }
226        // No module, no slot grid yet: the power read still runs, spaced
227        // from the probe, so a board without one still knows its hookup.
228        if let Some(report) = resources.on_usb_power {
229            Timer::after(Duration::from_millis(PPS_MIN_GAP_MS)).await;
230            report(crate::board::usb_powered(resources.i2c).await.ok());
231        }
232        Timer::after(PROBE_PERIOD).await;
233    }
234    link.ok();
235
236    let mut mirror = Mirror::new();
237    let mut start = Instant::now();
238    let (mut tick, mut next) = (0u32, 0usize);
239    loop {
240        let slot = slot_at(tick, next, resources.on_usb_power.is_some());
241        next = (next + 1) % SCHEDULE.len();
242        if next == 0 {
243            tick = tick.wrapping_add(1);
244        }
245        if slot == Slot::Aux {
246            if let Some(report) = resources.on_usb_power {
247                report(crate::board::usb_powered(resources.i2c).await.ok());
248            }
249        } else if let Some(t) = mirror.planner.plan(slot, &get_setpoint()) {
250            // Nothing due: no transaction, so no evidence about the link either way.
251            match mirror.run(&mut pps, t, on_read).await {
252                Ok(()) => link.ok(),
253                Err(e) => link.failed(t.name(), &e),
254            }
255        }
256        link.summarize();
257        start = Instant::from_micros(next_slot_start(
258            start.as_micros(),
259            Instant::now().as_micros(),
260        ));
261        Timer::at(start).await;
262    }
263}