m5stack_core/io/ow_temp.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2use embassy_time::{Duration, Ticker};
3use esp_hal::{Async, gpio::AnyPin, peripherals::RMT, rmt::ChannelCreator};
4
5use crate::driver::ds18b20::{Ds18b20Driver, Error};
6
7/// What [`ow_loop`] needs: something that becomes a driver.
8///
9/// Two shapes implement it, because the RMT has two possible owners. An app
10/// that drives nothing else with the RMT passes [`OnewireResources`] and the
11/// peripheral goes here whole; an app that also drives the SK6812 bars passes
12/// [`OnewireChannels`] from [`crate::board::rmt::RmtChannels`] and the two
13/// share the peripheral. Same loop either way — the choice is the board's and
14/// the application's, not this layer's.
15pub trait IntoOnewireDriver {
16 fn into_driver(self) -> Result<Ds18b20Driver, Error>;
17}
18
19/// The whole RMT peripheral plus the bus pin.
20pub struct OnewireResources<'a> {
21 pub rmt: RMT<'a>,
22 pub pin: AnyPin<'a>,
23}
24
25impl OnewireResources<'static> {
26 pub fn into_driver(self) -> Result<Ds18b20Driver, Error> {
27 Ds18b20Driver::new(self.rmt, self.pin)
28 }
29}
30
31impl IntoOnewireDriver for OnewireResources<'static> {
32 fn into_driver(self) -> Result<Ds18b20Driver, Error> {
33 OnewireResources::into_driver(self)
34 }
35}
36
37/// One TX and one RX channel plus the bus pin, leaving the rest of the RMT for
38/// another consumer.
39pub struct OnewireChannels {
40 pub tx: ChannelCreator<'static, Async, 0>,
41 pub rx: ChannelCreator<'static, Async, { crate::board::rmt::OW_RX }>,
42 pub pin: AnyPin<'static>,
43}
44
45impl IntoOnewireDriver for OnewireChannels {
46 fn into_driver(self) -> Result<Ds18b20Driver, Error> {
47 Ds18b20Driver::with_channels(self.tx, self.rx, self.pin)
48 }
49}
50
51const TEMP_LOOP_TIME_MS: u64 = 3000;
52
53/// 3s ticker, reads all sensors, calls on_temperatures with slice of (address, temp).
54pub async fn ow_loop(resources: impl IntoOnewireDriver, on_temperatures: fn(&[(u64, f32)])) {
55 let Ok(mut ow) = resources.into_driver() else {
56 error!("failed to init OneWire bus - pull-up resistor present?");
57 return;
58 };
59
60 let mut ticker = Ticker::every(Duration::from_millis(TEMP_LOOP_TIME_MS));
61 loop {
62 debug!("reading temperatures");
63 // Collected inside the arm, so the read's borrow of `ow` ends before
64 // the error path touches it again.
65 let mut buf: heapless::Vec<(u64, f32), 2> = heapless::Vec::new();
66 // The read's borrow of `ow` has to end before the error path can touch
67 // it again, so the outcome is reduced to an owned `Option<Error>` here
68 // rather than handled inside the match.
69 let failure = match ow.read_all_temperatures().await {
70 Ok(temperatures) => {
71 for (addr, temp) in temperatures {
72 debug!("temperature of {}C from sensor 0x{:x}", temp, addr.0);
73 if buf.push((addr.0, temp)).is_err() {
74 warn!("more than 2 sensors, ignoring extras");
75 break;
76 }
77 }
78 None
79 }
80 Err(e) => Some(e),
81 };
82 if let Some(e) = failure {
83 // Log and keep going, rather than terminating. A bus error is
84 // usually about the WIRING -- a pin swapped, a sensor shorting
85 // the line, a connector unplugged -- and returning here meant
86 // one bad read at boot silenced temperatures for the whole
87 // power cycle, with a single line to say why. The error names
88 // the failure (no presence pulse, a line that never released,
89 // a CRC fault) and repeats every cycle while it persists, so
90 // plugging a sensor in recovers by itself.
91 error!(
92 "OneWire bus error, retrying in {} ms: {:?}",
93 TEMP_LOOP_TIME_MS, e
94 );
95 // The cached addresses, and the power mode found with them,
96 // described a bus that was working; after a fault neither can
97 // be assumed.
98 ow.forget_addresses();
99 }
100 // An empty slice on a failed read is the point: the consumer clears its
101 // fields, so a lost sensor reads as absent rather than as its last
102 // value held for ever.
103 on_temperatures(buf.as_slice());
104 ticker.next().await;
105 }
106}