1use 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 #[derive(Debug, Clone)]
26 pub enum DeviceType {
27 Coordinator = 0x00,
29 Router = 0x01,
31 EndDevice = 0x02,
33 #[fallback = true]
34 Invalid(u8),
35 }
36}
37
38pub const NWK_COORDINATOR_ADDRESS: u16 = 0x0000;
39
40pub const NWK_UNASSIGNED_ADDRESS: u16 = 0xffff;
42
43pub const NWK_BROADCAST_ALL: u16 = 0xffff;
45
46pub const NWK_BROADCAST_ADDRESS_MIN: u16 = 0xfff8;
49
50pub mod relationship {
52 pub const PARENT: u8 = 0x00;
54 pub const CHILD: u8 = 0x01;
56 pub const SIBLING: u8 = 0x02;
58 pub const NONE: u8 = 0x03;
60 pub const PREVIOUS_CHILD: u8 = 0x04;
62 pub const UNAUTHENTICATED_CHILD: u8 = 0x05;
64}
65
66const NWKC_COORDINATOR_CAPABLE: bool = true;
68const NWKC_DEFAULT_SECURITY_LEVEL: u8 = 0x00; const 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
81const MAX_NEIGBOUR_TABLE: usize = 16;
85const MAX_ROUTE_TABLE: usize = 8;
87const MAX_BROADCAST_TRANSACTION_TABLE: usize = 4;
88const MAX_GROUP_ID_TABLE: usize = 4;
89const MAX_ROUTE_RECORD_TABLE: usize = 8;
91const MAX_NWK_ADDRESS_MAP: usize = 16;
92const MAX_MAC_INTERFACE_TABLE: usize = 1;
93const MAX_SECURITY_KEYS: usize = 2;
95
96pub const MAX_PARENT_LINK_COST: u8 = 3;
98
99pub fn link_cost_from_lqi(lqi: u8) -> u8 {
105 match lqi {
106 128..=255 => 1,
108 77..=127 => 2,
110 26..=76 => 3,
112 11..=25 => 5,
114 1..=10 => 6,
116 0 => 7,
118 }
119}
120
121construct_ib! {
122 #[ids = NibId]
126 #[fields = NibFields]
127 pub struct Nib {
128 #[setter = update_sequence_number]
130 sequence_number: u8, #[storage_key = 9]
132 #[setter = update_passive_ack_timeout]
133 passive_ack_timeout: u32, #[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, #[storage_key = 12]
141 #[setter = update_max_depth]
142 max_depth: u8, #[storage_key = 13]
144 #[setter = update_max_routers]
145 max_routers: u8, #[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, #[storage_key = 15]
153 #[setter = update_report_constant_cost]
154 report_constant_cost: u8 = 0x00, #[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, #[storage_key = 7]
163 #[setter = update_capability_information]
164 capability_information: CapabilityInformation = CapabilityInformation(0x00), #[storage_key = 17]
166 #[setter = update_addr_alloc]
167 addr_alloc: u8 = 0x0, #[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, #[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, #[storage_key = 22]
189 #[setter = update_stack_profile]
190 stack_profile: u8, #[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, #[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 #[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 #[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, }
281}
282
283impl_byte! {
284 #[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
285 pub struct CapabilityInformation(pub u8);
286}
287
288impl CapabilityInformation {
289 pub fn alternate_pan_coordinator(&self) -> bool {
291 self.0 & (1 << 0) != 0
292 }
293
294 pub fn device_type(&self) -> bool {
296 self.0 & (1 << 1) != 0
297 }
298
299 pub fn power_source(&self) -> bool {
301 self.0 & (1 << 2) != 0
302 }
303
304 pub fn receiver_on_when_idle(&self) -> bool {
306 self.0 & (1 << 3) != 0
307 }
308
309 pub fn security_capability(&self) -> bool {
311 self.0 & (1 << 6) != 0
312 }
313
314 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 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 pub extended_pan_id: IeeeAddress,
345 pub logical_channel: u8,
347 pub depth: u8,
349 #[ctx = ()]
351 pub permit_joining: bool,
352 pub potential_parent: u8,
354 #[ctx = ()]
356 pub router_capacity: bool,
357 #[ctx = ()]
359 pub end_device_capacity: bool,
360 pub update_id: u8,
362 pub pan_id: u16,
364 }
365}
366
367#[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 #[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 unsafe { mem::transmute::<u8, RouteStatus>(status) }
397 }
398 }
399
400 pub(crate) fn no_route_cache(&self) -> bool {
403 (self.status >> 3) & 0b1 != 0
404 }
405
406 pub(crate) fn many_to_one(&self) -> bool {
409 (self.status >> 4) & 0b1 != 0
410 }
411
412 pub(crate) fn route_record_required(&self) -> bool {
415 (self.status >> 5) & 0b1 != 0
416 }
417
418 pub(crate) fn group_id(&self) -> bool {
420 (self.status >> 6) & 0b1 != 0
421 }
422}
423
424impl_byte! {
425 #[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 #[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#[derive(Debug, Clone)]
454pub(crate) struct MacInterface {}
455
456impl_byte! {
457 #[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 #[derive(Debug, Clone)]
471 pub struct IncomingFrameCounterDescriptor {
472 pub sender_address: IeeeAddress,
473 pub incoming_frame_counter: u32,
474 }
475}
476
477#[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 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}