sml-kit 0.1.2

Read German smart meters in Rust: SML (Smart Message Language) decoder and encoder, sans-I/O, no_std, no allocator, no dependencies
Documentation
//! A blocking frame reader over [`std::io::Read`]: a serial port, a USB infrared head, a
//! TCP socket or a capture file.
//!
//! ```no_run
//! use sml_kit::{Obis, io::FrameReader};
//!
//! let port = std::fs::File::open("/dev/ttyUSB0")?; // 9600 8N1, configured beforehand
//! for frame in FrameReader::new(port) {
//!     let Ok(frame) = frame else { continue }; // a damaged frame, or a read timeout
//!     if let Ok(list) = sml_kit::readout(&frame) {
//!         println!("A+ = {:?}", list.quantity(Obis::ENERGY_IMPORT));
//!     }
//! }
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! Only available with the `std` feature. The core decoder underneath is the same
//! sans-I/O [`Decoder`].

use std::io::{self, ErrorKind, Read};
use std::vec;
use std::vec::Vec;

use crate::{CrcCheck, Decoder, Error};

/// The largest frame [`FrameReader::new`] accepts: far more than any meter telegram.
pub const DEFAULT_CAPACITY: usize = 64 * 1024;

/// What can go wrong while reading frames.
#[derive(Debug)]
pub enum ReadError {
    /// The source failed. `TimedOut` and `WouldBlock` (a serial port without data) are
    /// reported too; iterating again continues reading.
    Io(io::Error),
    /// A frame was damaged (CRC, padding, escape) or larger than the capacity. The
    /// reader has already moved on to the next frame.
    Frame(Error),
}

impl core::fmt::Display for ReadError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "read failed: {e}"),
            Self::Frame(e) => write!(f, "bad frame: {e}"),
        }
    }
}

impl std::error::Error for ReadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::Frame(e) => Some(e),
        }
    }
}

impl From<io::Error> for ReadError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<Error> for ReadError {
    fn from(e: Error) -> Self {
        Self::Frame(e)
    }
}

/// An iterator of verified transport payloads read from `R`.
///
/// Memory is bounded: one frame buffer of fixed capacity and a 256-byte read buffer,
/// allocated once.
///
/// Iteration ends when a read returns `Ok(0)`, which is end of input. A serial port
/// must therefore block until data arrives, or time out with an error: a tty set to
/// return 0 bytes on timeout (`VMIN = 0`) would end the loop at the first quiet second.
#[derive(Debug)] // `Decoder`'s Debug shows no buffer contents.
pub struct FrameReader<R> {
    inner: R,
    decoder: Decoder<Vec<u8>>,
    chunk: [u8; 256],
    pos: usize,
    len: usize,
}

impl<R: Read> FrameReader<R> {
    /// A reader accepting frames up to [`DEFAULT_CAPACITY`] bytes.
    pub fn new(inner: R) -> Self {
        Self::with_capacity(inner, DEFAULT_CAPACITY)
    }

    /// A reader accepting frames up to `capacity` bytes; a larger frame is reported as
    /// [`Error::BufferFull`] and skipped.
    pub fn with_capacity(inner: R, capacity: usize) -> Self {
        Self { inner, decoder: Decoder::new(vec![0; capacity]), chunk: [0; 256], pos: 0, len: 0 }
    }

    /// Set how the frame CRC is checked. [`CrcCheck::Strict`] by default.
    #[must_use]
    pub fn with_crc_check(mut self, check: CrcCheck) -> Self {
        self.decoder = self.decoder.with_crc_check(check);
        self
    }

    /// The source.
    pub fn get_ref(&self) -> &R {
        &self.inner
    }

