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

use crate::Error;

/// An OBIS code (IEC 62056-61): the six-byte name of a measured quantity.
///
/// Displays as `A-B:C.D.E*F`, e.g. `1-0:1.8.0*255` for imported active energy, and
/// parses from that form, from `A-B:C.D.E` (F = 255) and from the short `C.D.E` printed
/// on meters (A = 1, B = 0, F = 255):
///
/// ```
/// use sml_kit::Obis;
///
/// assert_eq!("1-0:1.8.0*255".parse(), Ok(Obis::ENERGY_IMPORT));
/// assert_eq!("1.8.0".parse(), Ok(Obis::ENERGY_IMPORT));
/// assert_eq!(Obis::ENERGY_IMPORT.name(), Some("active energy import (A+), total"));
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Obis(pub [u8; 6]);

impl Obis {
    /// `1-0:1.8.0*255`: active energy imported (A+), total.
    pub const ENERGY_IMPORT: Self = Self::new(1, 0, 1, 8, 0, 255);
    /// `1-0:1.8.1*255`: active energy imported, tariff 1.
    pub const ENERGY_IMPORT_T1: Self = Self::new(1, 0, 1, 8, 1, 255);
    /// `1-0:1.8.2*255`: active energy imported, tariff 2.
    pub const ENERGY_IMPORT_T2: Self = Self::new(1, 0, 1, 8, 2, 255);
    /// `1-0:2.8.0*255`: active energy exported (A−), total.
    pub const ENERGY_EXPORT: Self = Self::new(1, 0, 2, 8, 0, 255);
    /// `1-0:2.8.1*255`: active energy exported, tariff 1.
    pub const ENERGY_EXPORT_T1: Self = Self::new(1, 0, 2, 8, 1, 255);
    /// `1-0:2.8.2*255`: active energy exported, tariff 2.
    pub const ENERGY_EXPORT_T2: Self = Self::new(1, 0, 2, 8, 2, 255);
    /// `1-0:16.7.0*255`: active power, sum of phases (positive = import).
    pub const POWER: Self = Self::new(1, 0, 16, 7, 0, 255);
    /// `1-0:36.7.0*255`: active power, phase L1.
    pub const POWER_L1: Self = Self::new(1, 0, 36, 7, 0, 255);
    /// `1-0:56.7.0*255`: active power, phase L2.
    pub const POWER_L2: Self = Self::new(1, 0, 56, 7, 0, 255);
    /// `1-0:76.7.0*255`: active power, phase L3.
    pub const POWER_L3: Self = Self::new(1, 0, 76, 7, 0, 255);
    /// `1-0:31.7.0*255`: current, phase L1.
    pub const CURRENT_L1: Self = Self::new(1, 0, 31, 7, 0, 255);
    /// `1-0:51.7.0*255`: current, phase L2.
    pub const CURRENT_L2: Self = Self::new(1, 0, 51, 7, 0, 255);
    /// `1-0:71.7.0*255`: current, phase L3.
    pub const CURRENT_L3: Self = Self::new(1, 0, 71, 7, 0, 255);
    /// `1-0:32.7.0*255`: voltage, phase L1.
    pub const VOLTAGE_L1: Self = Self::new(1, 0, 32, 7, 0, 255);
    /// `1-0:52.7.0*255`: voltage, phase L2.
    pub const VOLTAGE_L2: Self = Self::new(1, 0, 52, 7, 0, 255);
    /// `1-0:72.7.0*255`: voltage, phase L3.
    pub const VOLTAGE_L3: Self = Self::new(1, 0, 72, 7, 0, 255);
    /// `1-0:14.7.0*255`: supply frequency.
    pub const FREQUENCY: Self = Self::new(1, 0, 14, 7, 0, 255);
    /// `1-0:0.0.9*255`: the device identifier (server ID).
    pub const DEVICE_ID: Self = Self::new(1, 0, 0, 0, 9, 255);
    /// `1-0:96.1.0*255`: the meter's serial number (server ID on newer meters).
    pub const SERIAL: Self = Self::new(1, 0, 96, 1, 0, 255);
    /// `1-0:96.5.0*255`: the operating status word.
    pub const STATUS: Self = Self::new(1, 0, 96, 5, 0, 255);
    /// `129-129:199.130.3*255`: the manufacturer identifier.
    pub const MANUFACTURER: Self = Self::new(129, 129, 199, 130, 3, 255);
    /// `1-0:96.50.1*1`: the manufacturer identifier as newer meters label it.
    pub const MANUFACTURER_ALT: Self = Self::new(1, 0, 96, 50, 1, 1);
    /// `129-129:199.130.5*255`: the meter's public key (for signed readings).
    pub const PUBLIC_KEY: Self = Self::new(129, 129, 199, 130, 5, 255);
    /// `1-0:0.2.0*0`: the firmware version.
    pub const FIRMWARE: Self = Self::new(1, 0, 0, 2, 0, 0);

