Skip to main content

zigbee_zcl/
frame.rs

1//! The ZCL frame: header and payload.
2
3use zigbee_primitives::wire::{Reader, Truncated, Writer};
4
5/// Global (profile-wide) or cluster-specific command.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum FrameType {
8    /// A global command ([`crate::foundation`]).
9    Global,
10    /// A command defined by the cluster.
11    Cluster,
12}
13
14/// Which side of the cluster sent the frame.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Direction {
17    /// From a client to a server (a command a server receives).
18    ClientToServer,
19    /// From a server to a client (reports, responses, notifications).
20    ServerToClient,
21}
22
23impl Direction {
24    /// The other direction.
25    pub fn reverse(self) -> Direction {
26        match self {
27            Direction::ClientToServer => Direction::ServerToClient,
28            Direction::ServerToClient => Direction::ClientToServer,
29        }
30    }
31}
32
33/// A ZCL frame header.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct Header {
36    /// Global or cluster-specific.
37    pub frame_type: FrameType,
38    /// Manufacturer code, for manufacturer-specific commands.
39    pub manufacturer: Option<u16>,
40    /// Who sent it.
41    pub direction: Direction,
42    /// The sender does not want a default response.
43    pub disable_default_response: bool,
44    /// Transaction sequence number.
45    pub seq: u8,
46    /// Command id.
47    pub command: u8,
48}
49
50/// A ZCL frame.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Frame {
53    /// The header.
54    pub header: Header,
55    /// The command's payload.
56    pub payload: Vec<u8>,
57}
58
59/// The frame was too short, or used reserved frame type bits.
60#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
61pub enum FrameError {
62    /// Too short.
63    #[error(transparent)]
64    Truncated(#[from] Truncated),
65    /// Frame type 2 or 3 is reserved.
66    #[error("reserved ZCL frame type {0}")]
67    ReservedType(u8),
68}
69
70impl Frame {
71    /// Parse a frame.
72    pub fn parse(bytes: &[u8]) -> Result<Frame, FrameError> {
73        let mut r = Reader::new(bytes);
74        let control = r.u8()?;
75        let frame_type = match control & 0x03 {
76            0 => FrameType::Global,
77            1 => FrameType::Cluster,
78            other => return Err(FrameError::ReservedType(other)),
79        };
80        let manufacturer = if control & 0x04 != 0 {
81            Some(r.u16()?)
82        } else {
83            None
84        };
85        let direction = if control & 0x08 != 0 {
86            Direction::ServerToClient
87        } else {
88            Direction::ClientToServer
89        };
90        let seq = r.u8()?;
91        let command = r.u8()?;
92        Ok(Frame {
93            header: Header {
94                frame_type,
95                manufacturer,
96                direction,
97                disable_default_response: control & 0x10 != 0,
98                seq,
99                command,
100            },
101            payload: r.rest().to_vec(),
102        })
103    }
104
105    /// Encode the frame.
106    pub fn encode(&self) -> Vec<u8> {
107        let h = &self.header;
108        let mut control = match h.frame_type {
109            FrameType::Global => 0,
110            FrameType::Cluster => 1,
111        };
112        if h.manufacturer.is_some() {
113            control |= 0x04;
114        }
115        if h.direction == Direction::ServerToClient {
116            control |= 0x08;
117        }
118        if h.disable_default_response {
119            control |= 0x10;
120        }
121        let mut w = Vec::with_capacity(5 + self.payload.len());
122        w.put_u8(control);
123        if let Some(m) = h.manufacturer {
124            w.put_u16(m);
125        }
126        w.put_u8(h.seq);
127        w.put_u8(h.command);
128        w.put_bytes(&self.payload);
129        w
130    }
131
132    /// A global command frame.
133    pub fn global(direction: Direction, seq: u8, command: u8, payload: Vec<u8>) -> Frame {
134        Frame {
135            header: Header {
136                frame_type: FrameType::Global,
137                manufacturer: None,
138                direction,
139                disable_default_response: false,
140                seq,
141                command,
142            },
143            payload,
144        }
145    }
146
147    /// A cluster-specific command frame.
148    pub fn cluster(direction: Direction, seq: u8, command: u8, payload: Vec<u8>) -> Frame {
149        Frame {
150            header: Header {
151                frame_type: FrameType::Cluster,
152                manufacturer: None,
153                direction,
154                disable_default_response: false,
155                seq,
156                command,
157            },
158            payload,
159        }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn round_trips_with_manufacturer_code() {
169        let mut f = Frame::cluster(Direction::ServerToClient, 7, 0x0A, vec![1, 2]);
170        f.header.manufacturer = Some(0x115F);
171        f.header.disable_default_response = true;
172        let bytes = f.encode();
173        assert_eq!(bytes, [0x1D, 0x5F, 0x11, 7, 0x0A, 1, 2]);
174        assert_eq!(Frame::parse(&bytes).unwrap(), f);
175        assert!(Frame::parse(&[0x02, 0, 0]).is_err());
176        assert!(Frame::parse(&[0x04, 0]).is_err());
177    }
178}