Skip to main content

smgw_lmn/
mbus.rs

1//! Import an authenticated wireless M-Bus (OMS) gas meter telegram into a TAF 15 history.
2//!
3//! Open the radio telegram with the [upstream crate](protocol), for example
4//! [`protocol::wireless::open`] with the meter's key. Then pass its application layer
5//! to [`capture_telegram`]. Only telegrams whose MAC or tag verified (OMS mode 7 with an
6//! AFL CMAC, or mode 10) are accepted. Mode 5 and the ELL hide a reading, but anyone in
7//! radio range can alter it without the key, so they are rejected as unauthenticated.
8//!
9//! Gas meters push readings without a gateway request. The host times them with its
10//! own clock ([`Slot`]) and keeps the last accepted message counter. It stores
11//! [`Accepted::counter`] in the same transaction as the history and passes it back as
12//! `last_counter` on the next call. A counter that does not rise is a replay.
13
14/// Upstream M-Bus and OMS types (`mbus-kit` with OMS security).
15pub use mbus_kit as protocol;
16
17use crate::Slot;
18use core::fmt;
19use protocol::{Address, Application, Function, Kind, Modifier, Unit, app::Authenticity};
20use smgw_core::taf15;
21
22/// The meter and register commissioned for one gas channel.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Source<'a> {
25    /// The volume register OBIS (for example `7-0:3.0.0*255`) with unit `m³`.
26    pub channel: taf15::Channel<'a>,
27    /// Manufacturer, identification number and medium from the meter's key sheet.
28    /// The version field is ignored.
29    pub meter: Address,
30}
31
32/// An accepted reading and the message counter the host must store with it.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct Accepted {
35    pub capture: taf15::Capture,
36    /// The authenticated OMS message counter of this telegram.
37    pub counter: u32,
38}
39
40/// Why a telegram was not imported. The destination is unchanged in every case.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ReadError {
43    /// The meter address or destination channel differs from commissioning.
44    WrongSource,
45    /// The telegram is plaintext, still encrypted, or only encrypted without a MAC.
46    Unauthenticated,
47    /// The message counter is not greater than the last accepted counter.
48    Replay,
49    /// The authenticated plain volume register is missing or appears more than once.
50    Register,
51    /// The register is not in m³, or the channel unit is not `m³`.
52    Unit,
53    /// The register value is not an exact integer quantity.
54    Value,
55    /// The reception time lies outside the slot it should fill.
56    Slot,
57    /// A record of the telegram is malformed.
58    Decode(protocol::Error),
59    /// The destination rejected the slot or a conflicting reading.
60    Capture(taf15::Error),
61}
62
63impl fmt::Display for ReadError {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(match self {
66            Self::WrongSource => "meter address or channel differs from commissioning",
67            Self::Unauthenticated => "telegram is not authenticated by an OMS MAC or tag",
68            Self::Replay => "message counter did not increase",
69            Self::Register => "expected exactly one authenticated plain volume register",
70            Self::Unit => "expected a volume register in m³",
71            Self::Value => "expected an exact integer register value",
72            Self::Slot => "reception time is outside the slot",
73            Self::Decode(e) => return write!(f, "M-Bus: {e}"),
74            Self::Capture(e) => return e.fmt(f),
75        })
76    }
77}
78
79impl core::error::Error for ReadError {
80    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
81        match self {
82            Self::Decode(e) => Some(e),
83            Self::Capture(e) => Some(e),
84            _ => None,
85        }
86    }
87}
88
89fn same_meter(a: Address, b: Address) -> bool {
90    a.manufacturer == b.manufacturer && a.id == b.id && a.medium == b.medium
91}
92
93/// Record the volume register of one authenticated telegram at `slot`.
94///
95/// The register is the single record with instantaneous function, storage 0,
96/// tariff 0, subunit 0, kind volume, unit m³ and no modifier other than a scale. The
97/// MAC or tag must cover the record's own bytes ([`protocol::Record::authenticity`]); a
98/// record nothing protects is ignored.
99pub fn capture_telegram<const N: usize>(
100    app: &Application<'_>,
101    source: &Source<'_>,
102    slot: Slot,
103    last_counter: Option<u32>,
104    destination: &mut taf15::Profile<'_, N>,
105) -> Result<Accepted, ReadError> {
106    if destination.channel() != source.channel
107        || !app
108            .meter()
109            .is_some_and(|meter| same_meter(meter, source.meter))
110    {
111        return Err(ReadError::WrongSource);
112    }
113    if source.channel.unit != "m³" {
114        return Err(ReadError::Unit);
115    }
116    let Authenticity::Authenticated { counter } = app.authenticity else {
117        return Err(ReadError::Unauthenticated);
118    };
119    if last_counter.is_some_and(|last| counter <= last) {
120        return Err(ReadError::Replay);
121    }
122    if !slot.contains_reception(destination.period().seconds()) {
123        return Err(ReadError::Slot);
124    }
125
126    let records = app.records().ok_or(ReadError::Unauthenticated)?;
127    let mut found = None;
128    for record in records {
129        let record = record.map_err(ReadError::Decode)?;
130        let dib = record.dib;
131        let plain = dib.function == Function::Instantaneous
132            && (dib.storage, dib.tariff, dib.subunit) == (0, 0, 0)
133            && record.description().kind == Kind::Volume
134            && record
135                .vib
136                .modifiers()
137                .all(|m| matches!(m, Modifier::Scale(_)));
138        let covered = matches!(record.authenticity, Authenticity::Authenticated { .. });
139        if !plain || !covered {
140            continue;
141        }
142        if found.is_some() {
143            return Err(ReadError::Register);
144        }
145        found = Some(record);
146    }
147    let record = found.ok_or(ReadError::Register)?;
148    let quantity = record.quantity().ok_or(ReadError::Value)?;
149    if quantity.unit != Some(Unit::M3) {
150        return Err(ReadError::Unit);
151    }
152    let capture = destination
153        .capture(
154            source.channel,
155            taf15::Record {
156                reference_utc: slot.reference_utc,
157                measured_utc: slot.received_utc,
158                coefficient: quantity.mantissa,
159                scale: quantity.exponent,
160                meter_status: None,
161            },
162        )
163        .map_err(ReadError::Capture)?;
164    Ok(Accepted { capture, counter })
165}