Skip to main content

zigbee_core/nwk/nlme/
mod.rs

1//! Network Management Entity
2//!
3//! The NLME shall provide a management service to allow an application to
4//! interact with the stack.
5//!
6//! it provides:
7//! * configuring a new device
8//! * starting a network
9//! * joining, rejoining and leaving a network
10//! * addressing
11//! * neighbor discovery
12//! * route discovery
13//! * reception control
14//! * routing
15
16use core::slice;
17use core::sync::atomic::AtomicU8;
18use core::sync::atomic::AtomicU32;
19use core::sync::atomic::Ordering;
20
21use byte::BytesExt;
22use byte::TryRead;
23use management::NlmeEdScanConfirm;
24use management::NlmeEdScanRequest;
25use management::NlmeJoinConfirm;
26use management::NlmeJoinRequest;
27use management::NlmeJoinStatus;
28use management::NlmeLeaveConfirm;
29use management::NlmeLeaveIndication;
30use management::NlmeLeaveRequest;
31use management::NlmeLeaveStatus;
32use management::NlmeNetworkDiscoveryConfirm;
33use management::NlmeNetworkFormationConfirm;
34use management::NlmeNetworkFormationRequest;
35use management::NlmeNwkStatusIndication;
36use management::NlmePermitJoiningConfirm;
37use management::NlmePermitJoiningRequest;
38use management::NlmeStartRouterConfirm;
39use management::NlmeStartRouterRequest;
40use management::RejoinNetwork;
41use thiserror::Error;
42use zigbee_mac::Address;
43use zigbee_mac::AssociationStatus;
44use zigbee_mac::MacShortAddress;
45use zigbee_mac::PanId;
46use zigbee_mac::mlme::MacConfig;
47use zigbee_mac::mlme::MacError;
48use zigbee_mac::mlme::Mlme;
49use zigbee_mac::mlme::ScanType;
50use zigbee_types::IeeeAddress;
51use zigbee_types::ShortAddress;
52use zigbee_types::StorageVec;
53use zigbee_types::sync::Signal;
54use zigbee_types::sync::with_timeout;
55
56use crate::nwk::frame::CommandFrame as NwkCommandFrame;
57use crate::nwk::frame::DataFrame as NwkDataFrame;
58use crate::nwk::frame::Frame as NwkFrame;
59use crate::nwk::frame::command::Command;
60use crate::nwk::frame::command::end_device_timeout_request;
61use crate::nwk::frame::command::end_device_timeout_request::EndDeviceTimeoutRequest;
62use crate::nwk::frame::command::end_device_timeout_response::EndDeviceTimeoutResponse;
63use crate::nwk::frame::command::leave::CommandOptions as LeaveCommandOptions;
64use crate::nwk::frame::command::leave::Leave;
65use crate::nwk::frame::command::network_status::NetworkStatusCode;
66use crate::nwk::frame::command::rejoin_request;
67use crate::nwk::frame::command::rejoin_request::RejoinRequest;
68use crate::nwk::frame::command::rejoin_response::RejoinResponse;
69use crate::nwk::frame::frame_control::DiscoverRoute;
70use crate::nwk::frame::frame_control::FrameControl as NwkFrameControl;
71use crate::nwk::frame::frame_control::FrameType as NwkFrameType;
72use crate::nwk::frame::header::Header as NwkHeader;
73use crate::nwk::nib;
74use crate::nwk::nib::CapabilityInformation;
75use crate::nwk::nib::DeviceType;
76use crate::nwk::nib::MAX_PARENT_LINK_COST;
77use crate::nwk::nib::NWK_BROADCAST_ADDRESS_MIN;
78use crate::nwk::nib::NWK_BROADCAST_ALL;
79use crate::nwk::nib::NWK_COORDINATOR_ADDRESS;
80use crate::nwk::nib::NWK_UNASSIGNED_ADDRESS;
81use crate::nwk::nib::Nib;
82use crate::nwk::nib::NwkNeighbor;
83use crate::nwk::nib::link_cost_from_lqi;
84use crate::nwk::nib::relationship;
85use crate::security::SecurityContext;
86
87/// Network management entity
88pub mod management;
89
90// sentinel for `pending_timeout_request`: no request outstanding
91const NO_PENDING_TIMEOUT: u8 = 0xff;
92
93// poll attempts while waiting for the parent to deliver a buffered Rejoin
94// Response (3.4.7.1: indirect transmission for a sleepy child)
95const REJOIN_RESPONSE_POLL_RETRIES: u8 = 20;
96
97// poll attempts covering macResponseWaitTime while waiting for the keepalive's
98// End Device Timeout Response (3.6.10.3)
99const TIMEOUT_RESPONSE_POLL_RETRIES: u8 = 3;
100
101// `parent_timeout_remaining_ms` value meaning "not tracking": either no
102// timeout was negotiated or it already expired
103const PARENT_TIMEOUT_INACTIVE: u32 = 0;
104
105// consecutive transmit failures classifying the link to the parent as failed
106// (3.6.3.7 leaves the counting scheme to the implementer)
107const MAX_PARENT_TRANSMIT_FAILURES: u8 = 3;
108
109#[derive(Debug, Error)]
110pub enum NetworkError {
111    #[error("mac error: {0}")]
112    MacError(#[from] MacError),
113    #[error("not joined to a network")]
114    NotJoined,
115    #[error("no transport key received from coordinator")]
116    NoTransportKey,
117    #[error("frame parse error")]
118    ParseError,
119    #[error("invalid frame")]
120    InvalidFrame,
121    #[error("frame does not fit a single APS frame")]
122    FrameTooLong,
123    #[error("no APS acknowledgement received")]
124    AckTimeout,
125    #[error("parent link failure")]
126    ParentLinkFailure,
127    #[error("security error: {0}")]
128    SecurityError(#[from] crate::security::SecurityError),
129}
130
131impl From<byte::Error> for NetworkError {
132    fn from(_: byte::Error) -> Self {
133        Self::ParseError
134    }
135}
136
137/// Network Layer Management Entity (3.2.2).
138///
139/// Provides the management service access point (NLME-SAP) that allows
140/// the next higher layer to interact with the NWK layer: network
141/// discovery, formation, joining, rejoining, data transmission, etc.
142pub struct Nlme<M> {
143    mac: M,
144    nwk_seq: AtomicU8,
145    // requested timeout enum awaiting a response (3.6.10.2); 0xff = none
146    pending_timeout_request: AtomicU8,
147    // remaining time before the parent is assumed to have aged this device out
148    // (3.6.10.6); the parent's neighbor entry is the only one an end device
149    // tracks, and the counter is volatile, so it lives here rather than in the
150    // flash-backed neighbor table
151    parent_timeout_remaining_ms: AtomicU32,
152    // Rejoin Response (3.4.7) handed from the receive path to the rejoin
153    // procedure waiting for it
154    rejoin_response: Signal<RejoinResponse>,
155    // End Device Timeout Response (3.4.12) handed from the receive path to the
156    // keepalive waiting for it
157    timeout_response: Signal<EndDeviceTimeoutResponse>,
158    // NLME-LEAVE.indication (3.2.2.19) raised by the receive path for the
159    // higher layer, which decides whether to re-commission or rejoin
160    leave_indication: Signal<NlmeLeaveIndication>,
161    // NLME-NWK-STATUS.indication (3.2.2.32) reporting a network failure to the
162    // higher layer
163    nwk_status_indication: Signal<NlmeNwkStatusIndication>,
164}
165
166/// Keepalive method negotiated with the router parent (3.6.10.3).
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum KeepaliveMethod {
169    /// The parent tracks a MAC data poll as a keepalive
170    /// (`nwkParentInformation` bit 0).
171    MacDataPoll,
172    /// The parent expects an End Device Timeout Request
173    /// (`nwkParentInformation` bit 1).
174    TimeoutRequest,
175    /// No timeout was negotiated: the parent ages this device out on its own
176    /// terms and no keepalive is sent.
177    None,
178}
179
180impl<M> Nlme<M>
181where
182    M: Mlme,
183{
184    /// Creates a new instance owning the given MAC.
185    ///
186    /// Mirrors the MAC's hardware-provisioned IEEE address into
187    /// `nwkIeeeAddress`, so it is valid even when resuming on a network
188    /// without re-associating. The information bases must be initialized
189    /// first.
190    pub fn new(mac: M) -> Self {
191        nib::get_ref().update_ieee_address(|value| *value = mac.ieee_address());
192        let nwk_seq = AtomicU8::new(mac.random_u8());
193        Self {
194            mac,
195            nwk_seq,
196            pending_timeout_request: AtomicU8::new(NO_PENDING_TIMEOUT),
197            parent_timeout_remaining_ms: AtomicU32::new(PARENT_TIMEOUT_INACTIVE),
198            rejoin_response: Signal::new(),
199            timeout_response: Signal::new(),
200            leave_indication: Signal::new(),
201            nwk_status_indication: Signal::new(),
202        }
203    }
204
205    /// Returns a random byte from the MAC layer, used for seeding sequence
206    /// counters without pulling chip-specific RNG into the core crate.
207    pub fn random_u8(&self) -> u8 {
208        self.mac.random_u8()
209    }
210
211    /// 3.2.2.19 - take a pending NLME-LEAVE.indication, if any.
212    ///
213    /// Reports that this device was removed from the network (device address
214    /// `None`), or that a neighbor left it. The indication stays pending until
215    /// taken.
216    pub fn take_leave_indication(&self) -> Option<NlmeLeaveIndication> {
217        self.leave_indication.try_take()
218    }
219
220    /// 3.2.2.19 - wait for the next NLME-LEAVE.indication.
221    pub async fn wait_leave_indication(&self) -> NlmeLeaveIndication {
222        self.leave_indication.wait().await
223    }
224
225    /// 3.2.2.32 - take a pending NLME-NWK-STATUS.indication, if any.
226    ///
227    /// Reports a network failure to the higher layer; the indication stays
228    /// pending until taken. A status of
229    /// [`NetworkStatusCode::ParentLinkFailure`] means the link to the parent
230    /// is gone and the device should rejoin (3.6.10.10).
231    pub fn take_nwk_status_indication(&self) -> Option<NlmeNwkStatusIndication> {
232        self.nwk_status_indication.try_take()
233    }
234
235    /// 3.2.2.32 - wait for the next NLME-NWK-STATUS.indication.
236    pub async fn wait_nwk_status_indication(&self) -> NlmeNwkStatusIndication {
237        self.nwk_status_indication.wait().await
238    }
239
240    fn next_nwk_seq(&self) -> u8 {
241        self.nwk_seq.fetch_add(1, Ordering::Relaxed).wrapping_add(1)
242    }
243
244    /// Build a NWK data frame into `buf`, returning the total frame length.
245    ///
246    /// When `secure` is true the frame is encrypted with the active
247    /// network key.
248    fn build_nwk_data_frame(
249        &self,
250        destination: ShortAddress,
251        secure: bool,
252        payload: &[u8],
253        buf: &mut [u8],
254    ) -> Result<usize, NetworkError> {
255        let nib = self.nib();
256        let frame_control = NwkFrameControl(0)
257            .set_frame_type(NwkFrameType::Data)
258            .set_protocol_version(2)
259            .set_discover_route(DiscoverRoute::Suppress)
260            .set_security_flag(secure);
261
262        let seq = self.next_nwk_seq();
263        let header = NwkHeader {
264            frame_control,
265            destination,
266            source: ShortAddress(*nib.network_address()),
267            radius: 30,
268            sequence_number: seq,
269            destination_ieee: None,
270            source_ieee: None,
271            multicast_control: None,
272            source_route_subframe: None,
273        };
274
275        if secure {
276            let nwk_frame = NwkFrame::Data(NwkDataFrame { header, payload });
277            let cx = SecurityContext::get();
278            let len = cx.encrypt_nwk_frame_in_place(nwk_frame, buf)?;
279            Ok(len)
280        } else {
281            let offset = &mut 0;
282            buf.write_with(offset, header, ())?;
283            let hdr_len = *offset;
284            let payload_len = payload.len().min(buf.len() - hdr_len);
285            buf[hdr_len..hdr_len + payload_len].copy_from_slice(&payload[..payload_len]);
286            Ok(hdr_len + payload_len)
287        }
288    }
289
290    /// Build a NWK command frame into `buf`, returning the total frame length
291    /// (3.3.2).
292    ///
293    /// When `secure` is false the frame is sent in the clear, as required for
294    /// a Trust Center rejoin (4.6.3.3.2).
295    fn build_nwk_command_frame(
296        &self,
297        destination: ShortAddress,
298        command: Command<'_>,
299        secure: bool,
300        buf: &mut [u8],
301    ) -> Result<usize, NetworkError> {
302        let nib = self.nib();
303        // the destination IEEE address is carried whenever it is known
304        // (3.4.6.2, 3.4.11.2)
305        let destination_ieee = self.neighbor_ieee_address(destination);
306        let frame_control = NwkFrameControl(0)
307            .set_frame_type(NwkFrameType::NwkCommand)
308            .set_protocol_version(2)
309            .set_discover_route(DiscoverRoute::Suppress)
310            .set_security_flag(secure)
311            .set_destination_ieee_flag(destination_ieee.is_some())
312            .set_source_ieee_flag(true);
313
314        let header = NwkHeader {
315            frame_control,
316            destination,
317            source: ShortAddress(*nib.network_address()),
318            radius: 1,
319            sequence_number: self.next_nwk_seq(),
320            destination_ieee,
321            source_ieee: Some(*nib.ieee_address()),
322            multicast_control: None,
323            source_route_subframe: None,
324        };
325
326        if !secure {
327            let offset = &mut 0;
328            buf.write_with(offset, header, ())?;
329            buf.write_with(offset, command, ())?;
330            return Ok(*offset);
331        }
332
333        let nwk_frame = NwkFrame::NwkCommand(NwkCommandFrame { header, command });
334        let cx = SecurityContext::get();
335        let len = cx.encrypt_nwk_frame_in_place(nwk_frame, buf)?;
336        Ok(len)
337    }
338
339    /// Build a failed NLME-JOIN.confirm (3.2.2.13.3).
340    fn join_failure(status: NlmeJoinStatus) -> NlmeJoinConfirm {
341        NlmeJoinConfirm {
342            status,
343            network_address: ShortAddress(0xffff),
344            extended_pan_id: IeeeAddress(0u64),
345            channel: 0,
346            enhanced_beacon_type: false,
347            mac_interface_index: 0u8,
348        }
349    }
350
351    /// Send an End Device Timeout Request to the parent (3.6.10.2).
352    ///
353    /// Requests the timeout enumeration from `nwkEndDeviceTimeoutDefault`.
354    /// The parent's response is consumed by the receive path and updates
355    /// `nwkParentInformation` and the negotiated timeout in the NIB; no
356    /// response means a legacy parent and leaves the NIB untouched.
357    pub async fn send_end_device_timeout_request(&self) -> Result<(), NetworkError> {
358        let requested_timeout = *self.nib().end_device_timeout_default();
359        let command = Command::EndDeviceTimeoutRequest(EndDeviceTimeoutRequest {
360            requested_timeout,
361            // all bits reserved, must be 0 (3.4.11.3.2)
362            end_device_configuration: 0x00,
363        });
364
365        let mut buf = [0u8; 256];
366        let len =
367            self.build_nwk_command_frame(self.parent_short_address()?, command, true, &mut buf)?;
368        self.pending_timeout_request
369            .store(requested_timeout, Ordering::Relaxed);
370        self.mac
371            .transmit_data(self.parent_address()?, &buf[..len])
372            .await?;
373        Ok(())
374    }
375
376    /// Program the MAC from the restored information base and report whether
377    /// this device is resuming on a network (3.6.8).
378    ///
379    /// A device that was reset while joined keeps its addresses in the NIB but
380    /// the radio comes up unconfigured: the PAN id, short address, channel and
381    /// the filtering that goes with membership have to be applied before it
382    /// can poll its parent again. A device that is not on a network only gets
383    /// the channel it will look for one on, leaving the rest to the join.
384    pub async fn resume(&self, channel: u8) -> bool {
385        let nib = self.nib();
386        let network_address = *nib.network_address();
387        let on_a_network = network_address != NWK_UNASSIGNED_ADDRESS;
388
389        let config = if on_a_network {
390            MacConfig::joined(channel, PanId(*nib.panid()), ShortAddress(network_address))
391        } else {
392            MacConfig::channel(channel)
393        };
394        self.mac.configure(config).await;
395
396        on_a_network
397    }
398
399    /// Negotiate the end-device timeout with the parent (3.6.10.2).
400    ///
401    /// Sends the request and waits for the parent's response, which stores the
402    /// negotiated timeout and the parent's keepalive methods in the NIB.
403    /// Returns whether a timeout was negotiated: a legacy parent never answers
404    /// and keeps its own default, leaving this device without a keepalive
405    /// method.
406    pub async fn negotiate_end_device_timeout(&self) -> Result<bool, NetworkError> {
407        // arm before transmitting: the response may be delivered by a
408        // concurrently running receive loop
409        self.timeout_response.reset();
410        self.send_end_device_timeout_request().await?;
411
412        let response = with_timeout(
413            self.timeout_response.wait(),
414            self.poll_until_timeout_response(TIMEOUT_RESPONSE_POLL_RETRIES),
415        )
416        .await
417        .or_else(|| self.timeout_response.try_take());
418
419        match response {
420            Some(response) if response.status == EndDeviceTimeoutResponse::STATUS_SUCCESS => {
421                Ok(true)
422            }
423            Some(response) => {
424                log::warn!(
425                    "[NWK] end-device timeout rejected (status={:#04x})",
426                    response.status
427                );
428                Ok(false)
429            }
430            None => {
431                log::warn!("[NWK] no end-device timeout response, assuming legacy parent");
432                Ok(false)
433            }
434        }
435    }
436
437    /// Recommended maximum poll interval in milliseconds, allowing three
438    /// keepalives per negotiated timeout period (3.6.10.3).
439    ///
440    /// Returns `None` when no timeout was negotiated or the parent does not
441    /// support the MAC data poll keepalive method.
442    pub fn negotiated_poll_interval_ms(&self) -> Option<u32> {
443        if self.keepalive_method() != KeepaliveMethod::MacDataPoll {
444            return None;
445        }
446        self.keepalive_interval_ms()
447    }
448
449    /// Keepalive method the parent expects (3.6.10.3).
450    ///
451    /// Bit 0 of `nwkParentInformation` takes precedence over bit 1; without a
452    /// negotiated timeout no keepalive is sent.
453    pub fn keepalive_method(&self) -> KeepaliveMethod {
454        let nib = self.nib();
455        if end_device_timeout_request::timeout_seconds(*nib.end_device_timeout()).is_none() {
456            return KeepaliveMethod::None;
457        }
458        let parent_information = *nib.parent_information();
459        if parent_information & EndDeviceTimeoutResponse::MAC_DATA_POLL_KEEPALIVE != 0 {
460            KeepaliveMethod::MacDataPoll
461        } else if parent_information & EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE != 0 {
462            KeepaliveMethod::TimeoutRequest
463        } else {
464            KeepaliveMethod::None
465        }
466    }
467
468    /// Recommended interval between keepalives in milliseconds: three
469    /// keepalives per negotiated Device Timeout period (3.6.10.3).
470    ///
471    /// Returns `None` when no timeout was negotiated with the parent.
472    pub fn keepalive_interval_ms(&self) -> Option<u32> {
473        Some(self.negotiated_timeout_ms()? / 3)
474    }
475
476    // negotiated Device Timeout period in milliseconds (Table 3.52)
477    fn negotiated_timeout_ms(&self) -> Option<u32> {
478        let seconds =
479            end_device_timeout_request::timeout_seconds(*self.nib().end_device_timeout())?;
480        Some(seconds.saturating_mul(1000))
481    }
482
483    /// Send one keepalive to the parent (3.6.10.3).
484    ///
485    /// The method follows `nwkParentInformation`: a MAC data poll, or an End
486    /// Device Timeout Request whose response is awaited. A failed timeout
487    /// request raises an NLME-NWK-STATUS.indication with
488    /// [`NetworkStatusCode::ParentLinkFailure`] and returns
489    /// [`NetworkError::ParentLinkFailure`]; a successful keepalive restarts
490    /// the local timeout (3.6.10.6).
491    pub async fn send_keepalive(&self) -> Result<(), NetworkError> {
492        match self.keepalive_method() {
493            KeepaliveMethod::MacDataPoll => self.mac_data_poll_keepalive().await,
494            KeepaliveMethod::TimeoutRequest => self.timeout_request_keepalive().await,
495            KeepaliveMethod::None => Ok(()),
496        }
497    }
498
499    // 3.6.10.3: a data poll refreshes the parent's timeout on its own; any
500    // frame it retrieves belongs to the receive loop, which is not running
501    // when the higher layer drives the keepalive itself
502    async fn mac_data_poll_keepalive(&self) -> Result<(), NetworkError> {
503        let mut buf = [0u8; 256];
504        match self.poll_nwk_frame(&mut buf).await {
505            Ok(Some(_)) => log::debug!("[NWK] keepalive poll dropped a data frame"),
506            Ok(None) => (),
507            Err(e) => return Err(e),
508        }
509        self.refresh_parent_timeout();
510        Ok(())
511    }
512
513    // 3.6.10.3: unicast an End Device Timeout Request and wait
514    // macResponseWaitTime for the response; anything else is a parent link
515    // failure
516    async fn timeout_request_keepalive(&self) -> Result<(), NetworkError> {
517        // arm before transmitting: the response may be delivered by a
518        // concurrently running receive loop
519        self.timeout_response.reset();
520        if let Err(e) = self.send_end_device_timeout_request().await {
521            log::warn!("[NWK] keepalive transmission failed ({e:?})");
522            return Err(self.parent_link_failure());
523        }
524
525        let response = with_timeout(
526            self.timeout_response.wait(),
527            self.poll_until_timeout_response(TIMEOUT_RESPONSE_POLL_RETRIES),
528        )
529        .await
530        // the response may have arrived in the very poll that ended the polling
531        .or_else(|| self.timeout_response.try_take());
532
533        match response {
534            Some(response) if response.status == EndDeviceTimeoutResponse::STATUS_SUCCESS => {
535                self.refresh_parent_timeout();
536                Ok(())
537            }
538            Some(response) => {
539                log::warn!("[NWK] keepalive rejected (status={:#04x})", response.status);
540                Err(self.parent_link_failure())
541            }
542            None => {
543                log::warn!("[NWK] no keepalive response from parent");
544                Err(self.parent_link_failure())
545            }
546        }
547    }
548
549    // poll the parent until the End Device Timeout Response has been processed
550    // or `retries` polls went unanswered; a sleepy child only receives the
551    // response by polling for it
552    async fn poll_until_timeout_response(&self, retries: u8) {
553        let mut buf = [0u8; 128];
554        for _ in 0..retries {
555            if self.timeout_response.is_signaled() {
556                return;
557            }
558            match self.poll_parent(&mut buf).await {
559                Ok(Some(len)) => match self.process_received_nwk_frame(&mut buf[..len]).await {
560                    Ok(Some(_)) => log::debug!("[NWK] keepalive poll dropped a data frame"),
561                    Ok(None) => (),
562                    Err(e) => log::debug!("[NWK] keepalive frame not processed: {e:?}"),
563                },
564                Ok(None) => (),
565                Err(e) => log::debug!("[NWK] keepalive poll failed: {e:?}"),
566            }
567        }
568    }
569
570    /// Restart the local end-device timeout after evidence that the parent
571    /// still holds this device in its neighbor table (3.6.10.6).
572    pub fn refresh_parent_timeout(&self) {
573        let remaining = self
574            .negotiated_timeout_ms()
575            .unwrap_or(PARENT_TIMEOUT_INACTIVE);
576        self.parent_timeout_remaining_ms
577            .store(remaining, Ordering::Relaxed);
578    }
579
580    /// Advance the local end-device timeout by `elapsed_ms` (3.6.10.6).
581    ///
582    /// Returns `true` once the timeout expires: the parent is assumed to have
583    /// aged this device out, which is reported to the higher layer as an
584    /// NLME-NWK-STATUS.indication with
585    /// [`NetworkStatusCode::ParentLinkFailure`]. Tracking then stops until the
586    /// next successful keepalive.
587    pub fn tick_parent_timeout(&self, elapsed_ms: u32) -> bool {
588        let remaining = self.parent_timeout_remaining_ms.load(Ordering::Relaxed);
589        if remaining == PARENT_TIMEOUT_INACTIVE {
590            return false;
591        }
592        let remaining = remaining.saturating_sub(elapsed_ms.max(1));
593        self.parent_timeout_remaining_ms
594            .store(remaining, Ordering::Relaxed);
595        if remaining != PARENT_TIMEOUT_INACTIVE {
596            return false;
597        }
598        log::warn!("[NWK] end-device timeout elapsed, assuming aged out by parent");
599        self.parent_link_failure();
600        true
601    }
602
603    /// Transmit a built frame through the parent, tracking the link
604    /// (3.6.3.7).
605    ///
606    /// Every neighbor with an outgoing link carries a failure counter; once
607    /// the link to the parent counts as failed, the higher layer is informed
608    /// with an NLME-NWK-STATUS.indication of `ParentLinkFailure` (3.6.3.7.1)
609    /// and [`NetworkError::ParentLinkFailure`] is returned.
610    async fn transmit_via_parent(&self, buf: &[u8]) -> Result<(), NetworkError> {
611        let parent = self.parent_address()?;
612        let Err(e) = self.mac.transmit_data(parent, buf).await else {
613            // an acknowledged frame proves the parent still holds this device
614            // in its neighbor table (3.6.10.6)
615            self.update_parent_neighbor(|neighbor| neighbor.transmit_failure = 0);
616            self.refresh_parent_timeout();
617            return Ok(());
618        };
619
620        let mut failures = 0;
621        self.update_parent_neighbor(|neighbor| {
622            neighbor.transmit_failure = neighbor.transmit_failure.saturating_add(1);
623            failures = neighbor.transmit_failure;
624        });
625        log::debug!("[NWK] transmission via parent failed ({e:?}), failures={failures}");
626        if failures < MAX_PARENT_TRANSMIT_FAILURES {
627            return Err(e.into());
628        }
629
630        self.update_parent_neighbor(|neighbor| neighbor.transmit_failure = 0);
631        Err(self.parent_link_failure())
632    }
633
634    // apply `update` to the parent's neighbor table entry, if there is one
635    fn update_parent_neighbor(&self, update: impl FnOnce(&mut NwkNeighbor)) {
636        self.nib().update_neighbor_table(|table| {
637            if let Some(parent) = table
638                .iter_mut()
639                .find(|n| n.relationship == relationship::PARENT)
640            {
641                update(parent);
642            }
643        });
644    }
645
646    // raise NLME-NWK-STATUS.indication 0x09 (3.6.3.7.1, 3.6.10.3, 3.2.2.32)
647    fn parent_link_failure(&self) -> NetworkError {
648        let network_address = self
649            .parent_short_address()
650            .unwrap_or(ShortAddress(NWK_UNASSIGNED_ADDRESS));
651        self.nwk_status_indication.signal(NlmeNwkStatusIndication {
652            status: NetworkStatusCode::ParentLinkFailure,
653            network_address,
654        });
655        NetworkError::ParentLinkFailure
656    }
657
658    /// Returns a reference to the global NIB singleton.
659    pub fn nib(&self) -> &'static Nib {
660        nib::get_ref()
661    }
662
663    /// Select parent candidates for an association join (3.6.1.4.1.1).
664    fn select_parent_candidates(
665        &self,
666        extended_pan_id: IeeeAddress,
667        join_as_router: bool,
668    ) -> heapless::Vec<usize, 16> {
669        self.select_candidates(extended_pan_id, join_as_router, true)
670    }
671
672    /// Select parent candidates for a rejoin (3.6.1.4.2).
673    ///
674    /// Same selection as for a join except that the network need not permit
675    /// joining: a rejoin reconnects a device the network already knows.
676    fn select_rejoin_candidates(
677        &self,
678        extended_pan_id: IeeeAddress,
679        join_as_router: bool,
680    ) -> heapless::Vec<usize, 16> {
681        self.select_candidates(extended_pan_id, join_as_router, false)
682    }
683
684    fn select_candidates(
685        &self,
686        extended_pan_id: IeeeAddress,
687        join_as_router: bool,
688        require_permit_joining: bool,
689    ) -> heapless::Vec<usize, 16> {
690        let table = self.nib().neighbor_table();
691        log::debug!("[NWK-JOIN] neighbor table: {table:#?}");
692        let stack_profile = self.nib().stack_profile();
693        let permits = |n: &NwkNeighbor| !require_permit_joining || n.permit_joining;
694
695        // 3.6.1.4.1.1: the update id wraps back to zero, so it is treated as
696        // a modular counter - an id `b` is newer than `a` when the signed
697        // difference `(b - a) as i8` is positive
698        let best_update_id = table
699            .iter()
700            .filter(|n| {
701                n.extended_pan_id == extended_pan_id && permits(n) && n.potential_parent == 1
702            })
703            .map(|n| n.update_id)
704            // positive signed difference means id is newer
705            .reduce(|best, id| {
706                if id.wrapping_sub(best).cast_signed() > 0 {
707                    id
708                } else {
709                    best
710                }
711            });
712
713        let mut candidates: heapless::Vec<usize, 16> = best_update_id
714            .into_iter()
715            .flat_map(|best_update_id| {
716                table.iter().enumerate().filter(move |(_, n)| {
717                    // correct network, accepting joins of the right type, low
718                    // enough link cost, a potential parent, and on the most
719                    // recent update id
720                    n.extended_pan_id == extended_pan_id
721                        && permits(n)
722                        && if join_as_router {
723                            n.router_capacity
724                        } else {
725                            n.end_device_capacity
726                        }
727                        && link_cost_from_lqi(n.lqi) <= MAX_PARENT_LINK_COST
728                        && n.potential_parent == 1
729                        && n.update_id == best_update_id
730                })
731            })
732            .map(|(i, _)| i)
733            .collect();
734
735        // finding no parent is otherwise indistinguishable from a dead radio:
736        // report what the scan saw next to what was asked for. a mismatched
737        // extended PAN id is by far the most common cause
738        if candidates.is_empty() {
739            if table.is_empty() {
740                log::warn!("[NWK-JOIN] no suitable parent: the scan found no networks at all");
741            } else {
742                log::warn!(
743                    "[NWK-JOIN] no suitable parent for EPID {:#018x} (joining as {}); the scan saw {} network(s):",
744                    extended_pan_id.0,
745                    if join_as_router {
746                        "router"
747                    } else {
748                        "end device"
749                    },
750                    table.len()
751                );
752                for n in table.iter() {
753                    log::warn!(
754                        "[NWK-JOIN]   EPID {:#018x} ch {} permit_joining={} router_capacity={} end_device_capacity={} lqi={} link_cost={} potential_parent={} update_id={}",
755                        n.extended_pan_id.0,
756                        n.logical_channel,
757                        n.permit_joining,
758                        n.router_capacity,
759                        n.end_device_capacity,
760                        n.lqi,
761                        link_cost_from_lqi(n.lqi),
762                        n.potential_parent,
763                        n.update_id
764                    );
765                }
766            }
767        }
768
769        // nwkStackProfile == 1 prefers minimum depth (3.6.1.4.1.1)
770        if *stack_profile == 1 {
771            candidates.sort_unstable_by_key(|&i| table[i].depth);
772        }
773
774        candidates
775    }
776
777    /// Build the IEEE 802.15.4 MAC `CapabilityInformation` from the NWK
778    /// layer `CapabilityInformation` bitmap (Table 3-62).
779    fn build_mac_capabilities(cap: &CapabilityInformation) -> zigbee_mac::CapabilityInformation {
780        zigbee_mac::CapabilityInformation {
781            // Bit 1 — Device type: 1 if joining as router (FFD)
782            full_function_device: cap.device_type(),
783            // Bit 2 — Power source
784            mains_power: cap.power_source(),
785            // Bit 3 — Receiver on when idle
786            idle_receive: cap.receiver_on_when_idle(),
787            // Bit 6 — Security capability
788            frame_protection: cap.security_capability(),
789            // Bit 7 — Allocate address
790            allocate_address: cap.allocate_address(),
791        }
792    }
793
794    /// Clear parent information and the negotiated end-device timeout; a
795    /// fresh join invalidates both (3.6.1.4.1.1, 3.6.10.2).
796    fn reset_parent_negotiation(&self) {
797        let nib = self.nib();
798        nib.update_parent_information(|value| *value = 0);
799        nib.update_end_device_timeout(|value| *value = NO_PENDING_TIMEOUT);
800        self.parent_timeout_remaining_ms
801            .store(PARENT_TIMEOUT_INACTIVE, Ordering::Relaxed);
802    }
803
804    /// Find the parent's MAC address from the neighbor table.
805    fn parent_address(&self) -> Result<Address, NetworkError> {
806        let addr = Address::Short(
807            PanId(*self.nib().panid()),
808            MacShortAddress(self.parent_short_address()?.0),
809        );
810        Ok(addr)
811    }
812
813    /// The IEEE address of a neighbor, once it has been learned from a
814    /// received frame carrying the source IEEE address field.
815    fn neighbor_ieee_address(&self, network_address: ShortAddress) -> Option<IeeeAddress> {
816        self.nib()
817            .neighbor_table()
818            .iter()
819            .find(|n| n.network_address == network_address)
820            .map(|n| n.extended_address)
821            .filter(|ieee| ieee.0 != 0)
822    }
823
824    /// The network address of a neighbor whose IEEE address has been learned
825    /// from a received frame (3.4.6.2).
826    pub(crate) fn short_address_for_ieee(&self, ieee: IeeeAddress) -> Option<ShortAddress> {
827        self.nib()
828            .neighbor_table()
829            .iter()
830            .find(|n| n.extended_address == ieee)
831            .map(|n| n.network_address)
832    }
833
834    /// Record the IEEE address a received frame reported for its source
835    /// (3.4.6.2: it lets us address later commands by both addresses).
836    fn learn_neighbor_ieee_address(&self, header: &NwkHeader<'_>) {
837        let Some(source_ieee) = header.source_ieee else {
838            return;
839        };
840        self.nib().update_neighbor_table(|table| {
841            if let Some(neighbor) = table
842                .iter_mut()
843                .find(|n| n.network_address == header.source)
844            {
845                neighbor.extended_address = source_ieee;
846            }
847        });
848    }
849
850    /// Find the parent's network address from the neighbor table.
851    fn parent_short_address(&self) -> Result<ShortAddress, NetworkError> {
852        let table = self.nib().neighbor_table();
853        let parent = table
854            .iter()
855            .find(|n| n.relationship == relationship::PARENT)
856            .ok_or(NetworkError::NotJoined)?;
857        Ok(parent.network_address)
858    }
859
860    /// Issue one MLME-POLL to the parent (3.6.6).
861    ///
862    /// Returns the raw MAC payload length, or `None` when nothing was buffered.
863    async fn poll_parent(&self, buf: &mut [u8]) -> Result<Option<usize>, NetworkError> {
864        let coord_addr = self.parent_address()?;
865        match self.mac.poll_data(coord_addr, buf).await {
866            Ok((len, _lqi)) => Ok(Some(len)),
867            Err(MacError::NoData) => Ok(None),
868            Err(e) => Err(e.into()),
869        }
870    }
871
872    /// Poll the parent once (MLME-POLL, 3.6.6) and process the retrieved NWK
873    /// frame, if any.
874    ///
875    /// A sleepy end device only receives buffered unicasts by polling.
876    /// Returns `Ok(None)` when nothing was buffered or the frame carried no
877    /// application data.
878    pub async fn poll_nwk_frame<'a>(
879        &self,
880        buf: &'a mut [u8],
881    ) -> Result<Option<NwkDataFrame<'a>>, NetworkError> {
882        let Some(len) = self.poll_parent(buf).await? else {
883            return Ok(None);
884        };
885        self.process_received_nwk_frame(&mut buf[..len]).await
886    }
887
888    /// Passively wait for the next inbound NWK frame and process it.
889    ///
890    /// For devices with `rxOnWhenIdle = TRUE`, which receive directly instead
891    /// of polling the parent for buffered unicasts. Returns `Ok(None)` when
892    /// the frame carried no application data.
893    pub async fn receive_nwk_frame<'a>(
894        &self,
895        buf: &'a mut [u8],
896    ) -> Result<Option<NwkDataFrame<'a>>, NetworkError> {
897        let (len, _lqi) = self.mac.receive(buf).await?;
898        self.process_received_nwk_frame(&mut buf[..len]).await
899    }
900
901    /// Decrypt one inbound NWK frame and hand NWK commands to the NWK layer.
902    async fn process_received_nwk_frame<'a>(
903        &self,
904        frame_buf: &'a mut [u8],
905    ) -> Result<Option<NwkDataFrame<'a>>, NetworkError> {
906        let cx = SecurityContext::get();
907        let nwk_frame = cx.decrypt_nwk_frame_in_place(frame_buf)?;
908
909        match nwk_frame {
910            NwkFrame::Data(data_frame) => {
911                self.learn_neighbor_ieee_address(&data_frame.header);
912                Ok(Some(data_frame))
913            }
914            // NWK command frames (link status, route requests, rejoin, ...) ride
915            // the same receive path; let the NWK layer process them, then report
916            // "no data" so the APS/ZDO caller skips this frame
917            NwkFrame::NwkCommand(command_frame) => {
918                self.learn_neighbor_ieee_address(&command_frame.header);
919                self.handle_nwk_command(&command_frame.header, command_frame.command)
920                    .await;
921                Ok(None)
922            }
923            _ => Ok(None),
924        }
925    }
926
927    /// Process an inbound NWK command frame (3.4).
928    ///
929    /// Scaffolding extension point: every NWK command variant is matched so a
930    /// handler can be filled in. Most are not yet acted upon — they are logged
931    /// and ignored. Returning unit keeps the caller's receive loop simple; add
932    /// a result type here if a handler needs to surface failures.
933    async fn handle_nwk_command(&self, header: &NwkHeader<'_>, command: Command<'_>) {
934        match command {
935            // routing (3.4.1-3.4.2): a sleepy end device routes via its parent,
936            // so route discovery is currently a no-op
937            Command::RouteRequest(_) => log::trace!("[NWK] route request (ignored)"),
938            Command::RouteReply(_) => log::trace!("[NWK] route reply (ignored)"),
939            Command::RouteRecord(_) => log::trace!("[NWK] route record (ignored)"),
940            // network maintenance (3.4.3, 3.4.9, 3.4.10)
941            Command::NetworkStatus(_) => log::trace!("[NWK] network status (ignored)"),
942            Command::NetworkReport(_) => log::trace!("[NWK] network report (ignored)"),
943            Command::NetworkUpdate(_) => log::trace!("[NWK] network update (ignored)"),
944            Command::Leave(leave) => self.handle_leave_command(header, &leave).await,
945            // rejoin (3.4.6–3.4.7): a request is parent-side only; a response
946            // is handed to the rejoin procedure waiting for it, which may be
947            // driven by another task than this receive path
948            Command::RejoinRequest(_) => log::trace!("[NWK] rejoin request (ignored)"),
949            Command::RejoinResponse(response) => {
950                log::debug!(
951                    "[NWK] rejoin response: address={:?}, status={:#04x}",
952                    response.network_address,
953                    response.status
954                );
955                if response.status == u8::from(AssociationStatus::Successful) {
956                    // 3.4.7.3.1: the parent may hand out a different address
957                    // than the one the device rejoined with
958                    self.nib()
959                        .update_network_address(|value| *value = response.network_address.0);
960                }
961                self.rejoin_response.signal(response);
962            }
963            // link management (3.4.8, 3.4.13)
964            Command::LinkStatus(_) => log::trace!("[NWK] link status (ignored)"),
965            Command::LinkPowerDelta(_) => log::trace!("[NWK] link power delta (ignored)"),
966            // end-device timeout requests are parent-side only (3.4.11)
967            Command::EndDeviceTimeoutRequest(_) => {
968                log::trace!("[NWK] end-device timeout request (ignored)");
969            }
970            // 3.6.10.2: on success store the parent information bitmask and
971            // the negotiated timeout, otherwise the parent keeps its default
972            Command::EndDeviceTimeoutResponse(response) => {
973                let pending = self
974                    .pending_timeout_request
975                    .swap(NO_PENDING_TIMEOUT, Ordering::Relaxed);
976                if response.status == EndDeviceTimeoutResponse::STATUS_SUCCESS
977                    && pending != NO_PENDING_TIMEOUT
978                {
979                    let nib = self.nib();
980                    nib.update_parent_information(|value| *value = response.parent_information);
981                    nib.update_end_device_timeout(|value| *value = pending);
982                    // the parent restarted its timeout counter for this device
983                    // (3.6.10.5), so the local one follows (3.6.10.6)
984                    self.refresh_parent_timeout();
985                    log::info!(
986                        "[NWK] end-device timeout negotiated: enum={pending}, parent_information={:#04x}",
987                        response.parent_information
988                    );
989                } else {
990                    log::warn!(
991                        "[NWK] end-device timeout response rejected or unexpected (status={:#04x})",
992                        response.status
993                    );
994                }
995                // hand it to a keepalive waiting for it (3.6.10.3)
996                self.timeout_response.signal(response);
997            }
998            Command::Reserved(id) => log::trace!("[NWK] reserved command {id:#04x} (ignored)"),
999        }
1000    }
1001
1002    /// Process an inbound Leave command frame (3.6.1.10.3).
1003    ///
1004    /// TODO: a router receiving a notification from its parent with the remove
1005    /// children sub-field set must rebroadcast the leave to its own children.
1006    async fn handle_leave_command(&self, header: &NwkHeader<'_>, leave: &Leave) {
1007        let options = leave.command_options;
1008        let is_from_parent = self
1009            .parent_short_address()
1010            .is_ok_and(|parent| parent == header.source);
1011
1012        if !options.request() {
1013            // notification: the sender left the network on its own initiative —
1014            // it is no longer a neighbor regardless of the rejoin flag
1015            self.nib().update_neighbor_table(|table| {
1016                table.retain(|n| n.network_address != header.source);
1017            });
1018
1019            if is_from_parent {
1020                // our parent has dropped us: we are no longer on the network,
1021                // and the indication carries a NULL device address (3.6.1.10.3)
1022                self.nib().update_extended_panid(|value| *value = 0);
1023                log::info!("[NWK] removed by parent (leave notification)");
1024                self.leave_indication.signal(NlmeLeaveIndication {
1025                    device_address: None,
1026                    rejoin: options.rejoin(),
1027                });
1028            } else {
1029                log::debug!(
1030                    "[NWK] neighbor {:?} left the network (rejoin={})",
1031                    header.source_ieee,
1032                    options.rejoin()
1033                );
1034                self.leave_indication.signal(NlmeLeaveIndication {
1035                    device_address: header.source_ieee,
1036                    rejoin: options.rejoin(),
1037                });
1038            }
1039            return;
1040        }
1041
1042        // request == 1: someone is asking us to leave (3.6.1.10.3.1). A leave
1043        // request is sent by the parent itself, so its NWK source address is
1044        // the sender the spec tests
1045        let from_parent = self
1046            .parent_short_address()
1047            .is_ok_and(|parent| parent == header.source);
1048        if !self.accepts_leave_request(header.destination, from_parent) {
1049            return;
1050        }
1051
1052        if let Err(e) = self
1053            .leave_network(options.remove_children(), options.rejoin())
1054            .await
1055        {
1056            log::warn!("[NWK] failed to announce leave: {e:?}");
1057        }
1058
1059        // 3.2.2.19: removed by another device, so the indication carries a NULL
1060        // device address; with the rejoin flag it asks the higher layer to come
1061        // back onto the network (3.6.1.10.4)
1062        self.leave_indication.signal(NlmeLeaveIndication {
1063            device_address: None,
1064            rejoin: options.rejoin(),
1065        });
1066    }
1067
1068    /// Validate a leave request against 3.6.1.10.3.1, which governs both the
1069    /// NWK Leave (request) command and the ZDO Mgmt_Leave_req.
1070    ///
1071    /// `destination` is the address the request was addressed to.
1072    /// `from_parent` says whether it reached this device over the parent link:
1073    /// the spec tests the MAC source address of the delivering frame, which is
1074    /// the parent for anything a child receives — not the originator of a
1075    /// relayed ZDP request.
1076    pub fn accepts_leave_request(&self, destination: ShortAddress, from_parent: bool) -> bool {
1077        // step 1: the coordinator never leaves, and a broadcast request is
1078        // dropped without further processing
1079        if *self.nib().network_address() == NWK_COORDINATOR_ADDRESS
1080            || destination.0 >= NWK_BROADCAST_ADDRESS_MIN
1081        {
1082            log::trace!("[NWK] leave request dropped (coordinator or broadcast destination)");
1083            return false;
1084        }
1085
1086        // step 2: a router honors any sender while nwkLeaveRequestAllowed is
1087        // set, ignoring the neighbor relationship
1088        if self.nib().capability_information().device_type() {
1089            let allowed = *self.nib().leave_request_allowed();
1090            if !allowed {
1091                log::trace!("[NWK] leave request refused (nwkLeaveRequestAllowed is FALSE)");
1092            }
1093            return allowed;
1094        }
1095
1096        // step 3: an end device is only removed by its parent
1097        if !from_parent {
1098            log::trace!("[NWK] leave request refused (sender is not our parent)");
1099        }
1100        from_parent
1101    }
1102
1103    /// 3.2.2.18
1104    ///
1105    /// Only self-removal (`device_address` `None` or this device's own IEEE
1106    /// address) is implemented: removing a child requires acting as its
1107    /// parent, which this stack does not yet support.
1108    pub async fn leave(&self, request: NlmeLeaveRequest) -> NlmeLeaveConfirm {
1109        if *self.nib().network_address() == NWK_UNASSIGNED_ADDRESS {
1110            return NlmeLeaveConfirm {
1111                status: NlmeLeaveStatus::InvalidRequest,
1112                device_address: request.device_address,
1113            };
1114        }
1115
1116        let is_self = request
1117            .device_address
1118            .is_none_or(|addr| addr == *self.nib().ieee_address());
1119        if !is_self {
1120            return NlmeLeaveConfirm {
1121                status: NlmeLeaveStatus::UnknownDevice,
1122                device_address: request.device_address,
1123            };
1124        }
1125
1126        let status = match self
1127            .leave_network(request.remove_children, request.rejoin)
1128            .await
1129        {
1130            Ok(()) => NlmeLeaveStatus::Success,
1131            Err(_) => NlmeLeaveStatus::MacError,
1132        };
1133        NlmeLeaveConfirm {
1134            status,
1135            device_address: None,
1136        }
1137    }
1138
1139    /// 3.6.1.10.1 + 3.6.1.10.4: announce this device's own removal from the
1140    /// network, then apply the local leave procedure.
1141    ///
1142    /// The local leave runs whether or not the announcement made it onto the
1143    /// air; the transmit result only feeds the NLME-LEAVE.confirm status.
1144    async fn leave_network(&self, remove_children: bool, rejoin: bool) -> Result<(), NetworkError> {
1145        let result = self.announce_leave(remove_children, rejoin).await;
1146        self.local_leave(rejoin);
1147        result
1148    }
1149
1150    /// 3.6.1.10.1: transmit this device's own leave command frame, with the
1151    /// request sub-field set to 0 — a notification, never a request addressed
1152    /// to someone else.
1153    async fn announce_leave(
1154        &self,
1155        remove_children: bool,
1156        rejoin: bool,
1157    ) -> Result<(), NetworkError> {
1158        let is_router_or_coordinator = self.nib().capability_information().device_type()
1159            || *self.nib().network_address() == NWK_COORDINATOR_ADDRESS;
1160
1161        let mut buf = [0u8; 64];
1162        if is_router_or_coordinator {
1163            let command = Command::Leave(Leave {
1164                command_options: LeaveCommandOptions(0)
1165                    .set_remove_children(remove_children)
1166                    .set_rejoin(rejoin),
1167            });
1168            let len = self.build_nwk_command_frame(
1169                ShortAddress(NWK_BROADCAST_ALL),
1170                command,
1171                true,
1172                &mut buf,
1173            )?;
1174            // read out before the `.await` below — held across it, this
1175            // guard would deadlock against a concurrent write of this field
1176            let pan_id = *self.nib().panid();
1177            self.mac
1178                .transmit_data(
1179                    Address::Short(PanId(pan_id), MacShortAddress(NWK_BROADCAST_ALL)),
1180                    &buf[..len],
1181                )
1182                .await?;
1183            return Ok(());
1184        }
1185
1186        // an end device unicasts to its parent and sends the remove children
1187        // sub-field as 0; only the rejoin flag is carried over
1188        let command = Command::Leave(Leave {
1189            command_options: LeaveCommandOptions(0).set_rejoin(rejoin),
1190        });
1191        let len =
1192            self.build_nwk_command_frame(self.parent_short_address()?, command, true, &mut buf)?;
1193        let result = self
1194            .mac
1195            .transmit_data(self.parent_address()?, &buf[..len])
1196            .await;
1197        // 3.6.1.10.1: an end device clears the extended PAN id right after
1198        // transmitting, ahead of the rest of the local leave process
1199        self.nib().update_extended_panid(|value| *value = 0);
1200        result.map_err(Into::into)
1201    }
1202
1203    /// 3.6.1.10.4: the local half of the leave procedure.
1204    fn local_leave(&self, rejoin: bool) {
1205        if rejoin {
1206            // step 1: with Rejoin set the NIB is kept, so the remembered
1207            // network is still there for a later NLME-JOIN.request with
1208            // `RejoinNetwork::NwkRejoin`; driving that is the higher layer's
1209            // call, which the NLME-LEAVE.indication/confirm hands it
1210            log::info!("[NWK] left the network, rejoin requested");
1211            return;
1212        }
1213
1214        self.clear_nib_on_leave();
1215    }
1216
1217    /// 3.6.1.10.4 (Rejoin = FALSE): clear the NIB attributes describing
1218    /// network membership, leaving the device unjoined.
1219    fn clear_nib_on_leave(&self) {
1220        let nib = self.nib();
1221        nib.update_neighbor_table(|value| value.clear());
1222        nib.update_route_table(|value| value.clear());
1223        nib.update_manager_addr(|value| *value = 0x0000);
1224        nib.update_update_id(|value| *value = 0x00);
1225        nib.update_network_address(|value| *value = NWK_UNASSIGNED_ADDRESS);
1226        nib.update_group_idtable(|value| value.clear());
1227        nib.update_extended_panid(|value| *value = 0);
1228        nib.update_route_record_table(|value| value.clear());
1229        nib.update_is_concentrator(|value| *value = false);
1230        nib.update_concentrator_radius(|value| *value = 0);
1231        nib.update_security_material_set(|value| value.clear());
1232        nib.update_active_key_seq_number(|value| *value = 0x00);
1233        nib.update_address_map(|value| value.clear());
1234        nib.update_panid(|value| *value = 0xffff);
1235        nib.update_tx_total(|value| *value = 0);
1236        nib.update_parent_information(|value| *value = 0x00);
1237    }
1238
1239    /// 3.2.2.3
1240    pub async fn network_discovery(
1241        &self,
1242        channels: core::ops::Range<u8>,
1243        duration: u8,
1244    ) -> Result<NlmeNetworkDiscoveryConfirm, NetworkError> {
1245        let scan_result = self
1246            .mac
1247            .scan_network(ScanType::Active, channels, duration)
1248            .await?;
1249
1250        // populate the neighbor table with mandatory fields (Table 3-63)
1251        // and optional discovery-time fields (Table 3-64)
1252        let neighbor_table = scan_result
1253            .pan_descriptor
1254            .iter()
1255            .filter_map(|pd| match pd.coord_address {
1256                Address::Short(_pan_id, short_address) => Some(NwkNeighbor {
1257                    // a beacon carries no IEEE address; learned later from
1258                    // received frames
1259                    extended_address: IeeeAddress(0),
1260                    network_address: ShortAddress(short_address.0),
1261                    device_type: if short_address.0 == NWK_COORDINATOR_ADDRESS {
1262                        DeviceType::Coordinator
1263                    } else {
1264                        DeviceType::Router
1265                    },
1266                    rx_on_when_idle: false,
1267                    end_device_configuration: 0,
1268                    relationship: relationship::NONE,
1269                    transmit_failure: 0,
1270                    lqi: pd.link_quality,
1271                    outgoing_cost: 0,
1272                    age: 0,
1273                    keepalive_received: false,
1274                    // Table 3-64: optional discovery-time fields
1275                    extended_pan_id: pd.zigbee_beacon.extended_pan_id,
1276                    logical_channel: pd.channel,
1277                    depth: pd.zigbee_beacon.stack_profile.device_depth(),
1278                    permit_joining: pd.superframe_spec.association_permit,
1279                    // a device is a potential parent if it can accept a child of
1280                    // either type; select_parent_candidates applies the
1281                    // join-type-specific capacity check (Table 3-64)
1282                    potential_parent: u8::from(
1283                        pd.zigbee_beacon.stack_profile.router_capacity()
1284                            || pd.zigbee_beacon.stack_profile.end_device_capacity()
1285                            || short_address.0 == NWK_COORDINATOR_ADDRESS,
1286                    ),
1287                    router_capacity: pd.zigbee_beacon.stack_profile.router_capacity(),
1288                    end_device_capacity: pd.zigbee_beacon.stack_profile.end_device_capacity(),
1289                    update_id: pd.zigbee_beacon.update_id,
1290                    pan_id: pd.coord_pan_id.0,
1291                }),
1292                Address::Extended(_, _) => None,
1293            })
1294            .collect();
1295
1296        self.nib()
1297            .update_neighbor_table(|value| *value = StorageVec(neighbor_table));
1298
1299        // build network descriptors for the confirm primitive
1300        let network_descriptors = scan_result
1301            .pan_descriptor
1302            .into_iter()
1303            .map(From::from)
1304            .collect();
1305
1306        Ok(NlmeNetworkDiscoveryConfirm {
1307            network_descriptor: network_descriptors,
1308        })
1309    }
1310
1311    /// 3.2.2.5
1312    #[allow(clippy::unused_async)]
1313    pub async fn network_formation(
1314        &self,
1315        _request: NlmeNetworkFormationRequest,
1316    ) -> NlmeNetworkFormationConfirm {
1317        todo!()
1318    }
1319
1320    /// 3.2.2.7
1321    // figure 3-39
1322    #[allow(clippy::unused_async, clippy::unused_async_trait_impl)]
1323    pub async fn permit_joining(
1324        &self,
1325        _request: NlmePermitJoiningRequest,
1326    ) -> NlmePermitJoiningConfirm {
1327        NlmePermitJoiningConfirm {
1328            status: NlmeJoinStatus::InvalidRequest,
1329        }
1330    }
1331
1332    /// 3.2.2.9
1333    #[allow(clippy::unused_async)]
1334    pub async fn start_router(&self, _request: NlmeStartRouterRequest) -> NlmeStartRouterConfirm {
1335        todo!()
1336    }
1337
1338    /// 3.2.2.11
1339    #[allow(clippy::unused_async)]
1340    pub async fn ed_scan(&self, _request: NlmeEdScanRequest) -> NlmeEdScanConfirm {
1341        todo!()
1342    }
1343
1344    /// 3.2.2.13
1345    // the association candidate loop is a single state machine; splitting it
1346    // up would scatter the 3.6.1.4.1.1 bookkeeping across functions
1347    #[allow(clippy::too_many_lines)]
1348    pub async fn join(&self, request: NlmeJoinRequest) -> NlmeJoinConfirm {
1349        if request.rejoin_network == RejoinNetwork::NwkRejoin {
1350            return self.nwk_rejoin(request).await;
1351        }
1352        let fail = Self::join_failure;
1353
1354        // validate the request (3.2.2.13.3); orphan (0x01) and channel
1355        // change (0x03) are not yet implemented
1356        if request.rejoin_network != RejoinNetwork::Association {
1357            return fail(NlmeJoinStatus::InvalidRequest);
1358        }
1359
1360        // a device already joined must not re-associate (3.6.1.4.1.1)
1361        if *self.nib().network_address() != 0xffff {
1362            return fail(NlmeJoinStatus::InvalidRequest);
1363        }
1364
1365        // parent selection (3.6.1.4.1.1): reset nwkParentInformation before
1366        // searching, per spec
1367        self.reset_parent_negotiation();
1368
1369        let join_as_router = request.capability_information.device_type();
1370
1371        let candidates = self.select_parent_candidates(request.extended_pan_id, join_as_router);
1372
1373        if candidates.is_empty() {
1374            // select_parent_candidates already logged why
1375            return fail(NlmeJoinStatus::NotPermitted);
1376        }
1377
1378        log::debug!("[NWK-JOIN] neighbor candidates: {candidates:?}");
1379
1380        // build MAC CapabilityInformation from NWK CapabilityInformation
1381        // bitmap (Table 3-62)
1382        let mac_caps = Self::build_mac_capabilities(&request.capability_information);
1383
1384        // 3.6.1.4.1.1: the capability information shall be stored as the
1385        // value of the nwkCapabilityInformation NIB attribute
1386        self.nib()
1387            .update_capability_information(|value| *value = request.capability_information);
1388
1389        // try each candidate in order (3.6.1.4.1.1)
1390        let mut last_status = NlmeJoinStatus::NotPermitted;
1391
1392        for &candidate_idx in &candidates {
1393            let table = self.nib().neighbor_table();
1394            let neighbor = &table[candidate_idx];
1395            let channel = neighbor.logical_channel;
1396            let pan_id = PanId(neighbor.pan_id);
1397            // the network's own EPID, learned from this candidate's beacon: a
1398            // join request may name the wildcard 0, and the NIB has to end up
1399            // with the network actually joined (3.6.1.4.1.1)
1400            let joined_epid = neighbor.extended_pan_id;
1401            let dest = Address::Short(pan_id, MacShortAddress(neighbor.network_address.0));
1402            drop(table);
1403
1404            match self.mac.associate(channel, dest, mac_caps).await {
1405                Ok(response) => {
1406                    match response.status {
1407                        AssociationStatus::Successful => {
1408                            let assigned_addr = response.association_address;
1409                            self.nib()
1410                                .update_network_address(|value| *value = assigned_addr.0);
1411                            self.nib()
1412                                .update_ieee_address(|value| *value = response.device_address);
1413                            self.nib()
1414                                .update_extended_panid(|value| *value = joined_epid.0);
1415                            self.nib().update_panid(|value| *value = pan_id.0);
1416
1417                            // read parent fields before the clearing loop
1418                            // zeroes them (3.6.1.4.1.1)
1419                            let parent_update_id =
1420                                self.nib().neighbor_table()[candidate_idx].update_id;
1421                            let parent_channel =
1422                                self.nib().neighbor_table()[candidate_idx].logical_channel;
1423                            self.nib()
1424                                .update_update_id(|value| *value = parent_update_id);
1425
1426                            // set the relationship field to parent and clear
1427                            // optional Table 3-64 fields on all entries, which
1428                            // should not be retained after joining
1429                            // TODO: retain only entries belonging to the joined
1430                            // network
1431                            self.nib().update_neighbor_table(|table| {
1432                                table[candidate_idx].relationship = relationship::PARENT;
1433                                for neighbor in table.iter_mut() {
1434                                    neighbor.extended_pan_id = IeeeAddress(0);
1435                                    neighbor.logical_channel = 0;
1436                                    neighbor.depth = 0;
1437                                    neighbor.permit_joining = false;
1438                                    neighbor.potential_parent = 0;
1439                                    neighbor.router_capacity = false;
1440                                    neighbor.end_device_capacity = false;
1441                                    neighbor.update_id = 0;
1442                                    neighbor.pan_id = 0xffff;
1443                                }
1444                            });
1445
1446                            return NlmeJoinConfirm {
1447                                status: NlmeJoinStatus::Success,
1448                                network_address: assigned_addr,
1449                                extended_pan_id: request.extended_pan_id,
1450                                channel: parent_channel,
1451                                enhanced_beacon_type: false,
1452                                mac_interface_index: 0u8,
1453                            };
1454                        }
1455                        AssociationStatus::NetworkAtCapacity => {
1456                            // mark this neighbor as not a potential parent so
1457                            // we don't retry (3.6.1.4.1.1)
1458                            self.nib().update_neighbor_table(|table| {
1459                                table[candidate_idx].potential_parent = 0;
1460                            });
1461                            last_status = NlmeJoinStatus::PanAtCapacity;
1462                        }
1463                        AssociationStatus::AccessDenied => {
1464                            self.nib().update_neighbor_table(|table| {
1465                                table[candidate_idx].potential_parent = 0;
1466                            });
1467                            last_status = NlmeJoinStatus::PanAccessDenied;
1468                        }
1469                        // other status codes are treated as a generic MAC-level failure
1470                        _ => {
1471                            last_status = NlmeJoinStatus::MacError;
1472                        }
1473                    }
1474                }
1475                Err(_mac_err) => {
1476                    last_status = NlmeJoinStatus::MacError;
1477                }
1478            }
1479        }
1480
1481        // all candidates exhausted
1482        fail(last_status)
1483    }
1484
1485    /// NLME-JOIN.request with `RejoinNetwork::NwkRejoin` (3.6.1.4.2).
1486    ///
1487    /// Reconnects to a network this device remembers — extended PAN id,
1488    /// network key — by unicasting a Rejoin Request (3.4.6) and waiting for
1489    /// the Rejoin Response (3.4.7). The remembered parent is tried first; if
1490    /// it does not answer, `request.scan_channels` are scanned for another
1491    /// router of the same network to rejoin through, which may operate on a
1492    /// different channel.
1493    ///
1494    /// `request.security_enabled` selects the rejoin flavour: `true` secures
1495    /// the Rejoin Request with the active network key (Secure Rejoin,
1496    /// 4.6.3.3.1), `false` sends it unsecured (Trust Center Rejoin,
1497    /// 4.6.3.3.2) for a device that no longer holds the key — the caller is
1498    /// then responsible for obtaining the current network key from the Trust
1499    /// Center.
1500    async fn nwk_rejoin(&self, request: NlmeJoinRequest) -> NlmeJoinConfirm {
1501        let fail = Self::join_failure;
1502
1503        // a rejoin only makes sense against a network this device already
1504        // remembers (BDB 7.1 step 4 only reaches here when
1505        // bdbNodeIsOnANetwork is TRUE and the extended PAN id is known). A
1506        // leave zeroes nwkExtendedPANId (3.6.1.10.1) without ending the rejoin
1507        // path, so an unknown extended PAN id takes the requested one
1508        let remembered_epid = *self.nib().extended_panid();
1509        if *self.nib().network_address() == 0xffff
1510            || (remembered_epid != 0 && remembered_epid != request.extended_pan_id.0)
1511        {
1512            return fail(NlmeJoinStatus::InvalidRequest);
1513        }
1514
1515        // whether joining or rejoining, nwkParentInformation is reset
1516        // (3.2.2.13.3)
1517        self.reset_parent_negotiation();
1518        self.nib()
1519            .update_capability_information(|value| *value = request.capability_information);
1520
1521        // the remembered parent needs no scan: try it before the discovery
1522        // below rebuilds the neighbor table from fresh beacons
1523        let mut last_status = NlmeJoinStatus::InvalidRequest;
1524        if let Ok(parent) = self.parent_short_address() {
1525            match self.rejoin_via_parent(parent, &request).await {
1526                // the channel is whatever the radio is already tuned to
1527                Ok(response) => return self.rejoin_confirm(response, &request, 0).await,
1528                Err(status) => {
1529                    log::debug!("[NWK-REJOIN] remembered parent failed ({status:?})");
1530                    last_status = status;
1531                }
1532            }
1533        }
1534
1535        if request.scan_channels.is_empty() {
1536            return fail(last_status);
1537        }
1538
1539        log::debug!(
1540            "[NWK-REJOIN] scanning {:?} for another parent",
1541            request.scan_channels
1542        );
1543        if let Err(e) = self
1544            .network_discovery(request.scan_channels.clone(), request.scan_duration)
1545            .await
1546        {
1547            log::warn!("[NWK-REJOIN] scan failed: {e:?}");
1548            return fail(NlmeJoinStatus::MacError);
1549        }
1550
1551        let join_as_router = request.capability_information.device_type();
1552        let candidates = self.select_rejoin_candidates(request.extended_pan_id, join_as_router);
1553        if candidates.is_empty() {
1554            log::warn!("[NWK-REJOIN] no parent candidate found");
1555            return fail(NlmeJoinStatus::NotPermitted);
1556        }
1557
1558        for candidate_idx in candidates {
1559            let Some((parent, channel)) = self.adopt_parent(candidate_idx).await else {
1560                continue;
1561            };
1562            match self.rejoin_via_parent(parent, &request).await {
1563                Ok(response) => return self.rejoin_confirm(response, &request, channel).await,
1564                Err(status) => {
1565                    log::debug!("[NWK-REJOIN] candidate {parent:?} failed ({status:?})");
1566                    last_status = status;
1567                }
1568            }
1569        }
1570
1571        fail(last_status)
1572    }
1573
1574    /// One Rejoin Request/Response exchange with `parent` (3.4.6, 3.4.7).
1575    async fn rejoin_via_parent(
1576        &self,
1577        parent: ShortAddress,
1578        request: &NlmeJoinRequest,
1579    ) -> Result<RejoinResponse, NlmeJoinStatus> {
1580        let command = Command::RejoinRequest(RejoinRequest {
1581            // the Capability Information bit layout (Table 3-62) is shared
1582            // with `nwk::nib::CapabilityInformation`
1583            capability_information: rejoin_request::CapabilityInformation(
1584                request.capability_information.0,
1585            ),
1586        });
1587
1588        let mut buf = [0u8; 128];
1589        let len = self
1590            .build_nwk_command_frame(parent, command, request.security_enabled, &mut buf)
1591            .map_err(|_| NlmeJoinStatus::MacError)?;
1592        let parent_addr = self
1593            .parent_address()
1594            .map_err(|_| NlmeJoinStatus::InvalidRequest)?;
1595
1596        // arm before transmitting: the response is delivered by the receive
1597        // path, which may be this procedure's own poll or a concurrent loop
1598        self.rejoin_response.reset();
1599        self.mac
1600            .transmit_data(parent_addr, &buf[..len])
1601            .await
1602            .map_err(|_| NlmeJoinStatus::MacError)?;
1603
1604        let response = self
1605            .await_rejoin_response(REJOIN_RESPONSE_POLL_RETRIES)
1606            .await
1607            .ok_or(NlmeJoinStatus::MacError)?;
1608
1609        match response.status {
1610            status if status == u8::from(AssociationStatus::Successful) => Ok(response),
1611            status if status == u8::from(AssociationStatus::NetworkAtCapacity) => {
1612                Err(NlmeJoinStatus::PanAtCapacity)
1613            }
1614            status if status == u8::from(AssociationStatus::AccessDenied) => {
1615                Err(NlmeJoinStatus::PanAccessDenied)
1616            }
1617            _ => Err(NlmeJoinStatus::MacError),
1618        }
1619    }
1620
1621    /// Build the successful NLME-JOIN.confirm of a rejoin (3.2.2.15).
1622    async fn rejoin_confirm(
1623        &self,
1624        response: RejoinResponse,
1625        request: &NlmeJoinRequest,
1626        channel: u8,
1627    ) -> NlmeJoinConfirm {
1628        // the receive path stored the assigned address; the hardware filter has
1629        // to follow it
1630        self.mac
1631            .configure(MacConfig::short_address(response.network_address))
1632            .await;
1633        // 3.2.2.13.3: nwkExtendedPANId names the network we are on again. a
1634        // rejoin request may carry the wildcard 0, which must not erase the
1635        // EPID the join stored
1636        if request.extended_pan_id.0 != 0 {
1637            self.nib()
1638                .update_extended_panid(|value| *value = request.extended_pan_id.0);
1639        }
1640
1641        NlmeJoinConfirm {
1642            status: NlmeJoinStatus::Success,
1643            network_address: response.network_address,
1644            extended_pan_id: request.extended_pan_id,
1645            channel,
1646            enhanced_beacon_type: false,
1647            mac_interface_index: 0u8,
1648        }
1649    }
1650
1651    /// Make the neighbor at `candidate_idx` this device's parent and tune the
1652    /// radio to its channel, returning its address and channel.
1653    ///
1654    /// A rejoin may land on a router other than the remembered parent, and the
1655    /// network may meanwhile have moved to another channel (3.6.1.4.2).
1656    async fn adopt_parent(&self, candidate_idx: usize) -> Option<(ShortAddress, u8)> {
1657        let nib = self.nib();
1658        let (parent, channel, pan_id, update_id) = {
1659            let table = nib.neighbor_table();
1660            let neighbor = table.get(candidate_idx)?;
1661            (
1662                neighbor.network_address,
1663                neighbor.logical_channel,
1664                neighbor.pan_id,
1665                neighbor.update_id,
1666            )
1667        };
1668
1669        nib.update_neighbor_table(|table| {
1670            for (index, neighbor) in table.iter_mut().enumerate() {
1671                neighbor.relationship = if index == candidate_idx {
1672                    relationship::PARENT
1673                } else {
1674                    relationship::NONE
1675                };
1676            }
1677        });
1678        nib.update_panid(|value| *value = pan_id);
1679        nib.update_update_id(|value| *value = update_id);
1680        self.mac.configure(MacConfig::channel(channel)).await;
1681
1682        Some((parent, channel))
1683    }
1684
1685    /// Wait for the receive path to deliver the Rejoin Response (3.4.7).
1686    ///
1687    /// A concurrently running receive loop may deliver it; otherwise the
1688    /// bounded polling below does.
1689    async fn await_rejoin_response(&self, retries: u8) -> Option<RejoinResponse> {
1690        with_timeout(
1691            self.rejoin_response.wait(),
1692            self.poll_until_rejoin_response(retries),
1693        )
1694        .await
1695        // the response may have arrived in the very poll that ended the polling
1696        .or_else(|| self.rejoin_response.try_take())
1697    }
1698
1699    /// Poll the parent until the Rejoin Response has been processed or
1700    /// `retries` polls went unanswered.
1701    ///
1702    /// Drives reception for a caller whose receive loop is not running yet; a
1703    /// data frame cannot be dispatched from here and is left to that loop.
1704    async fn poll_until_rejoin_response(&self, retries: u8) {
1705        let mut buf = [0u8; 128];
1706        for _ in 0..retries {
1707            if self.rejoin_response.is_signaled() {
1708                return;
1709            }
1710            match self.poll_parent(&mut buf).await {
1711                Ok(Some(len)) => match self.process_received_nwk_frame(&mut buf[..len]).await {
1712                    Ok(Some(_)) => log::debug!("[NWK-REJOIN] polled data frame dropped"),
1713                    Ok(None) => (),
1714                    Err(e) => log::debug!("[NWK-REJOIN] polled frame not processed: {e:?}"),
1715                },
1716                Ok(None) => (),
1717                Err(e) => log::debug!("[NWK-REJOIN] poll failed: {e:?}"),
1718            }
1719        }
1720    }
1721
1722    /// Poll the coordinator for pending data, strip the NWK header, and
1723    /// return the APS payload (3.6.2).
1724    pub async fn poll_nwk_data<'a>(
1725        &self,
1726        buf: &'a mut [u8],
1727        retries: u8,
1728    ) -> Result<NwkDataFrame<'a>, NetworkError> {
1729        for _ in 0..retries {
1730            // SAFETY: `buf` is mutably borrowed once at a time
1731            // need to get rid of the 'a lifetime in the loop
1732            // &mut buf is still guaranteed within 'a
1733            let buf = unsafe { slice::from_raw_parts_mut(buf.as_mut_ptr(), buf.len()) };
1734            match self.poll_nwk_frame(buf).await {
1735                Ok(Some(data_frame)) => {
1736                    return Ok(data_frame);
1737                }
1738                // keep polling: nothing buffered, a NWK command frame, or ambient
1739                // traffic the pre-key joiner cannot decode (SecurityError/ParseError)
1740                // the NWK-unsecured transport-key (4.6.3.7.2) stays buffered for a
1741                // later poll
1742                Ok(None) | Err(NetworkError::SecurityError(_) | NetworkError::ParseError) => (),
1743                Err(e) => return Err(e),
1744            }
1745        }
1746
1747        Err(NetworkError::MacError(MacError::NoData))
1748    }
1749
1750    /// Broadcast an NWK data frame (3.6.5).
1751    ///
1752    /// Wraps `payload` in a NWK header addressed to `destination` and
1753    /// transmits it as a MAC broadcast.
1754    ///
1755    /// When `secure` is true the NWK frame is encrypted with the
1756    /// active network key.
1757    pub async fn broadcast_data(
1758        &self,
1759        destination: ShortAddress,
1760        secure: bool,
1761        payload: &[u8],
1762    ) -> Result<(), NetworkError> {
1763        let mut buf = [0u8; 256];
1764        let total_len = self.build_nwk_data_frame(destination, secure, payload, &mut buf)?;
1765        // 3.6.5: a sleepy end device unicasts broadcasts to its parent,
1766        // which relays them into the network on its behalf
1767        self.transmit_via_parent(&buf[..total_len]).await
1768    }
1769
1770    /// Send an NWK data frame to a specific destination (3.6.3).
1771    ///
1772    /// Wraps `payload` in a NWK header addressed to `destination` and
1773    /// transmits it via the parent (for end devices) or directly.
1774    ///
1775    /// When `secure` is true the NWK frame is encrypted with the
1776    /// active network key.
1777    pub async fn send_data(
1778        &self,
1779        destination: ShortAddress,
1780        secure: bool,
1781        payload: &[u8],
1782    ) -> Result<(), NetworkError> {
1783        let mut buf = [0u8; 256];
1784        let total_len = self.build_nwk_data_frame(destination, secure, payload, &mut buf)?;
1785        // end devices route via parent
1786        self.transmit_via_parent(&buf[..total_len]).await
1787    }
1788}
1789
1790#[cfg(test)]
1791mod tests {
1792    use core::future::Future;
1793
1794    use zigbee_mac::AssociationStatus;
1795    use zigbee_mac::mlme::AssociationResponse;
1796    use zigbee_mac::mlme::MacConfig;
1797    use zigbee_mac::mlme::MacError;
1798    use zigbee_mac::mlme::ScanResult;
1799    use zigbee_mac::mlme::ScanType;
1800
1801    use super::*;
1802    // tests share a global NIB singleton — serialize against every other
1803    // module that touches it, not just this one
1804    use crate::TEST_MUTEX;
1805
1806    // minimal async block_on — the mock futures resolve immediately so a
1807    // single poll is sufficient
1808    #[allow(clippy::panic)]
1809    fn block_on<F: Future>(f: F) -> F::Output {
1810        use core::pin::pin;
1811        use core::task::Context;
1812        use core::task::Poll;
1813        use core::task::RawWaker;
1814        use core::task::RawWakerVTable;
1815        use core::task::Waker;
1816
1817        fn noop(_: *const ()) {}
1818        fn clone(p: *const ()) -> RawWaker {
1819            RawWaker::new(p, &VTABLE)
1820        }
1821        static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
1822
1823        let waker = unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) };
1824        let mut cx = Context::from_waker(&waker);
1825        let mut f = pin!(f);
1826
1827        match f.as_mut().poll(&mut cx) {
1828            Poll::Ready(val) => val,
1829            Poll::Pending => panic!("block_on: future returned Pending"),
1830        }
1831    }
1832
1833    mockall::mock! {
1834        Mlme {}
1835        impl Mlme for Mlme {
1836            fn ieee_address(&self) -> IeeeAddress;
1837            async fn configure(&self, config: MacConfig);
1838            async fn scan_network(
1839                &self,
1840                ty: ScanType,
1841                channels: core::ops::Range<u8>,
1842                duration: u8,
1843            ) -> Result<ScanResult, MacError>;
1844            async fn associate(
1845                &self,
1846                channel: u8,
1847                dest: Address,
1848                capabilities: zigbee_mac::CapabilityInformation,
1849            ) -> Result<AssociationResponse, MacError>;
1850            async fn poll_data(
1851                &self,
1852                coord_address: Address,
1853                buf: &mut [u8],
1854            ) -> Result<(usize, u8), MacError>;
1855            async fn receive(
1856                &self,
1857                buf: &mut [u8],
1858            ) -> Result<(usize, u8), MacError>;
1859            async fn transmit_data(
1860                &self,
1861                dest: Address,
1862                payload: &[u8],
1863            ) -> Result<(), MacError>;
1864            fn random_u32(&self) -> u32;
1865        }
1866    }
1867
1868    // creates a default `NwkNeighbor` pre-filled for parent selection
1869    fn make_neighbor(pan_id: u16, short_addr: u16, epid: u64, lqi: u8, depth: u8) -> NwkNeighbor {
1870        NwkNeighbor {
1871            extended_address: IeeeAddress(0),
1872            network_address: ShortAddress(short_addr),
1873            device_type: if short_addr == 0 {
1874                DeviceType::Coordinator
1875            } else {
1876                DeviceType::Router
1877            },
1878            rx_on_when_idle: false,
1879            end_device_configuration: 0,
1880            relationship: 0x03,
1881            transmit_failure: 0,
1882            lqi,
1883            outgoing_cost: 0,
1884            age: 0,
1885            keepalive_received: false,
1886            extended_pan_id: IeeeAddress(epid),
1887            logical_channel: 11,
1888            depth,
1889            permit_joining: true,
1890            potential_parent: 1,
1891            router_capacity: true,
1892            end_device_capacity: true,
1893            update_id: 0,
1894            pan_id,
1895        }
1896    }
1897
1898    fn make_nlme(mut mac: MockMlme) -> (std::sync::MutexGuard<'static, ()>, Nlme<MockMlme>) {
1899        let guard = TEST_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
1900        use crate::nwk::nib;
1901        nib::try_init();
1902        nib::reset();
1903        // the security context used by frame builders also needs the AIB
1904        crate::aps::aib::try_init();
1905        // reset() only rewrites fields with a declared default; StorageVec
1906        // fields (no default) persist across tests in the global NIB,
1907        // so clear explicitly
1908        nib::get_ref().update_neighbor_table(|value| *value = StorageVec::new());
1909        mac.expect_ieee_address()
1910            .return_const(IeeeAddress(0xa4c1_0000_0000_0001));
1911        mac.expect_random_u32().return_const(0u32);
1912        (guard, Nlme::new(mac))
1913    }
1914
1915    fn default_join_request(epid: u64) -> NlmeJoinRequest {
1916        NlmeJoinRequest {
1917            extended_pan_id: IeeeAddress(epid),
1918            rejoin_network: RejoinNetwork::Association,
1919            capability_information: CapabilityInformation(0x80),
1920            security_enabled: false,
1921            scan_channels: 0..0,
1922            scan_duration: 0,
1923        }
1924    }
1925
1926    #[test]
1927    fn select_parent_no_neighbors() {
1928        let (_guard, nlme) = make_nlme(MockMlme::new());
1929        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
1930        assert!(candidates.is_empty());
1931    }
1932
1933    #[test]
1934    fn select_parent_filters_by_extended_pan_id() {
1935        let (_guard, nlme) = make_nlme(MockMlme::new());
1936
1937        let mut table = StorageVec::new();
1938        // neighbor on the correct network
1939        table
1940            .push(make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0))
1941            .unwrap();
1942        // neighbor on a different network
1943        table
1944            .push(make_neighbor(0xBBBB, 0x0001, 0x9999, 200, 0))
1945            .unwrap();
1946        nlme.nib().update_neighbor_table(|value| *value = table);
1947
1948        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
1949        assert_eq!(candidates.len(), 1);
1950        assert_eq!(candidates[0], 0);
1951    }
1952
1953    #[test]
1954    fn select_parent_filters_by_link_cost() {
1955        let (_guard, nlme) = make_nlme(MockMlme::new());
1956
1957        let mut table = StorageVec::new();
1958        // good LQI => low cost => eligible
1959        table
1960            .push(make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0))
1961            .unwrap();
1962        // bad LQI => high cost => filtered out
1963        table
1964            .push(make_neighbor(0xAAAA, 0x0001, 0x1234, 10, 0))
1965            .unwrap();
1966        nlme.nib().update_neighbor_table(|value| *value = table);
1967
1968        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
1969        assert_eq!(candidates.len(), 1);
1970        assert_eq!(candidates[0], 0);
1971    }
1972
1973    #[test]
1974    fn select_parent_filters_by_end_device_capacity() {
1975        let (_guard, nlme) = make_nlme(MockMlme::new());
1976
1977        let mut table = StorageVec::new();
1978        let mut n = make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0);
1979        n.end_device_capacity = false;
1980        table.push(n).unwrap();
1981        nlme.nib().update_neighbor_table(|value| *value = table);
1982
1983        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
1984        assert!(candidates.is_empty());
1985    }
1986
1987    #[test]
1988    fn select_parent_filters_by_router_capacity() {
1989        let (_guard, nlme) = make_nlme(MockMlme::new());
1990
1991        let mut table = StorageVec::new();
1992        let mut n = make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0);
1993        n.router_capacity = false;
1994        table.push(n).unwrap();
1995        nlme.nib().update_neighbor_table(|value| *value = table);
1996
1997        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), true);
1998        assert!(candidates.is_empty());
1999    }
2000
2001    #[test]
2002    fn select_parent_end_device_accepts_router_without_router_capacity() {
2003        // a router parent that accepts end devices but not routers
2004        // (router_capacity == false, end_device_capacity == true) must remain a
2005        // valid parent for an end-device join
2006        let (_guard, nlme) = make_nlme(MockMlme::new());
2007
2008        let mut table = StorageVec::new();
2009        let mut n = make_neighbor(0xAAAA, 0x1234, 0x1234, 200, 0);
2010        n.router_capacity = false;
2011        n.end_device_capacity = true;
2012        table.push(n).unwrap();
2013        nlme.nib().update_neighbor_table(|value| *value = table);
2014
2015        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
2016        assert_eq!(candidates.len(), 1);
2017    }
2018
2019    #[test]
2020    fn select_parent_sorts_by_depth_for_stack_profile_1() {
2021        let (_guard, nlme) = make_nlme(MockMlme::new());
2022        nlme.nib().update_stack_profile(|value| *value = 1);
2023
2024        let mut table = StorageVec::new();
2025        table
2026            .push(make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 3))
2027            .unwrap();
2028        table
2029            .push(make_neighbor(0xAAAA, 0x0001, 0x1234, 200, 1))
2030            .unwrap();
2031        table
2032            .push(make_neighbor(0xAAAA, 0x0002, 0x1234, 200, 2))
2033            .unwrap();
2034        nlme.nib().update_neighbor_table(|value| *value = table);
2035
2036        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
2037        assert_eq!(candidates.len(), 3);
2038        // sorted: depth 1 (idx 1), depth 2 (idx 2), depth 3 (idx 0)
2039        assert_eq!(candidates[0], 1);
2040        assert_eq!(candidates[1], 2);
2041        assert_eq!(candidates[2], 0);
2042    }
2043
2044    #[test]
2045    fn select_parent_filters_not_permitting_join() {
2046        let (_guard, nlme) = make_nlme(MockMlme::new());
2047
2048        let mut table = StorageVec::new();
2049        let mut n = make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0);
2050        n.permit_joining = false;
2051        table.push(n).unwrap();
2052        nlme.nib().update_neighbor_table(|value| *value = table);
2053
2054        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
2055        assert!(candidates.is_empty());
2056    }
2057
2058    #[test]
2059    fn select_parent_filters_non_potential_parent() {
2060        let (_guard, nlme) = make_nlme(MockMlme::new());
2061
2062        let mut table = StorageVec::new();
2063        let mut n = make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0);
2064        n.potential_parent = 0;
2065        table.push(n).unwrap();
2066        nlme.nib().update_neighbor_table(|value| *value = table);
2067
2068        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
2069        assert!(candidates.is_empty());
2070    }
2071
2072    #[test]
2073    fn select_parent_prefers_most_recent_update_id() {
2074        let (_guard, nlme) = make_nlme(MockMlme::new());
2075
2076        let mut table = StorageVec::new();
2077        let mut n1 = make_neighbor(0xAAAA, 0x0000, 0x1234, 200, 0);
2078        n1.update_id = 5;
2079        table.push(n1).unwrap();
2080        let mut n2 = make_neighbor(0xAAAA, 0x0001, 0x1234, 200, 0);
2081        n2.update_id = 3;
2082        table.push(n2).unwrap();
2083        nlme.nib().update_neighbor_table(|value| *value = table);
2084
2085        let candidates = nlme.select_parent_candidates(IeeeAddress(0x1234), false);
2086        assert_eq!(candidates.len(), 1);
2087        assert_eq!(candidates[0], 0);
2088    }
2089
2090    #[test]
2091    fn join_successful_association() {
2092        let mut mac = MockMlme::new();
2093        mac.expect_associate().returning(|_, _, _| {
2094            Ok(AssociationResponse {
2095                device_address: IeeeAddress(0),
2096                association_address: ShortAddress(0x1234),
2097                status: AssociationStatus::Successful,
2098            })
2099        });
2100
2101        let (_guard, nlme) = make_nlme(mac);
2102
2103        let mut table = StorageVec::new();
2104        table
2105            .push(make_neighbor(0xAAAA, 0x0000, 0xDEAD, 200, 0))
2106            .unwrap();
2107        nlme.nib().update_neighbor_table(|value| *value = table);
2108
2109        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2110
2111        assert_eq!(confirm.status, NlmeJoinStatus::Success);
2112        assert_eq!(confirm.network_address.0, 0x1234);
2113        assert_eq!(confirm.extended_pan_id.0, 0xDEAD);
2114        assert_eq!(confirm.channel, 11);
2115
2116        assert_eq!(*nlme.nib().network_address(), 0x1234);
2117        assert_eq!(*nlme.nib().extended_panid(), 0xDEAD);
2118        assert_eq!(*nlme.nib().panid(), 0xAAAA);
2119        assert_eq!(*nlme.nib().update_id(), 0);
2120
2121        let table = nlme.nib().neighbor_table();
2122        assert_eq!(table[0].relationship, 0x00);
2123    }
2124
2125    #[test]
2126    fn join_sets_nwk_update_id_from_parent() {
2127        let mut mac = MockMlme::new();
2128        mac.expect_associate().returning(|_, _, _| {
2129            Ok(AssociationResponse {
2130                device_address: IeeeAddress(0),
2131                association_address: ShortAddress(0x1234),
2132                status: AssociationStatus::Successful,
2133            })
2134        });
2135
2136        let (_guard, nlme) = make_nlme(mac);
2137
2138        let mut n = make_neighbor(0xAAAA, 0x0000, 0xDEAD, 200, 0);
2139        n.update_id = 7;
2140        let mut table = StorageVec::new();
2141        table.push(n).unwrap();
2142        nlme.nib().update_neighbor_table(|value| *value = table);
2143
2144        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2145        assert_eq!(confirm.status, NlmeJoinStatus::Success);
2146        assert_eq!(*nlme.nib().update_id(), 7);
2147    }
2148
2149    #[test]
2150    fn join_fails_when_no_candidates() {
2151        let mac = MockMlme::new();
2152        let (_guard, nlme) = make_nlme(mac);
2153        nlme.nib()
2154            .update_neighbor_table(|value| *value = StorageVec::new());
2155        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2156        assert_eq!(confirm.status, NlmeJoinStatus::NotPermitted);
2157    }
2158
2159    #[test]
2160    fn join_fails_when_already_joined() {
2161        let mac = MockMlme::new();
2162        let (_guard, nlme) = make_nlme(mac);
2163        nlme.nib().update_network_address(|value| *value = 0x0001);
2164
2165        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2166        assert_eq!(confirm.status, NlmeJoinStatus::InvalidRequest);
2167    }
2168
2169    #[test]
2170    fn join_skips_capacity_rejected_parent_tries_next() {
2171        let mut mac = MockMlme::new();
2172        let mut seq = mockall::Sequence::new();
2173        mac.expect_associate()
2174            .times(1)
2175            .in_sequence(&mut seq)
2176            .returning(|_, _, _| {
2177                Ok(AssociationResponse {
2178                    device_address: IeeeAddress(0),
2179                    association_address: ShortAddress(0),
2180                    status: AssociationStatus::NetworkAtCapacity,
2181                })
2182            });
2183        mac.expect_associate()
2184            .times(1)
2185            .in_sequence(&mut seq)
2186            .returning(|_, _, _| {
2187                Ok(AssociationResponse {
2188                    device_address: IeeeAddress(0),
2189                    association_address: ShortAddress(0x5678),
2190                    status: AssociationStatus::Successful,
2191                })
2192            });
2193
2194        let (_guard, nlme) = make_nlme(mac);
2195
2196        let mut table = StorageVec::new();
2197        table
2198            .push(make_neighbor(0xAAAA, 0x0000, 0xDEAD, 200, 0))
2199            .unwrap();
2200        table
2201            .push(make_neighbor(0xAAAA, 0x0001, 0xDEAD, 200, 0))
2202            .unwrap();
2203        nlme.nib().update_neighbor_table(|value| *value = table);
2204
2205        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2206        assert_eq!(confirm.status, NlmeJoinStatus::Success);
2207        assert_eq!(confirm.network_address.0, 0x5678);
2208
2209        let table = nlme.nib().neighbor_table();
2210        assert_eq!(table[0].potential_parent, 0);
2211        assert_eq!(table[1].relationship, 0x00);
2212    }
2213
2214    #[test]
2215    fn join_all_candidates_rejected() {
2216        let mut mac = MockMlme::new();
2217        mac.expect_associate().returning(|_, _, _| {
2218            Ok(AssociationResponse {
2219                device_address: IeeeAddress(0),
2220                association_address: ShortAddress(0),
2221                status: AssociationStatus::AccessDenied,
2222            })
2223        });
2224
2225        let (_guard, nlme) = make_nlme(mac);
2226
2227        let mut table = StorageVec::new();
2228        table
2229            .push(make_neighbor(0xAAAA, 0x0000, 0xDEAD, 200, 0))
2230            .unwrap();
2231        nlme.nib().update_neighbor_table(|value| *value = table);
2232
2233        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2234        assert_eq!(confirm.status, NlmeJoinStatus::PanAccessDenied);
2235        assert_eq!(confirm.network_address.0, 0xffff);
2236    }
2237
2238    #[test]
2239    fn join_mac_error_reported() {
2240        let mut mac = MockMlme::new();
2241        mac.expect_associate()
2242            .returning(|_, _, _| Err(MacError::NoAck));
2243
2244        let (_guard, nlme) = make_nlme(mac);
2245
2246        let mut table = StorageVec::new();
2247        table
2248            .push(make_neighbor(0xAAAA, 0x0000, 0xDEAD, 200, 0))
2249            .unwrap();
2250        nlme.nib().update_neighbor_table(|value| *value = table);
2251
2252        let confirm = block_on(nlme.join(default_join_request(0xDEAD)));
2253        assert_eq!(confirm.status, NlmeJoinStatus::MacError);
2254    }
2255
2256    #[test]
2257    fn join_invalid_rejoin_network() {
2258        let mac = MockMlme::new();
2259        let (_guard, nlme) = make_nlme(mac);
2260
2261        let mut req = default_join_request(0xDEAD);
2262        req.rejoin_network = RejoinNetwork::Orphan;
2263
2264        let confirm = block_on(nlme.join(req));
2265        assert_eq!(confirm.status, NlmeJoinStatus::InvalidRequest);
2266    }
2267
2268    fn rejoin_request(epid: u64) -> NlmeJoinRequest {
2269        NlmeJoinRequest {
2270            extended_pan_id: IeeeAddress(epid),
2271            rejoin_network: RejoinNetwork::NwkRejoin,
2272            capability_information: CapabilityInformation(0x80),
2273            security_enabled: true,
2274            // no scan: these exercise the remembered-parent path
2275            scan_channels: 0..0,
2276            scan_duration: 0,
2277        }
2278    }
2279
2280    /// Build the encrypted bytes of an inbound Rejoin Response command frame,
2281    /// as `poll_data` would deliver it from the parent.
2282    fn encrypted_rejoin_response(network_address: u16, status: u8) -> heapless::Vec<u8, 128> {
2283        let nib = nib::get_ref();
2284        let header = NwkHeader {
2285            frame_control: NwkFrameControl(0)
2286                .set_frame_type(NwkFrameType::NwkCommand)
2287                .set_protocol_version(2)
2288                .set_discover_route(DiscoverRoute::Suppress)
2289                .set_security_flag(true)
2290                .set_source_ieee_flag(true),
2291            destination: ShortAddress(*nib.network_address()),
2292            source: ShortAddress(0x0000),
2293            radius: 1,
2294            sequence_number: 0,
2295            destination_ieee: None,
2296            source_ieee: Some(*nib.ieee_address()),
2297            multicast_control: None,
2298            source_route_subframe: None,
2299        };
2300        let command = Command::RejoinResponse(RejoinResponse {
2301            network_address: ShortAddress(network_address),
2302            status,
2303        });
2304        let nwk_frame = NwkFrame::NwkCommand(NwkCommandFrame { header, command });
2305        let mut buf = heapless::Vec::<u8, 128>::new();
2306        buf.resize(128, 0).unwrap();
2307        let len = SecurityContext::get()
2308            .encrypt_nwk_frame_in_place(nwk_frame, &mut buf)
2309            .unwrap();
2310        buf.truncate(len);
2311        buf
2312    }
2313
2314    #[test]
2315    fn nwk_rejoin_not_joined_is_invalid() {
2316        let (_guard, nlme) = make_nlme(MockMlme::new());
2317
2318        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
2319        assert_eq!(confirm.status, NlmeJoinStatus::InvalidRequest);
2320    }
2321
2322    #[test]
2323    fn nwk_rejoin_without_security_is_sent_unsecured() {
2324        // 4.6.3.3.2: a Trust Center rejoin carries no NWK security
2325        let mut mac = MockMlme::new();
2326        mac.expect_transmit_data()
2327            .times(1)
2328            .withf(|_dest, payload| {
2329                let (header, _) = NwkHeader::try_read(payload, ()).unwrap();
2330                !header.frame_control.security_flag()
2331            })
2332            .returning(|_, _| Ok(()));
2333        mac.expect_poll_data()
2334            .returning(|_, _| Err(MacError::NoData));
2335
2336        let (_guard, nlme) = make_nlme(mac);
2337        seed_joined_nib(&nlme);
2338
2339        let mut req = rejoin_request(0xDEAD);
2340        req.security_enabled = false;
2341
2342        let confirm = block_on(nlme.join(req));
2343        assert_eq!(confirm.status, NlmeJoinStatus::MacError);
2344    }
2345
2346    #[test]
2347    fn nwk_rejoin_epid_mismatch_is_invalid() {
2348        let (_guard, nlme) = make_nlme(MockMlme::new());
2349        seed_joined_nib(&nlme);
2350
2351        let confirm = block_on(nlme.join(rejoin_request(0xBEEF)));
2352        assert_eq!(confirm.status, NlmeJoinStatus::InvalidRequest);
2353    }
2354
2355    #[test]
2356    fn nwk_rejoin_success_sends_request_and_updates_address() {
2357        let mut mac = MockMlme::new();
2358        mac.expect_transmit_data()
2359            .times(1)
2360            .withf(|dest, payload| {
2361                let mut buf = [0u8; 256];
2362                buf[..payload.len()].copy_from_slice(payload);
2363                let Ok(NwkFrame::NwkCommand(command_frame)) =
2364                    SecurityContext::get().decrypt_nwk_frame_in_place(&mut buf[..payload.len()])
2365                else {
2366                    return false;
2367                };
2368                let Command::RejoinRequest(request) = command_frame.command else {
2369                    return false;
2370                };
2371                *dest == Address::Short(PanId(0xAAAA), MacShortAddress(0x0000))
2372                    // rejoin_request() uses CapabilityInformation(0x80):
2373                    // allocate address set, device_type (end device) clear
2374                    && request.capability_information.device_type() == 0
2375                    && request.capability_information.allocate_address() == 1
2376            })
2377            .returning(|_, _| Ok(()));
2378        mac.expect_poll_data().times(1).returning(|_, buf| {
2379            let response = encrypted_rejoin_response(0x5678, 0x00);
2380            buf[..response.len()].copy_from_slice(&response);
2381            Ok((response.len(), 200u8))
2382        });
2383        // the assigned address has to reach the hardware filter
2384        mac.expect_configure()
2385            .times(1)
2386            .withf(|config| config.short_address == Some(ShortAddress(0x5678)))
2387            .returning(|_| ());
2388
2389        let (_guard, nlme) = make_nlme(mac);
2390        seed_joined_nib(&nlme);
2391
2392        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
2393        assert_eq!(confirm.status, NlmeJoinStatus::Success);
2394        assert_eq!(confirm.network_address, ShortAddress(0x5678));
2395        assert_eq!(*nlme.nib().network_address(), 0x5678);
2396    }
2397
2398    #[test]
2399    fn rejoin_response_from_receive_path_applies_address_and_signals() {
2400        // a concurrent receive loop may retrieve the response instead of the
2401        // rejoin procedure's own poll
2402        let (_guard, nlme) = make_nlme(MockMlme::new());
2403        seed_joined_nib(&nlme);
2404
2405        block_on(nlme.handle_nwk_command(
2406            &dummy_header(0x0000),
2407            Command::RejoinResponse(RejoinResponse {
2408                network_address: ShortAddress(0x5678),
2409                status: 0x00,
2410            }),
2411        ));
2412
2413        assert_eq!(*nlme.nib().network_address(), 0x5678);
2414        block_on(nlme.rejoin_response.wait());
2415    }
2416
2417    #[test]
2418    fn nwk_rejoin_network_at_capacity() {
2419        let mut mac = MockMlme::new();
2420        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
2421        mac.expect_poll_data().times(1).returning(|_, buf| {
2422            let response = encrypted_rejoin_response(0xffff, 0x01);
2423            buf[..response.len()].copy_from_slice(&response);
2424            Ok((response.len(), 200u8))
2425        });
2426
2427        let (_guard, nlme) = make_nlme(mac);
2428        seed_joined_nib(&nlme);
2429
2430        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
2431        assert_eq!(confirm.status, NlmeJoinStatus::PanAtCapacity);
2432    }
2433
2434    #[test]
2435    fn nwk_rejoin_no_response_is_mac_error() {
2436        let mut mac = MockMlme::new();
2437        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
2438        mac.expect_poll_data()
2439            .returning(|_, _| Err(MacError::NoData));
2440
2441        let (_guard, nlme) = make_nlme(mac);
2442        seed_joined_nib(&nlme);
2443
2444        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
2445        assert_eq!(confirm.status, NlmeJoinStatus::MacError);
2446    }
2447
2448    #[test]
2449    fn nwk_rejoin_transmit_failure_is_mac_error() {
2450        let mut mac = MockMlme::new();
2451        mac.expect_transmit_data()
2452            .times(1)
2453            .returning(|_, _| Err(MacError::NoAck));
2454
2455        let (_guard, nlme) = make_nlme(mac);
2456        seed_joined_nib(&nlme);
2457
2458        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
2459        assert_eq!(confirm.status, NlmeJoinStatus::MacError);
2460    }
2461
2462    /// A minimal NWK header for feeding `handle_nwk_command` in tests; the
2463    /// source address is the only field most handlers inspect.
2464    fn dummy_header(source: u16) -> NwkHeader<'static> {
2465        NwkHeader {
2466            frame_control: NwkFrameControl(0).set_frame_type(NwkFrameType::NwkCommand),
2467            destination: ShortAddress(0x0000),
2468            source: ShortAddress(source),
2469            radius: 1,
2470            sequence_number: 0,
2471            destination_ieee: None,
2472            source_ieee: None,
2473            multicast_control: None,
2474            source_route_subframe: None,
2475        }
2476    }
2477
2478    /// Seed the global NIB with a joined-network state: parent neighbor,
2479    /// addresses, and NWK security material.
2480    fn seed_joined_nib(nlme: &Nlme<MockMlme>) {
2481        use zigbee_types::ByteArray;
2482
2483        use crate::nwk::nib::NetworkSecurityMaterialDescriptor;
2484
2485        let nib = nlme.nib();
2486        nib.update_panid(|value| *value = 0xAAAA);
2487        nib.update_network_address(|value| *value = 0x1234);
2488        nib.update_extended_panid(|value| *value = 0xDEAD);
2489
2490        let mut table = StorageVec::new();
2491        let mut parent = make_neighbor(0xAAAA, 0x0000, 0xDEAD, 200, 0);
2492        parent.relationship = relationship::PARENT;
2493        table.push(parent).unwrap();
2494        nib.update_neighbor_table(|value| *value = table);
2495
2496        let mut set = StorageVec::new();
2497        set.push(NetworkSecurityMaterialDescriptor {
2498            key_seq_number: 0,
2499            outgoing_frame_counter: 1,
2500            incoming_frame_counter_set: StorageVec::new(),
2501            key: ByteArray([0x42; 16]),
2502            network_key_type: 0,
2503        })
2504        .unwrap();
2505        nib.update_security_material_set(|value| *value = set);
2506    }
2507
2508    #[test]
2509    fn send_end_device_timeout_request_encodes_command() {
2510        let mut mac = MockMlme::new();
2511        mac.expect_transmit_data()
2512            .times(1)
2513            .withf(|dest, payload| {
2514                assert_eq!(
2515                    *dest,
2516                    Address::Short(PanId(0xAAAA), MacShortAddress(0x0000))
2517                );
2518                // header is unencrypted; verify it directly
2519                let (header, _) = NwkHeader::try_read(payload, ()).unwrap();
2520                assert_eq!(header.frame_control.frame_type(), NwkFrameType::NwkCommand);
2521                assert!(header.frame_control.security_flag());
2522                assert!(header.frame_control.source_ieee_flag());
2523                assert_eq!(header.radius, 1);
2524                assert_eq!(header.destination, ShortAddress(0x0000));
2525                assert_eq!(header.source, ShortAddress(0x1234));
2526
2527                // decrypt in place to verify the command payload
2528                let mut buf = [0u8; 256];
2529                buf[..payload.len()].copy_from_slice(payload);
2530                let frame = SecurityContext::get()
2531                    .decrypt_nwk_frame_in_place(&mut buf[..payload.len()])
2532                    .unwrap();
2533                let NwkFrame::NwkCommand(command_frame) = frame else {
2534                    panic!("expected NWK command frame");
2535                };
2536                let Command::EndDeviceTimeoutRequest(request) = command_frame.command else {
2537                    panic!("expected end device timeout request");
2538                };
2539                assert_eq!(request.requested_timeout, 0x08);
2540                assert_eq!(request.end_device_configuration, 0x00);
2541                true
2542            })
2543            .returning(|_, _| Ok(()));
2544
2545        let (_guard, nlme) = make_nlme(mac);
2546        seed_joined_nib(&nlme);
2547
2548        block_on(nlme.send_end_device_timeout_request()).unwrap();
2549        assert_eq!(
2550            nlme.pending_timeout_request.load(Ordering::Relaxed),
2551            *nlme.nib().end_device_timeout_default()
2552        );
2553    }
2554
2555    #[test]
2556    fn send_end_device_timeout_request_not_joined() {
2557        let (_guard, nlme) = make_nlme(MockMlme::new());
2558        let result = block_on(nlme.send_end_device_timeout_request());
2559        assert!(matches!(result, Err(NetworkError::NotJoined)));
2560    }
2561
2562    #[test]
2563    fn end_device_timeout_response_success_updates_nib() {
2564        let (_guard, nlme) = make_nlme(MockMlme::new());
2565        nlme.pending_timeout_request.store(0x03, Ordering::Relaxed);
2566
2567        block_on(nlme.handle_nwk_command(
2568            &dummy_header(0x0000),
2569            Command::EndDeviceTimeoutResponse(EndDeviceTimeoutResponse {
2570                status: EndDeviceTimeoutResponse::STATUS_SUCCESS,
2571                parent_information: 0b011,
2572            }),
2573        ));
2574
2575        let nib = nlme.nib();
2576        assert_eq!(*nib.parent_information(), 0b011);
2577        assert_eq!(*nib.end_device_timeout(), 0x03);
2578        // pending request consumed
2579        assert_eq!(
2580            nlme.pending_timeout_request.load(Ordering::Relaxed),
2581            NO_PENDING_TIMEOUT
2582        );
2583    }
2584
2585    #[test]
2586    fn end_device_timeout_response_rejected_leaves_nib_untouched() {
2587        let (_guard, nlme) = make_nlme(MockMlme::new());
2588        nlme.pending_timeout_request.store(0x03, Ordering::Relaxed);
2589
2590        block_on(nlme.handle_nwk_command(
2591            &dummy_header(0x0000),
2592            Command::EndDeviceTimeoutResponse(EndDeviceTimeoutResponse {
2593                status: EndDeviceTimeoutResponse::STATUS_INCORRECT_VALUE,
2594                parent_information: 0b001,
2595            }),
2596        ));
2597
2598        let nib = nlme.nib();
2599        assert_eq!(*nib.parent_information(), 0x00);
2600        assert_eq!(*nib.end_device_timeout(), NO_PENDING_TIMEOUT);
2601    }
2602
2603    #[test]
2604    fn end_device_timeout_response_unsolicited_ignored() {
2605        let (_guard, nlme) = make_nlme(MockMlme::new());
2606
2607        block_on(nlme.handle_nwk_command(
2608            &dummy_header(0x0000),
2609            Command::EndDeviceTimeoutResponse(EndDeviceTimeoutResponse {
2610                status: EndDeviceTimeoutResponse::STATUS_SUCCESS,
2611                parent_information: 0b001,
2612            }),
2613        ));
2614
2615        let nib = nlme.nib();
2616        assert_eq!(*nib.parent_information(), 0x00);
2617        assert_eq!(*nib.end_device_timeout(), NO_PENDING_TIMEOUT);
2618    }
2619
2620    #[test]
2621    fn leave_not_joined_is_invalid() {
2622        let (_guard, nlme) = make_nlme(MockMlme::new());
2623
2624        let confirm = block_on(nlme.leave(NlmeLeaveRequest {
2625            device_address: None,
2626            remove_children: false,
2627            rejoin: false,
2628        }));
2629        assert_eq!(confirm.status, NlmeLeaveStatus::InvalidRequest);
2630    }
2631
2632    #[test]
2633    fn leave_other_device_is_unknown() {
2634        let (_guard, nlme) = make_nlme(MockMlme::new());
2635        seed_joined_nib(&nlme);
2636
2637        let confirm = block_on(nlme.leave(NlmeLeaveRequest {
2638            device_address: Some(IeeeAddress(0x1111_1111_1111_1111)),
2639            remove_children: false,
2640            rejoin: false,
2641        }));
2642        assert_eq!(confirm.status, NlmeLeaveStatus::UnknownDevice);
2643    }
2644
2645    #[test]
2646    fn leave_self_end_device_unicasts_to_parent_and_clears_nib() {
2647        let mut mac = MockMlme::new();
2648        mac.expect_transmit_data()
2649            .times(1)
2650            .withf(|dest, payload| {
2651                assert_eq!(
2652                    *dest,
2653                    Address::Short(PanId(0xAAAA), MacShortAddress(0x0000))
2654                );
2655                let mut buf = [0u8; 256];
2656                buf[..payload.len()].copy_from_slice(payload);
2657                let frame = SecurityContext::get()
2658                    .decrypt_nwk_frame_in_place(&mut buf[..payload.len()])
2659                    .unwrap();
2660                let NwkFrame::NwkCommand(command_frame) = frame else {
2661                    panic!("expected NWK command frame");
2662                };
2663                let Command::Leave(leave) = command_frame.command else {
2664                    panic!("expected leave command");
2665                };
2666                assert!(!leave.command_options.request());
2667                assert!(!leave.command_options.rejoin());
2668                assert!(!leave.command_options.remove_children());
2669                true
2670            })
2671            .returning(|_, _| Ok(()));
2672
2673        let (_guard, nlme) = make_nlme(mac);
2674        seed_joined_nib(&nlme);
2675
2676        // 3.6.1.10.1: an end device sends the remove children sub-field as 0
2677        // even when the request asked for it
2678        let confirm = block_on(nlme.leave(NlmeLeaveRequest {
2679            device_address: None,
2680            remove_children: true,
2681            rejoin: false,
2682        }));
2683        assert_eq!(confirm.status, NlmeLeaveStatus::Success);
2684        assert_eq!(confirm.device_address, None);
2685
2686        let nib = nlme.nib();
2687        assert_eq!(*nib.network_address(), 0xffff);
2688        assert_eq!(*nib.extended_panid(), 0);
2689        assert!(nib.neighbor_table().is_empty());
2690        assert!(nib.security_material_set().is_empty());
2691    }
2692
2693    #[test]
2694    fn leave_self_clears_nib_even_when_transmit_fails() {
2695        let mut mac = MockMlme::new();
2696        mac.expect_transmit_data()
2697            .times(1)
2698            .returning(|_, _| Err(MacError::NoAck));
2699
2700        let (_guard, nlme) = make_nlme(mac);
2701        seed_joined_nib(&nlme);
2702
2703        let confirm = block_on(nlme.leave(NlmeLeaveRequest {
2704            device_address: None,
2705            remove_children: false,
2706            rejoin: false,
2707        }));
2708        // 3.6.1.10.1: the local leave runs regardless of the confirm status
2709        assert_eq!(confirm.status, NlmeLeaveStatus::MacError);
2710        assert_eq!(*nlme.nib().network_address(), NWK_UNASSIGNED_ADDRESS);
2711        assert!(nlme.nib().security_material_set().is_empty());
2712    }
2713
2714    #[test]
2715    fn leave_request_to_broadcast_address_is_dropped() {
2716        let (_guard, nlme) = make_nlme(MockMlme::new());
2717        seed_joined_nib(&nlme);
2718
2719        let header = NwkHeader {
2720            destination: ShortAddress(0xfffd),
2721            ..dummy_header(0x0000)
2722        };
2723        let leave = Leave {
2724            command_options: LeaveCommandOptions(0).set_request(true),
2725        };
2726        // no transmit_data expectation set: a call here would panic the mock
2727        block_on(nlme.handle_nwk_command(&header, Command::Leave(leave)));
2728
2729        assert_eq!(*nlme.nib().network_address(), 0x1234);
2730    }
2731
2732    #[test]
2733    fn leave_notification_from_parent_raises_indication() {
2734        let (_guard, nlme) = make_nlme(MockMlme::new());
2735        seed_joined_nib(&nlme);
2736
2737        let leave = Leave {
2738            command_options: LeaveCommandOptions(0).set_rejoin(true),
2739        };
2740        block_on(nlme.handle_nwk_command(&dummy_header(0x0000), Command::Leave(leave)));
2741
2742        // 3.6.1.10.3: removed by the parent -> NULL device address
2743        assert_eq!(
2744            nlme.take_leave_indication(),
2745            Some(NlmeLeaveIndication {
2746                device_address: None,
2747                rejoin: true,
2748            })
2749        );
2750    }
2751
2752    #[test]
2753    fn leave_self_with_rejoin_leaves_nib_untouched() {
2754        let mut mac = MockMlme::new();
2755        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
2756
2757        let (_guard, nlme) = make_nlme(mac);
2758        seed_joined_nib(&nlme);
2759
2760        let confirm = block_on(nlme.leave(NlmeLeaveRequest {
2761            device_address: None,
2762            remove_children: false,
2763            rejoin: true,
2764        }));
2765        assert_eq!(confirm.status, NlmeLeaveStatus::Success);
2766
2767        let nib = nlme.nib();
2768        // rejoin requested: the NIB is left intact for the (not yet
2769        // implemented) rejoin procedure, aside from the extended PAN id
2770        // which 3.6.1.10.1 clears unconditionally for an end device
2771        assert_eq!(*nib.network_address(), 0x1234);
2772        assert_eq!(*nib.extended_panid(), 0);
2773        assert!(!nib.neighbor_table().is_empty());
2774    }
2775
2776    #[test]
2777    fn leave_notification_removes_only_the_notifying_neighbor() {
2778        let (_guard, nlme) = make_nlme(MockMlme::new());
2779        seed_joined_nib(&nlme);
2780        nlme.nib().update_neighbor_table(|table| {
2781            let _ = table.push(make_neighbor(0xAAAA, 0x5678, 0xBEEF, 200, 1));
2782        });
2783        assert_eq!(nlme.nib().neighbor_table().len(), 2);
2784
2785        let leave = Leave {
2786            command_options: LeaveCommandOptions(0),
2787        };
2788        block_on(nlme.handle_nwk_command(&dummy_header(0x5678), Command::Leave(leave)));
2789
2790        let nib = nlme.nib();
2791        assert_eq!(nib.neighbor_table().len(), 1);
2792        assert_eq!(
2793            nib.neighbor_table()[0].network_address,
2794            ShortAddress(0x0000)
2795        );
2796        // not our parent -> we are still joined
2797        assert_ne!(*nib.network_address(), 0xffff);
2798    }
2799
2800    #[test]
2801    fn leave_notification_from_parent_marks_device_removed() {
2802        let (_guard, nlme) = make_nlme(MockMlme::new());
2803        seed_joined_nib(&nlme);
2804
2805        let leave = Leave {
2806            command_options: LeaveCommandOptions(0),
2807        };
2808        block_on(nlme.handle_nwk_command(&dummy_header(0x0000), Command::Leave(leave)));
2809
2810        let nib = nlme.nib();
2811        assert_eq!(*nib.extended_panid(), 0);
2812        assert!(nib.neighbor_table().is_empty());
2813    }
2814
2815    #[test]
2816    fn leave_request_from_parent_triggers_self_removal() {
2817        let mut mac = MockMlme::new();
2818        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
2819
2820        let (_guard, nlme) = make_nlme(mac);
2821        seed_joined_nib(&nlme);
2822
2823        let leave = Leave {
2824            command_options: LeaveCommandOptions(0).set_request(true),
2825        };
2826        block_on(nlme.handle_nwk_command(&dummy_header(0x0000), Command::Leave(leave)));
2827
2828        assert_eq!(*nlme.nib().network_address(), 0xffff);
2829    }
2830
2831    #[test]
2832    fn leave_request_from_non_parent_is_ignored() {
2833        let (_guard, nlme) = make_nlme(MockMlme::new());
2834        seed_joined_nib(&nlme);
2835
2836        let leave = Leave {
2837            command_options: LeaveCommandOptions(0).set_request(true),
2838        };
2839        // no transmit_data expectation set: a call here would panic the mock
2840        block_on(nlme.handle_nwk_command(&dummy_header(0x9999), Command::Leave(leave)));
2841
2842        assert_eq!(*nlme.nib().network_address(), 0x1234);
2843    }
2844
2845    #[test]
2846    fn leave_request_dropped_for_coordinator() {
2847        let (_guard, nlme) = make_nlme(MockMlme::new());
2848        seed_joined_nib(&nlme);
2849        nlme.nib().update_network_address(|value| *value = 0x0000);
2850
2851        let leave = Leave {
2852            command_options: LeaveCommandOptions(0).set_request(true),
2853        };
2854        // no transmit_data expectation set: a call here would panic the mock
2855        block_on(nlme.handle_nwk_command(&dummy_header(0x0000), Command::Leave(leave)));
2856
2857        assert_eq!(*nlme.nib().network_address(), 0x0000);
2858    }
2859
2860    #[test]
2861    fn negotiated_poll_interval() {
2862        let (_guard, nlme) = make_nlme(MockMlme::new());
2863        let nib = nlme.nib();
2864
2865        // not negotiated
2866        assert_eq!(nlme.negotiated_poll_interval_ms(), None);
2867
2868        // negotiated 2 min with MAC data poll keepalive: 120 s / 3 = 40 s
2869        nib.update_end_device_timeout(|value| *value = 1);
2870        nib.update_parent_information(|value| {
2871            *value = EndDeviceTimeoutResponse::MAC_DATA_POLL_KEEPALIVE;
2872        });
2873        assert_eq!(nlme.negotiated_poll_interval_ms(), Some(40_000));
2874
2875        // parent without MAC data poll keepalive support
2876        nib.update_parent_information(|value| {
2877            *value = EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE;
2878        });
2879        assert_eq!(nlme.negotiated_poll_interval_ms(), None);
2880    }
2881
2882    #[test]
2883    fn keepalive_method_follows_parent_information() {
2884        let (_guard, nlme) = make_nlme(MockMlme::new());
2885        let nib = nlme.nib();
2886
2887        // no negotiated timeout
2888        assert_eq!(nlme.keepalive_method(), KeepaliveMethod::None);
2889
2890        nib.update_end_device_timeout(|value| *value = 1);
2891        nib.update_parent_information(|value| {
2892            *value = EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE;
2893        });
2894        assert_eq!(nlme.keepalive_method(), KeepaliveMethod::TimeoutRequest);
2895
2896        // bit 0 takes precedence over bit 1
2897        nib.update_parent_information(|value| {
2898            *value = EndDeviceTimeoutResponse::MAC_DATA_POLL_KEEPALIVE
2899                | EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE;
2900        });
2901        assert_eq!(nlme.keepalive_method(), KeepaliveMethod::MacDataPoll);
2902    }
2903
2904    #[test]
2905    fn local_timeout_expiry_raises_parent_link_failure() {
2906        let (_guard, nlme) = make_nlme(MockMlme::new());
2907        seed_joined_nib(&nlme);
2908        let nib = nlme.nib();
2909
2910        // no negotiated timeout: nothing to track
2911        assert!(!nlme.tick_parent_timeout(10_000));
2912        assert!(nlme.take_nwk_status_indication().is_none());
2913
2914        // 10 s timeout, refreshed by the negotiation
2915        nib.update_end_device_timeout(|value| *value = 0);
2916        nib.update_parent_information(|value| {
2917            *value = EndDeviceTimeoutResponse::MAC_DATA_POLL_KEEPALIVE;
2918        });
2919        nlme.refresh_parent_timeout();
2920
2921        assert!(!nlme.tick_parent_timeout(4_000));
2922        assert!(!nlme.tick_parent_timeout(4_000));
2923        assert!(nlme.tick_parent_timeout(4_000));
2924
2925        let indication = nlme
2926            .take_nwk_status_indication()
2927            .expect("indication raised");
2928        assert_eq!(indication.status, NetworkStatusCode::ParentLinkFailure);
2929        assert_eq!(indication.network_address, ShortAddress(0x0000));
2930
2931        // expiry stops the tracking: it fires once, until the next keepalive
2932        assert!(!nlme.tick_parent_timeout(4_000));
2933        assert!(nlme.take_nwk_status_indication().is_none());
2934    }
2935
2936    #[test]
2937    fn keepalive_without_response_raises_parent_link_failure() {
2938        let mut mac = MockMlme::new();
2939        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
2940        mac.expect_poll_data()
2941            .returning(|_, _| Err(MacError::NoData));
2942
2943        let (_guard, nlme) = make_nlme(mac);
2944        seed_joined_nib(&nlme);
2945        let nib = nlme.nib();
2946        nib.update_end_device_timeout(|value| *value = 1);
2947        nib.update_parent_information(|value| {
2948            *value = EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE;
2949        });
2950
2951        let result = block_on(nlme.send_keepalive());
2952        assert!(matches!(result, Err(NetworkError::ParentLinkFailure)));
2953        assert_eq!(
2954            nlme.take_nwk_status_indication().map(|i| i.status),
2955            Some(NetworkStatusCode::ParentLinkFailure)
2956        );
2957    }
2958
2959    #[test]
2960    fn keepalive_response_refreshes_local_timeout() {
2961        // the parent answers the keepalive on the next poll
2962        let mut mac = MockMlme::new();
2963        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
2964        mac.expect_poll_data().returning(|_, buf| {
2965            let frame = encrypted_timeout_response(EndDeviceTimeoutResponse::STATUS_SUCCESS);
2966            buf[..frame.len()].copy_from_slice(&frame);
2967            Ok((frame.len(), 200))
2968        });
2969
2970        let (_guard, nlme) = make_nlme(mac);
2971        seed_joined_nib(&nlme);
2972        let nib = nlme.nib();
2973        // request and negotiate the 120 s timeout enumeration
2974        nib.update_end_device_timeout_default(|value| *value = 1);
2975        nib.update_end_device_timeout(|value| *value = 1);
2976        nib.update_parent_information(|value| {
2977            *value = EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE;
2978        });
2979
2980        assert!(block_on(nlme.send_keepalive()).is_ok());
2981        assert!(nlme.take_nwk_status_indication().is_none());
2982        // the negotiated 120 s are being tracked again
2983        assert!(!nlme.tick_parent_timeout(119_000));
2984        assert!(nlme.tick_parent_timeout(1_000));
2985    }
2986
2987    #[test]
2988    fn repeated_transmit_failures_report_parent_link_failure() {
2989        let mut mac = MockMlme::new();
2990        mac.expect_transmit_data()
2991            .returning(|_, _| Err(MacError::NoAck));
2992
2993        let (_guard, nlme) = make_nlme(mac);
2994        seed_joined_nib(&nlme);
2995
2996        // 3.6.3.7: a single failure does not condemn the link
2997        for _ in 1..MAX_PARENT_TRANSMIT_FAILURES {
2998            assert!(matches!(
2999                block_on(nlme.send_data(ShortAddress(0x0000), true, &[1, 2, 3])),
3000                Err(NetworkError::MacError(_))
3001            ));
3002            assert!(nlme.take_nwk_status_indication().is_none());
3003        }
3004
3005        // 3.6.3.7.1: the failed link to the parent is reported as 0x09
3006        assert!(matches!(
3007            block_on(nlme.send_data(ShortAddress(0x0000), true, &[1, 2, 3])),
3008            Err(NetworkError::ParentLinkFailure)
3009        ));
3010        assert_eq!(
3011            nlme.take_nwk_status_indication().map(|i| i.status),
3012            Some(NetworkStatusCode::ParentLinkFailure)
3013        );
3014        // the counter restarts, so the next failure is not reported at once
3015        assert!(matches!(
3016            block_on(nlme.send_data(ShortAddress(0x0000), true, &[1, 2, 3])),
3017            Err(NetworkError::MacError(_))
3018        ));
3019    }
3020
3021    #[test]
3022    fn successful_transmission_clears_the_failure_counter() {
3023        let mut mac = MockMlme::new();
3024        mac.expect_transmit_data()
3025            .times(1)
3026            .returning(|_, _| Err(MacError::NoAck));
3027        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
3028
3029        let (_guard, nlme) = make_nlme(mac);
3030        seed_joined_nib(&nlme);
3031
3032        let _ = block_on(nlme.send_data(ShortAddress(0x0000), true, &[1, 2, 3]));
3033        assert!(block_on(nlme.send_data(ShortAddress(0x0000), true, &[1, 2, 3])).is_ok());
3034
3035        let table = nlme.nib().neighbor_table();
3036        let parent = table
3037            .iter()
3038            .find(|n| n.relationship == relationship::PARENT)
3039            .expect("parent");
3040        assert_eq!(parent.transmit_failure, 0);
3041    }
3042
3043    #[test]
3044    fn select_rejoin_candidates_ignores_permit_joining() {
3045        let (_guard, nlme) = make_nlme(MockMlme::new());
3046        let mut closed = make_neighbor(0xAAAA, 0x1234, 0xDEAD, 200, 1);
3047        closed.permit_joining = false;
3048        nlme.nib().update_neighbor_table(|table| {
3049            let _ = table.push(closed);
3050        });
3051
3052        // a closed network still accepts a device it already knows (3.6.1.4.2)
3053        assert!(
3054            nlme.select_parent_candidates(IeeeAddress(0xDEAD), false)
3055                .is_empty()
3056        );
3057        assert_eq!(
3058            nlme.select_rejoin_candidates(IeeeAddress(0xDEAD), false),
3059            heapless::Vec::<usize, 16>::from_slice(&[0]).unwrap()
3060        );
3061    }
3062
3063    #[test]
3064    fn rejoin_scans_when_the_known_parent_is_gone() {
3065        let mut mac = MockMlme::new();
3066        // the remembered parent no longer answers, so a scan follows
3067        mac.expect_transmit_data()
3068            .times(1)
3069            .returning(|_, _| Err(MacError::NoAck));
3070        mac.expect_scan_network().times(1).returning(|_, _, _| {
3071            Ok(ScanResult {
3072                scan_type: ScanType::Active,
3073                pan_descriptor: Default::default(),
3074            })
3075        });
3076
3077        let (_guard, nlme) = make_nlme(mac);
3078        seed_joined_nib(&nlme);
3079
3080        let mut request = rejoin_request(0xDEAD);
3081        request.scan_channels = 20..21;
3082        let confirm = block_on(nlme.join(request));
3083
3084        // the scan found no beacon of the remembered network
3085        assert_eq!(confirm.status, NlmeJoinStatus::NotPermitted);
3086    }
3087
3088    #[test]
3089    fn adopt_parent_follows_the_candidate_channel() {
3090        let mut mac = MockMlme::new();
3091        mac.expect_configure()
3092            .times(1)
3093            .withf(|config| config.channel == Some(20))
3094            .returning(|_| ());
3095
3096        let (_guard, nlme) = make_nlme(mac);
3097        seed_joined_nib(&nlme);
3098        let mut candidate = make_neighbor(0xAAAA, 0x1234, 0xDEAD, 200, 1);
3099        candidate.logical_channel = 20;
3100        candidate.update_id = 7;
3101        nlme.nib().update_neighbor_table(|table| {
3102            let _ = table.push(candidate);
3103        });
3104
3105        let adopted = block_on(nlme.adopt_parent(1));
3106
3107        assert_eq!(adopted, Some((ShortAddress(0x1234), 20)));
3108        assert_eq!(nlme.parent_short_address().unwrap(), ShortAddress(0x1234));
3109        assert_eq!(*nlme.nib().update_id(), 7);
3110        // the previous parent is demoted: only one entry is the parent
3111        let table = nlme.nib().neighbor_table();
3112        assert_eq!(
3113            table
3114                .iter()
3115                .filter(|n| n.relationship == relationship::PARENT)
3116                .count(),
3117            1
3118        );
3119    }
3120
3121    #[test]
3122    fn rejoin_without_scan_channels_keeps_the_remembered_parent_failure() {
3123        let mut mac = MockMlme::new();
3124        mac.expect_transmit_data()
3125            .times(1)
3126            .returning(|_, _| Err(MacError::NoAck));
3127        // no scan_network expectation: a call here would panic the mock
3128
3129        let (_guard, nlme) = make_nlme(mac);
3130        seed_joined_nib(&nlme);
3131
3132        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
3133        assert_eq!(confirm.status, NlmeJoinStatus::MacError);
3134    }
3135
3136    #[test]
3137    fn leave_request_from_parent_raises_indication_with_rejoin_flag() {
3138        let mut mac = MockMlme::new();
3139        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
3140
3141        let (_guard, nlme) = make_nlme(mac);
3142        seed_joined_nib(&nlme);
3143
3144        let leave = Leave {
3145            command_options: LeaveCommandOptions(0).set_request(true).set_rejoin(true),
3146        };
3147        block_on(nlme.handle_nwk_command(&dummy_header(0x0000), Command::Leave(leave)));
3148
3149        // 3.2.2.19: removed by the parent -> NULL device address; the higher
3150        // layer drives the rejoin (3.6.1.10.4 step 1)
3151        assert_eq!(
3152            nlme.take_leave_indication(),
3153            Some(NlmeLeaveIndication {
3154                device_address: None,
3155                rejoin: true,
3156            })
3157        );
3158    }
3159
3160    #[test]
3161    fn rejoin_after_leave_accepts_the_requested_extended_pan_id() {
3162        let mut mac = MockMlme::new();
3163        mac.expect_transmit_data().times(1).returning(|_, _| Ok(()));
3164        mac.expect_poll_data().returning(|_, buf| {
3165            let frame = encrypted_rejoin_response(0x5678, 0x00);
3166            buf[..frame.len()].copy_from_slice(&frame);
3167            Ok((frame.len(), 200))
3168        });
3169        mac.expect_configure().times(1).returning(|_| ());
3170
3171        let (_guard, nlme) = make_nlme(mac);
3172        seed_joined_nib(&nlme);
3173        // a leave zeroed the extended PAN id (3.6.1.10.1)
3174        nlme.nib().update_extended_panid(|value| *value = 0);
3175
3176        let confirm = block_on(nlme.join(rejoin_request(0xDEAD)));
3177
3178        assert_eq!(confirm.status, NlmeJoinStatus::Success);
3179        assert_eq!(*nlme.nib().extended_panid(), 0xDEAD);
3180    }
3181
3182    /// An encrypted End Device Timeout Response as the parent sends it.
3183    fn encrypted_timeout_response(status: u8) -> heapless::Vec<u8, 128> {
3184        let nib = nib::get_ref();
3185        let header = NwkHeader {
3186            frame_control: NwkFrameControl(0)
3187                .set_frame_type(NwkFrameType::NwkCommand)
3188                .set_protocol_version(2)
3189                .set_discover_route(DiscoverRoute::Suppress)
3190                .set_security_flag(true)
3191                .set_source_ieee_flag(true),
3192            destination: ShortAddress(*nib.network_address()),
3193            source: ShortAddress(0x0000),
3194            radius: 1,
3195            sequence_number: 0,
3196            destination_ieee: None,
3197            source_ieee: Some(*nib.ieee_address()),
3198            multicast_control: None,
3199            source_route_subframe: None,
3200        };
3201        let command = Command::EndDeviceTimeoutResponse(EndDeviceTimeoutResponse {
3202            status,
3203            parent_information: EndDeviceTimeoutResponse::TIMEOUT_REQUEST_KEEPALIVE,
3204        });
3205        let nwk_frame = NwkFrame::NwkCommand(NwkCommandFrame { header, command });
3206        let mut buf = heapless::Vec::<u8, 128>::new();
3207        buf.resize(128, 0).unwrap();
3208        let len = SecurityContext::get()
3209            .encrypt_nwk_frame_in_place(nwk_frame, &mut buf)
3210            .unwrap();
3211        buf.truncate(len);
3212        buf
3213    }
3214}