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
//! A packed profile: `SML_GetProfilePack.Res` (TR-03109-1 Anlage IV), the answer to a
//! [`Body::GetProfilePackRequest`](crate::Body::GetProfilePackRequest).
//!
//! Where `GetProfileList.Res` sends one message per period, each value naming itself, the
//! packed form names the columns once in a header (OBIS code, unit, scaler) and then sends
//! rows of bare values. [`GetProfilePackResponse::quantity`] puts the two back together:
//!
//! ```
//! use sml_kit::{
//!     GetProfilePackResponse, Obis, ProfileColumn, ProfileColumns, ProfilePeriod,
//!     ProfilePeriods, ProfileValue, ProfileValues, ServerId, SmlValue, Time, Unit,
//! };
//!
//! let columns = [ProfileColumn { obis: Obis::ENERGY_IMPORT, unit: Unit::WH, scaler: -1 }];
//! let values = [ProfileValue { value: SmlValue::Uint(12_345), value_signature: None }];
//! let periods = [ProfilePeriod {
//!     val_time: Time::SecIndex(900),
//!     status: 0,
//!     values: ProfileValues::from_slice(&values),
//!     period_signature: None,
//! }];
//! let profile = GetProfilePackResponse {
//!     server_id: ServerId::new(b"\x0a\x01EMH\x00\x00\x41\xf0\x45"),
//!     act_time: Time::SecIndex(1000),
//!     reg_period: 900,
//!     tree_path: sml_kit::NameList::from_slice(&[]),
//!     columns: ProfileColumns::from_slice(&columns),
//!     periods: ProfilePeriods::from_slice(&periods),
//!     rawdata: None,
//!     profile_signature: None,
//! };
//! let first = profile.periods.iter().next().unwrap().unwrap();
//! assert_eq!(profile.quantity(&first, Obis::ENERGY_IMPORT).unwrap().to_string(), "1234.5 Wh");
//! ```

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

/// The column headers of a packed profile.
pub type ProfileColumns<'a> = Seq<'a, ProfileColumn>;
/// The rows of a packed profile.
pub type ProfilePeriods<'a> = Seq<'a, ProfilePeriod<'a>>;
/// The values of one row, in column order.
pub type ProfileValues<'a> = Seq<'a, ProfileValue<'a>>;

/// `SML_GetProfilePack.Res`: a profile as one header and many rows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GetProfilePackResponse<'a> {
    /// The device that answered.
    pub server_id: ServerId<'a>,
    /// The device's time when it answered.
    pub act_time: Time,
    /// The registration period in seconds (0: event driven).
    pub reg_period: u32,
    /// The profile.
    pub tree_path: NameList<'a>,
    /// What each column holds (`header_List`).
    pub columns: ProfileColumns<'a>,
    /// The rows (`period_List`).
    pub periods: ProfilePeriods<'a>,
    /// Raw data, when asked for.
    pub rawdata: Option<&'a [u8]>,
    /// A signature over the profile, when the device signs. **Not verified** by this crate.
    pub profile_signature: Option<&'a [u8]>,
}

impl<'a> GetProfilePackResponse<'a> {
    /// The value of column `obis` in `period`, scaled by the column's header, when it is
    /// numeric. `None` when no column has that name or a header or value cannot be read.
    /// (A decoded response has one value per column; a built one is not checked, and a
    /// short row gives `None` for the missing columns.)
    pub fn quantity(&self, period: &ProfilePeriod<'_>, obis: Obis) -> Option<Quantity> {
        let index = self.columns.iter().position(|c| c.is_ok_and(|c| c.obis == obis))?;
        let column = self.columns.iter().nth(index)?.ok()?;
        let value = period.values.iter().nth(index)?.ok()?;
        let mantissa = match value.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: column.scaler, unit: Some(column.unit) })
    }

    /// Reads the response and checks every row against the header: TR-03109-1 Anlage IV
    /// (77) requires one value per column, so a row of another length is
    /// [`Error::ListLength`], not a table with a hole in it.
    pub(crate) fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(8)?;
        let response = Self {
            server_id: ServerId::new(r.octet_string()?),
            act_time: Time::read(r, ctx.options)?,
            reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
            tree_path: Seq::read(r, ctx)?,
            columns: Seq::read(r, ctx)?,
            periods: Seq::read(r, ctx)?,
            rawdata: r.opt_octet_string()?,
            profile_signature: r.opt_octet_string()?,
        };
        for period in &response.periods {
            let found = period?.values.len();
            if found != response.columns.len() {
                return Err(Error::ListLength { expected: response.columns.len(), found });
            }
        }
        Ok(response)
    }

    pub(crate) fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(8)?;
        w.octet_string(self.server_id.as_bytes())?;
        self.act_time.write(w)?;
        w.unsigned(u64::from(self.reg_period), 4)?;
        self.tree_path.write(w)?;
        self.columns.write(w)?;
        self.periods.write(w)?;
        w.opt_octet_string(self.rawdata)?;
        w.opt_octet_string(self.profile_signature)
    }
}

/// `SML_ProfObjHeaderEntry`: what one column of a packed profile holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ProfileColumn {
    /// What the column's values are.
    pub obis: Obis,
    /// Their unit.
    pub unit: Unit,
    /// Their decimal exponent.
    pub scaler: i8,
}

/// `SML_ProfObjPeriodEntry`: one row of a packed profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProfilePeriod<'a> {
    /// The period's time.
    pub val_time: Time,
    /// Status bits of the period.
    pub status: u64,
    /// One value per column, in the header's order.
    pub values: ProfileValues<'a>,
    /// A signature over the period, when the device signs. **Not verified** by this crate.
    pub period_signature: Option<&'a [u8]>,
}

/// `SML_ValueEntry`: one value of a row; its unit and scaler are in the column header.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ProfileValue<'a> {
    /// 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 sealed::Sealed for ProfileColumn {}
impl sealed::Sealed for ProfilePeriod<'_> {}
impl sealed::Sealed for ProfileValue<'_> {}

impl<'a> Element<'a> for ProfileColumn {
    fn read(r: &mut Reader<'a>, _: Ctx) -> Result<Self> {
        r.list(3)?;
        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)?;
        Ok(Self { obis, unit, scaler })
    }

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

impl<'a> Element<'a> for ProfilePeriod<'a> {
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(4)?;
        Ok(Self {
            val_time: Time::read(r, ctx.options)?,
            status: r.unsigned()?,
            values: Seq::read(r, ctx)?,
            period_signature: r.opt_octet_string()?,
        })
    }

    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(4)?;
        self.val_time.write(w)?;
        w.unsigned(self.status, 8)?;
        self.values.write(w)?;
        w.opt_octet_string(self.period_signature)
    }
}

impl<'a> Element<'a> for ProfileValue<'a> {
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        r.list(2)?;
        let value = SmlValue::read(r, ctx.options)?.0;
        Ok(Self { value, value_signature: r.opt_octet_string()? })
    }

    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(2)?;
        self.value.write(w)?;
        w.opt_octet_string(self.value_signature)
    }
}