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