Skip to main content

zwave_cc/
crc16.rs

1//! CRC-16 Encapsulation and the CRC Z-Wave uses (CRC-CCITT, polynomial
2//! 0x1021, initial value 0x1D0F; the `crc` crate's `CRC_16_SPI_FUJITSU`).
3
4/// The CRC-16 Encapsulation command class id.
5pub const CC: u8 = 0x56;
6
7const ALG: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_SPI_FUJITSU);
8
9/// The Z-Wave CRC-16 of `data`.
10pub fn checksum(data: &[u8]) -> u16 {
11    ALG.checksum(data)
12}
13
14/// Wraps a command in CRC-16 Encapsulation.
15pub fn encapsulate(command: &[u8]) -> Vec<u8> {
16    let mut v = Vec::with_capacity(command.len() + 4);
17    v.extend_from_slice(&[CC, 0x01]);
18    v.extend_from_slice(command);
19    let c = checksum(&v);
20    v.extend_from_slice(&c.to_be_bytes());
21    v
22}
23
24/// Unwraps a CRC-16 Encapsulation frame (starting at `0x56 0x01`); `None`
25/// when it is too short or the CRC does not match.
26pub fn decapsulate(frame: &[u8]) -> Option<&[u8]> {
27    if frame.len() < 5 || frame[0] != CC || frame[1] != 0x01 {
28        return None;
29    }
30    let (body, crc) = frame.split_at(frame.len() - 2);
31    (checksum(body) == u16::from_be_bytes([crc[0], crc[1]])).then_some(&body[2..])
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn check_value_and_roundtrip() {
40        // The algorithm's published check value for "123456789".
41        assert_eq!(checksum(b"123456789"), 0xe5cc);
42        let f = encapsulate(&[0x20, 0x02]);
43        assert_eq!(decapsulate(&f), Some(&[0x20u8, 0x02][..]));
44        let mut bad = f.clone();
45        bad[2] ^= 1;
46        assert_eq!(decapsulate(&bad), None);
47    }
48}