sml-kit 0.1.0

SML (Smart Message Language) for Rust: German smart meter readout with a sans-I/O, no_std, allocation-free core
Documentation
//! Process parameters and profile entries: `SML_Tree`, `SML_ProcParValue`,
//! `SML_PeriodEntry` and `SML_TupelEntry` (TR-03109-1 Anlage IV, letters BB, FF, GG, HH).
//!
//! A gateway or service tool reads and writes a meter's parameters as a tree of named
//! nodes. FNN Lastenheft EDL names the common ones, e.g. device identification
//! `81 81 C7 82 01 FF` with the manufacturer, server ID, public key and firmware below it.
//!
//! ```
//! use sml_kit::{ProcParValue, SmlValue, Tree, Trees};
//!
//! let leaves = [Tree::leaf(&[0x81, 0x81, 0xC7, 0x82, 0x03, 0xFF], ProcParValue::Value(SmlValue::Bytes(b"EMH")))];
//! let root = Tree { name: &[0x81, 0x81, 0xC7, 0x82, 0x01, 0xFF], value: None, children: Some(Trees::from_slice(&leaves)) };
//! let manufacturer = root.child(&[0x81, 0x81, 0xC7, 0x82, 0x03, 0xFF]).unwrap();
//! assert_eq!(manufacturer.value, Some(ProcParValue::Value(SmlValue::Bytes(b"EMH"))));
//! ```

use crate::seq::{Ctx, Element, Seq};
use crate::tl::{Reader, Writer};
use crate::value::{Quantity, SmlValue, Time, Unit};
use crate::{Error, ListEntry, Obis, Result, ServerId};

/// The children of a [`Tree`].
pub type Trees<'a> = Seq<'a, Tree<'a>>;
/// Period entries of a profile.
pub type PeriodEntries<'a> = Seq<'a, PeriodEntry<'a>>;
/// A sequence of names: an `SML_TreePath`, or a profile's object list.
pub type NameList<'a> = Seq<'a, &'a [u8]>;

/// `SML_Tree`: one named parameter, with a value, children, or both.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Tree<'a> {
    /// The parameter's name, usually an OBIS code.
    pub name: &'a [u8],
    /// The parameter's value, when the node has one.
    pub value: Option<ProcParValue<'a>>,
    /// The child parameters, when the node has them.
    pub children: Option<Trees<'a>>,
}

impl<'a> Tree<'a> {
    /// A node with a value and no children.
    pub const fn leaf(name: &'a [u8], value: ProcParValue<'a>) -> Self {
        Self { name, value: Some(value), children: None }
    }

    /// Whether the node has no children (absent or empty).
    pub fn is_leaf(&self) -> bool {
        self.children.is_none_or(|c| c.is_empty())
    }

    /// The first child named `name` that parses.
    pub fn child(&self, name: &[u8]) -> Option<Self> {
        self.children?.iter().filter_map(core::result::Result::ok).find(|c| c.name == name)
    }
}

impl<'a> Element<'a> for Tree<'a> {
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(3)?;
        let name = r.octet_string()?;
        let value = if r.absent() { None } else { Some(ProcParValue::read(r, ctx)?) };
        // The children are checked with the depth-bounded skip and parsed only when
        // iterated, so a deep tree is an error here, never a deep recursion.
        let children = Seq::read_opt(r, ctx)?;
        Ok(Self { name, value, children })
    }

    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(3)?;
        w.octet_string(self.name)?;
        match self.value {
            Some(v) => v.write(w)?,
            None => w.absent()?,
        }
        Seq::write_opt(self.children, w)
    }
}

impl<'a> Tree<'a> {
    pub(crate) fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        // Validate the whole tree with the bounded skip before reading it.
        r.clone().skip()?;
        <Self as Element<'a>>::read(r, ctx)
    }

    pub(crate) fn read_opt(r: &mut Reader<'a>, ctx: Ctx) -> Result<Option<Self>> {
        if r.absent() { Ok(None) } else { Self::read(r, ctx).map(Some) }
    }

    /// Write the tree.
    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        <Self as Element<'a>>::write(self, w)
    }

    pub(crate) fn write_opt(t: Option<&Self>, w: &mut Writer<'_>) -> Result<()> {
        match t {
            Some(t) => t.write(w),
            None => w.absent(),
        }
    }
}

/// `SML_ProcParValue`: the value of a parameter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ProcParValue<'a> {
    /// `0x01`: a plain value.
    Value(SmlValue<'a>),
    /// `0x02`: a period entry (e.g. a historic consumption).
    Period(PeriodEntry<'a>),
    /// `0x03`: a tupel entry (signed A+/A− and reactive registers).
    Tupel(TupelEntry<'a>),
    /// `0x04`: a time.
    Time(Time),
    /// `0x05`: a list entry (e.g. the signed meter reading `01 00 01 11 00 FF` of an EDL
    /// meter). libsml does not accept this choice; the specification has it since 2009.
    Entry(ListEntry<'a>),
}

impl<'a> ProcParValue<'a> {
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(2)?;
        Ok(match r.unsigned()? {
            1 => Self::Value(SmlValue::read(r, ctx.options)?.0),
            2 => Self::Period(<PeriodEntry<'a> as Element<'a>>::read(r, ctx)?),
            3 => Self::Tupel(TupelEntry::read(r, ctx)?),
            4 => Self::Time(Time::read(r, ctx.options)?),
            5 => Self::Entry(<ListEntry<'a> as Element<'a>>::read(r, ctx)?),
            choice => return Err(Error::UnknownChoice { what: "SML_ProcParValue", choice }),
        })
    }

    /// Write the value with its choice tag.
    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(2)?;
        match self {
            Self::Value(v) => {
                w.unsigned(1, 1)?;
                v.write(w)
            }
            Self::Period(p) => {
                w.unsigned(2, 1)?;
                p.write(w)
            }
            Self::Tupel(t) => {
                w.unsigned(3, 1)?;
                t.write(w)
            }
            Self::Time(t) => {
                w.unsigned(4, 1)?;
                t.write(w)
            }
            Self::Entry(e) => {
                w.unsigned(5, 1)?;
                e.write(w)
            }
        }
    }
}

/// `SML_PeriodEntry`: one value of a profile period, or a historic value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PeriodEntry<'a> {
    /// What the value is.
    pub obis: Obis,
    /// The unit.
    pub unit: Unit,
    /// The decimal exponent.
    pub scaler: i8,
    /// The value.
    pub value: SmlValue<'a>,
    /// A signature over the value, when the device signs. **Not verified** by this crate.
    pub value_signature: Option<&'a [u8]>,
}

