sml-kit 0.1.2

Read German smart meters in Rust: SML (Smart Message Language) decoder and encoder, sans-I/O, no_std, no allocator, no dependencies
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! SML transport protocol version 1: framing, escaping, padding and the frame CRC.
//!
//! ```text
//! 1b 1b 1b 1b  01 01 01 01      start sequence
//! …payload…                     SML messages, padded with 0x00 to a multiple of 4
//! 1b 1b 1b 1b  1a pp cc cc      end sequence: pp padding bytes, cc cc CRC
//! ```
//!
//! After the start sequence the stream is read in 4-byte words. A word of four `0x1b`
//! is an escape: the next word is a command. `1b 1b 1b 1b` again means the payload
//! itself contains those four bytes; `1a …` ends the frame; `01 01 01 01` starts a new
//! one. Escapes are aligned to 4 bytes, which is why the payload is padded. Every CRC-valid
//! frame in the public real-meter corpus agrees, and libsml reads the same way.
//!
//! The CRC covers every transmitted byte from the start sequence up to and including
//! the padding count.

use crate::crc::{CrcCheck, Kermit, X25};
use crate::{Error, Result};

/// The escape word.
pub const ESCAPE: [u8; 4] = [0x1B; 4];
/// The start command of transport version 1.
pub const START: [u8; 4] = [0x01; 4];
/// The first byte of the end command.
pub const END: u8 = 0x1A;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
    /// Looking for the 8-byte start sequence; the number of bytes matched so far.
    Hunting(u8),
    /// Inside a frame, collecting a payload word.
    Payload,
    /// Inside a frame, collecting the word after an escape.
    Command,
}

/// A sans-I/O transport decoder that assembles frames in a buffer of type `B`.
///
/// Feed it bytes as they arrive, from an optical head, a serial line or a capture file,
/// and it hands out each complete, verified payload. It never allocates and never
/// panics. Garbage before a start sequence is skipped.
///
/// The buffer can be owned (`[u8; N]`, or a `Vec<u8>` with `std`) or borrowed
/// (`&mut [u8]`). Its length is the largest frame accepted.
///
/// ```
/// use sml_kit::{Decoder, encode_frame};
///
/// let mut wire = [0u8; 64];
/// let n = encode_frame(&[0x01, 0x02, 0x03], &mut wire).unwrap();
///
/// let mut decoder = Decoder::new([0u8; 64]);
/// let mut frames = 0;
/// decoder.push_slice(&wire[..n], |frame| {
///     assert_eq!(frame.unwrap(), &[0x01, 0x02, 0x03]);
///     frames += 1;
/// });
/// assert_eq!(frames, 1);
/// ```
#[derive(Clone)]
pub struct Decoder<B> {
    buf: B,
    len: usize,
    state: State,
    word: [u8; 4],
    word_len: usize,
    crc: X25,
    kermit: Kermit,
    check: CrcCheck,
}

/// Shows the state, never the buffer: a frame may hold credentials.
impl<B: AsRef<[u8]>> core::fmt::Debug for Decoder<B> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Decoder")
            .field("state", &self.state)
            .field("len", &self.len)
            .field("capacity", &self.buf.as_ref().len())
            .field("check", &self.check)
            .finish_non_exhaustive()
    }
}

impl<B: AsRef<[u8]> + AsMut<[u8]>> Decoder<B> {
    /// A decoder that assembles frames in `buf`. A frame larger than `buf` is reported
    /// as [`Error::BufferFull`] and skipped.
    pub fn new(buf: B) -> Self {
        Self {
            buf,
            len: 0,
            state: State::Hunting(0),
            word: [0; 4],
            word_len: 0,
            crc: X25::new(),
            kermit: Kermit::new(),
            check: CrcCheck::Strict,
        }
    }

    /// Set how the frame CRC is checked. [`CrcCheck::Strict`] by default.
    #[must_use]
    pub fn with_crc_check(mut self, check: CrcCheck) -> Self {
        self.check = check;
        self
    }

    /// Forget any frame in progress and look for the next start sequence, e.g. after a
    /// serial-port timeout.
    pub fn reset(&mut self) {
        self.state = State::Hunting(0);
        self.word_len = 0;
        self.len = 0;
    }

    /// The buffer frames are assembled in.
    pub fn into_inner(self) -> B {
        self.buf
    }

