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
//! The energy direction a meter reports in the status word of its energy registers.
//!
//! Many meters send the instantaneous power (`1-0:16.7.0`) without a sign and put the
//! direction, import (+A) or export (−A), in a status bit of `1.8.0`. Two layouts are in
//! the field, and the value alone does not tell them apart, so the caller names the one
//! the meter uses:
//!
//! | Layout | Bit | Specified by | Seen on |
//! |---|---|---|---|
//! | [`StatusWord::Edl`] | 5 (`0x20`) | FNN Lastenheft EDL 1.2, Tab. 7 | EMH ED300L, EMH eHZ, ISKRA MT175 |
//! | [`StatusWord::Mme`] | 11 (`0x800`) | manufacturer manuals (4-byte status) | DZG DVS74/DWSB20, Holley DTZ541 (corpus), Elster AS2020 |
//!
//! ```
//! use sml_kit::{Direction, GetListResponse, ListEntries, ListEntry, Obis, ServerId, StatusWord, Unit};
//!
//! // An ED300L feeding in: power without a sign, bit 5 set on 1.8.0.
//! let entries = [
//!     ListEntry { status: Some(0x1b0), ..ListEntry::number(Obis::ENERGY_IMPORT, Unit::WH, -1, 12_345) },
//!     ListEntry::number(Obis::POWER, Unit::W, 0, 230),
//! ];
//! let list = GetListResponse {
//!     client_id: None,
//!     server_id: ServerId::new(b"\x09\x01EMH\x00\x00\x41\xf0\x45"),
//!     list_name: None,
//!     act_sensor_time: None,
//!     entries: ListEntries::from_slice(&entries),
//!     list_signature: None,
//!     act_gateway_time: None,
//! };
//! assert_eq!(list.direction(StatusWord::Edl), Some(Direction::Export));
//! assert_eq!(list.signed_power(StatusWord::Edl).unwrap().to_string(), "-230 W");
//! ```

use core::fmt;

use crate::{GetListResponse, Obis, Quantity};

/// Where a meter's status word carries the energy direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StatusWord {
    /// Bit 5 (`0x20`): "Energierichtung, 0 = +A, 1 = −A" (FNN Lastenheft EDL 1.2, Tab. 7).
    /// EDL21 meters such as the EMH ED300L and eHZ and the ISKRA MT175.
    Edl,
    /// Bit 11 (`0x800`) of the 4-byte status of newer meters (bits 12–14 are the phases).
    /// DZG DVS74 and DWSB20, Holley DTZ541, Elster AS2020.
    Mme,
}

impl StatusWord {
    const fn mask(self) -> u64 {
        match self {
            Self::Edl => 1 << 5,
            Self::Mme => 1 << 11,
        }
    }
}

/// The direction of energy flow, from the meter's point of view.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
    /// Drawn from the grid (+A).
    Import,
    /// Fed into the grid (−A).
    Export,
}

impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Import => "import (+A)",
            Self::Export => "export (−A)",
        })
    }
}

impl GetListResponse<'_> {
    /// The direction the status word of `1.8.0` reports (of `2.8.0` when `1.8.0` has
    /// none), read in `layout`. `None` when neither register carries a status.
    ///
    /// The meter samples the bit with its registers and reports import at standstill.
    pub fn direction(&self, layout: StatusWord) -> Option<Direction> {
        let status = [Obis::ENERGY_IMPORT, Obis::ENERGY_EXPORT]
            .into_iter()
            .find_map(|obis| self.get(obis).and_then(|e| e.status))?;
        Some(if status & layout.mask() == 0 { Direction::Import } else { Direction::Export })
    }

    /// The power (`16.7.0`) with the sign from the status word: a power without a sign
    /// is negated when the meter reports export.
    ///
    /// A value the meter already sent negative is returned as sent. If the status then
    /// says import, the two disagree: on a DZG meter that is the DVS74 sign bug
    /// (`ParseOptions::with_dzg_power`), see the Meter quirks page.
    pub fn signed_power(&self, layout: StatusWord) -> Option<Quantity> {
        let power = self.quantity(Obis::POWER)?;
        Some(match self.direction(layout) {
            Some(Direction::Export) if power.mantissa > 0 => Quantity { mantissa: -power.mantissa, ..power },
            _ => power,
        })
    }
}