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 needs a second decryption;
99/// the returned body is then `Encrypted` again.
100#[cfg(feature = "oms")]
101pub fn open<'b, K: crate::oms::Keys + ?Sized>(
102    raw: &[u8],
103    format: Format,
104    keys: &K,
105    buf: &'b mut [u8],
106) -> Result<Option<(Telegram<'b>, usize)>> {
107    let half = buf.len() / 2;
108    let (frame_buf, plain_buf) = buf.split_at_mut(half);
109    let Some((frame, used)) = decode(raw, format, frame_buf)? else { return Ok(None) };
110    let app = frame.application()?;
111    let app = match &app.body {
112        crate::Body::Encrypted(e) => match e.decrypt(keys, plain_buf) {
113            Err(Error::NoKey) => app,
114            other => other?,
115        },
116        _ => app,
117    };
118    Ok(Some((Telegram { c: frame.c, address: frame.address, app }, used)))
119}
120
121/// Number of bytes on the air for a frame whose `L` field is `l`, in `format`.
122pub fn wire_len(l: u8, format: Format) -> usize {
123    let l = usize::from(l);
124    match format {
125        Format::A => {
126            let rest = l.saturating_sub(9);
127            1 + l + 2 + 2 * rest.div_ceil(16)
128        }
129        Format::B | Format::Stripped => 1 + l,
130    }
131}
132
133/// Decode a frame from `raw` (starting at the `L` field), checking every CRC. The data
134/// without CRCs is copied into `out`, which must hold at least `L + 1` bytes.
135///
136/// Returns `Ok(None)` when `raw` is shorter than the frame its `L` field announces.
137pub fn decode<'o>(raw: &[u8], format: Format, out: &'o mut [u8]) -> Result<Option<(Frame<'o>, usize)>> {
138    let Some(&l) = raw.first() else { return Ok(None) };
139    if l < 10 {
140        return Err(Error::InvalidLength);
141    }
142    let total = wire_len(l, format);
143    let Some(raw) = raw.get(..total) else { return Ok(None) };
144    let len = match format {
145        Format::A => strip_a(raw, out)?,
146        Format::B => strip_b(raw, out)?,
147        Format::Stripped => copy_into(out, 0, raw)?,
148    };
149    let data = out.get(..len).ok_or(Error::OutputTooSmall)?;
150    let frame = parse_fields(data)?;
151    Ok(Some((frame, total)))
152}
153
154fn copy_into(out: &mut [u8], at: usize, bytes: &[u8]) -> Result<usize> {
155    let end = at.checked_add(bytes.len()).ok_or(Error::OutputTooSmall)?;
156    out.get_mut(at..end).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
157    Ok(end)
158}
159
160fn check_crc(block: usize, data: &[u8], crc: &[u8]) -> Result<()> {
161    let computed = crc16(data);
162    let found = match crc {
163        [hi, lo] => u16::from_be_bytes([*hi, *lo]),
164        _ => return Err(Error::UnexpectedEnd),
165    };
166    if computed == found { Ok(()) } else { Err(Error::Crc { block, computed, found }) }
167}
168
169fn strip_a(raw: &[u8], out: &mut [u8]) -> Result<usize> {
170    let mut pos = 0usize;
171    let mut written = 0usize;
172    let mut block = 0usize;
173    let mut size = 10usize;
174    while pos < raw.len() {
175        let data_end = (pos + size).min(raw.len().saturating_sub(2));
176        let data = raw.get(pos..data_end).ok_or(Error::UnexpectedEnd)?;
177        let crc = raw.get(data_end..data_end + 2).ok_or(Error::UnexpectedEnd)?;
178        check_crc(block, data, crc)?;
179        written = copy_into(out, written, data)?;
180        pos = data_end + 2;
181        block += 1;
182        size = 16;
183    }
184    Ok(written)
185}
186
187fn strip_b(raw: &[u8], out: &mut [u8]) -> Result<usize> {
188    // A third block holds at least one byte and its CRC: L + 1 of 129 or 130 is no frame.
189    if matches!(raw.len(), 129 | 130) {
190        return Err(Error::InvalidLength);
191    }
192    // Block 1 (10 bytes) and block 2 (up to 118 bytes with CRC) share the first CRC.
193    let first_end = raw.len().min(128);
194    let first = raw.get(..first_end.saturating_sub(2)).ok_or(Error::UnexpectedEnd)?;
195    check_crc(0, first, raw.get(first.len()..first_end).ok_or(Error::UnexpectedEnd)?)?;
196    let mut written = copy_into(out, 0, first)?;
197    if raw.len() > 128 {
198        let third = raw.get(128..raw.len() - 2).ok_or(Error::UnexpectedEnd)?;
199        check_crc(1, third, raw.get(raw.len() - 2..).ok_or(Error::UnexpectedEnd)?)?;
200        written = copy_into(out, written, third)?;
201    }
202    Ok(written)
203}
204
205fn parse_fields(data: &[u8]) -> Result<Frame<'_>> {
206    let Some((&[_l, c, m0, m1, i0, i1, i2, i3, version, medium, ci], payload)) =
207        data.split_first_chunk::<11>()
208    else {
209        return Err(Error::UnexpectedEnd);
210    };
211    Ok(Frame { c, address: Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium]), ci, payload })
212}
213
214/// Encode a frame in format A: link fields, CI and payload, with a CRC after every
215/// block. Returns the number of bytes written. For simulators and tests.
216pub fn encode_a(c: u8, address: &Address, ci: u8, payload: &[u8], out: &mut [u8]) -> Result<usize> {
217    let l = payload.len().checked_add(10).filter(|&l| l <= 255).ok_or(Error::InvalidLength)?;
218    let l8 = u8::try_from(l).map_err(|_| Error::InvalidLength)?;
219    // The CRC-free data: L, C, address (8), CI, payload.
220    let mut head = [0u8; 11];
221    head[0] = l8;
222    head[1] = c;
223    head[2..10].copy_from_slice(&address.to_bytes());
224    head[10] = ci;
225    let data = head.iter().copied().chain(payload.iter().copied());
226
227    let mut written = 0usize;
228    let mut block = [0u8; 16];
229    let mut in_block = 0usize;
230    let mut size = 10usize;
231    let flush = |block: &[u8], written: &mut usize, out: &mut [u8]| -> Result<()> {
232        *written = copy_into(out, *written, block)?;
233        *written = copy_into(out, *written, &crc16(block).to_be_bytes())?;
234        Ok(())
235    };
236    for b in data {
237        *block.get_mut(in_block).ok_or(Error::InvalidLength)? = b;
238        in_block += 1;
239        if in_block == size {
240            flush(block.get(..in_block).unwrap_or(&[]), &mut written, out)?;
241            in_block = 0;
242            size = 16;
243        }
244    }
245    if in_block > 0 {
246        flush(block.get(..in_block).unwrap_or(&[]), &mut written, out)?;
247    }
248    Ok(written)
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::app::{Manufacturer, Medium};
255
256    #[test]
257    fn format_b_lengths_without_room_for_a_third_block_are_invalid() {
258        // L + 1 = 129 or 130: past the first CRC, but no byte for a third block.
259        for l in [128u8, 129] {
260            let mut raw = [0u8; 130];
261            raw[0] = l;
262            let mut out = [0u8; 300];
263            assert_eq!(
264                decode(&raw[..=usize::from(l)], Format::B, &mut out).unwrap_err(),
265                Error::InvalidLength,
266                "L {l}"
267            );
268        }
269    }
270
271    fn addr() -> Address {
272        Address {
273            manufacturer: Manufacturer::from_letters(*b"KAM").unwrap(),
274            id: [0x78, 0x56, 0x34, 0x12],
275            version: 0x1B,
276            medium: Medium::WATER,
277        }
278    }
279
280    #[test]
281    fn format_a_round_trip_for_every_length() {
282        for n in 0..60usize {
283            let payload: [u8; 60] = core::array::from_fn(|i| u8::try_from(i).unwrap() ^ 0x5A);
284            let mut wire = [0u8; 128];
285            let w = encode_a(control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire).unwrap();
286            assert_eq!(w, wire_len(wire[0], Format::A));
287            let mut out = [0u8; 128];
288            let (frame, used) = decode(&wire[..w], Format::A, &mut out).unwrap().unwrap();
289            assert_eq!(used, w);
290            assert_eq!(frame.c, control::SND_NR);
291            assert_eq!(frame.address, addr());
292            assert_eq!(frame.address.id_number(), Some(12_345_678));
293            assert_eq!(frame.ci, 0x7A);
294            assert_eq!(frame.payload, &payload[..n]);
295        }
296    }
297
298    #[test]
299    fn every_flipped_byte_is_caught() {
300        let mut wire = [0u8; 64];
301        let w =
302            encode_a(control::SND_NR, &addr(), 0x7A, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], &mut wire)
303                .unwrap();
304        for i in 1..w {
305            let mut bad = wire;
306            bad[i] ^= 0x10;
307            let mut out = [0u8; 64];
308            assert!(decode(&bad[..w], Format::A, &mut out).is_err(), "byte {i}");
309        }
310    }
311
312    #[test]
313    fn short_input_asks_for_more() {
314        let mut wire = [0u8; 64];
315        let w = encode_a(control::SND_NR, &addr(), 0x7A, &[0; 20], &mut wire).unwrap();
316        let mut out = [0u8; 64];
317        assert_eq!(decode(&wire[..w - 1], Format::A, &mut out).unwrap(), None);
318    }
319
320    #[test]
321    fn format_b_single_block() {
322        // Build format B by hand: L counts the CRC; one CRC over everything before it.
323        let a = addr().to_bytes();
324        let mut data = [0u8; 15];
325        data[0] = 14; // 1 C + 8 address + 1 CI + 2 payload + 2 CRC
326        data[1] = control::SND_NR;
327        data[2..10].copy_from_slice(&a);
328        data[10] = 0x78;
329        data[11] = 0x2F;
330        data[12] = 0x2F;
331        let crc = crc16(&data[..13]).to_be_bytes();
332        data[13..15].copy_from_slice(&crc);
333        let mut out = [0u8; 32];
334        let (frame, used) = decode(&data, Format::B, &mut out).unwrap().unwrap();
335        assert_eq!(used, 15);
336        assert_eq!(frame.payload, &[0x2F, 0x2F]);
337    }
338}