diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 832cc811..6bc88e19 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -265,7 +265,11 @@ 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, } /// The frame a send holds, as enqueued. @@ -364,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 { @@ -477,12 +485,13 @@ 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, 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 @@ -507,6 +516,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 { @@ -525,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, @@ -553,6 +569,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 { @@ -571,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, @@ -727,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 @@ -880,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(), @@ -1134,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/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/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/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index a1b5d0c6..321019d8 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; @@ -14,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); @@ -62,6 +60,18 @@ 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 policy = self.next_hop_policy(&core.nib); + + next_hop::reaches_directly(&core.nib.neighbors, destination, policy, now) + } + pub(super) fn sleepy_child_eui64(&self, nwk: Nwk) -> Option { self.core().nib.neighbors.sleepy_child_eui64(nwk) } @@ -173,25 +183,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 @@ -224,7 +247,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-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 078ee6cb..c9eb1783 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; @@ -183,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 { @@ -403,14 +412,16 @@ 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(), + next_hop_policy, now, ); @@ -426,39 +437,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 +456,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() } @@ -479,18 +507,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 { @@ -498,6 +516,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(); @@ -825,6 +859,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, @@ -877,13 +913,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 @@ -898,79 +936,78 @@ 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); + 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, + ); - next_hop - } else if self.is_neighbor(destination) { - // Children and direct neighbors are addressed directly, everything else - // goes through the routing table - destination - } else { - let next_hop = self.core().nib.routing.next_hop(destination); + let frame = Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey); + match resolved { + NextHop::Resolved(next_hop) => { + tracing::debug!("Relaying frame to {destination:?} via {next_hop:?}"); - match next_hop { - Some(next_hop) => next_hop, - None => { - tracing::debug!("No active route to relay frame to {destination:?}, dropping"); - 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); + self.enqueue_unicast_in( + &mut core, + frame, + TxPolicy { + priority: TxPriority::UserNormal, + class: TrafficClass::Forwarding, + }, + Confirm::OnHandoff, + next_hop, + poll_address, + ); } - }; - - tracing::debug!( - "Relaying frame from {:?} to {destination:?} via {next_hop_address:?}", - nwk_frame.nwk_header.source - ); + 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(&self.core().nib, next_hop_address); - self.enqueue_unicast( - Frame::nwk(nwk_frame, NwkSecurityMode::NetworkKey), - TxPolicy { - priority: TxPriority::UserNormal, - class: TrafficClass::Forwarding, - }, - Confirm::OnHandoff, - 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 - /// 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); @@ -1008,6 +1045,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-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index a5e653a7..c30cb100 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -2,20 +2,22 @@ use crate::runtime::Runtime; use core::cmp; use core::time::Duration; +use alloc::vec::Vec; use ziggurat_ieee_802154::types::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}; +use ziggurat_zigbee::nwk::next_hop::{self, RouteRecord}; 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, }; @@ -138,12 +140,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 @@ -210,7 +209,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), }), @@ -267,16 +266,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(); @@ -285,7 +284,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); } @@ -326,38 +328,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() + {} + + 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); - let _ = self.send_many_to_one_route_request().delivered().await; + let _ = self.send_many_to_one_route_request().delivered().await; - self.core().nib.routing.reset_mtorr_triggers(); + self.core().nib.routing.reset_mtorr_triggers(); - // Advertise every max interval, or sooner when one was requested - self.wait_for_debouncer(|nib| &nib.mtorr_debouncer, &self.mtorr_wake) - .await; + // 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 +390,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 +407,106 @@ 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 + } + + /// 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 (record, 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, + ) else { + return; + }; + + 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 + .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), + TxPolicy { + priority: TxPriority::UserNormal, + class: TrafficClass::Critical, + }, + Confirm::OnHandoff, + next_hop, + None, + )); + } + } + 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..cef11337 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -16,7 +16,7 @@ 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::sends::{ - Action, Broadcast as BroadcastRecord, Gpdf as GpdfRecord, TransmitError, + Action, Broadcast as BroadcastRecord, Gpdf as GpdfRecord, Routed, TransmitError, Unicast as UnicastRecord, }; @@ -197,12 +197,15 @@ 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, + 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(), + 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(), } } @@ -214,42 +217,51 @@ impl ZigbeeStack { .map(Ieee802154Address::Eui64) } - /// Resolve the route of an unrouted frame again: its next hop and the address it + /// 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: &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(); - policy.force_route_discovery &= nib.routing.own_discovery_underway( - self.state.network_address, - nwk_frame.nwk_header.destination, - now, - ); + let mut policy = self.next_hop_policy(nib); + 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) => Some(Routed { + next_hop, + poll_address: Self::poll_address(nib, next_hop), + }), + // 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, } } @@ -299,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 } @@ -365,7 +384,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-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 046d840f..a9886465 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -106,9 +106,18 @@ 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. 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) + }, lqa: entry.lqas.median().unwrap_or(0), }) .collect(); @@ -169,7 +178,7 @@ 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_required(), next_hop_address: entry.next_hop_address, }) .collect(); diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 05a23e45..5777a1b3 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -55,7 +55,8 @@ pub fn network_config(payload: &ConfigurePayload) -> NetworkConfig { }, }), tx_power: state.tx_power, - source_routing: payload.source_routing, + concentrator: 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, } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 3f8aa143..11fd32cb 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -296,6 +296,18 @@ 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, + + /// 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), @@ -315,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), @@ -332,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), diff --git a/crates/ziggurat-zigbee/src/nwk/frame.rs b/crates/ziggurat-zigbee/src/nwk/frame.rs index c8af256e..b744b324 100644 --- a/crates/ziggurat-zigbee/src/nwk/frame.rs +++ b/crates/ziggurat-zigbee/src/nwk/frame.rs @@ -613,6 +613,21 @@ 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. + /// 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.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) + } } /// A NWK frame ready to go into an 802.15.4 data frame, encrypted under `key` as it is @@ -699,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 = diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index cc09af65..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 { @@ -623,6 +631,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/next_hop.rs b/crates/ziggurat-zigbee/src/nwk/next_hop.rs index a98c2514..e2dcdafe 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, 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). 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,6 +59,16 @@ pub enum HostRoute { SourceRoute(Vec), } +/// 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. + 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 { @@ -67,36 +83,170 @@ 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. 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, + /// 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 + }) +} + +/// 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. /// -/// 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). pub fn resolve( - routing: &Routing, + routing: &mut Routing, neighbors: &Neighbors, frame: &mut NwkFrame, mode: &SendMode, policy: Policy, now: Instant, ) -> NextHop { + 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), + } +} + +/// 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, +) -> 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_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_required(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(destination); + } + + return NextHop::Resolved(next_hop); + } + + if reaches_directly(neighbors, destination, policy, now) { + return NextHop::Resolved(destination); + } + + if let Some(next_hop) = routing.next_hop(destination) { + 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 + // 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 { @@ -109,10 +259,27 @@ 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 { - match routing.route_to(destination, policy.max_source_route) { - Some(Route::NextHop(next_hop)) => return NextHop::Resolved(next_hop), + // 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 => {} } @@ -171,3 +338,172 @@ fn apply_source_route(frame: &mut NwkFrame, relays: Vec) -> NextHop { }); NextHop::Resolved(next_hop) } + +#[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), + }; + + /// 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()), + ) + } + + // 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)); + + // 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); + assert_eq!(due(&routing), None); + } + + // A concentrator that is our neighbor needs no source route to reach us + #[test] + fn test_neighbor_concentrator_needs_one_route_record() { + let mut routing = routing_to_concentrator(); + let neighbors = Neighbors::default(); + + routing.note_route_record_acked(CONCENTRATOR, CONCENTRATOR); + assert_eq!( + 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, even once the concentrator has our own route + #[test] + fn test_child_data_frames_always_need_a_route_record() { + let mut routing = routing_to_concentrator(); + let neighbors = neighbors_with_child(); + + routing.note_route_record_acked(CONCENTRATOR, RELAY); + routing.note_source_routed_frame(CONCENTRATOR); + + for _ in 0..2 { + assert_eq!( + route_record_due(&routing, &neighbors, &data_frame(CHILD), OWN), + Some(RouteRecord::Child { + nwk: CHILD, + eui64: CHILD_EUI64, + }) + ); + } + } + + // 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 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!(route_record_due(&routing, &neighbors, &command, OWN), None); + assert_eq!( + 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 f0ce768e..8098ed3b 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 @@ -74,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, @@ -85,7 +102,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, @@ -457,6 +474,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 { @@ -572,14 +597,43 @@ impl Routing { self.remove_route_record(destination) } - /// 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). + /// 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 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; + }; + + if entry.status != Status::Active || !entry.many_to_one { + return false; + } + + for_end_device_child || entry.route_record_required() + } + + /// `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 + } else { + RouteRecordState::Sent + }; + } + } + + /// 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; } } @@ -588,21 +642,30 @@ 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) + // 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 { // 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), } } @@ -758,7 +821,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/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 2fcc1c1a..1f6be903 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,11 +304,25 @@ 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])) ); } +// 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] @@ -315,7 +333,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 +354,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 +998,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)) + ); +} diff --git a/crates/ziggurat-zigbee/src/sends/mod.rs b/crates/ziggurat-zigbee/src/sends/mod.rs index 5dd10fc0..680f14d1 100644 --- a/crates/ziggurat-zigbee/src/sends/mod.rs +++ b/crates/ziggurat-zigbee/src/sends/mod.rs @@ -47,10 +47,11 @@ 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}; -pub use unicasts::Unicast; +pub use unicasts::{Routed, Unicast}; pub use unrouted::UnroutedUnicast; use broadcasts::Broadcasts; @@ -163,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. @@ -258,6 +260,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 +276,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 +470,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) { @@ -473,25 +497,24 @@ 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) - { + 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 { frame: unrouted.frame, priority: unrouted.priority, confirm: unrouted.confirm, - next_hop, - poll_address, + next_hop: routed.next_hop, + poll_address: routed.poll_address, }, now, Some(unrouted.deadline), @@ -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 @@ -558,13 +582,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); @@ -573,6 +596,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..15a9197e 100644 --- a/crates/ziggurat-zigbee/src/sends/tests.rs +++ b/crates/ziggurat-zigbee/src/sends/tests.rs @@ -148,11 +148,36 @@ 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 { 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, + }) }); self.settled() } @@ -244,6 +269,36 @@ fn test_held_unicast_waits_without_a_next_hop() { assert!(fixture.dequeue().is_none()); } +// Only a unicast's first transmit is marked as such; its retries are not +#[test] +fn test_retry_is_not_a_first_attempt() { + let mut fixture = Fixture::new(); + fixture.hold_unicast(); + assert!(fixture.pass(Some(NEXT_HOP)).is_empty()); + + let in_flight = fixture.dequeue().unwrap(); + assert!(matches!( + in_flight.transmit(), + 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 held unicast waits for a next hop, not for a discovery: any pass that finds one // releases it. #[test] @@ -355,6 +410,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] diff --git a/crates/ziggurat-zigbee/src/sends/unicasts.rs b/crates/ziggurat-zigbee/src/sends/unicasts.rs index 2794e730..74b5d347 100644 --- a/crates/ziggurat-zigbee/src/sends/unicasts.rs +++ b/crates/ziggurat-zigbee/src/sends/unicasts.rs @@ -29,6 +29,14 @@ 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, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Stage { /// Ready for the sender. @@ -56,6 +64,8 @@ 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. @@ -147,6 +157,7 @@ impl> Unicasts { next_hop: unicast.next_hop, poll_address: unicast.poll_address, attempts_remaining: tunables.unicast_retries(), + attempted: false, stage, deadline, copy_of, @@ -180,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, @@ -187,6 +200,7 @@ impl> Unicasts { transmit: Transmit::Unicast { next_hop: record.next_hop, frame_pending, + first_attempt, }, } }