Skip to main content

mbus_kit/
record.rs

1//! Data records (EN 13757-3): `DIB` (DIF + DIFEs), `VIB` (VIF + VIFEs), data.
2//!
3//! ```text
4//! DIF  [DIFE…]  VIF  [VIFE…]  data
5//! ```
6//!
7//! **DIF**: bit 7 extension, bit 6 storage number LSB, bits 5–4 function (instantaneous,
8//! maximum, minimum, during error), bits 3–0 data field (length and coding).
9//! **DIFE**: bit 7 extension, bit 6 subunit, bits 5–4 tariff, bits 3–0 storage number.
10//! **VIF**: bit 7 extension, bits 6–0 what the value is and its decimal exponent
11//! (see [`vif`](crate::vif)).
12//!
13//! Special DIFs: `2F` idle filler (skipped), `0F` manufacturer-specific data to the end,
14//! `1F` the same and more records follow in the next telegram.
15
16use core::fmt;
17
18use crate::time::{Date, DateTime, Time};
19use crate::value::{self, Quantity, Value};
20use crate::vif::{Description, Extension, Kind, MAX_EXTENSIONS, Modifier, RecordError, Vib};
21use crate::{Error, Result};
22
23/// The function field of a DIF.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Function {
26    /// Instantaneous value.
27    Instantaneous,
28    /// Maximum value.
29    Maximum,
30    /// Minimum value.
31    Minimum,
32    /// Value during an error state.
33    DuringError,
34}
35
36impl fmt::Display for Function {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.write_str(match self {
39            Self::Instantaneous => "instantaneous",
40            Self::Maximum => "maximum",
41            Self::Minimum => "minimum",
42            Self::DuringError => "during error",
43        })
44    }
45}
46
47/// The data field of a DIF: how the value is coded.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum DataField {
50    /// No data.
51    None,
52    /// Two's-complement integer, little-endian, of this many bytes.
53    Int(u8),
54    /// 32-bit IEEE 754 real.
55    Real32,
56    /// BCD, little-endian, of this many bytes (2 digits each).
57    Bcd(u8),
58    /// Variable length, announced by an LVAR byte.
59    Variable,
60    /// Selection for readout (no data).
61    Selection,
62}
63
64impl DataField {
65    /// The number of data bytes, `None` for variable length.
66    pub const fn size(self) -> Option<usize> {
67        match self {
68            Self::None | Self::Selection => Some(0),
69            Self::Int(n) | Self::Bcd(n) => Some(n as usize),
70            Self::Real32 => Some(4),
71            Self::Variable => None,
72        }
73    }
74
75    pub(crate) const fn from_nibble(n: u8) -> Self {
76        match n & 0x0F {
77            0x1 => Self::Int(1),
78            0x2 => Self::Int(2),
79            0x3 => Self::Int(3),
80            0x4 => Self::Int(4),
81            0x5 => Self::Real32,
82            0x6 => Self::Int(6),
83            0x7 => Self::Int(8),
84            0x8 => Self::Selection,
85            0x9 => Self::Bcd(1),
86            0xA => Self::Bcd(2),
87            0xB => Self::Bcd(3),
88            0xC => Self::Bcd(4),
89            0xD => Self::Variable,
90            0xE => Self::Bcd(6),
91            // 0x0, and 0xF which the caller handles as a special function.
92            _ => Self::None,
93        }
94    }
95}
96
97/// The number of data bytes an LVAR byte announces (EN 13757-3 Table 6).
98pub(crate) fn lvar_len(lvar: u8) -> Result<usize> {
99    Ok(match lvar {
100        0x00..=0xBF => usize::from(lvar),
101        0xC0..=0xC9 => usize::from(lvar - 0xC0),
102        0xD0..=0xD9 => usize::from(lvar - 0xD0),
103        0xE0..=0xEF => usize::from(lvar - 0xE0),
104        0xF0..=0xF4 => 4 * usize::from(lvar - 0xEC),
105        0xF5 => 48,
106        0xF6 => 64,
107        other => return Err(Error::UnsupportedLvar(other)),
108    })
109}
110
111/// The data information block: what kind of value, which storage, tariff and subunit.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub struct Dib {
114    /// The DIF byte.
115    pub dif: u8,
116    /// Instantaneous, maximum, minimum or during error.
117    pub function: Function,
118    /// How the value is coded.
119    pub data: DataField,
120    /// Storage number: 0 is the current value, higher numbers are historic values.
121    pub storage: u64,
122    /// Tariff.
123    pub tariff: u32,
124    /// Subunit (device unit).
125    pub subunit: u16,
126}
127
128/// One data record.
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub struct Record<'a> {
131    /// Data information.
132    pub dib: Dib,
133    /// Value information.
134    pub vib: Vib<'a>,
135    /// The value.
136    pub value: Value<'a>,
137    /// Whether every byte of this record came out of decryption. `false` for plaintext
138    /// telegrams and for the unencrypted tail after a partially encrypted mode-5/7
139    /// payload, which nothing protects. Decryption is confidentiality, not integrity:
140    /// see [`Authenticity::Encrypted`](crate::app::Authenticity::Encrypted).
141    pub from_ciphertext: bool,
142    /// The DIF … VIFE bytes as transmitted (`None` with a plain-text unit).
143    pub header: Option<&'a [u8]>,
144}
145
146impl Record<'_> {
147    /// What the value is: kind, unit and exponent (see [`Vib::description`]).
148    pub fn description(&self) -> Description {
149        self.vib.description()
150    }
151
152    /// The compact profile this record carries (VIFE `1F`, `13` or `1E` and an LVAR
153    /// payload), if it is one. Its base value is the record with the same storage,
154    /// tariff, subunit and VIF without the profile VIFE.
155    pub fn profile(&self) -> Option<crate::profile::Profile<'_>> {
156        let direction = self.vib.modifiers().find_map(|m| match m {
157            Modifier::CompactProfile(d) => Some(d),
158            _ => None,
159        })?;
160        match self.value {
161            Value::Text(b) | Value::Bytes(b) => crate::profile::Profile::parse(direction, b),
162            _ => None,
163        }
164    }
165
166    /// A short English name for what the record measures, e.g. `"volume flow"`.
167    pub fn name(&self) -> &'static str {
168        self.vib.description().kind.name()
169    }
170
171    /// The value as an exact [`Quantity`], with every multiplicative correction VIFE
172    /// applied.
173    ///
174    /// `None` when the value is not an integer or valid BCD, when the description has
175    /// no unit (identifiers, counters, dates), when a combinable VIFE changes the unit
176    /// or meaning in a way this crate does not model ("per hour", "date of", "number
177    /// of exceeds", additive offset, error, manufacturer-specific, reserved; see
178    /// [`Modifier::keeps_quantity`]), or when the corrected exponent overflows. Never a
179    /// value off by a correction factor (001-describe-every-record/SR-001).
180    pub fn quantity(&self) -> Option<Quantity> {
181        if let Value::Duration(q) = self.value {
182            return Some(q);
183        }
184        let (mantissa, base) = self.value.as_decimal()?;
185        let d = self.vib.description();
186        // A plain-text unit is a quantity without a `Unit`: the text is the unit.
187        let unit = match d.kind {
188            Kind::PlainText => None,
189            _ => Some(d.unit?),
190        };
191        let mut exponent = d.exponent.checked_add(base)?;
192        for m in self.vib.modifiers() {
193            match m {
194                Modifier::Scale(e) => exponent = exponent.checked_add(e)?,
195                m if m.keeps_quantity() => {}
196                _ => return None,
197            }
198        }
199        Some(Quantity { mantissa, exponent, unit })
200    }
201}
202
203impl fmt::Display for Record<'_> {
204    /// One line: `name · modifiers · function · storage · tariff · subunit — value`.
205    /// Defaults (instantaneous, storage 0, tariff 0, subunit 0) are left out.
206    ///
207    /// ```
208    /// # use mbus_kit::Records;
209    /// let r = Records::new(&[0xDA, 0x02, 0x3B, 0x13, 0x01]).next().unwrap().unwrap();
210    /// assert_eq!(r.to_string(), "volume flow · maximum · storage 5 — 0.113 m³/h");
211    /// ```
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        let d = self.vib.description();
214        match (d.kind, self.vib.plain_text()) {
215            // "value — 54.10 %RH"; with an unmodelled modifier "value in igal · per hour".
216            (Kind::PlainText, Some(unit)) if self.quantity().is_none() => {
217                f.write_str("value in ")?;
218                value::escaped(f, unit.iter().rev())?;
219            }
220            (Kind::PlainText, Some(_)) => f.write_str("value")?,
221            (kind, _) => write!(f, "{kind}")?,
222        }
223        // Applied corrections are in the value; "no error" says nothing.
224        let shown = |m: &Modifier| !matches!(m, Modifier::Scale(_) | Modifier::Error(RecordError(0)));
225        for m in self.vib.modifiers().filter(shown) {
226            write!(f, " · {m}")?;
227        }
228        let dib = &self.dib;
229        if dib.function != Function::Instantaneous {
230            write!(f, " · {}", dib.function)?;
231        }
232        if dib.storage != 0 {
233            write!(f, " · storage {}", dib.storage)?;
234        }
235        if dib.tariff != 0 {
236            write!(f, " · tariff {}", dib.tariff)?;
237        }
238        if dib.subunit != 0 {
239            write!(f, " · subunit {}", dib.subunit)?;
240        }
241        f.write_str(" — ")?;
242        match (self.quantity(), self.value) {
243            // A real is exact but long: show 9 significant digits, marked as rounded.
244            (Some(q), Value::Real32(_)) => match q.significant(9) {
245                Some(r) if r != q => write!(f, "≈ {r}")?,
246                _ => write!(f, "{q}")?,
247            },
248            // Type M, relative: a time point given as an offset back from reception (OMS
249            // Annex N N.13: "RX timestamp − 3 s").
250            (Some(q), Value::Duration(_)) => write!(f, "{q} before reception")?,
251            (Some(q), _) => write!(f, "{q}")?,
252            (None, _) if self.profile().is_some() => {
253                if let Some(p) = self.profile() {
254                    write!(f, "{p}")?;
255                }
256            }
257            (None, value) => write!(f, "{value}")?,
258        }
259        if let (Some(_), Some(text)) = (self.quantity().filter(|q| q.unit.is_none()), self.vib.plain_text()) {
260            f.write_str(" ")?;
261            value::escaped(f, text.iter().rev())?;
262        }
263        Ok(())
264    }
265}
266
267/// The records of a payload, parsed one at a time without allocating.
268///
269/// Stops at the first error, and at a `0F`/`1F` DIF; [`Records::manufacturer_data`]
270/// then returns the manufacturer-specific bytes that follow.
271#[derive(Clone, Debug)]
272pub struct Records<'a> {
273    buf: &'a [u8],
274    pos: usize,
275    done: bool,
276    manufacturer: Option<&'a [u8]>,
277    more_follows: bool,
278    ciphertext_end: usize,
279}
280
281impl<'a> Records<'a> {
282    /// Records in `buf` (the bytes after the data header).
283    pub const fn new(buf: &'a [u8]) -> Self {
284        Self { buf, pos: 0, done: false, manufacturer: None, more_follows: false, ciphertext_end: 0 }
285    }
286
287    /// Records whose first `ciphertext_end` bytes were decrypted.
288    pub(crate) const fn decrypted(buf: &'a [u8], ciphertext_end: usize) -> Self {
289        Self { buf, pos: 0, done: false, manufacturer: None, more_follows: false, ciphertext_end }
290    }
291
292    /// Manufacturer-specific bytes after a `0F`/`1F` DIF, once iteration has reached them.
293    pub const fn manufacturer_data(&self) -> Option<&'a [u8]> {
294        self.manufacturer
295    }
296
297    /// Whether a `1F` DIF announced more records in the next telegram.
298    pub const fn more_follows(&self) -> bool {
299        self.more_follows
300    }
301
302    fn byte(&mut self) -> Result<u8> {
303        let b = self.buf.get(self.pos).copied().ok_or(Error::UnexpectedEnd)?;
304        self.pos += 1;
305        Ok(b)
306    }
307
308    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
309        let end = self.pos.checked_add(n).ok_or(Error::UnexpectedEnd)?;
310        let s = self.buf.get(self.pos..end).ok_or(Error::UnexpectedEnd)?;
311        self.pos = end;
312        Ok(s)
313    }
314
315    fn record(&mut self, dif: u8) -> Result<Record<'a>> {
316        let header_start = self.pos.saturating_sub(1);
317        let function = match (dif >> 4) & 0x03 {
318            0 => Function::Instantaneous,
319            1 => Function::Maximum,
320            2 => Function::Minimum,
321            _ => Function::DuringError,
322        };
323        let mut storage = u64::from((dif >> 6) & 1);
324        let mut tariff = 0u32;
325        let mut subunit = 0u16;
326        let mut ext = dif & 0x80 != 0;
327        let mut i = 0u32;
328        while ext {
329            if i as usize >= MAX_EXTENSIONS {
330                return Err(Error::TooManyExtensions);
331            }
332            let dife = self.byte()?;
333            storage |= u64::from(dife & 0x0F) << (1 + 4 * i);
334            tariff |= u32::from((dife >> 4) & 0x03) << (2 * i);
335            subunit |= u16::from((dife >> 6) & 1) << i;
336            ext = dife & 0x80 != 0;
337            i += 1;
338        }
339        let data = DataField::from_nibble(dif);
340        let dib = Dib { dif, function, data, storage, tariff, subunit };
341
342        // A plain-text VIF `FC` puts its text after the VIFE chain (EN 13757-3:2018
343        // Table C.2); some meters (Elvaco CMa10) put it straight after the VIF. Try the
344        // standard first, the deviation if the standard does not parse.
345        let start = self.pos;
346        match self.value_part(dib, false, header_start) {
347            Err(e) if self.buf.get(start) == Some(&0xFC) => {
348                self.pos = start;
349                self.value_part(dib, true, header_start).map_err(|_| e)
350            }
351            r => r,
352        }
353    }
354
355    fn plain_text(&mut self) -> Result<&'a [u8]> {
356        let n = self.byte()?;
357        self.take(usize::from(n))
358    }
359
360    fn value_part(&mut self, dib: Dib, text_first: bool, header_start: usize) -> Result<Record<'a>> {
361        let data = dib.data;
362        let vif = self.byte()?;
363        let mut plain_text = if text_first { Some(self.plain_text()?) } else { None };
364        let mut vifes = [0u8; MAX_EXTENSIONS];
365        let mut vife_len = 0u8;
366        let mut ext = vif & 0x80 != 0;
367        while ext {
368            let vife = self.byte()?;
369            *vifes.get_mut(usize::from(vife_len)).ok_or(Error::TooManyExtensions)? = vife;
370            vife_len += 1;
371            ext = vife & 0x80 != 0;
372        }
373        // DIF … VIFE: the layout a compact frame refers to (none with a plain-text unit).
374        let header = (vif & 0x7F != 0x7C).then(|| self.buf.get(header_start..self.pos)).flatten();
375        if vif & 0x7F == 0x7C && plain_text.is_none() {
376            plain_text = Some(self.plain_text()?);
377        }
378        let vib = Vib::new(vif, vifes, vife_len, plain_text);
379        let time_point =
380            vib.description().kind.is_time_point() || vib.modifiers().any(Modifier::is_time_point);
381        let unsigned = vib.modifiers().any(|m| m == Modifier::Extension(Extension::Unsigned));
382
383        let value = match data {
384            DataField::None | DataField::Selection => Value::None,
385            DataField::Int(n) => {
386                let bytes = self.take(usize::from(n))?;
387                match (time_point, bytes) {
388                    (true, &[b0, b1]) => Value::Date(Date::from_type_g(b0, b1)),
389                    (true, &[b0, b1, b2]) => Value::Time(Time::from_type_j(b0, b1, b2)),
390                    (true, &[b0, b1, b2, b3]) => Value::DateTime(DateTime::from_type_f([b0, b1, b2, b3])),
391                    (true, &[b0, b1, b2, b3, b4, b5]) => {
392                        Value::DateTime(DateTime::from_type_i([b0, b1, b2, b3, b4, b5]))
393                    }
394                    _ if unsigned => Value::UInt(value::le_unsigned(bytes)),
395                    _ => Value::Int(value::le_signed(bytes)),
396                }
397            }
398            DataField::Real32 => {
399                let b = self.take(4)?;
400                Value::Real32(u32::from_le_bytes(b.try_into().map_err(|_| Error::UnexpectedEnd)?))
401            }
402            DataField::Bcd(n) => value::bcd(self.take(usize::from(n))?),
403            DataField::Variable => {
404                let lvar = self.byte()?;
405                match lvar {
406                    0x00..=0xBF => Value::Text(self.take(usize::from(lvar))?),
407                    0xC0..=0xC9 => value::bcd(self.take(usize::from(lvar - 0xC0))?),
408                    0xD0..=0xD9 => value::bcd(self.take(usize::from(lvar - 0xD0))?).negate(),
409                    0xE0..=0xEF => {
410                        let bytes = self.take(usize::from(lvar - 0xE0))?;
411                        if let Some(d) = time_point.then(|| value::type_m(bytes)).flatten() {
412                            Value::Duration(d)
413                        } else if bytes.len() <= 8 {
414                            Value::Int(value::le_signed(bytes))
415                        } else {
416                            Value::Bytes(bytes)
417                        }
418                    }
419                    // Binary numbers of 16, 20, 24, 28, 32 (4 × (LVAR − EC)), 48 and 64 bytes
420                    // (EN 13757-3:2018 as read by libmbus and wmbusmeters).
421                    0xF0..=0xF4 => Value::Bytes(self.take(4 * usize::from(lvar - 0xEC))?),
422                    0xF5 => Value::Bytes(self.take(48)?),
423                    0xF6 => Value::Bytes(self.take(64)?),
424                    other => return Err(Error::UnsupportedLvar(other)),
425                }
426            }
427        };
428        Ok(Record { dib, vib, value, from_ciphertext: false, header })
429    }
430}
431
432impl<'a> Iterator for Records<'a> {
433    type Item = Result<Record<'a>>;
434
435    fn next(&mut self) -> Option<Self::Item> {
436        while !self.done {
437            let Some(&dif) = self.buf.get(self.pos) else {
438                self.done = true;
439                return None;
440            };
441            self.pos += 1;
442            match dif {
443                // 2F: idle filler; 7F: global readout request, a marker without data.
444                0x2F | 0x7F => {}
445                0x0F | 0x1F => {
446                    self.more_follows = dif == 0x1F;
447                    self.manufacturer = Some(self.buf.get(self.pos..).unwrap_or(&[]));
448                    self.done = true;
449                    return None;
450                }
451                d if d & 0x0F == 0x0F => {
452                    self.done = true;
453                    return Some(Err(Error::ReservedDif(d)));
454                }
455                d => {
456                    let r = self.record(d).map(|mut r| {
457                        r.from_ciphertext = self.pos <= self.ciphertext_end;
458                        r
459                    });
460                    self.done = r.is_err();
461                    return Some(r);
462                }
463            }
464        }
465        None
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    extern crate std;
472    use super::*;
473    use std::string::ToString;
474
475    #[test]
476    fn storage_tariff_and_subunit_from_extensions() {
477        // DA 02: storage LSB 1 + DIFE storage 2 → 5; maximum; 4-digit BCD.
478        let mut r = Records::new(&[0xDA, 0x02, 0x3B, 0x13, 0x01]);
479        let rec = r.next().unwrap().unwrap();
480        assert_eq!(rec.dib.storage, 5);
481        assert_eq!(rec.dib.function, Function::Maximum);
482        assert_eq!(rec.dib.data, DataField::Bcd(2));
483        assert_eq!(rec.value, Value::Bcd(113));
484        // 8B 60: DIFE with subunit 1, tariff 2.
485        let rec = Records::new(&[0x8B, 0x60, 0x04, 0x37, 0x18, 0x02]).next().unwrap().unwrap();
486        assert_eq!((rec.dib.storage, rec.dib.tariff, rec.dib.subunit), (0, 2, 1));
487    }
488
489    #[test]
490    fn filler_and_manufacturer_data() {
491        let mut r = Records::new(&[0x2F, 0x2F, 0x01, 0xFD, 0x08, 0x05, 0x0F, 0xAA, 0xBB]);
492        let rec = r.next().unwrap().unwrap();
493        assert_eq!(rec.vib.vif(), 0xFD);
494        assert_eq!(rec.vib.vifes(), &[0x08]);
495        assert_eq!(rec.name(), "access number");
496        assert_eq!(rec.value, Value::Int(5));
497        assert!(r.next().is_none());
498        assert_eq!(r.manufacturer_data(), Some(&[0xAA, 0xBB][..]));
499        assert!(!r.more_follows());
500    }
501
502    #[test]
503    fn plain_text_vif() {
504        // 01 FC 03? no: VIF 7C, then length 3, then "hPa" reversed, then 1-byte int.
505        let rec = Records::new(&[0x01, 0x7C, 0x03, b'a', b'P', b'h', 0x2A]).next().unwrap().unwrap();
506        assert_eq!(rec.vib.plain_text(), Some(&b"aPh"[..]));
507        assert_eq!(rec.to_string(), "value — 42 hPa");
508        assert_eq!(rec.value, Value::Int(42));
509    }
510
511    #[test]
512    fn plain_text_after_vifes_and_the_elvaco_deviation() {
513        // EN 13757-3:2018 Table C.2: 0C FC A2 73 04 "lagi" 26 08 42 75 = 75420.826 igal/h.
514        let rec =
515            Records::new(&[0x0C, 0xFC, 0xA2, 0x73, 0x04, b'l', b'a', b'g', b'i', 0x26, 0x08, 0x42, 0x75])
516                .next()
517                .unwrap()
518                .unwrap();
519        assert_eq!(rec.vib.plain_text(), Some(&b"lagi"[..]));
520        assert_eq!(rec.value, Value::Bcd(75_420_826));
521        assert_eq!(rec.to_string(), "value in igal · per hour — 75420826");
522        // Elvaco CMa10 (libmbus test frame): 02 FC 03 "HR%" 74 22 15 = 54.10 %RH.
523        let rec =
524            Records::new(&[0x02, 0xFC, 0x03, b'H', b'R', b'%', 0x74, 0x22, 0x15]).next().unwrap().unwrap();
525        assert_eq!(rec.vib.plain_text(), Some(&b"HR%"[..]));
526        assert_eq!(rec.vib.vifes(), &[0x74]);
527        assert_eq!(rec.value, Value::Int(0x1522));
528    }
529
530    #[test]
531    fn too_many_extensions() {
532        let input = [0x84u8, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00];
533        assert_eq!(Records::new(&input).next(), Some(Err(Error::TooManyExtensions)));
534    }
535
536    #[test]
537    fn truncation_is_an_error() {
538        let full = [0x04u8, 0x13, 0x01, 0x02, 0x03, 0x04];
539        for cut in 1..full.len() {
540            assert!(matches!(Records::new(&full[..cut]).next(), Some(Err(_))), "cut {cut}");
541        }
542    }
543}