use core::mem;
use core::ops::Deref;
use core::ops::DerefMut;
use byte::BytesExt;
use byte::TryRead;
use byte::TryWrite;
use heapless::Vec;
use heapless::index_map::FnvIndexMap;
use zigbee_macros::construct_ib;
use zigbee_macros::impl_byte;
use zigbee_types::ByteArray;
use zigbee_types::IeeeAddress;
use zigbee_types::ShortAddress;
use zigbee_types::StorageVec;
use crate::security::frame::SecurityLevel;
impl_byte! {
#[tag(u8)]
#[derive(Debug, Clone)]
pub enum DeviceType {
Coordinator = 0x00,
Router = 0x01,
EndDevice = 0x02,
#[fallback = true]
Invalid(u8),
}
}
pub const NWK_COORDINATOR_ADDRESS: u16 = 0x0000;
pub const NWK_UNASSIGNED_ADDRESS: u16 = 0xffff;
pub const NWK_BROADCAST_ALL: u16 = 0xffff;
pub const NWK_BROADCAST_ADDRESS_MIN: u16 = 0xfff8;
pub mod relationship {
pub const PARENT: u8 = 0x00;
pub const CHILD: u8 = 0x01;
pub const SIBLING: u8 = 0x02;
pub const NONE: u8 = 0x03;
pub const PREVIOUS_CHILD: u8 = 0x04;
pub const UNAUTHENTICATED_CHILD: u8 = 0x05;
}
const NWKC_COORDINATOR_CAPABLE: bool = true;
const NWKC_DEFAULT_SECURITY_LEVEL: u8 = 0x00; const NWKC_MIN_HEADER_OVERHEAD: u8 = 0x08;
const NWKC_PROTOCOL_VERSION: u8 = 0x02;
const NWKC_WAIT_BEFORE_VALIDATION: u32 = 0x9c40;
const NWKC_ROUTE_DISCOVERY_TIME: u32 = 0x4c4b4;
const NWKC_MAX_BROADCAST_JITTER: u32 = 0x7d0;
const NWKC_INITIAL_RREQ_RETRIES: u8 = 0x03;
const NWKC_RREQ_RETRIES: u8 = 0x02;
const NWKC_RREQ_RETRY_INTERVAL: u32 = 0x1f02;
const NWKC_MIN_RREQ_JITTER: u32 = 0x3f;
const NWKC_MAX_RREQ_JITTER: u32 = 0xfa0;
const NWKC_MAC_FRAME_OVERHEAD: u8 = 0x0b;
const MAX_NEIGBOUR_TABLE: usize = 16;
const MAX_ROUTE_TABLE: usize = 8;
const MAX_BROADCAST_TRANSACTION_TABLE: usize = 4;
const MAX_GROUP_ID_TABLE: usize = 4;
const MAX_ROUTE_RECORD_TABLE: usize = 8;
const MAX_NWK_ADDRESS_MAP: usize = 16;
const MAX_MAC_INTERFACE_TABLE: usize = 1;
const MAX_SECURITY_KEYS: usize = 2;
pub const MAX_PARENT_LINK_COST: u8 = 3;
pub fn link_cost_from_lqi(lqi: u8) -> u8 {
match lqi {
128..=255 => 1,
77..=127 => 2,
26..=76 => 3,
11..=25 => 5,
1..=10 => 6,
0 => 7,
}
}
construct_ib! {
#[ids = NibId]
#[fields = NibFields]
pub struct Nib {
#[setter = update_sequence_number]
sequence_number: u8, #[storage_key = 9]
#[setter = update_passive_ack_timeout]
passive_ack_timeout: u32, #[storage_key = 10]
#[setter = update_max_broadcast_retries]
max_broadcast_retries: u8 = 0x03,
#[storage_key = 11]
#[setter = update_max_children]
max_children: u8, #[storage_key = 12]
#[setter = update_max_depth]
max_depth: u8, #[storage_key = 13]
#[setter = update_max_routers]
max_routers: u8, #[storage_key = 8]
#[setter = update_neighbor_table]
neighbor_table: StorageVec<NwkNeighbor, MAX_NEIGBOUR_TABLE>,
#[storage_key = 14]
#[setter = update_network_broadcast_delivery_time]
network_broadcast_delivery_time: u32, #[storage_key = 15]
#[setter = update_report_constant_cost]
report_constant_cost: u8 = 0x00, #[setter = update_route_table]
route_table: StorageVec<NwkRoute, MAX_ROUTE_TABLE>,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 16]
#[setter = update_sym_link]
sym_link: bool = false, #[storage_key = 7]
#[setter = update_capability_information]
capability_information: CapabilityInformation = CapabilityInformation(0x00), #[storage_key = 17]
#[setter = update_addr_alloc]
addr_alloc: u8 = 0x0, #[ctx = ()]
#[ctx_write = ()]
#[storage_key = 18]
#[setter = update_use_tree_routing]
use_tree_routing: bool = true,
#[storage_key = 19]
#[setter = update_manager_addr]
manager_addr: u16 = 0x0000, #[storage_key = 20]
#[setter = update_max_source_route]
max_source_route: u8 = 0x0c,
#[storage_key = 4]
#[setter = update_update_id]
update_id: u8 = 0x00,
#[storage_key = 21]
#[setter = update_transaction_persistence_time]
transaction_persistence_time: u16 = 0x01f4,
#[storage_key = 1]
#[setter = update_network_address]
network_address: u16 = 0xffff, #[storage_key = 22]
#[setter = update_stack_profile]
stack_profile: u8, #[setter = update_broadcast_transaction_table]
broadcast_transaction_table: StorageVec<TransactionRecord, MAX_BROADCAST_TRANSACTION_TABLE>,
#[storage_key = 23]
#[setter = update_group_idtable]
group_idtable: StorageVec<u16, MAX_GROUP_ID_TABLE>,
#[storage_key = 3]
#[setter = update_extended_panid]
extended_panid: u64 = 0x0000_0000_0000_0000, #[ctx = ()]
#[ctx_write = ()]
#[storage_key = 24]
#[setter = update_use_multicast]
use_multicast: bool = true,
#[setter = update_route_record_table]
route_record_table: StorageVec<RouteRecord, MAX_ROUTE_RECORD_TABLE>,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 25]
#[setter = update_is_concentrator]
is_concentrator: bool = false,
#[storage_key = 26]
#[setter = update_concentrator_radius]
concentrator_radius: u8 = 0x00,
#[storage_key = 27]
#[setter = update_concentrator_discovery_time]
concentrator_discovery_time: u8 = 0x00,
#[storage_key = 28]
#[setter = update_security_level]
security_level: SecurityLevel = SecurityLevel::EncMic32,
#[storage_key = 6]
#[setter = update_security_material_set]
security_material_set: StorageVec<NetworkSecurityMaterialDescriptor, MAX_SECURITY_KEYS>,
#[storage_key = 5]
#[setter = update_active_key_seq_number]
active_key_seq_number: u8 = 0x00,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 29]
#[setter = update_all_fresh]
all_fresh: bool = true,
#[storage_key = 30]
#[setter = update_link_status_period]
link_status_period: u8 = 0x0f,
#[storage_key = 31]
#[setter = update_router_age_limit]
router_age_limit: u8 = 0x03,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 32]
#[setter = update_unique_addr]
unique_addr: bool = true,
#[storage_key = 33]
#[setter = update_address_map]
address_map: StorageVec<AddressMap, MAX_NWK_ADDRESS_MAP>,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 34]
#[setter = update_time_stamp]
time_stamp: bool = false,
#[storage_key = 2]
#[setter = update_panid]
panid: u16 = 0xffff,
#[setter = update_tx_total]
tx_total: u16 = 0x0000,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 35]
#[setter = update_leave_request_allowed]
leave_request_allowed: bool = true,
#[storage_key = 36]
#[setter = update_parent_information]
parent_information: u8 = 0x00,
#[storage_key = 37]
#[setter = update_end_device_timeout_default]
end_device_timeout_default: u8 = 0x08,
#[storage_key = 39]
#[setter = update_end_device_timeout]
end_device_timeout: u8 = 0xff,
#[ctx = ()]
#[ctx_write = ()]
#[storage_key = 38]
#[setter = update_leave_request_without_rejoin_allowed]
leave_request_without_rejoin_allowed: bool = true,
#[setter = update_ieee_address]
ieee_address: IeeeAddress, }
}
impl_byte! {
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub struct CapabilityInformation(pub u8);
}
impl CapabilityInformation {
pub fn alternate_pan_coordinator(&self) -> bool {
self.0 & (1 << 0) != 0
}
pub fn device_type(&self) -> bool {
self.0 & (1 << 1) != 0
}
pub fn power_source(&self) -> bool {
self.0 & (1 << 2) != 0
}
pub fn receiver_on_when_idle(&self) -> bool {
self.0 & (1 << 3) != 0
}
pub fn security_capability(&self) -> bool {
self.0 & (1 << 6) != 0
}
pub fn allocate_address(&self) -> bool {
self.0 & (1 << 7) != 0
}
}
impl_byte! {
#[derive(Debug, Clone)]
pub struct NwkNeighbor {
pub extended_address: IeeeAddress,
pub network_address: ShortAddress,
pub device_type: DeviceType,
#[ctx = ()]
pub rx_on_when_idle: bool,
pub end_device_configuration: u16,
pub relationship: u8,
pub transmit_failure: u8,
pub lqi: u8,
pub outgoing_cost: u8,
pub age: u8,
#[ctx = ()]
pub keepalive_received: bool,
pub extended_pan_id: IeeeAddress,
pub logical_channel: u8,
pub depth: u8,
#[ctx = ()]
pub permit_joining: bool,
pub potential_parent: u8,
#[ctx = ()]
pub router_capacity: bool,
#[ctx = ()]
pub end_device_capacity: bool,
pub update_id: u8,
pub pan_id: u16,
}
}
#[derive(Debug, Clone)]
#[repr(u8)]
pub(crate) enum RouteStatus {
Active,
DiscoveryUnderway,
DiscoveryFailed,
Inactive,
ValidationUnderway,
Reserved,
}
impl_byte! {
#[derive(Debug, Clone)]
pub struct NwkRoute {
pub destination_address: ShortAddress,
pub next_hop_address: ShortAddress,
status: u8,
}
}
impl NwkRoute {
pub(crate) fn status(&self) -> RouteStatus {
let status = self.status & 0b111;
if status > 0x4 {
RouteStatus::Reserved
} else {
unsafe { mem::transmute::<u8, RouteStatus>(status) }
}
}
pub(crate) fn no_route_cache(&self) -> bool {
(self.status >> 3) & 0b1 != 0
}
pub(crate) fn many_to_one(&self) -> bool {
(self.status >> 4) & 0b1 != 0
}
pub(crate) fn route_record_required(&self) -> bool {
(self.status >> 5) & 0b1 != 0
}
pub(crate) fn group_id(&self) -> bool {
(self.status >> 6) & 0b1 != 0
}
}
impl_byte! {
#[derive(Debug, Clone)]
pub struct TransactionRecord {
pub source_address: ShortAddress,
pub sequence_number: u8,
pub expiration_time: u8,
}
}
impl_byte! {
#[derive(Debug, Clone)]
pub struct RouteRecord {
pub network_address: ShortAddress,
pub relay_count: u16,
pub path: StorageVec<ShortAddress, 16>,
}
}
impl_byte! {
#[derive(Debug, Clone)]
pub struct AddressMap {
pub ieee_address: IeeeAddress,
pub network_address: ShortAddress,
}
}
#[derive(Debug, Clone)]
pub(crate) struct MacInterface {}
impl_byte! {
#[derive(Debug, Clone)]
pub struct NetworkSecurityMaterialDescriptor {
pub key_seq_number: u8,
pub outgoing_frame_counter: u32,
pub incoming_frame_counter_set: StorageVec<IncomingFrameCounterDescriptor, MAX_NEIGBOUR_TABLE>,
pub key: ByteArray<16>,
pub network_key_type: u8,
}
}
impl_byte! {
#[derive(Debug, Clone)]
pub struct IncomingFrameCounterDescriptor {
pub sender_address: IeeeAddress,
pub incoming_frame_counter: u32,
}
}
#[cfg(feature = "storage")]
pub(crate) mod storage;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nib_set_vec() {
let nib = Nib::new();
let mut set = StorageVec::<NetworkSecurityMaterialDescriptor, MAX_SECURITY_KEYS>::new();
set.push(NetworkSecurityMaterialDescriptor {
key_seq_number: 0,
outgoing_frame_counter: 0,
incoming_frame_counter_set: StorageVec(Vec::new()),
key: ByteArray([0u8; 16]),
network_key_type: 0,
})
.unwrap();
nib.update_security_material_set(|value| *value = set);
assert_eq!(nib.security_material_set().len(), 1);
}
#[test]
fn nib_default() {
let nib = Nib::new();
assert_eq!(*nib.max_broadcast_retries(), 0x03);
assert_eq!(*nib.report_constant_cost(), 0x00);
assert!(!*nib.sym_link());
assert_eq!(*nib.capability_information(), CapabilityInformation(0x00));
assert_eq!(*nib.addr_alloc(), 0x0);
assert!(*nib.use_tree_routing());
assert_eq!(*nib.manager_addr(), 0x0000);
assert_eq!(*nib.max_source_route(), 0x0c);
assert_eq!(*nib.update_id(), 0x00);
assert_eq!(*nib.transaction_persistence_time(), 0x01f4);
assert_eq!(*nib.network_address(), 0xffff);
assert_eq!(*nib.extended_panid(), 0x0000_0000_0000_0000);
assert!(*nib.use_multicast());
assert!(!*nib.is_concentrator());
assert_eq!(*nib.concentrator_radius(), 0x00);
assert_eq!(*nib.concentrator_discovery_time(), 0x00);
assert_eq!(*nib.link_status_period(), 0x0f);
assert_eq!(*nib.router_age_limit(), 0x03);
assert!(*nib.unique_addr());
assert!(!*nib.time_stamp());
assert_eq!(*nib.panid(), 0xffff);
assert_eq!(*nib.tx_total(), 0x0000);
assert!(*nib.leave_request_allowed());
assert_eq!(*nib.parent_information(), 0x00);
assert_eq!(*nib.end_device_timeout_default(), 0x08);
assert!(*nib.leave_request_without_rejoin_allowed());
}
#[test]
fn storage_vec() {
let mut vec = StorageVec::<u8, 3>::new();
vec.push(1).unwrap();
vec.push(2).unwrap();
vec.push(3).unwrap();
let mut buf = [0u8; 5];
vec.try_write(&mut buf, byte::LE).unwrap();
assert_eq!(buf, [0x03, 0x00, 0x01, 0x02, 0x03]);
let (vec2, _) = StorageVec::<u8, 3>::try_read(&buf, byte::LE).unwrap();
assert_eq!(vec2.len(), 3);
assert_eq!(vec2[0], 1);
assert_eq!(vec2[1], 2);
assert_eq!(vec2[2], 3);
}
}