Skip to main content

zigbee_core/nwk/nib/
mod.rs

1//! NWK information base
2//!
3//! See Section 3.5.
4use core::mem;
5use core::ops::Deref;
6use core::ops::DerefMut;
7
8use byte::BytesExt;
9use byte::TryRead;
10use byte::TryWrite;
11use heapless::Vec;
12use heapless::index_map::FnvIndexMap;
13use zigbee_macros::construct_ib;
14use zigbee_macros::impl_byte;
15use zigbee_types::ByteArray;
16use zigbee_types::IeeeAddress;
17use zigbee_types::ShortAddress;
18use zigbee_types::StorageVec;
19
20use crate::security::frame::SecurityLevel;
21
22impl_byte! {
23    #[tag(u8)]
24    /// Zigbee device type.
25    #[derive(Debug, Clone)]
26    pub enum DeviceType {
27        /// Zigbee coordinator
28        Coordinator = 0x00,
29        /// Zigbee router
30        Router = 0x01,
31        /// Zigbee end device
32        EndDevice = 0x02,
33        #[fallback = true]
34        Invalid(u8),
35    }
36}
37
38pub const NWK_COORDINATOR_ADDRESS: u16 = 0x0000;
39
40/// Network address of a device that is not joined (3.6.1.10.4).
41pub const NWK_UNASSIGNED_ADDRESS: u16 = 0xffff;
42
43/// Broadcast to all devices (3.6.5, Table 3-68).
44pub const NWK_BROADCAST_ALL: u16 = 0xffff;
45
46/// Lowest reserved broadcast address; anything above is a broadcast (Table
47/// 3-68).
48pub const NWK_BROADCAST_ADDRESS_MIN: u16 = 0xfff8;
49
50/// Neighbor table relationship values (Table 3-63).
51pub mod relationship {
52    /// The neighbor is the parent of this device.
53    pub const PARENT: u8 = 0x00;
54    /// The neighbor is a child of this device.
55    pub const CHILD: u8 = 0x01;
56    /// The neighbor is a sibling.
57    pub const SIBLING: u8 = 0x02;
58    /// No relationship.
59    pub const NONE: u8 = 0x03;
60    /// Previous child (relationship ended).
61    pub const PREVIOUS_CHILD: u8 = 0x04;
62    /// Unauthenticated child.
63    pub const UNAUTHENTICATED_CHILD: u8 = 0x05;
64}
65
66/// See Section 3.5.1.
67const NWKC_COORDINATOR_CAPABLE: bool = true;
68const NWKC_DEFAULT_SECURITY_LEVEL: u8 = 0x00; // defined in stack profile
69const NWKC_MIN_HEADER_OVERHEAD: u8 = 0x08;
70const NWKC_PROTOCOL_VERSION: u8 = 0x02;
71const NWKC_WAIT_BEFORE_VALIDATION: u32 = 0x9c40;
72const NWKC_ROUTE_DISCOVERY_TIME: u32 = 0x4c4b4;
73const NWKC_MAX_BROADCAST_JITTER: u32 = 0x7d0;
74const NWKC_INITIAL_RREQ_RETRIES: u8 = 0x03;
75const NWKC_RREQ_RETRIES: u8 = 0x02;
76const NWKC_RREQ_RETRY_INTERVAL: u32 = 0x1f02;
77const NWKC_MIN_RREQ_JITTER: u32 = 0x3f;
78const NWKC_MAX_RREQ_JITTER: u32 = 0xfa0;
79const NWKC_MAC_FRAME_OVERHEAD: u8 = 0x0b;
80
81// implementation specific
82
83// 1 for end device
84const MAX_NEIGBOUR_TABLE: usize = 16;
85// 0 for end devices
86const MAX_ROUTE_TABLE: usize = 8;
87const MAX_BROADCAST_TRANSACTION_TABLE: usize = 4;
88const MAX_GROUP_ID_TABLE: usize = 4;
89// 0 for end devices
90const MAX_ROUTE_RECORD_TABLE: usize = 8;
91const MAX_NWK_ADDRESS_MAP: usize = 16;
92const MAX_MAC_INTERFACE_TABLE: usize = 1;
93// active plus alternate network key (4.6.3.4.2)
94const MAX_SECURITY_KEYS: usize = 2;
95
96/// Maximum acceptable link cost for parent selection (3.6.1.4.1.1).
97pub const MAX_PARENT_LINK_COST: u8 = 3;
98
99/// Computes the link cost (1-7, lower is better) from an LQI value
100/// (3.6.3.1).
101///
102/// The LQI-to-cost mapping is implementation-defined; this uses a threshold
103/// table suitable for IEEE 802.15.4 2.4 GHz PHY.
104pub fn link_cost_from_lqi(lqi: u8) -> u8 {
105    match lqi {
106        // excellent link (>= -55 dBm)
107        128..=255 => 1,
108        // good link (>= -65 dBm)
109        77..=127 => 2,
110        // acceptable (>= -75 dBm)
111        26..=76 => 3,
112        // marginal
113        11..=25 => 5,
114        // poor
115        1..=10 => 6,
116        // very poor
117        0 => 7,
118    }
119}
120
121construct_ib! {
122    /// Network Information Base.
123    ///
124    /// See Section 3.5.2.
125    #[ids = NibId]
126    #[fields = NibFields]
127    pub struct Nib {
128        /// Sequence number
129        #[setter = update_sequence_number]
130        sequence_number: u8, // random value, read only
131        #[storage_key = 9]
132        #[setter = update_passive_ack_timeout]
133        passive_ack_timeout: u32, // stack profile
134        #[storage_key = 10]
135        #[setter = update_max_broadcast_retries]
136        max_broadcast_retries: u8 = 0x03,
137        #[storage_key = 11]
138        #[setter = update_max_children]
139        max_children: u8, // stack profile
140        #[storage_key = 12]
141        #[setter = update_max_depth]
142        max_depth: u8, // stack profile, read only
143        #[storage_key = 13]
144        #[setter = update_max_routers]
145        max_routers: u8, // stack profile
146        #[storage_key = 8]
147        #[setter = update_neighbor_table]
148        neighbor_table: StorageVec<NwkNeighbor, MAX_NEIGBOUR_TABLE>,
149        #[storage_key = 14]
150        #[setter = update_network_broadcast_delivery_time]
151        network_broadcast_delivery_time: u32, // stack profile
152        #[storage_key = 15]
153        #[setter = update_report_constant_cost]
154        report_constant_cost: u8 = 0x00, // 0x00 - 0x01
155        #[setter = update_route_table]
156        route_table: StorageVec<NwkRoute, MAX_ROUTE_TABLE>,
157        #[ctx = ()]
158        #[ctx_write = ()]
159        #[storage_key = 16]
160        #[setter = update_sym_link]
161        sym_link: bool = false, // bool
162        #[storage_key = 7]
163        #[setter = update_capability_information]
164        capability_information: CapabilityInformation = CapabilityInformation(0x00), // read only
165        #[storage_key = 17]
166        #[setter = update_addr_alloc]
167        addr_alloc: u8 = 0x0, // 0x00 - 0x02
168        #[ctx = ()]
169        #[ctx_write = ()]
170        #[storage_key = 18]
171        #[setter = update_use_tree_routing]
172        use_tree_routing: bool = true,
173        #[storage_key = 19]
174        #[setter = update_manager_addr]
175        manager_addr: u16 = 0x0000, // <= 0xfff7
176        #[storage_key = 20]
177        #[setter = update_max_source_route]
178        max_source_route: u8 = 0x0c,
179        #[storage_key = 4]
180        #[setter = update_update_id]
181        update_id: u8 = 0x00,
182        #[storage_key = 21]
183        #[setter = update_transaction_persistence_time]
184        transaction_persistence_time: u16 = 0x01f4,
185        #[storage_key = 1]
186        #[setter = update_network_address]
187        network_address: u16 = 0xffff, //  <= 0xfff7
188        #[storage_key = 22]
189        #[setter = update_stack_profile]
190        stack_profile: u8, // <= 0x0f
191        #[setter = update_broadcast_transaction_table]
192        broadcast_transaction_table: StorageVec<TransactionRecord, MAX_BROADCAST_TRANSACTION_TABLE>,
193        #[storage_key = 23]
194        #[setter = update_group_idtable]
195        group_idtable: StorageVec<u16, MAX_GROUP_ID_TABLE>,
196        #[storage_key = 3]
197        #[setter = update_extended_panid]
198        extended_panid: u64 = 0x0000_0000_0000_0000, // <= 0xffff_ffff_ffff_fffe
199        #[ctx = ()]
200        #[ctx_write = ()]
201        #[storage_key = 24]
202        #[setter = update_use_multicast]
203        use_multicast: bool = true,
204        #[setter = update_route_record_table]
205        route_record_table: StorageVec<RouteRecord, MAX_ROUTE_RECORD_TABLE>,
206        #[ctx = ()]
207        #[ctx_write = ()]
208        #[storage_key = 25]
209        #[setter = update_is_concentrator]
210        is_concentrator: bool = false,
211        #[storage_key = 26]
212        #[setter = update_concentrator_radius]
213        concentrator_radius: u8 = 0x00,
214        #[storage_key = 27]
215        #[setter = update_concentrator_discovery_time]
216        concentrator_discovery_time: u8 = 0x00,
217        // nib security attributes
218        #[storage_key = 28]
219        #[setter = update_security_level]
220        security_level: SecurityLevel = SecurityLevel::EncMic32,
221        #[storage_key = 6]
222        #[setter = update_security_material_set]
223        security_material_set: StorageVec<NetworkSecurityMaterialDescriptor, MAX_SECURITY_KEYS>,
224        #[storage_key = 5]
225        #[setter = update_active_key_seq_number]
226        active_key_seq_number: u8 = 0x00,
227        #[ctx = ()]
228        #[ctx_write = ()]
229        #[storage_key = 29]
230        #[setter = update_all_fresh]
231        all_fresh: bool = true,
232
233        #[storage_key = 30]
234        #[setter = update_link_status_period]
235        link_status_period: u8 = 0x0f,
236        #[storage_key = 31]
237        #[setter = update_router_age_limit]
238        router_age_limit: u8 = 0x03,
239        #[ctx = ()]
240        #[ctx_write = ()]
241        #[storage_key = 32]
242        #[setter = update_unique_addr]
243        unique_addr: bool = true,
244        #[storage_key = 33]
245        #[setter = update_address_map]
246        address_map: StorageVec<AddressMap, MAX_NWK_ADDRESS_MAP>,
247        #[ctx = ()]
248        #[ctx_write = ()]
249        #[storage_key = 34]
250        #[setter = update_time_stamp]
251        time_stamp: bool = false,
252        #[storage_key = 2]
253        #[setter = update_panid]
254        panid: u16 = 0xffff,
255        #[setter = update_tx_total]
256        tx_total: u16 = 0x0000,
257        #[ctx = ()]
258        #[ctx_write = ()]
259        #[storage_key = 35]
260        #[setter = update_leave_request_allowed]
261        leave_request_allowed: bool = true,
262        #[storage_key = 36]
263        #[setter = update_parent_information]
264        parent_information: u8 = 0x00,
265        #[storage_key = 37]
266        #[setter = update_end_device_timeout_default]
267        end_device_timeout_default: u8 = 0x08,
268        // negotiated timeout enumeration (3.6.10.2); 0xff = not negotiated
269        #[storage_key = 39]
270        #[setter = update_end_device_timeout]
271        end_device_timeout: u8 = 0xff,
272        #[ctx = ()]
273        #[ctx_write = ()]
274        #[storage_key = 38]
275        #[setter = update_leave_request_without_rejoin_allowed]
276        leave_request_without_rejoin_allowed: bool = true,
277        #[setter = update_ieee_address]
278        ieee_address: IeeeAddress, // read only
279        // TODO: mac_interface_table (StorageVec<MacInterface, MAX_MAC_INTERFACE_TABLE>) not yet implemented
280    }
281}
282
283impl_byte! {
284    #[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
285    pub struct CapabilityInformation(pub u8);
286}
287
288impl CapabilityInformation {
289    /// Bit 0 — Alternate PAN coordinator (always 0 in Zigbee).
290    pub fn alternate_pan_coordinator(&self) -> bool {
291        self.0 & (1 << 0) != 0
292    }
293
294    /// Bit 1 — Device type: 1 = router (FFD), 0 = end device (RFD).
295    pub fn device_type(&self) -> bool {
296        self.0 & (1 << 1) != 0
297    }
298
299    /// Bit 2 — Power source: 1 = mains-powered, 0 = other.
300    pub fn power_source(&self) -> bool {
301        self.0 & (1 << 2) != 0
302    }
303
304    /// Bit 3 — Receiver on when idle.
305    pub fn receiver_on_when_idle(&self) -> bool {
306        self.0 & (1 << 3) != 0
307    }
308
309    /// Bit 6 — Security capability (always 0 in Zigbee).
310    pub fn security_capability(&self) -> bool {
311        self.0 & (1 << 6) != 0
312    }
313
314    /// Bit 7 — Allocate address: 1 = coordinator should allocate a short
315    /// address.
316    pub fn allocate_address(&self) -> bool {
317        self.0 & (1 << 7) != 0
318    }
319}
320
321impl_byte! {
322    #[derive(Debug, Clone)]
323    pub struct NwkNeighbor {
324        /// IEEE address of the neighbor, learned from received frames that
325        /// carry it; `IeeeAddress(0)` while unknown.
326        pub extended_address: IeeeAddress,
327        pub network_address: ShortAddress,
328        pub device_type: DeviceType,
329        #[ctx = ()]
330        pub rx_on_when_idle: bool,
331        pub end_device_configuration: u16,
332        pub relationship: u8,
333        pub transmit_failure: u8,
334        pub lqi: u8,
335        pub outgoing_cost: u8,
336        pub age: u8,
337        #[ctx = ()]
338        pub keepalive_received: bool,
339        // mac_interface_index omitted: only one mac interface is supported
340
341        // table 3-64: optional discovery-time fields, cleared after joining
342
343        /// Extended PAN identifier of the network the neighbor belongs to.
344        pub extended_pan_id: IeeeAddress,
345        /// The logical channel on which the neighbor is operating.
346        pub logical_channel: u8,
347        /// The tree depth of the neighbor device.
348        pub depth: u8,
349        /// Whether the neighbor is accepting join requests.
350        #[ctx = ()]
351        pub permit_joining: bool,
352        /// 0x00 = not a potential parent, 0x01 = potential parent.
353        pub potential_parent: u8,
354        /// Whether the neighbor can accept router-capable children.
355        #[ctx = ()]
356        pub router_capacity: bool,
357        /// Whether the neighbor can accept end-device children.
358        #[ctx = ()]
359        pub end_device_capacity: bool,
360        /// The nwkUpdateId from the beacon payload.
361        pub update_id: u8,
362        /// The 16-bit PAN identifier.
363        pub pan_id: u16,
364    }
365}
366
367/// See Table 3-67.
368#[derive(Debug, Clone)]
369#[repr(u8)]
370pub(crate) enum RouteStatus {
371    Active,
372    DiscoveryUnderway,
373    DiscoveryFailed,
374    Inactive,
375    ValidationUnderway,
376    Reserved,
377}
378
379impl_byte! {
380    /// See Table 3-66.
381    #[derive(Debug, Clone)]
382    pub struct NwkRoute {
383        pub destination_address: ShortAddress,
384        pub next_hop_address: ShortAddress,
385        status: u8,
386    }
387}
388
389impl NwkRoute {
390    pub(crate) fn status(&self) -> RouteStatus {
391        let status = self.status & 0b111;
392        if status > 0x4 {
393            RouteStatus::Reserved
394        } else {
395            // SAFETY: any status <= 0x4 is a valid RouteStatus
396            unsafe { mem::transmute::<u8, RouteStatus>(status) }
397        }
398    }
399
400    /// A flag indicating that the destination indicated by this address does
401    /// not store source routes.
402    pub(crate) fn no_route_cache(&self) -> bool {
403        (self.status >> 3) & 0b1 != 0
404    }
405
406    /// A flag indicating that the destination is a concentrator that issued a
407    /// many-to-one route request.
408    pub(crate) fn many_to_one(&self) -> bool {
409        (self.status >> 4) & 0b1 != 0
410    }
411
412    /// A flag indicating that a route record command frame should be sent to
413    /// the destination prior to the next data packet.
414    pub(crate) fn route_record_required(&self) -> bool {
415        (self.status >> 5) & 0b1 != 0
416    }
417
418    /// A flag indicating that the destination address is a Group ID.
419    pub(crate) fn group_id(&self) -> bool {
420        (self.status >> 6) & 0b1 != 0
421    }
422}
423
424impl_byte! {
425    /// See Table 3-70.
426    #[derive(Debug, Clone)]
427    pub struct TransactionRecord {
428        pub source_address: ShortAddress,
429        pub sequence_number: u8,
430        pub expiration_time: u8,
431    }
432}
433
434impl_byte! {
435    /// See Table 3-59.
436    #[derive(Debug, Clone)]
437    pub struct RouteRecord {
438        pub network_address: ShortAddress,
439        pub relay_count: u16,
440        pub path: StorageVec<ShortAddress, 16>,
441    }
442}
443
444impl_byte! {
445    #[derive(Debug, Clone)]
446    pub struct AddressMap {
447        pub ieee_address: IeeeAddress,
448        pub network_address: ShortAddress,
449    }
450}
451
452/// See Table 3-61.
453#[derive(Debug, Clone)]
454pub(crate) struct MacInterface {}
455
456impl_byte! {
457    /// See Table 4-3.
458    #[derive(Debug, Clone)]
459    pub struct NetworkSecurityMaterialDescriptor {
460        pub key_seq_number: u8,
461        pub outgoing_frame_counter: u32,
462        pub incoming_frame_counter_set: StorageVec<IncomingFrameCounterDescriptor, MAX_NEIGBOUR_TABLE>,
463        pub key: ByteArray<16>,
464        pub network_key_type: u8,
465    }
466}
467
468impl_byte! {
469    /// See Table 4-4.
470    #[derive(Debug, Clone)]
471    pub struct IncomingFrameCounterDescriptor {
472        pub sender_address: IeeeAddress,
473        pub incoming_frame_counter: u32,
474    }
475}
476
477/// Flash persistence of the NIB.
478#[cfg(feature = "storage")]
479pub(crate) mod storage;
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    #[test]
486    fn nib_set_vec() {
487        let nib = Nib::new();
488
489        let mut set = StorageVec::<NetworkSecurityMaterialDescriptor, MAX_SECURITY_KEYS>::new();
490        set.push(NetworkSecurityMaterialDescriptor {
491            key_seq_number: 0,
492            outgoing_frame_counter: 0,
493            incoming_frame_counter_set: StorageVec(Vec::new()),
494            key: ByteArray([0u8; 16]),
495            network_key_type: 0,
496        })
497        .unwrap();
498        nib.update_security_material_set(|value| *value = set);
499        assert_eq!(nib.security_material_set().len(), 1);
500    }
501
502    #[test]
503    fn nib_default() {
504        // local instance: the global singleton is shared with (and mutated
505        // by) other tests running in parallel
506        let nib = Nib::new();
507
508        assert_eq!(*nib.max_broadcast_retries(), 0x03);
509        assert_eq!(*nib.report_constant_cost(), 0x00);
510        assert!(!*nib.sym_link());
511        assert_eq!(*nib.capability_information(), CapabilityInformation(0x00));
512        assert_eq!(*nib.addr_alloc(), 0x0);
513        assert!(*nib.use_tree_routing());
514        assert_eq!(*nib.manager_addr(), 0x0000);
515        assert_eq!(*nib.max_source_route(), 0x0c);
516        assert_eq!(*nib.update_id(), 0x00);
517        assert_eq!(*nib.transaction_persistence_time(), 0x01f4);
518        assert_eq!(*nib.network_address(), 0xffff);
519        assert_eq!(*nib.extended_panid(), 0x0000_0000_0000_0000);
520        assert!(*nib.use_multicast());
521        assert!(!*nib.is_concentrator());
522        assert_eq!(*nib.concentrator_radius(), 0x00);
523        assert_eq!(*nib.concentrator_discovery_time(), 0x00);
524        assert_eq!(*nib.link_status_period(), 0x0f);
525        assert_eq!(*nib.router_age_limit(), 0x03);
526        assert!(*nib.unique_addr());
527        assert!(!*nib.time_stamp());
528        assert_eq!(*nib.panid(), 0xffff);
529        assert_eq!(*nib.tx_total(), 0x0000);
530        assert!(*nib.leave_request_allowed());
531        assert_eq!(*nib.parent_information(), 0x00);
532        assert_eq!(*nib.end_device_timeout_default(), 0x08);
533        assert!(*nib.leave_request_without_rejoin_allowed());
534    }
535
536    #[test]
537    fn storage_vec() {
538        let mut vec = StorageVec::<u8, 3>::new();
539        vec.push(1).unwrap();
540        vec.push(2).unwrap();
541        vec.push(3).unwrap();
542
543        let mut buf = [0u8; 5];
544        vec.try_write(&mut buf, byte::LE).unwrap();
545        assert_eq!(buf, [0x03, 0x00, 0x01, 0x02, 0x03]);
546
547        let (vec2, _) = StorageVec::<u8, 3>::try_read(&buf, byte::LE).unwrap();
548        assert_eq!(vec2.len(), 3);
549        assert_eq!(vec2[0], 1);
550        assert_eq!(vec2[1], 2);
551        assert_eq!(vec2[2], 3);
552    }
553}