Skip to main content

zigbee_ezsp/
frame.rs

1//! The EZSP frame header: sequence, frame control and frame id.
2//!
3//! Every EZSP exchange starts with a `version` command in the legacy format
4//! (one-byte frame control and frame id). Once the NCP has answered with
5//! protocol version 8 or later, both sides use the extended format: a
6//! two-byte frame control (whose high byte carries the format version, 1)
7//! and a two-byte frame id.
8
9use zigbee_primitives::wire::{Reader, Truncated};
10
11/// Which header layout a frame uses.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Format {
14    /// `seq, control, frame_id`: only for the first `version` exchange.
15    Legacy,
16    /// `seq, control_lo, control_hi, frame_id_lo, frame_id_hi`.
17    Extended,
18}
19
20/// Frame control: set in responses and callbacks (NCP to host).
21pub const CONTROL_RESPONSE: u8 = 0x80;
22/// Frame control: the NCP ran out of memory since the last response.
23pub const CONTROL_OVERFLOW: u8 = 0x01;
24/// Frame control: the NCP truncated this response.
25pub const CONTROL_TRUNCATED: u8 = 0x02;
26/// Frame control: the NCP has callbacks waiting.
27pub const CONTROL_PENDING_CALLBACKS: u8 = 0x04;
28/// Frame control: a synchronous callback.
29pub const CONTROL_SYNC_CALLBACK: u8 = 0x08;
30/// Frame control: an asynchronous callback (the UART host's normal case).
31pub const CONTROL_ASYNC_CALLBACK: u8 = 0x10;
32/// Extended frame control high byte: format version 1, unsecured, unpadded.
33pub const CONTROL_HIGH_FORMAT_1: u8 = 0x01;
34
35/// Frame header errors.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
37pub enum HeaderError {
38    /// Shorter than a header.
39    #[error(transparent)]
40    Truncated(#[from] Truncated),
41    /// The extended frame control names an unknown format version.
42    #[error("unsupported EZSP frame format version {0}")]
43    FormatVersion(u8),
44    /// The frame is encrypted or padded (EZSP security), which this crate
45    /// does not speak.
46    #[error("secured or padded EZSP frames are not supported")]
47    Secured,
48}
49
50/// A parsed frame header and its parameters.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Header<'a> {
53    /// Sequence number, echoed in the response.
54    pub seq: u8,
55    /// Frame control, low byte.
56    pub control: u8,
57    /// Frame id.
58    pub frame_id: u16,
59    /// Parameters after the header.
60    pub params: &'a [u8],
61}
62
63impl Header<'_> {
64    /// NCP to host.
65    pub fn is_response(&self) -> bool {
66        self.control & CONTROL_RESPONSE != 0
67    }
68
69    /// A callback (sync or async) rather than the response to a command.
70    pub fn is_callback(&self) -> bool {
71        self.control & (CONTROL_SYNC_CALLBACK | CONTROL_ASYNC_CALLBACK) != 0
72    }
73
74    /// The NCP reported running out of memory.
75    pub fn overflow(&self) -> bool {
76        self.is_response() && self.control & CONTROL_OVERFLOW != 0
77    }
78
79    /// The NCP truncated the response.
80    pub fn truncated(&self) -> bool {
81        self.is_response() && self.control & CONTROL_TRUNCATED != 0
82    }
83}
84
85/// Parse a frame in the given format.
86pub fn parse(frame: &[u8], format: Format) -> Result<Header<'_>, HeaderError> {
87    let mut r = Reader::new(frame);
88    let seq = r.u8()?;
89    let control = r.u8()?;
90    let frame_id = match format {
91        Format::Legacy => u16::from(r.u8()?),
92        Format::Extended => {
93            let high = r.u8()?;
94            if high & 0x03 != CONTROL_HIGH_FORMAT_1 {
95                return Err(HeaderError::FormatVersion(high & 0x03));
96            }
97            if high & 0xC0 != 0 {
98                return Err(HeaderError::Secured);
99            }
100            r.u16()?
101        }
102    };
103    Ok(Header {
104        seq,
105        control,
106        frame_id,
107        params: r.rest(),
108    })
109}
110
111/// The format of a frame from the host, as the NCP sees it: the legacy
112/// `version` command is exactly four bytes with frame id zero.
113pub fn detect_command_format(frame: &[u8]) -> Format {
114    match frame {
115        [_, 0x00, 0x00, _] => Format::Legacy,
116        _ => Format::Extended,
117    }
118}
119
120/// Build a frame.
121pub fn encode(format: Format, seq: u8, control: u8, frame_id: u16, params: &[u8]) -> Vec<u8> {
122    let mut out = Vec::with_capacity(5 + params.len());
123    out.push(seq);
124    out.push(control);
125    match format {
126        Format::Legacy => out.push(frame_id as u8),
127        Format::Extended => {
128            out.push(CONTROL_HIGH_FORMAT_1);
129            out.extend_from_slice(&frame_id.to_le_bytes());
130        }
131    }
132    out.extend_from_slice(params);
133    out
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn legacy_and_extended_round_trip() {
142        let legacy = encode(Format::Legacy, 0, 0, 0, &[13]);
143        assert_eq!(legacy, [0, 0, 0, 13]);
144        assert_eq!(detect_command_format(&legacy), Format::Legacy);
145        let ext = encode(Format::Extended, 5, 0, 0x0114, &[1, 2]);
146        assert_eq!(ext, [5, 0, 1, 0x14, 0x01, 1, 2]);
147        assert_eq!(detect_command_format(&ext), Format::Extended);
148        let h = parse(&ext, Format::Extended).unwrap();
149        assert_eq!((h.seq, h.frame_id, h.params), (5, 0x0114, &[1u8, 2][..]));
150        assert!(parse(&[1, 0x80, 0x81, 0, 0], Format::Extended).is_err());
151        assert!(parse(&[1], Format::Extended).is_err());
152    }
153}