    /// Feed every byte of `data`, calling `on_frame` for each complete frame or error.
    pub fn push_slice(&mut self, data: &[u8], mut on_frame: impl FnMut(Result<&[u8]>)) {
        for &b in data {
            match self.push(b) {
                Ok(Some(frame)) => on_frame(Ok(frame)),
                Ok(None) => {}
                Err(e) => on_frame(Err(e)),
            }
        }
    }

    /// Feed one byte. Returns the payload when this byte completes a frame.
    pub fn push(&mut self, byte: u8) -> Result<Option<&[u8]>> {
        match self.state {
            State::Hunting(matched) => {
                self.hunt(matched, byte);
                Ok(None)
            }
            State::Payload | State::Command => {
                if let Some(slot) = self.word.get_mut(self.word_len) {
                    *slot = byte;
                }
                self.word_len += 1;
                if self.word_len < 4 {
                    return Ok(None);
                }
                self.word_len = 0;
                let word = self.word;
                if self.state == State::Payload { self.payload_word(word) } else { self.command_word(word) }
            }
        }
    }

    fn hunt(&mut self, matched: u8, byte: u8) {
        let expected = if matched < 4 { 0x1B } else { 0x01 };
        let next = if byte == expected {
            matched + 1
        } else if byte == 0x1B {
            // A fifth 0x1b right after four keeps the last four as the escape. After a
            // partial `01` run, a 0x1b can only begin a new escape: one byte matched.
            if matched == 4 { 4 } else { 1 }
        } else {
            0
        };
        if next == 8 {
            self.begin_frame();
        } else {
            self.state = State::Hunting(next);
        }
    }

    fn begin_frame(&mut self) {
        self.len = 0;
        self.word_len = 0;
        self.crc = X25::new();
        self.kermit = Kermit::new();
        self.update_crc(&ESCAPE);
        self.update_crc(&START);
        self.state = State::Payload;
    }

    fn update_crc(&mut self, bytes: &[u8]) {
        self.crc.update(bytes);
        // Always kept, so changing the CRC mode mid-frame cannot leave it incomplete.
        self.kermit.update(bytes);
    }

    fn abort(&mut self, e: Error) -> Result<Option<&[u8]>> {
        self.state = State::Hunting(0);
        Err(e)
    }

    fn append(&mut self, word: [u8; 4]) -> Result<()> {
        let end = self.len.checked_add(4).ok_or(Error::BufferFull)?;
        self.buf.as_mut().get_mut(self.len..end).ok_or(Error::BufferFull)?.copy_from_slice(&word);
        self.len = end;
        Ok(())
    }

    fn payload_word(&mut self, word: [u8; 4]) -> Result<Option<&[u8]>> {
        self.update_crc(&word);
        if word == ESCAPE {
            self.state = State::Command;
            return Ok(None);
        }
        match self.append(word) {
            Ok(()) => Ok(None),
            Err(e) => self.abort(e),
        }
    }

    fn command_word(&mut self, word: [u8; 4]) -> Result<Option<&[u8]>> {
        self.state = State::Payload;
        if word == ESCAPE {
            self.update_crc(&word);
            return match self.append(ESCAPE) {
                Ok(()) => Ok(None),
                Err(e) => self.abort(e),
            };
        }
        if word == START {
            self.begin_frame();
            return Err(Error::UnexpectedStart);
        }
        let [cmd, padding, hi, lo] = word;
        if cmd != END {
            return self.abort(Error::InvalidEscape(word));
        }
        self.update_crc(&[cmd, padding]);
        let computed = self.crc.finish();
        let found = u16::from_be_bytes([hi, lo]);
        self.state = State::Hunting(0);
        if !self.check.accepts(computed, self.kermit.finish(), found) {
            return Err(Error::FrameCrc { computed, found });
        }
        let padding = usize::from(padding);
        let Some(payload_len) = self.len.checked_sub(padding).filter(|_| padding <= 3) else {
            return Err(Error::InvalidPadding);
        };
        let payload = self.buf.as_ref().get(..self.len).ok_or(Error::BufferFull)?;
        let (data, pad) = payload.split_at(payload_len);
        if pad.iter().any(|&b| b != 0) {
            return Err(Error::InvalidPadding);
        }
        Ok(Some(data))
    }
}

