From 496006ceac4e089106872ea64f13adb61cd40b73 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:29:27 +0000 Subject: [PATCH 01/19] Report the stack's own tree depth in beacons and Mgmt_Lqi_rsp --- crates/ziggurat-driver/src/zigbee_stack.rs | 15 +++++++++++++++ crates/ziggurat-driver/src/zigbee_stack/mac.rs | 2 +- crates/ziggurat-driver/src/zigbee_stack/zdp.rs | 11 ++++++++--- crates/ziggurat-protocol/src/bridge.rs | 1 + crates/ziggurat-protocol/src/wire.rs | 5 ++++- 5 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 832cc811..7effc0a2 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -266,6 +266,9 @@ pub struct NetworkConfig { /// The radio transmit power in dBm pub tx_power: i8, pub source_routing: bool, + /// A router's tree depth: one more than its parent's when it joined. The + /// coordinator's is always 0, whatever this says. + pub depth: u8, } /// The frame a send holds, as enqueued. @@ -477,6 +480,8 @@ pub struct State { pub role: NwkDeviceType, pub capability_information: NwkCapabilityInformation, pub nwk_manager_addr: Nwk, + /// Our tree depth, advertised in beacons. The coordinator is the root, at 0. + pub depth: u8, pub ieee_address: Eui64, pub network_address: Nwk, @@ -507,6 +512,12 @@ pub struct State { impl State { pub fn new(config: &NetworkConfig, aps_counter: u8) -> Self { + assert!( + config.depth <= MAX_DEPTH, + "depth {} is deeper than nwkcMaxDepth", + config.depth + ); + Self { core: Mutex::new(ZigbeeCore { nib: Nib { @@ -553,6 +564,10 @@ impl State { hack_force_route_discovery: false, role: config.role, + depth: match config.role { + NwkDeviceType::Coordinator => 0, + NwkDeviceType::Router | NwkDeviceType::EndDevice => config.depth, + }, capability_information: NwkCapabilityInformation { alternate_pan_coordinator: false, device_type: match config.role { diff --git a/crates/ziggurat-driver/src/zigbee_stack/mac.rs b/crates/ziggurat-driver/src/zigbee_stack/mac.rs index 46c0aa34..34335f34 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/mac.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/mac.rs @@ -152,7 +152,7 @@ impl ZigbeeStack { protocol_version: PROTOCOL_VERSION, reserved1: 0b00, router_capacity: true, - device_depth: 0, + device_depth: self.state.depth, end_device_capacity, extended_pan_id: self.state.extended_pan_id, tx_offset: 0xFFFFFF, diff --git a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 046d840f..68fafc2d 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -106,9 +106,14 @@ impl ZigbeeStack { _ => ZdpAffinity::NoneOfTheAbove, }, permit_joining: ZdpPermitJoining::Unknown, - // We are the coordinator (tree depth 0), so every neighbor of - // ours sits at depth 1 - depth: 1, + // Spec Table 2-102: the neighbor's tree depth. We know only the + // coordinator's, the root's, and our children's, one below ours. + // Other neighbors are reported as if they were our children + depth: if entry.device_type == NwkDeviceType::Coordinator { + 0 + } else { + (self.state.depth + 1).min(MAX_DEPTH) + }, lqa: entry.lqas.median().unwrap_or(0), }) .collect(); diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 05a23e45..92b78a7d 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -56,6 +56,7 @@ pub fn network_config(payload: &ConfigurePayload) -> NetworkConfig { }), tx_power: state.tx_power, source_routing: payload.source_routing, + depth: payload.depth, } } diff --git a/crates/ziggurat-protocol/src/wire.rs b/crates/ziggurat-protocol/src/wire.rs index 70eaf8f7..f79c2ebf 100644 --- a/crates/ziggurat-protocol/src/wire.rs +++ b/crates/ziggurat-protocol/src/wire.rs @@ -298,7 +298,10 @@ pub struct NetworkState { pub struct ConfigurePayload { pub role: NodeRole, pub source_routing: bool, - pub reserved: u7, + /// A router's tree depth; the coordinator's is always 0. Older clients leave these + /// bits reserved, as 0. + pub depth: u4, + pub reserved: u3, pub state: NetworkState, } From 417f7af19b7c72a5133c711e8d4dca0c9274227c Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:37:00 +0000 Subject: [PATCH 02/19] Turn concentrator behavior on and off at runtime --- crates/ziggurat-driver/src/zigbee_stack.rs | 24 ++-- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 2 +- .../ziggurat-driver/src/zigbee_stack/route.rs | 108 +++++++++++------- .../ziggurat-driver/src/zigbee_stack/sends.rs | 6 +- crates/ziggurat-protocol/src/bridge.rs | 2 +- 5 files changed, 86 insertions(+), 56 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 7effc0a2..6bc88e19 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -265,7 +265,8 @@ pub struct NetworkConfig { pub tclk_seed: Option, /// The radio transmit power in dBm pub tx_power: i8, - pub source_routing: bool, + /// Whether we start out as a concentrator (see [`ZigbeeStack::set_concentrator`]). + pub concentrator: bool, /// A router's tree depth: one more than its parent's when it joined. The /// coordinator's is always 0, whatever this says. pub depth: u8, @@ -367,6 +368,10 @@ pub struct Nib { pub nwk_security: NwkSecurity, /// The EUI64-to-network-address map, one owner per network address pub address_map: AddressMap, + /// `nwkIsConcentrator`: we advertise many-to-one routes to ourselves and + /// source-route through the route records they bring back. Whoever controls the + /// node decides, at any time. + pub is_concentrator: bool, } impl Nib { @@ -487,7 +492,6 @@ pub struct State { pub network_address: Nwk, pub extended_pan_id: Eui64, - pub is_concentrator: bool, pub security_level: u8, /// A flag that determines if a timestamp indication is provided on incoming and @@ -536,6 +540,7 @@ impl State { FRAME_COUNTER_NOTIFY_INTERVAL, ), address_map: AddressMap::new(config.network_address, config.ieee_address), + is_concentrator: config.concentrator, }, aib: Aib { aps_counter, @@ -586,7 +591,6 @@ impl State { nwk_manager_addr: Nwk(0x0000), network_address: config.network_address, extended_pan_id: config.extended_pan_id, - is_concentrator: config.source_routing, security_level: 5, time_stamp: false, leave_request_allowed: false, @@ -742,6 +746,9 @@ pub struct ZigbeeStack { /// Wakes the many-to-one route request task when its next advertisement moved /// earlier pub(crate) mtorr_wake: Notify, + /// Wakes the many-to-one advertiser when the client turns concentrator behavior on + /// or off + pub(crate) concentrator_changed: Notify, /// Signaled whenever a link status command is digested; the MTORR startup wait /// uses it to advertise as soon as a neighbor link is established @@ -895,6 +902,7 @@ impl ZigbeeStack { src_match_written: Mutex::new(SrcMatchTable::default()), parent_annce_received: Mutex::new(None), mtorr_wake: Notify::new(), + concentrator_changed: Notify::new(), link_status_received: Notify::new(), link_status_wake: Notify::new(), address_conflict_wake: Notify::new(), @@ -1149,12 +1157,10 @@ impl ZigbeeStack { }); // Advertise many-to-one routes to ourselves so that devices can route inbound - // traffic without per-device route discoveries - if self.state.is_concentrator { - self.spawn_tracked(|arc_self| async move { - arc_self.periodic_many_to_one_route_request_task().await; - }); - } + // traffic without per-device route discoveries, while we are a concentrator + self.spawn_tracked(|arc_self| async move { + arc_self.periodic_many_to_one_route_request_task().await; + }); // Reprogram the radio whenever it resets out from under us self.spawn_tracked(|arc_self| async move { diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 078ee6cb..8f2500c1 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -410,7 +410,7 @@ impl ZigbeeStack { &core.nib.neighbors, &mut nwk_frame, &mode, - self.next_hop_policy(), + self.next_hop_policy(&core.nib), now, ); diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index a5e653a7..036b8cd1 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -326,38 +326,51 @@ impl ZigbeeStack { }) } + /// Advertise many-to-one routes while we are a concentrator, idling otherwise. pub async fn periodic_many_to_one_route_request_task(&self) { - // Receivers drop route requests from senders with a zero outgoing cost, so - // the first advertisement waits until link status exchanges establish a - // neighbor link, bounded by a fixed ceiling in case the network is silent - let startup_deadline = self.core_now() + 2 * self.tunables.link_status_period(); - loop { - if self.core().nib.neighbors.any_live_router_link() { - break; + while !self.is_concentrator() { + self.concentrator_changed.notified().await; } - if self - .timeout_at_core(startup_deadline, self.link_status_received.notified()) - .await - .is_err() - { - break; - } - } + // Receivers drop route requests from senders with a zero outgoing cost, so + // the first advertisement waits until link status exchanges establish a + // neighbor link, bounded by a fixed ceiling in case the network is silent + let startup_deadline = self.core_now() + 2 * self.tunables.link_status_period(); - loop { - let now = self.core_now(); - let max_interval = self.tunables.mtorr_max_interval(); - self.core().nib.mtorr_debouncer.fired(now, max_interval); + while !self.core().nib.neighbors.any_live_router_link() + && self + .timeout_at_core(startup_deadline, self.link_status_received.notified()) + .await + .is_ok() + {} - let _ = self.send_many_to_one_route_request().delivered().await; + while self.is_concentrator() { + let now = self.core_now(); + let max_interval = self.tunables.mtorr_max_interval(); + self.core().nib.mtorr_debouncer.fired(now, max_interval); - self.core().nib.routing.reset_mtorr_triggers(); + let _ = self.send_many_to_one_route_request().delivered().await; - // Advertise every max interval, or sooner when one was requested - self.wait_for_debouncer(|nib| &nib.mtorr_debouncer, &self.mtorr_wake) - .await; + self.core().nib.routing.reset_mtorr_triggers(); + + // Advertise every max interval, or sooner when one was requested. Being + // turned off ends the wait + loop { + let due = core::pin::pin!( + self.wait_for_debouncer(|nib| &nib.mtorr_debouncer, &self.mtorr_wake) + ); + let changed = core::pin::pin!(self.concentrator_changed.notified()); + + if matches!( + futures::future::select(due, changed).await, + futures::future::Either::Left(_) + ) || !self.is_concentrator() + { + break; + } + } + } } } @@ -375,15 +388,14 @@ impl ZigbeeStack { /// Count a received route-failure network status toward an early many-to-one /// route request. pub(super) fn note_route_error(&self) { - if !self.state.is_concentrator { - return; - } - - let kick = self - .core() - .nib - .routing - .note_route_error(self.tunables.mtorr_route_error_threshold()); + let kick = { + let mut core = self.core(); + core.nib.is_concentrator + && core + .nib + .routing + .note_route_error(self.tunables.mtorr_route_error_threshold()) + }; if kick { self.request_many_to_one_route_request(); @@ -393,21 +405,33 @@ impl ZigbeeStack { /// Count a locally failed unicast delivery toward an early many-to-one route /// request. pub(super) fn note_delivery_failure(&self) { - if !self.state.is_concentrator { - return; - } - - let kick = self - .core() - .nib - .routing - .note_delivery_failure(self.tunables.mtorr_delivery_failure_threshold()); + let kick = { + let mut core = self.core(); + core.nib.is_concentrator + && core + .nib + .routing + .note_delivery_failure(self.tunables.mtorr_delivery_failure_threshold()) + }; if kick { self.request_many_to_one_route_request(); } } + /// Become a concentrator, or stop being one. It takes effect at once: the first + /// advertisement goes out right away, and frames stop being source-routed when it + /// is turned off. Route records keep being stored either way, since devices send + /// them for as long as their many-to-one routes last. + pub fn set_concentrator(&self, enabled: bool) { + self.core().nib.is_concentrator = enabled; + self.concentrator_changed.notify_one(); + } + + fn is_concentrator(&self) -> bool { + self.core().nib.is_concentrator + } + pub(super) fn invalidate_routes_via(&self, next_hop: Nwk) { self.core().nib.routing.invalidate_via(next_hop); } diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index 3d54d05c..e21e0dea 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -197,9 +197,9 @@ impl ZigbeeStack { } /// The stack settings next-hop resolution reads. - pub(super) fn next_hop_policy(&self) -> next_hop::Policy { + pub(super) fn next_hop_policy(&self, nib: &Nib) -> next_hop::Policy { next_hop::Policy { - is_concentrator: self.state.is_concentrator, + is_concentrator: nib.is_concentrator, force_route_discovery: self.state.hack_force_route_discovery, max_source_route: self.tunables.max_source_route(), new_router_child_window: 2 * self.tunables.link_status_period(), @@ -228,7 +228,7 @@ impl ZigbeeStack { // A forced discovery holds the frame only while it is underway. Once it is // answered or has lapsed, the frame takes any route like every other frame - let mut policy = self.next_hop_policy(); + let mut policy = self.next_hop_policy(nib); policy.force_route_discovery &= nib.routing.own_discovery_underway( self.state.network_address, nwk_frame.nwk_header.destination, diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 92b78a7d..5777a1b3 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -55,7 +55,7 @@ pub fn network_config(payload: &ConfigurePayload) -> NetworkConfig { }, }), tx_power: state.tx_power, - source_routing: payload.source_routing, + concentrator: payload.source_routing, depth: payload.depth, } } From 0033bd136340e62f4279c8a959a6572a48008f0e Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:46:06 +0000 Subject: [PATCH 03/19] Discover routes for frames relayed from our end device children --- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 108 ++++++++++++------ .../ziggurat-driver/src/zigbee_stack/sends.rs | 3 + 2 files changed, 78 insertions(+), 33 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 8f2500c1..f921321e 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -426,39 +426,13 @@ impl ZigbeeStack { poll_address, ) } - NextHop::NeedDiscovery => { - tracing::debug!("Holding frame until a route to {destination:?} is known"); - let id = core.sends.enqueue_unrouted_unicast( - UnroutedUnicast { - frame: Frame::nwk(nwk_frame, security), - priority: policy.priority, - confirm, - destination, - }, - now, - &self.tunables, - ); - - // The routing table starts a discovery unless the send can wait on - // one: a discovery of ours still underway, or one the timer pass starts - let route_request_identifier = core.nib.routing.want_route( - self.state.network_address, - destination, - now, - self.tunables.route_discovery_time(), - self.tunables.pending_route_discovery_attempts(), - self.activity_params(), - ); - if let Some(route_request_identifier) = route_request_identifier { - self.broadcast_discovery_request( - &mut core, - destination, - route_request_identifier, - ); - } - - SendHandle::new(id, &self.send_watches) - } + NextHop::NeedDiscovery => self.hold_for_route( + &mut core, + Frame::nwk(nwk_frame, security), + policy.priority, + confirm, + now, + ), NextHop::Discard => { tracing::debug!( "Dropping frame to {destination:?}: no route and discovery suppressed" @@ -471,6 +445,49 @@ impl ZigbeeStack { Ok(handle) } + /// Hold a unicast until a route to its destination is known. The routing table + /// starts a discovery unless the frame can wait on one: a discovery of ours still + /// underway, or one the timer pass starts. + fn hold_for_route( + &self, + core: &mut ZigbeeCore, + frame: Frame, + priority: TxPriority, + confirm: Confirm, + now: CoreInstant, + ) -> SendHandle { + let Frame::Nwk { nwk_frame, .. } = &frame else { + unreachable!("only NWK unicasts are routed") + }; + let destination = nwk_frame.nwk_header.destination; + + tracing::debug!("Holding frame until a route to {destination:?} is known"); + let id = core.sends.enqueue_unrouted_unicast( + UnroutedUnicast { + frame, + priority, + confirm, + destination, + }, + now, + &self.tunables, + ); + + let route_request_identifier = core.nib.routing.want_route( + self.state.network_address, + destination, + now, + self.tunables.route_discovery_time(), + self.tunables.pending_route_discovery_attempts(), + self.activity_params(), + ); + if let Some(route_request_identifier) = route_request_identifier { + self.broadcast_discovery_request(core, destination, route_request_identifier); + } + + SendHandle::new(id, &self.send_watches) + } + pub(super) fn next_nwk_sequence_number(&self) -> u8 { self.core().nib.next_sequence_number() } @@ -825,6 +842,8 @@ impl ZigbeeStack { } /// Zigbee spec 3.6.4.3: relay a unicast frame addressed to another device. + // The guard is moved into `commit_sends`; the lint misreads the early return + #[allow(clippy::significant_drop_tightening)] pub(super) fn relay_unicast_nwk_frame( &self, mut nwk_frame: NwkFrame, @@ -938,6 +957,29 @@ impl ZigbeeStack { match next_hop { Some(next_hop) => next_hop, + // Spec 3.6.4.5.1: a relay discovers a route only for a frame from its own + // end device child that allows discovery. End devices do not discover + // routes themselves, so their parent does it for them + None if nwk_frame.nwk_header.frame_control.discover_route + == NwkRouteDiscovery::Enable + && self + .end_device_child_eui64(nwk_frame.nwk_header.source) + .is_some() => + { + let now = self.core_now(); + let mut core = self.core(); + self.hold_for_route( + &mut core, + Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey), + TxPriority::UserNormal, + Confirm::OnHandoff, + now, + ); + self.commit_sends(core); + return; + } + // Any other frame is dropped: a relay never discovers on behalf of a + // router, which recovers through its own discovery or APS retries None => { tracing::debug!("No active route to relay frame to {destination:?}, dropping"); return; diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index e21e0dea..168db39f 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -229,6 +229,9 @@ impl ZigbeeStack { // A forced discovery holds the frame only while it is underway. Once it is // answered or has lapsed, the frame takes any route like every other frame let mut policy = self.next_hop_policy(nib); + // Spec 3.6.4.3: only a frame we originate takes a stored source route, not one + // we relay for an end device child + policy.is_concentrator &= nwk_frame.nwk_header.source == self.state.network_address; policy.force_route_discovery &= nib.routing.own_discovery_underway( self.state.network_address, nwk_frame.nwk_header.destination, From d904ad9b6b53ab0aacc12f90388c6267e49d910c Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:47:48 +0000 Subject: [PATCH 04/19] Send route records to concentrators over many-to-one routes --- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 43 ++++++++++++++++- .../ziggurat-driver/src/zigbee_stack/route.rs | 48 +++++++++++++++++-- crates/ziggurat-zigbee/src/nwk/routing.rs | 27 +++++++++++ 3 files changed, 112 insertions(+), 6 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index f921321e..7f5b8284 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -4,6 +4,7 @@ use crate::ziggurat_ieee_802154::{ Ieee802154Address, Ieee802154AddressingMode, Ieee802154DataFrame, Ieee802154Frame, Ieee802154FrameControl, Ieee802154FrameHeader, Ieee802154FrameType, Ieee802154FrameVersion, }; +use alloc::vec::Vec; use core::time::Duration; use ziggurat_ieee_802154::types::{Eui64, Key, Nwk}; use ziggurat_phy::RadioPhy; @@ -416,6 +417,21 @@ impl ZigbeeStack { let handle = match resolved { NextHop::Resolved(next_hop) => { + if nwk_frame.nwk_header.frame_control.frame_type == NwkFrameType::Data + && nwk_frame.nwk_header.source == self.state.network_address + && core.nib.routing.route_record_due(destination, false) + { + self.enqueue_route_record( + &mut core, + self.state.network_address, + self.state.ieee_address, + destination, + Vec::new(), + next_hop, + policy.priority, + ); + } + let poll_address = Self::poll_address(&core.nib, next_hop); self.enqueue_unicast_in( &mut core, @@ -992,11 +1008,33 @@ impl ZigbeeStack { nwk_frame.nwk_header.source ); + let source = nwk_frame.nwk_header.source; + let child_eui64 = self.end_device_child_eui64(source); + let mut core = self.core(); + + // Spec 3.6.4.5.5: a data frame from our end device child toward a concentrator + // is preceded by a route record for the child, starting with us + if let Some(child_eui64) = child_eui64 + && nwk_frame.nwk_header.frame_control.frame_type == NwkFrameType::Data + && core.nib.routing.route_record_due(destination, true) + { + self.enqueue_route_record( + &mut core, + source, + child_eui64, + destination, + Vec::from([self.state.network_address]), + next_hop_address, + TxPriority::UserNormal, + ); + } + // The originator's sequence number is preserved. Any failure handling (route // invalidation, the network status back to the originator) follows the send // table's verdict; nothing is awaited here. - let poll_address = Self::poll_address(&self.core().nib, next_hop_address); - self.enqueue_unicast( + let poll_address = Self::poll_address(&core.nib, next_hop_address); + self.enqueue_unicast_in( + &mut core, Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey), TxPolicy { priority: TxPriority::UserNormal, @@ -1006,6 +1044,7 @@ impl ZigbeeStack { next_hop_address, poll_address, ); + self.commit_sends(core); } /// Zigbee spec 3.6.4.8.1: when relaying fails, the routes through the dead link are diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 036b8cd1..8d43cb25 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -2,12 +2,13 @@ use crate::runtime::Runtime; use core::cmp; use core::time::Duration; -use ziggurat_ieee_802154::types::Nwk; +use alloc::vec::Vec; +use ziggurat_ieee_802154::types::{Eui64, Nwk}; use ziggurat_phy::RadioPhy; use ziggurat_zigbee::nwk::commands::{ - NwkCommand, NwkNetworkStatus, NwkNetworkStatusCommand, NwkRouteReplyCommand, - NwkRouteRequestCommand, NwkRouteRequestManyToOne, + NwkCommand, NwkNetworkStatus, NwkNetworkStatusCommand, NwkRouteRecordCommand, + NwkRouteReplyCommand, NwkRouteRequestCommand, NwkRouteRequestManyToOne, }; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; @@ -15,7 +16,7 @@ use super::TrafficClass; use super::routing::RouteReplyDisposition; use super::{ - AddrConflictSource, Broadcast, Confirm, NwkSecurityMode, SendHandle, SendMode, TxPolicy, + AddrConflictSource, Broadcast, Confirm, Frame, NwkSecurityMode, SendHandle, SendMode, TxPolicy, TxPriority, Unicast, ZigbeeCore, ZigbeeStack, }; @@ -432,6 +433,45 @@ impl ZigbeeStack { self.core().nib.is_concentrator } + /// Spec 3.6.4.5.5: tell a concentrator the path from `source`, ourselves or our end + /// device child, ahead of a data frame to it over the same next hop. `relays` is + /// the path so far: empty from us, our own address from a child. + #[allow(clippy::too_many_arguments)] + pub(super) fn enqueue_route_record( + &self, + core: &mut ZigbeeCore, + source: Nwk, + source_eui64: Eui64, + concentrator: Nwk, + relays: Vec, + next_hop: Nwk, + priority: TxPriority, + ) { + tracing::debug!("Sending a route record for {source:?} to {concentrator:?}"); + + let frame = self + .nwk_command_frame( + concentrator, + NwkCommand::RouteRecord(NwkRouteRecordCommand { relays }), + ) + .with_source(source) + .with_source_ieee(Some(source_eui64)) + .with_sequence_number(core.nib.next_sequence_number()); + + let poll_address = Self::poll_address(&core.nib, next_hop); + self.enqueue_unicast_in( + core, + Frame::nwk(frame, NwkSecurityMode::NetworkKey), + TxPolicy { + priority, + class: TrafficClass::Critical, + }, + Confirm::OnHandoff, + next_hop, + poll_address, + ); + } + pub(super) fn invalidate_routes_via(&self, next_hop: Nwk) { self.core().nib.routing.invalidate_via(next_hop); } diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index f0ce768e..2d45c07e 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -572,6 +572,33 @@ impl Routing { self.remove_route_record(destination) } + /// Spec 3.6.4.5.5: whether a route record has to precede a data frame toward + /// `destination` over its many-to-one route. A frame relayed for one of our end + /// device children always needs one. A frame we originate needs one while the + /// concentrator asks for it: a concentrator that keeps a route record table then + /// has our route until its next advertisement asks again, so the request is + /// cleared; one that keeps none needs a route record before every frame. + pub fn route_record_due(&mut self, destination: Nwk, for_end_device_child: bool) -> bool { + let Some(entry) = self.route_table.get_mut(&destination) else { + return false; + }; + + if entry.status != Status::Active || !entry.many_to_one { + return false; + } + + if for_end_device_child { + return true; + } + + let due = entry.route_record_required; + if !entry.no_route_cache { + entry.route_record_required = false; + } + + due + } + /// Spec 3.6.4.3.2: relaying a source-routed frame proves the concentrator that /// originated it holds a route record for the frame's source; no route record /// has to precede the next frame toward it (unless it keeps no route cache). From f347690dc1e982dfd4868182347cd72067186988 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:48:55 +0000 Subject: [PATCH 05/19] Report broken many-to-one routes to the concentrator --- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 67 ++++++++++++++++++- crates/ziggurat-zigbee/src/nwk/neighbors.rs | 11 +++ crates/ziggurat-zigbee/src/nwk/routing.rs | 8 +++ 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 7f5b8284..b70ee7db 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -1048,10 +1048,25 @@ impl ZigbeeStack { } /// Zigbee spec 3.6.4.8.1: when relaying fails, the routes through the dead link are - /// invalidated and the failure is reported back to the frame's originator. + /// invalidated and the failure is reported: to the concentrator for a route it + /// advertised, otherwise back to the frame's originator. fn handle_relay_failure(&self, failed: FailedNwkUnicast, next_hop: Nwk) { + // A failure on a route a concentrator advertised is reported to the + // concentrator, not to the frame's source + let many_to_one = !failed.source_routed + && self + .core() + .nib + .routing + .is_many_to_one_route(failed.destination); + self.invalidate_routes_via(next_hop); + if many_to_one { + self.report_many_to_one_route_failure(&failed, next_hop); + return; + } + let source = failed.source; let destination_ieee = self.core().nib.address_map.eui64_for(source); @@ -1089,6 +1104,56 @@ impl ZigbeeStack { } } + /// Spec 3.6.4.8.1: tell a concentrator that the route it advertised broke at us, so + /// it advertises again. Every router within its radius has a route to it, so the + /// report goes to a random other router neighbor rather than the dead next hop. + // The guard is moved into `commit_sends`; the lint misreads the early return + #[allow(clippy::significant_drop_tightening)] + fn report_many_to_one_route_failure(&self, failed: &FailedNwkUnicast, dead_next_hop: Nwk) { + let concentrator = failed.destination; + let mut core = self.core(); + + let relays: Vec = core + .nib + .neighbors + .live_router_links() + .into_iter() + .filter(|&relay| relay != dead_next_hop) + .collect(); + + if relays.is_empty() { + tracing::debug!("No router neighbor to report a broken route to {concentrator:?}"); + return; + } + + let relay = relays[usize::from(crate::rng::random_u16::()) % relays.len()]; + + tracing::info!( + "Reporting a broken many-to-one route to {concentrator:?} through {relay:?}" + ); + + let frame = self + .nwk_command_frame( + concentrator, + NwkCommand::NetworkStatus(NwkNetworkStatusCommand { + status_code: NwkNetworkStatus::ManyToOneRouteFailure, + network_address: failed.source, + }), + ) + .with_sequence_number(core.nib.next_sequence_number()); + + let poll_address = Self::poll_address(&core.nib, relay); + self.enqueue_unicast_in( + &mut core, + Frame::nwk(frame, NwkSecurityMode::NetworkKey), + TxPolicy::STACK_CRITICAL, + Confirm::OnHandoff, + relay, + poll_address, + ); + self.commit_sends(core); + } + /// Zigbee spec 3.6.6: re-broadcast a newly seen broadcast frame, preserving the /// originator's source address and sequence number. The first relay is jittered to /// decorrelate from the originator's wave; the broadcast-retransmit reactor then diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index cc09af65..bfe33b0f 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -623,6 +623,17 @@ impl Neighbors { /// Whether any router neighbor has established a bidirectional link with us, /// i.e. a received link status lists us with a nonzero cost. + /// The routers and coordinator we have a working link to, in both directions. + pub fn live_router_links(&self) -> Vec { + self.table + .values() + .filter(|entry| { + entry.device_type != NwkDeviceType::EndDevice && entry.outgoing_cost > 0 + }) + .map(|entry| entry.network_address) + .collect() + } + pub fn any_live_router_link(&self) -> bool { self.table .values() diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 2d45c07e..07ed98f1 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -457,6 +457,14 @@ impl Routing { /// Mark every active route through the given next hop as inactive, forcing a fresh /// discovery on next use. + /// Whether the active route to `destination` was learned from its many-to-one + /// route request. + pub fn is_many_to_one_route(&self, destination: Nwk) -> bool { + self.route_table + .get(&destination) + .is_some_and(|entry| entry.status == Status::Active && entry.many_to_one) + } + pub fn invalidate_via(&mut self, next_hop: Nwk) { for entry in self.route_table.values_mut() { if entry.status == Status::Active && entry.next_hop_address == next_hop { From 0f4492a42290692d8f2bd827bd91b311bd8dfc96 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:00:38 +0000 Subject: [PATCH 06/19] Drop relayed route records only when the frame is full --- crates/ziggurat-driver/src/zigbee_stack/nwk.rs | 12 +++++++----- crates/ziggurat-zigbee/src/nwk/frame.rs | 7 +++++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index b70ee7db..95d1e275 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -912,13 +912,15 @@ impl ZigbeeStack { if let NwkPayload::Command(command) = &mut nwk_frame.payload { match command { NwkCommand::RouteRecord(route_record) => { - // Spec 3.6.4.5.5: with no room left for our address the route record - // is discarded rather than overflowing the frame. - if route_record.relays.len() >= usize::from(self.tunables.max_source_route()) { - tracing::warn!("Dropping transiting route record: relay list is full"); + route_record.relays.push(self.state.network_address); + + // Spec 3.6.4.5.5: with no room left in the frame for our address, the + // route record is discarded. How long a source route the concentrator + // will use is its own limit, not ours + if !nwk_frame.fits_secured() { + tracing::warn!("Dropping transiting route record: the frame is full"); return; } - route_record.relays.push(self.state.network_address); } // A relay SHALL append its address to a transiting route record; one we // could not parse cannot have it appended, so it is discarded rather than diff --git a/crates/ziggurat-zigbee/src/nwk/frame.rs b/crates/ziggurat-zigbee/src/nwk/frame.rs index c8af256e..268b5179 100644 --- a/crates/ziggurat-zigbee/src/nwk/frame.rs +++ b/crates/ziggurat-zigbee/src/nwk/frame.rs @@ -613,6 +613,13 @@ impl NwkFrame { write_frame(|writer| self.serialize(writer, Some(key))) .expect("the NWK frame fits in an MSDU") } + + /// Whether the frame, secured, fits an 802.15.4 frame with short addresses. The + /// key does not change the length. + pub fn fits_secured(&self) -> bool { + write_frame::(|writer| self.serialize(writer, Some(&Key([0; 16])))) + .is_ok_and(|bytes| MAC_FRAME_OVERHEAD + bytes.len() <= MAX_PHY_PACKET_SIZE) + } } /// A NWK frame ready to go into an 802.15.4 data frame, encrypted under `key` as it is From 243c0fa33d51aa79c21acdfc8f4f07ca57455b64 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:18:27 +0000 Subject: [PATCH 07/19] Use a stored source route only over a good outbound first hop --- .../ziggurat-driver/src/zigbee_stack/sends.rs | 1 + crates/ziggurat-zigbee/src/constants.rs | 5 +++ crates/ziggurat-zigbee/src/nwk/next_hop.rs | 12 +++++- crates/ziggurat-zigbee/src/nwk/routing.rs | 33 +++++++++------- .../ziggurat-zigbee/src/nwk/routing/tests.rs | 39 ++++++++++++++++--- 5 files changed, 71 insertions(+), 19 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index 168db39f..198ec742 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -202,6 +202,7 @@ impl ZigbeeStack { is_concentrator: nib.is_concentrator, force_route_discovery: self.state.hack_force_route_discovery, max_source_route: self.tunables.max_source_route(), + source_route_max_first_hop_cost: self.tunables.source_route_max_first_hop_cost(), new_router_child_window: 2 * self.tunables.link_status_period(), } } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 3f8aa143..83dcf1c2 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -296,6 +296,11 @@ tunables! { /// often not heard, so waiting for it only causes needless retransmissions. broadcast_relayer_max_link_cost: u8 = 3, + /// A stored source route is used only while our outgoing cost to its first hop, as + /// that neighbor's link status reports it, is at most this value. The route was + /// learned from frames sent toward us, which says nothing about the link outward. + source_route_max_first_hop_cost: u8 = 3, + /// The minimum time between two consecutive many-to-one route requests, even when /// error thresholds are crossed. mtorr_min_interval: Duration = Duration::from_secs(10), diff --git a/crates/ziggurat-zigbee/src/nwk/next_hop.rs b/crates/ziggurat-zigbee/src/nwk/next_hop.rs index a98c2514..09ab911b 100644 --- a/crates/ziggurat-zigbee/src/nwk/next_hop.rs +++ b/crates/ziggurat-zigbee/src/nwk/next_hop.rs @@ -73,6 +73,8 @@ pub struct Policy { pub force_route_discovery: bool, /// The longest source route we embed. pub max_source_route: u8, + /// The highest outgoing cost to a source route's first hop we send over. + pub source_route_max_first_hop_cost: u8, /// How long after a router child associates or rejoins we send to it directly /// when no route is known. pub new_router_child_window: Duration, @@ -111,7 +113,15 @@ pub fn resolve( // A stored source route (concentrator behavior) wins over the routing table. if policy.is_concentrator && !policy.force_route_discovery { - match routing.route_to(destination, policy.max_source_route) { + // Our outgoing cost is the one the neighbor measured and reported; 0 means it + // has not reported one yet + let first_hop_usable = |hop| { + neighbors.link(hop).is_some_and(|link| { + (1..=policy.source_route_max_first_hop_cost).contains(&link.outgoing_cost) + }) + }; + + match routing.route_to(destination, policy.max_source_route, first_hop_usable) { Some(Route::NextHop(next_hop)) => return NextHop::Resolved(next_hop), Some(Route::SourceRouted(relays)) => return apply_source_route(frame, relays), None => {} diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 07ed98f1..b0076815 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -623,21 +623,28 @@ impl Routing { /// intermediate router still holding state (and our entries toward devices are /// mostly reverse-route side effects of their discoveries). This deviates from /// the spec's table-first order (3.6.4.3). - pub fn route_to(&self, destination: Nwk, max_source_route: u8) -> Option { - // TODO: a route record wins unconditionally here, with no outgoing-link-cost check. - // For a concentrator this reverses the device->coordinator path and assumes the link - // is symmetric: a device reachable directly inbound advertises Relay Count 0, so we - // transmit direct even when our outbound link to it is poor (asymmetric radio). The - // cost-aware AODV path only runs in the `_` fallback. Fold the neighbor's - // `outgoing_cost` in so a Relay-Count-0 record only yields `NextHop` when the - // outbound link is actually good; otherwise fall through to cost-based routing. - match self.route_record_table.get(&destination) { + /// + /// A source route is the reverse of the path a route record took toward us, so it + /// only proves the links in that direction. It is used only when `first_hop_usable` + /// accepts our link to its first hop: the last relay, or the destination itself + /// when there are none. Otherwise the cost-aware routing table decides. + pub fn route_to( + &self, + destination: Nwk, + max_source_route: u8, + first_hop_usable: impl Fn(Nwk) -> bool, + ) -> Option { + let record = self + .route_record_table + .get(&destination) + .filter(|relays| relays.len() < max_source_route as usize) + .filter(|relays| first_hop_usable(*relays.last().unwrap_or(&destination))); + + match record { // Spec 3.6.4.3.1: no intermediate relays means direct transmission Some(relays) if relays.is_empty() => Some(Route::NextHop(destination)), - Some(relays) if relays.len() < max_source_route as usize => { - Some(Route::SourceRouted(relays.clone())) - } - _ => self.next_hop(destination).map(Route::NextHop), + Some(relays) => Some(Route::SourceRouted(relays.clone())), + None => self.next_hop(destination).map(Route::NextHop), } } diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 2fcc1c1a..82dcc0ac 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -102,12 +102,16 @@ fn test_forget_drops_the_route_and_the_route_record() { let mut routing = Routing::default(); routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); routing.store_route_record(DEVICE, vec![ROUTER]); - assert!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE).is_some()); + assert!( + routing + .route_to(DEVICE, MAX_SOURCE_ROUTE, |_| true) + .is_some() + ); routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(DEVICE), None); - assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE), None); + assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE, |_| true), None); } #[test] @@ -300,7 +304,7 @@ fn test_unchanged_route_record_reports_a_relay_route_it_restores() { } ); assert_eq!( - routing.route_to(ROUTER, MAX_SOURCE_ROUTE), + routing.route_to(ROUTER, MAX_SOURCE_ROUTE, |_| true), Some(Route::SourceRouted(vec![NEIGHBOR])) ); } @@ -315,7 +319,7 @@ fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { routing.store_route_record(DEVICE, relays); assert!(routing.forget_route_to(DEVICE)); - assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE), None); + assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE, |_| true), None); } } @@ -336,7 +340,7 @@ fn test_forget_route_to_leaves_other_destinations_alone() { routing.forget_route_to(DEVICE); assert_eq!( - routing.route_to(ROUTER, MAX_SOURCE_ROUTE), + routing.route_to(ROUTER, MAX_SOURCE_ROUTE, |_| true), Some(Route::NextHop(ROUTER)) ); } @@ -980,3 +984,28 @@ fn test_equal_cost_copy_is_fresh_after_an_unhandled_cheaper_copy() { routing.note_route_request_handled(DEVICE, 1); assert!(!receive_copy(&mut routing, 2).fresh); } + +// A source route only proves its links toward us. With a poor outbound link to its +// first hop, the routing table's route is used instead. +#[test] +fn test_route_to_skips_a_source_route_with_an_unusable_first_hop() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.store_route_record(DEVICE, vec![OTHER_DEVICE, ROUTER]); + + assert_eq!( + routing.route_to(DEVICE, MAX_SOURCE_ROUTE, |hop| hop == ROUTER), + Some(Route::SourceRouted(vec![OTHER_DEVICE, ROUTER])) + ); + assert_eq!( + routing.route_to(DEVICE, MAX_SOURCE_ROUTE, |hop| hop != ROUTER), + Some(Route::NextHop(NEIGHBOR)) + ); + + // With no relays the destination itself is the first hop + routing.store_route_record(DEVICE, vec![]); + assert_eq!( + routing.route_to(DEVICE, MAX_SOURCE_ROUTE, |hop| hop != DEVICE), + Some(Route::NextHop(NEIGHBOR)) + ); +} From 584ffb5b1ee17ba0be6595e9f44a99febbf9ace8 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:25:26 +0000 Subject: [PATCH 08/19] Directly send to neighbors without a known route when `cost <= 2` --- .../src/zigbee_stack/joining.rs | 9 ++------- .../src/zigbee_stack/neighbor.rs | 20 +++++++++++++++++++ .../ziggurat-driver/src/zigbee_stack/nwk.rs | 4 +--- .../ziggurat-driver/src/zigbee_stack/route.rs | 7 ++----- .../ziggurat-driver/src/zigbee_stack/sends.rs | 1 + crates/ziggurat-zigbee/src/constants.rs | 7 +++++++ crates/ziggurat-zigbee/src/nwk/neighbors.rs | 8 ++++++++ crates/ziggurat-zigbee/src/nwk/next_hop.rs | 20 +++++++++++++++++++ 8 files changed, 61 insertions(+), 15 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/joining.rs b/crates/ziggurat-driver/src/zigbee_stack/joining.rs index 7142ec8f..6f71ab2c 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/joining.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/joining.rs @@ -401,10 +401,6 @@ impl ZigbeeStack { }) } - pub(super) fn is_neighbor(&self, nwk: Nwk) -> bool { - self.core().nib.neighbors.has_network_address(nwk) - } - /// Register an install-code-derived link key for a device expected to join: /// an `apsDeviceKeyPairSet` entry with `PROVISIONAL_KEY` attributes that /// replaces the well-known key for that device's network key delivery. @@ -628,8 +624,7 @@ impl ZigbeeStack { } } - /// Send a serialized APS frame to an on-network device, with NWK security. Direct - /// children do not participate in route discovery, so they are addressed directly. + /// Send a serialized APS frame to an on-network device, with NWK security. fn send_secured_aps_payload( &self, destination: Nwk, @@ -644,7 +639,7 @@ impl ZigbeeStack { self.send_unicast(Unicast { frame: nwk_frame, security: NwkSecurityMode::NetworkKey, - mode: if self.is_neighbor(destination) { + mode: if self.sends_directly_to(destination) { SendMode::Direct } else { SendMode::Route(RouteDirective::StackDecides) diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index a1b5d0c6..2ac611a7 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -7,6 +7,7 @@ use ziggurat_phy::RadioPhy; use ziggurat_zigbee::nwk::NwkDeviceType; use ziggurat_zigbee::nwk::commands::{NwkCommand, NwkLinkStatusCommand}; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; +use ziggurat_zigbee::nwk::next_hop; use super::TrafficClass; @@ -62,6 +63,25 @@ impl ZigbeeStack { self.core().nib.neighbors.end_device_child_eui64(nwk) } + /// Whether a unicast goes straight to its destination, with no route: an end device + /// child, a router child that has sent no link status yet, or a neighbor with a good + /// link. + #[allow(clippy::significant_drop_tightening)] + pub(super) fn sends_directly_to(&self, destination: Nwk) -> bool { + let now = self.core_now(); + let core = self.core(); + let neighbors = &core.nib.neighbors; + let policy = self.next_hop_policy(&core.nib); + + neighbors.end_device_child_eui64(destination).is_some() + || next_hop::is_direct_neighbor(neighbors, destination, policy.direct_max_link_cost) + || neighbors.is_recently_attached_router_child( + destination, + now, + policy.new_router_child_window, + ) + } + pub(super) fn sleepy_child_eui64(&self, nwk: Nwk) -> Option { self.core().nib.neighbors.sleepy_child_eui64(nwk) } diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 95d1e275..c40cfaf9 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -966,9 +966,7 @@ impl ZigbeeStack { .note_source_routed_frame(nwk_frame.nwk_header.source); next_hop - } else if self.is_neighbor(destination) { - // Children and direct neighbors are addressed directly, everything else - // goes through the routing table + } else if self.sends_directly_to(destination) { destination } else { let next_hop = self.core().nib.routing.next_hop(destination); diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 8d43cb25..7f3c3349 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -139,12 +139,9 @@ impl ZigbeeStack { let sender_ieee = sender_link.eui64; - // The maximum of the incoming and outgoing costs is used for computations to - // deprioritize asymmetric routes - let contributing_path_cost = cmp::max(sender_link.outgoing_cost, sender_link.incoming_cost); let updated_path_cost = route_request_cmd .path_cost - .saturating_add(contributing_path_cost); + .saturating_add(sender_link.cost()); // Deduplicate route requests and track the best path back to the originator. // Only the first copy, one advertising a strictly better forward cost, or an @@ -211,7 +208,7 @@ impl ZigbeeStack { route_request_identifier: route_request_cmd.route_request_identifier, originator_nwk: nwk_frame.nwk_header.source, responder_nwk: route_request_cmd.destination_address, - path_cost: contributing_path_cost, + path_cost: sender_link.cost(), originator_eui64: nwk_frame.nwk_header.source_ieee, responder_eui64: Some(responder_eui64), }), diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index 198ec742..0e7fa4c0 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -204,6 +204,7 @@ impl ZigbeeStack { max_source_route: self.tunables.max_source_route(), source_route_max_first_hop_cost: self.tunables.source_route_max_first_hop_cost(), new_router_child_window: 2 * self.tunables.link_status_period(), + direct_max_link_cost: self.tunables.direct_max_link_cost(), } } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 83dcf1c2..9307e1fa 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -301,6 +301,13 @@ tunables! { /// learned from frames sent toward us, which says nothing about the link outward. source_route_max_first_hop_cost: u8 = 3, + /// A neighbor is sent to directly, with no route, only while its link cost is at + /// most this value (spec 3.6.3.3). The link cost is the worse of the two directions. + /// Every link costs at least 1, so a relayed path costs at least 2. A direct link + /// of cost 1 or 2 is as cheap as any route a discovery could find. Above 2, a + /// relayed path may be cheaper, so a discovery decides. + direct_max_link_cost: u8 = 2, + /// The minimum time between two consecutive many-to-one route requests, even when /// error thresholds are crossed. mtorr_min_interval: Duration = Duration::from_secs(10), diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index bfe33b0f..2a5670a3 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -187,6 +187,14 @@ pub struct NeighborLink { pub incoming_cost: u8, } +impl NeighborLink { + /// The cost of the link for routing: the worse of the two directions, so an + /// asymmetric link is not preferred + pub fn cost(&self) -> u8 { + cmp::max(self.outgoing_cost, self.incoming_cost) + } +} + /// What a received link status changed in the sender's entry, for route maintenance. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct LinkStatusOutcome { diff --git a/crates/ziggurat-zigbee/src/nwk/next_hop.rs b/crates/ziggurat-zigbee/src/nwk/next_hop.rs index 09ab911b..12abe51e 100644 --- a/crates/ziggurat-zigbee/src/nwk/next_hop.rs +++ b/crates/ziggurat-zigbee/src/nwk/next_hop.rs @@ -78,6 +78,19 @@ pub struct Policy { /// How long after a router child associates or rejoins we send to it directly /// when no route is known. pub new_router_child_window: Duration, + /// The highest link cost to a neighbor we send to directly, with no route. + pub direct_max_link_cost: u8, +} + +/// Whether `destination` is a neighbor we can send to directly, with no route (spec +/// 3.6.3.3). +/// +/// A neighbor that has not listed us in a link status has no outgoing cost and is +/// excluded. +pub fn is_direct_neighbor(neighbors: &Neighbors, destination: Nwk, max_link_cost: u8) -> bool { + neighbors.link(destination).is_some_and(|link| { + link.outgoing_cost > 0 && link.incoming_cost > 0 && link.cost() <= max_link_cost + }) } /// Resolve the MAC next hop for a unicast. @@ -111,6 +124,13 @@ pub fn resolve( return NextHop::Resolved(destination); } + // A neighbor with a good link is reached directly. No route is cheaper + if !policy.force_route_discovery + && is_direct_neighbor(neighbors, destination, policy.direct_max_link_cost) + { + return NextHop::Resolved(destination); + } + // A stored source route (concentrator behavior) wins over the routing table. if policy.is_concentrator && !policy.force_route_discovery { // Our outgoing cost is the one the neighbor measured and reported; 0 means it From 2a56c49e0bbcc3f4daa2c1920a93ae09a64c7f14 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:20:03 +0000 Subject: [PATCH 09/19] Jitter every link status period so routers do not stay in step --- crates/ziggurat-driver/src/zigbee_stack/neighbor.rs | 6 +++++- crates/ziggurat-zigbee/src/constants.rs | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 2ac611a7..d1369a83 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -244,7 +244,11 @@ impl ZigbeeStack { fn restart_link_status_period(&self) { let now = self.core_now(); - let period = self.tunables.link_status_period(); + let jitter = self + .tunables + .link_status_jitter() + .mul_f32(crate::rng::random_f32::()); + let period = self.tunables.link_status_period().saturating_sub(jitter); self.core().nib.link_status_debouncer.fired(now, period); } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 9307e1fa..d9ec9356 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -327,6 +327,12 @@ tunables! { /// The time between link status command frames. link_status_period: Duration = Duration::from_secs(15), + /// Each link status period is shortened by a random amount up to this value (spec + /// 3.6.4.4.1). Routers that start together would otherwise send in step forever, + /// and a link status is sent once, without retries, so the same frames would + /// collide every period. + link_status_jitter: Duration = Duration::from_secs(1), + /// `nwkcMinRouterBootstrapJitter`: the shortest delay before a gratuitous link /// status. min_router_bootstrap_jitter: Duration = Duration::from_millis(500), From 4e2b0570856f5a76a76236f0f44553198b2f13b2 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:49:44 +0000 Subject: [PATCH 10/19] Delay relayed route requests by the cost of the incoming link --- .../ziggurat-driver/src/zigbee_stack/route.rs | 20 +++++++++---------- crates/ziggurat-zigbee/src/constants.rs | 11 ++++++++-- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 7f3c3349..2789ded4 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -265,16 +265,16 @@ impl ZigbeeStack { .with_radius(rebroadcast_radius) .with_sequence_number(nwk_frame.nwk_header.sequence_number); - // Spec 3.6.4.5.1.4: relayed route requests are jittered and retried. The jitter - // bounds are loaded once and subtracted saturating: a runtime tunable change can - // transiently leave min above max. - let min_jitter = self.tunables.min_rreq_jitter(); - let max_jitter = self.tunables.max_rreq_jitter(); - let jitter = (min_jitter - + max_jitter - .saturating_sub(min_jitter) - .mul_f32(crate::rng::random_f32::())) - * 2; + // Spec 3.6.4.5.1.4: relayed route requests are delayed and retried. The delay + // grows with the cost of the link this copy came over, so along a path it adds + // up to the path cost: the cheapest copy tends to arrive first, and fewer + // routers relay again for a cheaper copy. The random part keeps neighbors that + // heard the same copy from relaying at the same moment + let jitter = self.tunables.rreq_delay_per_link_cost() * u32::from(sender_link.cost()) + + self + .tunables + .rreq_jitter() + .mul_f32(crate::rng::random_f32::()); let attempts = self.tunables.rreq_retries().saturating_add(1); let mut core = self.core(); diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index d9ec9356..11fd32cb 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -350,8 +350,15 @@ tunables! { initial_rreq_retries: u8 = 3, rreq_retries: u8 = 2, rreq_retry_interval: Duration = Duration::from_millis(254), - min_rreq_jitter: Duration = Duration::from_millis(2), - max_rreq_jitter: Duration = Duration::from_millis(128), + + /// A relayed route request waits this long per unit of cost of the link it came + /// over, plus up to `rreq_jitter` at random. Over a path the waits add up to the + /// path cost times this value, so copies tend to arrive cheapest first. The spec + /// allows a cost-dependent delay (3.6.4.5.1.4). With link costs up to 7, the + /// defaults stay within the spec's 2 x [2, 128] ms window. + rreq_delay_per_link_cost: Duration = Duration::from_millis(32), + rreq_jitter: Duration = Duration::from_millis(32), + unicast_retries: u8 = 3, unicast_retry_delay: Duration = Duration::from_millis(50), broadcast_delivery_time: Duration = Duration::from_millis(9000), From 9a9c8edb700885c7bc3b2f7c3d775e375790917d Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:07:35 +0000 Subject: [PATCH 11/19] Stop relaying a route request copy once a cheaper copy is relayed --- .../ziggurat-driver/src/zigbee_stack/route.rs | 5 ++- crates/ziggurat-zigbee/src/sends/mod.rs | 26 ++++++++++++ crates/ziggurat-zigbee/src/sends/tests.rs | 41 +++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 2789ded4..591f5bb7 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -283,7 +283,10 @@ impl ZigbeeStack { core.nib .routing .note_route_request_handled(originator, request_id); - self.broadcast_route_request(&mut core, relayed_route_request_cmd, attempts, jitter); + let relay = + self.broadcast_route_request(&mut core, relayed_route_request_cmd, attempts, jitter); + core.sends + .route_request_relayed(originator, request_id, relay); self.commit_sends(core); } diff --git a/crates/ziggurat-zigbee/src/sends/mod.rs b/crates/ziggurat-zigbee/src/sends/mod.rs index 5dd10fc0..4f2dd765 100644 --- a/crates/ziggurat-zigbee/src/sends/mod.rs +++ b/crates/ziggurat-zigbee/src/sends/mod.rs @@ -47,6 +47,7 @@ use crate::aps::frame::ApsAckFrame; use crate::constants::Tunables; use crate::flat_map::{FlatMap, FlatSet}; use crate::gp::GpdfTarget; +use crate::nwk::routing::RouteRequestId; pub use broadcasts::{Broadcast, Schedule}; pub use gpdfs::{Gpdf, GpdfTrigger}; @@ -258,6 +259,10 @@ pub struct Sends { /// still has copies to send. Kept to stop those copies when the discovery is /// replaced or abandoned. route_requests: FlatMap, + /// The broadcast relaying another router's route request, by originator and + /// request identifier, while it still has copies to send. Kept to stop those copies + /// when a cheaper copy of the request is relayed. + relayed_route_requests: FlatMap<(Nwk, RouteRequestId), SendId>, outbox: Outbox, } @@ -270,6 +275,7 @@ impl Default for Sends { broadcasts: Broadcasts::default(), gpdfs: Gpdfs::default(), route_requests: FlatMap::new(), + relayed_route_requests: FlatMap::new(), outbox: VecDeque::new(), } } @@ -463,6 +469,23 @@ impl> Sends { } } + /// The driver relayed `relay`, a copy of `originator`'s route request `request_id`. + /// Copies still to come of the copy it relayed before are not sent: a cheaper path + /// replaced theirs (spec 3.6.4.5.1.4 allows discarding them). + pub fn route_request_relayed( + &mut self, + originator: Nwk, + request_id: RouteRequestId, + relay: SendId, + ) { + if let Some(previous) = self + .relayed_route_requests + .insert((originator, request_id), relay) + { + self.broadcasts.stop(previous, &mut self.outbox); + } + } + /// Fail every unrouted send to `destination`: no route to it will be found. Copies /// of its route request still to come are not sent. pub fn fail_unrouted(&mut self, destination: Nwk) { @@ -522,6 +545,7 @@ impl> Sends { self.broadcasts.abandon(&mut self.outbox); self.gpdfs.abandon(&mut self.outbox); self.route_requests.clear(); + self.relayed_route_requests.clear(); } /// Cancel a send. Returns whether it was cancelled: not if it is unknown, already @@ -573,6 +597,8 @@ impl> Sends { // A route request with no copy left to send needs no stopping self.route_requests .retain(|_, request| self.broadcasts.contains(*request)); + self.relayed_route_requests + .retain(|_, relay| self.broadcasts.contains(*relay)); } /// When the timer must next run, or `None` when nothing is waiting on time. diff --git a/crates/ziggurat-zigbee/src/sends/tests.rs b/crates/ziggurat-zigbee/src/sends/tests.rs index 7f59ade3..3d058251 100644 --- a/crates/ziggurat-zigbee/src/sends/tests.rs +++ b/crates/ziggurat-zigbee/src/sends/tests.rs @@ -148,6 +148,28 @@ impl Fixture { (request, self.settled()) } + /// Relay a copy of another router's route request, as the driver does: three copies, + /// the first due now. Returns the relay and what registering it settles. + fn relay_route_request(&mut self) -> (SendId, Vec) { + let relay = self.sends.enqueue_broadcast( + Broadcast { + frame: "relayed route request", + priority: TxPriority::UserNormal, + schedule: Schedule::FixedInterval { + interval: Duration::from_millis(254), + copies_remaining: 3, + next_attempt: self.now, + }, + }, + self.now, + &self.tunables, + ); + assert!(self.settled().is_empty()); + + self.sends.route_request_relayed(NEXT_HOP, 1, relay); + (relay, self.settled()) + } + /// Run a timer pass in which the routing table offers this next hop toward /// `DESTINATION`. Returns what the pass settles. fn pass(&mut self, next_hop: Option) -> Vec { @@ -355,6 +377,25 @@ fn test_new_route_request_stops_the_one_it_replaces() { assert!(fixture.dequeue().is_none()); } +// A relay of a cheaper copy of a route request stops the relay of the costlier copy, +// including the copies it has yet to send +#[test] +fn test_relayed_route_request_stops_the_costlier_relay() { + let mut fixture = Fixture::new(); + let (first_relay, settled) = fixture.relay_route_request(); + assert!(settled.is_empty()); + assert!(fixture.pass(None).is_empty()); + assert!(fixture.transmit_next().is_empty()); + + let (_, settled) = fixture.relay_route_request(); + assert_eq!(settled, [cancelled(first_relay)]); + + // Only the new relay has a copy to send + assert!(fixture.pass(None).is_empty()); + assert!(fixture.transmit_next().is_empty()); + assert!(fixture.dequeue().is_none()); +} + // A schedule with no copies at all never reaches the air: it fails as a handoff timeout // on its first pass instead of looking for a radio failure that never happened. #[test] From 8a77b37da73111530321e4afe000529b24e335cc Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:26:50 +0000 Subject: [PATCH 12/19] Fill each link status frame with as many entries as fit --- .../src/zigbee_stack/neighbor.rs | 48 +++++++++++-------- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 30 +++++++----- 2 files changed, 47 insertions(+), 31 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index d1369a83..c365de22 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -15,9 +15,6 @@ use super::{ Broadcast, EnqueueError, NwkSecurityMode, SendHandle, TxPolicy, TxPriority, ZigbeeStack, }; -/// Maximum number of link status entries that can be carried in a single frame. -const MAX_LINK_STATUSES: usize = 7; - impl ZigbeeStack { pub(super) fn maybe_recompute_lqa(&self, sender_nwk: Nwk, lqi: u8, _rssi: i8) { let link_status_due = self.core().nib.neighbors.record_lqa(sender_nwk, lqi); @@ -193,25 +190,38 @@ impl ZigbeeStack { link_statuses.sort_by_key(|a| a.address.as_u16()); let total = link_statuses.len(); + let build_frame = |start: usize, end: usize| { + self.nwk_command_frame( + BROADCAST_ALL_ROUTERS_AND_COORDINATOR, + NwkCommand::LinkStatus(NwkLinkStatusCommand { + is_first_frame: start == 0, + is_last_frame: end == total, + link_statuses: link_statuses[start..end].to_vec(), + }), + ) + .with_radius(1) + }; + // Measured with the auxiliary header the frame is sent with + let aux_header = self.outgoing_aux_header(0); + let fits = |start: usize, end: usize| { + let mut frame = build_frame(start, end); + frame.aux_header = Some(aux_header.clone()); + frame.fits_secured() + }; let mut start = 0; loop { - // Each frame carries up to `MAX_LINK_STATUSES` entries; consecutive frames - // repeat one boundary entry (the last of frame N is the first of frame N+1) - // so a receiver can stitch the advertised address range together (spec - // 3.6.4.4.2). An empty list still emits a single first+last frame. - let end = core::cmp::min(start + MAX_LINK_STATUSES, total); - - let link_status_frame = self - .nwk_command_frame( - BROADCAST_ALL_ROUTERS_AND_COORDINATOR, - NwkCommand::LinkStatus(NwkLinkStatusCommand { - is_first_frame: start == 0, - is_last_frame: end == total, - link_statuses: link_statuses[start..end].to_vec(), - }), - ) - .with_radius(1); + // Spec 3.4.8.3.2: the list is split only when it does not fit in one frame. + // Each frame takes as many entries as fit, and consecutive frames repeat + // one boundary entry (the last of frame N is the first of frame N+1), so a + // receiver can stitch the advertised address range together. An empty list + // still emits a single first+last frame. + let mut end = total.min(start + 1); + while end < total && fits(start, end + 1) { + end += 1; + } + + let link_status_frame = build_frame(start, end); // The last frame is the tracked one; earlier chunks are fire-and-forget. // They drain the single sender in admission order, so the last frame's diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index c40cfaf9..bfb482e5 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -512,18 +512,8 @@ impl ZigbeeStack { /// encrypt it with, or `None` for a frame sent unsecured. fn secure_nwk_frame(&self, nwk_frame: &mut NwkFrame, security: NwkSecurityMode) -> Option { if security == NwkSecurityMode::NetworkKey { - nwk_frame.aux_header = Some(NwkAuxHeader { - security_control: NwkSecurityHeaderControlField { - security_level: NwkSecurityLevel::NoSecurity, - key_id: NwkSecurityHeaderKeyId::NetworkKey, - extended_nonce: true, - require_verified_frame_counter: false, - }, - // The encryption frame counter always increments - frame_counter: self.next_nwk_frame_counter(), - extended_source: Some(self.state.ieee_address), - key_sequence_number: self.core().nib.nwk_security.active_key_seq_number(), - }); + // The encryption frame counter always increments + nwk_frame.aux_header = Some(self.outgoing_aux_header(self.next_nwk_frame_counter())); Some(self.core().nib.nwk_security.network_key()) } else { @@ -531,6 +521,22 @@ impl ZigbeeStack { } } + /// The auxiliary header our frames are secured with. Its length does not depend on + /// the frame counter, so a size check can pass any. + pub(super) fn outgoing_aux_header(&self, frame_counter: u32) -> NwkAuxHeader { + NwkAuxHeader { + security_control: NwkSecurityHeaderControlField { + security_level: NwkSecurityLevel::NoSecurity, + key_id: NwkSecurityHeaderKeyId::NetworkKey, + extended_nonce: true, + require_verified_frame_counter: false, + }, + frame_counter, + extended_source: Some(self.state.ieee_address), + key_sequence_number: self.core().nib.nwk_security.active_key_seq_number(), + } + } + fn increment_tx_total(&self) { let tx_total = { let mut core = self.core(); From 9086ff34cf9075997ecd0342567340ee639a427f Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:23:31 +0000 Subject: [PATCH 13/19] Decide route records in next-hop resolution, for held and relayed frames too --- .../src/zigbee_stack/neighbor.rs | 9 +- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 201 +++----- .../ziggurat-driver/src/zigbee_stack/route.rs | 52 +- .../ziggurat-driver/src/zigbee_stack/sends.rs | 92 +++- crates/ziggurat-zigbee/src/nwk/next_hop.rs | 453 +++++++++++++++++- crates/ziggurat-zigbee/src/sends/mod.rs | 81 +++- crates/ziggurat-zigbee/src/sends/tests.rs | 52 +- crates/ziggurat-zigbee/src/sends/unicasts.rs | 26 +- 8 files changed, 727 insertions(+), 239 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index c365de22..321019d8 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -67,16 +67,9 @@ impl ZigbeeStack { pub(super) fn sends_directly_to(&self, destination: Nwk) -> bool { let now = self.core_now(); let core = self.core(); - let neighbors = &core.nib.neighbors; let policy = self.next_hop_policy(&core.nib); - neighbors.end_device_child_eui64(destination).is_some() - || next_hop::is_direct_neighbor(neighbors, destination, policy.direct_max_link_cost) - || neighbors.is_recently_attached_router_child( - destination, - now, - policy.new_router_child_window, - ) + next_hop::reaches_directly(&core.nib.neighbors, destination, policy, now) } pub(super) fn sleepy_child_eui64(&self, nwk: Nwk) -> Option { diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index bfb482e5..4a3668a2 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -404,44 +404,31 @@ impl ZigbeeStack { let now = self.core_now(); let mut core = self.core(); - nwk_frame.nwk_header.sequence_number = core.nib.next_sequence_number(); + let nib = &mut core.nib; + nwk_frame.nwk_header.sequence_number = nib.next_sequence_number(); + let next_hop_policy = self.next_hop_policy(nib); let resolved = next_hop::resolve( - &core.nib.routing, - &core.nib.neighbors, + &mut nib.routing, + &nib.neighbors, &mut nwk_frame, &mode, - self.next_hop_policy(&core.nib), + next_hop_policy, now, ); let handle = match resolved { - NextHop::Resolved(next_hop) => { - if nwk_frame.nwk_header.frame_control.frame_type == NwkFrameType::Data - && nwk_frame.nwk_header.source == self.state.network_address - && core.nib.routing.route_record_due(destination, false) - { - self.enqueue_route_record( - &mut core, - self.state.network_address, - self.state.ieee_address, - destination, - Vec::new(), - next_hop, - policy.priority, - ); - } - - let poll_address = Self::poll_address(&core.nib, next_hop); - self.enqueue_unicast_in( - &mut core, - Frame::nwk(nwk_frame, security), - policy, - confirm, - next_hop, - poll_address, - ) - } + NextHop::Resolved { + next_hop, + route_record, + } => self.enqueue_resolved_in( + &mut core, + Frame::nwk(nwk_frame, security), + policy, + confirm, + next_hop, + route_record, + ), NextHop::NeedDiscovery => self.hold_for_route( &mut core, Frame::nwk(nwk_frame, security), @@ -722,7 +709,7 @@ impl ZigbeeStack { ), None => core .sends - .enqueue_unicast(unicast, self.core_now(), &self.tunables), + .enqueue_unicast(unicast, None, self.core_now(), &self.tunables), }; } } @@ -941,115 +928,57 @@ impl ZigbeeStack { } } - let next_hop_address = if let Some(source_route) = &mut nwk_frame.nwk_header.source_route { - // Spec 3.6.4.3.2: a source-routed frame names its own path; the relay - // list is followed instead of the routing table - let index = usize::from(source_route.relay_index); - - let next_hop = if index == 0 { - // The final relay forwards directly to the NWK destination - destination - } else { - if source_route.relays.get(index) != Some(&self.state.network_address) { - tracing::debug!("Dropping source routed frame not addressed through us"); - return; - } - - source_route.relay_index -= 1; - source_route.relays[index - 1] - }; - - // Delivery to our own end device child skips the rest of the relay list - let next_hop = if self.end_device_child_eui64(destination).is_some() { - destination - } else { - next_hop - }; - - self.core() - .nib - .routing - .note_source_routed_frame(nwk_frame.nwk_header.source); - - next_hop - } else if self.sends_directly_to(destination) { - destination - } else { - let next_hop = self.core().nib.routing.next_hop(destination); - - match next_hop { - Some(next_hop) => next_hop, - // Spec 3.6.4.5.1: a relay discovers a route only for a frame from its own - // end device child that allows discovery. End devices do not discover - // routes themselves, so their parent does it for them - None if nwk_frame.nwk_header.frame_control.discover_route - == NwkRouteDiscovery::Enable - && self - .end_device_child_eui64(nwk_frame.nwk_header.source) - .is_some() => - { - let now = self.core_now(); - let mut core = self.core(); - self.hold_for_route( - &mut core, - Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey), - TxPriority::UserNormal, - Confirm::OnHandoff, - now, - ); - self.commit_sends(core); - return; - } - // Any other frame is dropped: a relay never discovers on behalf of a - // router, which recovers through its own discovery or APS retries - None => { - tracing::debug!("No active route to relay frame to {destination:?}, dropping"); - return; - } - } - }; - - tracing::debug!( - "Relaying frame from {:?} to {destination:?} via {next_hop_address:?}", - nwk_frame.nwk_header.source - ); - - let source = nwk_frame.nwk_header.source; - let child_eui64 = self.end_device_child_eui64(source); + let now = self.core_now(); let mut core = self.core(); + let nib = &mut core.nib; + let policy = self.next_hop_policy(nib); + let resolved = next_hop::resolve( + &mut nib.routing, + &nib.neighbors, + &mut nwk_frame, + &SendMode::Relay, + policy, + now, + ); - // Spec 3.6.4.5.5: a data frame from our end device child toward a concentrator - // is preceded by a route record for the child, starting with us - if let Some(child_eui64) = child_eui64 - && nwk_frame.nwk_header.frame_control.frame_type == NwkFrameType::Data - && core.nib.routing.route_record_due(destination, true) - { - self.enqueue_route_record( - &mut core, - source, - child_eui64, - destination, - Vec::from([self.state.network_address]), - next_hop_address, - TxPriority::UserNormal, - ); + let frame = Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey); + match resolved { + NextHop::Resolved { + next_hop, + route_record, + } => { + tracing::debug!("Relaying frame to {destination:?} via {next_hop:?}"); + + // The originator's sequence number is preserved. Any failure handling + // (route invalidation, the network status back to the originator) follows + // the send table's verdict; nothing is awaited here. + self.enqueue_resolved_in( + &mut core, + frame, + TxPolicy { + priority: TxPriority::UserNormal, + class: TrafficClass::Forwarding, + }, + Confirm::OnHandoff, + next_hop, + route_record, + ); + } + NextHop::NeedDiscovery => { + self.hold_for_route( + &mut core, + frame, + TxPriority::UserNormal, + Confirm::OnHandoff, + now, + ); + } + NextHop::Discard => { + tracing::debug!("Not relaying frame to {destination:?}, no route"); + return; + } } - // The originator's sequence number is preserved. Any failure handling (route - // invalidation, the network status back to the originator) follows the send - // table's verdict; nothing is awaited here. - let poll_address = Self::poll_address(&core.nib, next_hop_address); - self.enqueue_unicast_in( - &mut core, - Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey), - TxPolicy { - priority: TxPriority::UserNormal, - class: TrafficClass::Forwarding, - }, - Confirm::OnHandoff, - next_hop_address, - poll_address, - ); self.commit_sends(core); } diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 591f5bb7..cbdf4e5c 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -3,7 +3,7 @@ use core::cmp; use core::time::Duration; use alloc::vec::Vec; -use ziggurat_ieee_802154::types::{Eui64, Nwk}; +use ziggurat_ieee_802154::types::Nwk; use ziggurat_phy::RadioPhy; use ziggurat_zigbee::nwk::commands::{ @@ -11,13 +11,14 @@ use ziggurat_zigbee::nwk::commands::{ NwkRouteReplyCommand, NwkRouteRequestCommand, NwkRouteRequestManyToOne, }; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; +use ziggurat_zigbee::nwk::next_hop::RouteRecord; use super::TrafficClass; use super::routing::RouteReplyDisposition; use super::{ - AddrConflictSource, Broadcast, Confirm, Frame, NwkSecurityMode, SendHandle, SendMode, TxPolicy, - TxPriority, Unicast, ZigbeeCore, ZigbeeStack, + AddrConflictSource, Broadcast, Confirm, Frame, Nib, NwkSecurityMode, SendHandle, SendMode, + TxPolicy, TxPriority, Unicast, ZigbeeCore, ZigbeeStack, }; impl ZigbeeStack { @@ -433,20 +434,26 @@ impl ZigbeeStack { self.core().nib.is_concentrator } - /// Spec 3.6.4.5.5: tell a concentrator the path from `source`, ourselves or our end - /// device child, ahead of a data frame to it over the same next hop. `relays` is - /// the path so far: empty from us, our own address from a child. - #[allow(clippy::too_many_arguments)] - pub(super) fn enqueue_route_record( + /// Spec 3.6.4.5.5: the route record that tells `concentrator` the path from us or + /// our end device child, sent ahead of a data frame to it. + pub(super) fn route_record_frame( &self, - core: &mut ZigbeeCore, - source: Nwk, - source_eui64: Eui64, + nib: &mut Nib, + record: RouteRecord, concentrator: Nwk, - relays: Vec, - next_hop: Nwk, - priority: TxPriority, - ) { + ) -> Frame { + let (source, source_eui64, relays) = match record { + RouteRecord::Ours => ( + self.state.network_address, + self.state.ieee_address, + Vec::new(), + ), + // The path from our child starts with us + RouteRecord::Child { nwk, eui64 } => { + (nwk, eui64, Vec::from([self.state.network_address])) + } + }; + tracing::debug!("Sending a route record for {source:?} to {concentrator:?}"); let frame = self @@ -456,20 +463,9 @@ impl ZigbeeStack { ) .with_source(source) .with_source_ieee(Some(source_eui64)) - .with_sequence_number(core.nib.next_sequence_number()); + .with_sequence_number(nib.next_sequence_number()); - let poll_address = Self::poll_address(&core.nib, next_hop); - self.enqueue_unicast_in( - core, - Frame::nwk(frame, NwkSecurityMode::NetworkKey), - TxPolicy { - priority, - class: TrafficClass::Critical, - }, - Confirm::OnHandoff, - next_hop, - poll_address, - ); + Frame::nwk(frame, NwkSecurityMode::NetworkKey) } pub(super) fn invalidate_routes_via(&self, next_hop: Nwk) { diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index 0e7fa4c0..1f43b658 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -14,9 +14,9 @@ use ziggurat_ieee_802154::types::Nwk; use ziggurat_phy::RadioPhy; use ziggurat_zigbee::Instant as CoreInstant; use ziggurat_zigbee::gp::build_gpdf_to_gpd; -use ziggurat_zigbee::nwk::next_hop::{self, NextHop}; +use ziggurat_zigbee::nwk::next_hop::{self, NextHop, RouteRecord}; use ziggurat_zigbee::sends::{ - Action, Broadcast as BroadcastRecord, Gpdf as GpdfRecord, TransmitError, + Action, Broadcast as BroadcastRecord, Gpdf as GpdfRecord, Routed, TransmitError, Unicast as UnicastRecord, }; @@ -65,6 +65,42 @@ impl ZigbeeStack { next_hop, poll_address, }, + None, + self.core_now(), + &self.tunables, + ); + + SendHandle::new(id, &self.send_watches) + } + + /// Enqueue a NWK unicast to the next hop resolution chose, preceded by the route + /// record it found due. Under a core lock the caller holds and commits. + pub(super) fn enqueue_resolved_in( + &self, + core: &mut ZigbeeCore, + frame: Frame, + policy: TxPolicy, + confirm: Confirm, + next_hop: Nwk, + route_record: Option, + ) -> SendHandle { + let Frame::Nwk { nwk_frame, .. } = &frame else { + unreachable!("only NWK unicasts are routed") + }; + let destination = nwk_frame.nwk_header.destination; + + let preceded_by = + route_record.map(|record| self.route_record_frame(&mut core.nib, record, destination)); + let poll_address = Self::poll_address(&core.nib, next_hop); + let id = core.sends.enqueue_unicast( + UnicastRecord { + frame, + priority: policy.priority, + confirm, + next_hop, + poll_address, + }, + preceded_by, self.core_now(), &self.tunables, ); @@ -199,6 +235,7 @@ impl ZigbeeStack { /// The stack settings next-hop resolution reads. pub(super) fn next_hop_policy(&self, nib: &Nib) -> next_hop::Policy { next_hop::Policy { + network_address: self.state.network_address, is_concentrator: nib.is_concentrator, force_route_discovery: self.state.hack_force_route_discovery, max_source_route: self.tunables.max_source_route(), @@ -216,45 +253,56 @@ impl ZigbeeStack { .map(Ieee802154Address::Eui64) } - /// Resolve the route of an unrouted frame again: its next hop and the address it - /// polls under if it is a sleepy child. `None` means no route yet. + /// Resolve the route of an unrouted frame again: how it is sent once it has one. + /// `None` means no route yet. fn resolve_unrouted_unicast( &self, - nib: &Nib, + nib: &mut Nib, frame: &mut Frame, now: CoreInstant, - ) -> Option<(Nwk, Option)> { + ) -> Option> { let Frame::Nwk { nwk_frame, .. } = frame else { unreachable!("only NWK unicasts await a route") }; + let destination = nwk_frame.nwk_header.destination; // A forced discovery holds the frame only while it is underway. Once it is // answered or has lapsed, the frame takes any route like every other frame let mut policy = self.next_hop_policy(nib); - // Spec 3.6.4.3: only a frame we originate takes a stored source route, not one - // we relay for an end device child - policy.is_concentrator &= nwk_frame.nwk_header.source == self.state.network_address; - policy.force_route_discovery &= nib.routing.own_discovery_underway( - self.state.network_address, - nwk_frame.nwk_header.destination, - now, - ); + policy.force_route_discovery &= + nib.routing + .own_discovery_underway(self.state.network_address, destination, now); + + // The frames we hold that we did not originate are relayed for our end device + // children + let mode = if nwk_frame.nwk_header.source == self.state.network_address { + SendMode::Route(RouteDirective::StackDecides) + } else { + SendMode::Relay + }; let resolved = next_hop::resolve( - &nib.routing, + &mut nib.routing, &nib.neighbors, nwk_frame, - &SendMode::Route(RouteDirective::StackDecides), + &mode, policy, now, ); match resolved { - NextHop::Resolved(next_hop) => Some((next_hop, Self::poll_address(nib, next_hop))), - NextHop::NeedDiscovery => None, - NextHop::Discard => { - unreachable!("a frame is only held for a route if it allows discovery") - } + NextHop::Resolved { + next_hop, + route_record, + } => Some(Routed { + next_hop, + poll_address: Self::poll_address(nib, next_hop), + preceded_by: route_record + .map(|record| self.route_record_frame(nib, record, destination)), + }), + // A relayed frame is discarded once its source is no longer our child. It + // stays held until its deadline, as it did before + NextHop::NeedDiscovery | NextHop::Discard => None, } } @@ -370,7 +418,7 @@ impl ZigbeeStack { .deliver_broadcasts(|key| self.passive_ack_quorum_heard(&core.nib, key)); core.sends.tick(now, &self.tunables, |frame| { - self.resolve_unrouted_unicast(&core.nib, frame, now) + self.resolve_unrouted_unicast(&mut core.nib, frame, now) }); let discoveries = core.nib.routing.tick_discoveries( diff --git a/crates/ziggurat-zigbee/src/nwk/next_hop.rs b/crates/ziggurat-zigbee/src/nwk/next_hop.rs index 12abe51e..af68a8a4 100644 --- a/crates/ziggurat-zigbee/src/nwk/next_hop.rs +++ b/crates/ziggurat-zigbee/src/nwk/next_hop.rs @@ -1,14 +1,17 @@ -//! The MAC next hop of a unicast we originate: a decision over the routing and -//! neighbor tables that may rewrite the frame to carry a source route (spec 3.6.4.3). +//! The MAC next hop of a unicast we originate or relay. +//! +//! A decision over the routing and neighbor tables that may rewrite the frame to carry +//! a source route (spec 3.6.4.3), with the route record due ahead of it (spec +//! 3.6.4.5.5). use alloc::vec::Vec; use core::time::Duration; -use ziggurat_ieee_802154::types::Nwk; +use ziggurat_ieee_802154::types::{Eui64, Nwk}; use crate::Instant; -use crate::nwk::frame::{NwkFrame, NwkRouteDiscovery, NwkSourceRoute}; +use crate::nwk::frame::{NwkFrame, NwkFrameType, NwkRouteDiscovery, NwkSourceRoute}; use crate::nwk::neighbors::Neighbors; use crate::nwk::routing::{Route, Routing}; @@ -23,6 +26,9 @@ pub enum SendMode { /// the route table or an applicable source route, discovering a route first if none is /// known. Route(RouteDirective), + /// Relay another device's frame: follow its source route, or route it like our own. + /// Only a frame from our own end device child may wait for a route discovery. + Relay, } /// How the host wants an originated unicast routed. @@ -53,11 +59,23 @@ pub enum HostRoute { SourceRoute(Vec), } +/// A route record that must precede a data frame to a concentrator (spec 3.6.4.5.5). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RouteRecord { + /// For a frame we originate: the path starts at us. + Ours, + /// For a frame we relay for our end device child: the path starts at the child. + Child { nwk: Nwk, eui64: Eui64 }, +} + /// The outcome of resolving a unicast's MAC next hop. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NextHop { - /// Transmit to this next hop now. - Resolved(Nwk), + /// Transmit to this next hop now, after the route record when one is due. + Resolved { + next_hop: Nwk, + route_record: Option, + }, /// No route known; the frame must wait for route discovery. NeedDiscovery, /// No route known and the frame's `discover_route` flag forbids discovering one. @@ -67,6 +85,8 @@ pub enum NextHop { /// The stack settings next-hop resolution reads. #[derive(Debug, Clone, Copy)] pub struct Policy { + /// Our own network address. + pub network_address: Nwk, /// We store route records and source-route through them. pub is_concentrator: bool, /// Ignore every known route and always discover, so routing logic is exercised. @@ -93,25 +113,161 @@ pub fn is_direct_neighbor(neighbors: &Neighbors, destination: Nwk, max_link_cost }) } -/// Resolve the MAC next hop for a unicast. +/// Whether we send to `destination` directly, with no route: our end device child, a +/// neighbor over a good link, or a router child that just attached. +pub fn reaches_directly( + neighbors: &Neighbors, + destination: Nwk, + policy: Policy, + now: Instant, +) -> bool { + neighbors.end_device_child_eui64(destination).is_some() + || is_direct_neighbor(neighbors, destination, policy.direct_max_link_cost) + || neighbors.is_recently_attached_router_child( + destination, + now, + policy.new_router_child_window, + ) +} + +/// Resolve the MAC next hop for a unicast, and the route record due ahead of it. /// -/// A source-routed result rewrites `frame`'s header in place (spec 3.6.4.3.1). When no -/// route is known the frame's `discover_route` flag decides between discovery and -/// discard. +/// Following or applying a source route rewrites `frame`'s header in place (spec +/// 3.6.4.3). A due route record is taken from the routing table, so a resolved frame +/// must be sent. pub fn resolve( - routing: &Routing, + routing: &mut Routing, neighbors: &Neighbors, frame: &mut NwkFrame, mode: &SendMode, policy: Policy, now: Instant, ) -> NextHop { + let mut resolved = match mode { + SendMode::Direct => NextHop::Resolved { + next_hop: frame.nwk_header.destination, + route_record: None, + }, + SendMode::Route(directive) => route(routing, neighbors, frame, directive, policy, now), + SendMode::Relay => relay(routing, neighbors, frame, policy, now), + }; + + if let NextHop::Resolved { route_record, .. } = &mut resolved { + *route_record = due_route_record(routing, neighbors, frame, policy.network_address); + } + + resolved +} + +/// Spec 3.6.4.5.5: the route record due ahead of a data frame from us or our end device +/// child toward a concentrator. +fn due_route_record( + routing: &mut Routing, + neighbors: &Neighbors, + frame: &NwkFrame, + network_address: Nwk, +) -> Option { + if frame.nwk_header.frame_control.frame_type != NwkFrameType::Data { + return None; + } + + let source = frame.nwk_header.source; let destination = frame.nwk_header.destination; - let directive = match mode { - SendMode::Direct => return NextHop::Resolved(destination), - SendMode::Route(directive) => directive, - }; + if source == network_address { + return routing + .route_record_due(destination, false) + .then_some(RouteRecord::Ours); + } + + let eui64 = neighbors.end_device_child_eui64(source)?; + routing + .route_record_due(destination, true) + .then_some(RouteRecord::Child { nwk: source, eui64 }) +} + +/// Spec 3.6.4.3: the next hop of a frame we relay. +fn relay( + routing: &mut Routing, + neighbors: &Neighbors, + frame: &mut NwkFrame, + policy: Policy, + now: Instant, +) -> NextHop { + let source = frame.nwk_header.source; + let destination = frame.nwk_header.destination; + + if let Some(source_route) = &mut frame.nwk_header.source_route { + // Spec 3.6.4.3.2: a source-routed frame names its own path; the relay list is + // followed instead of the routing table + let index = usize::from(source_route.relay_index); + + let next_hop = if index == 0 { + // The final relay forwards directly to the NWK destination + destination + } else { + if source_route.relays.get(index) != Some(&policy.network_address) { + tracing::debug!("Source routed frame is not addressed through us"); + return NextHop::Discard; + } + + source_route.relay_index -= 1; + source_route.relays[index - 1] + }; + + routing.note_source_routed_frame(source); + + // Delivery to our own end device child skips the rest of the relay list + if neighbors.end_device_child_eui64(destination).is_some() { + return NextHop::Resolved { + next_hop: destination, + route_record: None, + }; + } + + return NextHop::Resolved { + next_hop, + route_record: None, + }; + } + + if reaches_directly(neighbors, destination, policy, now) { + return NextHop::Resolved { + next_hop: destination, + route_record: None, + }; + } + + if let Some(next_hop) = routing.next_hop(destination) { + return NextHop::Resolved { + next_hop, + route_record: None, + }; + } + + // Spec 3.6.4.5.1: a relay discovers a route only for a frame from its own end device + // child that allows discovery. End devices do not discover routes themselves, so + // their parent does it for them. A relay never discovers on behalf of a router, + // which recovers through its own discovery or APS retries + if frame.nwk_header.frame_control.discover_route == NwkRouteDiscovery::Enable + && neighbors.end_device_child_eui64(source).is_some() + { + NextHop::NeedDiscovery + } else { + NextHop::Discard + } +} + +/// The next hop of a frame we originate. +fn route( + routing: &Routing, + neighbors: &Neighbors, + frame: &mut NwkFrame, + directive: &RouteDirective, + policy: Policy, + now: Instant, +) -> NextHop { + let destination = frame.nwk_header.destination; // A forced host route overrides everything, including a known route. if let RouteDirective::Force(route) = directive { @@ -121,14 +277,20 @@ pub fn resolve( // End device children never route-discover; their parent delivers directly. This // also keeps a stale route record from outliving a device rejoining as our child. if neighbors.end_device_child_eui64(destination).is_some() { - return NextHop::Resolved(destination); + return NextHop::Resolved { + next_hop: destination, + route_record: None, + }; } // A neighbor with a good link is reached directly. No route is cheaper if !policy.force_route_discovery && is_direct_neighbor(neighbors, destination, policy.direct_max_link_cost) { - return NextHop::Resolved(destination); + return NextHop::Resolved { + next_hop: destination, + route_record: None, + }; } // A stored source route (concentrator behavior) wins over the routing table. @@ -142,7 +304,12 @@ pub fn resolve( }; match routing.route_to(destination, policy.max_source_route, first_hop_usable) { - Some(Route::NextHop(next_hop)) => return NextHop::Resolved(next_hop), + Some(Route::NextHop(next_hop)) => { + return NextHop::Resolved { + next_hop, + route_record: None, + }; + } Some(Route::SourceRouted(relays)) => return apply_source_route(frame, relays), None => {} } @@ -152,7 +319,10 @@ pub fn resolve( if !policy.force_route_discovery && let Some(next_hop) = routing.next_hop(destination) { - return NextHop::Resolved(next_hop); + return NextHop::Resolved { + next_hop, + route_record: None, + }; } // A router child that just attached has sent no link status yet, send to it @@ -164,7 +334,10 @@ pub fn resolve( policy.new_router_child_window, ) { - return NextHop::Resolved(destination); + return NextHop::Resolved { + next_hop: destination, + route_record: None, + }; } // No usable route. A host hint stands in for discovery rather than triggering it. @@ -185,7 +358,10 @@ fn apply_host_route(frame: &mut NwkFrame, route: &HostRoute) -> NextHop { match route { // The next hop routes onward itself, so `discover_route` is left as built: // an intermediate hop still needs it to reach the final destination. - HostRoute::NextHop(next_hop) => NextHop::Resolved(*next_hop), + HostRoute::NextHop(next_hop) => NextHop::Resolved { + next_hop: *next_hop, + route_record: None, + }, HostRoute::SourceRoute(relays) => apply_source_route(frame, relays.clone()), } } @@ -199,5 +375,238 @@ fn apply_source_route(frame: &mut NwkFrame, relays: Vec) -> NextHop { relay_index: relays.len() as u8 - 1, relays, }); - NextHop::Resolved(next_hop) + NextHop::Resolved { + next_hop, + route_record: None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::nwk::NwkDeviceType; + use crate::nwk::activity::ActivityParams; + use crate::nwk::commands::{NwkCommand, NwkRouteRecordCommand, NwkRouteRequestManyToOne}; + use crate::nwk::frame::{Nsdu, NwkFrameControl, NwkHeader, NwkPayload}; + use crate::nwk::neighbors::{ChildDescriptor, Relationship}; + + const OWN: Nwk = Nwk(0x0000); + const CONCENTRATOR: Nwk = Nwk(0x1111); + const RELAY: Nwk = Nwk(0x2222); + const CHILD: Nwk = Nwk(0x3333); + const CHILD_EUI64: Eui64 = Eui64([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); + + const NOW: Instant = Instant::from_micros(0); + const ACTIVITY: ActivityParams = ActivityParams { + initial_count: 3, + period: Duration::from_secs(15), + }; + const POLICY: Policy = Policy { + network_address: OWN, + is_concentrator: false, + force_route_discovery: false, + max_source_route: 11, + source_route_max_first_hop_cost: 3, + new_router_child_window: Duration::from_secs(30), + direct_max_link_cost: 2, + }; + + /// A routing table with a many-to-one route to `CONCENTRATOR` through `RELAY`, from + /// a request that asks for route records. + fn routing_to_concentrator() -> Routing { + let mut routing = Routing::default(); + routing.accept_route_request( + CONCENTRATOR, + 1, + Nwk(0xFFFC), + RELAY, + 2, + NwkRouteRequestManyToOne::ManyToOneSenderSupportsRouteRecordTable, + NOW, + Duration::from_secs(10), + ACTIVITY, + ); + routing + } + + fn neighbors_with_child() -> Neighbors { + let mut neighbors = Neighbors::default(); + neighbors.upsert_child( + ChildDescriptor { + eui64: CHILD_EUI64, + network_address: CHILD, + device_type: NwkDeviceType::EndDevice, + rx_on_when_idle: false, + device_timeout: Some(Duration::from_secs(60)), + relationship: Relationship::Child, + }, + NOW, + ACTIVITY, + ); + neighbors + } + + fn frame(frame_type: NwkFrameType, source: Nwk, payload: NwkPayload) -> NwkFrame { + NwkFrame { + nwk_header: NwkHeader { + frame_control: NwkFrameControl { + frame_type, + protocol_version: 2, + discover_route: NwkRouteDiscovery::Enable, + multicast: false, + security: true, + source_route: false, + destination: false, + extended_source: false, + end_device_initiator: false, + reserved1: 0, + }, + destination: CONCENTRATOR, + source, + radius: 30, + sequence_number: 1, + destination_ieee: None, + source_ieee: None, + multicast_control: None, + source_route: None, + }, + aux_header: None, + payload, + } + } + + fn data_frame(source: Nwk) -> NwkFrame { + frame( + NwkFrameType::Data, + source, + NwkPayload::Opaque(Nsdu::from_slice(&[0x00]).unwrap()), + ) + } + + fn resolve_frame( + routing: &mut Routing, + neighbors: &Neighbors, + mut frame: NwkFrame, + mode: &SendMode, + ) -> NextHop { + resolve(routing, neighbors, &mut frame, mode, POLICY, NOW) + } + + // A concentrator that keeps a route record table needs our route record once per + // request for it + #[test] + fn test_our_data_frame_takes_the_route_record_once() { + let mut routing = routing_to_concentrator(); + let neighbors = Neighbors::default(); + let mode = SendMode::Route(RouteDirective::StackDecides); + + assert_eq!( + resolve_frame(&mut routing, &neighbors, data_frame(OWN), &mode), + NextHop::Resolved { + next_hop: RELAY, + route_record: Some(RouteRecord::Ours), + } + ); + assert_eq!( + resolve_frame(&mut routing, &neighbors, data_frame(OWN), &mode), + NextHop::Resolved { + next_hop: RELAY, + route_record: None, + } + ); + } + + // Spec 3.6.4.5.5: every data frame from an end device child to a concentrator needs + // a route record, and taking one leaves our own request in place + #[test] + fn test_relayed_child_data_frame_always_takes_a_route_record() { + let mut routing = routing_to_concentrator(); + let neighbors = neighbors_with_child(); + let child_record = NextHop::Resolved { + next_hop: RELAY, + route_record: Some(RouteRecord::Child { + nwk: CHILD, + eui64: CHILD_EUI64, + }), + }; + + for _ in 0..2 { + assert_eq!( + resolve_frame( + &mut routing, + &neighbors, + data_frame(CHILD), + &SendMode::Relay + ), + child_record + ); + } + + assert_eq!( + resolve_frame( + &mut routing, + &neighbors, + data_frame(OWN), + &SendMode::Route(RouteDirective::StackDecides) + ), + NextHop::Resolved { + next_hop: RELAY, + route_record: Some(RouteRecord::Ours), + } + ); + } + + // Only data frames carry route records, and only from us or our end device child + #[test] + fn test_no_route_record_for_commands_or_other_sources() { + let mut routing = routing_to_concentrator(); + let neighbors = neighbors_with_child(); + let command = frame( + NwkFrameType::Command, + OWN, + NwkPayload::Command(NwkCommand::RouteRecord(NwkRouteRecordCommand { + relays: Vec::new(), + })), + ); + + assert_eq!( + resolve_frame( + &mut routing, + &neighbors, + command, + &SendMode::Route(RouteDirective::StackDecides) + ), + NextHop::Resolved { + next_hop: RELAY, + route_record: None, + } + ); + assert_eq!( + resolve_frame( + &mut routing, + &neighbors, + data_frame(Nwk(0x4444)), + &SendMode::Relay + ), + NextHop::Resolved { + next_hop: RELAY, + route_record: None, + } + ); + + // Neither frame took our own request + assert_eq!( + resolve_frame( + &mut routing, + &neighbors, + data_frame(OWN), + &SendMode::Route(RouteDirective::StackDecides) + ), + NextHop::Resolved { + next_hop: RELAY, + route_record: Some(RouteRecord::Ours), + } + ); + } } diff --git a/crates/ziggurat-zigbee/src/sends/mod.rs b/crates/ziggurat-zigbee/src/sends/mod.rs index 4f2dd765..5e68a36e 100644 --- a/crates/ziggurat-zigbee/src/sends/mod.rs +++ b/crates/ziggurat-zigbee/src/sends/mod.rs @@ -36,6 +36,7 @@ mod unicasts; mod unrouted; use alloc::collections::VecDeque; +use alloc::vec::Vec; use core::cmp::Reverse; use core::time::Duration; @@ -51,7 +52,7 @@ use crate::nwk::routing::RouteRequestId; pub use broadcasts::{Broadcast, Schedule}; pub use gpdfs::{Gpdf, GpdfTrigger}; -pub use unicasts::Unicast; +pub use unicasts::{Routed, Unicast}; pub use unrouted::UnroutedUnicast; use broadcasts::Broadcasts; @@ -293,16 +294,49 @@ impl> Sends { self.outbox.pop_front() } - /// Enqueue a unicast with a known next hop. + /// Enqueue a unicast with a known next hop. `preceded_by` is sent first, to the same + /// next hop at the same priority, and the unicast waits until it is settled. pub fn enqueue_unicast( &mut self, unicast: Unicast, + preceded_by: Option, now: Instant, tunables: &Tunables, ) -> SendId { + let first = preceded_by.map(|frame| self.enqueue_ahead(frame, &unicast, now, tunables)); + let id = self.next_id(); self.unicasts - .enqueue(id, unicast, now, None, None, tunables); + .enqueue(id, unicast, now, None, None, first, tunables); + + id + } + + /// Enqueue `frame` to go ahead of `unicast`: to the same next hop, at the same + /// priority. + fn enqueue_ahead( + &mut self, + frame: F, + unicast: &Unicast, + now: Instant, + tunables: &Tunables, + ) -> SendId { + let id = self.next_id(); + self.unicasts.enqueue( + id, + Unicast { + frame, + priority: unicast.priority, + confirm: Confirm::OnHandoff, + next_hop: unicast.next_hop, + poll_address: unicast.poll_address, + }, + now, + None, + None, + None, + tunables, + ); id } @@ -316,7 +350,7 @@ impl> Sends { ) -> SendId { let id = self.next_id(); self.unicasts - .enqueue(id, unicast, now, None, Some(broadcast), tunables); + .enqueue(id, unicast, now, None, Some(broadcast), None, tunables); id } @@ -496,29 +530,37 @@ impl> Sends { } } - /// Move every unrouted send that `next_hop` finds a next hop for. + /// Move every unrouted send that `route` finds a next hop for. fn route_unicasts( &mut self, now: Instant, tunables: &Tunables, - mut next_hop: impl FnMut(&mut F) -> Option<(Nwk, Option)>, + mut route: impl FnMut(&mut F) -> Option>, ) { // A send without a next hop stays held - for (id, unrouted, (next_hop, poll_address)) in - self.unrouted_unicasts.take_routed(&mut next_hop) - { + let routed: Vec<_> = self.unrouted_unicasts.take_routed(&mut route).collect(); + + for (id, unrouted, routed) in routed { + let unicast = Unicast { + frame: unrouted.frame, + priority: unrouted.priority, + confirm: unrouted.confirm, + next_hop: routed.next_hop, + poll_address: routed.poll_address, + }; + + let first = routed + .preceded_by + .map(|frame| self.enqueue_ahead(frame, &unicast, now, tunables)); + + // The send keeps the deadline it was held with self.unicasts.enqueue( id, - Unicast { - frame: unrouted.frame, - priority: unrouted.priority, - confirm: unrouted.confirm, - next_hop, - poll_address, - }, + unicast, now, Some(unrouted.deadline), None, + first, tunables, ); } @@ -582,13 +624,12 @@ impl> Sends { &mut self, now: Instant, tunables: &Tunables, - // A frame's next hop, and the address its device polls under if the frame must - // wait for its poll - next_hop: impl FnMut(&mut F) -> Option<(Nwk, Option)>, + // How a held frame is sent once it has a route, `None` while it has none + route: impl FnMut(&mut F) -> Option>, ) { // Fail the sends past their deadline first, so routing never revives one self.unrouted_unicasts.tick(now, &mut self.outbox); - self.route_unicasts(now, tunables, next_hop); + self.route_unicasts(now, tunables, route); self.unicasts.tick(now, &mut self.outbox); self.broadcasts.tick(now, &mut self.outbox); diff --git a/crates/ziggurat-zigbee/src/sends/tests.rs b/crates/ziggurat-zigbee/src/sends/tests.rs index 3d058251..234d8cc3 100644 --- a/crates/ziggurat-zigbee/src/sends/tests.rs +++ b/crates/ziggurat-zigbee/src/sends/tests.rs @@ -72,6 +72,7 @@ impl Fixture { next_hop: CHILD_NWK, poll_address: Some(poll_address), }, + None, self.now, &self.tunables, ); @@ -173,8 +174,21 @@ impl Fixture { /// Run a timer pass in which the routing table offers this next hop toward /// `DESTINATION`. Returns what the pass settles. fn pass(&mut self, next_hop: Option) -> Vec { + self.pass_preceded(next_hop, None) + } + + /// [`Self::pass`], with a frame the routed send must be preceded by. + fn pass_preceded( + &mut self, + next_hop: Option, + preceded_by: Option<&'static str>, + ) -> Vec { self.sends.tick(self.now, &self.tunables, |_| { - next_hop.map(|next_hop| (next_hop, None)) + next_hop.map(|next_hop| Routed { + next_hop, + poll_address: None, + preceded_by, + }) }); self.settled() } @@ -284,6 +298,42 @@ fn test_held_unicast_is_routed_once_a_next_hop_is_found() { )); } +// A route record found due when a held unicast is routed goes out first, and the +// unicast waits until it is settled, retries included +#[test] +fn test_held_unicast_waits_for_the_frame_routed_ahead_of_it() { + let mut fixture = Fixture::new(); + let held = fixture.hold_unicast(); + + assert!( + fixture + .pass_preceded(Some(NEXT_HOP), Some("route record")) + .is_empty() + ); + + let in_flight = fixture.dequeue().unwrap(); + assert_eq!(in_flight.frame, "route record"); + assert!(matches!( + in_flight.transmit(), + Transmit::Unicast { next_hop, .. } if next_hop == NEXT_HOP + )); + + // The first attempt fails: the unicast keeps waiting for the retry + assert!(fixture.dequeue().is_none()); + let failed = Err(TransmitError::Failed(SendFailure::Cancelled)); + assert!(fixture.report(in_flight, failed).is_empty()); + assert!(fixture.pass(None).is_empty()); + + let in_flight = fixture.dequeue().unwrap(); + assert_eq!(in_flight.frame, "route record"); + let record = in_flight.id; + assert_eq!(fixture.transmitted(in_flight), [(record, Ok(()))]); + + let in_flight = fixture.dequeue().unwrap(); + assert_eq!(in_flight.frame, "held unicast"); + assert_eq!(fixture.transmitted(in_flight), [(held, Ok(()))]); +} + #[test] fn test_held_unicast_fails_at_its_deadline() { let mut fixture = Fixture::new(); diff --git a/crates/ziggurat-zigbee/src/sends/unicasts.rs b/crates/ziggurat-zigbee/src/sends/unicasts.rs index 2794e730..87110bff 100644 --- a/crates/ziggurat-zigbee/src/sends/unicasts.rs +++ b/crates/ziggurat-zigbee/src/sends/unicasts.rs @@ -29,6 +29,16 @@ pub struct Unicast { pub poll_address: Option, } +/// How a held unicast is sent once it has a route. +#[derive(Debug)] +pub struct Routed { + pub next_hop: Nwk, + /// The address the device polls under, if the frame must wait for its poll. + pub poll_address: Option, + /// A frame sent first, to the same next hop. + pub preceded_by: Option, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Stage { /// Ready for the sender. @@ -60,6 +70,8 @@ struct Record { deadline: Instant, /// The broadcast this frame copies to a sleepy child. copy_of: Option, + /// The send that goes first: this frame is not sent while that one is in the table. + after: Option, } impl Record { @@ -120,7 +132,9 @@ impl> Unicasts { /// A unicast fails if not handed off within the handoff timeout; a held frame if /// not polled for within the transaction persistence time. A send admitted earlier /// passes the deadline it was admitted with: it replaces the handoff timeout and - /// caps the persistence time. + /// caps the persistence time. A send `after` another is not sent while that one is + /// in the table. + #[allow(clippy::too_many_arguments)] pub(super) fn enqueue( &mut self, id: SendId, @@ -128,6 +142,7 @@ impl> Unicasts { now: Instant, admitted_deadline: Option, copy_of: Option, + after: Option, tunables: &Tunables, ) { let persistence_deadline = now + tunables.transaction_persistence_time(); @@ -150,6 +165,7 @@ impl> Unicasts { stage, deadline, copy_of, + after, }, ); } @@ -159,7 +175,13 @@ impl> Unicasts { pub(super) fn best_queued(&self, now: Instant) -> Option<(SendId, TxPriority)> { self.records .iter() - .filter(|(_, record)| record.stage == Stage::Queued && now < record.deadline) + .filter(|(_, record)| { + record.stage == Stage::Queued + && now < record.deadline + && record + .after + .is_none_or(|first| !self.records.contains_key(&first)) + }) .max_by_key(|(id, record)| (record.priority, Reverse(**id))) .map(|(id, record)| (*id, record.priority)) } From c5c8d3bbec09da492f5b35b29e355583c086b6ee Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:57:30 +0000 Subject: [PATCH 14/19] Send route records at transmit time and keep them due until the concentrator source-routes to us --- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 42 +-- .../ziggurat-driver/src/zigbee_stack/route.rs | 84 ++++-- .../ziggurat-driver/src/zigbee_stack/sends.rs | 58 +---- .../ziggurat-driver/src/zigbee_stack/zdp.rs | 3 +- crates/ziggurat-zigbee/src/nwk/next_hop.rs | 241 +++++------------- crates/ziggurat-zigbee/src/nwk/routing.rs | 63 +++-- crates/ziggurat-zigbee/src/sends/mod.rs | 72 ++---- crates/ziggurat-zigbee/src/sends/tests.rs | 69 ++--- crates/ziggurat-zigbee/src/sends/unicasts.rs | 26 +- 9 files changed, 254 insertions(+), 404 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 4a3668a2..c9eb1783 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -184,6 +184,14 @@ impl ZigbeeStack { ); } + // A frame the concentrator source-routed to us shows it has our route + if nwk_frame.nwk_header.source_route.is_some() { + self.core() + .nib + .routing + .note_source_routed_frame(nwk_frame.nwk_header.source); + } + // Update the address cache. Hearing a device is not a join, so the address keeps // its session state. if let Some(src_eui64) = nwk_frame.nwk_header.source_ieee { @@ -418,17 +426,17 @@ impl ZigbeeStack { ); let handle = match resolved { - NextHop::Resolved { - next_hop, - route_record, - } => self.enqueue_resolved_in( - &mut core, - Frame::nwk(nwk_frame, security), - policy, - confirm, - next_hop, - route_record, - ), + NextHop::Resolved(next_hop) => { + let poll_address = Self::poll_address(&core.nib, next_hop); + self.enqueue_unicast_in( + &mut core, + Frame::nwk(nwk_frame, security), + policy, + confirm, + next_hop, + poll_address, + ) + } NextHop::NeedDiscovery => self.hold_for_route( &mut core, Frame::nwk(nwk_frame, security), @@ -709,7 +717,7 @@ impl ZigbeeStack { ), None => core .sends - .enqueue_unicast(unicast, None, self.core_now(), &self.tunables), + .enqueue_unicast(unicast, self.core_now(), &self.tunables), }; } } @@ -943,16 +951,14 @@ impl ZigbeeStack { let frame = Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey); match resolved { - NextHop::Resolved { - next_hop, - route_record, - } => { + NextHop::Resolved(next_hop) => { tracing::debug!("Relaying frame to {destination:?} via {next_hop:?}"); // The originator's sequence number is preserved. Any failure handling // (route invalidation, the network status back to the originator) follows // the send table's verdict; nothing is awaited here. - self.enqueue_resolved_in( + let poll_address = Self::poll_address(&core.nib, next_hop); + self.enqueue_unicast_in( &mut core, frame, TxPolicy { @@ -961,7 +967,7 @@ impl ZigbeeStack { }, Confirm::OnHandoff, next_hop, - route_record, + poll_address, ); } NextHop::NeedDiscovery => { diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index cbdf4e5c..ba897970 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -11,14 +11,14 @@ use ziggurat_zigbee::nwk::commands::{ NwkRouteReplyCommand, NwkRouteRequestCommand, NwkRouteRequestManyToOne, }; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; -use ziggurat_zigbee::nwk::next_hop::RouteRecord; +use ziggurat_zigbee::nwk::next_hop::{self, RouteRecord}; use super::TrafficClass; use super::routing::RouteReplyDisposition; use super::{ - AddrConflictSource, Broadcast, Confirm, Frame, Nib, NwkSecurityMode, SendHandle, SendMode, - TxPolicy, TxPriority, Unicast, ZigbeeCore, ZigbeeStack, + AddrConflictSource, Broadcast, Confirm, Frame, NwkSecurityMode, SendHandle, SendMode, TxPolicy, + TxPriority, Unicast, ZigbeeCore, ZigbeeStack, }; impl ZigbeeStack { @@ -434,38 +434,70 @@ impl ZigbeeStack { self.core().nib.is_concentrator } - /// Spec 3.6.4.5.5: the route record that tells `concentrator` the path from us or - /// our end device child, sent ahead of a data frame to it. - pub(super) fn route_record_frame( - &self, - nib: &mut Nib, - record: RouteRecord, - concentrator: Nwk, - ) -> Frame { - let (source, source_eui64, relays) = match record { - RouteRecord::Ours => ( + /// Spec 3.6.4.5.5: transmit the route record due before `data`, to the same next hop. + /// The route record tells the concentrator the path from us or our end device + /// child. It goes out once here, so it always precedes the data. If it is not + /// acked, the send table retries it like any other unicast. + // The lint misses that `nib` borrows the guard until the frame is built + #[allow(clippy::significant_drop_tightening)] + pub(super) async fn transmit_route_record(&self, data: &NwkFrame, next_hop: Nwk) { + let concentrator = data.nwk_header.destination; + + let mut frame = { + let mut core = self.core(); + let nib = &mut core.nib; + + let Some(record) = next_hop::route_record_due( + &nib.routing, + &nib.neighbors, + data, self.state.network_address, - self.state.ieee_address, - Vec::new(), - ), - // The path from our child starts with us - RouteRecord::Child { nwk, eui64 } => { - (nwk, eui64, Vec::from([self.state.network_address])) - } - }; + ) else { + return; + }; + + let (source, source_eui64, relays) = match record { + RouteRecord::Ours => { + nib.routing.note_route_record_sent(concentrator, next_hop); + ( + self.state.network_address, + self.state.ieee_address, + Vec::new(), + ) + } + // The path from our child starts with us + RouteRecord::Child { nwk, eui64 } => { + (nwk, eui64, Vec::from([self.state.network_address])) + } + }; - tracing::debug!("Sending a route record for {source:?} to {concentrator:?}"); + tracing::debug!("Sending a route record for {source:?} to {concentrator:?}"); - let frame = self - .nwk_command_frame( + self.nwk_command_frame( concentrator, NwkCommand::RouteRecord(NwkRouteRecordCommand { relays }), ) .with_source(source) .with_source_ieee(Some(source_eui64)) - .with_sequence_number(nib.next_sequence_number()); + .with_sequence_number(nib.next_sequence_number()) + }; - Frame::nwk(frame, NwkSecurityMode::NetworkKey) + let result = self + .transmit_unicast(&mut frame, next_hop, NwkSecurityMode::NetworkKey, false) + .await; + + if result.is_err() { + drop(self.enqueue_unicast( + Frame::nwk(frame, NwkSecurityMode::NetworkKey), + TxPolicy { + priority: TxPriority::UserNormal, + class: TrafficClass::Critical, + }, + Confirm::OnHandoff, + next_hop, + None, + )); + } } pub(super) fn invalidate_routes_via(&self, next_hop: Nwk) { diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index 1f43b658..cef11337 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -14,7 +14,7 @@ use ziggurat_ieee_802154::types::Nwk; use ziggurat_phy::RadioPhy; use ziggurat_zigbee::Instant as CoreInstant; use ziggurat_zigbee::gp::build_gpdf_to_gpd; -use ziggurat_zigbee::nwk::next_hop::{self, NextHop, RouteRecord}; +use ziggurat_zigbee::nwk::next_hop::{self, NextHop}; use ziggurat_zigbee::sends::{ Action, Broadcast as BroadcastRecord, Gpdf as GpdfRecord, Routed, TransmitError, Unicast as UnicastRecord, @@ -65,42 +65,6 @@ impl ZigbeeStack { next_hop, poll_address, }, - None, - self.core_now(), - &self.tunables, - ); - - SendHandle::new(id, &self.send_watches) - } - - /// Enqueue a NWK unicast to the next hop resolution chose, preceded by the route - /// record it found due. Under a core lock the caller holds and commits. - pub(super) fn enqueue_resolved_in( - &self, - core: &mut ZigbeeCore, - frame: Frame, - policy: TxPolicy, - confirm: Confirm, - next_hop: Nwk, - route_record: Option, - ) -> SendHandle { - let Frame::Nwk { nwk_frame, .. } = &frame else { - unreachable!("only NWK unicasts are routed") - }; - let destination = nwk_frame.nwk_header.destination; - - let preceded_by = - route_record.map(|record| self.route_record_frame(&mut core.nib, record, destination)); - let poll_address = Self::poll_address(&core.nib, next_hop); - let id = core.sends.enqueue_unicast( - UnicastRecord { - frame, - priority: policy.priority, - confirm, - next_hop, - poll_address, - }, - preceded_by, self.core_now(), &self.tunables, ); @@ -253,14 +217,14 @@ impl ZigbeeStack { .map(Ieee802154Address::Eui64) } - /// Resolve the route of an unrouted frame again: how it is sent once it has one. - /// `None` means no route yet. + /// Resolve the route of an unrouted frame again: its next hop, and the address it + /// polls under if it is a sleepy child. `None` means no route yet. fn resolve_unrouted_unicast( &self, nib: &mut Nib, frame: &mut Frame, now: CoreInstant, - ) -> Option> { + ) -> Option { let Frame::Nwk { nwk_frame, .. } = frame else { unreachable!("only NWK unicasts await a route") }; @@ -291,14 +255,9 @@ impl ZigbeeStack { ); match resolved { - NextHop::Resolved { - next_hop, - route_record, - } => Some(Routed { + NextHop::Resolved(next_hop) => Some(Routed { next_hop, poll_address: Self::poll_address(nib, next_hop), - preceded_by: route_record - .map(|record| self.route_record_frame(nib, record, destination)), }), // A relayed frame is discarded once its source is no longer our child. It // stays held until its deadline, as it did before @@ -352,12 +311,19 @@ impl ZigbeeStack { Transmit::Unicast { next_hop, frame_pending, + first_attempt, }, Frame::Nwk { nwk_frame, security, }, ) => { + // Spec 3.6.4.5.5: the route record goes out before the data frame, not + // before its retries + if first_attempt { + self.transmit_route_record(nwk_frame, next_hop).await; + } + self.transmit_unicast(nwk_frame, next_hop, *security, frame_pending) .await } diff --git a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 68fafc2d..23206351 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -174,7 +174,8 @@ impl ZigbeeStack { }, memory_constrained: false, many_to_one: entry.many_to_one, - route_record_required: entry.route_record_required, + route_record_required: entry.route_record_state + != routing::RouteRecordState::Known, next_hop_address: entry.next_hop_address, }) .collect(); diff --git a/crates/ziggurat-zigbee/src/nwk/next_hop.rs b/crates/ziggurat-zigbee/src/nwk/next_hop.rs index af68a8a4..0b390135 100644 --- a/crates/ziggurat-zigbee/src/nwk/next_hop.rs +++ b/crates/ziggurat-zigbee/src/nwk/next_hop.rs @@ -1,8 +1,8 @@ -//! The MAC next hop of a unicast we originate or relay. +//! The MAC next hop of a unicast we originate or relay, and the route record due before +//! it is transmitted. //! //! A decision over the routing and neighbor tables that may rewrite the frame to carry -//! a source route (spec 3.6.4.3), with the route record due ahead of it (spec -//! 3.6.4.5.5). +//! a source route (spec 3.6.4.3). use alloc::vec::Vec; use core::time::Duration; @@ -59,7 +59,8 @@ pub enum HostRoute { SourceRoute(Vec), } -/// A route record that must precede a data frame to a concentrator (spec 3.6.4.5.5). +/// A route record to transmit just before a data frame to a concentrator (spec +/// 3.6.4.5.5). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RouteRecord { /// For a frame we originate: the path starts at us. @@ -71,11 +72,8 @@ pub enum RouteRecord { /// The outcome of resolving a unicast's MAC next hop. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NextHop { - /// Transmit to this next hop now, after the route record when one is due. - Resolved { - next_hop: Nwk, - route_record: Option, - }, + /// Transmit to this next hop now. + Resolved(Nwk), /// No route known; the frame must wait for route discovery. NeedDiscovery, /// No route known and the frame's `discover_route` flag forbids discovering one. @@ -130,11 +128,10 @@ pub fn reaches_directly( ) } -/// Resolve the MAC next hop for a unicast, and the route record due ahead of it. +/// Resolve the MAC next hop for a unicast. /// /// Following or applying a source route rewrites `frame`'s header in place (spec -/// 3.6.4.3). A due route record is taken from the routing table, so a resolved frame -/// must be sent. +/// 3.6.4.3). pub fn resolve( routing: &mut Routing, neighbors: &Neighbors, @@ -143,26 +140,17 @@ pub fn resolve( policy: Policy, now: Instant, ) -> NextHop { - let mut resolved = match mode { - SendMode::Direct => NextHop::Resolved { - next_hop: frame.nwk_header.destination, - route_record: None, - }, + match mode { + SendMode::Direct => NextHop::Resolved(frame.nwk_header.destination), SendMode::Route(directive) => route(routing, neighbors, frame, directive, policy, now), SendMode::Relay => relay(routing, neighbors, frame, policy, now), - }; - - if let NextHop::Resolved { route_record, .. } = &mut resolved { - *route_record = due_route_record(routing, neighbors, frame, policy.network_address); } - - resolved } -/// Spec 3.6.4.5.5: the route record due ahead of a data frame from us or our end device -/// child toward a concentrator. -fn due_route_record( - routing: &mut Routing, +/// Spec 3.6.4.5.5: the route record to transmit just before a data frame from us or our +/// end device child toward a concentrator. +pub fn route_record_due( + routing: &Routing, neighbors: &Neighbors, frame: &NwkFrame, network_address: Nwk, @@ -176,13 +164,16 @@ fn due_route_record( if source == network_address { return routing - .route_record_due(destination, false) + .route_record_required(destination, false) .then_some(RouteRecord::Ours); } + // TODO: spec 3.6.4.5.5 allows skipping the route record for a child that already + // received a frame the concentrator source-routed to it. We send one before every + // relayed frame. let eui64 = neighbors.end_device_child_eui64(source)?; routing - .route_record_due(destination, true) + .route_record_required(destination, true) .then_some(RouteRecord::Child { nwk: source, eui64 }) } @@ -219,30 +210,18 @@ fn relay( // Delivery to our own end device child skips the rest of the relay list if neighbors.end_device_child_eui64(destination).is_some() { - return NextHop::Resolved { - next_hop: destination, - route_record: None, - }; + return NextHop::Resolved(destination); } - return NextHop::Resolved { - next_hop, - route_record: None, - }; + return NextHop::Resolved(next_hop); } if reaches_directly(neighbors, destination, policy, now) { - return NextHop::Resolved { - next_hop: destination, - route_record: None, - }; + return NextHop::Resolved(destination); } if let Some(next_hop) = routing.next_hop(destination) { - return NextHop::Resolved { - next_hop, - route_record: None, - }; + return NextHop::Resolved(next_hop); } // Spec 3.6.4.5.1: a relay discovers a route only for a frame from its own end device @@ -277,20 +256,14 @@ fn route( // End device children never route-discover; their parent delivers directly. This // also keeps a stale route record from outliving a device rejoining as our child. if neighbors.end_device_child_eui64(destination).is_some() { - return NextHop::Resolved { - next_hop: destination, - route_record: None, - }; + return NextHop::Resolved(destination); } // A neighbor with a good link is reached directly. No route is cheaper if !policy.force_route_discovery && is_direct_neighbor(neighbors, destination, policy.direct_max_link_cost) { - return NextHop::Resolved { - next_hop: destination, - route_record: None, - }; + return NextHop::Resolved(destination); } // A stored source route (concentrator behavior) wins over the routing table. @@ -305,10 +278,7 @@ fn route( match routing.route_to(destination, policy.max_source_route, first_hop_usable) { Some(Route::NextHop(next_hop)) => { - return NextHop::Resolved { - next_hop, - route_record: None, - }; + return NextHop::Resolved(next_hop); } Some(Route::SourceRouted(relays)) => return apply_source_route(frame, relays), None => {} @@ -319,10 +289,7 @@ fn route( if !policy.force_route_discovery && let Some(next_hop) = routing.next_hop(destination) { - return NextHop::Resolved { - next_hop, - route_record: None, - }; + return NextHop::Resolved(next_hop); } // A router child that just attached has sent no link status yet, send to it @@ -334,10 +301,7 @@ fn route( policy.new_router_child_window, ) { - return NextHop::Resolved { - next_hop: destination, - route_record: None, - }; + return NextHop::Resolved(destination); } // No usable route. A host hint stands in for discovery rather than triggering it. @@ -358,10 +322,7 @@ fn apply_host_route(frame: &mut NwkFrame, route: &HostRoute) -> NextHop { match route { // The next hop routes onward itself, so `discover_route` is left as built: // an intermediate hop still needs it to reach the final destination. - HostRoute::NextHop(next_hop) => NextHop::Resolved { - next_hop: *next_hop, - route_record: None, - }, + HostRoute::NextHop(next_hop) => NextHop::Resolved(*next_hop), HostRoute::SourceRoute(relays) => apply_source_route(frame, relays.clone()), } } @@ -375,10 +336,7 @@ fn apply_source_route(frame: &mut NwkFrame, relays: Vec) -> NextHop { relay_index: relays.len() as u8 - 1, relays, }); - NextHop::Resolved { - next_hop, - route_record: None, - } + NextHop::Resolved(next_hop) } #[cfg(test)] @@ -402,15 +360,6 @@ mod tests { initial_count: 3, period: Duration::from_secs(15), }; - const POLICY: Policy = Policy { - network_address: OWN, - is_concentrator: false, - force_route_discovery: false, - max_source_route: 11, - source_route_max_first_hop_cost: 3, - new_router_child_window: Duration::from_secs(30), - direct_max_link_cost: 2, - }; /// A routing table with a many-to-one route to `CONCENTRATOR` through `RELAY`, from /// a request that asks for route records. @@ -484,83 +433,64 @@ mod tests { ) } - fn resolve_frame( - routing: &mut Routing, - neighbors: &Neighbors, - mut frame: NwkFrame, - mode: &SendMode, - ) -> NextHop { - resolve(routing, neighbors, &mut frame, mode, POLICY, NOW) + // A concentrator that keeps a route record table needs our route record until it + // source-routes a frame through us after we sent one + #[test] + fn test_our_data_frames_need_route_records_until_the_concentrator_has_our_route() { + let mut routing = routing_to_concentrator(); + let neighbors = Neighbors::default(); + let due = |routing: &Routing| route_record_due(routing, &neighbors, &data_frame(OWN), OWN); + + // A source route built before the concentrator asked again is no proof + routing.note_source_routed_frame(CONCENTRATOR); + assert_eq!(due(&routing), Some(RouteRecord::Ours)); + + // Sending one is no proof either + routing.note_route_record_sent(CONCENTRATOR, RELAY); + assert_eq!(due(&routing), Some(RouteRecord::Ours)); + + routing.note_source_routed_frame(CONCENTRATOR); + assert_eq!(due(&routing), None); } - // A concentrator that keeps a route record table needs our route record once per - // request for it + // A concentrator that is our neighbor needs no source route to reach us #[test] - fn test_our_data_frame_takes_the_route_record_once() { + fn test_neighbor_concentrator_needs_one_route_record() { let mut routing = routing_to_concentrator(); let neighbors = Neighbors::default(); - let mode = SendMode::Route(RouteDirective::StackDecides); + routing.note_route_record_sent(CONCENTRATOR, CONCENTRATOR); assert_eq!( - resolve_frame(&mut routing, &neighbors, data_frame(OWN), &mode), - NextHop::Resolved { - next_hop: RELAY, - route_record: Some(RouteRecord::Ours), - } - ); - assert_eq!( - resolve_frame(&mut routing, &neighbors, data_frame(OWN), &mode), - NextHop::Resolved { - next_hop: RELAY, - route_record: None, - } + route_record_due(&routing, &neighbors, &data_frame(OWN), OWN), + None ); } // Spec 3.6.4.5.5: every data frame from an end device child to a concentrator needs - // a route record, and taking one leaves our own request in place + // a route record, even once the concentrator has our own route #[test] - fn test_relayed_child_data_frame_always_takes_a_route_record() { + fn test_child_data_frames_always_need_a_route_record() { let mut routing = routing_to_concentrator(); let neighbors = neighbors_with_child(); - let child_record = NextHop::Resolved { - next_hop: RELAY, - route_record: Some(RouteRecord::Child { - nwk: CHILD, - eui64: CHILD_EUI64, - }), - }; + + routing.note_route_record_sent(CONCENTRATOR, RELAY); + routing.note_source_routed_frame(CONCENTRATOR); for _ in 0..2 { assert_eq!( - resolve_frame( - &mut routing, - &neighbors, - data_frame(CHILD), - &SendMode::Relay - ), - child_record + route_record_due(&routing, &neighbors, &data_frame(CHILD), OWN), + Some(RouteRecord::Child { + nwk: CHILD, + eui64: CHILD_EUI64, + }) ); } - - assert_eq!( - resolve_frame( - &mut routing, - &neighbors, - data_frame(OWN), - &SendMode::Route(RouteDirective::StackDecides) - ), - NextHop::Resolved { - next_hop: RELAY, - route_record: Some(RouteRecord::Ours), - } - ); } - // Only data frames carry route records, and only from us or our end device child + // Only data frames need route records, and only from us or our end device child #[test] fn test_no_route_record_for_commands_or_other_sources() { - let mut routing = routing_to_concentrator(); + let routing = routing_to_concentrator(); let neighbors = neighbors_with_child(); let command = frame( NwkFrameType::Command, @@ -570,43 +500,10 @@ mod tests { })), ); + assert_eq!(route_record_due(&routing, &neighbors, &command, OWN), None); assert_eq!( - resolve_frame( - &mut routing, - &neighbors, - command, - &SendMode::Route(RouteDirective::StackDecides) - ), - NextHop::Resolved { - next_hop: RELAY, - route_record: None, - } - ); - assert_eq!( - resolve_frame( - &mut routing, - &neighbors, - data_frame(Nwk(0x4444)), - &SendMode::Relay - ), - NextHop::Resolved { - next_hop: RELAY, - route_record: None, - } - ); - - // Neither frame took our own request - assert_eq!( - resolve_frame( - &mut routing, - &neighbors, - data_frame(OWN), - &SendMode::Route(RouteDirective::StackDecides) - ), - NextHop::Resolved { - next_hop: RELAY, - route_record: Some(RouteRecord::Ours), - } + route_record_due(&routing, &neighbors, &data_frame(Nwk(0x4444)), OWN), + None ); } } diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index b0076815..876888d2 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -26,6 +26,17 @@ pub enum Status { Inactive = 3, } +/// Spec 3.6.4.5.5: whether a concentrator still needs our route record. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RouteRecordState { + /// The concentrator has our route, or never asked for it. + Known, + /// The concentrator asked for our route record, and we have not sent one since. + Needed, + /// We sent a route record, but the concentrator has not yet shown it has our route. + Sent, +} + #[derive(Debug)] pub struct TableEntry { /// Destination address the routing table entry is for @@ -40,9 +51,9 @@ pub struct TableEntry { /// many-to-one route request. pub many_to_one: bool, - /// A flag indicating that a route record command frame SHOULD be sent to the - /// destination prior to the next data packet. - pub route_record_required: bool, + /// Whether a route record command frame SHOULD be sent to the destination prior to + /// the next data packet (the spec's "route record required" flag). + pub route_record_state: RouteRecordState, /// When set to TRUE, this flag indicates that an expected regular many-to-one route /// request was missed, i.e. the last many-to-one route request for this destination @@ -85,7 +96,7 @@ impl TableEntry { status, no_route_cache: false, many_to_one: false, - route_record_required: false, + route_record_state: RouteRecordState::Known, expired: false, next_hop_address, path_cost: u8::MAX, @@ -582,12 +593,11 @@ impl Routing { /// Spec 3.6.4.5.5: whether a route record has to precede a data frame toward /// `destination` over its many-to-one route. A frame relayed for one of our end - /// device children always needs one. A frame we originate needs one while the - /// concentrator asks for it: a concentrator that keeps a route record table then - /// has our route until its next advertisement asks again, so the request is - /// cleared; one that keeps none needs a route record before every frame. - pub fn route_record_due(&mut self, destination: Nwk, for_end_device_child: bool) -> bool { - let Some(entry) = self.route_table.get_mut(&destination) else { + /// device children always needs one. A frame we originate needs one until the + /// concentrator shows it has our route. A concentrator that keeps no route cache + /// needs one before every frame. + pub fn route_record_required(&self, destination: Nwk, for_end_device_child: bool) -> bool { + let Some(entry) = self.route_table.get(&destination) else { return false; }; @@ -595,26 +605,31 @@ impl Routing { return false; } - if for_end_device_child { - return true; - } + for_end_device_child + || entry.no_route_cache + || entry.route_record_state != RouteRecordState::Known + } - let due = entry.route_record_required; - if !entry.no_route_cache { - entry.route_record_required = false; + /// We transmitted our route record to `concentrator` via `next_hop`. A concentrator + /// that is our neighbor needs no source route to reach us. + pub fn note_route_record_sent(&mut self, concentrator: Nwk, next_hop: Nwk) { + if let Some(entry) = self.route_table.get_mut(&concentrator) { + entry.route_record_state = if next_hop == concentrator { + RouteRecordState::Known + } else { + RouteRecordState::Sent + }; } - - due } - /// Spec 3.6.4.3.2: relaying a source-routed frame proves the concentrator that - /// originated it holds a route record for the frame's source; no route record - /// has to precede the next frame toward it (unless it keeps no route cache). + /// A frame source-routed by `concentrator` reached us, so it has a source route + /// through us (spec 3.6.4.3.2). It only proves the concentrator has our route if + /// our route record went out after its last advertisement. pub fn note_source_routed_frame(&mut self, concentrator: Nwk) { if let Some(entry) = self.route_table.get_mut(&concentrator) - && !entry.no_route_cache + && entry.route_record_state == RouteRecordState::Sent { - entry.route_record_required = false; + entry.route_record_state = RouteRecordState::Known; } } @@ -800,7 +815,7 @@ impl Routing { // concentrator; spec 3.6.4.5.1.8: a later plain request never clears it if many_to_one != NwkRouteRequestManyToOne::NotManyToOne { originator_entry.many_to_one = true; - originator_entry.route_record_required = true; + originator_entry.route_record_state = RouteRecordState::Needed; originator_entry.no_route_cache = many_to_one == NwkRouteRequestManyToOne::ManyToOneSenderDoesntSupportRouteRecordTable; } diff --git a/crates/ziggurat-zigbee/src/sends/mod.rs b/crates/ziggurat-zigbee/src/sends/mod.rs index 5e68a36e..680f14d1 100644 --- a/crates/ziggurat-zigbee/src/sends/mod.rs +++ b/crates/ziggurat-zigbee/src/sends/mod.rs @@ -36,7 +36,6 @@ mod unicasts; mod unrouted; use alloc::collections::VecDeque; -use alloc::vec::Vec; use core::cmp::Reverse; use core::time::Duration; @@ -165,10 +164,11 @@ pub enum Confirm { #[derive(Debug, Clone, Copy)] pub enum Transmit { /// A MAC unicast to `next_hop`. `frame_pending` tells a polling device that more - /// frames await it (802.15.4 spec 6.7.3). + /// frames await it (802.15.4 spec 6.7.3). `first_attempt` is false for a retry. Unicast { next_hop: Nwk, frame_pending: bool, + first_attempt: bool, }, Broadcast, /// A GPDF timed from its trigger, without CSMA, retries, or an ACK. @@ -294,49 +294,16 @@ impl> Sends { self.outbox.pop_front() } - /// Enqueue a unicast with a known next hop. `preceded_by` is sent first, to the same - /// next hop at the same priority, and the unicast waits until it is settled. + /// Enqueue a unicast with a known next hop. pub fn enqueue_unicast( &mut self, unicast: Unicast, - preceded_by: Option, now: Instant, tunables: &Tunables, ) -> SendId { - let first = preceded_by.map(|frame| self.enqueue_ahead(frame, &unicast, now, tunables)); - let id = self.next_id(); self.unicasts - .enqueue(id, unicast, now, None, None, first, tunables); - - id - } - - /// Enqueue `frame` to go ahead of `unicast`: to the same next hop, at the same - /// priority. - fn enqueue_ahead( - &mut self, - frame: F, - unicast: &Unicast, - now: Instant, - tunables: &Tunables, - ) -> SendId { - let id = self.next_id(); - self.unicasts.enqueue( - id, - Unicast { - frame, - priority: unicast.priority, - confirm: Confirm::OnHandoff, - next_hop: unicast.next_hop, - poll_address: unicast.poll_address, - }, - now, - None, - None, - None, - tunables, - ); + .enqueue(id, unicast, now, None, None, tunables); id } @@ -350,7 +317,7 @@ impl> Sends { ) -> SendId { let id = self.next_id(); self.unicasts - .enqueue(id, unicast, now, None, Some(broadcast), None, tunables); + .enqueue(id, unicast, now, None, Some(broadcast), tunables); id } @@ -535,32 +502,23 @@ impl> Sends { &mut self, now: Instant, tunables: &Tunables, - mut route: impl FnMut(&mut F) -> Option>, + mut route: impl FnMut(&mut F) -> Option, ) { // A send without a next hop stays held - let routed: Vec<_> = self.unrouted_unicasts.take_routed(&mut route).collect(); - - for (id, unrouted, routed) in routed { - let unicast = Unicast { - frame: unrouted.frame, - priority: unrouted.priority, - confirm: unrouted.confirm, - next_hop: routed.next_hop, - poll_address: routed.poll_address, - }; - - let first = routed - .preceded_by - .map(|frame| self.enqueue_ahead(frame, &unicast, now, tunables)); - + for (id, unrouted, routed) in self.unrouted_unicasts.take_routed(&mut route) { // The send keeps the deadline it was held with self.unicasts.enqueue( id, - unicast, + Unicast { + frame: unrouted.frame, + priority: unrouted.priority, + confirm: unrouted.confirm, + next_hop: routed.next_hop, + poll_address: routed.poll_address, + }, now, Some(unrouted.deadline), None, - first, tunables, ); } @@ -625,7 +583,7 @@ impl> Sends { now: Instant, tunables: &Tunables, // How a held frame is sent once it has a route, `None` while it has none - route: impl FnMut(&mut F) -> Option>, + route: impl FnMut(&mut F) -> Option, ) { // Fail the sends past their deadline first, so routing never revives one self.unrouted_unicasts.tick(now, &mut self.outbox); diff --git a/crates/ziggurat-zigbee/src/sends/tests.rs b/crates/ziggurat-zigbee/src/sends/tests.rs index 234d8cc3..15a9197e 100644 --- a/crates/ziggurat-zigbee/src/sends/tests.rs +++ b/crates/ziggurat-zigbee/src/sends/tests.rs @@ -72,7 +72,6 @@ impl Fixture { next_hop: CHILD_NWK, poll_address: Some(poll_address), }, - None, self.now, &self.tunables, ); @@ -174,20 +173,10 @@ impl Fixture { /// Run a timer pass in which the routing table offers this next hop toward /// `DESTINATION`. Returns what the pass settles. fn pass(&mut self, next_hop: Option) -> Vec { - self.pass_preceded(next_hop, None) - } - - /// [`Self::pass`], with a frame the routed send must be preceded by. - fn pass_preceded( - &mut self, - next_hop: Option, - preceded_by: Option<&'static str>, - ) -> Vec { self.sends.tick(self.now, &self.tunables, |_| { next_hop.map(|next_hop| Routed { next_hop, poll_address: None, - preceded_by, }) }); self.settled() @@ -280,58 +269,52 @@ fn test_held_unicast_waits_without_a_next_hop() { assert!(fixture.dequeue().is_none()); } -// A held unicast waits for a next hop, not for a discovery: any pass that finds one -// releases it. +// Only a unicast's first transmit is marked as such; its retries are not #[test] -fn test_held_unicast_is_routed_once_a_next_hop_is_found() { +fn test_retry_is_not_a_first_attempt() { let mut fixture = Fixture::new(); fixture.hold_unicast(); - assert!(fixture.pass(Some(NEXT_HOP)).is_empty()); - assert!(!fixture.holding()); let in_flight = fixture.dequeue().unwrap(); - assert_eq!(in_flight.frame, "held unicast"); assert!(matches!( in_flight.transmit(), - Transmit::Unicast { next_hop, .. } if next_hop == NEXT_HOP + Transmit::Unicast { + first_attempt: true, + .. + } )); + let failed = Err(TransmitError::Failed(SendFailure::Cancelled)); + assert!(fixture.report(in_flight, failed).is_empty()); + assert!(fixture.pass(None).is_empty()); + + let in_flight = fixture.dequeue().unwrap(); + assert!(matches!( + in_flight.transmit(), + Transmit::Unicast { + first_attempt: false, + .. + } + )); + assert_eq!(fixture.transmitted(in_flight).len(), 1); } -// A route record found due when a held unicast is routed goes out first, and the -// unicast waits until it is settled, retries included +// A held unicast waits for a next hop, not for a discovery: any pass that finds one +// releases it. #[test] -fn test_held_unicast_waits_for_the_frame_routed_ahead_of_it() { +fn test_held_unicast_is_routed_once_a_next_hop_is_found() { let mut fixture = Fixture::new(); - let held = fixture.hold_unicast(); + fixture.hold_unicast(); - assert!( - fixture - .pass_preceded(Some(NEXT_HOP), Some("route record")) - .is_empty() - ); + assert!(fixture.pass(Some(NEXT_HOP)).is_empty()); + assert!(!fixture.holding()); let in_flight = fixture.dequeue().unwrap(); - assert_eq!(in_flight.frame, "route record"); + assert_eq!(in_flight.frame, "held unicast"); assert!(matches!( in_flight.transmit(), Transmit::Unicast { next_hop, .. } if next_hop == NEXT_HOP )); - - // The first attempt fails: the unicast keeps waiting for the retry - assert!(fixture.dequeue().is_none()); - let failed = Err(TransmitError::Failed(SendFailure::Cancelled)); - assert!(fixture.report(in_flight, failed).is_empty()); - assert!(fixture.pass(None).is_empty()); - - let in_flight = fixture.dequeue().unwrap(); - assert_eq!(in_flight.frame, "route record"); - let record = in_flight.id; - assert_eq!(fixture.transmitted(in_flight), [(record, Ok(()))]); - - let in_flight = fixture.dequeue().unwrap(); - assert_eq!(in_flight.frame, "held unicast"); - assert_eq!(fixture.transmitted(in_flight), [(held, Ok(()))]); } #[test] diff --git a/crates/ziggurat-zigbee/src/sends/unicasts.rs b/crates/ziggurat-zigbee/src/sends/unicasts.rs index 87110bff..74b5d347 100644 --- a/crates/ziggurat-zigbee/src/sends/unicasts.rs +++ b/crates/ziggurat-zigbee/src/sends/unicasts.rs @@ -31,12 +31,10 @@ pub struct Unicast { /// How a held unicast is sent once it has a route. #[derive(Debug)] -pub struct Routed { +pub struct Routed { pub next_hop: Nwk, /// The address the device polls under, if the frame must wait for its poll. pub poll_address: Option, - /// A frame sent first, to the same next hop. - pub preceded_by: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -66,12 +64,12 @@ struct Record { /// Transmit attempts left after the current one. A failed transmit of a held frame /// waits for the next poll instead, until the frame expires. attempts_remaining: u8, + /// The frame was lent to the radio before. + attempted: bool, stage: Stage, deadline: Instant, /// The broadcast this frame copies to a sleepy child. copy_of: Option, - /// The send that goes first: this frame is not sent while that one is in the table. - after: Option, } impl Record { @@ -132,9 +130,7 @@ impl> Unicasts { /// A unicast fails if not handed off within the handoff timeout; a held frame if /// not polled for within the transaction persistence time. A send admitted earlier /// passes the deadline it was admitted with: it replaces the handoff timeout and - /// caps the persistence time. A send `after` another is not sent while that one is - /// in the table. - #[allow(clippy::too_many_arguments)] + /// caps the persistence time. pub(super) fn enqueue( &mut self, id: SendId, @@ -142,7 +138,6 @@ impl> Unicasts { now: Instant, admitted_deadline: Option, copy_of: Option, - after: Option, tunables: &Tunables, ) { let persistence_deadline = now + tunables.transaction_persistence_time(); @@ -162,10 +157,10 @@ impl> Unicasts { next_hop: unicast.next_hop, poll_address: unicast.poll_address, attempts_remaining: tunables.unicast_retries(), + attempted: false, stage, deadline, copy_of, - after, }, ); } @@ -175,13 +170,7 @@ impl> Unicasts { pub(super) fn best_queued(&self, now: Instant) -> Option<(SendId, TxPriority)> { self.records .iter() - .filter(|(_, record)| { - record.stage == Stage::Queued - && now < record.deadline - && record - .after - .is_none_or(|first| !self.records.contains_key(&first)) - }) + .filter(|(_, record)| record.stage == Stage::Queued && now < record.deadline) .max_by_key(|(id, record)| (record.priority, Reverse(**id))) .map(|(id, record)| (*id, record.priority)) } @@ -202,6 +191,8 @@ impl> Unicasts { let record = self.records.get_mut(&id).unwrap(); debug_assert_eq!(record.stage, Stage::Queued); record.stage = Stage::Transmitting { acked: false }; + let first_attempt = !record.attempted; + record.attempted = true; InFlight { id, @@ -209,6 +200,7 @@ impl> Unicasts { transmit: Transmit::Unicast { next_hop: record.next_hop, frame_pending, + first_attempt, }, } } From 61c07dd4acb3c646762733991264f4443b537598 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:18:59 +0000 Subject: [PATCH 15/19] Update the route record state only once our route record is acked --- .../ziggurat-driver/src/zigbee_stack/route.rs | 39 +++++++++++-------- crates/ziggurat-zigbee/src/nwk/next_hop.rs | 8 ++-- crates/ziggurat-zigbee/src/nwk/routing.rs | 6 +-- 3 files changed, 30 insertions(+), 23 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index ba897970..c30cb100 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -443,7 +443,7 @@ impl ZigbeeStack { pub(super) async fn transmit_route_record(&self, data: &NwkFrame, next_hop: Nwk) { let concentrator = data.nwk_header.destination; - let mut frame = { + let (record, mut frame) = { let mut core = self.core(); let nib = &mut core.nib; @@ -457,14 +457,11 @@ impl ZigbeeStack { }; let (source, source_eui64, relays) = match record { - RouteRecord::Ours => { - nib.routing.note_route_record_sent(concentrator, next_hop); - ( - self.state.network_address, - self.state.ieee_address, - Vec::new(), - ) - } + RouteRecord::Ours => ( + self.state.network_address, + self.state.ieee_address, + Vec::new(), + ), // The path from our child starts with us RouteRecord::Child { nwk, eui64 } => { (nwk, eui64, Vec::from([self.state.network_address])) @@ -473,19 +470,29 @@ impl ZigbeeStack { tracing::debug!("Sending a route record for {source:?} to {concentrator:?}"); - self.nwk_command_frame( - concentrator, - NwkCommand::RouteRecord(NwkRouteRecordCommand { relays }), - ) - .with_source(source) - .with_source_ieee(Some(source_eui64)) - .with_sequence_number(nib.next_sequence_number()) + let frame = self + .nwk_command_frame( + concentrator, + NwkCommand::RouteRecord(NwkRouteRecordCommand { relays }), + ) + .with_source(source) + .with_source_ieee(Some(source_eui64)) + .with_sequence_number(nib.next_sequence_number()); + + (record, frame) }; let result = self .transmit_unicast(&mut frame, next_hop, NwkSecurityMode::NetworkKey, false) .await; + if result.is_ok() && record == RouteRecord::Ours { + self.core() + .nib + .routing + .note_route_record_acked(concentrator, next_hop); + } + if result.is_err() { drop(self.enqueue_unicast( Frame::nwk(frame, NwkSecurityMode::NetworkKey), diff --git a/crates/ziggurat-zigbee/src/nwk/next_hop.rs b/crates/ziggurat-zigbee/src/nwk/next_hop.rs index 0b390135..e2dcdafe 100644 --- a/crates/ziggurat-zigbee/src/nwk/next_hop.rs +++ b/crates/ziggurat-zigbee/src/nwk/next_hop.rs @@ -445,8 +445,8 @@ mod tests { routing.note_source_routed_frame(CONCENTRATOR); assert_eq!(due(&routing), Some(RouteRecord::Ours)); - // Sending one is no proof either - routing.note_route_record_sent(CONCENTRATOR, RELAY); + // An acked one is no proof either + routing.note_route_record_acked(CONCENTRATOR, RELAY); assert_eq!(due(&routing), Some(RouteRecord::Ours)); routing.note_source_routed_frame(CONCENTRATOR); @@ -459,7 +459,7 @@ mod tests { let mut routing = routing_to_concentrator(); let neighbors = Neighbors::default(); - routing.note_route_record_sent(CONCENTRATOR, CONCENTRATOR); + routing.note_route_record_acked(CONCENTRATOR, CONCENTRATOR); assert_eq!( route_record_due(&routing, &neighbors, &data_frame(OWN), OWN), None @@ -473,7 +473,7 @@ mod tests { let mut routing = routing_to_concentrator(); let neighbors = neighbors_with_child(); - routing.note_route_record_sent(CONCENTRATOR, RELAY); + routing.note_route_record_acked(CONCENTRATOR, RELAY); routing.note_source_routed_frame(CONCENTRATOR); for _ in 0..2 { diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 876888d2..22342bc3 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -610,9 +610,9 @@ impl Routing { || entry.route_record_state != RouteRecordState::Known } - /// We transmitted our route record to `concentrator` via `next_hop`. A concentrator - /// that is our neighbor needs no source route to reach us. - pub fn note_route_record_sent(&mut self, concentrator: Nwk, next_hop: Nwk) { + /// `next_hop` acked our route record to `concentrator`. A concentrator that is our + /// neighbor got it directly, and needs no source route to reach us. + pub fn note_route_record_acked(&mut self, concentrator: Nwk, next_hop: Nwk) { if let Some(entry) = self.route_table.get_mut(&concentrator) { entry.route_record_state = if next_hop == concentrator { RouteRecordState::Known From f5111f99304387d6818774af8f63d468a32311a1 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:19:30 +0000 Subject: [PATCH 16/19] Report route records as required in Mgmt_Rtg_rsp for concentrators without a route cache --- crates/ziggurat-driver/src/zigbee_stack/zdp.rs | 3 +-- crates/ziggurat-zigbee/src/nwk/routing.rs | 10 +++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 23206351..332f3d24 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -174,8 +174,7 @@ impl ZigbeeStack { }, memory_constrained: false, many_to_one: entry.many_to_one, - route_record_required: entry.route_record_state - != routing::RouteRecordState::Known, + route_record_required: entry.route_record_required(), next_hop_address: entry.next_hop_address, }) .collect(); diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 22342bc3..d2e730ac 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -85,6 +85,12 @@ pub struct TableEntry { } impl TableEntry { + /// Whether our data frames to this concentrator need a route record first. One that + /// keeps no route cache needs one before every frame. + pub fn route_record_required(&self) -> bool { + self.no_route_cache || self.route_record_state != RouteRecordState::Known + } + const fn new( destination: Nwk, status: Status, @@ -605,9 +611,7 @@ impl Routing { return false; } - for_end_device_child - || entry.no_route_cache - || entry.route_record_state != RouteRecordState::Known + for_end_device_child || entry.route_record_required() } /// `next_hop` acked our route record to `concentrator`. A concentrator that is our From f313e3a4e2a57cd27635ad26b7bf1d17c3df1d93 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:19:57 +0000 Subject: [PATCH 17/19] Report the coordinator at depth 0 in Mgmt_Lqi_rsp when it was first heard in a link status --- crates/ziggurat-driver/src/zigbee_stack/zdp.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 332f3d24..a9886465 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -108,8 +108,12 @@ impl ZigbeeStack { permit_joining: ZdpPermitJoining::Unknown, // Spec Table 2-102: the neighbor's tree depth. We know only the // coordinator's, the root's, and our children's, one below ours. - // Other neighbors are reported as if they were our children - depth: if entry.device_type == NwkDeviceType::Coordinator { + // Other neighbors are reported as if they were our children. A + // coordinator first heard in a link status is stored as a router, + // but its address is always 0x0000 + depth: if entry.device_type == NwkDeviceType::Coordinator + || entry.network_address == Nwk(0x0000) + { 0 } else { (self.state.depth + 1).min(MAX_DEPTH) From 1f12fa0550414e4210e401b17be99a5dcd98719c Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:20:48 +0000 Subject: [PATCH 18/19] Size secured NWK frames without encrypting them --- crates/ziggurat-zigbee/src/nwk/frame.rs | 43 ++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/ziggurat-zigbee/src/nwk/frame.rs b/crates/ziggurat-zigbee/src/nwk/frame.rs index 268b5179..b744b324 100644 --- a/crates/ziggurat-zigbee/src/nwk/frame.rs +++ b/crates/ziggurat-zigbee/src/nwk/frame.rs @@ -614,11 +614,19 @@ impl NwkFrame { .expect("the NWK frame fits in an MSDU") } - /// Whether the frame, secured, fits an 802.15.4 frame with short addresses. The - /// key does not change the length. + /// Whether the frame, secured, fits an 802.15.4 frame with short addresses. + /// Encryption does not change the length, so the frame is only serialized, with + /// room for the MIC. pub fn fits_secured(&self) -> bool { - write_frame::(|writer| self.serialize(writer, Some(&Key([0; 16])))) - .is_ok_and(|bytes| MAC_FRAME_OVERHEAD + bytes.len() <= MAX_PHY_PACKET_SIZE) + write_frame::(|writer| { + self.nwk_header.serialize(writer)?; + self.aux_header + .as_ref() + .expect("a secured frame has an auxiliary header") + .serialize(writer)?; + self.payload.serialize(writer) + }) + .is_ok_and(|bytes| MAC_FRAME_OVERHEAD + bytes.len() + MIC_LENGTH <= MAX_PHY_PACKET_SIZE) } } @@ -706,6 +714,33 @@ mod test { assert_eq!(decrypted_nwk_frame.encrypt(&key), bytes); } + // The size check without encryption agrees with the encrypted frame at every + // payload length + #[test] + fn test_fits_secured_matches_the_encrypted_length() { + let bytes = + hex!("0802426b00000f2e287a0a0000a8ef171e004b120000f7a7e37b47adb47593c8a375c98ba6"); + let key = Key::from_hex("e8785a1ed5996b3ef715cb3fbdd69187"); + let mut frame = EncryptedNwkFrame::from_bytes(&bytes) + .unwrap() + .decrypt(&key) + .unwrap(); + + for length in 0..=MAX_NSDU_SIZE { + frame.payload = NwkPayload::Opaque(Nsdu::from_slice(&vec![0; length]).unwrap()); + + let encrypted_fits = + write_frame::(|writer| frame.serialize(writer, Some(&key))) + .is_ok_and(|bytes| MAC_FRAME_OVERHEAD + bytes.len() <= MAX_PHY_PACKET_SIZE); + + assert_eq!( + frame.fits_secured(), + encrypted_fits, + "payload length {length}" + ); + } + } + #[test] fn test_source_route() { let bytes = From f13aadb805ce1b3ace207bbf8064352d5236ddf6 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:22:31 +0000 Subject: [PATCH 19/19] Use a route record with no relays even when source routes are capped at 0 --- crates/ziggurat-zigbee/src/nwk/routing.rs | 4 +++- crates/ziggurat-zigbee/src/nwk/routing/tests.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index d2e730ac..8098ed3b 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -656,7 +656,9 @@ impl Routing { let record = self .route_record_table .get(&destination) - .filter(|relays| relays.len() < max_source_route as usize) + // A record with no relays needs no source route header, so the limit does not + // apply to it + .filter(|relays| relays.is_empty() || relays.len() < max_source_route as usize) .filter(|relays| first_hop_usable(*relays.last().unwrap_or(&destination))); match record { diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 82dcc0ac..1f6be903 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -309,6 +309,20 @@ fn test_unchanged_route_record_reports_a_relay_route_it_restores() { ); } +// With source routes turned off, a route record with no relays is still a direct route +#[test] +fn test_empty_route_record_is_used_with_source_routes_off() { + let mut routing = Routing::default(); + routing.store_route_record(DEVICE, vec![]); + routing.store_route_record(OTHER_DEVICE, vec![ROUTER]); + + assert_eq!( + routing.route_to(DEVICE, 0, |_| true), + Some(Route::NextHop(DEVICE)) + ); + assert_eq!(routing.route_to(OTHER_DEVICE, 0, |_| true), None); +} + // A route record wins over the routing table, so a reported failure must remove it // too, whether it is direct or a source route. #[test]