mbus-kit 0.3.0

M-Bus and wireless M-Bus (EN 13757-2/-3/-4) for Rust: heat, water and gas meter readout with a sans-I/O, no_std, allocation-free core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Wireless M-Bus link layer (EN 13757-4): frame formats A and B.
//!
//! Both formats start with the same 10 bytes:
//!
//! ```text
//! L  C  M M  A A A A A A
//!       ^^^  ^^^^^^^^^^^ address: ID (4, BCD, LSB first), version, device type
//!       manufacturer (LE, three letters)
//! ```
//!
//! **Format A** (modes S, T and C with preamble A): every block carries its own CRC.
//! Block 1 is those 10 bytes, then blocks of 16 bytes, the last one shorter. `L` counts
//! the bytes after itself **without** the CRCs.
//!
//! **Format B** (mode C with preamble B): block 1 has no CRC; block 2 (up to 118 bytes
//! including its CRC) ends with a CRC over blocks 1 and 2; a longer frame has a third
//! block with its own CRC. `L` counts the bytes after itself **with** the CRCs.
//!
//! **Stripped**: the receiver already removed the CRCs; `L` counts the bytes after it.
//!
//! CRCs are CRC-16/EN-13757, most significant byte first. The decoder copies the data
//! without CRCs into a caller buffer, so the frame borrows from that buffer.

pub use crate::app::Address;
use crate::app::Application;
use crate::crc::crc16;
use crate::{Error, Result};

/// Frame format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
    /// Format A: a CRC after every block.
    A,
    /// Format B: CRCs after block 2 and block 3 only.
    B,
    /// The receiver has already checked and removed the CRCs (what most wM-Bus sticks
    /// deliver, and how captures are usually logged): `L` counts the bytes after itself.
    /// Integrity then rests on the receiver.
    Stripped,
}

/// C-field values a meter sends.
pub mod control {
    /// `SND_NR`: unsolicited user data, no reply expected. A meter's periodic telegram.
    pub const SND_NR: u8 = 0x44;
    /// `SND_IR`: installation request.
    pub const SND_IR: u8 = 0x46;
    /// `ACC_NR`: access demand, no data.
    pub const ACC_NR: u8 = 0x47;
    /// `RSP_UD`: response to a request.
    pub const RSP_UD: u8 = 0x08;
}

/// A decoded wireless frame, CRCs removed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Frame<'o> {
    /// C field.
    pub c: u8,
    /// The sending meter.
    pub address: Address,
    /// CI field: what the payload is.
    pub ci: u8,
    /// The payload after the CI field (header and records, possibly encrypted).
    pub payload: &'o [u8],
}

impl<'o> Frame<'o> {
    /// The layers above the link layer (ELL, AFL, TPL) and the records, parsed with this
    /// frame's address as the link address (it forms the mode-5 and ELL IVs).
    pub fn application(&self) -> Result<Application<'o>> {
        Application::parse_with_link(self.ci, self.payload, Some(self.address))
    }
}

/// A received wireless telegram, opened: link layer and application, decrypted where
/// a key was found.
#[cfg(feature = "oms")]
#[derive(Clone, Debug)]
pub struct Telegram<'b> {
    /// C field.
    pub c: u8,
    /// The transmitter (for a meter behind a radio adapter, see [`Application::meter`]).
    pub address: Address,
    /// The application, decrypted if the key lookup had the meter's key.
    pub app: Application<'b>,
}