    /// The OBIS code `A-B:C.D.E*F`.
    #[allow(clippy::many_single_char_names)] // A to F are the standard's names.
    pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> Self {
        Self([a, b, c, d, e, f])
    }

    /// The OBIS code in `bytes`, which must be exactly six bytes long.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        <[u8; 6]>::try_from(bytes).map(Self).map_err(|_| Error::ObisLength(bytes.len()))
    }

    /// What the code means, for the codes a German meter commonly sends.
    pub fn name(&self) -> Option<&'static str> {
        const NAMES: &[(Obis, &str)] = &[
            (Obis::ENERGY_IMPORT, "active energy import (A+), total"),
            (Obis::ENERGY_IMPORT_T1, "active energy import (A+), tariff 1"),
            (Obis::ENERGY_IMPORT_T2, "active energy import (A+), tariff 2"),
            (Obis::ENERGY_EXPORT, "active energy export (A-), total"),
            (Obis::ENERGY_EXPORT_T1, "active energy export (A-), tariff 1"),
            (Obis::ENERGY_EXPORT_T2, "active energy export (A-), tariff 2"),
            (Obis::POWER, "active power, total"),
            (Obis::POWER_L1, "active power, L1"),
            (Obis::POWER_L2, "active power, L2"),
            (Obis::POWER_L3, "active power, L3"),
            (Obis::CURRENT_L1, "current, L1"),
            (Obis::CURRENT_L2, "current, L2"),
            (Obis::CURRENT_L3, "current, L3"),
            (Obis::VOLTAGE_L1, "voltage, L1"),
            (Obis::VOLTAGE_L2, "voltage, L2"),
            (Obis::VOLTAGE_L3, "voltage, L3"),
            (Obis::FREQUENCY, "frequency"),
            (Obis::DEVICE_ID, "device identifier"),
            (Obis::SERIAL, "serial number"),
            (Obis::STATUS, "status word"),
            (Obis::MANUFACTURER, "manufacturer"),
            (Obis::MANUFACTURER_ALT, "manufacturer"),
            (Obis::PUBLIC_KEY, "public key"),
            (Obis::FIRMWARE, "firmware version"),
        ];
        NAMES.iter().find(|(o, _)| o == self).map(|&(_, n)| n)
    }

    /// Whether this is active power, total or per phase (`1-0:{16,36,56,76}.7.0`, any F).
    pub(crate) fn is_active_power(self) -> bool {
        matches!(self.0, [1, 0, 16 | 36 | 56 | 76, 7, 0, _])
    }
}

impl From<[u8; 6]> for Obis {
    fn from(bytes: [u8; 6]) -> Self {
        Self(bytes)
    }
}

impl From<Obis> for [u8; 6] {
    fn from(obis: Obis) -> Self {
        obis.0
    }
}

/// Six bytes, or [`Error::ObisLength`].
impl TryFrom<&[u8]> for Obis {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self, Error> {
        Self::from_bytes(bytes)
    }
}

impl fmt::Display for Obis {
    #[allow(clippy::many_single_char_names)] // A to F are the standard's names.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let [a, b, c, d, e, g] = self.0;
        write!(f, "{a}-{b}:{c}.{d}.{e}*{g}")
    }
}

