#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
use core::cell::RefCell;
use matter_kit::clusters::basic_information::{
self, Attributes, BasicInformation, CapabilityMinima, Location, Product,
};
use matter_kit::clusters::descriptor::{self, DeviceType};
use matter_kit::clusters::general_commissioning::{
self, Aftermath, GeneralCommissioning, RegulatoryLocation,
};
use matter_kit::clusters::{Cluster, Descriptor};
use matter_kit::commissioning::failsafe::{BasicCommissioningInfo, FailSafe};
use matter_kit::commissioning::window::CommissioningWindow;
use matter_kit::dm::{Endpoint, Node, Privilege, global};
use matter_kit::im::{
AccessControl, AttributeData, AttributePath, ClusterHandler, CommandData, CommandPath,
InteractionContext, Outcome, Status,
};
use matter_kit::msg::{FabricIndex, VendorId};
use matter_kit::platform::{Duration, Instant};
use matter_kit::tlv::{ContainerKind, Tag, TlvReader, TlvWriter};
#[test]
fn cluster_ids_and_revisions_match_the_specification() {
assert_eq!(descriptor::ID, 0x001D);
assert_eq!(descriptor::REVISION, 3);
assert_eq!(descriptor::FEATURE_TAG_LIST, 1 << 0);
assert_eq!(basic_information::ID, 0x0028);
assert_eq!(basic_information::REVISION, 6);
assert_eq!(general_commissioning::ID, 0x0030);
assert_eq!(general_commissioning::REVISION, 2);
assert_eq!(general_commissioning::FEATURE_TERMS_AND_CONDITIONS, 1 << 0);
assert_eq!(general_commissioning::FEATURE_NETWORK_RECOVERY, 1 << 1);
}
#[test]
fn descriptor_attribute_ids_match_section_9_5_6() {
assert_eq!(descriptor::DEVICE_TYPE_LIST, 0x0000);
assert_eq!(descriptor::SERVER_LIST, 0x0001);
assert_eq!(descriptor::CLIENT_LIST, 0x0002);
assert_eq!(descriptor::PARTS_LIST, 0x0003);
assert_eq!(descriptor::TAG_LIST, 0x0004);
assert_eq!(descriptor::ENDPOINT_UNIQUE_ID, 0x0005);
}
#[test]
fn basic_information_attribute_and_event_ids_match_section_11_1() {
assert_eq!(basic_information::DATA_MODEL_REVISION_ID, 0x0000);
assert_eq!(basic_information::VENDOR_NAME, 0x0001);
assert_eq!(basic_information::VENDOR_ID, 0x0002);
assert_eq!(basic_information::PRODUCT_NAME, 0x0003);
assert_eq!(basic_information::PRODUCT_ID, 0x0004);
assert_eq!(basic_information::NODE_LABEL, 0x0005);
assert_eq!(basic_information::LOCATION, 0x0006);
assert_eq!(basic_information::HARDWARE_VERSION, 0x0007);
assert_eq!(basic_information::HARDWARE_VERSION_STRING, 0x0008);
assert_eq!(basic_information::SOFTWARE_VERSION, 0x0009);
assert_eq!(basic_information::SOFTWARE_VERSION_STRING, 0x000A);
assert_eq!(basic_information::MANUFACTURING_DATE, 0x000B);
assert_eq!(basic_information::PART_NUMBER, 0x000C);
assert_eq!(basic_information::PRODUCT_URL, 0x000D);
assert_eq!(basic_information::PRODUCT_LABEL, 0x000E);
assert_eq!(basic_information::SERIAL_NUMBER, 0x000F);
assert_eq!(basic_information::LOCAL_CONFIG_DISABLED, 0x0010);
assert_eq!(basic_information::REACHABLE, 0x0011);
assert_eq!(basic_information::UNIQUE_ID, 0x0012);
assert_eq!(basic_information::CAPABILITY_MINIMA, 0x0013);
assert_eq!(basic_information::PRODUCT_APPEARANCE, 0x0014);
assert_eq!(basic_information::SPECIFICATION_VERSION_ID, 0x0015);
assert_eq!(basic_information::MAX_PATHS_PER_INVOKE, 0x0016);
assert_eq!(basic_information::CONFIGURATION_VERSION, 0x0018);
assert_eq!(basic_information::START_UP, 0x00);
assert_eq!(basic_information::SHUT_DOWN, 0x01);
assert_eq!(basic_information::LEAVE, 0x02);
assert_eq!(basic_information::REACHABLE_CHANGED, 0x03);
}
#[test]
fn specification_version_is_matter_1_6() {
assert_eq!(basic_information::SPECIFICATION_VERSION, 0x0106_0000);
let bytes = basic_information::SPECIFICATION_VERSION.to_be_bytes();
assert_eq!(bytes, [1, 6, 0, 0]);
}
#[test]
fn general_commissioning_ids_match_section_11_10() {
assert_eq!(general_commissioning::BREADCRUMB, 0x0000);
assert_eq!(general_commissioning::BASIC_COMMISSIONING_INFO, 0x0001);
assert_eq!(general_commissioning::REGULATORY_CONFIG, 0x0002);
assert_eq!(general_commissioning::LOCATION_CAPABILITY, 0x0003);
assert_eq!(
general_commissioning::SUPPORTS_CONCURRENT_CONNECTION,
0x0004
);
assert_eq!(general_commissioning::ARM_FAIL_SAFE, 0x00);
assert_eq!(general_commissioning::ARM_FAIL_SAFE_RESPONSE, 0x01);
assert_eq!(general_commissioning::SET_REGULATORY_CONFIG, 0x02);
assert_eq!(general_commissioning::SET_REGULATORY_CONFIG_RESPONSE, 0x03);
assert_eq!(general_commissioning::COMMISSIONING_COMPLETE, 0x04);
assert_eq!(general_commissioning::COMMISSIONING_COMPLETE_RESPONSE, 0x05);
assert_eq!(RegulatoryLocation::Indoor.value(), 0);
assert_eq!(RegulatoryLocation::Outdoor.value(), 1);
assert_eq!(RegulatoryLocation::IndoorOutdoor.value(), 2);
assert_eq!(RegulatoryLocation::from_value(3), None);
}
#[test]
fn every_descriptor_is_well_formed() {
for cluster in [
descriptor::cluster(),
descriptor::cluster_with_tags(),
descriptor::cluster_with_unique_id(),
descriptor::cluster_full(),
general_commissioning::cluster(),
] {
assert!(cluster.is_well_formed(), "{:#06x}", cluster.id);
}
let product = sample_product();
for (local, reachable) in [(false, false), (true, false), (false, true), (true, true)] {
let attributes = Attributes::new(&product, local, reachable);
assert!(attributes.cluster().is_well_formed());
}
}
#[test]
fn access_qualities_match_the_tables() {
let product = sample_product();
let attributes = Attributes::new(&product, false, false);
let cluster = attributes.cluster();
let node_label = cluster.attribute(basic_information::NODE_LABEL).unwrap();
assert!(node_label.access.is_writable());
assert_eq!(node_label.access.write, Some(Privilege::Manage));
assert_eq!(node_label.access.read, Some(Privilege::View));
let location = cluster.attribute(basic_information::LOCATION).unwrap();
assert_eq!(location.access.write, Some(Privilege::Administer));
let vendor = cluster.attribute(basic_information::VENDOR_NAME).unwrap();
assert!(!vendor.access.is_writable());
let gc = general_commissioning::cluster();
let breadcrumb = gc.attribute(general_commissioning::BREADCRUMB).unwrap();
assert_eq!(breadcrumb.access.write, Some(Privilege::Administer));
let regulatory = gc
.attribute(general_commissioning::REGULATORY_CONFIG)
.unwrap();
assert!(!regulatory.access.is_writable());
for id in [
general_commissioning::ARM_FAIL_SAFE,
general_commissioning::SET_REGULATORY_CONFIG,
general_commissioning::COMMISSIONING_COMPLETE,
] {
let command = gc.accepted_command(id).unwrap();
assert_eq!(
command.access.invoke,
Some(Privilege::Administer),
"{id:#04x}"
);
}
let complete = gc
.accepted_command(general_commissioning::COMMISSIONING_COMPLETE)
.unwrap();
assert!(complete.access.is_fabric_scoped());
assert!(
!gc.accepted_command(general_commissioning::ARM_FAIL_SAFE)
.unwrap()
.access
.is_fabric_scoped(),
"ArmFailSafe is `A`, not `AF` — it must work over PASE, before any fabric exists"
);
}
#[test]
fn generated_command_list_is_derived_from_the_responses() {
let generated: Vec<u32> = general_commissioning::cluster()
.generated_command_ids()
.collect();
assert_eq!(
generated,
vec![
general_commissioning::ARM_FAIL_SAFE_RESPONSE,
general_commissioning::SET_REGULATORY_CONFIG_RESPONSE,
general_commissioning::COMMISSIONING_COMPLETE_RESPONSE,
]
);
}
const fn sample_product() -> Product<'static> {
Product::new(
"Test Vendor",
VendorId(0xFFF1),
"Test Product",
0x8000,
"0123456789abcdef",
)
.with_hardware(1, "v1")
.with_software(0x0001_0000, "1.0")
.with_serial_number("SN-1")
.with_max_paths_per_invoke(3)
}
struct AllowAll;
impl AccessControl for AllowAll {
fn allows(&self, _path: &AttributePath, _required: Privilege) -> Outcome {
Outcome::Granted
}
}
fn read_attribute<H: ClusterHandler>(
node: Node<'_>,
handler: &H,
endpoint: u16,
cluster: u32,
attribute: u32,
) -> Result<Vec<u8>, Status> {
let resolved = node
.resolve(endpoint, cluster, attribute)
.expect("the path exists");
let mut buf = [0u8; 1024];
let mut w = TlvWriter::new(&mut buf);
handler.read(
&resolved,
&InteractionContext::default(),
&mut w,
Tag::Anonymous,
)?;
Ok(w.finish().expect("finish").to_vec())
}
fn decode_u64(bytes: &[u8]) -> u64 {
let mut reader = TlvReader::new(bytes);
reader
.next_element()
.unwrap()
.unwrap()
.unsigned()
.expect("an unsigned value")
}
fn decode_utf8(bytes: &[u8]) -> String {
let mut reader = TlvReader::new(bytes);
reader
.next_element()
.unwrap()
.unwrap()
.utf8()
.expect("a string")
.to_owned()
}
fn decode_u64_array(bytes: &[u8]) -> Vec<u64> {
let mut reader = TlvReader::new(bytes);
let array = reader.next_element().unwrap().unwrap();
assert_eq!(array.value.container(), Some(ContainerKind::Array));
let mut out = Vec::new();
let depth = reader.depth();
while let Some(element) = reader.next_element().unwrap() {
if reader.depth() < depth {
break;
}
out.push(element.unsigned().expect("unsigned member"));
}
out
}
const DEVICE_TYPES: &[DeviceType] = &[DeviceType::new(0x0016, 3)];
#[test]
fn server_list_is_read_out_of_the_node_not_stored() {
let clusters = [descriptor::cluster(), general_commissioning::cluster()];
let endpoints = [Endpoint::new(0, &clusters).with_device_types(DEVICE_TYPES)];
let node = Node::new(&endpoints);
node.validate().expect("well formed");
let desc = Descriptor::new(node, 0);
let bytes = read_attribute(node, &desc, 0, descriptor::ID, descriptor::SERVER_LIST).unwrap();
assert_eq!(
decode_u64_array(&bytes),
vec![
u64::from(descriptor::ID),
u64::from(general_commissioning::ID)
]
);
}
#[test]
fn device_type_list_carries_the_struct_of_section_9_5_5_1() {
let clusters = [descriptor::cluster()];
let endpoints = [Endpoint::new(0, &clusters).with_device_types(DEVICE_TYPES)];
let node = Node::new(&endpoints);
let desc = Descriptor::new(node, 0);
let bytes =
read_attribute(node, &desc, 0, descriptor::ID, descriptor::DEVICE_TYPE_LIST).unwrap();
let mut reader = TlvReader::new(&bytes);
reader.next_element().unwrap().unwrap(); reader.next_element().unwrap().unwrap(); let device_type = reader.next_element().unwrap().unwrap();
assert_eq!(device_type.tag, Tag::Context(0));
assert_eq!(device_type.unsigned().unwrap(), 0x0016);
let revision = reader.next_element().unwrap().unwrap();
assert_eq!(revision.tag, Tag::Context(1));
assert_eq!(revision.unsigned().unwrap(), 3);
}
#[test]
fn a_descriptor_refuses_to_answer_for_another_endpoint() {
let clusters = [descriptor::cluster()];
let endpoints = [
Endpoint::new(0, &clusters).with_device_types(DEVICE_TYPES),
Endpoint::new(1, &clusters),
];
let node = Node::new(&endpoints);
let desc = Descriptor::new(node, 0);
assert_eq!(
read_attribute(node, &desc, 1, descriptor::ID, descriptor::SERVER_LIST),
Err(Status::UnsupportedEndpoint)
);
}
#[test]
fn the_attribute_list_matches_what_the_instance_serves() {
let clusters = [descriptor::cluster_full()];
let endpoints = [Endpoint::new(0, &clusters).with_device_types(DEVICE_TYPES)];
let node = Node::new(&endpoints);
let desc = Descriptor::new(node, 0).with_unique_id("endpoint-0");
for id in desc.descriptor().attribute_ids() {
if global::is_global(id) {
continue;
}
let result = read_attribute(node, &desc, 0, descriptor::ID, id);
assert!(result.is_ok(), "declared but not served: {id:#06x}");
}
let plain = Descriptor::new(node, 0);
assert!(
!plain
.descriptor()
.attribute_ids()
.any(|id| id == descriptor::ENDPOINT_UNIQUE_ID)
);
assert_eq!(
read_attribute(
node,
&plain,
0,
descriptor::ID,
descriptor::ENDPOINT_UNIQUE_ID
),
Err(Status::UnsupportedAttribute)
);
}
#[test]
fn basic_information_serves_its_product_record() {
let product = sample_product();
let attributes = Attributes::new(&product, false, false);
let clusters = [attributes.cluster()];
let endpoints = [Endpoint::new(0, &clusters)];
let node = Node::new(&endpoints);
let location = Location::region_agnostic();
let info = BasicInformation::new(&product, &location);
let read = |id: u32| read_attribute(node, &info, 0, basic_information::ID, id).unwrap();
assert_eq!(
decode_utf8(&read(basic_information::VENDOR_NAME)),
"Test Vendor"
);
assert_eq!(decode_u64(&read(basic_information::VENDOR_ID)), 0xFFF1);
assert_eq!(decode_u64(&read(basic_information::PRODUCT_ID)), 0x8000);
assert_eq!(
decode_u64(&read(basic_information::SOFTWARE_VERSION)),
0x0001_0000
);
assert_eq!(decode_utf8(&read(basic_information::SERIAL_NUMBER)), "SN-1");
assert_eq!(
decode_u64(&read(basic_information::SPECIFICATION_VERSION_ID)),
0x0106_0000
);
assert_eq!(
decode_u64(&read(basic_information::MAX_PATHS_PER_INVOKE)),
3
);
assert_eq!(decode_utf8(&read(basic_information::LOCATION)), "XX");
assert_eq!(decode_utf8(&read(basic_information::NODE_LABEL)), "");
}
#[test]
fn optional_attributes_are_absent_unless_given() {
let product = Product::new("V", VendorId(1), "P", 2, "u");
let attributes = Attributes::new(&product, false, false);
for id in [
basic_information::SERIAL_NUMBER,
basic_information::PART_NUMBER,
basic_information::PRODUCT_URL,
basic_information::PRODUCT_LABEL,
basic_information::MANUFACTURING_DATE,
basic_information::PRODUCT_APPEARANCE,
basic_information::LOCAL_CONFIG_DISABLED,
basic_information::REACHABLE,
] {
assert!(
!attributes.cluster().attribute_ids().any(|a| a == id),
"{id:#06x} declared without a value"
);
}
let over_declared = Attributes::new(&sample_product(), true, true);
let clusters = [over_declared.cluster()];
let endpoints = [Endpoint::new(0, &clusters)];
let node = Node::new(&endpoints);
let location = Location::region_agnostic();
let info = BasicInformation::new(&product, &location);
assert_eq!(
read_attribute(
node,
&info,
0,
basic_information::ID,
basic_information::SERIAL_NUMBER
),
Err(Status::UnsupportedAttribute)
);
assert_eq!(
read_attribute(
node,
&info,
0,
basic_information::ID,
basic_information::REACHABLE
),
Err(Status::UnsupportedAttribute)
);
}
#[test]
fn capability_minima_omits_the_revision_6_fields_when_absent() {
let explicitly_absent = CapabilityMinima {
simultaneous_invocations: None,
simultaneous_writes: None,
read_paths: None,
subscribe_paths: None,
..CapabilityMinima::default()
};
let product = sample_product().with_capability_minima(explicitly_absent);
let attributes = Attributes::new(&product, false, false);
let clusters = [attributes.cluster()];
let endpoints = [Endpoint::new(0, &clusters)];
let node = Node::new(&endpoints);
let location = Location::region_agnostic();
let info = BasicInformation::new(&product, &location);
let bytes = read_attribute(
node,
&info,
0,
basic_information::ID,
basic_information::CAPABILITY_MINIMA,
)
.unwrap();
let tags = struct_tags(&bytes);
assert_eq!(tags, vec![0, 1]);
let product = sample_product().with_capability_minima(CapabilityMinima {
case_sessions_per_fabric: 3,
subscriptions_per_fabric: 3,
simultaneous_invocations: Some(2),
simultaneous_writes: Some(2),
read_paths: Some(9),
subscribe_paths: Some(3),
});
let info = BasicInformation::new(&product, &location);
let bytes = read_attribute(
node,
&info,
0,
basic_information::ID,
basic_information::CAPABILITY_MINIMA,
)
.unwrap();
assert_eq!(struct_tags(&bytes), vec![0, 1, 2, 3, 4, 5]);
}
fn struct_tags(bytes: &[u8]) -> Vec<u8> {
let mut reader = TlvReader::new(bytes);
reader.next_element().unwrap().unwrap();
let depth = reader.depth();
let mut tags = Vec::new();
while let Some(element) = reader.next_element().unwrap() {
if reader.depth() < depth {
break;
}
if let Tag::Context(number) = element.tag {
tags.push(number);
}
reader.skip_value(&element).unwrap();
}
tags
}
#[test]
fn writing_node_label_and_location_enforces_their_constraints() {
let product = sample_product();
let attributes = Attributes::new(&product, false, false);
let clusters = [attributes.cluster()];
let endpoints = [Endpoint::new(0, &clusters)];
let node = Node::new(&endpoints);
let location = Location::region_agnostic();
let info = BasicInformation::new(&product, &location);
let ctx = InteractionContext::default();
let write = |id: u32, value: &str| {
let resolved = node.resolve(0, basic_information::ID, id).unwrap();
let mut buf = [0u8; 512];
let mut w = TlvWriter::new_in(&mut buf, ContainerKind::Structure);
w.utf8(Tag::Context(2), value).unwrap();
let encoded = w.finish().unwrap().to_vec();
info.write(&resolved, &encoded, matter_kit::im::WriteOp::Replace, &ctx)
};
assert_eq!(
write(basic_information::NODE_LABEL, "Kitchen light"),
Ok(())
);
assert_eq!(info.node_label().as_str(), "Kitchen light");
assert_eq!(
write(basic_information::NODE_LABEL, &"x".repeat(33)),
Err(Status::ConstraintError)
);
assert_eq!(info.node_label().as_str(), "Kitchen light");
assert_eq!(write(basic_information::LOCATION, "DE"), Ok(()));
assert_eq!(location.get(), *b"DE");
assert_eq!(
write(basic_information::LOCATION, "DEU"),
Err(Status::ConstraintError)
);
assert_eq!(
write(basic_information::LOCATION, "D"),
Err(Status::ConstraintError)
);
assert_eq!(location.get(), *b"DE");
assert_eq!(
write(basic_information::VENDOR_NAME, "Someone Else"),
Err(Status::UnsupportedWrite)
);
}
#[test]
fn reachable_changed_is_reported_only_on_an_actual_change() {
let product = sample_product();
let location = Location::region_agnostic();
let info = BasicInformation::new(&product, &location).with_reachable(true);
assert_eq!(info.reachable(), Some(true));
assert!(!info.set_reachable(true));
assert!(info.set_reachable(false));
assert_eq!(info.reachable(), Some(false));
let plain = BasicInformation::new(&product, &location);
assert_eq!(plain.reachable(), None);
assert!(!plain.set_reachable(false));
}
struct Device<'a> {
node: Node<'a>,
gc: GeneralCommissioning<'a>,
}
fn gc_clusters() -> [matter_kit::dm::ClusterDescriptor<'static>; 1] {
[general_commissioning::cluster()]
}
fn device<'a>(
endpoints: &'a [Endpoint<'a>],
location: &'a Location,
capability: RegulatoryLocation,
fail_safe: &'a RefCell<FailSafe>,
window: &'a RefCell<CommissioningWindow>,
) -> Device<'a> {
Device {
node: Node::new(endpoints),
gc: GeneralCommissioning::new(location, capability, fail_safe, window),
}
}
fn closed_window() -> RefCell<CommissioningWindow> {
RefCell::new(CommissioningWindow::new())
}
#[cfg(feature = "rustcrypto")]
fn open_a_window(window: &RefCell<CommissioningWindow>, now: Instant) {
use matter_kit::clusters::AdministratorCommissioning;
use matter_kit::clusters::administrator_commissioning::OpenWindowRequest;
use matter_kit::crypto::Spake2pVerifierData;
let fail_safe = RefCell::new(FailSafe::new(BasicCommissioningInfo::default()));
let no_vendor = |_: FabricIndex| None;
let admin = AdministratorCommissioning::new(window, &fail_safe, &no_vendor);
let verifier =
Spake2pVerifierData::from_passcode(20_202_021, &[0x42; 16], 1000).expect("verifier");
let bytes = verifier.to_bytes();
admin
.open_commissioning_window(
&OpenWindowRequest {
timeout_seconds: 300,
verifier: &bytes,
discriminator: 840,
iterations: 1000,
salt: &[0x42; 16],
},
&InteractionContext {
now,
..InteractionContext::default()
},
)
.expect("open");
}
fn fresh_fail_safe() -> RefCell<FailSafe> {
RefCell::new(FailSafe::new(BasicCommissioningInfo::default()))
}
fn at(seconds: u64) -> Instant {
Instant::ZERO.saturating_add(Duration::from_secs(seconds))
}
fn invoke_error(device: &Device<'_>, command: u32, fields: &[u8], ctx: &InteractionContext) -> u64 {
use matter_kit::im::{InvokeResponse, InvokeResponseMessage, Server};
let path = CommandPath::command(0, general_commissioning::ID, command);
let data = CommandData {
fields: Some(fields),
..CommandData::new(path)
};
let mut scratch = [0u8; 512];
let mut buf = [0u8; 2048];
let access = AllowAll;
let server = Server::new(device.node, &access, &device.gc, 8);
let (bytes, _) = server
.serve_invoke([Ok(data)], ctx, false, &mut scratch, &mut buf)
.expect("serve");
let response = InvokeResponseMessage::decode(bytes).expect("decode");
let mut responses = response.responses().expect("responses");
let first = responses.next().expect("one response").expect("decode");
match first {
InvokeResponse::Command(c) => {
assert_eq!(c.path.endpoint, Some(0));
assert_eq!(c.path.cluster, Some(general_commissioning::ID));
let fields = c.fields.expect("response fields");
let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
reader.next_element().unwrap().unwrap();
let error = reader.next_element().unwrap().unwrap();
assert_eq!(error.tag, Tag::Context(0));
error.unsigned().expect("an ErrorCode")
}
InvokeResponse::Status(s) => panic!("expected a response command, got {:?}", s.status),
}
}
fn arm_fields(expiry: u16, breadcrumb: u64) -> Vec<u8> {
let mut buf = [0u8; 64];
let mut w = TlvWriter::new_in(&mut buf, ContainerKind::Structure);
w.start_structure(Tag::Context(1)).unwrap();
w.unsigned(Tag::Context(0), u64::from(expiry)).unwrap();
w.unsigned(Tag::Context(1), breadcrumb).unwrap();
w.end_container().unwrap();
w.finish().unwrap().to_vec()
}
fn regulatory_fields(config: RegulatoryLocation, country: &str, breadcrumb: u64) -> Vec<u8> {
let mut buf = [0u8; 64];
let mut w = TlvWriter::new_in(&mut buf, ContainerKind::Structure);
w.start_structure(Tag::Context(1)).unwrap();
w.unsigned(Tag::Context(0), u64::from(config.value()))
.unwrap();
w.utf8(Tag::Context(1), country).unwrap();
w.unsigned(Tag::Context(2), breadcrumb).unwrap();
w.end_container().unwrap();
w.finish().unwrap().to_vec()
}
fn empty_struct() -> Vec<u8> {
let mut buf = [0u8; 8];
let mut w = TlvWriter::new_in(&mut buf, ContainerKind::Structure);
w.start_structure(Tag::Context(1)).unwrap();
w.end_container().unwrap();
w.finish().unwrap().to_vec()
}
fn over_pase(now: Instant) -> InteractionContext<'static> {
InteractionContext {
now,
..InteractionContext::default()
}
}
fn over_case(fabric: u8, now: Instant) -> InteractionContext<'static> {
InteractionContext {
fabric_index: Some(FabricIndex(fabric)),
now,
..InteractionContext::default()
}
}
#[test]
fn a_commissioning_flow_arms_configures_and_completes() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&arm_fields(60, 1),
&over_pase(at(0))
),
0
);
assert!(device.gc.fail_safe().is_armed(at(0)));
assert_eq!(device.gc.fail_safe().breadcrumb(), 1);
assert_eq!(
invoke_error(
&device,
general_commissioning::SET_REGULATORY_CONFIG,
®ulatory_fields(RegulatoryLocation::Indoor, "DE", 2),
&over_pase(at(1))
),
0
);
assert_eq!(location.get(), *b"DE");
assert_eq!(device.gc.regulatory_config(), RegulatoryLocation::Indoor);
assert_eq!(device.gc.fail_safe().breadcrumb(), 2);
device
.gc
.fail_safe_mut()
.record(at(2), |p| p.added_noc = true)
.unwrap();
device
.gc
.fail_safe_mut()
.adopt_fabric(FabricIndex(1), at(2))
.unwrap();
assert_eq!(
invoke_error(
&device,
general_commissioning::COMMISSIONING_COMPLETE,
&empty_struct(),
&over_case(1, at(3))
),
0
);
assert!(!device.gc.fail_safe().is_armed(at(3)));
assert_eq!(device.gc.fail_safe().breadcrumb(), 0);
assert_eq!(device.gc.take_aftermath(), Some(Aftermath::Commissioned));
}
#[test]
fn commissioning_complete_over_pase_is_refused_by_the_server_before_the_cluster() {
use matter_kit::im::{InvokeResponse, InvokeResponseMessage, Server};
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
device.gc.arm_fail_safe(60, 0, None, false, at(0));
let fields = empty_struct();
let data = CommandData {
fields: Some(&fields),
..CommandData::new(CommandPath::command(
0,
general_commissioning::ID,
general_commissioning::COMMISSIONING_COMPLETE,
))
};
let mut scratch = [0u8; 512];
let mut buf = [0u8; 2048];
let access = AllowAll;
let server = Server::new(device.node, &access, &device.gc, 8);
let (bytes, _) = server
.serve_invoke([Ok(data)], &over_pase(at(1)), false, &mut scratch, &mut buf)
.expect("serve");
let response = InvokeResponseMessage::decode(bytes).unwrap();
let first = response.responses().unwrap().next().unwrap().unwrap();
match first {
InvokeResponse::Status(s) => assert_eq!(s.status.status, Status::UnsupportedAccess),
InvokeResponse::Command(_) => panic!("a fabric-scoped command must not run over PASE"),
}
assert!(device.gc.fail_safe().is_armed(at(1)));
}
#[test]
fn set_regulatory_config_sets_location_even_when_the_mode_is_refused() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::Indoor,
&fail_safe,
&window,
);
assert_eq!(device.gc.regulatory_config(), RegulatoryLocation::Indoor);
assert_eq!(
invoke_error(
&device,
general_commissioning::SET_REGULATORY_CONFIG,
®ulatory_fields(RegulatoryLocation::Outdoor, "NL", 9),
&over_pase(at(0))
),
1 );
assert_eq!(device.gc.regulatory_config(), RegulatoryLocation::Indoor);
assert_eq!(location.get(), *b"NL");
assert_eq!(device.gc.fail_safe().breadcrumb(), 0);
}
#[test]
fn an_arm_fail_safe_conflict_is_reported_as_busy_with_other_admin() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&arm_fields(600, 1),
&over_case(1, at(0))
),
0
);
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&arm_fields(600, 2),
&over_case(2, at(1))
),
4 );
}
#[cfg(feature = "rustcrypto")]
#[test]
fn an_open_commissioning_window_reserves_the_failsafe_for_pase() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
open_a_window(&window, at(0));
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&arm_fields(600, 1),
&over_case(1, at(0))
),
4 );
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&arm_fields(600, 1),
&over_pase(at(0))
),
0
);
}
#[test]
fn a_lapsed_failsafe_is_reaped_by_the_next_command() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
device.gc.arm_fail_safe(60, 1, None, false, at(0));
device
.gc
.fail_safe_mut()
.record(at(1), |p| p.added_noc = true)
.unwrap();
device
.gc
.fail_safe_mut()
.adopt_fabric(FabricIndex(2), at(1))
.unwrap();
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&arm_fields(60, 5),
&over_pase(at(100))
),
0
);
let Some(Aftermath::Rollback(cleanup)) = device.gc.take_aftermath() else {
panic!("the lapsed context owed a rollback");
};
assert_eq!(cleanup.remove_fabric, Some(FabricIndex(2)));
}
#[test]
fn the_breadcrumb_round_trips_through_a_read_and_a_write() {
use matter_kit::im::Server;
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
let node = device.node;
let path = AttributePath::attribute(
0,
general_commissioning::ID,
general_commissioning::BREADCRUMB,
);
let mut buf = [0u8; 64];
let mut w = TlvWriter::new_in(&mut buf, ContainerKind::Structure);
w.unsigned(Tag::Context(2), 0xDEAD_BEEF).unwrap();
let encoded = w.finish().unwrap().to_vec();
let access = AllowAll;
let server = Server::new(node, &access, &device.gc, 8);
let mut out = [0u8; 1024];
server
.serve_write(
[Ok(AttributeData {
data_version: None,
path,
data: &encoded,
})],
&InteractionContext::default(),
false,
&mut out,
)
.expect("write");
assert_eq!(device.gc.fail_safe().breadcrumb(), 0xDEAD_BEEF);
let bytes = read_attribute(
node,
&device.gc,
0,
general_commissioning::ID,
general_commissioning::BREADCRUMB,
)
.unwrap();
assert_eq!(decode_u64(&bytes), 0xDEAD_BEEF);
}
#[test]
fn basic_commissioning_info_carries_both_timers() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
let bytes = read_attribute(
device.node,
&device.gc,
0,
general_commissioning::ID,
general_commissioning::BASIC_COMMISSIONING_INFO,
)
.unwrap();
let mut reader = TlvReader::new(&bytes);
reader.next_element().unwrap().unwrap();
let expiry = reader.next_element().unwrap().unwrap();
assert_eq!(expiry.tag, Tag::Context(0));
assert_eq!(expiry.unsigned().unwrap(), 900);
let cumulative = reader.next_element().unwrap().unwrap();
assert_eq!(cumulative.tag, Tag::Context(1));
assert_eq!(cumulative.unsigned().unwrap(), 900);
}
#[test]
fn a_tuple_of_clusters_dispatches_on_the_cluster_id() {
let product = sample_product();
let attributes = Attributes::new(&product, false, false);
let location = Location::region_agnostic();
let clusters = [
descriptor::cluster(),
attributes.cluster(),
general_commissioning::cluster(),
];
let endpoints = [Endpoint::new(0, &clusters).with_device_types(DEVICE_TYPES)];
let node = Node::new(&endpoints);
node.validate().expect("well formed");
let fail_safe = fresh_fail_safe();
let window = closed_window();
let handler = (
Descriptor::new(node, 0),
BasicInformation::new(&product, &location),
GeneralCommissioning::new(
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
),
);
assert_eq!(
decode_u64_array(
&read_attribute(node, &handler, 0, descriptor::ID, descriptor::SERVER_LIST).unwrap()
),
vec![
u64::from(descriptor::ID),
u64::from(basic_information::ID),
u64::from(general_commissioning::ID),
]
);
assert_eq!(
decode_utf8(
&read_attribute(
node,
&handler,
0,
basic_information::ID,
basic_information::VENDOR_NAME
)
.unwrap()
),
"Test Vendor"
);
assert_eq!(
decode_u64(
&read_attribute(
node,
&handler,
0,
general_commissioning::ID,
general_commissioning::LOCATION_CAPABILITY
)
.unwrap()
),
2
);
}
#[test]
fn the_cluster_trait_ids_agree_with_the_module_constants() {
assert_eq!(<Descriptor<'_> as Cluster>::ID, descriptor::ID);
assert_eq!(<BasicInformation<'_> as Cluster>::ID, basic_information::ID);
assert_eq!(
<GeneralCommissioning<'_> as Cluster>::ID,
general_commissioning::ID
);
}
#[test]
fn a_truncated_command_is_rejected_not_defaulted() {
let clusters = gc_clusters();
let endpoints = [Endpoint::new(0, &clusters)];
let location = Location::region_agnostic();
let fail_safe = fresh_fail_safe();
let window = closed_window();
let device = device(
&endpoints,
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
let whole = arm_fields(60, 1);
for cut in 1..whole.len() {
let truncated = whole.get(..cut).expect("in range");
let status = invoke_status(&device, general_commissioning::ARM_FAIL_SAFE, truncated);
assert!(
!device.gc.fail_safe().is_armed(at(0)),
"a {cut}-octet ArmFailSafe armed the fail-safe: {status:?}"
);
assert_eq!(device.gc.fail_safe().breadcrumb(), 0);
}
assert_eq!(
invoke_error(
&device,
general_commissioning::ARM_FAIL_SAFE,
&whole,
&over_pase(at(0))
),
0
);
}
fn invoke_status(device: &Device<'_>, command: u32, fields: &[u8]) -> Result<u32, Status> {
use matter_kit::im::{InvokeResponse, InvokeResponseMessage, Server};
let data = CommandData {
fields: Some(fields),
..CommandData::new(CommandPath::command(0, general_commissioning::ID, command))
};
let mut scratch = [0u8; 512];
let mut buf = [0u8; 2048];
let access = AllowAll;
let server = Server::new(device.node, &access, &device.gc, 8);
let Ok((bytes, _)) =
server.serve_invoke([Ok(data)], &over_pase(at(0)), false, &mut scratch, &mut buf)
else {
return Err(Status::InvalidAction);
};
let response = InvokeResponseMessage::decode(bytes).expect("decode");
match response
.responses()
.expect("responses")
.next()
.expect("one")
.expect("decode")
{
InvokeResponse::Command(c) => Ok(c.path.command.unwrap_or(0)),
InvokeResponse::Status(s) => Err(s.status.status),
}
}
#[test]
fn capability_minima_carries_the_revision_6_fields_by_default() {
let product = sample_product();
let attributes = Attributes::new(&product, false, false);
let clusters = [attributes.cluster()];
let endpoints = [Endpoint::new(0, &clusters)];
let node = Node::new(&endpoints);
let location = Location::region_agnostic();
let info = BasicInformation::new(&product, &location);
let bytes = read_attribute(
node,
&info,
0,
basic_information::ID,
basic_information::CAPABILITY_MINIMA,
)
.unwrap();
assert_eq!(
struct_tags(&bytes),
vec![0, 1, 2, 3, 4, 5],
"a revision-6 cluster sent a pre-revision-6 CapabilityMinimaStruct"
);
}
#[cfg(feature = "rustcrypto")]
#[test]
fn capability_minima_reports_the_tables_it_describes() {
use matter_kit::config::{Capacity, Config, DefaultConfig, SubscriptionCapacity};
use matter_kit::im::SubscriptionTable;
use matter_kit::session::SessionTable;
type Sessions = SessionTable<DefaultConfig, 16>;
type Subs = SubscriptionTable<DefaultConfig>;
let minima = CapabilityMinima::from_tables::<DefaultConfig, Sessions, Subs>();
assert_eq!(
minima.read_paths,
Some(DefaultConfig::READ_PATHS as u16),
"ReadPathsSupported must be §2.11.2.1's real limit"
);
assert_eq!(
minima.subscribe_paths,
Some(<Subs as SubscriptionCapacity>::PATHS as u16),
"SubscribePathsSupported must be the table's own path width"
);
assert_eq!(
minima.subscriptions_per_fabric,
<Subs as Capacity>::PER_FABRIC as u16
);
assert_eq!(
minima.case_sessions_per_fabric,
<Sessions as Capacity>::PER_FABRIC as u16,
"CaseSessionsPerFabric is the session table divided among the fabrics, not a floor"
);
assert!(minima.case_sessions_per_fabric >= 3);
assert!(minima.simultaneous_invocations.is_some_and(|n| n >= 1));
assert!(minima.simultaneous_writes.is_some_and(|n| n >= 1));
}