    /// The source, mutably (e.g. to change a serial port's settings).
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    /// The source, consuming the reader.
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: Read> Iterator for FrameReader<R> {
    type Item = Result<Vec<u8>, ReadError>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            while self.pos < self.len {
                let byte = self.chunk.get(self.pos).copied().unwrap_or(0);
                self.pos += 1;
                match self.decoder.push(byte) {
                    Ok(Some(frame)) => return Some(Ok(frame.to_vec())),
                    Ok(None) => {}
                    Err(e) => return Some(Err(ReadError::Frame(e))),
                }
            }
            match self.inner.read(&mut self.chunk) {
                Ok(0) => return None,
                Ok(n) => {
                    self.pos = 0;
                    self.len = n.min(self.chunk.len());
                }
                Err(e) if e.kind() == ErrorKind::Interrupted => {}
                Err(e) => return Some(Err(ReadError::Io(e))),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encode_frame;

    fn frame(payload: &[u8]) -> Vec<u8> {
        let mut out = vec![0u8; payload.len() * 2 + 32];
        let n = encode_frame(payload, &mut out).unwrap();
        out.truncate(n);
        out
    }

    #[test]
    fn two_frames_and_noise_then_end() {
        let mut stream = vec![0x00, 0x42];
        stream.extend(frame(b"one!"));
        stream.extend([0x1B, 0x1B, 0x07]);
        stream.extend(frame(b"two"));
        let got: Vec<_> = FrameReader::new(stream.as_slice()).map(Result::unwrap).collect();
        assert_eq!(got, [b"one!".to_vec(), b"two".to_vec()]);
    }

    // 001-real-meter-readiness/SR-008
    #[test]
    fn an_oversized_frame_is_an_error_then_reading_continues() {
        let mut stream = frame(&[7; 200]);
        stream.extend(frame(&[8; 40]));
        let mut r = FrameReader::with_capacity(stream.as_slice(), 64);
        assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::BufferFull)))));
        assert_eq!(r.next().unwrap().unwrap(), [8; 40]);
        assert!(r.next().is_none());
    }

    /// Returns one error, then the data.
    struct Flaky<'a> {
        error: Option<ErrorKind>,
        data: &'a [u8],
    }

    impl Read for Flaky<'_> {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if let Some(kind) = self.error.take() {
                return Err(kind.into());
            }
            self.data.read(buf)
        }
    }

    // 001-real-meter-readiness/SR-008
    #[test]
    fn a_timeout_is_reported_and_the_next_call_continues() {
        let data = frame(b"late");
        let mut r = FrameReader::new(Flaky { error: Some(ErrorKind::TimedOut), data: &data });
        assert!(matches!(r.next(), Some(Err(ReadError::Io(e))) if e.kind() == ErrorKind::TimedOut));
        assert_eq!(r.next().unwrap().unwrap(), b"late");
    }

    // 001-real-meter-readiness/SR-008
    #[test]
    fn interrupted_is_retried_silently() {
        let data = frame(b"ok");
        let mut r = FrameReader::new(Flaky { error: Some(ErrorKind::Interrupted), data: &data });
        assert_eq!(r.next().unwrap().unwrap(), b"ok");
    }

    #[test]
    fn a_damaged_frame_is_a_frame_error_not_an_io_error() {
        let mut data = frame(b"abcd");
        data[9] ^= 1;
        let mut r = FrameReader::new(data.as_slice());
        assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::FrameCrc { .. })))));
    }

    #[test]
    fn the_default_capacity_takes_large_frames() {
        assert_eq!(DEFAULT_CAPACITY, 65_536);
        let big = frame(&[7; 2000]);
        assert_eq!(FrameReader::new(big.as_slice()).next().unwrap().unwrap(), [7; 2000]);
    }

    #[test]
    fn read_errors_display_and_chain() {
        use std::error::Error as _;
        use std::string::ToString;
        let frame_error = ReadError::from(Error::BufferFull);
        assert_eq!(frame_error.to_string(), "bad frame: frame larger than the decoder buffer");
        assert_eq!(frame_error.source().unwrap().to_string(), "frame larger than the decoder buffer");
        let io_error = ReadError::from(io::Error::from(ErrorKind::TimedOut));
        assert!(io_error.to_string().starts_with("read failed: "));
        assert!(io_error.source().is_some());
    }

    #[test]
    fn a_damaged_frame_is_reported_once() {
        let mut data = frame(b"abcd");
        data[9] ^= 1;
        let mut r = FrameReader::new(data.as_slice());
        assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::FrameCrc { .. })))));
    }
}