Skip to main content

zigbee_ash/
frame.rs

1//! ASH frames: control byte, data randomization, CRC and byte stuffing.
2
3use crc::{Crc, CRC_16_IBM_3740};
4
5/// Flag byte: ends every frame.
6pub const FLAG: u8 = 0x7E;
7/// Escape byte: the next byte is XORed with [`FLIP`].
8pub const ESCAPE: u8 = 0x7D;
9/// Software flow control: resume.
10pub const XON: u8 = 0x11;
11/// Software flow control: pause.
12pub const XOFF: u8 = 0x13;
13/// Substitute byte: a low-level receive error replaced a byte; the frame is bad.
14pub const SUBSTITUTE: u8 = 0x18;
15/// Cancel byte: discards the frame in progress.
16pub const CANCEL: u8 = 0x1A;
17/// XOR applied to an escaped byte.
18pub const FLIP: u8 = 0x20;
19
20/// The ASH protocol version this crate speaks.
21pub const ASH_VERSION: u8 = 2;
22
23/// Smallest DATA field (the smallest EZSP frame).
24pub const MIN_DATA_LEN: usize = 3;
25/// Largest DATA field (the largest EZSP frame).
26pub const MAX_DATA_LEN: usize = 220;
27/// Largest frame before stuffing: control, data and CRC.
28pub const MAX_FRAME_LEN: usize = 1 + MAX_DATA_LEN + 2;
29
30/// CRC-CCITT as ASH uses it: polynomial 0x1021, initial 0xFFFF, not reflected.
31const CRC: Crc<u16> = Crc::<u16>::new(&CRC_16_IBM_3740);
32
33/// Reset codes an NCP reports in RSTACK and ERROR frames.
34pub mod reset_code {
35    /// Reset reason unknown.
36    pub const UNKNOWN: u8 = 0x00;
37    /// External (pin) reset.
38    pub const EXTERNAL: u8 = 0x01;
39    /// Power on.
40    pub const POWER_ON: u8 = 0x02;
41    /// Watchdog.
42    pub const WATCHDOG: u8 = 0x03;
43    /// Assert.
44    pub const ASSERT: u8 = 0x06;
45    /// Returned from the bootloader.
46    pub const BOOTLOADER: u8 = 0x09;
47    /// Software reset, the reply to RST.
48    pub const SOFTWARE: u8 = 0x0B;
49    /// The NCP gave up after too many ACK timeouts.
50    pub const ACK_TIMEOUTS: u8 = 0x51;
51    /// Chip-specific reset reason.
52    pub const CHIP_SPECIFIC: u8 = 0x80;
53}
54
55/// One ASH frame.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Frame {
58    /// Carries one EZSP frame.
59    Data {
60        /// This frame's number, 0 to 7.
61        frm_num: u8,
62        /// Set when this is a retransmission.
63        re_tx: bool,
64        /// The next frame number the sender expects to receive.
65        ack_num: u8,
66        /// The EZSP frame, already de-randomized.
67        payload: Vec<u8>,
68    },
69    /// Acknowledges every frame before `ack_num`.
70    Ack {
71        /// The next frame number expected.
72        ack_num: u8,
73        /// The sender is not ready to receive DATA.
74        not_ready: bool,
75    },
76    /// Rejects: the frame `ack_num` was missing or bad.
77    Nak {
78        /// The next frame number expected.
79        ack_num: u8,
80        /// The sender is not ready to receive DATA.
81        not_ready: bool,
82    },
83    /// Host to NCP: reset.
84    Rst,
85    /// NCP to host: reset done.
86    RstAck {
87        /// ASH version, 2.
88        version: u8,
89        /// Why the NCP reset ([`reset_code`]).
90        code: u8,
91    },
92    /// NCP to host: fatal error, the NCP is now disconnected.
93    Error {
94        /// ASH version, 2.
95        version: u8,
96        /// The error ([`reset_code`]).
97        code: u8,
98    },
99}
100
101/// Why a received frame was dropped.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
103pub enum FrameError {
104    /// The CRC did not match.
105    #[error("bad CRC")]
106    BadCrc,
107    /// Shorter than the frame type allows.
108    #[error("frame too short")]
109    TooShort,
110    /// Longer than [`MAX_FRAME_LEN`] or the frame type allows.
111    #[error("frame too long")]
112    TooLong,
113    /// A substitute byte marked a UART error inside the frame.
114    #[error("UART error inside frame")]
115    CommError,
116    /// The control byte names no frame type.
117    #[error("invalid control byte {0:#04x}")]
118    InvalidControl(u8),
119}
120
121/// XOR `data` with ASH's pseudo-random sequence (seed 0x42, polynomial 0xB8).
122/// Applying it twice restores the input.
123pub fn randomize(data: &mut [u8]) {
124    let mut rand: u8 = 0x42;
125    for byte in data.iter_mut() {
126        *byte ^= rand;
127        rand = if rand & 1 == 0 {
128            rand >> 1
129        } else {
130            (rand >> 1) ^ 0xB8
131        };
132    }
133}
134
135fn is_reserved(byte: u8) -> bool {
136    matches!(byte, FLAG | ESCAPE | XON | XOFF | SUBSTITUTE | CANCEL)
137}
138
139impl Frame {
140    /// The control byte.
141    pub fn control(&self) -> u8 {
142        match self {
143            Frame::Data {
144                frm_num,
145                re_tx,
146                ack_num,
147                ..
148            } => ((frm_num & 7) << 4) | (u8::from(*re_tx) << 3) | (ack_num & 7),
149            Frame::Ack { ack_num, not_ready } => 0x80 | (u8::from(*not_ready) << 3) | (ack_num & 7),
150            Frame::Nak { ack_num, not_ready } => 0xA0 | (u8::from(*not_ready) << 3) | (ack_num & 7),
151            Frame::Rst => 0xC0,
152            Frame::RstAck { .. } => 0xC1,
153            Frame::Error { .. } => 0xC2,
154        }
155    }
156
157    /// The frame as sent on the wire: stuffed, with its CRC and closing flag.
158    /// RST is preceded by a cancel byte so it never joins a partial frame.
159    pub fn encode(&self) -> Vec<u8> {
160        let mut raw = Vec::with_capacity(8);
161        raw.push(self.control());
162        match self {
163            Frame::Data { payload, .. } => {
164                let start = raw.len();
165                raw.extend_from_slice(payload);
166                if let Some(data) = raw.get_mut(start..) {
167                    randomize(data);
168                }
169            }
170            Frame::RstAck { version, code } | Frame::Error { version, code } => {
171                raw.push(*version);
172                raw.push(*code);
173            }
174            _ => {}
175        }
176        let crc = CRC.checksum(&raw);
177        raw.extend_from_slice(&crc.to_be_bytes());
178
179        let mut out = Vec::with_capacity(raw.len() * 2 + 2);
180        if matches!(self, Frame::Rst) {
181            out.push(CANCEL);
182        }
183        for byte in raw {
184            if is_reserved(byte) {
185                out.push(ESCAPE);
186                out.push(byte ^ FLIP);
187            } else {
188                out.push(byte);
189            }
190        }
191        out.push(FLAG);
192        out
193    }
194
195    /// Parse an unstuffed frame: control byte, fields and CRC, without the flag.
196    pub fn parse(raw: &[u8]) -> Result<Frame, FrameError> {
197        if raw.len() > MAX_FRAME_LEN {
198            return Err(FrameError::TooLong);
199        }
200        let (body, crc) = match raw.len().checked_sub(2) {
201            Some(split) if split >= 1 => raw.split_at(split),
202            _ => return Err(FrameError::TooShort),
203        };
204        let wanted = u16::from_be_bytes(match crc {
205            [a, b] => [*a, *b],
206            _ => return Err(FrameError::TooShort),
207        });
208        if CRC.checksum(body) != wanted {
209            return Err(FrameError::BadCrc);
210        }
211        let (control, fields) = match body.split_first() {
212            Some((c, f)) => (*c, f),
213            None => return Err(FrameError::TooShort),
214        };
215        let fixed = |len: usize| -> Result<(), FrameError> {
216            match fields.len().cmp(&len) {
217                std::cmp::Ordering::Less => Err(FrameError::TooShort),
218                std::cmp::Ordering::Greater => Err(FrameError::TooLong),
219                std::cmp::Ordering::Equal => Ok(()),
220            }
221        };
222        let ack_num = control & 7;
223        let not_ready = control & 0x08 != 0;
224        if control & 0x80 == 0 {
225            if fields.len() < MIN_DATA_LEN {
226                return Err(FrameError::TooShort);
227            }
228            let mut payload = fields.to_vec();
229            randomize(&mut payload);
230            return Ok(Frame::Data {
231                frm_num: (control >> 4) & 7,
232                re_tx: control & 0x08 != 0,
233                ack_num,
234                payload,
235            });
236        }
237        match control & 0xE0 {
238            0x80 => fixed(0).map(|_| Frame::Ack { ack_num, not_ready }),
239            0xA0 => fixed(0).map(|_| Frame::Nak { ack_num, not_ready }),
240            _ => match (control, fields) {
241                (0xC0, _) => fixed(0).map(|_| Frame::Rst),
242                (0xC1, [version, code]) => Ok(Frame::RstAck {
243                    version: *version,
244                    code: *code,
245                }),
246                (0xC2, [version, code]) => Ok(Frame::Error {
247                    version: *version,
248                    code: *code,
249                }),
250                (0xC1 | 0xC2, _) => Err(if fields.len() < 2 {
251                    FrameError::TooShort
252                } else {
253                    FrameError::TooLong
254                }),
255                _ => Err(FrameError::InvalidControl(control)),
256            },
257        }
258    }
259}
260
261/// Splits a received byte stream into frames: removes stuffing, honours the
262/// cancel and substitute bytes, ignores XON/XOFF, and bounds the buffer at
263/// [`MAX_FRAME_LEN`] so a stream without flags cannot grow memory.
264#[derive(Debug, Default, Clone)]
265pub struct Decoder {
266    buf: Vec<u8>,
267    escaped: bool,
268    error: Option<FrameError>,
269}
270
271impl Decoder {
272    /// An empty decoder.
273    pub fn new() -> Self {
274        Decoder {
275            buf: Vec::with_capacity(MAX_FRAME_LEN),
276            escaped: false,
277            error: None,
278        }
279    }
280
281    /// Drop any partial frame.
282    pub fn reset(&mut self) {
283        self.buf.clear();
284        self.escaped = false;
285        self.error = None;
286    }
287
288    /// Feed one byte. Returns a frame, or the reason one was dropped, when a
289    /// flag byte ends it.
290    pub fn push(&mut self, byte: u8) -> Option<Result<Frame, FrameError>> {
291        match byte {
292            FLAG => {
293                let error = self.error.take();
294                let escaped = std::mem::replace(&mut self.escaped, false);
295                if self.buf.is_empty() && error.is_none() {
296                    return None;
297                }
298                let result = match error {
299                    Some(e) => Err(e),
300                    None if escaped => Err(FrameError::CommError),
301                    None => Frame::parse(&self.buf),
302                };
303                self.buf.clear();
304                Some(result)
305            }
306            CANCEL => {
307                self.reset();
308                None
309            }
310            SUBSTITUTE => {
311                self.error = Some(FrameError::CommError);
312                None
313            }
314            XON | XOFF => None,
315            ESCAPE => {
316                self.escaped = true;
317                None
318            }
319            _ => {
320                if self.error.is_some() {
321                    return None;
322                }
323                let value = if std::mem::replace(&mut self.escaped, false) {
324                    byte ^ FLIP
325                } else {
326                    byte
327                };
328                if self.buf.len() >= MAX_FRAME_LEN {
329                    self.error = Some(FrameError::TooLong);
330                    self.buf.clear();
331                } else {
332                    self.buf.push(value);
333                }
334                None
335            }
336        }
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    fn decode_all(bytes: &[u8]) -> Vec<Result<Frame, FrameError>> {
345        let mut d = Decoder::new();
346        bytes.iter().filter_map(|b| d.push(*b)).collect()
347    }
348
349    // Worked examples from UG101, "ASH Protocol", section 4.
350    #[test]
351    fn rst_matches_ug101() {
352        assert_eq!(Frame::Rst.encode(), [0x1A, 0xC0, 0x38, 0xBC, 0x7E]);
353    }
354
355    #[test]
356    fn rstack_matches_ug101() {
357        let bytes = [0xC1, 0x02, 0x02, 0x9B, 0x7B, 0x7E];
358        assert_eq!(
359            decode_all(&bytes),
360            vec![Ok(Frame::RstAck {
361                version: 2,
362                code: 2
363            })]
364        );
365        assert_eq!(
366            Frame::RstAck {
367                version: 2,
368                code: 2
369            }
370            .encode(),
371            bytes
372        );
373    }
374
375    #[test]
376    fn ack_and_nak_match_ug101() {
377        assert_eq!(
378            Frame::Ack {
379                ack_num: 1,
380                not_ready: false
381            }
382            .encode(),
383            [0x81, 0x60, 0x59, 0x7E]
384        );
385        assert_eq!(
386            Frame::Nak {
387                ack_num: 6,
388                not_ready: false
389            }
390            .encode(),
391            [0xA6, 0x34, 0xDC, 0x7E]
392        );
393    }
394
395    #[test]
396    fn version_data_frame_matches_ug101() {
397        // EZSP "version" command, seq 0, desired protocol version 2.
398        let frame = Frame::Data {
399            frm_num: 2,
400            re_tx: false,
401            ack_num: 5,
402            payload: vec![0x00, 0x00, 0x00, 0x02],
403        };
404        assert_eq!(
405            frame.encode(),
406            [0x25, 0x42, 0x21, 0xA8, 0x56, 0xA6, 0x09, 0x7E]
407        );
408        assert_eq!(decode_all(&frame.encode()), vec![Ok(frame)]);
409    }
410
411    #[test]
412    fn randomize_is_an_involution() {
413        let mut data: Vec<u8> = (0..=255).collect();
414        randomize(&mut data);
415        assert_ne!(data, (0..=255).collect::<Vec<u8>>());
416        randomize(&mut data);
417        assert_eq!(data, (0..=255).collect::<Vec<u8>>());
418    }
419
420    #[test]
421    fn stuffing_round_trips_reserved_bytes() {
422        // Payload chosen so that randomized bytes and CRC hit reserved values.
423        for seed in 0u8..=255 {
424            let payload = vec![
425                seed,
426                FLAG ^ 0x42,
427                ESCAPE,
428                XON,
429                XOFF,
430                SUBSTITUTE,
431                CANCEL,
432                0xFF,
433            ];
434            let frame = Frame::Data {
435                frm_num: seed & 7,
436                re_tx: seed & 1 == 1,
437                ack_num: 3,
438                payload,
439            };
440            let wire = frame.encode();
441            assert!(wire[..wire.len() - 1]
442                .iter()
443                .all(|b| !is_reserved(*b) || *b == ESCAPE));
444            assert_eq!(decode_all(&wire), vec![Ok(frame)]);
445        }
446    }
447
448    #[test]
449    fn bad_crc_cancel_substitute_and_overlong_are_handled() {
450        let mut wire = Frame::Ack {
451            ack_num: 1,
452            not_ready: false,
453        }
454        .encode();
455        wire[1] ^= 0x01;
456        assert_eq!(decode_all(&wire), vec![Err(FrameError::BadCrc)]);
457
458        // Cancel discards the partial frame before it.
459        let mut stream = vec![0x81, 0x60, CANCEL];
460        stream.extend(
461            Frame::Ack {
462                ack_num: 2,
463                not_ready: false,
464            }
465            .encode(),
466        );
467        assert_eq!(
468            decode_all(&stream),
469            vec![Ok(Frame::Ack {
470                ack_num: 2,
471                not_ready: false
472            })]
473        );
474
475        assert_eq!(
476            decode_all(&[0x81, SUBSTITUTE, 0x60, 0x59, FLAG]),
477            vec![Err(FrameError::CommError)]
478        );
479
480        let mut long = vec![0x01; MAX_FRAME_LEN + 10];
481        long.push(FLAG);
482        assert_eq!(decode_all(&long), vec![Err(FrameError::TooLong)]);
483        assert_eq!(decode_all(&[FLAG, FLAG]), vec![]);
484    }
485}