Skip to main content

zigbee_mac/
mlme.rs

1use ieee802154::mac::Address;
2use ieee802154::mac::PanId;
3use ieee802154::mac::beacon::SuperframeSpecification;
4use ieee802154::mac::command::AssociationStatus;
5use ieee802154::mac::command::CapabilityInformation;
6use thiserror::Error;
7use zigbee_macros::impl_byte;
8use zigbee_types::ByteArray;
9use zigbee_types::IeeeAddress;
10use zigbee_types::ShortAddress;
11
12pub const MAX_IEEE802154_CHANNELS: usize = 27;
13
14pub const MAX_PAN_DESCRIPTOR_SIZE: usize = 27;
15
16pub const A_BASE_SLOT_DURATION: u32 = 60;
17pub const A_NUM_SUPER_FRAME_SLOTS: u32 = 16;
18pub const A_BASE_SUPER_FRAME_DURATION: u32 = A_BASE_SLOT_DURATION * A_NUM_SUPER_FRAME_SLOTS;
19
20/// The maximum time, in symbols, a device shall wait for a response command
21/// to be available following a request command. See IEEE 802.15.4-2003 7.4.2.
22/// aResponseWaitTime = 32 * aBaseSuperframeDuration = 32 * 960 = 30720 symbols.
23pub const A_RESPONSE_WAIT_TIME: u32 = 32 * A_BASE_SUPER_FRAME_DURATION;
24
25/// The maximum number of retries allowed after a transmission failure (i.e. a
26/// missing acknowledgment). See IEEE 802.15.4-2003 7.4.2 (aMaxFrameRetries).
27pub const A_MAX_FRAME_RETRIES: u8 = 3;
28
29/// MAC sub-layer management entity.
30///
31/// All methods take `&self`: an implementation is expected to provide its own
32/// interior mutability (the radio is a single shared resource). This lets the
33/// upper layers hold the MAC by shared reference and drive receive and transmit
34/// concurrently from separate tasks.
35pub trait Mlme {
36    /// The device's IEEE (extended) address as provisioned by the hardware,
37    /// e.g. read from efuse.
38    fn ieee_address(&self) -> IeeeAddress;
39
40    /// MLME-SET.request of the addressing attributes (IEEE 802.15.4 7.4.2)
41    /// and the operating channel.
42    ///
43    /// Applies what the network layer knows about this device, so the
44    /// hardware filter accepts frames addressed to it: the channel it
45    /// operates on, `macPANId`, and the `macShortAddress` it was assigned.
46    /// [`Self::associate`] already does this for an association; the NWK layer
47    /// calls this when the values come from elsewhere — a rejoin response, a
48    /// parent on another channel, or a restored information base after a
49    /// reset (3.6.8).
50    async fn configure(&self, config: MacConfig);
51
52    async fn scan_network(
53        &self,
54        ty: ScanType,
55        channels: core::ops::Range<u8>,
56        duration: u8,
57    ) -> Result<ScanResult, MacError>;
58
59    async fn associate(
60        &self,
61        channel: u8,
62        dest: Address,
63        capabilities: CapabilityInformation,
64    ) -> Result<AssociationResponse, MacError>;
65
66    /// MLME-POLL.request + data reception (IEEE 802.15.4 7.1.16.1).
67    ///
68    /// Sends a data request command to `coord_address`, then stays in
69    /// receive mode to capture both the ACK (with frame-pending check)
70    /// and the subsequent data frame in a single uninterrupted session.
71    ///
72    /// Returns `Ok((bytes_written, lqi))` on success,
73    /// `Err(MacError::NoData)` if the ACK has frame-pending clear or
74    /// no data frame arrives within the timeout, and `Err(MacError::NoAck)`
75    /// if the data request itself went unacknowledged — the coordinator is
76    /// unreachable rather than merely idle.
77    async fn poll_data(
78        &self,
79        coord_address: Address,
80        buf: &mut [u8],
81    ) -> Result<(usize, u8), MacError>;
82
83    /// Passively wait for and return the next inbound MAC data frame.
84    ///
85    /// Unlike [`Self::poll_data`], this sends nothing — it relies on the radio
86    /// being in receive mode (rx-on-when-idle) and simply yields the next data
87    /// frame addressed to this device (or a relevant broadcast). Intended for
88    /// the steady-state receive loop after joining.
89    ///
90    /// Returns `Ok((bytes_written, lqi))` for the received frame's payload.
91    async fn receive(&self, buf: &mut [u8]) -> Result<(usize, u8), MacError>;
92
93    /// Transmit a MAC data frame carrying the given NWK-layer payload.
94    ///
95    /// The implementation constructs the MAC header (frame control,
96    /// sequence number, addressing) and appends `payload` as the MAC
97    /// service data unit.
98    async fn transmit_data(&self, dest: Address, payload: &[u8]) -> Result<(), MacError>;
99
100    /// Returns a 32-bit random value from the MAC-layer RNG.
101    /// This value is not guaranteed cryptographic
102    fn random_u32(&self) -> u32;
103
104    fn random_u8(&self) -> u8 {
105        (self.random_u32() & 0xff) as u8
106    }
107}
108
109/// MAC attributes the network layer programs (see [`Mlme::configure`]).
110///
111/// Every field is optional: `None` leaves that attribute as the implementation
112/// has it, so a caller only states what it actually knows.
113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
114pub struct MacConfig {
115    /// `phyCurrentChannel`: the channel the network operates on.
116    pub channel: Option<u8>,
117    /// `macPANId` of that network.
118    pub pan_id: Option<PanId>,
119    /// `macShortAddress` assigned to this device.
120    pub short_address: Option<ShortAddress>,
121    /// `macPromiscuousMode` (7.4.2): pass every frame up instead of filtering
122    /// on the addresses above.
123    pub promiscuous: Option<bool>,
124    /// Acknowledge received frames that request it (7.5.6.4).
125    pub auto_ack_rx: Option<bool>,
126    /// Wait for the acknowledgement of transmitted frames that request it.
127    pub auto_ack_tx: Option<bool>,
128}
129
130impl MacConfig {
131    /// Attributes of a device operating as a member of a network: filtering on
132    /// its addresses, acknowledging and expecting acknowledgements.
133    pub fn joined(channel: u8, pan_id: PanId, short_address: ShortAddress) -> Self {
134        Self {
135            channel: Some(channel),
136            pan_id: Some(pan_id),
137            short_address: Some(short_address),
138            promiscuous: Some(false),
139            auto_ack_rx: Some(true),
140            auto_ack_tx: Some(true),
141        }
142    }
143}
144
145impl MacConfig {
146    /// Tune the radio to a channel, leaving the addressing attributes alone.
147    pub fn channel(channel: u8) -> Self {
148        Self {
149            channel: Some(channel),
150            ..Self::default()
151        }
152    }
153
154    /// Apply an assigned short address, leaving channel and PAN id alone.
155    pub fn short_address(address: ShortAddress) -> Self {
156        Self {
157            short_address: Some(address),
158            ..Self::default()
159        }
160    }
161}
162
163#[derive(Debug)]
164pub struct AssociationResponse {
165    pub device_address: IeeeAddress,
166    pub association_address: ShortAddress,
167    pub status: AssociationStatus,
168}
169
170#[repr(u8)]
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum ScanType {
173    Ed,
174    Active,
175    Passive,
176    Orphan,
177}
178
179#[derive(Debug, Error)]
180pub enum MacError {
181    #[error("no beacons received")]
182    NoBeacon,
183    #[error("invalid scan parameters")]
184    InvalidScanParams,
185    #[error("read error")]
186    ReadError(byte::Error),
187    #[error("invalid frame")]
188    InvalidFrame(byte::Error),
189    #[error("no data available from coordinator")]
190    NoData,
191    #[error("no acknowledgment received")]
192    NoAck,
193    #[cfg(feature = "esp")]
194    #[error("transmit failed (no ack, channel busy or coex abort)")]
195    TxFailed,
196    #[cfg(feature = "esp")]
197    #[error("transmit-done signal timed out")]
198    TxTimeout,
199    #[cfg(feature = "esp")]
200    #[error("radio error")]
201    RadioError(#[from] esp_radio::ieee802154::Error),
202    #[cfg(feature = "esp")]
203    #[error("timed out waiting for the radio (held by another MAC operation)")]
204    RadioLockTimeout,
205    #[cfg(feature = "esp")]
206    #[error("radio lock wait queue full (too many concurrent MAC operations)")]
207    RadioLockQueueFull,
208}
209
210impl From<byte::Error> for MacError {
211    fn from(e: byte::Error) -> Self {
212        Self::InvalidFrame(e)
213    }
214}
215
216#[cfg(feature = "alloc")]
217pub type PanDescriptorList = alloc::vec::Vec<PanDescriptor>;
218#[cfg(not(feature = "alloc"))]
219pub type PanDescriptorList = heapless::Vec<PanDescriptor, MAX_PAN_DESCRIPTOR_SIZE>;
220
221#[derive(Debug)]
222pub struct ScanResult {
223    pub scan_type: ScanType,
224    pub pan_descriptor: PanDescriptorList,
225}
226
227#[non_exhaustive]
228#[derive(Debug)]
229pub struct PanDescriptor {
230    pub channel: u8,
231    pub coord_addr_mode: u8,
232    pub coord_pan_id: ShortAddress,
233    pub coord_address: Address,
234    pub superframe_spec: SuperframeSpecification,
235    // TODO: gts_permit, timestamp, acl_entry, security_failure
236    pub link_quality: u8,
237    pub security_use: bool,
238    pub zigbee_beacon: ZigbeeBeacon,
239}
240
241impl_byte! {
242    #[derive(Debug)]
243    pub struct ZigbeeBeacon {
244        pub protocol_id: u8,
245        pub stack_profile: StackProfile,
246        pub extended_pan_id: IeeeAddress,
247        pub tx_offset: ByteArray<3>,
248        pub update_id: u8,
249    }
250}
251
252impl_byte! {
253    /// Stack Profile field
254    ///
255    /// See Zigbee specification Annex D for bit field layout.
256    #[derive(Clone, Copy, Eq, PartialEq)]
257    pub struct StackProfile(pub u16);
258}
259
260impl core::fmt::Debug for StackProfile {
261    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
262        f.debug_struct("StackProfile")
263            .field("stack_profile", &self.stack_profile())
264            .field("protocol_version", &self.protocol_version())
265            .field("router_capacity", &self.router_capacity())
266            .field("device_depth", &self.device_depth())
267            .field("end_device_capacity", &self.end_device_capacity())
268            .finish()
269    }
270}
271
272impl StackProfile {
273    /// Stack profile value
274    pub fn stack_profile(&self) -> u8 {
275        ((self.0 & mask::STACK_PROFILE) >> offset::STACK_PROFILE) as u8
276    }
277
278    /// Sets the stack profile value
279    #[must_use]
280    pub fn set_stack_profile(mut self, value: u8) -> Self {
281        self.0 = (self.0 & !mask::STACK_PROFILE)
282            | ((value as u16 & (mask::STACK_PROFILE >> offset::STACK_PROFILE))
283                << offset::STACK_PROFILE);
284        self
285    }
286
287    /// Protocol version
288    pub fn protocol_version(&self) -> u8 {
289        ((self.0 & mask::PROTOCOL_VERSION) >> offset::PROTOCOL_VERSION) as u8
290    }
291
292    /// Sets the protocol version
293    #[must_use]
294    pub fn set_protocol_version(mut self, value: u8) -> Self {
295        self.0 = (self.0 & !mask::PROTOCOL_VERSION)
296            | ((value as u16 & (mask::PROTOCOL_VERSION >> offset::PROTOCOL_VERSION))
297                << offset::PROTOCOL_VERSION);
298        self
299    }
300
301    /// Route capacity flag
302    pub fn router_capacity(&self) -> bool {
303        ((self.0 & mask::ROUTER_CAPACITY) >> offset::ROUTER_CAPACITY) != 0
304    }
305
306    /// Sets the route capacity flag
307    #[must_use]
308    pub fn set_router_capacity(mut self, value: bool) -> Self {
309        self.0 = (self.0 & !mask::ROUTER_CAPACITY) | (u16::from(value) << offset::ROUTER_CAPACITY);
310        self
311    }
312
313    /// Device depth
314    pub fn device_depth(&self) -> u8 {
315        ((self.0 & mask::DEVICE_DEPTH) >> offset::DEVICE_DEPTH) as u8
316    }
317
318    /// Sets the device depth
319    #[must_use]
320    pub fn set_device_depth(mut self, value: u8) -> Self {
321        self.0 = (self.0 & !mask::DEVICE_DEPTH)
322            | ((value as u16 & (mask::DEVICE_DEPTH >> offset::DEVICE_DEPTH))
323                << offset::DEVICE_DEPTH);
324        self
325    }
326
327    /// End device capacity flag
328    pub fn end_device_capacity(&self) -> bool {
329        ((self.0 & mask::END_DEVICE_CAPACITY) >> offset::END_DEVICE_CAPACITY) != 0
330    }
331
332    /// Sets the end device capacity flag
333    #[must_use]
334    pub fn set_end_device_capacity(mut self, value: bool) -> Self {
335        self.0 = (self.0 & !mask::END_DEVICE_CAPACITY)
336            | (u16::from(value) << offset::END_DEVICE_CAPACITY);
337        self
338    }
339}
340
341mod offset {
342    pub const STACK_PROFILE: u16 = 0;
343    pub const PROTOCOL_VERSION: u16 = 4;
344    pub const ROUTER_CAPACITY: u16 = 10;
345    pub const DEVICE_DEPTH: u16 = 11;
346    pub const END_DEVICE_CAPACITY: u16 = 15;
347}
348
349mod mask {
350    // stack_profile: bits 0-3 (4 bits)
351    pub const STACK_PROFILE: u16 = 0x0F;
352    // protocol_version: bits 4-7 (4 bits)
353    pub const PROTOCOL_VERSION: u16 = 0xF0;
354    // route_capacity: bit 10 (1 bit)
355    pub const ROUTER_CAPACITY: u16 = 0x400;
356    // device_depth: bits 11-14 (4 bits)
357    pub const DEVICE_DEPTH: u16 = 0x7800;
358    // end_device_capacity: bit 15 (1 bit)
359    pub const END_DEVICE_CAPACITY: u16 = 0x8000;
360}