1pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Source<'a> {
25 pub channel: taf15::Channel<'a>,
27 pub meter: Address,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct Accepted {
35 pub capture: taf15::Capture,
36 pub counter: u32,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ReadError {
43 WrongSource,
45 Unauthenticated,
47 Replay,
49 Register,
51 Unit,
53 Value,
55 Slot,
57 Decode(protocol::Error),
59 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
93pub 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}