Skip to main content

sml_kit/
crc.rs

1//! CRC-16/X-25, the checksum SML uses for both the transport frame and each message,
2//! and CRC-16/KERMIT, the checksum some meters use instead.
3//!
4//! **CRC-16/X-25**: polynomial 0x1021 (reflected 0x8408), initial value 0xFFFF, input and
5//! output reflected, final XOR 0xFFFF. Check value over `"123456789"`: `0x906E`.
6//!
7//! **Byte order on the wire.** The CRC is transmitted low byte first, as in HDLC, both in
8//! the transport end sequence and in a message's `Unsigned16` CRC field.
9//! Every CRC-valid frame in the public real-meter corpus agrees.
10//!
11//! **CRC-16/KERMIT** uses the same reflected polynomial with initial value 0 and no final
12//! XOR (check value `0x2189`). Some Holley DTZ541 units compute it instead of X-25.
13//! [`CrcCheck::Lenient`] accepts it; [`CrcCheck::Strict`] does not.
14
15/// How strictly a CRC is checked.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
17pub enum CrcCheck {
18    /// CRC-16/X-25, low byte first on the wire. The default, and what the specification
19    /// and every conforming meter use.
20    #[default]
21    Strict,
22    /// CRC-16/X-25 or CRC-16/KERMIT, each in either byte order, for meters that deviate
23    /// (some Holley DTZ541 send KERMIT).
24    ///
25    /// Four values are accepted instead of one, so a corrupted telegram passes with a
26    /// probability of 4/65536 instead of 1/65536. Use it for the meter that needs it,
27    /// not as a default.
28    Lenient,
29    /// The CRC is not checked. For captures known to be damaged, never for billing.
30    Off,
31}
32
33impl CrcCheck {
34    /// Whether a CRC read from the wire as a big-endian `u16` matches.
35    ///
36    /// `x25` and `kermit` are the CRCs computed over the same bytes.
37    pub(crate) fn accepts(self, x25: u16, kermit: u16, wire_be: u16) -> bool {
38        match self {
39            Self::Strict => wire_be == x25.swap_bytes(),
40            Self::Lenient => [x25, x25.swap_bytes(), kermit, kermit.swap_bytes()].contains(&wire_be),
41            Self::Off => true,
42        }
43    }
44}
45
46// A const fn cannot use `get_mut`, and both loops are bounded by the array length.
47#[allow(clippy::indexing_slicing, clippy::cast_possible_truncation)]
48const fn table() -> [u16; 256] {
49    let mut t = [0u16; 256];
50    let mut i = 0;
51    while i < 256 {
52        let mut crc = i as u16;
53        let mut bit = 0;
54        while bit < 8 {
55            crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
56            bit += 1;
57        }
58        t[i] = crc;
59        i += 1;
60    }
61    t
62}
63
64static TABLE: [u16; 256] = table();
65
66/// One table step of the reflected 0x1021 polynomial, shared by X-25 and KERMIT.
67fn step(crc: u16, byte: u8) -> u16 {
68    let [low, _] = (crc ^ u16::from(byte)).to_le_bytes();
69    // A `u8` index is always inside the 256-entry table.
70    (crc >> 8) ^ TABLE.get(usize::from(low)).copied().unwrap_or(0)
71}
72
73/// An incremental CRC-16/X-25.
74#[derive(Clone, Copy, Debug)]
75pub struct X25(u16);
76
77impl Default for X25 {
78    fn default() -> Self {
79        Self::new()
80    }
81}
82
83impl X25 {
84    /// A fresh CRC.
85    pub const fn new() -> Self {
86        Self(0xFFFF)
87    }
88
89    /// Add bytes.
90    pub fn update(&mut self, bytes: &[u8]) {
91        self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
92    }
93
94    /// The CRC of everything added so far.
95    pub const fn finish(self) -> u16 {
96        self.0 ^ 0xFFFF
97    }
98}
99
100/// An incremental CRC-16/KERMIT.
101#[derive(Clone, Copy, Debug, Default)]
102pub struct Kermit(u16);
103
104impl Kermit {
105    /// A fresh CRC.
106    pub const fn new() -> Self {
107        Self(0)
108    }
109
110    /// Add bytes.
111    pub fn update(&mut self, bytes: &[u8]) {
112        self.0 = bytes.iter().fold(self.0, |c, &b| step(c, b));
113    }
114
115    /// The CRC of everything added so far.
116    pub const fn finish(self) -> u16 {
117        self.0
118    }
119}
120
121/// The CRC-16/X-25 of `bytes`.
122pub fn x25(bytes: &[u8]) -> u16 {
123    let mut c = X25::new();
124    c.update(bytes);
125    c.finish()
126}
127
128/// The CRC-16/KERMIT of `bytes`.
129pub fn kermit(bytes: &[u8]) -> u16 {
130    let mut c = Kermit::new();
131    c.update(bytes);
132    c.finish()
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn standard_check_values() {
141        assert_eq!(x25(b"123456789"), 0x906E);
142        assert_eq!(kermit(b"123456789"), 0x2189);
143    }
144
145    #[test]
146    fn incremental_equals_one_shot() {
147        let mut c = X25::new();
148        c.update(b"1234");
149        c.update(b"56789");
150        assert_eq!(c.finish(), x25(b"123456789"));
151    }
152
153    // 001-real-meter-readiness/SR-003
154    #[test]
155    fn strict_wants_x25_low_byte_first() {
156        let (x25, k) = (0x906E, 0x2189);
157        assert!(CrcCheck::Strict.accepts(x25, k, 0x6E90));
158        assert!(!CrcCheck::Strict.accepts(x25, k, 0x906E));
159        assert!(!CrcCheck::Strict.accepts(x25, k, 0x2189));
160        assert!(!CrcCheck::Strict.accepts(x25, k, 0x8921));
161        for wire in [0x6E90, 0x906E, 0x2189, 0x8921] {
162            assert!(CrcCheck::Lenient.accepts(x25, k, wire));
163        }
164        assert!(!CrcCheck::Lenient.accepts(x25, k, 0x1234));
165        assert!(CrcCheck::Off.accepts(x25, k, 0));
166        assert_eq!(CrcCheck::default(), CrcCheck::Strict);
167    }
168}