/// Frame `payload` for transport version 1 into `out`: start sequence, escaped payload,
/// zero padding to a multiple of 4, end sequence and CRC (low byte first). Returns the
/// number of bytes written.
pub fn encode_frame(payload: &[u8], out: &mut [u8]) -> Result<usize> {
    let mut w = crate::tl::Writer::new(out);
    w.raw(&ESCAPE)?;
    w.raw(&START)?;
    // Zero bytes that bring the payload to a multiple of 4: 0 to 3.
    let padding = [0u8, 3, 2, 1].get(payload.len() % 4).copied().unwrap_or(0);
    for chunk in payload.chunks(4) {
        let mut word = [0u8; 4];
        word.get_mut(..chunk.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(chunk);
        if word == ESCAPE {
            w.raw(&ESCAPE)?;
        }
        w.raw(&word)?;
    }
    w.raw(&ESCAPE)?;
    w.raw(&[END, padding])?;
    let crc = crate::crc::x25(w.written());
    w.raw(&crc.to_le_bytes())?;
    Ok(w.position())
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;

    fn decode_all(wire: &[u8]) -> ([u8; 128], usize, usize) {
        let mut buf = [0u8; 128];
        let mut out = [0u8; 128];
        let mut out_len = 0;
        let mut frames = 0;
        let mut d = Decoder::new(&mut buf);
        d.push_slice(wire, |f| {
            let f = f.unwrap();
            out[..f.len()].copy_from_slice(f);
            out_len = f.len();
            frames += 1;
        });
        (out, out_len, frames)
    }

    #[test]
    fn round_trip_with_padding() {
        for len in 0..=9 {
            let payload: [u8; 9] = core::array::from_fn(|i| u8::try_from(i).unwrap() + 0x40);
            let mut wire = [0u8; 64];
            let n = encode_frame(&payload[..len], &mut wire).unwrap();
            assert_eq!(n % 4, 0);
            let (out, out_len, frames) = decode_all(&wire[..n]);
            assert_eq!(frames, 1);
            assert_eq!(&out[..out_len], &payload[..len]);
        }
    }

    #[test]
    fn escaped_payload_word_survives() {
        let payload = [0x76, 0x05, 0x00, 0x00, 0x1B, 0x1B, 0x1B, 0x1B, 0x62, 0x00];
        let mut wire = [0u8; 64];
        let n = encode_frame(&payload, &mut wire).unwrap();
        // The aligned 1b1b1b1b word is doubled on the wire.
        assert_eq!(&wire[12..20], &[0x1B; 8]);
        let (out, out_len, _) = decode_all(&wire[..n]);
        assert_eq!(&out[..out_len], &payload);
    }

    #[test]
    fn garbage_before_the_start_is_skipped() {
        let mut wire = [0u8; 64];
        wire[..5].copy_from_slice(&[0x00, 0x1B, 0x1B, 0x42, 0x1B]);
        let n = encode_frame(&[1, 2, 3, 4], &mut wire[5..]).unwrap();
        let (out, out_len, frames) = decode_all(&wire[..5 + n]);
        assert_eq!(frames, 1);
        assert_eq!(&out[..out_len], &[1, 2, 3, 4]);
    }

    #[test]
    fn a_flipped_bit_fails_the_crc() {
        let mut wire = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
        wire[9] ^= 0x01;
        let mut buf = [0u8; 64];
        let mut d = Decoder::new(&mut buf);
        let mut errors = 0;
        d.push_slice(&wire[..n], |f| {
            assert!(matches!(f, Err(Error::FrameCrc { .. })));
            errors += 1;
        });
        assert_eq!(errors, 1);
    }

    fn frames(wire: &[u8]) -> usize {
        let mut d = Decoder::new([0u8; 64]);
        let mut n = 0;
        d.push_slice(wire, |f| n += usize::from(f.is_ok()));
        n
    }

    // 001-real-meter-readiness/SR-002
    #[test]
    fn hunter_rejects_a_start_broken_by_a_stray_escape_byte() {
        let mut frame = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
        // `1b1b1b1b 01 1b 01 01 01 01` is not a start sequence, so the body that follows
        // must not become a frame.
        let mut wire = std::vec![0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x1B, 0x01, 0x01, 0x01, 0x01];
        wire.extend_from_slice(&frame[8..n]);
        assert_eq!(frames(&wire), 0);
    }

    // 001-real-meter-readiness/SR-002
    #[test]
    fn hunter_resynchronises_on_extra_escape_bytes() {
        let mut frame = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
        for prefix in [&[0x1B][..], &[0x1B, 0x1B, 0x1B], &[0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x1B]] {
            let mut wire = prefix.to_vec();
            wire.extend_from_slice(&frame[..n]);
            assert_eq!(frames(&wire), 1, "prefix {prefix:02x?}");
        }
    }

    // 002-complete-protocol/SR-005: transport version 2 is refused.
    #[test]
    fn transport_v2_start_is_not_a_frame_start() {
        let mut frame = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut frame).unwrap();
        // 1b1b1b1b 02 TT UU 01: a version-2 start, block 0, file 0.
        let mut wire = std::vec![0x1B, 0x1B, 0x1B, 0x1B, 0x02, 0x00, 0x00, 0x01];
        wire.extend_from_slice(&frame[8..n]);
        assert_eq!(frames(&wire), 0);
        // A version-1 frame right after it is still found.
        wire.extend_from_slice(&frame[..n]);
        assert_eq!(frames(&wire), 1);
    }

    #[test]
    fn byte_by_byte_and_chunked_feeding_agree() {
        let mut frame = [0u8; 64];
        let n = encode_frame(&[9; 13], &mut frame).unwrap();
        for chunk in 1..=n {
            let mut d = Decoder::new([0u8; 64]);
            let mut got = 0;
            for part in frame[..n].chunks(chunk) {
                d.push_slice(part, |f| got += usize::from(f.is_ok()));
            }
            assert_eq!(got, 1, "chunk size {chunk}");
        }
    }

    #[test]
    fn lenient_accepts_a_kermit_frame_crc_strict_does_not() {
        let mut wire = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
        let k = crate::crc::kermit(&wire[..n - 2]);
        wire[n - 2..n].copy_from_slice(&k.to_be_bytes());
        let mut strict = Decoder::new([0u8; 64]);
        let mut errors = 0;
        strict.push_slice(&wire[..n], |f| errors += usize::from(matches!(f, Err(Error::FrameCrc { .. }))));
        assert_eq!(errors, 1);
        let mut lenient = Decoder::new([0u8; 64]).with_crc_check(CrcCheck::Lenient);
        let mut ok = 0;
        lenient.push_slice(&wire[..n], |f| ok += usize::from(f.is_ok()));
        assert_eq!(ok, 1);
    }

    #[test]
    fn switching_to_lenient_mid_frame_still_accepts_kermit() {
        let mut wire = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
        let k = crate::crc::kermit(&wire[..n - 2]);
        wire[n - 2..n].copy_from_slice(&k.to_be_bytes());
        let mut d = Decoder::new([0u8; 64]);
        d.push_slice(&wire[..6], |_| {});
        let mut d = d.with_crc_check(CrcCheck::Lenient);
        let mut ok = 0;
        d.push_slice(&wire[6..n], |f| ok += usize::from(f.is_ok()));
        assert_eq!(ok, 1);
    }

    #[test]
    fn debug_shows_state_not_buffer() {
        let d = Decoder::new([0x42u8; 8]);
        assert_eq!(
            std::format!("{d:?}"),
            "Decoder { state: Hunting(0), len: 0, capacity: 8, check: Strict, .. }"
        );
    }

    #[test]
    fn reset_drops_a_frame_in_progress() {
        let mut wire = [0u8; 64];
        let n = encode_frame(&[1, 2, 3, 4], &mut wire).unwrap();
        let mut d = Decoder::new([0u8; 64]);
        d.push_slice(&wire[..10], |_| {});
        d.reset();
        let mut ok = 0;
        d.push_slice(&wire[..n], |f| ok += usize::from(f.is_ok()));
        assert_eq!(ok, 1);
    }

    #[test]
    fn a_frame_larger_than_the_buffer_is_reported() {
        let mut wire = [0u8; 64];
        let n = encode_frame(&[7; 20], &mut wire).unwrap();
        let mut buf = [0u8; 8];
        let mut d = Decoder::new(&mut buf);
        let mut full = false;
        d.push_slice(&wire[..n], |f| full |= f == Err(Error::BufferFull));
        assert!(full);
    }
}