1use zigbee_primitives::wire::{Reader, Truncated};
6
7const END: u8 = 0xC0;
8const ESC: u8 = 0xDB;
9const ESC_END: u8 = 0xDC;
10const ESC_ESC: u8 = 0xDD;
11pub const MAX_FRAME: usize = 512;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Frame {
17 pub command: u8,
19 pub seq: u8,
21 pub status: u8,
23 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
104pub enum FrameError {
105 #[error("deCONZ frame of {0} bytes is too short")]
107 Short(usize),
108 #[error("deCONZ frame checksum mismatch")]
110 Checksum,
111 #[error("deCONZ frame length field {0} does not match")]
113 Length(usize),
114 #[error(transparent)]
116 Truncated(#[from] Truncated),
117}
118
119#[derive(Debug, Default)]
122pub struct Decoder {
123 buf: Vec<u8>,
124 escaped: bool,
125 overflow: bool,
126}
127
128impl Decoder {
129 pub fn new() -> Decoder {
131 Decoder::default()
132 }
133
134 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 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}