Skip to main content

mbus_kit/
crc.rs

1//! The CRCs of wireless M-Bus and its receiver sticks.
2//!
3//! [`crc16`] is CRC-16/EN-13757, the block checksum of wireless M-Bus (EN 13757-4):
4//! polynomial 0x3D65, initial value 0x0000, not reflected, final XOR 0xFFFF, transmitted
5//! most significant byte first; check value over `"123456789"` `0xC2B7`.
6//!
7//! [`crc16_x25`] is CRC-16/X-25 (IBM-SDLC), the frame check of the IMST sticks' host
8//! controller interfaces: reflected polynomial 0x8408, initial value 0xFFFF, final XOR
9//! 0xFFFF, transmitted least significant byte first; check value `0x906E`.
10
11const fn table() -> [u16; 256] {
12    let mut t = [0u16; 256];
13    let mut i = 0usize;
14    while i < 256 {
15        #[allow(clippy::cast_possible_truncation)] // i < 256
16        let mut crc = (i as u16) << 8;
17        let mut bit = 0;
18        while bit < 8 {
19            crc = if crc & 0x8000 != 0 { (crc << 1) ^ 0x3D65 } else { crc << 1 };
20            bit += 1;
21        }
22        #[allow(clippy::indexing_slicing)] // i < 256, and a const fn cannot use get_mut
23        {
24            t[i] = crc;
25        }
26        i += 1;
27    }
28    t
29}
30
31static TABLE: [u16; 256] = table();
32
33/// The CRC-16/EN-13757 of `bytes`.
34pub fn crc16(bytes: &[u8]) -> u16 {
35    let mut crc = 0u16;
36    for &b in bytes {
37        let [high, _] = crc.to_be_bytes();
38        let idx = usize::from(high ^ b);
39        crc = (crc << 8) ^ TABLE.get(idx).copied().unwrap_or(0);
40    }
41    crc ^ 0xFFFF
42}
43
44/// The CRC-16/X-25 of `bytes` (bitwise: the stick frames are short).
45pub fn crc16_x25(bytes: &[u8]) -> u16 {
46    let mut crc = 0xFFFFu16;
47    for &b in bytes {
48        crc ^= u16::from(b);
49        for _ in 0..8 {
50            crc = if crc & 1 != 0 { (crc >> 1) ^ 0x8408 } else { crc >> 1 };
51        }
52    }
53    !crc
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn standard_check_value() {
62        assert_eq!(crc16(b"123456789"), 0xC2B7);
63        assert_eq!(crc16_x25(b"123456789"), 0x906E);
64    }
65}