Skip to main content

zigbee_deconz/
frame.rs

1//! deCONZ frames on the wire: SLIP-framed (RFC 1055), each frame a command
2//! id, sequence number, status, total length, payload, and a 16-bit
3//! checksum (the two's complement of the byte sum).
4
5use zigbee_primitives::wire::{Reader, Truncated};
6
7const END: u8 = 0xC0;
8const ESC: u8 = 0xDB;
9const ESC_END: u8 = 0xDC;
10const ESC_ESC: u8 = 0xDD;
11/// The longest frame (before SLIP escaping) the decoder accepts.
12pub const MAX_FRAME: usize = 512;
13
14/// One frame.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Frame {
17    /// Command id ([`crate::ids::command`]).
18    pub command: u8,
19    /// Sequence number; a response echoes its request's.
20    pub seq: u8,
21    /// Status ([`crate::ids::status`]); 0 in requests.
22    pub status: u8,
23    /// Payload.
24    pub payload: Vec<u8>,
25}
26
27fn checksum(bytes: &[u8]) -> u16 {
28    let sum = bytes
29        .iter()
30        .fold(0u16, |a, b| a.wrapping_add(u16::from(*b)));
31    (!sum).wrapping_add(1)
32}
33
34impl Frame {
35    /// A frame.
36    pub fn new(command: u8, seq: u8, status: u8, payload: Vec<u8>) -> Frame {
37        Frame {
38            command,
39            seq,
40            status,
41            payload,
42        }
43    }
44
45    /// The frame before SLIP escaping, with its checksum.
46    pub fn to_bytes(&self) -> Vec<u8> {
47        let len = (self.payload.len() + 5) as u16;
48        let mut out = Vec::with_capacity(self.payload.len() + 7);
49        out.push(self.command);
50        out.push(self.seq);
51        out.push(self.status);
52        out.extend_from_slice(&len.to_le_bytes());
53        out.extend_from_slice(&self.payload);
54        out.extend_from_slice(&checksum(&out).to_le_bytes());
55        out
56    }
57
58    /// Parse a frame (after SLIP decoding), checking its length and
59    /// checksum.
60    pub fn parse(bytes: &[u8]) -> Result<Frame, FrameError> {
61        if bytes.len() < 7 {
62            return Err(FrameError::Short(bytes.len()));
63        }
64        let (body, crc) = bytes.split_at(bytes.len() - 2);
65        let crc = u16::from_le_bytes([crc[0], crc[1]]);
66        if checksum(body) != crc {
67            return Err(FrameError::Checksum);
68        }
69        let mut r = Reader::new(body);
70        let command = r.u8()?;
71        let seq = r.u8()?;
72        let status = r.u8()?;
73        let len = usize::from(r.u16()?);
74        if len != body.len() {
75            return Err(FrameError::Length(len));
76        }
77        Ok(Frame {
78            command,
79            seq,
80            status,
81            payload: r.rest().to_vec(),
82        })
83    }
84
85    /// The bytes on the wire: SLIP-escaped, between END bytes.
86    pub fn encode(&self) -> Vec<u8> {
87        let bytes = self.to_bytes();
88        let mut out = Vec::with_capacity(bytes.len() + 4);
89        out.push(END);
90        for b in bytes {
91            match b {
92                END => out.extend_from_slice(&[ESC, ESC_END]),
93                ESC => out.extend_from_slice(&[ESC, ESC_ESC]),
94                b => out.push(b),
95            }
96        }
97        out.push(END);
98        out
99    }
100}
101
102/// A frame did not parse.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
104pub enum FrameError {
105    /// Shorter than a header and checksum.
106    #[error("deCONZ frame of {0} bytes is too short")]
107    Short(usize),
108    /// The checksum did not match.
109    #[error("deCONZ frame checksum mismatch")]
110    Checksum,
111    /// The length field disagrees with the frame.
112    #[error("deCONZ frame length field {0} does not match")]
113    Length(usize),
114    /// Truncated.
115    #[error(transparent)]
116    Truncated(#[from] Truncated),
117}
118
119/// Splits a SLIP byte stream into frames. Holds at most [`MAX_FRAME`]
120/// bytes.
121#[derive(Debug, Default)]
122pub struct Decoder {
123    buf: Vec<u8>,
124    escaped: bool,
125    overflow: bool,
126}
127
128impl Decoder {
129    /// An empty decoder.
130    pub fn new() -> Decoder {
131        Decoder::default()
132    }
133
134    /// Feed bytes; returns every frame they complete, good or bad.
135    pub fn push(&mut self, bytes: &[u8]) -> Vec<Result<Frame, FrameError>> {
136        let mut out = Vec::new();
137        for &b in bytes {
138            match b {
139                END => {
140                    if !self.buf.is_empty() && !self.overflow {
141                        out.push(Frame::parse(&self.buf));
142                    }
143                    self.buf.clear();
144                    self.escaped = false;
145                    self.overflow = false;
146                }
147                ESC if !self.escaped => self.escaped = true,
148                b => {
149                    let b = match (self.escaped, b) {
150                        (true, ESC_END) => END,
151                        (true, ESC_ESC) => ESC,
152                        (_, b) => b,
153                    };
154                    self.escaped = false;
155                    if self.buf.len() < MAX_FRAME {
156                        self.buf.push(b);
157                    } else {
158                        self.overflow = true;
159                    }
160                }
161            }
162        }
163        out
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn version_request_bytes() {
173        // VERSION, seq 1: 0D 01 00 09 00 00 00 00 00, checksum E9 FF.
174        let f = Frame::new(0x0D, 1, 0, vec![0; 4]);
175        assert_eq!(
176            f.to_bytes(),
177            [0x0D, 0x01, 0x00, 0x09, 0x00, 0, 0, 0, 0, 0xE9, 0xFF]
178        );
179    }
180
181    #[test]
182    fn escapes_and_round_trips() {
183        let f = Frame::new(0x17, 0xC0, 0, vec![0xC0, 0xDB, 1]);
184        let wire = f.encode();
185        assert!(!wire[1..wire.len() - 1].contains(&END));
186        let mut d = Decoder::new();
187        assert_eq!(d.push(&wire[..4]), vec![]);
188        assert_eq!(d.push(&wire[4..]), vec![Ok(f)]);
189        let mut bad = Frame::new(1, 1, 0, vec![]).to_bytes();
190        bad[1] ^= 1;
191        let mut wire = vec![END];
192        wire.extend_from_slice(&bad);
193        wire.push(END);
194        assert_eq!(d.push(&wire), vec![Err(FrameError::Checksum)]);
195    }
196}