use byte::BytesExt;
use byte::ctx;
use zigbee_types::IeeeAddress;
use crate::apl::descriptors::node_descriptor::LogicalType;
use crate::apl::descriptors::node_power_descriptor::CurrentPowerMode;
use crate::apl::descriptors::node_power_descriptor::CurrentPowerSourceLevel;
use crate::apl::descriptors::node_power_descriptor::PowerSource;
use crate::nwk::nlme::management::NlmeLeaveStatus;
pub const NWK_ADDR_REQ: u16 = 0x0000;
pub const IEEE_ADDR_REQ: u16 = 0x0001;
pub const NODE_DESC_REQ: u16 = 0x0002;
pub const POWER_DESC_REQ: u16 = 0x0003;
pub const SIMPLE_DESC_REQ: u16 = 0x0004;
pub const ACTIVE_EP_REQ: u16 = 0x0005;
pub const MATCH_DESC_REQ: u16 = 0x0006;
pub const BIND_REQ: u16 = 0x0021;
pub const UNBIND_REQ: u16 = 0x0022;
pub const MGMT_LEAVE_REQ: u16 = 0x0034;
pub const NWK_ADDR_RSP: u16 = 0x8000;
pub const IEEE_ADDR_RSP: u16 = 0x8001;
pub const NODE_DESC_RSP: u16 = 0x8002;
pub const POWER_DESC_RSP: u16 = 0x8003;
pub const SIMPLE_DESC_RSP: u16 = 0x8004;
pub const ACTIVE_EP_RSP: u16 = 0x8005;
pub const MATCH_DESC_RSP: u16 = 0x8006;
pub const BIND_RSP: u16 = 0x8021;
pub const UNBIND_RSP: u16 = 0x8022;
pub const MGMT_LEAVE_RSP: u16 = 0x8034;
const STATUS_SUCCESS: u8 = 0x00;
const STATUS_INV_REQUESTTYPE: u8 = 0x80;
const STATUS_DEVICE_NOT_FOUND: u8 = 0x81;
const STATUS_INVALID_EP: u8 = 0x82;
const STATUS_NOT_ACTIVE: u8 = 0x83;
const STATUS_NOT_SUPPORTED: u8 = 0x84;
const STATUS_NO_ENTRY: u8 = 0x88;
const STATUS_NOT_PERMITTED: u8 = 0x8b;
const STATUS_TABLE_FULL: u8 = 0x8c;
const STATUS_NOT_AUTHORIZED: u8 = 0x8d;
const MGMT_LEAVE_REMOVE_CHILDREN: u8 = 0b0100_0000;
const MGMT_LEAVE_REJOIN: u8 = 0b1000_0000;
const NODE_DESCRIPTOR_SIZE: usize = 13;
const POWER_DESCRIPTOR_SIZE: usize = 2;
const WILDCARD_PROFILE_ID: u16 = 0xffff;
fn append(out: &mut [u8], offset: &mut usize, bytes: &[u8]) -> Result<(), byte::Error> {
let end = offset
.checked_add(bytes.len())
.ok_or(byte::Error::Incomplete)?;
out.get_mut(*offset..end)
.ok_or(byte::Error::Incomplete)?
.copy_from_slice(bytes);
*offset = end;
Ok(())
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NodeDescriptorConfig {
pub logical_type: LogicalType,
pub complex_descriptor_available: bool,
pub user_descriptor_available: bool,
pub frequency_band: u8,
pub mac_capability_flags: u8,
pub manufacturer_code: u16,
pub maximum_buffer_size: u8,
pub maximum_incoming_transfer_size: u16,
pub server_mask: u16,
pub maximum_outgoing_transfer_size: u16,
pub descriptor_capability_field: u8,
}
impl NodeDescriptorConfig {
fn write(&self, out: &mut [u8]) -> Result<usize, byte::Error> {
let offset = &mut 0;
let logical_type = match self.logical_type {
LogicalType::Coordinator => 0b000,
LogicalType::Router => 0b001,
LogicalType::EndDevice => 0b010,
LogicalType::Reserved(v) => v,
};
let byte0 = (logical_type & 0b111)
| (u8::from(self.complex_descriptor_available) << 3)
| (u8::from(self.user_descriptor_available) << 4);
out.write_with(offset, byte0, ctx::LE)?;
out.write_with(offset, (self.frequency_band & 0x1f) << 3, ctx::LE)?;
out.write_with(offset, self.mac_capability_flags, ctx::LE)?;
out.write_with(offset, self.manufacturer_code, ctx::LE)?;
out.write_with(offset, self.maximum_buffer_size, ctx::LE)?;
out.write_with(offset, self.maximum_incoming_transfer_size, ctx::LE)?;
out.write_with(offset, self.server_mask, ctx::LE)?;
out.write_with(offset, self.maximum_outgoing_transfer_size, ctx::LE)?;
out.write_with(offset, self.descriptor_capability_field, ctx::LE)?;
Ok(*offset)
}
}
#[derive(Debug, Clone, Copy)]
pub struct PowerDescriptorConfig<'a> {
pub current_power_mode: CurrentPowerMode,
pub available_power_sources: &'a [PowerSource],
pub current_power_source: PowerSource,
pub current_power_source_level: CurrentPowerSourceLevel,
}
impl PowerDescriptorConfig<'_> {
fn write(&self, out: &mut [u8]) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(
offset,
self.current_power_mode.bits()
| (PowerSource::bitmap(self.available_power_sources) << 4),
ctx::LE,
)?;
out.write_with(
offset,
self.current_power_source.bits() | (self.current_power_source_level.bits() << 4),
ctx::LE,
)?;
Ok(*offset)
}
}
#[derive(Debug, Clone, Copy)]
pub struct EndpointDescriptor<'a> {
pub endpoint: u8,
pub profile_id: u16,
pub device_id: u16,
pub device_version: u8,
pub input_clusters: &'a [u16],
pub output_clusters: &'a [u16],
}
impl EndpointDescriptor<'_> {
fn write(&self, out: &mut [u8]) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, self.endpoint, ctx::LE)?;
out.write_with(offset, self.profile_id, ctx::LE)?;
out.write_with(offset, self.device_id, ctx::LE)?;
out.write_with(offset, self.device_version & 0x0f, ctx::LE)?;
out.write_with(
offset,
u8::try_from(self.input_clusters.len()).unwrap_or(u8::MAX),
ctx::LE,
)?;
for &cluster in self.input_clusters {
out.write_with(offset, cluster, ctx::LE)?;
}
out.write_with(
offset,
u8::try_from(self.output_clusters.len()).unwrap_or(u8::MAX),
ctx::LE,
)?;
for &cluster in self.output_clusters {
out.write_with(offset, cluster, ctx::LE)?;
}
Ok(*offset)
}
}
#[derive(Debug, Clone, Copy)]
pub struct DeviceDescriptorConfig<'a> {
pub node: NodeDescriptorConfig,
pub power: PowerDescriptorConfig<'a>,
pub endpoints: &'a [EndpointDescriptor<'a>],
}
impl DeviceDescriptorConfig<'_> {
fn endpoint(&self, endpoint: u8) -> Option<&EndpointDescriptor<'_>> {
self.endpoints.iter().find(|e| e.endpoint == endpoint)
}
pub fn supports_endpoint(&self, endpoint: u8) -> bool {
self.endpoint(endpoint).is_some()
}
pub fn node_desc_rsp(
&self,
seq: u8,
nwk_addr: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
let mut nd = [0u8; NODE_DESCRIPTOR_SIZE];
let n = self.node.write(&mut nd)?;
append(out, offset, &nd[..n])?;
Ok(*offset)
}
pub fn power_desc_rsp(
&self,
seq: u8,
nwk_addr: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
let mut pd = [0u8; POWER_DESCRIPTOR_SIZE];
let n = self.power.write(&mut pd)?;
append(out, offset, &pd[..n])?;
Ok(*offset)
}
pub fn matching_endpoints(&self, request: &MatchDescReq<'_>, out: &mut [u8]) -> usize {
let mut count = 0;
for ep in self.endpoints {
if request.profile_id != WILDCARD_PROFILE_ID && request.profile_id != ep.profile_id {
continue;
}
let matches = request
.input_clusters()
.any(|cluster| ep.input_clusters.contains(&cluster))
|| request
.output_clusters()
.any(|cluster| ep.output_clusters.contains(&cluster));
if matches {
let Some(slot) = out.get_mut(count) else {
break;
};
*slot = ep.endpoint;
count += 1;
}
}
count
}
pub fn active_ep_rsp(
&self,
seq: u8,
nwk_addr: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
out.write_with(
offset,
u8::try_from(self.endpoints.len()).unwrap_or(u8::MAX),
ctx::LE,
)?;
for ep in self.endpoints {
out.write_with(offset, ep.endpoint, ctx::LE)?;
}
Ok(*offset)
}
pub fn simple_desc_rsp(
&self,
seq: u8,
nwk_addr: u16,
endpoint: u8,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
if let Some(ep) = self.endpoint(endpoint) {
let mut desc = [0u8; 64];
let len = ep.write(&mut desc)?;
out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
out.write_with(offset, u8::try_from(len).unwrap_or(u8::MAX), ctx::LE)?;
append(out, offset, &desc[..len])?;
} else {
out.write_with(offset, STATUS_NOT_ACTIVE, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
out.write_with(offset, 0u8, ctx::LE)?;
}
Ok(*offset)
}
}
pub const ADDR_REQUEST_SINGLE: u8 = 0x00;
pub const ADDR_REQUEST_EXTENDED: u8 = 0x01;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NwkAddrReq {
pub seq: u8,
pub ieee_addr: IeeeAddress,
pub request_type: u8,
}
pub fn parse_nwk_addr_req(asdu: &[u8]) -> Option<NwkAddrReq> {
let offset = &mut 0;
let seq: u8 = asdu.read_with(offset, ctx::LE).ok()?;
let ieee_addr: u64 = asdu.read_with(offset, ctx::LE).ok()?;
let request_type: u8 = asdu.read_with(offset, ctx::LE).ok()?;
Some(NwkAddrReq {
seq,
ieee_addr: IeeeAddress(ieee_addr),
request_type,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IeeeAddrReq {
pub seq: u8,
pub nwk_addr_of_interest: u16,
pub request_type: u8,
}
pub fn parse_ieee_addr_req(asdu: &[u8]) -> Option<IeeeAddrReq> {
let offset = &mut 0;
let seq: u8 = asdu.read_with(offset, ctx::LE).ok()?;
let nwk_addr_of_interest: u16 = asdu.read_with(offset, ctx::LE).ok()?;
let request_type: u8 = asdu.read_with(offset, ctx::LE).ok()?;
Some(IeeeAddrReq {
seq,
nwk_addr_of_interest,
request_type,
})
}
pub fn parse_addr_of_interest(asdu: &[u8]) -> Option<u16> {
Some(u16::from_le_bytes(asdu.get(1..3)?.try_into().ok()?))
}
pub fn addr_rsp(
seq: u8,
ieee_addr: IeeeAddress,
nwk_addr: u16,
extended: bool,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
out.write_with(offset, ieee_addr.0, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
if extended {
out.write_with(offset, 0u8, ctx::LE)?;
out.write_with(offset, 0u8, ctx::LE)?;
}
Ok(*offset)
}
pub fn addr_rsp_error(
seq: u8,
error: DiscoveryError,
ieee_addr: IeeeAddress,
nwk_addr: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, error.code(), ctx::LE)?;
out.write_with(offset, ieee_addr.0, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
Ok(*offset)
}
pub fn descriptor_rsp_error(
seq: u8,
error: DiscoveryError,
nwk_addr_of_interest: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, error.code(), ctx::LE)?;
out.write_with(offset, nwk_addr_of_interest, ctx::LE)?;
Ok(*offset)
}
pub fn active_ep_rsp_error(
seq: u8,
error: DiscoveryError,
nwk_addr_of_interest: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut descriptor_rsp_error(seq, error, nwk_addr_of_interest, out)?;
out.write_with(offset, 0u8, ctx::LE)?;
Ok(*offset)
}
pub fn simple_desc_rsp_error(
seq: u8,
error: DiscoveryError,
nwk_addr_of_interest: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut descriptor_rsp_error(seq, error, nwk_addr_of_interest, out)?;
out.write_with(offset, 0u8, ctx::LE)?;
Ok(*offset)
}
pub fn node_desc_req(
seq: u8,
nwk_addr_of_interest: u16,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, nwk_addr_of_interest, ctx::LE)?;
Ok(*offset)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeDescRsp {
pub seq: u8,
pub status: u8,
pub nwk_addr_of_interest: u16,
pub server_mask: Option<u16>,
}
impl NodeDescRsp {
pub fn stack_revision(&self) -> Option<u8> {
self.server_mask.map(|mask| (mask >> 9) as u8)
}
}
pub fn parse_node_desc_rsp(asdu: &[u8]) -> Option<NodeDescRsp> {
let seq = *asdu.first()?;
let status = *asdu.get(1)?;
let nwk_addr_of_interest = u16::from_le_bytes(asdu.get(2..4)?.try_into().ok()?);
let server_mask = asdu
.get(12..14)
.and_then(|bytes| bytes.try_into().ok())
.map(u16::from_le_bytes)
.filter(|_| status == STATUS_SUCCESS);
Some(NodeDescRsp {
seq,
status,
nwk_addr_of_interest,
server_mask,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BindReq {
pub seq: u8,
pub src_address: IeeeAddress,
pub src_endpoint: u8,
pub cluster_id: u16,
pub destination: BindReqDestination,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindReqDestination {
Group(u16),
Device { ieee: IeeeAddress, endpoint: u8 },
}
pub fn parse_bind_req(asdu: &[u8]) -> Option<BindReq> {
let offset = &mut 0;
let seq: u8 = asdu.read_with(offset, ctx::LE).ok()?;
let src_address: u64 = asdu.read_with(offset, ctx::LE).ok()?;
let src_endpoint: u8 = asdu.read_with(offset, ctx::LE).ok()?;
let cluster_id: u16 = asdu.read_with(offset, ctx::LE).ok()?;
let dst_addr_mode: u8 = asdu.read_with(offset, ctx::LE).ok()?;
let destination = match dst_addr_mode {
BIND_ADDR_MODE_GROUP => BindReqDestination::Group(asdu.read_with(offset, ctx::LE).ok()?),
BIND_ADDR_MODE_DEVICE => BindReqDestination::Device {
ieee: IeeeAddress(asdu.read_with(offset, ctx::LE).ok()?),
endpoint: asdu.read_with(offset, ctx::LE).ok()?,
},
_ => return None,
};
Some(BindReq {
seq,
src_address: IeeeAddress(src_address),
src_endpoint,
cluster_id,
destination,
})
}
const BIND_ADDR_MODE_GROUP: u8 = 0x01;
const BIND_ADDR_MODE_DEVICE: u8 = 0x03;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindStatus {
Success,
InvalidEndpoint,
TableFull,
NoEntry,
NotSupported,
}
impl BindStatus {
fn code(self) -> u8 {
match self {
Self::Success => STATUS_SUCCESS,
Self::InvalidEndpoint => STATUS_INVALID_EP,
Self::TableFull => STATUS_TABLE_FULL,
Self::NoEntry => STATUS_NO_ENTRY,
Self::NotSupported => STATUS_NOT_SUPPORTED,
}
}
}
pub fn bind_rsp(seq: u8, status: BindStatus, out: &mut [u8]) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, status.code(), ctx::LE)?;
Ok(*offset)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MatchDescReq<'a> {
pub seq: u8,
pub nwk_addr_of_interest: u16,
pub profile_id: u16,
input_clusters: &'a [u8],
output_clusters: &'a [u8],
}
impl MatchDescReq<'_> {
pub fn input_clusters(&self) -> impl Iterator<Item = u16> + '_ {
cluster_ids(self.input_clusters)
}
pub fn output_clusters(&self) -> impl Iterator<Item = u16> + '_ {
cluster_ids(self.output_clusters)
}
}
fn cluster_ids(bytes: &[u8]) -> impl Iterator<Item = u16> + '_ {
bytes
.as_chunks::<2>()
.0
.iter()
.copied()
.map(u16::from_le_bytes)
}
pub fn parse_match_desc_req(asdu: &[u8]) -> Option<MatchDescReq<'_>> {
let seq = *asdu.first()?;
let nwk_addr_of_interest = u16::from_le_bytes(asdu.get(1..3)?.try_into().ok()?);
let profile_id = u16::from_le_bytes(asdu.get(3..5)?.try_into().ok()?);
let in_count = usize::from(*asdu.get(5)?);
let in_end = 6 + in_count * 2;
let input_clusters = asdu.get(6..in_end)?;
let out_count = usize::from(*asdu.get(in_end)?);
let out_start = in_end + 1;
let output_clusters = asdu.get(out_start..out_start + out_count * 2)?;
Some(MatchDescReq {
seq,
nwk_addr_of_interest,
profile_id,
input_clusters,
output_clusters,
})
}
pub fn match_desc_rsp(
seq: u8,
nwk_addr: u16,
matches: &[u8],
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
out.write_with(offset, nwk_addr, ctx::LE)?;
out.write_with(
offset,
u8::try_from(matches.len()).unwrap_or(u8::MAX),
ctx::LE,
)?;
for &endpoint in matches {
out.write_with(offset, endpoint, ctx::LE)?;
}
Ok(*offset)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscoveryError {
InvalidRequestType,
DeviceNotFound,
}
impl DiscoveryError {
fn code(self) -> u8 {
match self {
Self::InvalidRequestType => STATUS_INV_REQUESTTYPE,
Self::DeviceNotFound => STATUS_DEVICE_NOT_FOUND,
}
}
}
pub fn match_desc_rsp_error(
seq: u8,
error: DiscoveryError,
out: &mut [u8],
) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, error.code(), ctx::LE)?;
out.write_with(offset, 0u8, ctx::LE)?;
Ok(*offset)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MgmtLeaveReq {
pub seq: u8,
pub device_address: Option<IeeeAddress>,
pub remove_children: bool,
pub rejoin: bool,
}
pub fn parse_mgmt_leave_req(asdu: &[u8]) -> Option<MgmtLeaveReq> {
let seq = *asdu.first()?;
let addr_bytes: [u8; 8] = asdu.get(1..9)?.try_into().ok()?;
let device_address = match u64::from_le_bytes(addr_bytes) {
0 => None,
addr => Some(IeeeAddress(addr)),
};
let options = *asdu.get(9)?;
Some(MgmtLeaveReq {
seq,
device_address,
remove_children: options & MGMT_LEAVE_REMOVE_CHILDREN != 0,
rejoin: options & MGMT_LEAVE_REJOIN != 0,
})
}
pub fn leave_status(status: NlmeLeaveStatus) -> u8 {
match status {
NlmeLeaveStatus::Success => STATUS_SUCCESS,
NlmeLeaveStatus::InvalidRequest => STATUS_INV_REQUESTTYPE,
NlmeLeaveStatus::UnknownDevice => STATUS_DEVICE_NOT_FOUND,
NlmeLeaveStatus::MacError => STATUS_NOT_PERMITTED,
NlmeLeaveStatus::NotAuthorized => STATUS_NOT_AUTHORIZED,
}
}
pub fn mgmt_leave_rsp(seq: u8, status: u8, out: &mut [u8]) -> Result<usize, byte::Error> {
let offset = &mut 0;
out.write_with(offset, seq, ctx::LE)?;
out.write_with(offset, status, ctx::LE)?;
Ok(*offset)
}
#[cfg(test)]
mod tests {
use super::*;
const NODE: NodeDescriptorConfig = NodeDescriptorConfig {
logical_type: LogicalType::EndDevice,
complex_descriptor_available: false,
user_descriptor_available: false,
frequency_band: 0x08,
mac_capability_flags: 0x88,
manufacturer_code: 0x1037,
maximum_buffer_size: 80,
maximum_incoming_transfer_size: 128,
server_mask: 0,
maximum_outgoing_transfer_size: 128,
descriptor_capability_field: 0,
};
const POWER: PowerDescriptorConfig = PowerDescriptorConfig {
current_power_mode: CurrentPowerMode::Synchronized,
available_power_sources: &[PowerSource::ConstantMainPower],
current_power_source: PowerSource::ConstantMainPower,
current_power_source_level: CurrentPowerSourceLevel::Full,
};
const ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
endpoint: 1,
profile_id: 0x0104,
device_id: 0x0302,
device_version: 1,
input_clusters: &[0x0000, 0x0402],
output_clusters: &[0x0019],
}];
fn cfg() -> DeviceDescriptorConfig<'static> {
DeviceDescriptorConfig {
node: NODE,
power: POWER,
endpoints: &ENDPOINTS,
}
}
#[test]
fn node_desc_rsp_layout() {
let mut out = [0u8; 32];
let n = cfg().node_desc_rsp(0x42, 0x1234, &mut out).unwrap();
assert_eq!(
&out[..n],
&[
0x42, 0x00, 0x34, 0x12, 0x02, 0x40, 0x88, 0x37, 0x10, 0x50, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, ]
);
}
#[test]
fn active_ep_rsp_layout() {
let mut out = [0u8; 16];
let n = cfg().active_ep_rsp(0x07, 0x1234, &mut out).unwrap();
assert_eq!(&out[..n], &[0x07, 0x00, 0x34, 0x12, 0x01, 0x01]);
}
#[test]
fn simple_desc_rsp_known_endpoint() {
let mut out = [0u8; 32];
let n = cfg().simple_desc_rsp(0x07, 0x1234, 1, &mut out).unwrap();
assert_eq!(
&out[..n],
&[
0x07, 0x00, 0x34, 0x12, 0x0e, 0x01, 0x04, 0x01, 0x02, 0x03, 0x01, 0x02, 0x00, 0x00, 0x02, 0x04, 0x01, 0x19, 0x00, ]
);
}
#[test]
fn simple_desc_rsp_unknown_endpoint_not_active() {
let mut out = [0u8; 16];
let n = cfg().simple_desc_rsp(0x07, 0x1234, 9, &mut out).unwrap();
assert_eq!(&out[..n], &[0x07, 0x83, 0x34, 0x12, 0x00]);
}
#[test]
fn power_desc_rsp_layout() {
let mut out = [0u8; 16];
let n = cfg().power_desc_rsp(0x07, 0x1234, &mut out).unwrap();
assert_eq!(
&out[..n],
&[
0x07, 0x00, 0x34, 0x12, 0x10, 0xc1, ]
);
}
const MATCH_REQ: [u8; 13] = [
0x33, 0x34, 0x12, 0x04, 0x01, 0x02, 0x00, 0x00, 0x02, 0x04, 0x01, 0x19, 0x00, ];
#[test]
fn parse_match_desc_req_lists() {
let req = parse_match_desc_req(&MATCH_REQ).unwrap();
assert_eq!(req.seq, 0x33);
assert_eq!(req.nwk_addr_of_interest, 0x1234);
assert_eq!(req.profile_id, 0x0104);
assert!(req.input_clusters().eq([0x0000, 0x0402]));
assert!(req.output_clusters().eq([0x0019]));
}
#[test]
fn parse_match_desc_req_rejects_truncated_list() {
assert!(parse_match_desc_req(&MATCH_REQ[..8]).is_none());
assert!(parse_match_desc_req(&MATCH_REQ[..10]).is_none());
assert!(parse_match_desc_req(&[0x33, 0x34]).is_none());
}
#[test]
fn matching_endpoints_by_input_cluster() {
let asdu = [0x33, 0x34, 0x12, 0x04, 0x01, 0x01, 0x02, 0x04, 0x00];
let req = parse_match_desc_req(&asdu).unwrap();
let mut out = [0u8; 4];
assert_eq!(cfg().matching_endpoints(&req, &mut out), 1);
assert_eq!(out[0], 1);
}
#[test]
fn matching_endpoints_by_output_cluster() {
let asdu = [0x33, 0x34, 0x12, 0x04, 0x01, 0x00, 0x01, 0x19, 0x00];
let req = parse_match_desc_req(&asdu).unwrap();
let mut out = [0u8; 4];
assert_eq!(cfg().matching_endpoints(&req, &mut out), 1);
}
#[test]
fn matching_endpoints_wildcard_profile() {
let asdu = [0x33, 0x34, 0x12, 0xff, 0xff, 0x01, 0x02, 0x04, 0x00];
let req = parse_match_desc_req(&asdu).unwrap();
let mut out = [0u8; 4];
assert_eq!(cfg().matching_endpoints(&req, &mut out), 1);
}
#[test]
fn matching_endpoints_rejects_wrong_profile_and_unknown_cluster() {
let asdu = [0x33, 0x34, 0x12, 0x09, 0x01, 0x01, 0x02, 0x04, 0x00];
let req = parse_match_desc_req(&asdu).unwrap();
let mut out = [0u8; 4];
assert_eq!(cfg().matching_endpoints(&req, &mut out), 0);
let asdu = [0x33, 0x34, 0x12, 0x04, 0x01, 0x01, 0x06, 0x00, 0x00];
let req = parse_match_desc_req(&asdu).unwrap();
assert_eq!(cfg().matching_endpoints(&req, &mut out), 0);
}
#[test]
fn match_desc_rsp_layout() {
let mut out = [0u8; 16];
let n = match_desc_rsp(0x33, 0x1234, &[1], &mut out).unwrap();
assert_eq!(&out[..n], &[0x33, 0x00, 0x34, 0x12, 0x01, 0x01]);
}
#[test]
fn match_desc_rsp_error_omits_address() {
let mut out = [0u8; 16];
let n = match_desc_rsp_error(0x33, DiscoveryError::InvalidRequestType, &mut out).unwrap();
assert_eq!(&out[..n], &[0x33, 0x80, 0x00]);
let n = match_desc_rsp_error(0x33, DiscoveryError::DeviceNotFound, &mut out).unwrap();
assert_eq!(&out[..n], &[0x33, 0x81, 0x00]);
}
#[test]
fn descriptor_rsp_reports_short_buffer_instead_of_panicking() {
let mut out = [0u8; 4];
assert!(cfg().power_desc_rsp(0x07, 0x1234, &mut out).is_err());
assert!(cfg().node_desc_rsp(0x07, 0x1234, &mut out).is_err());
assert!(cfg().simple_desc_rsp(0x07, 0x1234, 1, &mut out).is_err());
}
#[test]
fn bind_rsp_carries_status() {
let mut out = [0u8; 4];
let n = bind_rsp(0x21, BindStatus::Success, &mut out).unwrap();
assert_eq!(&out[..n], &[0x21, 0x00]);
let n = bind_rsp(0x21, BindStatus::InvalidEndpoint, &mut out).unwrap();
assert_eq!(&out[..n], &[0x21, 0x82]);
let n = bind_rsp(0x21, BindStatus::TableFull, &mut out).unwrap();
assert_eq!(&out[..n], &[0x21, 0x8c]);
}
#[test]
fn parse_bind_req_device_and_group_modes() {
let device = [
0x21, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x0a, 0x02, 0x04, 0x03, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01,
];
let request = parse_bind_req(&device).unwrap();
assert_eq!(request.seq, 0x21);
assert_eq!(request.src_address, IeeeAddress(0x8877_6655_4433_2211));
assert_eq!(request.src_endpoint, 0x0a);
assert_eq!(request.cluster_id, 0x0402);
assert_eq!(
request.destination,
BindReqDestination::Device {
ieee: IeeeAddress(0x0807_0605_0403_0201),
endpoint: 0x01,
}
);
let group = [
0x22, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x0a, 0x02, 0x04, 0x01, 0x34,
0x12,
];
let request = parse_bind_req(&group).unwrap();
assert_eq!(request.destination, BindReqDestination::Group(0x1234));
assert!(parse_bind_req(&device[..device.len() - 1]).is_none());
let mut unknown = device;
unknown[12] = 0x02;
assert!(parse_bind_req(&unknown).is_none());
}
#[test]
fn addr_rsp_layout() {
let mut out = [0u8; 16];
let n = addr_rsp(
0x07,
IeeeAddress(0x0011_2233_4455_6677),
0x1234,
false,
&mut out,
)
.unwrap();
assert_eq!(
&out[..n],
&[
0x07, 0x00, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x34, 0x12, ]
);
let n = addr_rsp(
0x07,
IeeeAddress(0x0011_2233_4455_6677),
0x1234,
true,
&mut out,
)
.unwrap();
assert_eq!(&out[n - 2..n], &[0x00, 0x00]);
}
#[test]
fn addr_rsp_error_carries_the_echoed_addresses() {
let mut out = [0u8; 16];
let n = addr_rsp_error(
0x07,
DiscoveryError::DeviceNotFound,
IeeeAddress(0x0011_2233_4455_6677),
0x1234,
&mut out,
)
.unwrap();
assert_eq!(
&out[..n],
&[
0x07, 0x81, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x34, 0x12
]
);
}
#[test]
fn parse_addr_requests() {
let nwk = [
0x11, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x01, 0x00,
];
let request = parse_nwk_addr_req(&nwk).unwrap();
assert_eq!(request.seq, 0x11);
assert_eq!(request.ieee_addr, IeeeAddress(0x0011_2233_4455_6677));
assert_eq!(request.request_type, ADDR_REQUEST_EXTENDED);
assert!(parse_nwk_addr_req(&nwk[..9]).is_none());
let ieee = [0x12, 0x34, 0x12, 0x00, 0x00];
let request = parse_ieee_addr_req(&ieee).unwrap();
assert_eq!(request.seq, 0x12);
assert_eq!(request.nwk_addr_of_interest, 0x1234);
assert_eq!(request.request_type, ADDR_REQUEST_SINGLE);
assert!(parse_ieee_addr_req(&ieee[..3]).is_none());
}
#[test]
fn descriptor_rsp_error_omits_the_descriptor() {
let mut out = [0u8; 16];
let n = descriptor_rsp_error(0x07, DiscoveryError::InvalidRequestType, 0x1234, &mut out)
.unwrap();
assert_eq!(&out[..n], &[0x07, 0x80, 0x34, 0x12]);
let n =
simple_desc_rsp_error(0x07, DiscoveryError::DeviceNotFound, 0x1234, &mut out).unwrap();
assert_eq!(&out[..n], &[0x07, 0x81, 0x34, 0x12, 0x00]);
}
#[test]
fn parse_node_desc_rsp_reads_the_stack_revision() {
let mut out = [0u8; 32];
let mut cfg = cfg();
cfg.node.server_mask = 22 << 9;
let n = cfg.node_desc_rsp(0x42, 0x1234, &mut out).unwrap();
let response = parse_node_desc_rsp(&out[..n]).unwrap();
assert_eq!(response.seq, 0x42);
assert_eq!(response.status, STATUS_SUCCESS);
assert_eq!(response.nwk_addr_of_interest, 0x1234);
assert_eq!(response.stack_revision(), Some(22));
let n =
descriptor_rsp_error(0x42, DiscoveryError::DeviceNotFound, 0x1234, &mut out).unwrap();
assert_eq!(
parse_node_desc_rsp(&out[..n]).unwrap().stack_revision(),
None
);
}
#[test]
fn parse_mgmt_leave_req_self_null_address() {
let asdu = [
0x09, 0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00, 0b1100_0000, ];
let req = parse_mgmt_leave_req(&asdu).unwrap();
assert_eq!(req.seq, 0x09);
assert_eq!(req.device_address, None);
assert!(req.remove_children);
assert!(req.rejoin);
}
#[test]
fn parse_mgmt_leave_req_targets_device() {
let asdu = [
0x0a, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x00, ];
let req = parse_mgmt_leave_req(&asdu).unwrap();
assert_eq!(req.seq, 0x0a);
assert_eq!(req.device_address, Some(IeeeAddress(0x0011_2233_4455_6677)));
assert!(!req.remove_children);
assert!(!req.rejoin);
}
#[test]
fn parse_mgmt_leave_req_too_short() {
assert!(parse_mgmt_leave_req(&[0x01, 0x02]).is_none());
}
#[test]
fn mgmt_leave_rsp_layout() {
let mut out = [0u8; 4];
let n = mgmt_leave_rsp(0x09, 0x00, &mut out).unwrap();
assert_eq!(&out[..n], &[0x09, 0x00]);
}
}