/// One call from radio bytes to records: check and strip the CRCs, parse every layer,
/// and decrypt (and authenticate) with the meter's key from `keys`.
///
/// `buf` holds the frame without CRCs and the plaintext: it needs twice the frame's
/// length (512 bytes always suffice). Returns `Ok(None)` when `raw` is shorter than
/// its `L` field announces. Without the meter's key, the telegram is returned with its
/// body still [`Body::Encrypted`](crate::Body::Encrypted) and
/// [`Authenticity::None`](crate::app::Authenticity::None), not as an error: the
/// unencrypted layers (address, ELL, header) are still useful.
///
/// An ELL-encrypted telegram whose TPL is encrypted as well is opened through both.
#[cfg(feature = "oms")]
pub fn open<'b, K: crate::oms::Keys + ?Sized>(
    raw: &[u8],
    format: Format,
    keys: &K,
    buf: &'b mut [u8],
) -> Result<Option<(Telegram<'b>, usize)>> {
    let half = buf.len() / 2;
    let (frame_buf, plain_buf) = buf.split_at_mut(half);
    let Some((frame, used)) = decode(raw, format, &mut *frame_buf)? else { return Ok(None) };
    let (c, address) = (frame.c, frame.address);
    let app = frame.application()?;
    let telegram = |app| Ok(Some((Telegram { c, address, app }, used)));
    // Not encrypted, or no key: the frame as decoded (decoded again, to lend it `buf`).
    let plain = |frame_buf: &'b mut [u8]| match decode(raw, format, frame_buf)? {
        Some((frame, _)) => telegram(frame.application()?),
        None => Ok(None),
    };
    let crate::Body::Encrypted(e) = &app.body else { return plain(frame_buf) };
    let inner = match e.decrypt(keys, plain_buf) {
        Err(Error::NoKey) => return plain(frame_buf),
        other => other?,
    };
    // An encrypted ELL around an encrypted TPL: open the TPL into the frame's half.
    let crate::Body::Encrypted(e) = &inner.body else { return telegram(inner) };
    match e.decrypt(keys, frame_buf) {
        Err(Error::NoKey) => telegram(inner),
        other => telegram(other?),
    }
}

/// Number of bytes on the air for a frame whose `L` field is `l`, in `format`.
pub fn wire_len(l: u8, format: Format) -> usize {
    let l = usize::from(l);
    match format {
        Format::A => {
            let rest = l.saturating_sub(9);
            1 + l + 2 + 2 * rest.div_ceil(16)
        }
        Format::B | Format::Stripped => 1 + l,
    }
}

/// Decode a frame from `raw` (starting at the `L` field), checking every CRC. The data
/// without CRCs is copied into `out`, which must hold at least `L + 1` bytes.
///
/// Returns `Ok(None)` when `raw` is shorter than the frame its `L` field announces.
pub fn decode<'o>(raw: &[u8], format: Format, out: &'o mut [u8]) -> Result<Option<(Frame<'o>, usize)>> {
    let Some(&l) = raw.first() else { return Ok(None) };
    if l < 10 {
        return Err(Error::InvalidLength);
    }
    let total = wire_len(l, format);
    let Some(raw) = raw.get(..total) else { return Ok(None) };
    let len = match format {
        Format::A => strip_a(raw, out)?,
        Format::B => strip_b(raw, out)?,
        Format::Stripped => copy_into(out, 0, raw)?,
    };
    let data = out.get(..len).ok_or(Error::OutputTooSmall)?;
    let frame = parse_fields(data)?;
    Ok(Some((frame, total)))
}

fn copy_into(out: &mut [u8], at: usize, bytes: &[u8]) -> Result<usize> {
    let end = at.checked_add(bytes.len()).ok_or(Error::OutputTooSmall)?;
    out.get_mut(at..end).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
    Ok(end)
}

fn check_crc(block: usize, data: &[u8], crc: &[u8]) -> Result<()> {
    let computed = crc16(data);
    let found = match crc {
        [hi, lo] => u16::from_be_bytes([*hi, *lo]),
        _ => return Err(Error::UnexpectedEnd),
    };
    if computed == found { Ok(()) } else { Err(Error::Crc { block, computed, found }) }
}

fn strip_a(raw: &[u8], out: &mut [u8]) -> Result<usize> {
    let mut pos = 0usize;
    let mut written = 0usize;
    let mut block = 0usize;
    let mut size = 10usize;
    while pos < raw.len() {
        let data_end = (pos + size).min(raw.len().saturating_sub(2));
        let data = raw.get(pos..data_end).ok_or(Error::UnexpectedEnd)?;
        let crc = raw.get(data_end..data_end + 2).ok_or(Error::UnexpectedEnd)?;
        check_crc(block, data, crc)?;
        written = copy_into(out, written, data)?;
        pos = data_end + 2;
        block += 1;
        size = 16;
    }
    Ok(written)
}