impl FromStr for Obis {
    type Err = Error;

    #[allow(clippy::many_single_char_names)] // A to F are the standard's names.
    fn from_str(s: &str) -> Result<Self, Error> {
        fn num(s: &str) -> Result<u8, Error> {
            // `u8::from_str` alone would accept a leading `+`; it rejects empty and > 255.
            if !s.bytes().all(|b| b.is_ascii_digit()) {
                return Err(Error::ObisSyntax);
            }
            s.parse().map_err(|_| Error::ObisSyntax)
        }
        fn cde(s: &str) -> Result<[u8; 3], Error> {
            let mut it = s.split('.');
            let (Some(c), Some(d), Some(e), None) = (it.next(), it.next(), it.next(), it.next()) else {
                return Err(Error::ObisSyntax);
            };
            Ok([num(c)?, num(d)?, num(e)?])
        }
        let (ab, rest) = match s.split_once(':') {
            Some((ab, rest)) => (Some(ab), rest),
            None => (None, s),
        };
        let (cde_text, f) = match rest.split_once('*') {
            Some((cde, f)) => (cde, num(f)?),
            None => (rest, 255),
        };
        let (a, b) = match ab {
            Some(ab) => {
                let (a, b) = ab.split_once('-').ok_or(Error::ObisSyntax)?;
                (num(a)?, num(b)?)
            }
            None if f == 255 && !rest.contains('*') => (1, 0),
            None => return Err(Error::ObisSyntax),
        };
        let [c, d, e] = cde(cde_text)?;
        Ok(Self([a, b, c, d, e, f]))
    }
}

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

    #[test]
    fn displays_in_reduced_id_notation() {
        assert_eq!(Obis::ENERGY_IMPORT.to_string(), "1-0:1.8.0*255");
        assert_eq!(Obis::MANUFACTURER.to_string(), "129-129:199.130.3*255");
    }

    #[test]
    fn rejects_wrong_length() {
        assert_eq!(Obis::from_bytes(&[1, 2, 3]), Err(Error::ObisLength(3)));
        assert_eq!(Obis::try_from(&[1u8, 2, 3][..]), Err(Error::ObisLength(3)));
        assert_eq!(Obis::try_from(&[1u8, 0, 1, 8, 0, 255][..]), Ok(Obis::ENERGY_IMPORT));
        assert_eq!(Obis::from([1, 0, 1, 8, 0, 255]), Obis::ENERGY_IMPORT);
        assert_eq!(<[u8; 6]>::from(Obis::POWER), [1, 0, 16, 7, 0, 255]);
    }

    #[test]
    fn parses_the_three_forms() {
        assert_eq!("1-0:1.8.0*255".parse(), Ok(Obis::ENERGY_IMPORT));
        assert_eq!("1-0:1.8.0".parse(), Ok(Obis::ENERGY_IMPORT));
        assert_eq!("16.7.0".parse(), Ok(Obis::POWER));
        assert_eq!("1-0:96.50.1*1".parse(), Ok(Obis::MANUFACTURER_ALT));
        for o in [Obis::MANUFACTURER, Obis::FIRMWARE, Obis::new(0, 0, 0, 0, 0, 0)] {
            assert_eq!(o.to_string().parse(), Ok(o));
        }
    }

    #[test]
    fn rejects_malformed_text() {
        for bad in [
            "",
            "1.8",
            "1.8.0.0",
            "1-0:1.8.0*",
            "1:1.8.0",
            "256.8.0",
            "+1.8.0",
            "1.8.0*255",
            "a.b.c",
            "1-0-0:1.8.0",
        ] {
            assert_eq!(bad.parse::<Obis>(), Err(Error::ObisSyntax), "{bad}");
        }
    }

    #[test]
    fn power_codes_any_billing_period() {
        assert!(Obis::POWER_L2.is_active_power());
        assert!(Obis::new(1, 0, 16, 7, 0, 0).is_active_power());
        assert!(!Obis::ENERGY_IMPORT.is_active_power());
    }
}