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