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
use core::fmt;

/// A device's server ID: the bytes a meter names itself with in `OpenResponse`,
/// `GetListResponse` and `Attention`.
///
/// German meters use 10 bytes (DIN 43863-5): a type byte, the medium (`1` =
/// electricity), the three-letter FLAG manufacturer code, a production block and a
/// big-endian serial number. Such an ID displays the way it is printed on the meter:
///
/// ```
/// use sml_kit::ServerId;
///
/// let id = ServerId::new(&[0x0a, 0x01, b'I', b'S', b'K', 0x00, 0x04, 0x7a, 0x55, 0x44]);
/// assert_eq!(id.manufacturer(), Some("ISK"));
/// assert_eq!(id.serial(), Some(75_126_084));
/// assert_eq!(id.to_string(), "1 ISK00 75126084");
///
/// // Anything else is shown as hex, never as raw text.
/// assert_eq!(ServerId::new(&[0xde, 0xad]).to_string(), "dead");
/// ```
///
/// The block is shown as two hex digits (it is BCD on the meters seen so far). The
/// layout comes from public captures, not from the DIN text itself.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ServerId<'a>(&'a [u8]);

impl<'a> ServerId<'a> {
    /// A server ID over `bytes`.
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self(bytes)
    }

    /// The raw bytes.
    pub const fn as_bytes(&self) -> &'a [u8] {
        self.0
    }

    /// The fields of a standard 10-byte ID: medium, manufacturer, block, serial.
    fn standard(&self) -> Option<(u8, &'a str, u8, u32)> {
        let [_, medium, m0, m1, m2, block, s0, s1, s2, s3] = *self.0 else { return None };
        let flag = self.0.get(2..5)?;
        if ![m0, m1, m2].iter().all(u8::is_ascii_uppercase) {
            return None;
        }
        let manufacturer = core::str::from_utf8(flag).ok()?;
        Some((medium, manufacturer, block, u32::from_be_bytes([s0, s1, s2, s3])))
    }

    /// The FLAG manufacturer code (e.g. `"EMH"`, `"ISK"`, `"DZG"`), for a standard ID.
    pub fn manufacturer(&self) -> Option<&'a str> {
        self.standard().map(|(_, m, _, _)| m)
    }

    /// The medium (`1` = electricity), for a standard ID.
    pub fn medium(&self) -> Option<u8> {
        self.standard().map(|(m, _, _, _)| m)
    }

    /// The production block, for a standard ID.
    pub fn block(&self) -> Option<u8> {
        self.standard().map(|(_, _, b, _)| b)
    }

    /// The serial number, for a standard ID.
    pub fn serial(&self) -> Option<u32> {
        self.standard().map(|(_, _, _, s)| s)
    }
}

impl fmt::Display for ServerId<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Only three checked uppercase letters are ever written as text; every other
        // byte a meter sends is written as hex, so it cannot carry control sequences.
        match self.standard() {
            Some((medium, manufacturer, block, serial)) => {
                write!(f, "{medium} {manufacturer}{block:02x} {serial:08}")
            }
            None => self.0.iter().try_for_each(|b| write!(f, "{b:02x}")),
        }
    }
}

impl fmt::Debug for ServerId<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ServerId({self})")
    }
}

impl PartialEq<[u8]> for ServerId<'_> {
    fn eq(&self, other: &[u8]) -> bool {
        self.0 == other
    }
}

impl PartialEq<&[u8]> for ServerId<'_> {
    fn eq(&self, other: &&[u8]) -> bool {
        self.0 == *other
    }
}

impl<'a> From<&'a [u8]> for ServerId<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self(bytes)
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use std::format;
    use std::string::ToString;

    #[test]
    fn standard_ids_from_real_meters() {
        // EasyMeter: 1-0:0.0.0 reads "1ESY1162232997" next to this binary ID.
        let esy = [0x09, 0x01, b'E', b'S', b'Y', 0x11, 0x03, 0xb5, 0x99, 0xa5];
        assert_eq!(ServerId::new(&esy).to_string(), "1 ESY11 62232997");
        let emh = [0x09, 0x01, b'E', b'M', b'H', 0x00, 0x00, 0x41, 0xf0, 0x45];
        assert_eq!(ServerId::new(&emh).to_string(), "1 EMH00 04321349");
        assert_eq!(ServerId::new(&emh).medium(), Some(1));
        assert_eq!(ServerId::new(&emh).block(), Some(0));
    }

    // 001-real-meter-readiness/SR-007
    #[test]
    fn meter_bytes_never_reach_the_output_as_text() {
        let gas = [0x0a, 0x07, b'A', b'B', b'C', 0x42, 0, 0, 0, 7];
        let id = ServerId::new(&gas);
        assert_eq!((id.medium(), id.block(), id.serial()), (Some(7), Some(0x42), Some(7)));
        assert_eq!(format!("{id:?}"), "ServerId(7 ABC42 00000007)");
        // Both impls on purpose: `PartialEq<[u8]>` and `PartialEq<&[u8]>`.
        #[allow(clippy::op_ref)]
        let both = id == gas[..] && id == &gas[..];
        assert!(both);
        #[allow(clippy::op_ref)]
        let neither = id != [1u8][..] && id != &[1u8][..];
        assert!(neither);
        let evil = [0x0a, 0x01, 0x1b, b'[', b'2', b'J', 0, 0, 0, 1];
        let shown = ServerId::new(&evil).to_string();
        assert_eq!(shown, "0a011b5b324a00000001");
        assert!(shown.bytes().all(|b| b.is_ascii_hexdigit()));
        assert_eq!(ServerId::new(&evil).manufacturer(), None);
        assert_eq!(ServerId::new(&[]).to_string(), "");
        let lower = [0x0a, 0x01, b'e', b'm', b'h', 0, 0, 0, 0, 1];
        assert_eq!(ServerId::new(&lower).manufacturer(), None);
    }
}