From f6494fd22c4e5aaf51e67a1345d4b87968fcb228 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:56:29 +0000 Subject: [PATCH 01/11] Start activity counters set to `router_age_limit`, not to 0 --- .../src/zigbee_stack/joining.rs | 2 + .../src/zigbee_stack/neighbor.rs | 1 + .../ziggurat-driver/src/zigbee_stack/nwk.rs | 7 +- .../ziggurat-driver/src/zigbee_stack/route.rs | 10 +- .../ziggurat-driver/src/zigbee_stack/sends.rs | 1 + crates/ziggurat-protocol/src/bridge.rs | 10 +- crates/ziggurat-zigbee/src/nwk/neighbors.rs | 120 ++++++++++++---- crates/ziggurat-zigbee/src/nwk/routing.rs | 95 ++++++++++--- .../ziggurat-zigbee/src/nwk/routing/tests.rs | 132 +++++++++++++----- 9 files changed, 289 insertions(+), 89 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/joining.rs b/crates/ziggurat-driver/src/zigbee_stack/joining.rs index 5c80c16e..05f45ab5 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/joining.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/joining.rs @@ -117,6 +117,7 @@ impl ZigbeeStack { relationship: neighbors::Relationship::UnauthenticatedChild, }, self.core_now(), + self.tunables.router_age_limit(), ); // A new child deadline may precede everything the maintenance task knows @@ -1180,6 +1181,7 @@ impl ZigbeeStack { }, }, self.core_now(), + self.tunables.router_age_limit(), ); // A new child deadline may precede everything the maintenance task knows diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 02bf4a7d..696ffcca 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -84,6 +84,7 @@ impl ZigbeeStack { lqi, &link_status_cmd, self.core_now(), + self.tunables.router_age_limit(), ); // The neighbor no longer answers at its old address, so routes through it diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index b5569389..741bc1ea 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -53,7 +53,11 @@ impl ZigbeeStack { } pub(super) fn forget_nwk_state_in(&self, mut core: CoreGuard<'_>, nwk: Nwk) { - core.nib.routing.forget(self.state.network_address, nwk); + core.nib.routing.forget( + self.state.network_address, + nwk, + self.tunables.router_age_limit(), + ); core.sends.fail_unrouted(nwk); self.commit_sends(core); } @@ -442,6 +446,7 @@ impl ZigbeeStack { now, self.tunables.route_discovery_time(), self.tunables.pending_route_discovery_attempts(), + self.tunables.router_age_limit(), ); if let Some(route_request_identifier) = route_request_identifier { self.broadcast_discovery_request( diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 3dbcc177..74927828 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -44,6 +44,7 @@ impl ZigbeeStack { nwk_frame.nwk_header.source, updated_path_cost, now, + self.tunables.router_age_limit(), ); let (next_hop_nwk, path_cost) = match outcome.disposition { @@ -158,6 +159,7 @@ impl ZigbeeStack { route_request_cmd.many_to_one, self.core_now(), self.tunables.route_discovery_time(), + self.tunables.router_age_limit(), ); if !outcome.accepted { @@ -233,10 +235,10 @@ impl ZigbeeStack { // many-to-one requests are addressed to a broadcast address, so there is no // destination to track for them. if !many_to_one { - self.core() - .nib - .routing - .note_relayed_discovery(route_request_cmd.destination_address); + self.core().nib.routing.note_relayed_discovery( + route_request_cmd.destination_address, + self.tunables.router_age_limit(), + ); } let rebroadcast_radius = nwk_frame.nwk_header.radius.saturating_sub(1); diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index b07cab0a..2a489840 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -372,6 +372,7 @@ impl ZigbeeStack { self.state.network_address, now, self.tunables.route_discovery_time(), + self.tunables.router_age_limit(), |destination| core.sends.has_unrouted(destination), ); diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 00651768..91a3b9cb 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -202,6 +202,7 @@ pub fn apply_children( relationship: Relationship::Child, }, now, + stack.tunables.router_age_limit(), ); core.nib.address_map.update_mapping(entry.ieee, entry.nwk); } @@ -223,9 +224,12 @@ pub fn apply_route_table( ) { let mut core = stack.state.core.lock(); for entry in payload.entries { - core.nib - .routing - .restore_route(entry.destination, entry.next_hop, entry.path_cost); + core.nib.routing.restore_route( + entry.destination, + entry.next_hop, + entry.path_cost, + stack.tunables.router_age_limit(), + ); } } diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index e7e8ab40..1dee991d 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -522,17 +522,23 @@ impl Neighbors { /// across attachment retries. The fields a device may change between attachments /// are refreshed even on existing entries: a device may re-attach with different /// capabilities (e.g. re-flashed from router to end device). - pub fn upsert_child(&mut self, child: ChildDescriptor, now: Instant) { - self.upsert(child, now, Some(now)); + pub fn upsert_child(&mut self, child: ChildDescriptor, now: Instant, router_age_limit: u8) { + self.upsert(child, now, Some(now), router_age_limit); } /// Seed a child entry restored by the client on startup. Unlike a device that /// associates or rejoins, a restored child did not just attach to us. - pub fn restore_child(&mut self, child: ChildDescriptor, now: Instant) { - self.upsert(child, now, None); + pub fn restore_child(&mut self, child: ChildDescriptor, now: Instant, router_age_limit: u8) { + self.upsert(child, now, None, router_age_limit); } - fn upsert(&mut self, child: ChildDescriptor, now: Instant, attached_at: Option) { + fn upsert( + &mut self, + child: ChildDescriptor, + now: Instant, + attached_at: Option, + router_age_limit: u8, + ) { let entry = self.table.entry(child.eui64).or_insert_with(|| TableEntry { extended_address: child.eui64, network_address: child.network_address, @@ -555,8 +561,8 @@ impl Neighbors { attached_at, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: 0, - router_inbound_activity: 0, + router_outbound_activity: router_age_limit, + router_inbound_activity: router_age_limit, security_timer: 0, }); @@ -713,6 +719,7 @@ impl Neighbors { /// Digest a received link status command, updating the sender's entry (creating a /// sibling entry for previously unseen routers). + #[allow(clippy::too_many_arguments)] pub fn on_link_status( &mut self, own_address: Nwk, @@ -721,6 +728,7 @@ impl Neighbors { lqi: u8, link_status_cmd: &NwkLinkStatusCommand, now: Instant, + router_age_limit: u8, ) -> LinkStatusOutcome { // Collect the set of already-connected neighbors before mutating the state, for // the neighbor set diversity computation @@ -794,8 +802,8 @@ impl Neighbors { attached_at: None, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: 0, - router_inbound_activity: 0, + router_outbound_activity: router_age_limit, + router_inbound_activity: router_age_limit, security_timer: 0, }; @@ -883,6 +891,7 @@ mod test { use hex_literal::hex; const CHILD_NWK: Nwk = Nwk(0x1234); + const ROUTER_AGE_LIMIT: u8 = 3; fn neighbors_with(device_type: NwkDeviceType) -> Neighbors { let mut neighbors = Neighbors::default(); @@ -896,6 +905,7 @@ mod test { relationship: Relationship::Child, }, Instant::from_micros(0), + ROUTER_AGE_LIMIT, ); neighbors } @@ -964,7 +974,8 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - let outcome = neighbors.on_link_status(own, router, old, 200, &link_status, now); + let outcome = + neighbors.on_link_status(own, router, old, 200, &link_status, now, ROUTER_AGE_LIMIT); assert_eq!(outcome, LinkStatusOutcome::default()); neighbors.record_lqa(old, 200); neighbors.record_lqa(old, 200); @@ -975,7 +986,8 @@ mod test { // link status carries the new address with the router's EUI64 neighbors.record_lqa(new, 40); neighbors.record_lqa(new, 40); - let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now); + let outcome = + neighbors.on_link_status(own, router, new, 40, &link_status, now, ROUTER_AGE_LIMIT); assert_eq!( outcome, LinkStatusOutcome { @@ -1001,7 +1013,8 @@ mod test { assert_eq!(advertised, vec![new]); // A later link status from the same address changes nothing - let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now); + let outcome = + neighbors.on_link_status(own, router, new, 40, &link_status, now, ROUTER_AGE_LIMIT); assert_eq!(outcome, LinkStatusOutcome::default()); } @@ -1019,6 +1032,7 @@ mod test { 200, &listing, Instant::from_micros(0), + ROUTER_AGE_LIMIT, ); let empty = NwkLinkStatusCommand { @@ -1027,7 +1041,15 @@ mod test { link_statuses: vec![], }; let later = Instant::from_micros(1); - let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, later); + let outcome = neighbors.on_link_status( + own, + router, + router_nwk, + 200, + &empty, + later, + ROUTER_AGE_LIMIT, + ); assert_eq!(outcome, LinkStatusOutcome::default()); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 1); @@ -1041,10 +1063,26 @@ mod test { let mut neighbors = Neighbors::default(); let listing = link_status_listing(own); - neighbors.on_link_status(own, router, router_nwk, 200, &listing, now); + neighbors.on_link_status( + own, + router, + router_nwk, + 200, + &listing, + now, + ROUTER_AGE_LIMIT, + ); let without_us = link_status_listing(Nwk(0x2222)); - let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &without_us, now); + let outcome = neighbors.on_link_status( + own, + router, + router_nwk, + 200, + &without_us, + now, + ROUTER_AGE_LIMIT, + ); assert_eq!( outcome, @@ -1083,8 +1121,16 @@ mod test { let mut neighbors = Neighbors::default(); let listing = link_status_listing(own); - neighbors.on_link_status(own, router, router_nwk, 200, &listing, now); - neighbors.on_link_status(own, router, router_nwk, 200, frame, now); + neighbors.on_link_status( + own, + router, + router_nwk, + 200, + &listing, + now, + ROUTER_AGE_LIMIT, + ); + neighbors.on_link_status(own, router, router_nwk, 200, frame, now, ROUTER_AGE_LIMIT); neighbors.link(router_nwk).unwrap().outgoing_cost } @@ -1138,7 +1184,15 @@ mod test { |neighbors: &Neighbors| neighbors.link(router_nwk).unwrap().incoming_cost; // One sample is the link quality, and the router is listed at once - neighbors.on_link_status(own, router, router_nwk, 200, &link_status, now); + neighbors.on_link_status( + own, + router, + router_nwk, + 200, + &link_status, + now, + ROUTER_AGE_LIMIT, + ); assert_eq!(incoming_cost(&neighbors), lqi_to_link_cost(200)); assert_eq!(neighbors.link_status_entries().len(), 1); @@ -1169,14 +1223,29 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 200, &link_status, now); - neighbors.on_link_status(own, other, contested, 200, &link_status, now); + neighbors.on_link_status(own, router, old, 200, &link_status, now, ROUTER_AGE_LIMIT); + neighbors.on_link_status( + own, + other, + contested, + 200, + &link_status, + now, + ROUTER_AGE_LIMIT, + ); // The router's link status from an address the other neighbor holds, or from // our own address, is an address conflict: the router keeps its entry's address for conflicting in [contested, own] { - let outcome = - neighbors.on_link_status(own, router, conflicting, 200, &link_status, now); + let outcome = neighbors.on_link_status( + own, + router, + conflicting, + 200, + &link_status, + now, + ROUTER_AGE_LIMIT, + ); assert_eq!(outcome, LinkStatusOutcome::default()); assert_eq!(neighbors.link(old).unwrap().eui64, router); assert_eq!(neighbors.link(contested).unwrap().eui64, other); @@ -1193,13 +1262,13 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 10, &link_status, now); + neighbors.on_link_status(own, router, old, 10, &link_status, now, ROUTER_AGE_LIMIT); // More samples than the window buffered under the new address: the ring wraps for lqi in [10, 20, 200, 220] { neighbors.record_lqa(new, lqi); } - neighbors.on_link_status(own, router, new, 220, &link_status, now); + neighbors.on_link_status(own, router, new, 220, &link_status, now, ROUTER_AGE_LIMIT); // The window is [20, 200, 220] and its oldest (20) is replaced next, giving // [200, 220, 30]: a scrambled order would replace 220 and drop the median to 30 @@ -1223,6 +1292,7 @@ mod test { relationship: Relationship::Child, }, Instant::from_micros(0), + ROUTER_AGE_LIMIT, ); assert_eq!( @@ -1261,6 +1331,7 @@ mod test { relationship: Relationship::UnauthenticatedChild, }, Instant::from_micros(0), + ROUTER_AGE_LIMIT, ); // Still a child for parent duties while unauthenticated @@ -1288,6 +1359,7 @@ mod test { relationship: Relationship::UnauthenticatedChild, }, Instant::from_micros(0), + ROUTER_AGE_LIMIT, ); assert_eq!( relationship_of(&neighbors, eui64), diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 49c92b8c..4b5f9b2b 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -73,7 +73,12 @@ pub struct TableEntry { } impl TableEntry { - const fn new(destination: Nwk, status: Status, next_hop_address: Nwk) -> Self { + const fn new( + destination: Nwk, + status: Status, + next_hop_address: Nwk, + router_age_limit: u8, + ) -> Self { Self { destination, status, @@ -84,7 +89,7 @@ impl TableEntry { next_hop_address, path_cost: u8::MAX, total_usage_count: 0, - recent_activity: 0, + recent_activity: router_age_limit, } } @@ -335,6 +340,7 @@ impl Routing { now: Instant, route_discovery_time: Duration, attempts: u8, + router_age_limit: u8, ) -> Option { if self.discoveries_left.contains_key(&destination) { return None; @@ -347,7 +353,13 @@ impl Routing { return None; } - Some(self.begin_discovery(own_address, destination, now, route_discovery_time)) + Some(self.begin_discovery( + own_address, + destination, + now, + route_discovery_time, + router_age_limit, + )) } /// Decide what becomes of each destination our frames wait for a route to. @@ -358,6 +370,7 @@ impl Routing { own_address: Nwk, now: Instant, route_discovery_time: Duration, + router_age_limit: u8, wanted: impl Fn(Nwk) -> bool, ) -> DiscoveryTick { let mut tick = DiscoveryTick::default(); @@ -381,8 +394,13 @@ impl Routing { // route was lost before the frame could use it if *discoveries_left > 0 { *discoveries_left -= 1; - let request_id = - self.begin_discovery(own_address, destination, now, route_discovery_time); + let request_id = self.begin_discovery( + own_address, + destination, + now, + route_discovery_time, + router_age_limit, + ); tick.restarted.push((destination, request_id)); true } else { @@ -448,7 +466,7 @@ impl Routing { } /// The device at `nwk` left or joined again, clear associated state. - pub fn forget(&mut self, own_address: Nwk, nwk: Nwk) { + pub fn forget(&mut self, own_address: Nwk, nwk: Nwk, router_age_limit: u8) { self.route_table.remove(&nwk); self.route_record_table.remove(&nwk); self.discoveries_left.remove(&nwk); @@ -471,15 +489,26 @@ impl Routing { { self.route_table.insert( nwk, - TableEntry::new(nwk, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP), + TableEntry::new( + nwk, + Status::DiscoveryUnderway, + UNKNOWN_NEXT_HOP, + router_age_limit, + ), ); } } /// Seed an active routing entry restored by the client on startup. Unlike a route /// learned at runtime, this does not record a change (the client already has it). - pub fn restore_route(&mut self, destination: Nwk, next_hop: Nwk, path_cost: u8) { - let mut entry = TableEntry::new(destination, Status::Active, next_hop); + pub fn restore_route( + &mut self, + destination: Nwk, + next_hop: Nwk, + path_cost: u8, + router_age_limit: u8, + ) { + let mut entry = TableEntry::new(destination, Status::Active, next_hop, router_age_limit); entry.path_cost = path_cost; self.route_table.insert(destination, entry); } @@ -571,16 +600,21 @@ impl Routing { destination: Nwk, now: Instant, route_discovery_time: Duration, + router_age_limit: u8, ) -> RouteRequestId { // Expire stale discoveries before establishing the new one. A just-expired // discovery toward this same destination would otherwise tear down the // `DiscoveryUnderway` route entry created below. self.expire_discoveries(now); - let route_table_entry = self - .route_table - .entry(destination) - .or_insert_with(|| TableEntry::new(destination, Status::Inactive, UNKNOWN_NEXT_HOP)); + let route_table_entry = self.route_table.entry(destination).or_insert_with(|| { + TableEntry::new( + destination, + Status::Inactive, + UNKNOWN_NEXT_HOP, + router_age_limit, + ) + }); route_table_entry.status = Status::DiscoveryUnderway; self.request_sequence_number = self.request_sequence_number.wrapping_add(1); @@ -656,6 +690,7 @@ impl Routing { many_to_one: NwkRouteRequestManyToOne, now: Instant, route_discovery_time: Duration, + router_age_limit: u8, ) -> RouteRequestOutcome { self.expire_discoveries(now); @@ -701,10 +736,14 @@ impl Routing { // Spec 3.6.4.5.1.2: the route back to the originator runs through the device we // accepted the request from, subject to the 3.6.4.5.3 suitability rule. - let originator_entry = self - .route_table - .entry(originator) - .or_insert_with(|| TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP)); + let originator_entry = self.route_table.entry(originator).or_insert_with(|| { + TableEntry::new( + originator, + Status::Inactive, + UNKNOWN_NEXT_HOP, + router_age_limit, + ) + }); let route_changed = originator_entry.consider_route(sender, updated_path_cost); @@ -740,7 +779,7 @@ impl Routing { /// Before relaying a route request: mark the destination's entry as /// `DiscoveryUnderway`, so the reply we relay back finds it (spec 3.6.4.5.1.2). - pub fn note_relayed_discovery(&mut self, destination: Nwk) { + pub fn note_relayed_discovery(&mut self, destination: Nwk, router_age_limit: u8) { self.route_table .entry(destination) .and_modify(|entry| { @@ -749,7 +788,12 @@ impl Routing { } }) .or_insert_with(|| { - TableEntry::new(destination, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP) + TableEntry::new( + destination, + Status::DiscoveryUnderway, + UNKNOWN_NEXT_HOP, + router_age_limit, + ) }); } @@ -766,6 +810,7 @@ impl Routing { sender: Nwk, updated_path_cost: u8, now: Instant, + router_age_limit: u8, ) -> RouteReplyOutcome { // A reply to a discovery that has lapsed finds no entry and is dropped self.expire_discoveries(now); @@ -857,10 +902,14 @@ impl Routing { // Spec 3.6.4.5.2.1: relaying the reply also establishes the reverse route // toward the originator of the route request, subject to the 3.6.4.5.3 // suitability rule so a worse path never replaces a good ACTIVE route. - let reverse_entry = self - .route_table - .entry(originator) - .or_insert_with(|| TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP)); + let reverse_entry = self.route_table.entry(originator).or_insert_with(|| { + TableEntry::new( + originator, + Status::Inactive, + UNKNOWN_NEXT_HOP, + router_age_limit, + ) + }); let update = reverse_entry .consider_route(next_hop, forward_cost) diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 28909239..f984511c 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -18,6 +18,7 @@ const NEIGHBOR: Nwk = Nwk(0x4444); const START: Instant = Instant::from_micros(0); const ROUTE_DISCOVERY_TIME: Duration = Duration::from_secs(10); const MAX_SOURCE_ROUTE: u8 = 11; +const ROUTER_AGE_LIMIT: u8 = 3; /// A route request relayed to us by `NEIGHBOR`. #[derive(Clone, Copy)] @@ -39,6 +40,7 @@ fn receive(routing: &mut Routing, request: RouteRequest, now: Instant) -> bool { NwkRouteRequestManyToOne::NotManyToOne, now, ROUTE_DISCOVERY_TIME, + ROUTER_AGE_LIMIT, ) .accepted } @@ -48,7 +50,7 @@ fn receive(routing: &mut Routing, request: RouteRequest, now: Instant) -> bool { #[test] fn test_forget_drops_our_discovery_toward_the_device() { let mut routing = Routing::default(); - routing.begin_discovery(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME); + routing.begin_discovery(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, ROUTER_AGE_LIMIT); assert_eq!( routing.own_discovery_lapse(OWN, DEVICE, START), Some(START + ROUTE_DISCOVERY_TIME) @@ -58,7 +60,7 @@ fn test_forget_drops_our_discovery_toward_the_device() { Some(Status::DiscoveryUnderway) ); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); assert_eq!(routing.own_discovery_lapse(OWN, DEVICE, START), None); assert_eq!(routing.route_status(DEVICE), None); @@ -67,11 +69,11 @@ fn test_forget_drops_our_discovery_toward_the_device() { #[test] fn test_forget_drops_the_route_and_the_route_record() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); routing.store_route_record(DEVICE, vec![ROUTER]); assert!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE).is_some()); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); assert_eq!(routing.next_hop(DEVICE), None); assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE), None); @@ -80,10 +82,10 @@ fn test_forget_drops_the_route_and_the_route_record() { #[test] fn test_forget_leaves_other_destinations_alone() { let mut routing = Routing::default(); - routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3); - routing.begin_discovery(OWN, ROUTER, START, ROUTE_DISCOVERY_TIME); + routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + routing.begin_discovery(OWN, ROUTER, START, ROUTE_DISCOVERY_TIME, ROUTER_AGE_LIMIT); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); assert_eq!(routing.next_hop(OTHER_DEVICE), Some(NEIGHBOR)); assert_eq!( @@ -105,7 +107,7 @@ fn test_forget_keeps_the_duplicate_check_for_a_request_the_device_originated() { }; assert!(receive(&mut routing, request, START)); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); let late_copy = RouteRequest { path_cost: 7, @@ -124,7 +126,7 @@ fn test_forget_keeps_the_duplicate_check_for_a_request_toward_the_device() { }; assert!(receive(&mut routing, request, START)); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); let late_copy = RouteRequest { path_cost: 7, @@ -145,15 +147,16 @@ fn test_forget_keeps_a_relayed_discovery_toward_the_device_answerable() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); assert_eq!( routing.route_status(DEVICE), Some(Status::DiscoveryUnderway) ); - let reply = routing.accept_route_reply(OWN, ROUTER, 1, DEVICE, DEVICE, 1, START); + let reply = + routing.accept_route_reply(OWN, ROUTER, 1, DEVICE, DEVICE, 1, START, ROUTER_AGE_LIMIT); assert_eq!( reply.disposition, RouteReplyDisposition::Relay { @@ -174,10 +177,10 @@ fn test_forget_placeholder_for_a_relayed_discovery_expires_with_it() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.restore_route(DEVICE, OTHER_DEVICE, 3); - routing.note_relayed_discovery(DEVICE); + routing.restore_route(DEVICE, OTHER_DEVICE, 3, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); assert_eq!(routing.next_hop(DEVICE), None); assert_eq!( routing.route_status(DEVICE), @@ -208,13 +211,13 @@ fn test_relayed_discovery_still_expires_after_its_originator_is_forgotten() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(OTHER_DEVICE); + routing.note_relayed_discovery(OTHER_DEVICE, ROUTER_AGE_LIMIT); assert_eq!( routing.route_status(OTHER_DEVICE), Some(Status::DiscoveryUnderway) ); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); // Any later request runs the expiry let unrelated = RouteRequest { @@ -278,7 +281,7 @@ fn test_unchanged_route_record_reports_a_relay_route_it_restores() { fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { for relays in [vec![], vec![ROUTER]] { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); routing.store_route_record(DEVICE, relays); assert!(routing.forget_route_to(DEVICE)); @@ -289,7 +292,7 @@ fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { #[test] fn test_forget_route_to_reports_only_a_removed_route_record() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); assert!(!routing.forget_route_to(DEVICE)); assert_eq!(routing.next_hop(DEVICE), None); @@ -311,13 +314,20 @@ fn test_forget_route_to_leaves_other_destinations_alone() { /// A frame of ours wants a route to `DEVICE`. Returns whether that starts a discovery. fn want(routing: &mut Routing, now: Instant, attempts: u8) -> bool { routing - .want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts) + .want_route( + OWN, + DEVICE, + now, + ROUTE_DISCOVERY_TIME, + attempts, + ROUTER_AGE_LIMIT, + ) .is_some() } /// Run a timer pass, with a frame still waiting for the route or not. fn tick(routing: &mut Routing, now: Instant, wanted: bool) -> DiscoveryTick { - routing.tick_discoveries(OWN, now, ROUTE_DISCOVERY_TIME, |_| wanted) + routing.tick_discoveries(OWN, now, ROUTE_DISCOVERY_TIME, ROUTER_AGE_LIMIT, |_| wanted) } #[test] @@ -423,7 +433,7 @@ fn test_relayed_discovery_toward_the_destination_is_not_ours() { path_cost: 3, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); assert!(want(&mut routing, START, 1)); } @@ -454,11 +464,18 @@ fn test_relayed_discovery_does_not_keep_ours_alive() { #[test] fn test_removing_the_route_keeps_a_discovery_underway() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); assert!(routing.remove_route(DEVICE)); let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1) + .want_route( + OWN, + DEVICE, + START, + ROUTE_DISCOVERY_TIME, + 1, + ROUTER_AGE_LIMIT, + ) .unwrap(); assert!(!routing.remove_route(DEVICE)); assert!(!routing.forget_route_to(DEVICE)); @@ -470,13 +487,29 @@ fn test_removing_the_route_keeps_a_discovery_underway() { /// `DEVICE` answers our route request through `NEIGHBOR`. fn reply(routing: &mut Routing, request_id: RouteRequestId, now: Instant) -> RouteReplyOutcome { - routing.accept_route_reply(OWN, OWN, request_id, DEVICE, NEIGHBOR, 3, now) + routing.accept_route_reply( + OWN, + OWN, + request_id, + DEVICE, + NEIGHBOR, + 3, + now, + ROUTER_AGE_LIMIT, + ) } /// Start a discovery toward `DEVICE` and have the device answer it. fn answered_discovery(routing: &mut Routing, attempts: u8) { let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, attempts) + .want_route( + OWN, + DEVICE, + START, + ROUTE_DISCOVERY_TIME, + attempts, + ROUTER_AGE_LIMIT, + ) .unwrap(); let reply = reply(routing, request_id, START); @@ -513,7 +546,7 @@ fn test_relayed_discovery_does_not_revive_our_answered_one() { path_cost: 3, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); assert_eq!( routing.route_status(DEVICE), Some(Status::DiscoveryUnderway) @@ -527,15 +560,31 @@ fn test_relayed_discovery_does_not_revive_our_answered_one() { fn test_reply_with_the_highest_path_cost_answers_the_discovery() { let mut routing = Routing::default(); let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1) + .want_route( + OWN, + DEVICE, + START, + ROUTE_DISCOVERY_TIME, + 1, + ROUTER_AGE_LIMIT, + ) .unwrap(); - let reply = routing.accept_route_reply(OWN, OWN, request_id, DEVICE, NEIGHBOR, u8::MAX, START); + let reply = routing.accept_route_reply( + OWN, + OWN, + request_id, + DEVICE, + NEIGHBOR, + u8::MAX, + START, + ROUTER_AGE_LIMIT, + ); assert_eq!(reply.disposition, RouteReplyDisposition::Established); assert_eq!(tick(&mut routing, START, false), DiscoveryTick::default()); routing.invalidate_via(NEIGHBOR); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); assert!(want(&mut routing, START, 1)); } @@ -563,7 +612,7 @@ fn test_forget_ends_our_discovery_toward_the_device() { let mut routing = Routing::default(); assert!(want(&mut routing, START, 1)); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); assert_eq!(routing.next_discovery_lapse(OWN, START), None); assert!(want(&mut routing, START, 1)); @@ -575,7 +624,14 @@ fn test_forget_ends_our_discovery_toward_the_device() { fn test_reply_to_a_lapsed_discovery_is_dropped() { let mut routing = Routing::default(); let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1) + .want_route( + OWN, + DEVICE, + START, + ROUTE_DISCOVERY_TIME, + 1, + ROUTER_AGE_LIMIT, + ) .unwrap(); let late = reply(&mut routing, request_id, START + ROUTE_DISCOVERY_TIME); @@ -670,7 +726,14 @@ fn check_own_discovery(steps: &[Step], attempts: u8) { // The driver only holds a frame when it has no route Step::Hold if routing.next_hop(DEVICE).is_some() => {} Step::Hold => { - let started = routing.want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts); + let started = routing.want_route( + OWN, + DEVICE, + now, + ROUTE_DISCOVERY_TIME, + attempts, + ROUTER_AGE_LIMIT, + ); // Only the first frame to wait can start a discovery, and a discovery // of ours that is still underway serves it @@ -780,7 +843,7 @@ fn check_own_discovery(steps: &[Step], attempts: u8) { path_cost: 3, }; assert!(receive(&mut routing, request, now), "{steps:?}"); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); model.expire(); model.relayed_live = true; @@ -851,6 +914,7 @@ fn receive_copy(routing: &mut Routing, path_cost: u8) -> RouteRequestOutcome { NwkRouteRequestManyToOne::NotManyToOne, START, ROUTE_DISCOVERY_TIME, + ROUTER_AGE_LIMIT, ) } From 8e6731daeb7455a98116cd41a7e38e184758b902 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:59:55 +0000 Subject: [PATCH 02/11] Make router decay a function of time --- .../src/zigbee_stack/neighbor.rs | 11 +- crates/ziggurat-zigbee/src/nwk.rs | 1 + crates/ziggurat-zigbee/src/nwk/activity.rs | 101 ++++++++++++++++++ crates/ziggurat-zigbee/src/nwk/neighbors.rs | 31 +++--- crates/ziggurat-zigbee/src/nwk/routing.rs | 20 ++-- crates/ziggurat-zigbee/src/time.rs | 2 +- 6 files changed, 140 insertions(+), 26 deletions(-) create mode 100644 crates/ziggurat-zigbee/src/nwk/activity.rs diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 696ffcca..859599e1 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -115,15 +115,16 @@ impl ZigbeeStack { return Err(EnqueueError::NotStarted); } - // Decrement the `recent_activity` field of every active routing table entry - self.core().nib.routing.decay_activity(); - self.maybe_age_neighbors(); - // Decrement the inbound and outbound activity fields for neighbors let mut link_statuses = { let mut core = self.core(); - core.nib.neighbors.decay_activity(); + let now = self.core_now(); + let period = self.tunables.link_status_period(); + + // Both decay by the time passed, so an extra link status is harmless + core.nib.routing.decay_activity(now, period); + core.nib.neighbors.decay_activity(now, period); if empty { Vec::new() diff --git a/crates/ziggurat-zigbee/src/nwk.rs b/crates/ziggurat-zigbee/src/nwk.rs index ebd20ec8..818c5d89 100644 --- a/crates/ziggurat-zigbee/src/nwk.rs +++ b/crates/ziggurat-zigbee/src/nwk.rs @@ -1,3 +1,4 @@ +pub mod activity; pub mod address_conflicts; pub mod addresses; pub mod broadcast_budget; diff --git a/crates/ziggurat-zigbee/src/nwk/activity.rs b/crates/ziggurat-zigbee/src/nwk/activity.rs new file mode 100644 index 00000000..3c110621 --- /dev/null +++ b/crates/ziggurat-zigbee/src/nwk/activity.rs @@ -0,0 +1,101 @@ +use core::time::Duration; + +use crate::Instant; + +const STEPS_PER_COUNT: u16 = 256; + +/// A spec activity counter (`RecentActivity`, `RouterOutboundActivity`, +/// `RouterInboundActivity`). +/// +/// It is held in steps of 1/256 of a count, so it decays by the time that has passed +/// and not once per period. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Activity { + steps: u16, +} + +impl Activity { + const MAX_STEPS: u16 = u8::MAX as u16 * STEPS_PER_COUNT; + + pub const fn new(count: u8) -> Self { + Self { + steps: count as u16 * STEPS_PER_COUNT, + } + } + + /// The whole counts held. + pub const fn count(&self) -> u8 { + (self.steps / STEPS_PER_COUNT) as u8 + } + + pub fn record_use(&mut self) { + self.steps = self + .steps + .saturating_add(STEPS_PER_COUNT) + .min(Self::MAX_STEPS); + } + + pub const fn decay(&mut self, steps: u16) { + self.steps = self.steps.saturating_sub(steps); + } +} + +/// The decay steps owed for the time from `*decayed_at` to `now`, at one count per +/// `period`. `*decayed_at` moves forward by the steps returned, so the rest of the time +/// counts toward the next call. +pub fn take_decay_steps(decayed_at: &mut Instant, now: Instant, period: Duration) -> u16 { + let step = period / u32::from(STEPS_PER_COUNT); + let elapsed = now.saturating_duration_since(*decayed_at).as_micros() / step.as_micros(); + let steps = u16::try_from(elapsed).unwrap_or(u16::MAX); + + *decayed_at = *decayed_at + step * u32::from(steps); + steps +} + +#[cfg(test)] +mod test { + use super::*; + + const PERIOD: Duration = Duration::from_secs(16); + + fn at(millis: u64) -> Instant { + Instant::from_micros(0) + Duration::from_millis(millis) + } + + #[test] + fn test_activity_decays_by_the_time_passed() { + let mut activity = Activity::new(3); + let mut decayed_at = at(0); + + // Half a period is half a count: the whole count drops from 3 to 2 + activity.decay(take_decay_steps(&mut decayed_at, at(8_000), PERIOD)); + assert_eq!(activity.count(), 2); + + // The same instant again owes nothing + assert_eq!(take_decay_steps(&mut decayed_at, at(8_000), PERIOD), 0); + + // The other half completes one whole count of decay + activity.decay(take_decay_steps(&mut decayed_at, at(16_000), PERIOD)); + assert_eq!(activity, Activity::new(2)); + } + + #[test] + fn test_time_shorter_than_a_step_carries_over() { + let mut decayed_at = at(0); + + // One step is 16 s / 256 = 62.5 ms + assert_eq!(take_decay_steps(&mut decayed_at, at(60), PERIOD), 0); + assert_eq!(take_decay_steps(&mut decayed_at, at(125), PERIOD), 2); + } + + #[test] + fn test_activity_stays_between_0_and_255() { + let mut activity = Activity::new(254); + activity.record_use(); + activity.record_use(); + assert_eq!(activity, Activity::new(255)); + + activity.decay(u16::MAX); + assert_eq!(activity, Activity::new(0)); + } +} diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index 1dee991d..b07eb1e5 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -3,6 +3,7 @@ use alloc::vec::Vec; use core::cmp; use crate::Instant; +use crate::nwk::activity::{Activity, take_decay_steps}; use crate::nwk::commands::{NwkLinkStatus, NwkLinkStatusCommand}; use crate::nwk::frame::NwkHeader; use crate::ring_buffer::RingBuffer; @@ -126,8 +127,8 @@ pub struct TableEntry { pub router_connectivity: u8, pub router_neighbor_set_diversity: u8, - pub router_outbound_activity: u8, - pub router_inbound_activity: u8, + pub router_outbound_activity: Activity, + pub router_inbound_activity: Activity, pub security_timer: u8, } @@ -197,6 +198,8 @@ pub struct Neighbors { /// LQI samples for senders that have no neighbor entry yet, capped at /// [`PENDING_LQA_CAP`] entries. pending_lqas: FlatMap, + /// Up to when the activity counters have been decayed + activity_decayed_at: Instant, } impl Neighbors { @@ -561,8 +564,8 @@ impl Neighbors { attached_at, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: router_age_limit, - router_inbound_activity: router_age_limit, + router_outbound_activity: Activity::new(router_age_limit), + router_inbound_activity: Activity::new(router_age_limit), security_timer: 0, }); @@ -658,19 +661,21 @@ impl Neighbors { stale_neighbors } - /// Called once per `nwkLinkStatusPeriod`: decrement the inbound and outbound - /// activity counters for every neighbor. - pub fn decay_activity(&mut self) { + /// Decay the inbound and outbound activity of every neighbor by the time passed + /// since the last call, at one count per `period` (`nwkLinkStatusPeriod`). + pub fn decay_activity(&mut self, now: Instant, period: Duration) { + let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + for entry in self.table.values_mut() { - entry.router_outbound_activity = entry.router_outbound_activity.saturating_sub(1); - entry.router_inbound_activity = entry.router_inbound_activity.saturating_sub(1); + entry.router_outbound_activity.decay(steps); + entry.router_inbound_activity.decay(steps); } } /// A unicast was forwarded through this neighbor. pub fn record_outbound_activity(&mut self, eui64: Eui64) { if let Some(entry) = self.table.get_mut(&eui64) { - entry.router_outbound_activity = entry.router_outbound_activity.saturating_add(1); + entry.router_outbound_activity.record_use(); } } @@ -681,7 +686,7 @@ impl Neighbors { .values_mut() .find(|entry| entry.network_address == nwk) { - entry.router_inbound_activity = entry.router_inbound_activity.saturating_add(1); + entry.router_inbound_activity.record_use(); } } @@ -802,8 +807,8 @@ impl Neighbors { attached_at: None, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: router_age_limit, - router_inbound_activity: router_age_limit, + router_outbound_activity: Activity::new(router_age_limit), + router_inbound_activity: Activity::new(router_age_limit), security_timer: 0, }; diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 4b5f9b2b..80abd645 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -2,6 +2,7 @@ use crate::flat_map::FlatMap; use alloc::vec::Vec; use crate::Instant; +use crate::nwk::activity::{Activity, take_decay_steps}; use crate::nwk::commands::NwkRouteRequestManyToOne; use core::time::Duration; use ziggurat_ieee_802154::types::Nwk; @@ -69,7 +70,7 @@ pub struct TableEntry { /// used to forward a state packet towards its destination; and decremented /// unconditionally once every `nwkLinkStatusPeriod`. A value of 0 indicates no /// packets have recently been forwarded along this route. - pub recent_activity: u8, + pub recent_activity: Activity, } impl TableEntry { @@ -89,7 +90,7 @@ impl TableEntry { next_hop_address, path_cost: u8::MAX, total_usage_count: 0, - recent_activity: router_age_limit, + recent_activity: Activity::new(router_age_limit), } } @@ -253,6 +254,9 @@ pub struct Routing { /// originating in a particular router; the latter is used to identify stale routing /// information." request_sequence_number: RouteRequestId, + + /// Up to when `recent_activity` has been decayed + activity_decayed_at: Instant, } impl Routing { @@ -425,17 +429,19 @@ impl Routing { /// A frame was forwarded along the route: bump its usage counters. pub fn record_usage(&mut self, destination: Nwk) { if let Some(entry) = self.route_table.get_mut(&destination) { - entry.recent_activity = entry.recent_activity.saturating_add(1); + entry.recent_activity.record_use(); entry.total_usage_count = entry.total_usage_count.saturating_add(1); } } - /// Called once per `nwkLinkStatusPeriod`: decrement the `recent_activity` field of - /// every active routing table entry. - pub fn decay_activity(&mut self) { + /// Decay the `recent_activity` of every active routing table entry by the time + /// passed since the last call, at one count per `period` (`nwkLinkStatusPeriod`). + pub fn decay_activity(&mut self, now: Instant, period: Duration) { + let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + for entry in self.route_table.values_mut() { if entry.status == Status::Active { - entry.recent_activity = entry.recent_activity.saturating_sub(1); + entry.recent_activity.decay(steps); } } } diff --git a/crates/ziggurat-zigbee/src/time.rs b/crates/ziggurat-zigbee/src/time.rs index 1049fa6a..28595510 100644 --- a/crates/ziggurat-zigbee/src/time.rs +++ b/crates/ziggurat-zigbee/src/time.rs @@ -6,7 +6,7 @@ use core::time::Duration; /// The sans-io core never reads a clock; the driver passes `now` in and converts its own /// platform clock (tokio, embassy, a sim) to and from this type at the boundary. Replacing /// `std::time::Instant` is what lets this crate build for `no_std` targets. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Instant { micros: u64, } From d4cb78bcb215bb134d9de000c75c30e20eb4b59c Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:00:48 +0000 Subject: [PATCH 03/11] Decay inactive routes as well --- crates/ziggurat-zigbee/src/nwk/routing.rs | 9 ++++----- crates/ziggurat-zigbee/src/nwk/routing/tests.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 80abd645..c9b60b3b 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -434,15 +434,14 @@ impl Routing { } } - /// Decay the `recent_activity` of every active routing table entry by the time - /// passed since the last call, at one count per `period` (`nwkLinkStatusPeriod`). + /// Decay the `recent_activity` of every routing table entry by the time passed + /// since the last call, at one count per `period` (`nwkLinkStatusPeriod`). pub fn decay_activity(&mut self, now: Instant, period: Duration) { let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + // Spec Table 3-77: "decremented unconditionally", whatever the route's status for entry in self.route_table.values_mut() { - if entry.status == Status::Active { - entry.recent_activity.decay(steps); - } + entry.recent_activity.decay(steps); } } diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index f984511c..37b2c469 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -66,6 +66,20 @@ fn test_forget_drops_our_discovery_toward_the_device() { assert_eq!(routing.route_status(DEVICE), None); } +#[test] +fn test_recent_activity_decays_on_an_inactive_route() { + let period = Duration::from_secs(15); + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + routing.invalidate_via(NEIGHBOR); + assert_eq!(routing.route_status(DEVICE), Some(Status::Inactive)); + + routing.decay_activity(START + period, period); + + let entry = routing.entries().next().unwrap(); + assert_eq!(entry.recent_activity, Activity::new(ROUTER_AGE_LIMIT - 1)); +} + #[test] fn test_forget_drops_the_route_and_the_route_record() { let mut routing = Routing::default(); From 90fd0daf95e30edf4f88bac3a682dd674db55d5e Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:10:24 +0000 Subject: [PATCH 04/11] Gratuitous link status broadcasts --- crates/ziggurat-driver/src/zigbee_stack.rs | 7 +++ .../src/zigbee_stack/neighbor.rs | 44 +++++++++++++++++-- crates/ziggurat-zigbee/src/constants.rs | 8 ++++ crates/ziggurat-zigbee/src/nwk/neighbors.rs | 39 +++++++++++++--- 4 files changed, 89 insertions(+), 9 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 7f665290..3d0c06c4 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -723,6 +723,11 @@ pub struct ZigbeeStack { /// Signaled whenever a link status command is digested; the MTORR startup wait /// uses it to advertise as soon as a neighbor link is established pub(crate) link_status_received: Notify, + /// When the next link status broadcast is due: one period after the last, or + /// sooner when a gratuitous one was asked for + pub(crate) next_link_status_at: Mutex, + /// Wakes the link status task when `next_link_status_at` moved earlier + pub(crate) link_status_wake: Notify, pub(crate) address_conflict_wake: Notify, /// Wakes the beacon-spam reactor when a beacon request opens its spray window. pub(crate) beacon_spam_wake: Notify, @@ -843,6 +848,8 @@ impl ZigbeeStack { parent_annce_received: Mutex::new(None), mtorr_kick: Notify::new(), link_status_received: Notify::new(), + next_link_status_at: Mutex::new(CoreInstant::from_micros(0)), + link_status_wake: Notify::new(), address_conflict_wake: Notify::new(), beacon_spam_wake: Notify::new(), maintenance_wake: Notify::new(), diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 859599e1..e2c2727b 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -3,6 +3,7 @@ use alloc::vec::Vec; use ziggurat_ieee_802154::types::{Eui64, Nwk}; use ziggurat_phy::RadioPhy; +use ziggurat_zigbee::Instant as CoreInstant; use ziggurat_zigbee::nwk::commands::{NwkCommand, NwkLinkStatusCommand}; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; @@ -102,6 +103,18 @@ impl ZigbeeStack { self.invalidate_routes_via(neighbor_nwk); } + if outcome.gratuitous_link_status_due { + // Spec 3.6.4.4.2: the answer goes out after a random delay + let min_jitter = self.tunables.min_router_bootstrap_jitter(); + let max_jitter = self.tunables.max_router_bootstrap_jitter(); + let jitter = min_jitter + + max_jitter + .saturating_sub(min_jitter) + .mul_f32(crate::rng::random_f32::()); + + self.send_link_status_by(self.core_now() + jitter); + } + self.link_status_received.notify_one(); } @@ -186,19 +199,42 @@ impl ZigbeeStack { } } + /// Move the next link status broadcast earlier, to `at`. It stays where it is if + /// it is already due sooner. + fn send_link_status_by(&self, at: CoreInstant) { + let mut next = self.next_link_status_at.lock(); + + if at < *next { + *next = at; + drop(next); + + self.link_status_wake.notify_one(); + } + } + pub async fn periodic_link_status_broadcast_task(&self) { - let mut next = self.core_now() + self.tunables.link_status_period(); + *self.next_link_status_at.lock() = self.core_now() + self.tunables.link_status_period(); loop { - self.sleep_until_core(next).await; + let next = *self.next_link_status_at.lock(); + let due = core::pin::pin!(self.sleep_until_core(next)); + let moved = core::pin::pin!(self.link_status_wake.notified()); + + // The broadcast moved earlier: sleep again, until its new time + if let futures::future::Either::Right(((), _)) = + futures::future::select(due, moved).await + { + continue; + } + + // Spec 3.6.4.4.1: the next one follows within a period + *self.next_link_status_at.lock() = self.core_now() + self.tunables.link_status_period(); // The link status broadcast has a radius of 1 so delivery does not wait for // a relay quorum. if let Ok(link_status) = self.send_link_status_broadcast(false) { let _ = link_status.delivered().await; } - - next = next + self.tunables.link_status_period(); } } } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 4035fb2b..9b141bf3 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -315,6 +315,14 @@ tunables! { /// The time between link status command frames. link_status_period: Duration = Duration::from_secs(15), + /// `nwkcMinRouterBootstrapJitter`: the shortest delay before a gratuitous link + /// status. + min_router_bootstrap_jitter: Duration = Duration::from_millis(500), + + /// `nwkcMaxRouterBootstrapJitter`: the longest delay before a gratuitous link + /// status. + max_router_bootstrap_jitter: Duration = Duration::from_secs(1), + /// The number of missed link status command frames before resetting the link costs /// to zero. router_age_limit: u8 = 3, diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index b07eb1e5..16be3b43 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -189,6 +189,9 @@ pub struct LinkStatusOutcome { pub lost_link: Option, /// The sender's previous network address, if the link status came from a new one. pub replaced_address: Option, + /// A router we did not know sent an empty list: it just started, and we owe it a + /// link status of our own (spec 3.6.4.4.2). + pub gratuitous_link_status_due: bool, } /// The neighbor table: link quality accounting, link status digestion, and aging. @@ -782,6 +785,9 @@ impl Neighbors { } } + let gratuitous_link_status_due = + link_status_cmd.link_statuses.is_empty() && !self.table.contains_key(&source_ieee); + let neighbor_entry = self.table.entry(source_ieee).or_insert_with(|| { tracing::info!("Creating new neighbor entry for {source_ieee:?}"); @@ -873,11 +879,6 @@ impl Neighbors { } } - if link_status_cmd.link_statuses.is_empty() { - // TODO: Initiate a gratuitous link status broadcast, jittered by - // nwkcMinRouterBootstrapJitter < nwkcMaxRouterBootstrapJitter - } - tracing::trace!("Updated neighbor table entry: {neighbor_entry:?}"); let lost_link = previous_outgoing_cost > 0 && neighbor_entry.outgoing_cost == 0; @@ -885,6 +886,7 @@ impl Neighbors { LinkStatusOutcome { lost_link: lost_link.then_some(neighbor_entry.network_address), replaced_address, + gratuitous_link_status_due, } } } @@ -998,6 +1000,7 @@ mod test { LinkStatusOutcome { lost_link: None, replaced_address: Some(old), + gratuitous_link_status_due: false, } ); @@ -1060,6 +1063,31 @@ mod test { assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 1); } + #[test] + fn test_empty_link_status_from_unknown_router_is_owed_an_answer() { + let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); + let (own, router_nwk) = (Nwk(0x0000), Nwk(0x1111)); + let now = Instant::from_micros(0); + let empty = link_status_frame(true, true, &[]); + let mut neighbors = Neighbors::default(); + + let outcome = + neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ROUTER_AGE_LIMIT); + assert_eq!( + outcome, + LinkStatusOutcome { + lost_link: None, + replaced_address: None, + gratuitous_link_status_due: true, + } + ); + + // The router is known now + let outcome = + neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ROUTER_AGE_LIMIT); + assert_eq!(outcome, LinkStatusOutcome::default()); + } + #[test] fn test_link_status_leaving_us_out_zeroes_outgoing_cost() { let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); @@ -1094,6 +1122,7 @@ mod test { LinkStatusOutcome { lost_link: Some(router_nwk), replaced_address: None, + gratuitous_link_status_due: false, } ); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 0); From 224b0fd66bd2f12a7e00101d522eb60ab1667daf Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:11:12 +0000 Subject: [PATCH 05/11] Move link status schedule into its own sans-io crate for testing --- crates/ziggurat-driver/src/zigbee_stack.rs | 10 +-- .../src/zigbee_stack/neighbor.rs | 34 ++++---- crates/ziggurat-zigbee/src/nwk.rs | 1 + .../src/nwk/link_status_schedule.rs | 78 +++++++++++++++++++ crates/ziggurat-zigbee/src/nwk/neighbors.rs | 6 ++ 5 files changed, 108 insertions(+), 21 deletions(-) create mode 100644 crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 3d0c06c4..c6285c52 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -53,6 +53,7 @@ pub use ziggurat_zigbee::nwk::broadcast_budget::{ BroadcastAdmission, BroadcastBudget, TrafficClass, }; pub use ziggurat_zigbee::nwk::broadcasts::Broadcasts; +pub use ziggurat_zigbee::nwk::link_status_schedule::LinkStatusSchedule; pub use ziggurat_zigbee::nwk::neighbors::Neighbors; pub use ziggurat_zigbee::nwk::next_hop::{HostRoute, RouteDirective, SendMode}; pub use ziggurat_zigbee::nwk::routing::Routing; @@ -350,6 +351,8 @@ pub struct Nib { /// The neighbor table: link quality accounting, link status digestion, aging pub neighbors: Neighbors, + /// When the next link status broadcast is due + pub link_status_schedule: LinkStatusSchedule, /// NWK routing state and decision logic (route/discovery/record tables) pub routing: Routing, /// Broadcast deduplication and passive acknowledgment accounting @@ -508,6 +511,7 @@ impl State { update_id: config.update_id, tx_total: 0, neighbors: Neighbors::default(), + link_status_schedule: LinkStatusSchedule::default(), routing: Routing::default(), broadcasts: Broadcasts::default(), nwk_security: NwkSecurity::new( @@ -723,10 +727,7 @@ pub struct ZigbeeStack { /// Signaled whenever a link status command is digested; the MTORR startup wait /// uses it to advertise as soon as a neighbor link is established pub(crate) link_status_received: Notify, - /// When the next link status broadcast is due: one period after the last, or - /// sooner when a gratuitous one was asked for - pub(crate) next_link_status_at: Mutex, - /// Wakes the link status task when `next_link_status_at` moved earlier + /// Wakes the link status task when the next link status broadcast moved earlier pub(crate) link_status_wake: Notify, pub(crate) address_conflict_wake: Notify, /// Wakes the beacon-spam reactor when a beacon request opens its spray window. @@ -848,7 +849,6 @@ impl ZigbeeStack { parent_annce_received: Mutex::new(None), mtorr_kick: Notify::new(), link_status_received: Notify::new(), - next_link_status_at: Mutex::new(CoreInstant::from_micros(0)), link_status_wake: Notify::new(), address_conflict_wake: Notify::new(), beacon_spam_wake: Notify::new(), diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index e2c2727b..5b951d46 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -3,7 +3,6 @@ use alloc::vec::Vec; use ziggurat_ieee_802154::types::{Eui64, Nwk}; use ziggurat_phy::RadioPhy; -use ziggurat_zigbee::Instant as CoreInstant; use ziggurat_zigbee::nwk::commands::{NwkCommand, NwkLinkStatusCommand}; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; @@ -112,7 +111,16 @@ impl ZigbeeStack { .saturating_sub(min_jitter) .mul_f32(crate::rng::random_f32::()); - self.send_link_status_by(self.core_now() + jitter); + let answer_at = self.core_now() + jitter; + + if self + .core() + .nib + .link_status_schedule + .bring_forward(answer_at) + { + self.link_status_wake.notify_one(); + } } self.link_status_received.notify_one(); @@ -199,24 +207,19 @@ impl ZigbeeStack { } } - /// Move the next link status broadcast earlier, to `at`. It stays where it is if - /// it is already due sooner. - fn send_link_status_by(&self, at: CoreInstant) { - let mut next = self.next_link_status_at.lock(); + fn restart_link_status_period(&self) { + let now = self.core_now(); + let period = self.tunables.link_status_period(); - if at < *next { - *next = at; - drop(next); - - self.link_status_wake.notify_one(); - } + self.core().nib.link_status_schedule.restart(now, period); } pub async fn periodic_link_status_broadcast_task(&self) { - *self.next_link_status_at.lock() = self.core_now() + self.tunables.link_status_period(); + // The network start has just sent one + self.restart_link_status_period(); loop { - let next = *self.next_link_status_at.lock(); + let next = self.core().nib.link_status_schedule.next(); let due = core::pin::pin!(self.sleep_until_core(next)); let moved = core::pin::pin!(self.link_status_wake.notified()); @@ -227,8 +230,7 @@ impl ZigbeeStack { continue; } - // Spec 3.6.4.4.1: the next one follows within a period - *self.next_link_status_at.lock() = self.core_now() + self.tunables.link_status_period(); + self.restart_link_status_period(); // The link status broadcast has a radius of 1 so delivery does not wait for // a relay quorum. diff --git a/crates/ziggurat-zigbee/src/nwk.rs b/crates/ziggurat-zigbee/src/nwk.rs index 818c5d89..68ff0c27 100644 --- a/crates/ziggurat-zigbee/src/nwk.rs +++ b/crates/ziggurat-zigbee/src/nwk.rs @@ -5,6 +5,7 @@ pub mod broadcast_budget; pub mod broadcasts; pub mod commands; pub mod frame; +pub mod link_status_schedule; pub mod neighbors; pub mod next_hop; pub mod routing; diff --git a/crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs b/crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs new file mode 100644 index 00000000..ceca2af6 --- /dev/null +++ b/crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs @@ -0,0 +1,78 @@ +use core::time::Duration; + +use crate::Instant; + +/// When the next link status broadcast is due (spec 3.6.4.4.1): one period after the +/// last, or sooner when an early one was asked for. +#[derive(Debug, Default)] +pub struct LinkStatusSchedule { + next: Instant, +} + +impl LinkStatusSchedule { + pub const fn next(&self) -> Instant { + self.next + } + + /// Ask for a link status broadcast by `at`. Returns whether the next one moved + /// earlier: it stays where it is if it is already due sooner. + pub fn bring_forward(&mut self, at: Instant) -> bool { + let earlier = at < self.next; + + if earlier { + self.next = at; + } + + earlier + } + + /// A link status broadcast goes out at `now`: the next one is due a `period` later. + pub fn restart(&mut self, now: Instant, period: Duration) { + self.next = now + period; + } +} + +#[cfg(test)] +mod test { + use super::*; + + const PERIOD: Duration = Duration::from_secs(15); + + fn at(millis: u64) -> Instant { + Instant::from_micros(0) + Duration::from_millis(millis) + } + + fn started() -> LinkStatusSchedule { + let mut schedule = LinkStatusSchedule::default(); + schedule.restart(at(0), PERIOD); + schedule + } + + #[test] + fn test_requests_close_together_share_the_earliest_time() { + let mut schedule = started(); + + assert!(schedule.bring_forward(at(700))); + assert!(!schedule.bring_forward(at(900))); + assert!(schedule.bring_forward(at(600))); + + assert_eq!(schedule.next(), at(600)); + } + + #[test] + fn test_request_after_the_period_end_changes_nothing() { + let mut schedule = started(); + + assert!(!schedule.bring_forward(at(15_500))); + assert_eq!(schedule.next(), at(15_000)); + } + + #[test] + fn test_broadcast_restarts_the_period() { + let mut schedule = started(); + schedule.bring_forward(at(700)); + + schedule.restart(at(700), PERIOD); + assert_eq!(schedule.next(), at(15_700)); + } +} diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index 16be3b43..fccfee9d 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -1086,6 +1086,12 @@ mod test { let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ROUTER_AGE_LIMIT); assert_eq!(outcome, LinkStatusOutcome::default()); + + // Another unknown router is owed one too + let other = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:22"); + let outcome = + neighbors.on_link_status(own, other, Nwk(0x2222), 200, &empty, now, ROUTER_AGE_LIMIT); + assert!(outcome.gratuitous_link_status_due); } #[test] From 979cd542ec753eae9e015e87b108fe4aa5434daf Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:27:08 +0000 Subject: [PATCH 06/11] Send early link statuses for new routers and answer empty ones, via a generic `Debouncer` --- crates/ziggurat-driver/src/zigbee_stack.rs | 6 +- .../src/zigbee_stack/neighbor.rs | 61 +++++--- crates/ziggurat-zigbee/src/debouncer.rs | 79 +++++++++++ crates/ziggurat-zigbee/src/lib.rs | 1 + crates/ziggurat-zigbee/src/nwk.rs | 1 - .../src/nwk/link_status_schedule.rs | 78 ----------- crates/ziggurat-zigbee/src/nwk/neighbors.rs | 130 ++++++++++++++---- 7 files changed, 222 insertions(+), 134 deletions(-) create mode 100644 crates/ziggurat-zigbee/src/debouncer.rs delete mode 100644 crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index c6285c52..869bd62d 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -22,6 +22,7 @@ use core::future::Future; use core::ops::{Deref, DerefMut}; use core::sync::atomic::{AtomicBool, AtomicU32, Ordering as AtomicOrdering}; use core::time::Duration; +use ziggurat_zigbee::debouncer::Debouncer; use ziggurat_zigbee::flat_map::FlatMap; use ziggurat_zigbee::nwk::frame::{NwkFrame, NwkSecurityHeaderKeyId}; @@ -53,7 +54,6 @@ pub use ziggurat_zigbee::nwk::broadcast_budget::{ BroadcastAdmission, BroadcastBudget, TrafficClass, }; pub use ziggurat_zigbee::nwk::broadcasts::Broadcasts; -pub use ziggurat_zigbee::nwk::link_status_schedule::LinkStatusSchedule; pub use ziggurat_zigbee::nwk::neighbors::Neighbors; pub use ziggurat_zigbee::nwk::next_hop::{HostRoute, RouteDirective, SendMode}; pub use ziggurat_zigbee::nwk::routing::Routing; @@ -352,7 +352,7 @@ pub struct Nib { /// The neighbor table: link quality accounting, link status digestion, aging pub neighbors: Neighbors, /// When the next link status broadcast is due - pub link_status_schedule: LinkStatusSchedule, + pub link_status_debouncer: Debouncer, /// NWK routing state and decision logic (route/discovery/record tables) pub routing: Routing, /// Broadcast deduplication and passive acknowledgment accounting @@ -511,7 +511,7 @@ impl State { update_id: config.update_id, tx_total: 0, neighbors: Neighbors::default(), - link_status_schedule: LinkStatusSchedule::default(), + link_status_debouncer: Debouncer::default(), routing: Routing::default(), broadcasts: Broadcasts::default(), nwk_security: NwkSecurity::new( diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 5b951d46..f8012ff5 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -3,6 +3,7 @@ use alloc::vec::Vec; use ziggurat_ieee_802154::types::{Eui64, Nwk}; 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}; @@ -17,7 +18,38 @@ const MAX_LINK_STATUSES: usize = 7; impl ZigbeeStack { pub(super) fn maybe_recompute_lqa(&self, sender_nwk: Nwk, lqi: u8, _rssi: i8) { - self.core().nib.neighbors.record_lqa(sender_nwk, lqi); + let link_status_due = self.core().nib.neighbors.record_lqa(sender_nwk, lqi); + + if link_status_due { + self.request_link_status_for_new_router(); + } + } + + /// Send the next link status soon: a router it will newly list waits for it to + /// learn its cost. + fn request_link_status_for_new_router(&self) { + // Coordinator only. Routers must not run this as it is: every router that + // hears a new neighbor would send within the same half second, each with its + // whole list, and most of those frames would collide. + if self.state.role == NwkDeviceType::Coordinator { + self.request_early_link_status(); + } + } + + /// Send the next link status after the delay of a gratuitous one (spec 3.6.4.4.2). + fn request_early_link_status(&self) { + let min_jitter = self.tunables.min_router_bootstrap_jitter(); + let max_jitter = self.tunables.max_router_bootstrap_jitter(); + let jitter = min_jitter + + max_jitter + .saturating_sub(min_jitter) + .mul_f32(crate::rng::random_f32::()); + + let at = self.core_now() + jitter; + + if self.core().nib.link_status_debouncer.request(at) { + self.link_status_wake.notify_one(); + } } pub(super) fn end_device_child_eui64(&self, nwk: Nwk) -> Option { @@ -102,25 +134,10 @@ impl ZigbeeStack { self.invalidate_routes_via(neighbor_nwk); } - if outcome.gratuitous_link_status_due { - // Spec 3.6.4.4.2: the answer goes out after a random delay - let min_jitter = self.tunables.min_router_bootstrap_jitter(); - let max_jitter = self.tunables.max_router_bootstrap_jitter(); - let jitter = min_jitter - + max_jitter - .saturating_sub(min_jitter) - .mul_f32(crate::rng::random_f32::()); - - let answer_at = self.core_now() + jitter; - - if self - .core() - .nib - .link_status_schedule - .bring_forward(answer_at) - { - self.link_status_wake.notify_one(); - } + if outcome.link_status_answer_due { + self.request_early_link_status(); + } else if outcome.link_status_due { + self.request_link_status_for_new_router(); } self.link_status_received.notify_one(); @@ -211,7 +228,7 @@ impl ZigbeeStack { let now = self.core_now(); let period = self.tunables.link_status_period(); - self.core().nib.link_status_schedule.restart(now, period); + self.core().nib.link_status_debouncer.fired(now, period); } pub async fn periodic_link_status_broadcast_task(&self) { @@ -219,7 +236,7 @@ impl ZigbeeStack { self.restart_link_status_period(); loop { - let next = self.core().nib.link_status_schedule.next(); + let next = self.core().nib.link_status_debouncer.next(); let due = core::pin::pin!(self.sleep_until_core(next)); let moved = core::pin::pin!(self.link_status_wake.notified()); diff --git a/crates/ziggurat-zigbee/src/debouncer.rs b/crates/ziggurat-zigbee/src/debouncer.rs new file mode 100644 index 00000000..2fb47cfc --- /dev/null +++ b/crates/ziggurat-zigbee/src/debouncer.rs @@ -0,0 +1,79 @@ +//! A timer that fires at a fixed interval, or sooner when asked. + +use core::time::Duration; + +use crate::Instant; + +/// A periodic deadline that a request can move earlier. A burst of requests fires once. +#[derive(Debug, Default)] +pub struct Debouncer { + next: Instant, +} + +impl Debouncer { + pub const fn next(&self) -> Instant { + self.next + } + + /// Ask for a firing by `at`. Returns whether the next firing moved earlier: it + /// stays where it is if it is already due sooner. + pub fn request(&mut self, at: Instant) -> bool { + let earlier = at < self.next; + + if earlier { + self.next = at; + } + + earlier + } + + /// It fires at `now`: the next firing is due an `interval` later. + pub fn fired(&mut self, now: Instant, interval: Duration) { + self.next = now + interval; + } +} + +#[cfg(test)] +mod test { + use super::*; + + const INTERVAL: Duration = Duration::from_secs(15); + + fn at(millis: u64) -> Instant { + Instant::from_micros(0) + Duration::from_millis(millis) + } + + fn started() -> Debouncer { + let mut debouncer = Debouncer::default(); + debouncer.fired(at(0), INTERVAL); + debouncer + } + + #[test] + fn test_requests_close_together_share_the_earliest_time() { + let mut debouncer = started(); + + assert!(debouncer.request(at(700))); + assert!(!debouncer.request(at(900))); + assert!(debouncer.request(at(600))); + + assert_eq!(debouncer.next(), at(600)); + } + + #[test] + fn test_request_after_the_interval_end_changes_nothing() { + let mut debouncer = started(); + + assert!(!debouncer.request(at(15_500))); + assert_eq!(debouncer.next(), at(15_000)); + } + + #[test] + fn test_firing_restarts_the_interval() { + let mut debouncer = started(); + debouncer.request(at(700)); + + debouncer.fired(at(700), INTERVAL); + assert_eq!(debouncer.next(), at(15_700)); + } +} diff --git a/crates/ziggurat-zigbee/src/lib.rs b/crates/ziggurat-zigbee/src/lib.rs index a060f8e8..8444f3aa 100644 --- a/crates/ziggurat-zigbee/src/lib.rs +++ b/crates/ziggurat-zigbee/src/lib.rs @@ -6,6 +6,7 @@ pub mod aps; pub mod beacon; pub mod constants; pub mod crypto; +pub mod debouncer; pub mod flat_map; pub mod gp; pub mod nwk; diff --git a/crates/ziggurat-zigbee/src/nwk.rs b/crates/ziggurat-zigbee/src/nwk.rs index 68ff0c27..818c5d89 100644 --- a/crates/ziggurat-zigbee/src/nwk.rs +++ b/crates/ziggurat-zigbee/src/nwk.rs @@ -5,7 +5,6 @@ pub mod broadcast_budget; pub mod broadcasts; pub mod commands; pub mod frame; -pub mod link_status_schedule; pub mod neighbors; pub mod next_hop; pub mod routing; diff --git a/crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs b/crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs deleted file mode 100644 index ceca2af6..00000000 --- a/crates/ziggurat-zigbee/src/nwk/link_status_schedule.rs +++ /dev/null @@ -1,78 +0,0 @@ -use core::time::Duration; - -use crate::Instant; - -/// When the next link status broadcast is due (spec 3.6.4.4.1): one period after the -/// last, or sooner when an early one was asked for. -#[derive(Debug, Default)] -pub struct LinkStatusSchedule { - next: Instant, -} - -impl LinkStatusSchedule { - pub const fn next(&self) -> Instant { - self.next - } - - /// Ask for a link status broadcast by `at`. Returns whether the next one moved - /// earlier: it stays where it is if it is already due sooner. - pub fn bring_forward(&mut self, at: Instant) -> bool { - let earlier = at < self.next; - - if earlier { - self.next = at; - } - - earlier - } - - /// A link status broadcast goes out at `now`: the next one is due a `period` later. - pub fn restart(&mut self, now: Instant, period: Duration) { - self.next = now + period; - } -} - -#[cfg(test)] -mod test { - use super::*; - - const PERIOD: Duration = Duration::from_secs(15); - - fn at(millis: u64) -> Instant { - Instant::from_micros(0) + Duration::from_millis(millis) - } - - fn started() -> LinkStatusSchedule { - let mut schedule = LinkStatusSchedule::default(); - schedule.restart(at(0), PERIOD); - schedule - } - - #[test] - fn test_requests_close_together_share_the_earliest_time() { - let mut schedule = started(); - - assert!(schedule.bring_forward(at(700))); - assert!(!schedule.bring_forward(at(900))); - assert!(schedule.bring_forward(at(600))); - - assert_eq!(schedule.next(), at(600)); - } - - #[test] - fn test_request_after_the_period_end_changes_nothing() { - let mut schedule = started(); - - assert!(!schedule.bring_forward(at(15_500))); - assert_eq!(schedule.next(), at(15_000)); - } - - #[test] - fn test_broadcast_restarts_the_period() { - let mut schedule = started(); - schedule.bring_forward(at(700)); - - schedule.restart(at(700), PERIOD); - assert_eq!(schedule.next(), at(15_700)); - } -} diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index fccfee9d..9efc80a4 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -133,6 +133,12 @@ pub struct TableEntry { } impl TableEntry { + /// Whether our link status lists this neighbor: a router we have heard from. A + /// neighbor without a sample has no cost to report. + pub fn is_in_link_status(&self) -> bool { + self.device_type == NwkDeviceType::Router && !self.lqas.is_empty() + } + pub fn incoming_link_cost(&self) -> u8 { self.lqas.median().map_or(0, lqi_to_link_cost) } @@ -189,9 +195,13 @@ pub struct LinkStatusOutcome { pub lost_link: Option, /// The sender's previous network address, if the link status came from a new one. pub replaced_address: Option, - /// A router we did not know sent an empty list: it just started, and we owe it a - /// link status of our own (spec 3.6.4.4.2). - pub gratuitous_link_status_due: bool, + /// Our link status lists the sender from now on and did not before, so the sender + /// has yet to learn its cost from us. + pub link_status_due: bool, + /// The sender's list was empty: it just started and asks who its neighbors are. + /// The spec owes an answer only to an unknown sender (3.6.4.4.2). We answer a + /// known one too so a restarted neighbor hears us at once. + pub link_status_answer_due: bool, } /// The neighbor table: link quality accounting, link status digestion, and aging. @@ -208,14 +218,18 @@ pub struct Neighbors { impl Neighbors { /// Record an LQI sample for the device that transmitted a frame to us. LQA is a /// property of the radio link to the MAC transmitter; the frame's NWK originator - /// may be several hops away. - pub fn record_lqa(&mut self, sender_nwk: Nwk, lqi: u8) { + /// may be several hops away. Returns whether a link status is due: ours lists the + /// sender from now on and did not before. + pub fn record_lqa(&mut self, sender_nwk: Nwk, lqi: u8) -> bool { if let Some(entry) = self .table .values_mut() .find(|entry| entry.network_address == sender_nwk) { + let was_in_link_status = entry.is_in_link_status(); entry.lqas.push(lqi); + + !was_in_link_status && entry.is_in_link_status() } else { // No neighbor entry yet (e.g. a sibling router that has not sent a link // status command). Buffer the sample so the entry starts with usable link @@ -227,6 +241,8 @@ impl Neighbors { } self.pending_lqas.entry(sender_nwk).or_default().push(lqi); + + false } } @@ -713,14 +729,11 @@ impl Neighbors { .values() // Only include routers in the link status list. Otherwise, we advertise // sleepy end devices that cannot be routed through. - .filter(|neighbor| neighbor.device_type == NwkDeviceType::Router) - .filter_map(|neighbor| { - // A neighbor we have not heard from yet has no cost to report - neighbor.lqas.median().map(|lqa| NwkLinkStatus { - address: neighbor.network_address, - incoming_cost: lqi_to_link_cost(lqa), - outgoing_cost: neighbor.outgoing_cost, - }) + .filter(|neighbor| neighbor.is_in_link_status()) + .map(|neighbor| NwkLinkStatus { + address: neighbor.network_address, + incoming_cost: neighbor.incoming_link_cost(), + outgoing_cost: neighbor.outgoing_cost, }) .collect() } @@ -785,8 +798,10 @@ impl Neighbors { } } - let gratuitous_link_status_due = - link_status_cmd.link_statuses.is_empty() && !self.table.contains_key(&source_ieee); + let was_in_link_status = self + .table + .get(&source_ieee) + .is_some_and(TableEntry::is_in_link_status); let neighbor_entry = self.table.entry(source_ieee).or_insert_with(|| { tracing::info!("Creating new neighbor entry for {source_ieee:?}"); @@ -886,7 +901,8 @@ impl Neighbors { LinkStatusOutcome { lost_link: lost_link.then_some(neighbor_entry.network_address), replaced_address, - gratuitous_link_status_due, + link_status_due: !was_in_link_status && neighbor_entry.is_in_link_status(), + link_status_answer_due: link_status_cmd.link_statuses.is_empty(), } } } @@ -981,9 +997,7 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - let outcome = - neighbors.on_link_status(own, router, old, 200, &link_status, now, ROUTER_AGE_LIMIT); - assert_eq!(outcome, LinkStatusOutcome::default()); + neighbors.on_link_status(own, router, old, 200, &link_status, now, ROUTER_AGE_LIMIT); neighbors.record_lqa(old, 200); neighbors.record_lqa(old, 200); assert_eq!(neighbors.link(old).unwrap().eui64, router); @@ -1000,7 +1014,8 @@ mod test { LinkStatusOutcome { lost_link: None, replaced_address: Some(old), - gratuitous_link_status_due: false, + link_status_due: false, + link_status_answer_due: false, } ); @@ -1059,12 +1074,12 @@ mod test { ROUTER_AGE_LIMIT, ); - assert_eq!(outcome, LinkStatusOutcome::default()); + assert_eq!(outcome.lost_link, None); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 1); } #[test] - fn test_empty_link_status_from_unknown_router_is_owed_an_answer() { + fn test_link_status_from_unknown_router_makes_ours_due() { let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); let (own, router_nwk) = (Nwk(0x0000), Nwk(0x1111)); let now = Instant::from_micros(0); @@ -1078,20 +1093,74 @@ mod test { LinkStatusOutcome { lost_link: None, replaced_address: None, - gratuitous_link_status_due: true, + link_status_due: true, + link_status_answer_due: true, } ); - // The router is known now + // The router is known now: its empty list is still owed an answer let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ROUTER_AGE_LIMIT); - assert_eq!(outcome, LinkStatusOutcome::default()); + assert_eq!( + outcome, + LinkStatusOutcome { + lost_link: None, + replaced_address: None, + link_status_due: false, + link_status_answer_due: true, + } + ); - // Another unknown router is owed one too + // Another unknown router makes one due too, whatever its list holds let other = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:22"); - let outcome = - neighbors.on_link_status(own, other, Nwk(0x2222), 200, &empty, now, ROUTER_AGE_LIMIT); - assert!(outcome.gratuitous_link_status_due); + let listing = link_status_listing(own); + let outcome = neighbors.on_link_status( + own, + other, + Nwk(0x2222), + 200, + &listing, + now, + ROUTER_AGE_LIMIT, + ); + assert!(outcome.link_status_due); + assert!(!outcome.link_status_answer_due); + } + + #[test] + fn test_first_frame_from_a_router_without_samples_makes_our_link_status_due() { + let mut neighbors = neighbors_with(NwkDeviceType::Router); + + assert!(neighbors.record_lqa(CHILD_NWK, 200)); + assert!(!neighbors.record_lqa(CHILD_NWK, 200)); + } + + #[test] + fn test_frames_from_other_senders_do_not_make_our_link_status_due() { + // An end device is never listed + let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); + assert!(!neighbors.record_lqa(CHILD_NWK, 200)); + + // Neither is a sender without a neighbor entry + assert!(!neighbors.record_lqa(Nwk(0x2222), 200)); + } + + #[test] + fn test_link_status_from_a_heard_end_device_makes_ours_due() { + // A child restored without its device type is loaded as an end device + let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); + neighbors.record_lqa(CHILD_NWK, 200); + + let outcome = neighbors.on_link_status( + Nwk(0x0000), + Eui64::from_hex("00:11:22:33:44:55:66:77"), + CHILD_NWK, + 200, + &link_status_listing(Nwk(0x0000)), + Instant::from_micros(0), + ROUTER_AGE_LIMIT, + ); + assert!(outcome.link_status_due); } #[test] @@ -1128,7 +1197,8 @@ mod test { LinkStatusOutcome { lost_link: Some(router_nwk), replaced_address: None, - gratuitous_link_status_due: false, + link_status_due: false, + link_status_answer_due: false, } ); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 0); From 0a64c402c235115c0815e690ff61c37c72311b4c Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:38:47 +0000 Subject: [PATCH 07/11] Migrate MTORR hooks to debouncer --- crates/ziggurat-driver/src/zigbee_stack.rs | 31 +++++++++++++--- .../src/zigbee_stack/neighbor.rs | 20 +++++------ .../ziggurat-driver/src/zigbee_stack/route.rs | 33 +++++++++-------- crates/ziggurat-zigbee/src/debouncer.rs | 35 ++++++++++++++----- 4 files changed, 81 insertions(+), 38 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 869bd62d..bcb41d05 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -353,6 +353,8 @@ pub struct Nib { pub neighbors: Neighbors, /// When the next link status broadcast is due pub link_status_debouncer: Debouncer, + /// When the next many-to-one route request is due + pub mtorr_debouncer: Debouncer, /// NWK routing state and decision logic (route/discovery/record tables) pub routing: Routing, /// Broadcast deduplication and passive acknowledgment accounting @@ -512,6 +514,7 @@ impl State { tx_total: 0, neighbors: Neighbors::default(), link_status_debouncer: Debouncer::default(), + mtorr_debouncer: Debouncer::default(), routing: Routing::default(), broadcasts: Broadcasts::default(), nwk_security: NwkSecurity::new( @@ -720,9 +723,9 @@ pub struct ZigbeeStack { /// network-wide broadcast storm (spec 2.4.3.1.12.2) pub(crate) parent_annce_received: Mutex>, - /// Wakes the MTORR scheduler before its max interval when accumulated route - /// errors or delivery failures cross their thresholds - pub(crate) mtorr_kick: Notify, + /// Wakes the many-to-one route request task when its next advertisement moved + /// earlier + pub(crate) mtorr_wake: 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 @@ -804,6 +807,26 @@ impl ZigbeeStack { R::sleep(deadline.saturating_duration_since(self.core_now())).await; } + /// Sleep until a debouncer fires. `wake` signals that a request moved its next + /// firing earlier: the sleep then starts again, until the new time. + async fn wait_for_debouncer( + &self, + debouncer: impl Fn(&Nib) -> &Debouncer + Send, + wake: &Notify, + ) { + loop { + let next = debouncer(&self.core().nib).next(); + let due = core::pin::pin!(self.sleep_until_core(next)); + let moved = core::pin::pin!(wake.notified()); + + if let futures::future::Either::Left(((), _)) = + futures::future::select(due, moved).await + { + return; + } + } + } + /// Run `future`, failing with [`Elapsed`] if a [`CoreInstant`] deadline passes first. async fn timeout_at_core( &self, @@ -847,7 +870,7 @@ impl ZigbeeStack { src_match_sync: Notify::new(), src_match_written: Mutex::new(SrcMatchTable::default()), parent_annce_received: Mutex::new(None), - mtorr_kick: Notify::new(), + mtorr_wake: Notify::new(), link_status_received: Notify::new(), link_status_wake: Notify::new(), address_conflict_wake: Notify::new(), diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index f8012ff5..e2be03f3 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -1,5 +1,6 @@ use crate::runtime::Runtime; use alloc::vec::Vec; +use core::time::Duration; use ziggurat_ieee_802154::types::{Eui64, Nwk}; use ziggurat_phy::RadioPhy; @@ -47,7 +48,12 @@ impl ZigbeeStack { let at = self.core_now() + jitter; - if self.core().nib.link_status_debouncer.request(at) { + if self + .core() + .nib + .link_status_debouncer + .request(at, Duration::ZERO) + { self.link_status_wake.notify_one(); } } @@ -236,16 +242,8 @@ impl ZigbeeStack { self.restart_link_status_period(); loop { - let next = self.core().nib.link_status_debouncer.next(); - let due = core::pin::pin!(self.sleep_until_core(next)); - let moved = core::pin::pin!(self.link_status_wake.notified()); - - // The broadcast moved earlier: sleep again, until its new time - if let futures::future::Either::Right(((), _)) = - futures::future::select(due, moved).await - { - continue; - } + self.wait_for_debouncer(|nib| &nib.link_status_debouncer, &self.link_status_wake) + .await; self.restart_link_status_period(); diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 74927828..fa4a640b 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -346,25 +346,28 @@ impl ZigbeeStack { } loop { - let min_deadline = self.core_now() + self.tunables.mtorr_min_interval(); - let max_deadline = self.core_now() + self.tunables.mtorr_max_interval(); + 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; self.core().nib.routing.reset_mtorr_triggers(); - // Advertise every max interval, sooner when accumulated route errors or - // delivery failures signal that routes toward us have gone bad, but never - // within the min interval - let max_sleep = core::pin::pin!(self.sleep_until_core(max_deadline)); - let kicked = core::pin::pin!(self.mtorr_kick.notified()); + // Advertise every max interval, or sooner when one was requested + self.wait_for_debouncer(|nib| &nib.mtorr_debouncer, &self.mtorr_wake) + .await; + } + } - if let futures::future::Either::Right(((), _)) = - futures::future::select(max_sleep, kicked).await - { - // Kicked early: still honor the minimum spacing before re-advertising. - self.sleep_until_core(min_deadline).await; - } + /// Advertise the many-to-one route again soon, but never within the min interval + /// of the last advertisement. + fn request_many_to_one_route_request(&self) { + let now = self.core_now(); + let min_interval = self.tunables.mtorr_min_interval(); + + if self.core().nib.mtorr_debouncer.request(now, min_interval) { + self.mtorr_wake.notify_one(); } } @@ -382,7 +385,7 @@ impl ZigbeeStack { .note_route_error(self.tunables.mtorr_route_error_threshold()); if kick { - self.mtorr_kick.notify_one(); + self.request_many_to_one_route_request(); } } @@ -400,7 +403,7 @@ impl ZigbeeStack { .note_delivery_failure(self.tunables.mtorr_delivery_failure_threshold()); if kick { - self.mtorr_kick.notify_one(); + self.request_many_to_one_route_request(); } } diff --git a/crates/ziggurat-zigbee/src/debouncer.rs b/crates/ziggurat-zigbee/src/debouncer.rs index 2fb47cfc..b9e6bc75 100644 --- a/crates/ziggurat-zigbee/src/debouncer.rs +++ b/crates/ziggurat-zigbee/src/debouncer.rs @@ -8,6 +8,7 @@ use crate::Instant; #[derive(Debug, Default)] pub struct Debouncer { next: Instant, + last_fired: Instant, } impl Debouncer { @@ -15,9 +16,11 @@ impl Debouncer { self.next } - /// Ask for a firing by `at`. Returns whether the next firing moved earlier: it - /// stays where it is if it is already due sooner. - pub fn request(&mut self, at: Instant) -> bool { + /// Ask for a firing by `at`, but no sooner than `min_interval` after the last one. + /// Returns whether the next firing moved earlier: it stays where it is if it is + /// already due sooner. + pub fn request(&mut self, at: Instant, min_interval: Duration) -> bool { + let at = at.max(self.last_fired + min_interval); let earlier = at < self.next; if earlier { @@ -29,6 +32,7 @@ impl Debouncer { /// It fires at `now`: the next firing is due an `interval` later. pub fn fired(&mut self, now: Instant, interval: Duration) { + self.last_fired = now; self.next = now + interval; } } @@ -53,9 +57,9 @@ mod test { fn test_requests_close_together_share_the_earliest_time() { let mut debouncer = started(); - assert!(debouncer.request(at(700))); - assert!(!debouncer.request(at(900))); - assert!(debouncer.request(at(600))); + assert!(debouncer.request(at(700), Duration::ZERO)); + assert!(!debouncer.request(at(900), Duration::ZERO)); + assert!(debouncer.request(at(600), Duration::ZERO)); assert_eq!(debouncer.next(), at(600)); } @@ -64,16 +68,31 @@ mod test { fn test_request_after_the_interval_end_changes_nothing() { let mut debouncer = started(); - assert!(!debouncer.request(at(15_500))); + assert!(!debouncer.request(at(15_500), Duration::ZERO)); assert_eq!(debouncer.next(), at(15_000)); } #[test] fn test_firing_restarts_the_interval() { let mut debouncer = started(); - debouncer.request(at(700)); + debouncer.request(at(700), Duration::ZERO); debouncer.fired(at(700), INTERVAL); assert_eq!(debouncer.next(), at(15_700)); } + + #[test] + fn test_request_waits_out_the_minimum_interval() { + let min_interval = Duration::from_secs(10); + let mut debouncer = started(); + + // Too soon after the last firing: held until the minimum interval has passed + assert!(debouncer.request(at(2_000), min_interval)); + assert_eq!(debouncer.next(), at(10_000)); + + // A request after it is taken as it is + debouncer.fired(at(10_000), INTERVAL); + assert!(debouncer.request(at(21_000), min_interval)); + assert_eq!(debouncer.next(), at(21_000)); + } } From aa6d26bf6821710c54c6b2e35e15b4ba3b0f4187 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:06:44 +0000 Subject: [PATCH 08/11] Gate early link status for unknown routers behind a hack flag --- crates/ziggurat-driver/src/zigbee_stack/neighbor.rs | 4 +++- crates/ziggurat-zigbee/src/constants.rs | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index e2be03f3..309cf5dc 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -142,7 +142,9 @@ impl ZigbeeStack { if outcome.link_status_answer_due { self.request_early_link_status(); - } else if outcome.link_status_due { + } else if outcome.link_status_due + && self.tunables.hack_early_link_status_for_unknown_routers() + { self.request_link_status_for_new_router(); } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 9b141bf3..3f8aa143 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -414,6 +414,13 @@ tunables! { /// that permanently permit joins. Zero disables it (a single beacon per request, /// the spec behaviour). hack_beacon_spam_duration: Duration = Duration::from_millis(100), + + /// Uncooperative on a large network: as the coordinator, send an extra link status + /// within a second of the first link status from a router we did not know, so it + /// learns its cost without waiting for the next period. After a restart every + /// router is unknown, which means a burst of link statuses. When false, such a + /// router waits for the periodic link status. + hack_early_link_status_for_unknown_routers: bool = true, } #[cfg(test)] From 4001a53368146fad43f0ae7dbd6ade5556a2c9e2 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:25:05 +0000 Subject: [PATCH 09/11] Compute activity decay steps without truncating the period --- crates/ziggurat-zigbee/src/nwk/activity.rs | 23 ++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/ziggurat-zigbee/src/nwk/activity.rs b/crates/ziggurat-zigbee/src/nwk/activity.rs index 3c110621..7d07c144 100644 --- a/crates/ziggurat-zigbee/src/nwk/activity.rs +++ b/crates/ziggurat-zigbee/src/nwk/activity.rs @@ -44,11 +44,15 @@ impl Activity { /// `period`. `*decayed_at` moves forward by the steps returned, so the rest of the time /// counts toward the next call. pub fn take_decay_steps(decayed_at: &mut Instant, now: Instant, period: Duration) -> u16 { - let step = period / u32::from(STEPS_PER_COUNT); - let elapsed = now.saturating_duration_since(*decayed_at).as_micros() / step.as_micros(); - let steps = u16::try_from(elapsed).unwrap_or(u16::MAX); + let steps_per_count = u64::from(STEPS_PER_COUNT); + let period = u64::try_from(period.as_micros()).unwrap(); + let elapsed = now.as_micros().saturating_sub(decayed_at.as_micros()); + let steps = u16::try_from(elapsed * steps_per_count / period).unwrap_or(u16::MAX); - *decayed_at = *decayed_at + step * u32::from(steps); + // Rounded up, so a step shorter than a microsecond still moves `*decayed_at` + let taken = (u64::from(steps) * period).div_ceil(steps_per_count); + + *decayed_at = Instant::from_micros(decayed_at.as_micros() + taken); steps } @@ -88,6 +92,17 @@ mod test { assert_eq!(take_decay_steps(&mut decayed_at, at(125), PERIOD), 2); } + #[test] + fn test_period_shorter_than_256_microseconds_decays() { + let period = Duration::from_micros(100); + let mut decayed_at = at(0); + let now = Instant::from_micros(50); + + // Half a period is half a count, and the same instant again owes nothing + assert_eq!(take_decay_steps(&mut decayed_at, now, period), 128); + assert_eq!(take_decay_steps(&mut decayed_at, now, period), 0); + } + #[test] fn test_activity_stays_between_0_and_255() { let mut activity = Activity::new(254); From 41bf06f9271e1c16f4e186e1f7034285a31c1ae9 Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:25:35 +0000 Subject: [PATCH 10/11] Take every elapsed activity decay step in one call --- crates/ziggurat-zigbee/src/nwk/activity.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ziggurat-zigbee/src/nwk/activity.rs b/crates/ziggurat-zigbee/src/nwk/activity.rs index 7d07c144..f7479ad8 100644 --- a/crates/ziggurat-zigbee/src/nwk/activity.rs +++ b/crates/ziggurat-zigbee/src/nwk/activity.rs @@ -47,13 +47,15 @@ pub fn take_decay_steps(decayed_at: &mut Instant, now: Instant, period: Duration let steps_per_count = u64::from(STEPS_PER_COUNT); let period = u64::try_from(period.as_micros()).unwrap(); let elapsed = now.as_micros().saturating_sub(decayed_at.as_micros()); - let steps = u16::try_from(elapsed * steps_per_count / period).unwrap_or(u16::MAX); + let steps = elapsed * steps_per_count / period; // Rounded up, so a step shorter than a microsecond still moves `*decayed_at` - let taken = (u64::from(steps) * period).div_ceil(steps_per_count); + let taken = (steps * period).div_ceil(steps_per_count); + // All of the steps are taken, even when they are more than a counter can hold: + // none is left over to decay a use recorded after this call *decayed_at = Instant::from_micros(decayed_at.as_micros() + taken); - steps + u16::try_from(steps).unwrap_or(u16::MAX) } #[cfg(test)] @@ -103,6 +105,16 @@ mod test { assert_eq!(take_decay_steps(&mut decayed_at, now, period), 0); } + #[test] + fn test_long_gap_is_taken_in_one_call() { + let mut decayed_at = at(0); + + // Two hours hold more steps than a counter does + let now = at(2 * 60 * 60 * 1000); + assert_eq!(take_decay_steps(&mut decayed_at, now, PERIOD), u16::MAX); + assert_eq!(take_decay_steps(&mut decayed_at, now, PERIOD), 0); + } + #[test] fn test_activity_stays_between_0_and_255() { let mut activity = Activity::new(254); From 52e1bf99820ad8e28d525f0e64fae5f920dfda7a Mon Sep 17 00:00:00 2001 From: puddly <32534428+puddly@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:28:30 +0000 Subject: [PATCH 11/11] Decay activity counters before every update, not only on a link status --- crates/ziggurat-driver/src/zigbee_stack.rs | 9 + .../src/zigbee_stack/joining.rs | 4 +- .../src/zigbee_stack/neighbor.rs | 20 +- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 28 ++- .../ziggurat-driver/src/zigbee_stack/route.rs | 7 +- .../ziggurat-driver/src/zigbee_stack/sends.rs | 2 +- crates/ziggurat-protocol/src/bridge.rs | 5 +- crates/ziggurat-zigbee/src/nwk/activity.rs | 9 + crates/ziggurat-zigbee/src/nwk/neighbors.rs | 197 +++++++++--------- crates/ziggurat-zigbee/src/nwk/routing.rs | 86 ++++---- .../ziggurat-zigbee/src/nwk/routing/tests.rs | 144 +++++-------- 11 files changed, 252 insertions(+), 259 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index bcb41d05..832cc811 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -24,6 +24,7 @@ use core::sync::atomic::{AtomicBool, AtomicU32, Ordering as AtomicOrdering}; use core::time::Duration; use ziggurat_zigbee::debouncer::Debouncer; use ziggurat_zigbee::flat_map::FlatMap; +use ziggurat_zigbee::nwk::activity::ActivityParams; use ziggurat_zigbee::nwk::frame::{NwkFrame, NwkSecurityHeaderKeyId}; mod aps; @@ -807,6 +808,14 @@ impl ZigbeeStack { R::sleep(deadline.saturating_duration_since(self.core_now())).await; } + /// What the tables need to keep their activity counters. + pub fn activity_params(&self) -> ActivityParams { + ActivityParams { + initial_count: self.tunables.router_age_limit(), + period: self.tunables.link_status_period(), + } + } + /// Sleep until a debouncer fires. `wake` signals that a request moved its next /// firing earlier: the sleep then starts again, until the new time. async fn wait_for_debouncer( diff --git a/crates/ziggurat-driver/src/zigbee_stack/joining.rs b/crates/ziggurat-driver/src/zigbee_stack/joining.rs index 05f45ab5..7142ec8f 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/joining.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/joining.rs @@ -117,7 +117,7 @@ impl ZigbeeStack { relationship: neighbors::Relationship::UnauthenticatedChild, }, self.core_now(), - self.tunables.router_age_limit(), + self.activity_params(), ); // A new child deadline may precede everything the maintenance task knows @@ -1181,7 +1181,7 @@ impl ZigbeeStack { }, }, self.core_now(), - self.tunables.router_age_limit(), + self.activity_params(), ); // A new child deadline may precede everything the maintenance task knows diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 309cf5dc..a1b5d0c6 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -122,7 +122,7 @@ impl ZigbeeStack { lqi, &link_status_cmd, self.core_now(), - self.tunables.router_age_limit(), + self.activity_params(), ); // The neighbor no longer answers at its old address, so routes through it @@ -163,20 +163,10 @@ impl ZigbeeStack { self.maybe_age_neighbors(); - let mut link_statuses = { - let mut core = self.core(); - let now = self.core_now(); - let period = self.tunables.link_status_period(); - - // Both decay by the time passed, so an extra link status is harmless - core.nib.routing.decay_activity(now, period); - core.nib.neighbors.decay_activity(now, period); - - if empty { - Vec::new() - } else { - core.nib.neighbors.link_status_entries() - } + let mut link_statuses = if empty { + Vec::new() + } else { + self.core().nib.neighbors.link_status_entries() }; // Link statuses are sorted in ascending order diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 741bc1ea..078ee6cb 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -56,7 +56,8 @@ impl ZigbeeStack { core.nib.routing.forget( self.state.network_address, nwk, - self.tunables.router_age_limit(), + self.core_now(), + self.activity_params(), ); core.sends.fail_unrouted(nwk); self.commit_sends(core); @@ -446,7 +447,7 @@ impl ZigbeeStack { now, self.tunables.route_discovery_time(), self.tunables.pending_route_discovery_attempts(), - self.tunables.router_age_limit(), + self.activity_params(), ); if let Some(route_request_identifier) = route_request_identifier { self.broadcast_discovery_request( @@ -574,13 +575,19 @@ impl ZigbeeStack { let relaying_ieee = core.nib.address_map.eui64_for(next_hop_address); if let Some(relaying_ieee) = relaying_ieee { - core.nib.neighbors.record_outbound_activity(relaying_ieee); + core.nib.neighbors.record_outbound_activity( + relaying_ieee, + self.core_now(), + self.tunables.link_status_period(), + ); } // And the routing table counters - core.nib - .routing - .record_usage(nwk_frame.nwk_header.destination); + core.nib.routing.record_usage( + nwk_frame.nwk_header.destination, + self.core_now(), + self.tunables.link_status_period(), + ); } self.increment_tx_total(); @@ -841,10 +848,11 @@ impl ZigbeeStack { self.maybe_recompute_lqa(sender_nwk, lqi, rssi); // Receiving a unicast from a neighbor counts as inbound activity - self.core() - .nib - .neighbors - .record_inbound_activity(sender_nwk); + self.core().nib.neighbors.record_inbound_activity( + sender_nwk, + self.core_now(), + self.tunables.link_status_period(), + ); // Spec 3.6.2.2: the radius is decremented on receipt and a frame that reaches // zero is never retransmitted diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index fa4a640b..a5e653a7 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -44,7 +44,7 @@ impl ZigbeeStack { nwk_frame.nwk_header.source, updated_path_cost, now, - self.tunables.router_age_limit(), + self.activity_params(), ); let (next_hop_nwk, path_cost) = match outcome.disposition { @@ -159,7 +159,7 @@ impl ZigbeeStack { route_request_cmd.many_to_one, self.core_now(), self.tunables.route_discovery_time(), - self.tunables.router_age_limit(), + self.activity_params(), ); if !outcome.accepted { @@ -237,7 +237,8 @@ impl ZigbeeStack { if !many_to_one { self.core().nib.routing.note_relayed_discovery( route_request_cmd.destination_address, - self.tunables.router_age_limit(), + self.core_now(), + self.activity_params(), ); } diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index 2a489840..3d54d05c 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -372,7 +372,7 @@ impl ZigbeeStack { self.state.network_address, now, self.tunables.route_discovery_time(), - self.tunables.router_age_limit(), + self.activity_params(), |destination| core.sends.has_unrouted(destination), ); diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 91a3b9cb..05a23e45 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -202,7 +202,7 @@ pub fn apply_children( relationship: Relationship::Child, }, now, - stack.tunables.router_age_limit(), + stack.activity_params(), ); core.nib.address_map.update_mapping(entry.ieee, entry.nwk); } @@ -228,7 +228,8 @@ pub fn apply_route_table( entry.destination, entry.next_hop, entry.path_cost, - stack.tunables.router_age_limit(), + stack.core_now(), + stack.activity_params(), ); } } diff --git a/crates/ziggurat-zigbee/src/nwk/activity.rs b/crates/ziggurat-zigbee/src/nwk/activity.rs index f7479ad8..4bf77424 100644 --- a/crates/ziggurat-zigbee/src/nwk/activity.rs +++ b/crates/ziggurat-zigbee/src/nwk/activity.rs @@ -40,6 +40,15 @@ impl Activity { } } +/// What a table needs to keep activity counters. +#[derive(Debug, Clone, Copy)] +pub struct ActivityParams { + /// The count a new counter starts at (`nwkRouterAgeLimit`) + pub initial_count: u8, + /// The time one count takes to decay (`nwkLinkStatusPeriod`) + pub period: Duration, +} + /// The decay steps owed for the time from `*decayed_at` to `now`, at one count per /// `period`. `*decayed_at` moves forward by the steps returned, so the rest of the time /// counts toward the next call. diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index 9efc80a4..cc09af65 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -3,7 +3,7 @@ use alloc::vec::Vec; use core::cmp; use crate::Instant; -use crate::nwk::activity::{Activity, take_decay_steps}; +use crate::nwk::activity::{Activity, ActivityParams, take_decay_steps}; use crate::nwk::commands::{NwkLinkStatus, NwkLinkStatusCommand}; use crate::nwk::frame::NwkHeader; use crate::ring_buffer::RingBuffer; @@ -544,14 +544,19 @@ impl Neighbors { /// across attachment retries. The fields a device may change between attachments /// are refreshed even on existing entries: a device may re-attach with different /// capabilities (e.g. re-flashed from router to end device). - pub fn upsert_child(&mut self, child: ChildDescriptor, now: Instant, router_age_limit: u8) { - self.upsert(child, now, Some(now), router_age_limit); + pub fn upsert_child(&mut self, child: ChildDescriptor, now: Instant, activity: ActivityParams) { + self.upsert(child, now, Some(now), activity); } /// Seed a child entry restored by the client on startup. Unlike a device that /// associates or rejoins, a restored child did not just attach to us. - pub fn restore_child(&mut self, child: ChildDescriptor, now: Instant, router_age_limit: u8) { - self.upsert(child, now, None, router_age_limit); + pub fn restore_child( + &mut self, + child: ChildDescriptor, + now: Instant, + activity: ActivityParams, + ) { + self.upsert(child, now, None, activity); } fn upsert( @@ -559,8 +564,10 @@ impl Neighbors { child: ChildDescriptor, now: Instant, attached_at: Option, - router_age_limit: u8, + activity: ActivityParams, ) { + self.decay_activity(now, activity.period); + let entry = self.table.entry(child.eui64).or_insert_with(|| TableEntry { extended_address: child.eui64, network_address: child.network_address, @@ -583,8 +590,8 @@ impl Neighbors { attached_at, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: Activity::new(router_age_limit), - router_inbound_activity: Activity::new(router_age_limit), + router_outbound_activity: Activity::new(activity.initial_count), + router_inbound_activity: Activity::new(activity.initial_count), security_timer: 0, }); @@ -685,6 +692,10 @@ impl Neighbors { pub fn decay_activity(&mut self, now: Instant, period: Duration) { let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + if steps == 0 { + return; + } + for entry in self.table.values_mut() { entry.router_outbound_activity.decay(steps); entry.router_inbound_activity.decay(steps); @@ -692,14 +703,18 @@ impl Neighbors { } /// A unicast was forwarded through this neighbor. - pub fn record_outbound_activity(&mut self, eui64: Eui64) { + pub fn record_outbound_activity(&mut self, eui64: Eui64, now: Instant, period: Duration) { + self.decay_activity(now, period); + if let Some(entry) = self.table.get_mut(&eui64) { entry.router_outbound_activity.record_use(); } } /// A unicast from this neighbor was received for relaying. - pub fn record_inbound_activity(&mut self, nwk: Nwk) { + pub fn record_inbound_activity(&mut self, nwk: Nwk, now: Instant, period: Duration) { + self.decay_activity(now, period); + if let Some(entry) = self .table .values_mut() @@ -749,8 +764,10 @@ impl Neighbors { lqi: u8, link_status_cmd: &NwkLinkStatusCommand, now: Instant, - router_age_limit: u8, + activity: ActivityParams, ) -> LinkStatusOutcome { + self.decay_activity(now, activity.period); + // Collect the set of already-connected neighbors before mutating the state, for // the neighbor set diversity computation let neighbors_with_nonzero_outgoing_cost = self @@ -828,8 +845,8 @@ impl Neighbors { attached_at: None, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: Activity::new(router_age_limit), - router_inbound_activity: Activity::new(router_age_limit), + router_outbound_activity: Activity::new(activity.initial_count), + router_inbound_activity: Activity::new(activity.initial_count), security_timer: 0, }; @@ -914,7 +931,10 @@ mod test { use hex_literal::hex; const CHILD_NWK: Nwk = Nwk(0x1234); - const ROUTER_AGE_LIMIT: u8 = 3; + const ACTIVITY: ActivityParams = ActivityParams { + initial_count: 3, + period: Duration::from_secs(15), + }; fn neighbors_with(device_type: NwkDeviceType) -> Neighbors { let mut neighbors = Neighbors::default(); @@ -928,7 +948,7 @@ mod test { relationship: Relationship::Child, }, Instant::from_micros(0), - ROUTER_AGE_LIMIT, + ACTIVITY, ); neighbors } @@ -997,7 +1017,7 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 200, &link_status, now, ROUTER_AGE_LIMIT); + neighbors.on_link_status(own, router, old, 200, &link_status, now, ACTIVITY); neighbors.record_lqa(old, 200); neighbors.record_lqa(old, 200); assert_eq!(neighbors.link(old).unwrap().eui64, router); @@ -1007,8 +1027,7 @@ mod test { // link status carries the new address with the router's EUI64 neighbors.record_lqa(new, 40); neighbors.record_lqa(new, 40); - let outcome = - neighbors.on_link_status(own, router, new, 40, &link_status, now, ROUTER_AGE_LIMIT); + let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now, ACTIVITY); assert_eq!( outcome, LinkStatusOutcome { @@ -1036,8 +1055,7 @@ mod test { assert_eq!(advertised, vec![new]); // A later link status from the same address changes nothing - let outcome = - neighbors.on_link_status(own, router, new, 40, &link_status, now, ROUTER_AGE_LIMIT); + let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now, ACTIVITY); assert_eq!(outcome, LinkStatusOutcome::default()); } @@ -1055,7 +1073,7 @@ mod test { 200, &listing, Instant::from_micros(0), - ROUTER_AGE_LIMIT, + ACTIVITY, ); let empty = NwkLinkStatusCommand { @@ -1064,15 +1082,8 @@ mod test { link_statuses: vec![], }; let later = Instant::from_micros(1); - let outcome = neighbors.on_link_status( - own, - router, - router_nwk, - 200, - &empty, - later, - ROUTER_AGE_LIMIT, - ); + let outcome = + neighbors.on_link_status(own, router, router_nwk, 200, &empty, later, ACTIVITY); assert_eq!(outcome.lost_link, None); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 1); @@ -1086,8 +1097,7 @@ mod test { let empty = link_status_frame(true, true, &[]); let mut neighbors = Neighbors::default(); - let outcome = - neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ROUTER_AGE_LIMIT); + let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ACTIVITY); assert_eq!( outcome, LinkStatusOutcome { @@ -1099,8 +1109,7 @@ mod test { ); // The router is known now: its empty list is still owed an answer - let outcome = - neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ROUTER_AGE_LIMIT); + let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ACTIVITY); assert_eq!( outcome, LinkStatusOutcome { @@ -1114,15 +1123,8 @@ mod test { // Another unknown router makes one due too, whatever its list holds let other = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:22"); let listing = link_status_listing(own); - let outcome = neighbors.on_link_status( - own, - other, - Nwk(0x2222), - 200, - &listing, - now, - ROUTER_AGE_LIMIT, - ); + let outcome = + neighbors.on_link_status(own, other, Nwk(0x2222), 200, &listing, now, ACTIVITY); assert!(outcome.link_status_due); assert!(!outcome.link_status_answer_due); } @@ -1158,7 +1160,7 @@ mod test { 200, &link_status_listing(Nwk(0x0000)), Instant::from_micros(0), - ROUTER_AGE_LIMIT, + ACTIVITY, ); assert!(outcome.link_status_due); } @@ -1171,26 +1173,11 @@ mod test { let mut neighbors = Neighbors::default(); let listing = link_status_listing(own); - neighbors.on_link_status( - own, - router, - router_nwk, - 200, - &listing, - now, - ROUTER_AGE_LIMIT, - ); + neighbors.on_link_status(own, router, router_nwk, 200, &listing, now, ACTIVITY); let without_us = link_status_listing(Nwk(0x2222)); - let outcome = neighbors.on_link_status( - own, - router, - router_nwk, - 200, - &without_us, - now, - ROUTER_AGE_LIMIT, - ); + let outcome = + neighbors.on_link_status(own, router, router_nwk, 200, &without_us, now, ACTIVITY); assert_eq!( outcome, @@ -1231,16 +1218,8 @@ mod test { let mut neighbors = Neighbors::default(); let listing = link_status_listing(own); - neighbors.on_link_status( - own, - router, - router_nwk, - 200, - &listing, - now, - ROUTER_AGE_LIMIT, - ); - neighbors.on_link_status(own, router, router_nwk, 200, frame, now, ROUTER_AGE_LIMIT); + neighbors.on_link_status(own, router, router_nwk, 200, &listing, now, ACTIVITY); + neighbors.on_link_status(own, router, router_nwk, 200, frame, now, ACTIVITY); neighbors.link(router_nwk).unwrap().outgoing_cost } @@ -1294,15 +1273,7 @@ mod test { |neighbors: &Neighbors| neighbors.link(router_nwk).unwrap().incoming_cost; // One sample is the link quality, and the router is listed at once - neighbors.on_link_status( - own, - router, - router_nwk, - 200, - &link_status, - now, - ROUTER_AGE_LIMIT, - ); + neighbors.on_link_status(own, router, router_nwk, 200, &link_status, now, ACTIVITY); assert_eq!(incoming_cost(&neighbors), lqi_to_link_cost(200)); assert_eq!(neighbors.link_status_entries().len(), 1); @@ -1333,16 +1304,8 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 200, &link_status, now, ROUTER_AGE_LIMIT); - neighbors.on_link_status( - own, - other, - contested, - 200, - &link_status, - now, - ROUTER_AGE_LIMIT, - ); + neighbors.on_link_status(own, router, old, 200, &link_status, now, ACTIVITY); + neighbors.on_link_status(own, other, contested, 200, &link_status, now, ACTIVITY); // The router's link status from an address the other neighbor holds, or from // our own address, is an address conflict: the router keeps its entry's address @@ -1354,7 +1317,7 @@ mod test { 200, &link_status, now, - ROUTER_AGE_LIMIT, + ACTIVITY, ); assert_eq!(outcome, LinkStatusOutcome::default()); assert_eq!(neighbors.link(old).unwrap().eui64, router); @@ -1372,13 +1335,13 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 10, &link_status, now, ROUTER_AGE_LIMIT); + neighbors.on_link_status(own, router, old, 10, &link_status, now, ACTIVITY); // More samples than the window buffered under the new address: the ring wraps for lqi in [10, 20, 200, 220] { neighbors.record_lqa(new, lqi); } - neighbors.on_link_status(own, router, new, 220, &link_status, now, ROUTER_AGE_LIMIT); + neighbors.on_link_status(own, router, new, 220, &link_status, now, ACTIVITY); // The window is [20, 200, 220] and its oldest (20) is replaced next, giving // [200, 220, 30]: a scrambled order would replace 220 and drop the median to 30 @@ -1389,6 +1352,46 @@ mod test { ); } + fn inbound_activity(neighbors: &Neighbors) -> u8 { + let entry = neighbors.entries().next().unwrap(); + entry.router_inbound_activity.count() + } + + #[test] + fn test_new_neighbor_is_not_charged_for_time_before_it_existed() { + // Created a minute in: the minute before must not decay its counters + let created = Instant::from_micros(0) + Duration::from_secs(60); + let mut neighbors = Neighbors::default(); + neighbors.restore_child( + ChildDescriptor { + eui64: Eui64::from_hex("00:11:22:33:44:55:66:77"), + network_address: CHILD_NWK, + device_type: NwkDeviceType::Router, + rx_on_when_idle: true, + device_timeout: None, + relationship: Relationship::Child, + }, + created, + ACTIVITY, + ); + + neighbors.decay_activity(created + Duration::from_secs(1), ACTIVITY.period); + assert_eq!(inbound_activity(&neighbors), ACTIVITY.initial_count - 1); + } + + #[test] + fn test_use_is_not_charged_for_time_before_it() { + // By a minute in, the count the neighbor started with has decayed away + let used = Instant::from_micros(0) + Duration::from_secs(60); + let mut neighbors = neighbors_with(NwkDeviceType::Router); + neighbors.record_inbound_activity(CHILD_NWK, used, ACTIVITY.period); + neighbors.record_inbound_activity(CHILD_NWK, used, ACTIVITY.period); + + // The two uses lose only the second that follows them + neighbors.decay_activity(used + Duration::from_secs(1), ACTIVITY.period); + assert_eq!(inbound_activity(&neighbors), 1); + } + #[test] fn test_only_end_device_children_time_out() { let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); @@ -1402,7 +1405,7 @@ mod test { relationship: Relationship::Child, }, Instant::from_micros(0), - ROUTER_AGE_LIMIT, + ACTIVITY, ); assert_eq!( @@ -1441,7 +1444,7 @@ mod test { relationship: Relationship::UnauthenticatedChild, }, Instant::from_micros(0), - ROUTER_AGE_LIMIT, + ACTIVITY, ); // Still a child for parent duties while unauthenticated @@ -1469,7 +1472,7 @@ mod test { relationship: Relationship::UnauthenticatedChild, }, Instant::from_micros(0), - ROUTER_AGE_LIMIT, + ACTIVITY, ); assert_eq!( relationship_of(&neighbors, eui64), diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index c9b60b3b..f0ce768e 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -2,7 +2,7 @@ use crate::flat_map::FlatMap; use alloc::vec::Vec; use crate::Instant; -use crate::nwk::activity::{Activity, take_decay_steps}; +use crate::nwk::activity::{Activity, ActivityParams, take_decay_steps}; use crate::nwk::commands::NwkRouteRequestManyToOne; use core::time::Duration; use ziggurat_ieee_802154::types::Nwk; @@ -78,7 +78,7 @@ impl TableEntry { destination: Nwk, status: Status, next_hop_address: Nwk, - router_age_limit: u8, + activity: ActivityParams, ) -> Self { Self { destination, @@ -90,7 +90,7 @@ impl TableEntry { next_hop_address, path_cost: u8::MAX, total_usage_count: 0, - recent_activity: Activity::new(router_age_limit), + recent_activity: Activity::new(activity.initial_count), } } @@ -344,8 +344,10 @@ impl Routing { now: Instant, route_discovery_time: Duration, attempts: u8, - router_age_limit: u8, + activity: ActivityParams, ) -> Option { + self.decay_activity(now, activity.period); + if self.discoveries_left.contains_key(&destination) { return None; } @@ -362,7 +364,7 @@ impl Routing { destination, now, route_discovery_time, - router_age_limit, + activity, )) } @@ -374,9 +376,11 @@ impl Routing { own_address: Nwk, now: Instant, route_discovery_time: Duration, - router_age_limit: u8, + activity: ActivityParams, wanted: impl Fn(Nwk) -> bool, ) -> DiscoveryTick { + self.decay_activity(now, activity.period); + let mut tick = DiscoveryTick::default(); self.expire_discoveries(now); @@ -403,7 +407,7 @@ impl Routing { destination, now, route_discovery_time, - router_age_limit, + activity, ); tick.restarted.push((destination, request_id)); true @@ -427,7 +431,9 @@ impl Routing { } /// A frame was forwarded along the route: bump its usage counters. - pub fn record_usage(&mut self, destination: Nwk) { + pub fn record_usage(&mut self, destination: Nwk, now: Instant, period: Duration) { + self.decay_activity(now, period); + if let Some(entry) = self.route_table.get_mut(&destination) { entry.recent_activity.record_use(); entry.total_usage_count = entry.total_usage_count.saturating_add(1); @@ -439,6 +445,10 @@ impl Routing { pub fn decay_activity(&mut self, now: Instant, period: Duration) { let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + if steps == 0 { + return; + } + // Spec Table 3-77: "decremented unconditionally", whatever the route's status for entry in self.route_table.values_mut() { entry.recent_activity.decay(steps); @@ -471,7 +481,9 @@ impl Routing { } /// The device at `nwk` left or joined again, clear associated state. - pub fn forget(&mut self, own_address: Nwk, nwk: Nwk, router_age_limit: u8) { + pub fn forget(&mut self, own_address: Nwk, nwk: Nwk, now: Instant, activity: ActivityParams) { + self.decay_activity(now, activity.period); + self.route_table.remove(&nwk); self.route_record_table.remove(&nwk); self.discoveries_left.remove(&nwk); @@ -494,12 +506,7 @@ impl Routing { { self.route_table.insert( nwk, - TableEntry::new( - nwk, - Status::DiscoveryUnderway, - UNKNOWN_NEXT_HOP, - router_age_limit, - ), + TableEntry::new(nwk, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP, activity), ); } } @@ -511,9 +518,12 @@ impl Routing { destination: Nwk, next_hop: Nwk, path_cost: u8, - router_age_limit: u8, + now: Instant, + activity: ActivityParams, ) { - let mut entry = TableEntry::new(destination, Status::Active, next_hop, router_age_limit); + self.decay_activity(now, activity.period); + + let mut entry = TableEntry::new(destination, Status::Active, next_hop, activity); entry.path_cost = path_cost; self.route_table.insert(destination, entry); } @@ -605,7 +615,7 @@ impl Routing { destination: Nwk, now: Instant, route_discovery_time: Duration, - router_age_limit: u8, + activity: ActivityParams, ) -> RouteRequestId { // Expire stale discoveries before establishing the new one. A just-expired // discovery toward this same destination would otherwise tear down the @@ -613,12 +623,7 @@ impl Routing { self.expire_discoveries(now); let route_table_entry = self.route_table.entry(destination).or_insert_with(|| { - TableEntry::new( - destination, - Status::Inactive, - UNKNOWN_NEXT_HOP, - router_age_limit, - ) + TableEntry::new(destination, Status::Inactive, UNKNOWN_NEXT_HOP, activity) }); route_table_entry.status = Status::DiscoveryUnderway; @@ -695,8 +700,10 @@ impl Routing { many_to_one: NwkRouteRequestManyToOne, now: Instant, route_discovery_time: Duration, - router_age_limit: u8, + activity: ActivityParams, ) -> RouteRequestOutcome { + self.decay_activity(now, activity.period); + self.expire_discoveries(now); let fresh = match self.discovery_table.get_mut(&(originator, request_id)) { @@ -742,12 +749,7 @@ impl Routing { // Spec 3.6.4.5.1.2: the route back to the originator runs through the device we // accepted the request from, subject to the 3.6.4.5.3 suitability rule. let originator_entry = self.route_table.entry(originator).or_insert_with(|| { - TableEntry::new( - originator, - Status::Inactive, - UNKNOWN_NEXT_HOP, - router_age_limit, - ) + TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP, activity) }); let route_changed = originator_entry.consider_route(sender, updated_path_cost); @@ -784,7 +786,14 @@ impl Routing { /// Before relaying a route request: mark the destination's entry as /// `DiscoveryUnderway`, so the reply we relay back finds it (spec 3.6.4.5.1.2). - pub fn note_relayed_discovery(&mut self, destination: Nwk, router_age_limit: u8) { + pub fn note_relayed_discovery( + &mut self, + destination: Nwk, + now: Instant, + activity: ActivityParams, + ) { + self.decay_activity(now, activity.period); + self.route_table .entry(destination) .and_modify(|entry| { @@ -797,7 +806,7 @@ impl Routing { destination, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP, - router_age_limit, + activity, ) }); } @@ -815,8 +824,10 @@ impl Routing { sender: Nwk, updated_path_cost: u8, now: Instant, - router_age_limit: u8, + activity: ActivityParams, ) -> RouteReplyOutcome { + self.decay_activity(now, activity.period); + // A reply to a discovery that has lapsed finds no entry and is dropped self.expire_discoveries(now); @@ -908,12 +919,7 @@ impl Routing { // toward the originator of the route request, subject to the 3.6.4.5.3 // suitability rule so a worse path never replaces a good ACTIVE route. let reverse_entry = self.route_table.entry(originator).or_insert_with(|| { - TableEntry::new( - originator, - Status::Inactive, - UNKNOWN_NEXT_HOP, - router_age_limit, - ) + TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP, activity) }); let update = reverse_entry diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 37b2c469..2fcc1c1a 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -19,6 +19,10 @@ const START: Instant = Instant::from_micros(0); const ROUTE_DISCOVERY_TIME: Duration = Duration::from_secs(10); const MAX_SOURCE_ROUTE: u8 = 11; const ROUTER_AGE_LIMIT: u8 = 3; +const ACTIVITY: ActivityParams = ActivityParams { + initial_count: ROUTER_AGE_LIMIT, + period: Duration::from_secs(15), +}; /// A route request relayed to us by `NEIGHBOR`. #[derive(Clone, Copy)] @@ -40,7 +44,7 @@ fn receive(routing: &mut Routing, request: RouteRequest, now: Instant) -> bool { NwkRouteRequestManyToOne::NotManyToOne, now, ROUTE_DISCOVERY_TIME, - ROUTER_AGE_LIMIT, + ACTIVITY, ) .accepted } @@ -50,7 +54,7 @@ fn receive(routing: &mut Routing, request: RouteRequest, now: Instant) -> bool { #[test] fn test_forget_drops_our_discovery_toward_the_device() { let mut routing = Routing::default(); - routing.begin_discovery(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, ROUTER_AGE_LIMIT); + routing.begin_discovery(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, ACTIVITY); assert_eq!( routing.own_discovery_lapse(OWN, DEVICE, START), Some(START + ROUTE_DISCOVERY_TIME) @@ -60,7 +64,7 @@ fn test_forget_drops_our_discovery_toward_the_device() { Some(Status::DiscoveryUnderway) ); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.own_discovery_lapse(OWN, DEVICE, START), None); assert_eq!(routing.route_status(DEVICE), None); @@ -70,7 +74,7 @@ fn test_forget_drops_our_discovery_toward_the_device() { fn test_recent_activity_decays_on_an_inactive_route() { let period = Duration::from_secs(15); let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); routing.invalidate_via(NEIGHBOR); assert_eq!(routing.route_status(DEVICE), Some(Status::Inactive)); @@ -80,14 +84,27 @@ fn test_recent_activity_decays_on_an_inactive_route() { assert_eq!(entry.recent_activity, Activity::new(ROUTER_AGE_LIMIT - 1)); } +#[test] +fn test_new_route_is_not_charged_for_time_before_it_existed() { + // Created a minute in: the minute before must not decay its counter + let created = START + Duration::from_secs(60); + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, created, ACTIVITY); + + routing.decay_activity(created + Duration::from_secs(1), ACTIVITY.period); + + let entry = routing.entries().next().unwrap(); + assert_eq!(entry.recent_activity.count(), ROUTER_AGE_LIMIT - 1); +} + #[test] fn test_forget_drops_the_route_and_the_route_record() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + 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()); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(DEVICE), None); assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE), None); @@ -96,10 +113,10 @@ fn test_forget_drops_the_route_and_the_route_record() { #[test] fn test_forget_leaves_other_destinations_alone() { let mut routing = Routing::default(); - routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); - routing.begin_discovery(OWN, ROUTER, START, ROUTE_DISCOVERY_TIME, ROUTER_AGE_LIMIT); + routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.begin_discovery(OWN, ROUTER, START, ROUTE_DISCOVERY_TIME, ACTIVITY); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(OTHER_DEVICE), Some(NEIGHBOR)); assert_eq!( @@ -121,7 +138,7 @@ fn test_forget_keeps_the_duplicate_check_for_a_request_the_device_originated() { }; assert!(receive(&mut routing, request, START)); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); let late_copy = RouteRequest { path_cost: 7, @@ -140,7 +157,7 @@ fn test_forget_keeps_the_duplicate_check_for_a_request_toward_the_device() { }; assert!(receive(&mut routing, request, START)); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); let late_copy = RouteRequest { path_cost: 7, @@ -161,16 +178,15 @@ fn test_forget_keeps_a_relayed_discovery_toward_the_device_answerable() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!( routing.route_status(DEVICE), Some(Status::DiscoveryUnderway) ); - let reply = - routing.accept_route_reply(OWN, ROUTER, 1, DEVICE, DEVICE, 1, START, ROUTER_AGE_LIMIT); + let reply = routing.accept_route_reply(OWN, ROUTER, 1, DEVICE, DEVICE, 1, START, ACTIVITY); assert_eq!( reply.disposition, RouteReplyDisposition::Relay { @@ -191,10 +207,10 @@ fn test_forget_placeholder_for_a_relayed_discovery_expires_with_it() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.restore_route(DEVICE, OTHER_DEVICE, 3, ROUTER_AGE_LIMIT); - routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); + routing.restore_route(DEVICE, OTHER_DEVICE, 3, START, ACTIVITY); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(DEVICE), None); assert_eq!( routing.route_status(DEVICE), @@ -225,13 +241,13 @@ fn test_relayed_discovery_still_expires_after_its_originator_is_forgotten() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(OTHER_DEVICE, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(OTHER_DEVICE, START, ACTIVITY); assert_eq!( routing.route_status(OTHER_DEVICE), Some(Status::DiscoveryUnderway) ); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); // Any later request runs the expiry let unrelated = RouteRequest { @@ -295,7 +311,7 @@ fn test_unchanged_route_record_reports_a_relay_route_it_restores() { fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { for relays in [vec![], vec![ROUTER]] { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); routing.store_route_record(DEVICE, relays); assert!(routing.forget_route_to(DEVICE)); @@ -306,7 +322,7 @@ fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { #[test] fn test_forget_route_to_reports_only_a_removed_route_record() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); assert!(!routing.forget_route_to(DEVICE)); assert_eq!(routing.next_hop(DEVICE), None); @@ -328,20 +344,13 @@ fn test_forget_route_to_leaves_other_destinations_alone() { /// A frame of ours wants a route to `DEVICE`. Returns whether that starts a discovery. fn want(routing: &mut Routing, now: Instant, attempts: u8) -> bool { routing - .want_route( - OWN, - DEVICE, - now, - ROUTE_DISCOVERY_TIME, - attempts, - ROUTER_AGE_LIMIT, - ) + .want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts, ACTIVITY) .is_some() } /// Run a timer pass, with a frame still waiting for the route or not. fn tick(routing: &mut Routing, now: Instant, wanted: bool) -> DiscoveryTick { - routing.tick_discoveries(OWN, now, ROUTE_DISCOVERY_TIME, ROUTER_AGE_LIMIT, |_| wanted) + routing.tick_discoveries(OWN, now, ROUTE_DISCOVERY_TIME, ACTIVITY, |_| wanted) } #[test] @@ -447,7 +456,7 @@ fn test_relayed_discovery_toward_the_destination_is_not_ours() { path_cost: 3, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); assert!(want(&mut routing, START, 1)); } @@ -478,18 +487,11 @@ fn test_relayed_discovery_does_not_keep_ours_alive() { #[test] fn test_removing_the_route_keeps_a_discovery_underway() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3, ROUTER_AGE_LIMIT); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); assert!(routing.remove_route(DEVICE)); let request_id = routing - .want_route( - OWN, - DEVICE, - START, - ROUTE_DISCOVERY_TIME, - 1, - ROUTER_AGE_LIMIT, - ) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1, ACTIVITY) .unwrap(); assert!(!routing.remove_route(DEVICE)); assert!(!routing.forget_route_to(DEVICE)); @@ -501,29 +503,13 @@ fn test_removing_the_route_keeps_a_discovery_underway() { /// `DEVICE` answers our route request through `NEIGHBOR`. fn reply(routing: &mut Routing, request_id: RouteRequestId, now: Instant) -> RouteReplyOutcome { - routing.accept_route_reply( - OWN, - OWN, - request_id, - DEVICE, - NEIGHBOR, - 3, - now, - ROUTER_AGE_LIMIT, - ) + routing.accept_route_reply(OWN, OWN, request_id, DEVICE, NEIGHBOR, 3, now, ACTIVITY) } /// Start a discovery toward `DEVICE` and have the device answer it. fn answered_discovery(routing: &mut Routing, attempts: u8) { let request_id = routing - .want_route( - OWN, - DEVICE, - START, - ROUTE_DISCOVERY_TIME, - attempts, - ROUTER_AGE_LIMIT, - ) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, attempts, ACTIVITY) .unwrap(); let reply = reply(routing, request_id, START); @@ -560,7 +546,7 @@ fn test_relayed_discovery_does_not_revive_our_answered_one() { path_cost: 3, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); assert_eq!( routing.route_status(DEVICE), Some(Status::DiscoveryUnderway) @@ -574,14 +560,7 @@ fn test_relayed_discovery_does_not_revive_our_answered_one() { fn test_reply_with_the_highest_path_cost_answers_the_discovery() { let mut routing = Routing::default(); let request_id = routing - .want_route( - OWN, - DEVICE, - START, - ROUTE_DISCOVERY_TIME, - 1, - ROUTER_AGE_LIMIT, - ) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1, ACTIVITY) .unwrap(); let reply = routing.accept_route_reply( @@ -592,13 +571,13 @@ fn test_reply_with_the_highest_path_cost_answers_the_discovery() { NEIGHBOR, u8::MAX, START, - ROUTER_AGE_LIMIT, + ACTIVITY, ); assert_eq!(reply.disposition, RouteReplyDisposition::Established); assert_eq!(tick(&mut routing, START, false), DiscoveryTick::default()); routing.invalidate_via(NEIGHBOR); - routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); assert!(want(&mut routing, START, 1)); } @@ -626,7 +605,7 @@ fn test_forget_ends_our_discovery_toward_the_device() { let mut routing = Routing::default(); assert!(want(&mut routing, START, 1)); - routing.forget(OWN, DEVICE, ROUTER_AGE_LIMIT); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_discovery_lapse(OWN, START), None); assert!(want(&mut routing, START, 1)); @@ -638,14 +617,7 @@ fn test_forget_ends_our_discovery_toward_the_device() { fn test_reply_to_a_lapsed_discovery_is_dropped() { let mut routing = Routing::default(); let request_id = routing - .want_route( - OWN, - DEVICE, - START, - ROUTE_DISCOVERY_TIME, - 1, - ROUTER_AGE_LIMIT, - ) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1, ACTIVITY) .unwrap(); let late = reply(&mut routing, request_id, START + ROUTE_DISCOVERY_TIME); @@ -740,14 +712,8 @@ fn check_own_discovery(steps: &[Step], attempts: u8) { // The driver only holds a frame when it has no route Step::Hold if routing.next_hop(DEVICE).is_some() => {} Step::Hold => { - let started = routing.want_route( - OWN, - DEVICE, - now, - ROUTE_DISCOVERY_TIME, - attempts, - ROUTER_AGE_LIMIT, - ); + let started = + routing.want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts, ACTIVITY); // Only the first frame to wait can start a discovery, and a discovery // of ours that is still underway serves it @@ -857,7 +823,7 @@ fn check_own_discovery(steps: &[Step], attempts: u8) { path_cost: 3, }; assert!(receive(&mut routing, request, now), "{steps:?}"); - routing.note_relayed_discovery(DEVICE, ROUTER_AGE_LIMIT); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); model.expire(); model.relayed_live = true; @@ -928,7 +894,7 @@ fn receive_copy(routing: &mut Routing, path_cost: u8) -> RouteRequestOutcome { NwkRouteRequestManyToOne::NotManyToOne, START, ROUTE_DISCOVERY_TIME, - ROUTER_AGE_LIMIT, + ACTIVITY, ) }