Skip to main content

zigbee_core/aps/frame/
frame_control.rs

1//! APS Header Frame Control
2//!
3//! See Section 2.2.5.1
4use core::mem;
5
6use zigbee_macros::impl_byte;
7
8impl_byte! {
9    /// Frame Control field
10    ///
11    /// See Section 2.2.5.1.1
12    #[derive(Clone, Copy, Eq, PartialEq, Default)]
13    pub struct FrameControl(pub u8);
14}
15
16impl FrameControl {
17    /// See Section 2.2.5.1.1
18    pub fn frame_type(&self) -> FrameType {
19        unsafe { mem::transmute((self.0 & mask::FRAME_TYPE) >> offset::FRAME_TYPE) }
20    }
21
22    /// Sets the frame type
23    #[must_use]
24    pub fn set_frame_type(mut self, value: FrameType) -> Self {
25        self.0 = (self.0 & !mask::FRAME_TYPE) | (value as u8) << offset::FRAME_TYPE;
26        self
27    }
28
29    pub fn delivery_mode(&self) -> DeliveryMode {
30        unsafe { mem::transmute((self.0 & mask::DELIVERY_MODE) >> offset::DELIVERY_MODE) }
31    }
32
33    #[must_use]
34    pub fn set_delivery_mode(mut self, value: DeliveryMode) -> Self {
35        self.0 = (self.0 & !mask::DELIVERY_MODE) | (value as u8) << offset::DELIVERY_MODE;
36        self
37    }
38
39    /// whether the destination endpoint, cluster, profile, and source
40    /// endpoint fields are present in the acknowledgement frame
41    pub fn ack_format_flag(&self) -> bool {
42        ((self.0 & mask::ACK_FORMAT_FLAG) >> offset::ACK_FORMAT_FLAG) != 0
43    }
44
45    /// Sets the ack format flag
46    #[must_use]
47    pub fn set_ack_format_flag(mut self, value: bool) -> Self {
48        self.0 = (self.0 & !mask::ACK_FORMAT_FLAG) | ((value as u8) << offset::ACK_FORMAT_FLAG);
49        self
50    }
51
52    pub fn security_flag(&self) -> bool {
53        ((self.0 & mask::SECURITY_FLAG) >> offset::SECURITY_FLAG) != 0
54    }
55
56    #[must_use]
57    pub fn set_security_flag(mut self, value: bool) -> Self {
58        self.0 = (self.0 & !mask::SECURITY_FLAG) | ((value as u8) << offset::SECURITY_FLAG);
59        self
60    }
61
62    /// whether the originator requires an acknowledgement frame; always
63    /// false for broadcast or multicast
64    pub fn ack_request(&self) -> bool {
65        ((self.0 & mask::ACK_FLAG) >> offset::ACK_FLAG) != 0
66    }
67
68    /// Requests an APS acknowledgement for this frame (2.2.8.4.3).
69    ///
70    /// Must stay 0 for acknowledgement frames and for broadcast or
71    /// group-addressed transmissions.
72    #[must_use]
73    pub fn set_ack_request(mut self, value: bool) -> Self {
74        self.0 = (self.0 & !mask::ACK_FLAG) | ((value as u8) << offset::ACK_FLAG);
75        self
76    }
77
78    /// whether the extended header is included in the frame
79    pub fn extended_header(&self) -> bool {
80        ((self.0 & mask::EXTENDED_HEADER_FLAG) >> offset::EXTENDED_HEADER_FLAG) != 0
81    }
82
83    /// Whether the endpoint, cluster, and profile fields are present
84    /// (2.2.5.1).
85    ///
86    /// True for data frames and data-frame acks; an ack format sub-field of
87    /// 1 marks a command-frame ack without addressing fields (2.2.5.1.1.4).
88    pub fn has_data_fields(&self) -> bool {
89        matches!(self.frame_type(), FrameType::Data | FrameType::InterPan)
90            || (self.frame_type() == FrameType::Acknowledgement && !self.ack_format_flag())
91    }
92
93    /// Whether the destination endpoint field is present (2.2.5.1.2).
94    ///
95    /// Present for unicast or broadcast delivery when data fields are included.
96    pub fn has_destination_endpoint(&self) -> bool {
97        self.has_data_fields()
98            && matches!(
99                self.delivery_mode(),
100                DeliveryMode::Unicast | DeliveryMode::Broadcast
101            )
102    }
103}
104
105impl core::fmt::Debug for FrameControl {
106    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
107        f.debug_struct("FrameControl")
108            .field("frame_type", &self.frame_type())
109            .field("delivery_mode", &self.delivery_mode())
110            .field("ack_format", &self.ack_format_flag())
111            .field("security_flag", &self.security_flag())
112            .field("ack_request", &self.ack_request())
113            .field("extended_header", &self.extended_header())
114            .finish()
115    }
116}
117
118/// Frame Type
119///
120/// See Section 2.2.5.1.1
121#[repr(u8)]
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum FrameType {
124    Data = 0b00,
125    Command = 0b01,
126    Acknowledgement = 0b10,
127    InterPan = 0b11,
128}
129
130#[repr(u8)]
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum DeliveryMode {
133    Unicast = 0b00,
134    Reserved = 0b01,
135    Broadcast = 0b10,
136    GroubAddressing = 0b11,
137}
138
139impl_byte! {
140    #[derive(Clone, Debug, Eq, PartialEq)]
141    pub struct ExtendedFrameControlField {
142        pub extended_frame_control: ExtendedFrameControl,
143        #[parse_if = extended_frame_control.is_fragmented()]
144        pub block_number: Option<u8>,
145        #[parse_if = extended_frame_control.is_fragmented()]
146        pub ack_bitfield: Option<u8>,
147    }
148}
149
150impl_byte! {
151    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
152    pub struct ExtendedFrameControl {
153        fragmentation: Fragmentation
154    }
155}
156
157impl ExtendedFrameControl {
158    pub fn is_fragmented(&self) -> bool {
159        matches!(
160            self.fragmentation,
161            Fragmentation::Fragmentation | Fragmentation::PartOfFragmentedTransmission
162        )
163    }
164}
165
166impl_byte! {
167    #[tag(u8)]
168    /// Extended Header Sub-Frame
169    ///
170    /// See Section 2.2.5.1.8
171    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
172    pub enum Fragmentation {
173        NoFragmentation = 0b00,
174        Fragmentation = 0b01,
175        PartOfFragmentedTransmission = 0b10,
176        #[fallback = true]
177        Reserved(u8),
178    }
179}
180
181// 2.2.5.1.1 frame control bit layout
182mod offset {
183    pub const FRAME_TYPE: u8 = 0;
184    pub const DELIVERY_MODE: u8 = 2;
185    pub const ACK_FORMAT_FLAG: u8 = 4;
186    pub const SECURITY_FLAG: u8 = 5;
187    pub const ACK_FLAG: u8 = 6;
188    pub const EXTENDED_HEADER_FLAG: u8 = 7;
189}
190
191mod mask {
192    pub const FRAME_TYPE: u8 = 0x03;
193    pub const DELIVERY_MODE: u8 = 0x0C;
194    pub const ACK_FORMAT_FLAG: u8 = 0x10;
195    pub const SECURITY_FLAG: u8 = 0x20;
196    pub const ACK_FLAG: u8 = 0x40;
197    pub const EXTENDED_HEADER_FLAG: u8 = 0x80;
198}
199
200#[cfg(test)]
201mod tests {
202    use byte::TryRead;
203
204    use super::*;
205
206    #[test]
207    fn parse_frame_control() {
208        // bits 0-1: 01 (Command), bits 2-3: 00 (Unicast), rest: 0
209        let raw = [0b0000_0001_u8];
210
211        let (frame_control, len) = FrameControl::try_read(&raw, ()).unwrap();
212        assert_eq!(len, 1);
213        assert_eq!(frame_control.frame_type(), FrameType::Command);
214        assert_eq!(frame_control.delivery_mode(), DeliveryMode::Unicast);
215        assert!(!frame_control.ack_format_flag());
216        assert!(!frame_control.security_flag());
217        assert!(!frame_control.ack_request());
218        assert!(!frame_control.extended_header());
219    }
220
221    #[test]
222    fn parse_frame_control_data_broadcast_with_security() {
223        // bits 0-1: 00 (Data), bits 2-3: 10 (Broadcast), bit 5: 1 (Security)
224        let raw = [0b0010_1000_u8];
225
226        let (frame_control, len) = FrameControl::try_read(&raw, ()).unwrap();
227        assert_eq!(len, 1);
228        assert_eq!(frame_control.frame_type(), FrameType::Data);
229        assert_eq!(frame_control.delivery_mode(), DeliveryMode::Broadcast);
230        assert!(!frame_control.ack_format_flag());
231        assert!(frame_control.security_flag());
232        assert!(!frame_control.ack_request());
233        assert!(!frame_control.extended_header());
234    }
235
236    #[test]
237    fn set_frame_control_roundtrip() {
238        let fc = FrameControl::default()
239            .set_frame_type(FrameType::Data)
240            .set_delivery_mode(DeliveryMode::Broadcast);
241        assert_eq!(fc.0, 0x08);
242        assert_eq!(fc.frame_type(), FrameType::Data);
243        assert_eq!(fc.delivery_mode(), DeliveryMode::Broadcast);
244    }
245
246    #[test]
247    fn parse_extended_frame_control_with_fragmentation() {
248        let raw = [0b01u8];
249
250        let (frame_control, len) = ExtendedFrameControl::try_read(&raw, ()).unwrap();
251        assert_eq!(len, 1);
252        assert!(matches!(
253            frame_control.fragmentation,
254            Fragmentation::Fragmentation
255        ));
256    }
257
258    #[test]
259    fn parse_extended_frame_control_without_fragmentation() {
260        let raw = [0b00u8];
261
262        let (frame_control, len) = ExtendedFrameControl::try_read(&raw, ()).unwrap();
263        assert_eq!(len, 1);
264        assert!(matches!(
265            frame_control.fragmentation,
266            Fragmentation::NoFragmentation
267        ));
268    }
269}