fn strip_b(raw: &[u8], out: &mut [u8]) -> Result<usize> {
    // A third block holds at least one byte and its CRC: L + 1 of 129 or 130 is no frame.
    if matches!(raw.len(), 129 | 130) {
        return Err(Error::InvalidLength);
    }
    // Block 1 (10 bytes) and block 2 (up to 118 bytes with CRC) share the first CRC.
    let first_end = raw.len().min(128);
    let first = raw.get(..first_end.saturating_sub(2)).ok_or(Error::UnexpectedEnd)?;
    check_crc(0, first, raw.get(first.len()..first_end).ok_or(Error::UnexpectedEnd)?)?;
    let mut written = copy_into(out, 0, first)?;
    if raw.len() > 128 {
        let third = raw.get(128..raw.len() - 2).ok_or(Error::UnexpectedEnd)?;
        check_crc(1, third, raw.get(raw.len() - 2..).ok_or(Error::UnexpectedEnd)?)?;
        written = copy_into(out, written, third)?;
    }
    Ok(written)
}

fn parse_fields(data: &[u8]) -> Result<Frame<'_>> {
    let Some((&[_l, c, m0, m1, i0, i1, i2, i3, version, medium, ci], payload)) =
        data.split_first_chunk::<11>()
    else {
        return Err(Error::UnexpectedEnd);
    };
    Ok(Frame { c, address: Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium]), ci, payload })
}

