Skip to main content

mbus_kit/
compact.rs

1//! Compact frames (EN 13757-3:2018 Annex G): values without their DIF/VIF layout.
2//!
3//! A meter sends a full frame now and then (CI `78`/`7A`/`72`) and compact frames (CI
4//! `79`/`7B`/`73`) in between. A compact frame carries the **format signature** — a CRC
5//! of the full frame's DIF, DIFE, VIF and VIFE bytes — the **full-frame CRC** of the
6//! records it stands for, and the data bytes only. A receiver keeps the layouts it has
7//! seen, keyed by signature, and rebuilds the full records from them.
8//!
9//! ```text
10//! compact:  79  signature(2, LE)  full-frame CRC(2, LE)  data…
11//! format:   69  length  signature(2, LE)  DIF VIF … (the layout only)
12//! ```
13//!
14//! The cache is the caller's: implement [`Formats`] over a map or a database, or use the
15//! fixed-size [`FormatCache`] in firmware. [`Format::of`] computes a full frame's layout
16//! and signature to put into it.
17
18use crate::crc::crc16;
19use crate::record::{DataField, Records};
20use crate::{Check, Error, Result};
21
22/// A record layout: the DIF/DIFE/VIF/VIFE bytes of every record, and their signature.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct Format<'a> {
25    /// CRC-16/EN-13757 of `headers`.
26    pub signature: u16,
27    /// DIF, DIFEs, VIF and VIFEs of every record, in order; fillers left out.
28    pub headers: &'a [u8],
29}
30
31impl<'a> Format<'a> {
32    /// The layout of `records` (the data records of a full frame), written into `out`.
33    /// `None` if a record does not parse, `out` is too small, or a record cannot be
34    /// carried in a compact frame (plain-text VIF, manufacturer data).
35    pub fn of<'o>(records: &Records<'_>, out: &'o mut [u8]) -> Option<Format<'o>> {
36        let mut n = 0usize;
37        for r in records.clone() {
38            let header = r.ok()?.header?;
39            out.get_mut(n..n + header.len())?.copy_from_slice(header);
40            n += header.len();
41        }
42        let headers = out.get(..n)?;
43        Some(Format { signature: crc16(headers), headers })
44    }
45
46    /// A layout received in a format frame (CI `69`/`6A`/`6B`); `None` if the bytes do
47    /// not match the signature they come with.
48    pub fn received(signature: u16, headers: &'a [u8]) -> Option<Self> {
49        (crc16(headers) == signature).then_some(Self { signature, headers })
50    }
51}
52
53/// Where compact frames find their layouts.
54///
55/// **Fill it only from frames you trust at least as much as the compact frames it will
56/// serve.** A CRC-16 signature is not a MAC: anyone in radio range can send a format frame
57/// or a plaintext full frame whose layout collides with a genuine one and re-reads the
58/// same data bytes as other records with a matching full-frame CRC. Expanded records are
59/// only as trustworthy as the frame their layout came from: for an authenticated or
60/// decrypted compact frame, learn layouts from that meter's decrypted full frames only
61/// (004-compact-and-fragments/SR-001).
62pub trait Formats {
63    /// The DIF/VIF bytes for `signature`, if known.
64    fn headers(&self, signature: u16) -> Option<&[u8]>;
65}
66
67impl Formats for Format<'_> {
68    fn headers(&self, signature: u16) -> Option<&[u8]> {
69        (self.signature == signature).then_some(self.headers)
70    }
71}
72
73impl Formats for [Format<'_>] {
74    fn headers(&self, signature: u16) -> Option<&[u8]> {
75        self.iter().find_map(|f| f.headers(signature))
76    }
77}
78
79impl<F: Formats + ?Sized> Formats for &F {
80    fn headers(&self, signature: u16) -> Option<&[u8]> {
81        (**self).headers(signature)
82    }
83}
84
85/// A fixed-size cache of `N` layouts of at most `B` bytes, replacing the oldest: enough
86/// for the handful of meters a firmware listens to, without an allocator.
87#[derive(Clone, Debug)]
88pub struct FormatCache<const N: usize, const B: usize> {
89    entries: [(u16, u8, [u8; B]); N],
90    used: usize,
91    next: usize,
92}
93
94impl<const N: usize, const B: usize> Default for FormatCache<N, B> {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100impl<const N: usize, const B: usize> FormatCache<N, B> {
101    /// An empty cache.
102    pub const fn new() -> Self {
103        Self { entries: [(0, 0, [0; B]); N], used: 0, next: 0 }
104    }
105
106    /// Remember a layout (replacing the oldest when full). `false` if it is longer than
107    /// `B` bytes (or 255, the most a format frame can carry).
108    pub fn insert(&mut self, format: &Format<'_>) -> bool {
109        let len = format.headers.len();
110        let Ok(stored) = u8::try_from(len) else { return false };
111        if len > B || N == 0 {
112            return false;
113        }
114        if self.headers(format.signature).is_some() {
115            return true;
116        }
117        let Some((sig, l, bytes)) = self.entries.get_mut(self.next) else { return false };
118        let Some(dst) = bytes.get_mut(..len) else { return false };
119        dst.copy_from_slice(format.headers);
120        *sig = format.signature;
121        *l = stored;
122        self.next = (self.next + 1) % N;
123        self.used = (self.used + 1).min(N);
124        true
125    }
126}
127
128impl<const N: usize, const B: usize> Formats for FormatCache<N, B> {
129    fn headers(&self, signature: u16) -> Option<&[u8]> {
130        self.entries
131            .iter()
132            .take(self.used)
133            .find(|(s, ..)| *s == signature)
134            .and_then(|(_, l, b)| b.get(..usize::from(*l)))
135    }
136}
137
138/// A compact frame's application data.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub struct Compact<'a> {
141    /// The format signature: which layout the data follows.
142    pub signature: u16,
143    /// CRC-16/EN-13757 of the full records this frame stands for.
144    pub crc: u16,
145    /// The data bytes of every record, concatenated.
146    pub data: &'a [u8],
147    /// Came out of a decrypted ELL: the expanded records say so.
148    decrypted: bool,
149}
150
151impl Compact<'_> {
152    pub(crate) fn parse(bytes: &[u8], decrypted: bool) -> Result<Compact<'_>> {
153        let (&[s0, s1, c0, c1], data) = bytes.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
154        let (signature, crc) = (u16::from_le_bytes([s0, s1]), u16::from_le_bytes([c0, c1]));
155        Ok(Compact { signature, crc, data, decrypted })
156    }
157
158    /// Rebuild the full records into `out` with the layout from `formats`, and verify the
159    /// full-frame CRC. [`Error::UnknownFormat`] when the layout is not known yet (wait for
160    /// a full frame); [`Check::FullFrameCrc`] when the rebuilt records do not match.
161    pub fn expand<'o, F: Formats + ?Sized>(&self, formats: &F, out: &'o mut [u8]) -> Result<Records<'o>> {
162        let headers = formats.headers(self.signature).ok_or(Error::UnknownFormat(self.signature))?;
163        let mut h = 0usize; // position in headers
164        let mut d = 0usize; // position in data
165        let mut n = 0usize; // position in out
166        let mut put = |bytes: &[u8], n: &mut usize| -> Result<()> {
167            out.get_mut(*n..*n + bytes.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
168            *n += bytes.len();
169            Ok(())
170        };
171        while h < headers.len() {
172            let start = h;
173            let dif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
174            h += 1;
175            if dif & 0x0F == 0x0F {
176                // Manufacturer data (0F/1F) and specials are not part of a layout.
177                return Err(Error::InvalidFormat);
178            }
179            let mut ext = dif & 0x80 != 0;
180            while ext {
181                ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
182                h += 1;
183            }
184            let vif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
185            h += 1;
186            if vif & 0x7F == 0x7C {
187                // A plain-text unit's text sits between VIF and data: not in a layout.
188                return Err(Error::InvalidFormat);
189            }
190            let mut ext = vif & 0x80 != 0;
191            while ext {
192                ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
193                h += 1;
194            }
195            put(headers.get(start..h).ok_or(Error::UnexpectedEnd)?, &mut n)?;
196            let len = match DataField::from_nibble(dif) {
197                DataField::None | DataField::Selection => 0,
198                DataField::Int(k) | DataField::Bcd(k) => usize::from(k),
199                DataField::Real32 => 4,
200                DataField::Variable => {
201                    1 + crate::record::lvar_len(*self.data.get(d).ok_or(Error::UnexpectedEnd)?)?
202                }
203            };
204            put(self.data.get(d..d + len).ok_or(Error::UnexpectedEnd)?, &mut n)?;
205            d += len;
206        }
207        let full = out.get(..n).ok_or(Error::OutputTooSmall)?;
208        if d != self.data.len() || crc16(full) != self.crc {
209            return Err(Error::Verification(Check::FullFrameCrc));
210        }
211        Ok(if self.decrypted { Records::decrypted(full, full.len()) } else { Records::new(full) })
212    }
213}