Skip to main content

mbus_kit/
wireless.rs

1//! Wireless M-Bus link layer (EN 13757-4): frame formats A and B.
2//!
3//! Both formats start with the same 10 bytes:
4//!
5//! ```text
6//! L  C  M M  A A A A A A
7//!       ^^^  ^^^^^^^^^^^ address: ID (4, BCD, LSB first), version, device type
8//!       manufacturer (LE, three letters)
9//! ```
10//!
11//! **Format A** (modes S, T and C with preamble A): every block carries its own CRC.
12//! Block 1 is those 10 bytes, then blocks of 16 bytes, the last one shorter. `L` counts
13//! the bytes after itself **without** the CRCs.
14//!
15//! **Format B** (mode C with preamble B): block 1 has no CRC; block 2 (up to 118 bytes
16//! including its CRC) ends with a CRC over blocks 1 and 2; a longer frame has a third
17//! block with its own CRC. `L` counts the bytes after itself **with** the CRCs.
18//!
19//! **Stripped**: the receiver already removed the CRCs; `L` counts the bytes after it.
20//!
21//! CRCs are CRC-16/EN-13757, most significant byte first. The decoder copies the data
22//! without CRCs into a caller buffer, so the frame borrows from that buffer.
23
24pub use crate::app::Address;
25use crate::app::Application;
26use crate::crc::crc16;
27use crate::{Error, Result};
28
29/// Frame format.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Format {
32    /// Format A: a CRC after every block.
33    A,
34    /// Format B: CRCs after block 2 and block 3 only.
35    B,
36    /// The receiver has already checked and removed the CRCs (what most wM-Bus sticks
37    /// deliver, and how captures are usually logged): `L` counts the bytes after itself.
38    /// Integrity then rests on the receiver.
39    Stripped,
40}
41
42/// C-field values a meter sends.
43pub mod control {
44    /// `SND_NR`: unsolicited user data, no reply expected. A meter's periodic telegram.
45    pub const SND_NR: u8 = 0x44;
46    /// `SND_IR`: installation request.
47    pub const SND_IR: u8 = 0x46;
48    /// `ACC_NR`: access demand, no data.
49    pub const ACC_NR: u8 = 0x47;
50    /// `RSP_UD`: response to a request.
51    pub const RSP_UD: u8 = 0x08;
52}
53
54/// A decoded wireless frame, CRCs removed.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct Frame<'o> {
57    /// C field.
58    pub c: u8,
59    /// The sending meter.
60    pub address: Address,
61    /// CI field: what the payload is.
62    pub ci: u8,
63    /// The payload after the CI field (header and records, possibly encrypted).
64    pub payload: &'o [u8],
65}
66
67impl<'o> Frame<'o> {
68    /// The layers above the link layer (ELL, AFL, TPL) and the records, parsed with this
69    /// frame's address as the link address (it forms the mode-5 and ELL IVs).
70    pub fn application(&self) -> Result<Application<'o>> {
71        Application::parse_with_link(self.ci, self.payload, Some(self.address))
72    }
73}
74
75/// A received wireless telegram, opened: link layer and application, decrypted where
76/// a key was found.
77#[cfg(feature = "oms")]
78#[derive(Clone, Debug)]
79pub struct Telegram<'b> {
80    /// C field.
81    pub c: u8,
82    /// The transmitter (for a meter behind a radio adapter, see [`Application::meter`]).
83    pub address: Address,
84    /// The application, decrypted if the key lookup had the meter's key.
85    pub app: Application<'b>,
86}
87
88/// One call from radio bytes to records: check and strip the CRCs, parse every layer,
89/// and decrypt (and authenticate) with the meter's key from `keys`.
90///
91/// `buf` holds the frame without CRCs and the plaintext: it needs twice the frame's
92/// length (512 bytes always suffice). Returns `Ok(None)` when `raw` is shorter than
93/// its `L` field announces. Without the meter's key, the telegram is returned with its
94/// body still [`Body::Encrypted`](crate::Body::Encrypted) and
95/// [`Authenticity::None`](crate::app::Authenticity::None), not as an error: the
96/// unencrypted layers (address, ELL, header) are still useful.
97///
98/// An ELL-encrypted telegram whose TPL is encrypted as well is opened through both.
99#[cfg(feature = "oms")]
100pub fn open<'b, K: crate::oms::Keys + ?Sized>(
101    raw: &[u8],
102    format: Format,
103    keys: &K,
104    buf: &'b mut [u8],
105) -> Result<Option<(Telegram<'b>, usize)>> {
106    let half = buf.len() / 2;
107    let (frame_buf, plain_buf) = buf.split_at_mut(half);
108    let Some((frame, used)) = decode(raw, format, &mut *frame_buf)? else { return Ok(None) };
109    let (c, address) = (frame.c, frame.address);
110    let app = frame.application()?;
111    let telegram = |app| Ok(Some((Telegram { c, address, app }, used)));
112    // Not encrypted, or no key: the frame as decoded (decoded again, to lend it `buf`).
113    let plain = |frame_buf: &'b mut [u8]| match decode(raw, format, frame_buf)? {
114        Some((frame, _)) => telegram(frame.application()?),
115        None => Ok(None),
116    };
117    let crate::Body::Encrypted(e) = &app.body else { return plain(frame_buf) };
118    let inner = match e.decrypt(keys, plain_buf) {
119        Err(Error::NoKey) => return plain(frame_buf),
120        other => other?,
121    };
122    // An encrypted ELL around an encrypted TPL: open the TPL into the frame's half.
123    let crate::Body::Encrypted(e) = &inner.body else { return telegram(inner) };
124    match e.decrypt(keys, frame_buf) {
125        Err(Error::NoKey) => telegram(inner),
126        other => telegram(other?),
127    }
128}
129
130/// Number of bytes on the air for a frame whose `L` field is `l`, in `format`.
131pub fn wire_len(l: u8, format: Format) -> usize {
132    let l = usize::from(l);
133    match format {
134        Format::A => {
135            let rest = l.saturating_sub(9);
136            1 + l + 2 + 2 * rest.div_ceil(16)
137        }
138        Format::B | Format::Stripped => 1 + l,
139    }
140}
141
142/// Decode a frame from `raw` (starting at the `L` field), checking every CRC. The data
143/// without CRCs is copied into `out`, which must hold at least `L + 1` bytes.
144///
145/// Returns `Ok(None)` when `raw` is shorter than the frame its `L` field announces.
146pub fn decode<'o>(raw: &[u8], format: Format, out: &'o mut [u8]) -> Result<Option<(Frame<'o>, usize)>> {
147    let Some(&l) = raw.first() else { return Ok(None) };
148    if l < 10 {
149        return Err(Error::InvalidLength);
150    }
151    let total = wire_len(l, format);
152    let Some(raw) = raw.get(..total) else { return Ok(None) };
153    let len = match format {
154        Format::A => strip_a(raw, out)?,
155        Format::B => strip_b(raw, out)?,
156        Format::Stripped => copy_into(out, 0, raw)?,
157    };
158    let data = out.get(..len).ok_or(Error::OutputTooSmall)?;
159    let frame = parse_fields(data)?;
160    Ok(Some((frame, total)))
161}
162
163fn copy_into(out: &mut [u8], at: usize, bytes: &[u8]) -> Result<usize> {
164    let end = at.checked_add(bytes.len()).ok_or(Error::OutputTooSmall)?;
165    out.get_mut(at..end).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
166    Ok(end)
167}
168
169fn check_crc(block: usize, data: &[u8], crc: &[u8]) -> Result<()> {
170    let computed = crc16(data);
171    let found = match crc {
172        [hi, lo] => u16::from_be_bytes([*hi, *lo]),
173        _ => return Err(Error::UnexpectedEnd),
174    };
175    if computed == found { Ok(()) } else { Err(Error::Crc { block, computed, found }) }
176}
177
178fn strip_a(raw: &[u8], out: &mut [u8]) -> Result<usize> {
179    let mut pos = 0usize;
180    let mut written = 0usize;
181    let mut block = 0usize;
182    let mut size = 10usize;
183    while pos < raw.len() {
184        let data_end = (pos + size).min(raw.len().saturating_sub(2));
185        let data = raw.get(pos..data_end).ok_or(Error::UnexpectedEnd)?;
186        let crc = raw.get(data_end..data_end + 2).ok_or(Error::UnexpectedEnd)?;
187        check_crc(block, data, crc)?;
188        written = copy_into(out, written, data)?;
189        pos = data_end + 2;
190        block += 1;
191        size = 16;
192    }
193    Ok(written)
194}
195
196fn strip_b(raw: &[u8], out: &mut [u8]) -> Result<usize> {
197    // A third block holds at least one byte and its CRC: L + 1 of 129 or 130 is no frame.
198    if matches!(raw.len(), 129 | 130) {
199        return Err(Error::InvalidLength);
200    }
201    // Block 1 (10 bytes) and block 2 (up to 118 bytes with CRC) share the first CRC.
202    let first_end = raw.len().min(128);
203    let first = raw.get(..first_end.saturating_sub(2)).ok_or(Error::UnexpectedEnd)?;
204    check_crc(0, first, raw.get(first.len()..first_end).ok_or(Error::UnexpectedEnd)?)?;
205    let mut written = copy_into(out, 0, first)?;
206    if raw.len() > 128 {
207        let third = raw.get(128..raw.len() - 2).ok_or(Error::UnexpectedEnd)?;
208        check_crc(1, third, raw.get(raw.len() - 2..).ok_or(Error::UnexpectedEnd)?)?;
209        written = copy_into(out, written, third)?;
210    }
211    Ok(written)
212}
213
214fn parse_fields(data: &[u8]) -> Result<Frame<'_>> {
215    let Some((&[_l, c, m0, m1, i0, i1, i2, i3, version, medium, ci], payload)) =
216        data.split_first_chunk::<11>()
217    else {
218        return Err(Error::UnexpectedEnd);
219    };
220    Ok(Frame { c, address: Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium]), ci, payload })
221}
222
223/// Encode a frame: link fields, CI and payload, with the CRCs `format` puts on the air
224/// (none for [`Format::Stripped`]). Returns the number of bytes written. For simulators
225/// and tests; `sim::Telegram` (feature `oms`) builds the payload of a secured one. Format B follows EN 13757-4 as [`decode`] reads it; no third-party format-B
226/// frame has confirmed either (D-006).
227///
228/// [`Error::InvalidLength`] when the frame cannot exist (`L` above 255), and
229/// [`Error::OutputTooSmall`] when `out` cannot hold it; nothing is a frame then.
230pub fn encode(
231    format: Format,
232    c: u8,
233    address: &Address,
234    ci: u8,
235    payload: &[u8],
236    out: &mut [u8],
237) -> Result<usize> {
238    // The CRC-free data: L, C, address (8), CI, payload.
239    let n = payload.len().checked_add(11).ok_or(Error::InvalidLength)?;
240    let l = match format {
241        Format::A | Format::Stripped => n - 1,
242        // One CRC up to 126 data bytes (128 on the air), a second one above.
243        Format::B if n <= 126 => n + 1,
244        Format::B => n + 3,
245    };
246    let l = u8::try_from(l).map_err(|_| Error::InvalidLength)?;
247    let total = wire_len(l, format);
248    let out = out.get_mut(..total).ok_or(Error::OutputTooSmall)?;
249    let mut head = [0u8; 11];
250    head[0] = l;
251    head[1] = c;
252    head[2..10].copy_from_slice(&address.to_bytes());
253    head[10] = ci;
254    match format {
255        Format::Stripped => {
256            let at = copy_into(out, 0, &head)?;
257            copy_into(out, at, payload)
258        }
259        Format::B => {
260            let at = copy_into(out, 0, &head)?;
261            let first = n.min(126);
262            let (p1, p2) = payload.split_at(first - 11);
263            let at = copy_into(out, at, p1)?;
264            let crc = crc16(out.get(..at).ok_or(Error::OutputTooSmall)?).to_be_bytes();
265            let at = copy_into(out, at, &crc)?;
266            if p2.is_empty() {
267                return Ok(at);
268            }
269            let end = copy_into(out, at, p2)?;
270            let crc = crc16(out.get(at..end).ok_or(Error::OutputTooSmall)?).to_be_bytes();
271            copy_into(out, end, &crc)
272        }
273        Format::A => {
274            // Block 1 is the 10 bytes after L … A plus L itself; then 16-byte blocks.
275            let mut written = 0usize;
276            let mut block = [0u8; 16];
277            let mut in_block = 0usize;
278            let mut size = 10usize;
279            for b in head.iter().chain(payload) {
280                *block.get_mut(in_block).ok_or(Error::InvalidLength)? = *b;
281                in_block += 1;
282                if in_block == size {
283                    let data = block.get(..in_block).unwrap_or(&[]);
284                    written = copy_into(out, written, data)?;
285                    written = copy_into(out, written, &crc16(data).to_be_bytes())?;
286                    in_block = 0;
287                    size = 16;
288                }
289            }
290            if in_block > 0 {
291                let data = block.get(..in_block).unwrap_or(&[]);
292                written = copy_into(out, written, data)?;
293                written = copy_into(out, written, &crc16(data).to_be_bytes())?;
294            }
295            Ok(written)
296        }
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use crate::app::{Manufacturer, Medium};
304
305    #[test]
306    fn format_b_lengths_without_room_for_a_third_block_are_invalid() {
307        // L + 1 = 129 or 130: past the first CRC, but no byte for a third block.
308        for l in [128u8, 129] {
309            let mut raw = [0u8; 130];
310            raw[0] = l;
311            let mut out = [0u8; 300];
312            assert_eq!(
313                decode(&raw[..=usize::from(l)], Format::B, &mut out).unwrap_err(),
314                Error::InvalidLength,
315                "L {l}"
316            );
317        }
318    }
319
320    fn addr() -> Address {
321        Address {
322            manufacturer: Manufacturer::from_letters(*b"KAM").unwrap(),
323            id: [0x78, 0x56, 0x34, 0x12],
324            version: 0x1B,
325            medium: Medium::WATER,
326        }
327    }
328
329    #[test]
330    fn format_a_round_trip_for_every_length() {
331        for n in 0..60usize {
332            let payload: [u8; 60] = core::array::from_fn(|i| u8::try_from(i).unwrap() ^ 0x5A);
333            let mut wire = [0u8; 128];
334            let w = encode(Format::A, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire).unwrap();
335            assert_eq!(w, wire_len(wire[0], Format::A));
336            let mut out = [0u8; 128];
337            let (frame, used) = decode(&wire[..w], Format::A, &mut out).unwrap().unwrap();
338            assert_eq!(used, w);
339            assert_eq!(frame.c, control::SND_NR);
340            assert_eq!(frame.address, addr());
341            assert_eq!(frame.address.id_number(), Some(12_345_678));
342            assert_eq!(frame.ci, 0x7A);
343            assert_eq!(frame.payload, &payload[..n]);
344        }
345    }
346
347    #[test]
348    fn every_flipped_byte_is_caught() {
349        let mut wire = [0u8; 64];
350        let w = encode(
351            Format::A,
352            control::SND_NR,
353            &addr(),
354            0x7A,
355            &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
356            &mut wire,
357        )
358        .unwrap();
359        for i in 1..w {
360            let mut bad = wire;
361            bad[i] ^= 0x10;
362            let mut out = [0u8; 64];
363            assert!(decode(&bad[..w], Format::A, &mut out).is_err(), "byte {i}");
364        }
365    }
366
367    #[test]
368    fn short_input_asks_for_more() {
369        let mut wire = [0u8; 64];
370        let w = encode(Format::A, control::SND_NR, &addr(), 0x7A, &[0; 20], &mut wire).unwrap();
371        let mut out = [0u8; 64];
372        assert_eq!(decode(&wire[..w - 1], Format::A, &mut out).unwrap(), None);
373    }
374
375    #[test]
376    fn format_b_single_block() {
377        // Build format B by hand: L counts the CRC; one CRC over everything before it.
378        let a = addr().to_bytes();
379        let mut data = [0u8; 15];
380        data[0] = 14; // 1 C + 8 address + 1 CI + 2 payload + 2 CRC
381        data[1] = control::SND_NR;
382        data[2..10].copy_from_slice(&a);
383        data[10] = 0x78;
384        data[11] = 0x2F;
385        data[12] = 0x2F;
386        let crc = crc16(&data[..13]).to_be_bytes();
387        data[13..15].copy_from_slice(&crc);
388        let mut out = [0u8; 32];
389        let (frame, used) = decode(&data, Format::B, &mut out).unwrap().unwrap();
390        assert_eq!(used, 15);
391        assert_eq!(frame.payload, &[0x2F, 0x2F]);
392    }
393
394    #[test]
395    fn every_format_round_trips_every_length() {
396        // 008-oms-sim/SR-005: format B across its 126/127-byte split; too long is an error.
397        let payload: [u8; 250] = core::array::from_fn(|i| u8::try_from(i % 251).unwrap() ^ 0xA5);
398        for format in [Format::A, Format::B, Format::Stripped] {
399            for n in 0..=245usize {
400                let mut wire = [0u8; 320];
401                let w = match encode(format, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire) {
402                    Ok(w) => w,
403                    Err(e) => {
404                        assert!(format == Format::B && n > 241, "{format:?} {n}: {e:?}");
405                        assert_eq!(e, Error::InvalidLength);
406                        continue;
407                    }
408                };
409                assert_eq!(w, wire_len(wire[0], format), "{format:?} {n}");
410                let mut out = [0u8; 320];
411                let (frame, used) = decode(&wire[..w], format, &mut out).unwrap().unwrap();
412                assert_eq!((used, frame.ci, frame.payload), (w, 0x7A, &payload[..n]), "{format:?} {n}");
413                if w > 1 {
414                    let mut short = [0u8; 320];
415                    assert_eq!(
416                        encode(format, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut short[..w - 1]),
417                        Err(Error::OutputTooSmall)
418                    );
419                }
420            }
421            let mut wire = [0u8; 400];
422            assert_eq!(
423                encode(format, control::SND_NR, &addr(), 0x7A, &[0; 246], &mut wire),
424                Err(Error::InvalidLength)
425            );
426        }
427    }
428}