Skip to main content

sml_kit/
io.rs

1//! A blocking frame reader over [`std::io::Read`]: a serial port, a USB infrared head, a
2//! TCP socket or a capture file.
3//!
4//! ```no_run
5//! use sml_kit::{Obis, io::FrameReader};
6//!
7//! let port = std::fs::File::open("/dev/ttyUSB0")?; // 9600 8N1, configured beforehand
8//! for frame in FrameReader::new(port) {
9//!     let Ok(frame) = frame else { continue }; // a damaged frame, or a read timeout
10//!     if let Ok(list) = sml_kit::readout(&frame) {
11//!         println!("A+ = {:?}", list.quantity(Obis::ENERGY_IMPORT));
12//!     }
13//! }
14//! # Ok::<(), std::io::Error>(())
15//! ```
16//!
17//! Only available with the `std` feature. The core decoder underneath is the same
18//! sans-I/O [`Decoder`].
19
20use std::io::{self, ErrorKind, Read};
21use std::vec;
22use std::vec::Vec;
23
24use crate::{CrcCheck, Decoder, Error};
25
26/// The largest frame [`FrameReader::new`] accepts: far more than any meter telegram.
27pub const DEFAULT_CAPACITY: usize = 64 * 1024;
28
29/// What can go wrong while reading frames.
30#[derive(Debug)]
31pub enum ReadError {
32    /// The source failed. `TimedOut` and `WouldBlock` (a serial port without data) are
33    /// reported too; iterating again continues reading.
34    Io(io::Error),
35    /// A frame was damaged (CRC, padding, escape) or larger than the capacity. The
36    /// reader has already moved on to the next frame.
37    Frame(Error),
38}
39
40impl core::fmt::Display for ReadError {
41    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42        match self {
43            Self::Io(e) => write!(f, "read failed: {e}"),
44            Self::Frame(e) => write!(f, "bad frame: {e}"),
45        }
46    }
47}
48
49impl std::error::Error for ReadError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Self::Io(e) => Some(e),
53            Self::Frame(e) => Some(e),
54        }
55    }
56}
57
58impl From<io::Error> for ReadError {
59    fn from(e: io::Error) -> Self {
60        Self::Io(e)
61    }
62}
63
64impl From<Error> for ReadError {
65    fn from(e: Error) -> Self {
66        Self::Frame(e)
67    }
68}
69
70/// An iterator of verified transport payloads read from `R`.
71///
72/// Memory is bounded: one frame buffer of fixed capacity and a 256-byte read buffer,
73/// allocated once.
74///
75/// Iteration ends when a read returns `Ok(0)`, which is end of input. A serial port
76/// must therefore block until data arrives, or time out with an error: a tty set to
77/// return 0 bytes on timeout (`VMIN = 0`) would end the loop at the first quiet second.
78#[derive(Debug)] // `Decoder`'s Debug shows no buffer contents.
79pub struct FrameReader<R> {
80    inner: R,
81    decoder: Decoder<Vec<u8>>,
82    chunk: [u8; 256],
83    pos: usize,
84    len: usize,
85}
86
87impl<R: Read> FrameReader<R> {
88    /// A reader accepting frames up to [`DEFAULT_CAPACITY`] bytes.
89    pub fn new(inner: R) -> Self {
90        Self::with_capacity(inner, DEFAULT_CAPACITY)
91    }
92
93    /// A reader accepting frames up to `capacity` bytes; a larger frame is reported as
94    /// [`Error::BufferFull`] and skipped.
95    pub fn with_capacity(inner: R, capacity: usize) -> Self {
96        Self { inner, decoder: Decoder::new(vec![0; capacity]), chunk: [0; 256], pos: 0, len: 0 }
97    }
98
99    /// Set how the frame CRC is checked. [`CrcCheck::Strict`] by default.
100    #[must_use]
101    pub fn with_crc_check(mut self, check: CrcCheck) -> Self {
102        self.decoder = self.decoder.with_crc_check(check);
103        self
104    }
105
106    /// The source.
107    pub fn get_ref(&self) -> &R {
108        &self.inner
109    }
110
111    /// The source, mutably (e.g. to change a serial port's settings).
112    pub fn get_mut(&mut self) -> &mut R {
113        &mut self.inner
114    }
115
116    /// The source, consuming the reader.
117    pub fn into_inner(self) -> R {
118        self.inner
119    }
120}
121
122impl<R: Read> Iterator for FrameReader<R> {
123    type Item = Result<Vec<u8>, ReadError>;
124
125    fn next(&mut self) -> Option<Self::Item> {
126        loop {
127            while self.pos < self.len {
128                let byte = self.chunk.get(self.pos).copied().unwrap_or(0);
129                self.pos += 1;
130                match self.decoder.push(byte) {
131                    Ok(Some(frame)) => return Some(Ok(frame.to_vec())),
132                    Ok(None) => {}
133                    Err(e) => return Some(Err(ReadError::Frame(e))),
134                }
135            }
136            match self.inner.read(&mut self.chunk) {
137                Ok(0) => return None,
138                Ok(n) => {
139                    self.pos = 0;
140                    self.len = n.min(self.chunk.len());
141                }
142                Err(e) if e.kind() == ErrorKind::Interrupted => {}
143                Err(e) => return Some(Err(ReadError::Io(e))),
144            }
145        }
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use crate::encode_frame;
153
154    fn frame(payload: &[u8]) -> Vec<u8> {
155        let mut out = vec![0u8; payload.len() * 2 + 32];
156        let n = encode_frame(payload, &mut out).unwrap();
157        out.truncate(n);
158        out
159    }
160
161    #[test]
162    fn two_frames_and_noise_then_end() {
163        let mut stream = vec![0x00, 0x42];
164        stream.extend(frame(b"one!"));
165        stream.extend([0x1B, 0x1B, 0x07]);
166        stream.extend(frame(b"two"));
167        let got: Vec<_> = FrameReader::new(stream.as_slice()).map(Result::unwrap).collect();
168        assert_eq!(got, [b"one!".to_vec(), b"two".to_vec()]);
169    }
170
171    // 001-real-meter-readiness/SR-008
172    #[test]
173    fn an_oversized_frame_is_an_error_then_reading_continues() {
174        let mut stream = frame(&[7; 200]);
175        stream.extend(frame(&[8; 40]));
176        let mut r = FrameReader::with_capacity(stream.as_slice(), 64);
177        assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::BufferFull)))));
178        assert_eq!(r.next().unwrap().unwrap(), [8; 40]);
179        assert!(r.next().is_none());
180    }
181
182    /// Returns one error, then the data.
183    struct Flaky<'a> {
184        error: Option<ErrorKind>,
185        data: &'a [u8],
186    }
187
188    impl Read for Flaky<'_> {
189        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
190            if let Some(kind) = self.error.take() {
191                return Err(kind.into());
192            }
193            self.data.read(buf)
194        }
195    }
196
197    // 001-real-meter-readiness/SR-008
198    #[test]
199    fn a_timeout_is_reported_and_the_next_call_continues() {
200        let data = frame(b"late");
201        let mut r = FrameReader::new(Flaky { error: Some(ErrorKind::TimedOut), data: &data });
202        assert!(matches!(r.next(), Some(Err(ReadError::Io(e))) if e.kind() == ErrorKind::TimedOut));
203        assert_eq!(r.next().unwrap().unwrap(), b"late");
204    }
205
206    // 001-real-meter-readiness/SR-008
207    #[test]
208    fn interrupted_is_retried_silently() {
209        let data = frame(b"ok");
210        let mut r = FrameReader::new(Flaky { error: Some(ErrorKind::Interrupted), data: &data });
211        assert_eq!(r.next().unwrap().unwrap(), b"ok");
212    }
213
214    #[test]
215    fn a_damaged_frame_is_a_frame_error_not_an_io_error() {
216        let mut data = frame(b"abcd");
217        data[9] ^= 1;
218        let mut r = FrameReader::new(data.as_slice());
219        assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::FrameCrc { .. })))));
220    }
221
222    #[test]
223    fn the_default_capacity_takes_large_frames() {
224        assert_eq!(DEFAULT_CAPACITY, 65_536);
225        let big = frame(&[7; 2000]);
226        assert_eq!(FrameReader::new(big.as_slice()).next().unwrap().unwrap(), [7; 2000]);
227    }
228
229    #[test]
230    fn read_errors_display_and_chain() {
231        use std::error::Error as _;
232        use std::string::ToString;
233        let frame_error = ReadError::from(Error::BufferFull);
234        assert_eq!(frame_error.to_string(), "bad frame: frame larger than the decoder buffer");
235        assert_eq!(frame_error.source().unwrap().to_string(), "frame larger than the decoder buffer");
236        let io_error = ReadError::from(io::Error::from(ErrorKind::TimedOut));
237        assert!(io_error.to_string().starts_with("read failed: "));
238        assert!(io_error.source().is_some());
239    }
240
241    #[test]
242    fn a_damaged_frame_is_reported_once() {
243        let mut data = frame(b"abcd");
244        data[9] ^= 1;
245        let mut r = FrameReader::new(data.as_slice());
246        assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::FrameCrc { .. })))));
247    }
248}