impl PeriodEntry<'_> {
    /// The value as an exact [`Quantity`], when it is numeric.
    pub fn quantity(&self) -> Option<Quantity> {
        let mantissa = match self.value {
            SmlValue::Int(v) => i128::from(v),
            SmlValue::Uint(v) => i128::from(v),
            SmlValue::Bool(_) | SmlValue::Bytes(_) | SmlValue::Time(_) => return None,
        };
        Some(Quantity { mantissa, exponent: self.scaler, unit: Some(self.unit) })
    }
}

impl<'a> Element<'a> for PeriodEntry<'a> {
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(5)?;
        let obis = Obis::from_bytes(r.octet_string()?)?;
        let unit = Unit(u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?);
        let scaler = i8::try_from(r.integer()?).map_err(|_| Error::ValueOutOfRange)?;
        let value = SmlValue::read(r, ctx.options)?.0;
        let value_signature = r.opt_octet_string()?;
        Ok(Self { obis, unit, scaler, value, value_signature })
    }

    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(5)?;
        w.octet_string(&self.obis.0)?;
        w.unsigned(u64::from(self.unit.0), 1)?;
        w.integer(i64::from(self.scaler), 1)?;
        self.value.write(w)?;
        w.opt_octet_string(self.value_signature)
    }
}

/// One register of a [`TupelEntry`]: `value × 10^scaler` in `unit`, as on the wire
/// (`Unsigned8`, `Integer8`, `Integer64`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Register {
    /// The unit.
    pub unit: Unit,
    /// The decimal exponent.
    pub scaler: i8,
    /// The raw value.
    pub value: i64,
}

impl Register {
    /// The register as an exact [`Quantity`].
    pub const fn quantity(self) -> Quantity {
        Quantity { mantissa: self.value as i128, exponent: self.scaler, unit: Some(self.unit) }
    }
}

/// `SML_TupelEntry`: a signed set of registers (A+, R1, R4 and A−, R2, R3). 23 fields on
/// the wire.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TupelEntry<'a> {
    /// The device.
    pub server_id: ServerId<'a>,
    /// When the registers were captured.
    pub sec_index: Time,
    /// Device status bits.
    pub status: u64,
    /// Active energy import (A+).
    pub a_plus: Register,
    /// Reactive energy, quadrant I (R1).
    pub r1: Register,
    /// Reactive energy, quadrant IV (R4).
    pub r4: Register,
    /// Signature over A+, R1 and R4. **Not verified** by this crate.
    pub signature_a_plus: &'a [u8],
    /// Active energy export (A−).
    pub a_minus: Register,
    /// Reactive energy, quadrant II (R2).
    pub r2: Register,
    /// Reactive energy, quadrant III (R3).
    pub r3: Register,
    /// Signature over A−, R2 and R3. **Not verified** by this crate.
    pub signature_a_minus: &'a [u8],
}

fn read_register(r: &mut Reader<'_>) -> Result<Register> {
    let unit = Unit(u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?);
    let scaler = i8::try_from(r.integer()?).map_err(|_| Error::ValueOutOfRange)?;
    Ok(Register { unit, scaler, value: r.integer()? })
}

fn write_register(w: &mut Writer<'_>, reg: Register) -> Result<()> {
    w.unsigned(u64::from(reg.unit.0), 1)?;
    w.integer(i64::from(reg.scaler), 1)?;
    w.integer(reg.value, 8)
}

impl<'a> TupelEntry<'a> {
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(23)?;
        let server_id = ServerId::new(r.octet_string()?);
        let sec_index = Time::read(r, ctx.options)?;
        let status = r.unsigned()?;
        let (a_plus, r1, r4) = (read_register(r)?, read_register(r)?, read_register(r)?);
        let signature_a_plus = r.octet_string()?;
        let (a_minus, r2, r3) = (read_register(r)?, read_register(r)?, read_register(r)?);
        let signature_a_minus = r.octet_string()?;
        Ok(Self {
            server_id,
            sec_index,
            status,
            a_plus,
            r1,
            r4,
            signature_a_plus,
            a_minus,
            r2,
            r3,
            signature_a_minus,
        })
    }

    /// Write the entry, every register in its fixed wire width.
    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(23)?;
        w.octet_string(self.server_id.as_bytes())?;
        self.sec_index.write(w)?;
        w.unsigned(self.status, 8)?;
        for q in [self.a_plus, self.r1, self.r4] {
            write_register(w, q)?;
        }
        w.octet_string(self.signature_a_plus)?;
        for q in [self.a_minus, self.r2, self.r3] {
            write_register(w, q)?;
        }
        w.octet_string(self.signature_a_minus)
    }
}