/// Encode a frame: link fields, CI and payload, with the CRCs `format` puts on the air
/// (none for [`Format::Stripped`]). Returns the number of bytes written. For simulators
/// 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
/// frame has confirmed either (D-006).
///
/// [`Error::InvalidLength`] when the frame cannot exist (`L` above 255), and
/// [`Error::OutputTooSmall`] when `out` cannot hold it; nothing is a frame then.
pub fn encode(
    format: Format,
    c: u8,
    address: &Address,
    ci: u8,
    payload: &[u8],
    out: &mut [u8],
) -> Result<usize> {
    // The CRC-free data: L, C, address (8), CI, payload.
    let n = payload.len().checked_add(11).ok_or(Error::InvalidLength)?;
    let l = match format {
        Format::A | Format::Stripped => n - 1,
        // One CRC up to 126 data bytes (128 on the air), a second one above.
        Format::B if n <= 126 => n + 1,
        Format::B => n + 3,
    };
    let l = u8::try_from(l).map_err(|_| Error::InvalidLength)?;
    let total = wire_len(l, format);
    let out = out.get_mut(..total).ok_or(Error::OutputTooSmall)?;
    let mut head = [0u8; 11];
    head[0] = l;
    head[1] = c;
    head[2..10].copy_from_slice(&address.to_bytes());
    head[10] = ci;
    match format {
        Format::Stripped => {
            let at = copy_into(out, 0, &head)?;
            copy_into(out, at, payload)
        }
        Format::B => {
            let at = copy_into(out, 0, &head)?;
            let first = n.min(126);
            let (p1, p2) = payload.split_at(first - 11);
            let at = copy_into(out, at, p1)?;
            let crc = crc16(out.get(..at).ok_or(Error::OutputTooSmall)?).to_be_bytes();
            let at = copy_into(out, at, &crc)?;
            if p2.is_empty() {
                return Ok(at);
            }
            let end = copy_into(out, at, p2)?;
            let crc = crc16(out.get(at..end).ok_or(Error::OutputTooSmall)?).to_be_bytes();
            copy_into(out, end, &crc)
        }
        Format::A => {
            // Block 1 is the 10 bytes after L … A plus L itself; then 16-byte blocks.
            let mut written = 0usize;
            let mut block = [0u8; 16];
            let mut in_block = 0usize;
            let mut size = 10usize;
            for b in head.iter().chain(payload) {
                *block.get_mut(in_block).ok_or(Error::InvalidLength)? = *b;
                in_block += 1;
                if in_block == size {
                    let data = block.get(..in_block).unwrap_or(&[]);
                    written = copy_into(out, written, data)?;
                    written = copy_into(out, written, &crc16(data).to_be_bytes())?;
                    in_block = 0;
                    size = 16;
                }
            }
            if in_block > 0 {
                let data = block.get(..in_block).unwrap_or(&[]);
                written = copy_into(out, written, data)?;
                written = copy_into(out, written, &crc16(data).to_be_bytes())?;
            }
            Ok(written)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::{Manufacturer, Medium};

    #[test]
    fn format_b_lengths_without_room_for_a_third_block_are_invalid() {
        // L + 1 = 129 or 130: past the first CRC, but no byte for a third block.
        for l in [128u8, 129] {
            let mut raw = [0u8; 130];
            raw[0] = l;
            let mut out = [0u8; 300];
            assert_eq!(
                decode(&raw[..=usize::from(l)], Format::B, &mut out).unwrap_err(),
                Error::InvalidLength,
                "L {l}"
            );
        }
    }

    fn addr() -> Address {
        Address {
            manufacturer: Manufacturer::from_letters(*b"KAM").unwrap(),
            id: [0x78, 0x56, 0x34, 0x12],
            version: 0x1B,
            medium: Medium::WATER,
        }
    }

    #[test]
    fn format_a_round_trip_for_every_length() {
        for n in 0..60usize {
            let payload: [u8; 60] = core::array::from_fn(|i| u8::try_from(i).unwrap() ^ 0x5A);
            let mut wire = [0u8; 128];
            let w = encode(Format::A, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire).unwrap();
            assert_eq!(w, wire_len(wire[0], Format::A));
            let mut out = [0u8; 128];
            let (frame, used) = decode(&wire[..w], Format::A, &mut out).unwrap().unwrap();
            assert_eq!(used, w);
            assert_eq!(frame.c, control::SND_NR);
            assert_eq!(frame.address, addr());
            assert_eq!(frame.address.id_number(), Some(12_345_678));
            assert_eq!(frame.ci, 0x7A);
            assert_eq!(frame.payload, &payload[..n]);
        }
    }

    #[test]
    fn every_flipped_byte_is_caught() {
        let mut wire = [0u8; 64];
        let w = encode(
            Format::A,
            control::SND_NR,
            &addr(),
            0x7A,
            &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
            &mut wire,
        )
        .unwrap();
        for i in 1..w {
            let mut bad = wire;
            bad[i] ^= 0x10;
            let mut out = [0u8; 64];
            assert!(decode(&bad[..w], Format::A, &mut out).is_err(), "byte {i}");
        }
    }

    #[test]
    fn short_input_asks_for_more() {
        let mut wire = [0u8; 64];
        let w = encode(Format::A, control::SND_NR, &addr(), 0x7A, &[0; 20], &mut wire).unwrap();
        let mut out = [0u8; 64];
        assert_eq!(decode(&wire[..w - 1], Format::A, &mut out).unwrap(), None);
    }

    #[test]
    fn format_b_single_block() {
        // Build format B by hand: L counts the CRC; one CRC over everything before it.
        let a = addr().to_bytes();
        let mut data = [0u8; 15];
        data[0] = 14; // 1 C + 8 address + 1 CI + 2 payload + 2 CRC
        data[1] = control::SND_NR;
        data[2..10].copy_from_slice(&a);
        data[10] = 0x78;
        data[11] = 0x2F;
        data[12] = 0x2F;
        let crc = crc16(&data[..13]).to_be_bytes();
        data[13..15].copy_from_slice(&crc);
        let mut out = [0u8; 32];
        let (frame, used) = decode(&data, Format::B, &mut out).unwrap().unwrap();
        assert_eq!(used, 15);
        assert_eq!(frame.payload, &[0x2F, 0x2F]);
    }

    #[test]
    fn every_format_round_trips_every_length() {
        // 008-oms-sim/SR-005: format B across its 126/127-byte split; too long is an error.
        let payload: [u8; 250] = core::array::from_fn(|i| u8::try_from(i % 251).unwrap() ^ 0xA5);
        for format in [Format::A, Format::B, Format::Stripped] {
            for n in 0..=245usize {
                let mut wire = [0u8; 320];
                let w = match encode(format, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire) {
                    Ok(w) => w,
                    Err(e) => {
                        assert!(format == Format::B && n > 241, "{format:?} {n}: {e:?}");
                        assert_eq!(e, Error::InvalidLength);
                        continue;
                    }
                };
                assert_eq!(w, wire_len(wire[0], format), "{format:?} {n}");
                let mut out = [0u8; 320];
                let (frame, used) = decode(&wire[..w], format, &mut out).unwrap().unwrap();
                assert_eq!((used, frame.ci, frame.payload), (w, 0x7A, &payload[..n]), "{format:?} {n}");
                if w > 1 {
                    let mut short = [0u8; 320];
                    assert_eq!(
                        encode(format, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut short[..w - 1]),
                        Err(Error::OutputTooSmall)
                    );
                }
            }
            let mut wire = [0u8; 400];
            assert_eq!(
                encode(format, control::SND_NR, &addr(), 0x7A, &[0; 246], &mut wire),
                Err(Error::InvalidLength)
            );
        }
    }
}