diff --git a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 5f791582..046d840f 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -109,7 +109,7 @@ impl ZigbeeStack { // We are the coordinator (tree depth 0), so every neighbor of // ours sits at depth 1 depth: 1, - lqa: entry.lqa().unwrap_or(0), + lqa: entry.lqas.median().unwrap_or(0), }) .collect(); diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index 631e8f29..e7e8ab40 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -25,6 +25,33 @@ const PENDING_LQA_CAP: usize = 64; /// a heap buffer per neighbor would fragment a small arena. pub type LqaSamples = RingBuffer; +impl LqaSamples { + /// Spec 3.6.3: the link quality is the median of the samples held. A window that + /// is not full yet still counts, down to a single sample. `None` when there is no + /// sample. + pub fn median(&self) -> Option { + let samples = self.values(); + + if samples.is_empty() { + return None; + } + + let mut sorted = [0; LINK_QUALITY_SAMPLES]; + let sorted = &mut sorted[..samples.len()]; + sorted.copy_from_slice(samples); + sorted.sort_unstable(); + + let middle = sorted.len() / 2; + + if sorted.len() % 2 == 1 { + Some(sorted[middle]) + } else { + // Average of the two middle elements for an even sample count + Some(((sorted[middle - 1] as u16 + sorted[middle] as u16) / 2) as u8) + } + } +} + /// Compute the link cost (1-7) based on the LQI (0-255). const fn lqi_to_link_cost(lqi: u8) -> u8 { match lqi { @@ -105,28 +132,8 @@ pub struct TableEntry { } impl TableEntry { - pub fn lqa(&self) -> Option { - if !self.lqas.is_full() { - return None; - } - - let mut sorted = [0; LINK_QUALITY_SAMPLES]; - sorted.copy_from_slice(self.lqas.values()); - sorted.sort_unstable(); - - // The median of the sample window - if LINK_QUALITY_SAMPLES % 2 == 1 { - Some(sorted[LINK_QUALITY_SAMPLES / 2]) - } else { - // Average of the two middle elements for an even sample count - let mid1 = sorted[LINK_QUALITY_SAMPLES / 2 - 1]; - let mid2 = sorted[LINK_QUALITY_SAMPLES / 2]; - Some(((mid1 as u16 + mid2 as u16) / 2) as u8) - } - } - pub fn incoming_link_cost(&self) -> u8 { - self.lqa().map_or(0, lqi_to_link_cost) + self.lqas.median().map_or(0, lqi_to_link_cost) } pub const fn is_child(&self) -> bool { @@ -694,9 +701,8 @@ impl Neighbors { // sleepy end devices that cannot be routed through. .filter(|neighbor| neighbor.device_type == NwkDeviceType::Router) .filter_map(|neighbor| { - // We only calculate link statuses for neighbors for which we have - // seen more than a few packets - neighbor.lqa().map(|lqa| NwkLinkStatus { + // 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, @@ -816,7 +822,25 @@ impl Neighbors { if link_status_cmd.is_first_frame { neighbor_entry.router_connectivity = 0; neighbor_entry.router_neighbor_set_diversity = 0; - neighbor_entry.outgoing_cost = 0; // If we do not find it in the list, it is 0 + } + + // The list is sorted by address. A frame says nothing about us if our address + // is outside its range, or if its list is empty. + if let (Some(first), Some(last)) = ( + link_status_cmd.link_statuses.first(), + link_status_cmd.link_statuses.last(), + ) { + let own = own_address.as_u16(); + let covers_us = (link_status_cmd.is_first_frame || first.address.as_u16() <= own) + && (link_status_cmd.is_last_frame || own <= last.address.as_u16()); + + if covers_us { + neighbor_entry.outgoing_cost = link_status_cmd + .link_statuses + .iter() + .find(|link_status| link_status.address == own_address) + .map_or(0, |link_status| link_status.incoming_cost); + } } for link_status in link_status_cmd.link_statuses.iter() { @@ -834,10 +858,6 @@ impl Neighbors { .saturating_add(connectivity); } } - - if link_status.address == own_address { - neighbor_entry.outgoing_cost = link_status.incoming_cost; - } } if link_status_cmd.link_statuses.is_empty() { @@ -985,6 +1005,160 @@ mod test { assert_eq!(outcome, LinkStatusOutcome::default()); } + #[test] + fn test_empty_link_status_keeps_outgoing_cost() { + let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); + let (own, router_nwk) = (Nwk(0x0000), Nwk(0x1111)); + let mut neighbors = Neighbors::default(); + + let listing = link_status_listing(own); + neighbors.on_link_status( + own, + router, + router_nwk, + 200, + &listing, + Instant::from_micros(0), + ); + + let empty = NwkLinkStatusCommand { + is_first_frame: true, + is_last_frame: true, + link_statuses: vec![], + }; + let later = Instant::from_micros(1); + let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, later); + + assert_eq!(outcome, LinkStatusOutcome::default()); + assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 1); + } + + #[test] + fn test_link_status_leaving_us_out_zeroes_outgoing_cost() { + 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 mut neighbors = Neighbors::default(); + + let listing = link_status_listing(own); + neighbors.on_link_status(own, router, router_nwk, 200, &listing, now); + + let without_us = link_status_listing(Nwk(0x2222)); + let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &without_us, now); + + assert_eq!( + outcome, + LinkStatusOutcome { + lost_link: Some(router_nwk), + replaced_address: None, + } + ); + assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 0); + } + + fn link_status_frame( + is_first_frame: bool, + is_last_frame: bool, + addresses: &[u16], + ) -> NwkLinkStatusCommand { + NwkLinkStatusCommand { + is_first_frame, + is_last_frame, + link_statuses: addresses + .iter() + .map(|&address| NwkLinkStatus { + address: Nwk(address), + incoming_cost: 3, + outgoing_cost: 3, + }) + .collect(), + } + } + + /// Our outgoing cost to a router that listed us at cost 1, after it sends `frame`. + fn outgoing_cost_after(own: Nwk, frame: &NwkLinkStatusCommand) -> u8 { + let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); + let router_nwk = Nwk(0x1111); + let now = Instant::from_micros(0); + 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.link(router_nwk).unwrap().outgoing_cost + } + + #[test] + fn test_link_status_frame_not_covering_us_keeps_outgoing_cost() { + let own = Nwk(0x3000); + + // We sort after the last entry and more frames follow + let first_of_many = link_status_frame(true, false, &[0x1000, 0x2000]); + assert_eq!(outgoing_cost_after(own, &first_of_many), 1); + + // We sort before the first entry and frames came before + let last_of_many = link_status_frame(false, true, &[0x4000, 0x5000]); + assert_eq!(outgoing_cost_after(own, &last_of_many), 1); + + let middle_of_many = link_status_frame(false, false, &[0x4000, 0x5000]); + assert_eq!(outgoing_cost_after(own, &middle_of_many), 1); + } + + #[test] + fn test_link_status_frame_covering_us_sets_outgoing_cost() { + let own = Nwk(0x3000); + + // Between the first and the last entry + let middle_of_many = link_status_frame(false, false, &[0x2000, 0x4000]); + assert_eq!(outgoing_cost_after(own, &middle_of_many), 0); + + // Below the first entry of the first frame + let first_of_many = link_status_frame(true, false, &[0x4000, 0x5000]); + assert_eq!(outgoing_cost_after(own, &first_of_many), 0); + + // Above the last entry of the last frame + let last_of_many = link_status_frame(false, true, &[0x1000, 0x2000]); + assert_eq!(outgoing_cost_after(own, &last_of_many), 0); + + // Listed as the entry two frames share + let listed = link_status_frame(false, false, &[0x3000, 0x4000]); + assert_eq!(outgoing_cost_after(own, &listed), 3); + } + + #[test] + fn test_link_cost_uses_the_samples_held() { + 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 link_status = link_status_listing(own); + let mut neighbors = Neighbors::default(); + + let incoming_cost = + |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); + assert_eq!(incoming_cost(&neighbors), lqi_to_link_cost(200)); + assert_eq!(neighbors.link_status_entries().len(), 1); + + // Two samples: their average + neighbors.record_lqa(router_nwk, 40); + assert_eq!(incoming_cost(&neighbors), lqi_to_link_cost(120)); + + // Three samples: the median + neighbors.record_lqa(router_nwk, 40); + assert_eq!(incoming_cost(&neighbors), lqi_to_link_cost(40)); + } + + #[test] + fn test_restored_child_without_samples_has_no_link_cost() { + let neighbors = neighbors_with(NwkDeviceType::Router); + + assert_eq!(neighbors.link(CHILD_NWK).unwrap().incoming_cost, 0); + assert!(neighbors.link_status_entries().is_empty()); + } + #[test] fn test_link_status_keeps_address_another_neighbor_holds() { let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11");