Skip to main content

zigbee_mac/esp/
mod.rs

1use alloc::vec::Vec;
2
3use byte::BytesExt;
4use embassy_futures::select::Either;
5use embassy_futures::select::select;
6use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
7use embassy_time::Timer;
8use esp_radio::ieee802154::Config;
9use esp_radio::ieee802154::Frame;
10use esp_radio::ieee802154::Ieee802154;
11use esp_radio::ieee802154::ReceivedFrame;
12use ieee802154::mac::Address;
13use ieee802154::mac::FrameContent;
14use ieee802154::mac::FrameType;
15use ieee802154::mac::FrameVersion;
16use ieee802154::mac::Header;
17use ieee802154::mac::PanId;
18use ieee802154::mac::command::CapabilityInformation;
19use ieee802154::mac::command::Command;
20use ieee802154::mac::security::SecurityContext;
21
22use crate::esp::driver::Ieee802154Driver;
23use crate::esp::fair_mutex::FairMutex;
24use crate::esp::fair_mutex::FairMutexGuard;
25use crate::mlme::A_BASE_SUPER_FRAME_DURATION;
26use crate::mlme::A_MAX_FRAME_RETRIES;
27use crate::mlme::A_RESPONSE_WAIT_TIME;
28use crate::mlme::AssociationResponse;
29use crate::mlme::MAX_IEEE802154_CHANNELS;
30use crate::mlme::MacConfig;
31use crate::mlme::MacError;
32use crate::mlme::Mlme;
33use crate::mlme::PanDescriptor;
34use crate::mlme::PanDescriptorList;
35use crate::mlme::ScanResult;
36use crate::mlme::ScanType;
37
38mod driver;
39mod fair_mutex;
40
41// higher-layer retries of the whole association handshake; aMaxFrameRetries
42// ack-retransmission already covers a lost request or poll, this is a safety
43// net for a parent that accepts the request but is slow to respond
44const ASSOCIATE_REQUEST_RETRIES: u8 = 3;
45
46// number of times the association response is polled per request attempt
47const ASSOCIATE_POLL_RETRIES: u8 = 5;
48
49// number of poll rounds per steady-state MLME-POLL before reporting no data
50const POLL_DATA_RETRIES: u8 = 5;
51
52const RADIO_LOCK_TIMEOUT_MS: u64 = 5_000;
53
54/// `esp-radio` [`Mlme`] implementation
55///
56/// The radio is a single shared resource: the inner state is held behind an
57/// async mutex so the trait's `&self` methods can be driven concurrently from a
58/// receive task and a transmit path. The extended address is cached so it can
59/// be read without locking.
60pub struct EspMlme<'a> {
61    inner: FairMutex<CriticalSectionRawMutex, EspMlmeInner<'a>>,
62    ieee_address: u64,
63}
64
65impl<'a> EspMlme<'a> {
66    pub fn new(ieee802154: Ieee802154<'a>, config: Config) -> Self {
67        // seed the MAC seq number randomly (7.2.1.2): a fixed start re-uses low
68        // numbers each reboot, which a parent's duplicate filter drops as stale
69        let inner = EspMlmeInner {
70            driver: Ieee802154Driver::new(ieee802154, config),
71            seq_number: (esp_hal::rng::Rng::new().random() & 0xff) as u8,
72        };
73        let ieee_address = inner.driver.ieee_address().0;
74        Self {
75            inner: FairMutex::new(inner),
76            ieee_address,
77        }
78    }
79
80    /// The device's IEEE 802.15.4 extended (EUI-64) address.
81    pub fn ieee_address(&self) -> u64 {
82        self.ieee_address
83    }
84
85    async fn lock(
86        &self,
87    ) -> Result<FairMutexGuard<'_, CriticalSectionRawMutex, EspMlmeInner<'a>>, MacError> {
88        match select(
89            Timer::after_millis(RADIO_LOCK_TIMEOUT_MS),
90            self.inner.lock(),
91        )
92        .await
93        {
94            Either::First(_) => Err(MacError::RadioLockTimeout),
95            Either::Second(Ok(guard)) => Ok(guard),
96            Either::Second(Err(_)) => {
97                log::warn!("[MAC] radio lock queue full");
98                Err(MacError::RadioLockQueueFull)
99            }
100        }
101    }
102
103    async fn receive_data(&self, buf: &mut [u8]) -> Result<(usize, u8), MacError> {
104        loop {
105            // drain under a brief lock, then idle-wait lock-free so a
106            // concurrent transmit can acquire the radio while we
107            // wait for the next frame
108            {
109                let mut inner = self.lock().await?;
110                if let Some(received) = inner.try_drain(buf)? {
111                    return Ok(received);
112                }
113            }
114            driver::wait_rx_signal().await;
115        }
116    }
117}
118
119struct EspMlmeInner<'a> {
120    driver: Ieee802154Driver<'a>,
121    seq_number: u8,
122}
123
124impl EspMlmeInner<'_> {
125    fn sequence_number(&mut self) -> u8 {
126        self.seq_number = self.seq_number.wrapping_add(1);
127        self.seq_number
128    }
129
130    // retransmits up to aMaxFrameRetries times if unacknowledged (IEEE 802.15.4
131    // 7.5.6.4); returns MacError::NoAck if every attempt goes unacknowledged
132    async fn transmit_acked(&mut self, frame: &[u8]) -> Result<(), MacError> {
133        for _ in 0..=A_MAX_FRAME_RETRIES {
134            match self.driver.transmit(frame).await {
135                Ok(()) if self.driver.last_tx_acked() => return Ok(()),
136                Ok(()) => {}
137                // no ack / channel busy: retransmit (7.5.6.4)
138                Err(MacError::TxFailed) => {}
139                // a lost radio interrupt: retry rather than wedge the caller
140                Err(MacError::TxTimeout) => log::warn!("[MLME] tx-done timeout, retrying"),
141                Err(e) => return Err(e),
142            }
143        }
144        Err(MacError::NoAck)
145    }
146
147    fn flush(&mut self) {
148        while self.driver.poll_received().is_some() {}
149    }
150
151    fn poll_frame(&mut self) -> Option<Result<ReceivedFrame, MacError>> {
152        self.driver
153            .poll_received()
154            .map(|r| r.map_err(MacError::RadioError))
155    }
156
157    async fn next_frame(&mut self) -> Result<ReceivedFrame, MacError> {
158        loop {
159            // wait for a fully-received frame before draining: draining
160            // re-issues RxStart and aborts a frame still on the air
161            // (dropped a fast ~2ms indirect response). signal is
162            // level-held, so drain until empty then reset
163            self.driver.wait_rx_available().await;
164            if let Some(result) = self.poll_frame() {
165                return result;
166            }
167            self.driver.reset_rx_signal();
168        }
169    }
170
171    fn try_drain(&mut self, buf: &mut [u8]) -> Result<Option<(usize, u8)>, MacError> {
172        while let Some(result) = self.poll_frame() {
173            if let Some(received) = copy_data_payload(result?, buf) {
174                return Ok(Some(received));
175            }
176        }
177        Ok(None)
178    }
179
180    fn beacon_request_frame(&mut self) -> [u8; 10] {
181        let seq_number = self.sequence_number();
182        [0x3, 0x8, seq_number, 0xff, 0xff, 0xff, 0xff, 0x7, 0x0, 0x0]
183    }
184
185    async fn scan_channel_active(
186        &mut self,
187        channel: u8,
188        duration: u8,
189    ) -> Result<Option<PanDescriptorList>, MacError> {
190        self.flush();
191        self.driver.update_driver_config(|config| {
192            config.promiscuous = false;
193            config.channel = channel;
194        });
195        self.driver.start_receive();
196
197        let frame = self.beacon_request_frame();
198        if let Err(e) = self.driver.transmit(&frame).await {
199            log::error!("[MLME-SCAN]: error transmitting beacon: {e}");
200        }
201
202        log::debug!("[MLME-SCAN] sent beacon frame to channel {channel}, waiting for messages...");
203
204        let delay_us: u64 = calculate_scan_duration_max_us(duration).into();
205        log::debug!("[MLME-SCAN] waiting for response for {delay_us}us");
206
207        let mut pds = Vec::new();
208        let deadline = Timer::after_micros(delay_us);
209        let mut deadline = core::pin::pin!(deadline);
210
211        loop {
212            match embassy_futures::select::select(&mut deadline, self.next_frame()).await {
213                Either::First(_) => break,
214                Either::Second(Ok(frame)) => {
215                    if let Some(pd) = self.parse_beacon(frame) {
216                        pds.push(pd);
217                    }
218                }
219                Either::Second(Err(_)) => continue,
220            }
221        }
222
223        Ok(Some(pds))
224    }
225
226    fn parse_beacon(&self, received: ReceivedFrame) -> Option<PanDescriptor> {
227        match received {
228            ReceivedFrame {
229                frame:
230                    Frame {
231                        header:
232                            hdr @ Header {
233                                source: Some(source),
234                                ..
235                            },
236                        content: FrameContent::Beacon(beacon_content),
237                        payload,
238                        ..
239                    },
240                channel,
241                lqi,
242                ..
243            } => {
244                log::debug!("[MLME-SCAN] received beacon frame on channel {channel}");
245
246                let zigbee_beacon = match payload.read_with(&mut 0, ()) {
247                    Ok(zb) => zb,
248                    Err(e) => {
249                        log::warn!("[MLME-SCAN] failed to parse zigbee beacon: {e:?}");
250                        return None;
251                    }
252                };
253
254                Some(PanDescriptor {
255                    channel,
256                    coord_addr_mode: match source {
257                        Address::Short(_, _) => 0x2,
258                        Address::Extended(_, _) => 0x3,
259                    },
260                    coord_pan_id: source.pan_id().0.into(),
261                    coord_address: source,
262                    superframe_spec: beacon_content.superframe_spec,
263                    link_quality: lqi,
264                    security_use: hdr.has_security(),
265                    zigbee_beacon,
266                })
267            }
268            other => {
269                log::debug!("[MLME-SCAN] received non-beacon frame: {other:?}");
270                None
271            }
272        }
273    }
274
275    // MAC data request command frame (IEEE 802.15.4 7.3.4). returns the buffer
276    // and on-air length (written bytes + 2 for the FCS the radio appends); the
277    // source address mode varies (extended before a short address is assigned,
278    // short after) so the length is not fixed — caller must transmit exactly
279    // &buf[..len], not the whole fixed-size array
280    fn data_request_frame(&mut self, dest: Address) -> Result<([u8; 20], usize), MacError> {
281        let seq = self.sequence_number();
282        let source = match self.driver.short_address() {
283            Some(short) => Address::Short(dest.pan_id(), ieee802154::mac::ShortAddress(short)),
284            None => Address::Extended(dest.pan_id(), self.driver.ieee_address()),
285        };
286        let frame_header = Header {
287            frame_type: FrameType::MacCommand,
288            frame_pending: false,
289            ack_request: true,
290            pan_id_compress: true,
291            seq_no_suppress: false,
292            ie_present: false,
293            version: FrameVersion::Ieee802154_2003,
294            seq,
295            destination: Some(dest),
296            source: Some(source),
297            auxiliary_security_header: None,
298        };
299        let frame_content = FrameContent::Command(Command::DataRequest);
300
301        let mut buf = [0u8; 20];
302        let offset = &mut 0;
303        buf.write_with(
304            offset,
305            frame_header,
306            &Some(&mut SecurityContext::no_security()),
307        )?;
308        buf.write_with(offset, frame_content, ())?;
309
310        Ok((buf, *offset + 2))
311    }
312
313    // listens up to timeout_us for a MAC association response, draining and
314    // discarding any other frame. does not flush, so a response already
315    // queued (a parent that sent it directly) is not lost
316    async fn recv_association_response(
317        &mut self,
318        timeout_us: u64,
319    ) -> Result<Option<AssociationResponse>, MacError> {
320        // wait ~4ms before each drain (> a frame's ~0.8ms air time): draining
321        // mid-reception re-issues RxStart and aborts the frame. time-based, not
322        // signal-based: the RX signal may not fire even when the frame is
323        // queued. no logging in the loop — the UART critical section
324        // stalls the RX ISR
325        let timeout = Timer::after_micros(timeout_us);
326        let receive = async {
327            loop {
328                Timer::after_micros(4000).await;
329                while let Some(result) = self.poll_frame() {
330                    if let ReceivedFrame {
331                        frame:
332                            Frame {
333                                content:
334                                    FrameContent::Command(Command::AssociationResponse(
335                                        short_addr,
336                                        status,
337                                    )),
338                                ..
339                            },
340                        ..
341                    } = result?
342                    {
343                        return Ok::<_, MacError>(AssociationResponse {
344                            device_address: zigbee_types::IeeeAddress(self.driver.ieee_address().0),
345                            association_address: zigbee_types::ShortAddress(short_addr.0),
346                            status,
347                        });
348                    }
349                }
350            }
351        };
352        match embassy_futures::select::select(timeout, receive).await {
353            Either::First(_) => Ok(None),
354            Either::Second(Ok(r)) => Ok(Some(r)),
355            Either::Second(Err(e)) => Err(e),
356        }
357    }
358
359    // an indirect (poll) response is always a unicast, so ambient broadcasts
360    // never shadow it
361    fn take_unicast_data(&mut self, buf: &mut [u8]) -> Result<Option<(usize, u8)>, MacError> {
362        while let Some(result) = self.poll_frame() {
363            let received = result?;
364            if matches!(
365                received.frame.header.destination,
366                Some(Address::Short(_, ieee802154::mac::ShortAddress(d))) if d >= 0xfff8
367            ) {
368                continue;
369            }
370            if let Some(data) = copy_data_payload(received, buf) {
371                return Ok(Some(data));
372            }
373        }
374        Ok(None)
375    }
376
377    // shares recv_association_response's timing discipline: waits ~4ms before
378    // each drain (the RX signal may not fire even when a frame is queued) and
379    // never logs in the loop (the UART critical section stalls the RX ISR)
380    async fn recv_data_response(
381        &mut self,
382        timeout_us: u64,
383        buf: &mut [u8],
384    ) -> Result<Option<(usize, u8)>, MacError> {
385        let timeout = Timer::after_micros(timeout_us);
386        let receive = async {
387            loop {
388                Timer::after_micros(4000).await;
389                if let Some(data) = self.take_unicast_data(buf)? {
390                    return Ok::<_, MacError>(Some(data));
391                }
392            }
393        };
394        match embassy_futures::select::select(timeout, receive).await {
395            Either::First(_) => Ok(None),
396            Either::Second(result) => result,
397        }
398    }
399
400    fn association_request_frame(
401        &mut self,
402        dest: Address,
403        src: Option<Address>,
404        capabilities: CapabilityInformation,
405    ) -> Result<[u8; 21], MacError> {
406        let seq = self.sequence_number();
407        let frame_header = Header {
408            frame_type: FrameType::MacCommand,
409            frame_pending: false,
410            ack_request: true,
411            pan_id_compress: false,
412            seq_no_suppress: false,
413            ie_present: false,
414            version: FrameVersion::Ieee802154_2003,
415            seq,
416            destination: Some(dest),
417            source: src,
418            auxiliary_security_header: None,
419        };
420        let frame_content = FrameContent::Command(Command::AssociationRequest(capabilities));
421
422        let mut buf = [0u8; 21];
423        let offset = &mut 0;
424        buf.write_with(
425            offset,
426            frame_header,
427            &Some(&mut SecurityContext::no_security()),
428        )?;
429        buf.write_with(offset, frame_content, ())?;
430
431        Ok(buf)
432    }
433}
434
435// non-data frames (commands, beacons, acks) yield None
436fn copy_data_payload(received: ReceivedFrame, buf: &mut [u8]) -> Option<(usize, u8)> {
437    let ReceivedFrame {
438        frame:
439            Frame {
440                content: FrameContent::Data,
441                payload,
442                ..
443            },
444        lqi,
445        ..
446    } = received
447    else {
448        return None;
449    };
450    let len = payload.len().min(buf.len());
451    buf[..len].copy_from_slice(&payload[..len]);
452    Some((len, lqi))
453}
454
455fn calculate_scan_duration_max_us(duration: u8) -> u32 {
456    // we assume a symbol period of 16us (QPSK, 2.4Ghz)
457    16 * A_BASE_SUPER_FRAME_DURATION * (2 * (duration as u32) + 1)
458}
459
460impl EspMlmeInner<'_> {
461    async fn scan_network(
462        &mut self,
463        scan_type: ScanType,
464        channels: core::ops::Range<u8>,
465        duration: u8,
466    ) -> Result<ScanResult, MacError> {
467        if !matches!(scan_type, ScanType::Active) {
468            return Err(MacError::InvalidScanParams);
469        }
470
471        log::debug!("[MLME-SCAN] start scan");
472
473        let mut pan_descriptor = Vec::new();
474        for c in channels {
475            if (c as usize) >= MAX_IEEE802154_CHANNELS {
476                continue;
477            }
478
479            match self.scan_channel_active(c, duration).await {
480                Ok(Some(mut pd)) => {
481                    pan_descriptor.append(&mut pd);
482                }
483                Err(e) => {
484                    log::error!("[MLME-SCAN] error on channel {c}: {e}");
485                }
486                _ => (),
487            }
488        }
489
490        log::debug!("[MLME-SCAN] success");
491
492        Ok(ScanResult {
493            scan_type,
494            pan_descriptor,
495        })
496    }
497
498    async fn associate(
499        &mut self,
500        channel: u8,
501        dest: Address,
502        capabilities: CapabilityInformation,
503    ) -> Result<AssociationResponse, MacError> {
504        // filter on our extended address: the association response is an
505        // indirect tx addressed to it (7.5.6.4). auto_ack_rx must stay
506        // on to ack it — promiscuous suppresses the ack and floods the
507        // RX queue with broadcasts
508        self.driver.update_driver_config(|config| {
509            *config = Default::default();
510            config.channel = channel;
511            config.pan_id = Some(dest.pan_id().0);
512            config.auto_ack_tx = true;
513            config.auto_ack_rx = true;
514            config.promiscuous = false;
515        });
516        // arm RX after the config change: otherwise general RX is off until a
517        // later TX triggers rx-on-when-idle and the response is missed
518        self.driver.start_receive();
519
520        let ext_addr = self.driver.ieee_address();
521        // 7.3.1.1: source PAN is the broadcast PAN (0xffff), source is the ext
522        // addr
523        let src = Address::Extended(PanId::broadcast(), ext_addr);
524        let timeout_us = (A_RESPONSE_WAIT_TIME as u64) * 16;
525
526        // retry the full handshake (7.5.3.1): a lost/unacked request leaves the
527        // parent with nothing to buffer, so re-send each round. within a round
528        // listen first (rx-on-when-idle parent replies directly) then poll for
529        // indirect delivery. never flush — a direct response may already be
530        // queued
531        let mut response = None;
532        'association: for _ in 0..ASSOCIATE_REQUEST_RETRIES {
533            let frame = self.association_request_frame(dest, Some(src), capabilities)?;
534            match self.transmit_acked(&frame).await {
535                Ok(()) => {}
536                Err(MacError::NoAck) => {
537                    log::debug!("[MLME-ASSOCIATE] request not acked, retrying");
538                    continue;
539                }
540                Err(e) => return Err(e),
541            }
542            log::debug!(
543                "[MLME-ASSOCIATE] request acked, ack_pending={:?}",
544                self.driver.last_ack_frame_pending()
545            );
546
547            // catch a directly-sent response before spending a poll round-trip
548            if let Some(r) = self.recv_association_response(timeout_us).await? {
549                response = Some(r);
550                break 'association;
551            }
552
553            for _ in 0..ASSOCIATE_POLL_RETRIES {
554                let (data_req, len) = self.data_request_frame(dest)?;
555                match self.transmit_acked(&data_req[..len]).await {
556                    Ok(()) | Err(MacError::NoAck) => {}
557                    Err(e) => return Err(e),
558                }
559                // arm RX for the indirect response (~2-3ms after the poll ack);
560                // start_receive is a no-op if already receiving. no log here —
561                // the UART critical section stalls the RX ISR
562                // and a TI parent replies once
563                self.driver.start_receive();
564                if let Some(r) = self.recv_association_response(timeout_us).await? {
565                    response = Some(r);
566                    break 'association;
567                }
568            }
569        }
570        let response = response.ok_or(MacError::NoData)?;
571
572        log::debug!(
573            "[MLME-ASSOCIATE] success, short_addr={:?}",
574            response.association_address
575        );
576
577        // set the assigned short address so the hw filter accepts our unicasts
578        let short = response.association_address.0;
579        self.driver.update_driver_config(|config| {
580            config.promiscuous = false;
581            config.short_addr = Some(short);
582        });
583
584        Ok(response)
585    }
586
587    async fn poll_data(
588        &mut self,
589        coord_address: Address,
590        buf: &mut [u8],
591    ) -> Result<(usize, u8), MacError> {
592        // a response elicited by an earlier poll may have landed after its
593        // listen window closed; deliver it instead of flushing it away
594        if let Some((len, lqi)) = self.take_unicast_data(buf)? {
595            log::trace!("[MLME-POLL] rx buffered data len={len}");
596            return Ok((len, lqi));
597        }
598        let timeout_us = (A_RESPONSE_WAIT_TIME as u64) * 16;
599
600        // retry the poll handshake (7.5.6.3)
601        let mut acked = false;
602        for _ in 0..POLL_DATA_RETRIES {
603            let (data_req, len) = self.data_request_frame(coord_address)?;
604            match self.transmit_acked(&data_req[..len]).await {
605                // no ack after retries: the parent may be busy; keep listening
606                Ok(()) => acked = true,
607                Err(MacError::NoAck) => {}
608                Err(e) => return Err(e),
609            }
610            // arm RX for the indirect response (~2-3ms after the poll ack);
611            // start_receive is a no-op if already receiving
612            self.driver.start_receive();
613            if let Some((len, lqi)) = self.recv_data_response(timeout_us, buf).await? {
614                log::trace!("[MLME-POLL] rx data len={len}");
615                return Ok((len, lqi));
616            }
617        }
618        // an unacknowledged poll says nothing about buffered data: the parent
619        // itself is unreachable, which the NWK layer treats as a missed
620        // keepalive (3.6.10.3)
621        if acked {
622            log::trace!("[MLME-POLL] no data");
623            Err(MacError::NoData)
624        } else {
625            log::trace!("[MLME-POLL] no ack");
626            Err(MacError::NoAck)
627        }
628    }
629
630    async fn transmit_data(&mut self, dest: Address, payload: &[u8]) -> Result<(), MacError> {
631        let seq = self.sequence_number();
632
633        // NWK broadcast addresses (0xfff8-0xffff) map to the MAC broadcast
634        // address 0xffff, which is never acknowledged (IEEE 802.15.4 7.2.1.1.2)
635        let is_broadcast = matches!(dest, Address::Short(_, sa) if sa.0 >= 0xfff8);
636        let dest = if is_broadcast {
637            Address::Short(dest.pan_id(), ieee802154::mac::ShortAddress(0xffff))
638        } else {
639            dest
640        };
641
642        let source = Some(match self.driver.short_address() {
643            Some(short) => Address::Short(dest.pan_id(), ieee802154::mac::ShortAddress(short)),
644            None => Address::Extended(dest.pan_id(), self.driver.ieee_address()),
645        });
646
647        let frame_header = Header {
648            frame_type: FrameType::Data,
649            frame_pending: false,
650            ack_request: !is_broadcast,
651            pan_id_compress: source.is_some(),
652            seq_no_suppress: false,
653            ie_present: false,
654            version: FrameVersion::Ieee802154_2003,
655            seq,
656            destination: Some(dest),
657            source,
658            auxiliary_security_header: None,
659        };
660
661        let mut frame_buf = [0u8; 127];
662        let offset = &mut 0;
663        frame_buf.write_with(
664            offset,
665            frame_header,
666            &Some(&mut SecurityContext::no_security()),
667        )?;
668        let hdr_len = *offset;
669        let payload_len = payload.len().min(frame_buf.len() - hdr_len - 2);
670        frame_buf[hdr_len..hdr_len + payload_len].copy_from_slice(&payload[..payload_len]);
671        // 2-byte FCS placeholder (IEEE 802.15.4 7.2.1.8) — the hardware
672        // computes the actual CRC-16 over the frame and overwrites these
673        // bytes during transmission
674        let total_len = hdr_len + payload_len + 2;
675
676        // retransmit unicasts per 7.5.6.4: a single CCA-busy or lost ack must
677        // not drop a ZDO/APS response — the coordinator treats the silence as
678        // an interview failure
679        if is_broadcast {
680            self.driver.transmit(&frame_buf[..total_len]).await?;
681        } else {
682            self.transmit_acked(&frame_buf[..total_len]).await?;
683        }
684        log::trace!("[MLME] tx data, len={total_len}");
685
686        Ok(())
687    }
688}
689
690impl Mlme for EspMlme<'_> {
691    fn ieee_address(&self) -> zigbee_types::IeeeAddress {
692        zigbee_types::IeeeAddress(self.ieee_address)
693    }
694
695    async fn configure(&self, config: MacConfig) {
696        // returns `()`, so `Self::lock`'s error has nowhere to go — locks
697        // unbounded and skips on queue-full instead.
698        let Ok(mut inner) = self.inner.lock().await else {
699            log::error!("[MAC] radio lock queue full, skipping configure");
700            return;
701        };
702        inner.driver.update_driver_config(|driver| {
703            if let Some(channel) = config.channel {
704                driver.channel = channel;
705            }
706            if let Some(pan_id) = config.pan_id {
707                driver.pan_id = Some(pan_id.0);
708            }
709            if let Some(short_address) = config.short_address {
710                driver.short_addr = Some(short_address.0);
711            }
712            if let Some(promiscuous) = config.promiscuous {
713                driver.promiscuous = promiscuous;
714            }
715            if let Some(auto_ack_rx) = config.auto_ack_rx {
716                driver.auto_ack_rx = auto_ack_rx;
717            }
718            if let Some(auto_ack_tx) = config.auto_ack_tx {
719                driver.auto_ack_tx = auto_ack_tx;
720            }
721        });
722        // arm RX for the new configuration: otherwise reception stays off
723        // until the next transmit triggers rx-on-when-idle
724        inner.driver.start_receive();
725    }
726
727    async fn scan_network(
728        &self,
729        ty: ScanType,
730        channels: core::ops::Range<u8>,
731        duration: u8,
732    ) -> Result<ScanResult, MacError> {
733        self.lock()
734            .await?
735            .scan_network(ty, channels, duration)
736            .await
737    }
738
739    async fn associate(
740        &self,
741        channel: u8,
742        dest: Address,
743        capabilities: CapabilityInformation,
744    ) -> Result<AssociationResponse, MacError> {
745        self.lock()
746            .await?
747            .associate(channel, dest, capabilities)
748            .await
749    }
750
751    async fn poll_data(
752        &self,
753        coord_address: Address,
754        buf: &mut [u8],
755    ) -> Result<(usize, u8), MacError> {
756        self.lock().await?.poll_data(coord_address, buf).await
757    }
758
759    async fn receive(&self, buf: &mut [u8]) -> Result<(usize, u8), MacError> {
760        match self.receive_data(buf).await {
761            Ok((len, lqi)) => {
762                log::trace!("[MLME] rx data, len={len}");
763                Ok((len, lqi))
764            }
765            Err(e) => Err(e),
766        }
767    }
768
769    async fn transmit_data(&self, dest: Address, payload: &[u8]) -> Result<(), MacError> {
770        self.lock().await?.transmit_data(dest, payload).await
771    }
772
773    fn random_u32(&self) -> u32 {
774        esp_hal::rng::Rng::new().random()
775    }
776}