sml-kit 0.1.1

Read German smart meters in Rust: SML (Smart Message Language) decoder and encoder, sans-I/O, no_std, no allocator, no dependencies
Documentation
//! A whole SML file: the unit a client sends and a meter answers with.

use crate::message::{Body, Message};
use crate::tl::Writer;
use crate::{Error, Result};

/// The most messages a file can hold: each gets a one-byte message number.
const MAX_MESSAGES: usize = 256;

/// The longest file-ID prefix of a transaction ID.
const PREFIX: usize = 7;

/// An SML file: an open, the requests (or responses) and a close, sharing one file ID.
///
/// [`write`](Self::write) gives every message a transaction ID unique in the file (the
/// file ID's first seven bytes and the message number) and its own CRC. A meter repeats a
/// request's transaction ID in its answer, which is how a client matches the two.
///
/// ```
/// use sml_kit::{Body, CloseRequest, GetListRequest, OpenRequest, SmlFile, encode_frame};
///
/// let bodies = [
///     Body::OpenRequest(OpenRequest {
///         codepage: None,
///         client_id: b"gw-1",
///         req_file_id: b"F42",
///         server_id: None,
///         username: None,
///         password: None,
///         sml_version: None,
///     }),
///     Body::GetListRequest(GetListRequest {
///         client_id: b"gw-1",
///         server_id: None,
///         username: None,
///         password: None,
///         list_name: None,
///     }),
///     Body::CloseRequest(CloseRequest { global_signature: None }),
/// ];
/// let mut payload = [0u8; 128];
/// let n = SmlFile { file_id: b"F42", messages: &bodies }.write(&mut payload)?;
///
/// let mut wire = [0u8; 300];
/// let len = encode_frame(&payload[..n], &mut wire)?; // send &wire[..len]
/// # assert!(len > n);
/// # Ok::<(), sml_kit::Error>(())
/// ```
///
/// The shape is checked, not the direction: a file must start with an `OpenRequest` or
/// `OpenResponse`, end with a `CloseRequest` or `CloseResponse`, and have at most 256
/// messages; anything else is [`Error::InvalidFile`]. Every message is written with
/// `group_no` 0 and `abort_on_error` 0; for other values write [`Message`]s one by one.
///
/// `Debug` shows each body through its own `Debug`, which prints passwords as
/// `<redacted>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SmlFile<'a> {
    /// The file ID, also the prefix of every transaction ID.
    pub file_id: &'a [u8],
    /// The messages, in order.
    pub messages: &'a [Body<'a>],
}

impl SmlFile<'_> {
    /// Write every message with its CRC into `out`. Returns the number of bytes written:
    /// the unframed payload for [`encode_frame`](crate::encode_frame).
    pub fn write(&self, out: &mut [u8]) -> Result<usize> {
        let opens = matches!(self.messages.first(), Some(Body::OpenRequest(_) | Body::OpenResponse(_)));
        let closes = matches!(self.messages.last(), Some(Body::CloseRequest(_) | Body::CloseResponse(_)));
        if !opens || !closes || self.messages.len() > MAX_MESSAGES {
            return Err(Error::InvalidFile);
        }
        let prefix_len = self.file_id.len().min(PREFIX);
        let mut tx = [0u8; PREFIX + 1];
        if let (Some(dst), Some(src)) = (tx.get_mut(..prefix_len), self.file_id.get(..prefix_len)) {
            dst.copy_from_slice(src);
        }
        let mut w = Writer::new(out);
        for (number, &body) in (0..=u8::MAX).zip(self.messages) {
            if let Some(last) = tx.get_mut(prefix_len) {
                *last = number;
            }
            let transaction_id = tx.get(..=prefix_len).unwrap_or(&[]);
            Message { transaction_id, group_no: 0, abort_on_error: 0, body }.write(&mut w)?;
        }
        Ok(w.position())
    }
}