#![allow(
clippy::expect_used,
clippy::indexing_slicing,
clippy::arithmetic_side_effects,
clippy::print_stdout,
clippy::too_many_lines,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
use core::cell::RefCell;
use core::future::poll_fn;
use core::pin::pin;
use core::task::Poll;
use matter_kit::acl::{Acl, AclAccess, SubjectDescriptor};
use matter_kit::attestation::factory::DevelopmentChain;
use matter_kit::clusters::access_control::{self, AccessControl};
use matter_kit::clusters::administrator_commissioning::{self, AdministratorCommissioning};
use matter_kit::clusters::basic_information::{
Attributes, BasicInformation, CapabilityMinima, Location, Product,
};
use matter_kit::clusters::binding::{self, Binding};
use matter_kit::clusters::descriptor::{self, Descriptor};
use matter_kit::clusters::general_commissioning::{self, GeneralCommissioning, RegulatoryLocation};
use matter_kit::clusters::general_diagnostics::{
self, BootReason, Diagnostics, GeneralDiagnostics,
};
use matter_kit::clusters::generated::device_types::ON_OFF_LIGHT;
use matter_kit::clusters::group_key_management::{self, GroupKeyManagement};
use matter_kit::clusters::groups::{self, Groups};
use matter_kit::clusters::identify::{
EffectIdentifierEnum, EffectVariantEnum, Identify, IdentifyHooks, IdentifyTypeEnum,
};
use matter_kit::clusters::label::{self, FixedLabel, Label, UserLabel};
use matter_kit::clusters::on_off::{self, OnOff, OnOffHooks};
use matter_kit::clusters::operational_credentials::{
self as opcreds, DeviceAttestation, OperationalCredentials,
};
use matter_kit::clusters::scenes::{self, ExtensionFieldSetStruct, SceneHooks, SceneTable, Scenes};
use matter_kit::clusters::{At, Endpoints};
use matter_kit::commissioning::failsafe::{BasicCommissioningInfo, FailSafe};
use matter_kit::commissioning::window::{CommissioningWindow, WindowStatus};
use matter_kit::config::{Config, DefaultConfig};
use matter_kit::crypto::{KeyPurpose, KeyStore, SoftKeyStore, Spake2pVerifierData};
use matter_kit::discovery::responder::{Advertisement, Responder};
use matter_kit::discovery::txt::{CommissionableTxt, CommissioningMode, OperationalTxt};
use matter_kit::discovery::{COMMISSIONABLE_SERVICE, MDNS_PORT, OPERATIONAL_SERVICE};
use matter_kit::dm::spec::Optional;
use matter_kit::dm::{DataVersions, DeviceType, Endpoint, Node};
use matter_kit::fabric::FabricTable;
use matter_kit::im::{
ClusterHandler, Dispatcher, InteractionContext, Lifecycle, NewSubscription, ReadCursor,
ReportReason, Request, Served, Server, SubscribeResponse, SubscriptionPolicy,
SubscriptionTable,
};
use matter_kit::messaging::{Due, Messaging, Received};
use matter_kit::msg::{FabricIndex, NodeId, ProtocolId, SessionId, VendorId};
use matter_kit::platform::os::{StdRng, StdTimer, StdUdp, block_on};
use matter_kit::platform::{Instant, Peer, PeerAddr, Rng, Timer, Udp};
use matter_kit::sc::PbkdfParameters;
use matter_kit::session::SessionKind;
const PASSCODE: u32 = 20_202_021;
const ITERATIONS: u32 = 10_000;
const DISCRIMINATOR: u16 = 3840;
const VENDOR: VendorId = VendorId(0xFFF1);
const PRODUCT_ID: u16 = 0x8000;
const PRODUCT: Product<'static> = Product::new(
"Example Vendor",
VENDOR,
"matter-kit light",
PRODUCT_ID,
"matter-kit-light-0001",
)
.with_capability_minima(CapabilityMinima::from_tables::<
DefaultConfig,
Sessions,
Subscriptions,
>());
const ACL_ENTRIES: usize = 20;
const ACL_SUBJECTS: usize = 4;
const ACL_TARGETS: usize = 3;
const FIXED_LABELS: &[Label<'static>] = &[match Label::new("model", "matter-kit") {
Some(l) => l,
None => panic!("within §9.7.4.1's 16 characters"),
}];
const DEFAULT_IFINDEX: u32 = 1;
const CERTIFICATION_DECLARATION: &[u8] = &[
0x30, 0x81, 0xe8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02, 0xa0, 0x81,
0xda, 0x30, 0x81, 0xd7, 0x02, 0x01, 0x03, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48,
0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x30, 0x45, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
0x01, 0x07, 0x01, 0xa0, 0x38, 0x04, 0x36, 0x15, 0x24, 0x00, 0x01, 0x25, 0x01, 0xf1, 0xff, 0x36,
0x02, 0x05, 0x00, 0x80, 0x18, 0x25, 0x03, 0x34, 0x12, 0x2c, 0x04, 0x13, 0x5a, 0x49, 0x47, 0x32,
0x30, 0x31, 0x34, 0x31, 0x5a, 0x42, 0x33, 0x33, 0x30, 0x30, 0x30, 0x31, 0x2d, 0x32, 0x34, 0x24,
0x05, 0x00, 0x24, 0x06, 0x00, 0x25, 0x07, 0x94, 0x26, 0x24, 0x08, 0x00, 0x18, 0x31, 0x7c, 0x30,
0x7a, 0x02, 0x01, 0x03, 0x80, 0x14, 0x62, 0xfa, 0x82, 0x33, 0x59, 0xac, 0xfa, 0xa9, 0x96, 0x3e,
0x1c, 0xfa, 0x14, 0x0a, 0xdd, 0xf5, 0x04, 0xf3, 0x71, 0x60, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86,
0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
0x04, 0x03, 0x02, 0x04, 0x46, 0x30, 0x44, 0x02, 0x20, 0x43, 0xa6, 0x3f, 0x2b, 0x94, 0x3d, 0xf3,
0x3c, 0x38, 0xb3, 0xe0, 0x2f, 0xca, 0xa7, 0x5f, 0xe3, 0x53, 0x2a, 0xeb, 0xbf, 0x5e, 0x63, 0xf5,
0xbb, 0xdb, 0xc0, 0xb1, 0xf0, 0x1d, 0x3c, 0x4f, 0x60, 0x02, 0x20, 0x4c, 0x1a, 0xbf, 0x5f, 0x18,
0x07, 0xb8, 0x18, 0x94, 0xb1, 0x57, 0x6c, 0x47, 0xe4, 0x72, 0x4e, 0x4d, 0x96, 0x6c, 0x61, 0x2e,
0xd3, 0xfa, 0x25, 0xc1, 0x18, 0xc3, 0xf2, 0xb3, 0xf9, 0x03, 0x69,
];
const ROOT_NODE: &[DeviceType] = &[DeviceType::new(0x0016, 3)];
const ON_OFF_LIGHT_TYPE: &[DeviceType] = &[DeviceType::new(ON_OFF_LIGHT.id, ON_OFF_LIGHT.revision)];
const GROUPS_PER_FABRIC: usize = 4;
const GROUP_SLOTS: usize = 16;
const SCENE_SLOTS: usize = 16;
const SCENE_BYTES: usize = 128;
const FABRICS: usize = 5;
type GroupTable<'a> =
Groups<'a, GROUP_SLOTS, Identify<'a, Lamp>, SceneTable<SCENE_SLOTS, SCENE_BYTES, FABRICS>>;
type Stack = Messaging<DefaultConfig, 16, 64>;
type Subscriptions = SubscriptionTable<DefaultConfig>;
type Sessions = matter_kit::session::SessionTable<DefaultConfig, 16>;
#[derive(Debug, Clone, Copy)]
struct PendingSubscribe {
id: u32,
max_interval_s: u16,
more_chunks: bool,
}
struct Memberships<'a>(&'a GroupTable<'a>);
impl group_key_management::GroupTable for Memberships<'_> {
fn memberships(
&self,
each: &mut dyn FnMut(
matter_kit::msg::FabricIndex,
matter_kit::msg::GroupId,
matter_kit::im::EndpointId,
),
) {
for membership in self.0.memberships().iter() {
each(membership.fabric, membership.group, 1);
}
}
fn name(
&self,
fabric: matter_kit::msg::FabricIndex,
group: matter_kit::msg::GroupId,
) -> Option<&str> {
let _ = (fabric, group);
None
}
}
#[derive(Debug)]
struct Interaction {
read_cursor: ReadCursor,
pending_read: heapless::Vec<u8, 1024>,
pending_subscribe: Option<PendingSubscribe>,
}
impl Default for Interaction {
fn default() -> Self {
Self {
read_cursor: ReadCursor::START,
pending_read: heapless::Vec::new(),
pending_subscribe: None,
}
}
}
impl Interaction {
fn idle(&self) -> bool {
self.pending_read.is_empty() && self.pending_subscribe.is_none()
}
}
#[derive(Debug, Default)]
struct Interactions {
entries: heapless::Vec<(matter_kit::exchange::ExchangeKey, Instant, Interaction), 8>,
}
impl Interactions {
fn new() -> Self {
Self::default()
}
fn get(&mut self, key: matter_kit::exchange::ExchangeKey, now: Instant) -> &mut Interaction {
let expiry = now.saturating_sub(matter_kit::exchange::EXCHANGE_IDLE_TIMEOUT);
self.entries
.retain(|(k, seen, _)| *k == key || *seen > expiry);
if let Some(index) = self.entries.iter().position(|(k, _, _)| *k == key) {
self.entries[index].1 = now;
return &mut self.entries[index].2;
}
if self.entries.is_full() {
self.entries.remove(0);
}
let _ = self.entries.push((key, now, Interaction::default()));
&mut self
.entries
.last_mut()
.expect("just pushed, and the table was made room for")
.2
}
fn idle(&self, key: matter_kit::exchange::ExchangeKey) -> bool {
self.entries
.iter()
.find(|(k, _, _)| *k == key)
.is_none_or(|(_, _, state)| state.idle())
}
fn priming(&self, subscription: u32) -> bool {
self.entries.iter().any(|(_, _, state)| {
state
.pending_subscribe
.is_some_and(|p| p.id == subscription)
})
}
fn len(&self) -> usize {
self.entries.len()
}
fn forget(&mut self, key: matter_kit::exchange::ExchangeKey) {
self.entries.retain(|(k, _, _)| *k != key);
}
}
#[derive(Debug, Clone, Copy, Default)]
struct SubscriptionContext {
session: Option<SessionId>,
fabric_index: Option<FabricIndex>,
peer_node_id: Option<NodeId>,
}
enum Event {
Matter(usize, PeerAddr),
Mdns(usize),
Deadline,
}
fn main() {
let timer = StdTimer::new();
let rng = StdRng;
let matter_socket = match StdUdp::bind(matter_kit::PORT) {
Ok(socket) => socket,
Err(e) => {
println!("could not bind UDP {} ({e:?})", matter_kit::PORT);
println!("another Matter node is probably already running.");
return;
}
};
let advertise_addr: Option<[u8; 16]> = std::env::var("MATTER_ADVERTISE_ADDR")
.ok()
.and_then(|v| v.parse::<std::net::Ipv6Addr>().ok())
.map(|a| a.octets());
let scope_id: u32 = std::env::var("MATTER_IFINDEX")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(DEFAULT_IFINDEX);
let mdns_socket = match StdUdp::bind_mdns(scope_id) {
Ok(socket) => socket,
Err(e) => {
println!("could not bind mDNS ({e:?}); the node will not be discoverable.");
return;
}
};
let Some(mdns_group) = mdns_socket.mdns_group() else {
println!("the mDNS socket has no group to answer on");
return;
};
let location = Location::region_agnostic();
let attributes = Attributes::new(&PRODUCT, false, false);
let diagnostics_descriptor = general_diagnostics::conforming(0, &Optional::NONE)
.expect("the const parameters hold the mandatory set");
let lamp_descriptor = OnOff::<Lamp>::conforming(on_off::feature::LIGHTING, &Optional::NONE)
.expect("the const parameters hold the Lighting set");
let identify_descriptor = Identify::<Lamp>::conforming(&Identify::<Lamp>::WITH_TRIGGER_EFFECT)
.expect("the const parameters hold the Identify set");
let groups_descriptor =
Groups::<GROUP_SLOTS>::conforming(groups::feature::GROUP_NAMES, &Optional::NONE)
.expect("the const parameters hold the Groups set");
let group_key_descriptor =
GroupKeyManagement::<DefaultConfig, Memberships<'_>>::conforming(0, &Optional::NONE)
.expect("the const parameters hold the Group Key Management set");
let scenes_descriptor =
Scenes::<Lamp, GroupTable, SCENE_SLOTS, SCENE_BYTES, FABRICS>::conforming(
scenes::feature::SCENE_NAMES,
&Scenes::<Lamp, GroupTable, SCENE_SLOTS, SCENE_BYTES, FABRICS>::WITH_COPY_SCENE,
)
.expect("the const parameters hold the Scenes set");
let clusters = [
descriptor::cluster(), binding::cluster(), access_control::cluster(), attributes.cluster(), general_commissioning::cluster(), diagnostics_descriptor.descriptor(), administrator_commissioning::cluster(), opcreds::cluster(), group_key_descriptor.descriptor(), label::fixed_cluster(), label::user_cluster(), ];
let lamp_clusters = [
identify_descriptor.descriptor(), groups_descriptor.descriptor(), lamp_descriptor.descriptor(), descriptor::cluster(), scenes_descriptor.descriptor(), ];
let endpoints = [
Endpoint::new(0, &clusters).with_device_types(ROOT_NODE),
Endpoint::new(1, &lamp_clusters).with_device_types(ON_OFF_LIGHT_TYPE),
];
let node = Node::new(&endpoints);
node.validate().expect("the clusters are sorted by id");
let keys = RefCell::new(SoftKeyStore::<8>::new());
let mut scratch_cert = [0u8; 1024];
let mut paa_der: heapless::Vec<u8, 1024> = heapless::Vec::new();
let mut pai_der: heapless::Vec<u8, 1024> = heapless::Vec::new();
let mut dac_der: heapless::Vec<u8, 1024> = heapless::Vec::new();
let dac_key = {
let mut store = keys.borrow_mut();
let mut seed = [0u8; 32];
let mut fresh = |store: &mut SoftKeyStore<8>| {
rng.fill(&mut seed).expect("rng");
store
.generate(KeyPurpose::DeviceAttestation, &seed)
.expect("generate an attestation key")
};
let (paa_key, _) = fresh(&mut store);
let (pai_key, pai_public) = fresh(&mut store);
let (dac_key, dac_public) = fresh(&mut store);
let now_unix = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0u64, |d| d.as_secs());
let not_before = u32::try_from(
now_unix.saturating_sub(u64::try_from(matter_kit::der::MATTER_EPOCH_UNIX).unwrap_or(0)),
)
.unwrap_or(0);
let chain = DevelopmentChain::new(not_before, 10);
paa_der
.extend_from_slice(chain.paa(&*store, &mut scratch_cert, paa_key).expect("PAA"))
.expect("the PAA fits");
pai_der
.extend_from_slice(
chain
.pai(&*store, &mut scratch_cert, paa_key, &pai_public)
.expect("PAI"),
)
.expect("the PAI fits");
dac_der
.extend_from_slice(
chain
.dac(&*store, &mut scratch_cert, pai_key, &dac_public, PRODUCT_ID)
.expect("DAC"),
)
.expect("the DAC fits");
dac_key
};
let paa_der = &paa_der[..];
let pai_der = &pai_der[..];
let dac_der = &dac_der[..];
if let Ok(dir) = std::env::var("MATTER_PAA_OUT") {
let path = std::path::Path::new(&dir).join("matter-kit-dev-paa.der");
match std::fs::write(&path, paa_der) {
Ok(()) => println!(" PAA written to {}", path.display()),
Err(e) => println!(" could not write the PAA to {} ({e})", path.display()),
}
}
let fabrics = RefCell::new(FabricTable::<DefaultConfig, { DefaultConfig::FABRICS }>::new());
let rng_cell = RefCell::new(StdRng);
let fail_safe = RefCell::new(FailSafe::new(BasicCommissioningInfo::default()));
let window = RefCell::new(CommissioningWindow::new());
let vendor_of_fabric = |index: matter_kit::msg::FabricIndex| {
fabrics.borrow().find(index).map(|f| f.admin_vendor_id)
};
let general_commissioning = GeneralCommissioning::new(
&location,
RegulatoryLocation::IndoorOutdoor,
&fail_safe,
&window,
);
let admin_commissioning =
AdministratorCommissioning::new(&window, &fail_safe, &vendor_of_fabric);
let acl = RefCell::new(Acl::<DefaultConfig, ACL_ENTRIES, ACL_SUBJECTS, ACL_TARGETS>::new());
let access_control_cluster = AccessControl::new(&acl);
let bindings = Binding::<DefaultConfig, 8>::new(4);
let user_labels = UserLabel::<4>::new();
let diagnostics = Uptime::new(&timer);
let lamp = Lamp::default();
let lamp_cluster = OnOff::new(&lamp, on_off::feature::LIGHTING, None);
lamp_cluster.start(false);
let scene_table = SceneTable::<SCENE_SLOTS, SCENE_BYTES, FABRICS>::new(true);
let identify_cluster = Identify::new(&lamp, IdentifyTypeEnum::LightOutput);
let groups_cluster: GroupTable<'_> =
Groups::with(GROUPS_PER_FABRIC, true, &identify_cluster, &scene_table);
let scenes_cluster = Scenes::new(&scene_table, &groups_cluster, &lamp, true);
let memberships = Memberships(&groups_cluster);
let group_keys = RefCell::new(matter_kit::group::GroupKeys::<DefaultConfig>::new());
let group_keys_cluster = GroupKeyManagement::new(&group_keys, &memberships);
let opcreds = OperationalCredentials::new(
&fabrics,
&keys,
&rng_cell,
&fail_safe,
DeviceAttestation {
dac: dac_der,
pai: pai_der,
certification_declaration: CERTIFICATION_DECLARATION,
dac_key,
firmware_information: None,
},
);
let handler = Endpoints((
At::new(
0,
(
Descriptor::new(node, 0).with_parts(&[1]),
&bindings,
&access_control_cluster,
BasicInformation::new(&PRODUCT, &location),
&general_commissioning,
GeneralDiagnostics::new(&diagnostics, 0),
&admin_commissioning,
&opcreds,
&group_keys_cluster,
FixedLabel::new(FIXED_LABELS),
&user_labels,
),
),
At::new(
1,
(
Descriptor::new(node, 1),
&identify_cluster,
&groups_cluster,
&lamp_cluster,
&scenes_cluster,
),
),
));
let versions = DataVersions::<16>::new(rng.next_u32().expect("rng"));
let events = RefCell::new(matter_kit::dm::events::EventStore::<4, 4, 4>::new({
let mut numbers = matter_kit::dm::events::EventNumbers::restore(0);
if let Some(owed) = numbers.reservation() {
numbers.reserved(owed);
}
numbers
}));
let txt = CommissionableTxt {
discriminator: DISCRIMINATOR,
vendor_id: Some(VENDOR),
product_id: Some(PRODUCT_ID),
commissioning_mode: CommissioningMode::Basic,
..CommissionableTxt::default()
}
.encode()
.expect("the advertisement fits");
let txt = txt.finish();
let long_subtype = format!("_L{DISCRIMINATOR}");
let short_subtype = format!("_S{}", DISCRIMINATOR >> 8);
let advertisement = Advertisement::new(
"0011223344556677",
COMMISSIONABLE_SERVICE,
"0011223344556677",
matter_kit::PORT,
txt,
)
.with_subtype(&long_subtype)
.expect("subtype")
.with_subtype(&short_subtype)
.expect("subtype")
.with_subtype("_CM")
.expect("subtype");
let commissionable = match advertise_addr {
Some(address) => advertisement.with_address(address).expect("address"),
None => advertisement,
};
let mut salt = [0u8; matter_kit::crypto::PBKDF_SALT_MIN_BYTES];
for chunk in salt.chunks_mut(4) {
let word = rng.next_u32().expect("rng").to_le_bytes();
for (slot, byte) in chunk.iter_mut().zip(word) {
*slot = byte;
}
}
let parameters = PbkdfParameters::new(ITERATIONS, &salt).expect("parameters");
let verifier =
Spake2pVerifierData::from_passcode(PASSCODE, &salt, ITERATIONS).expect("verifier");
let mut stack = Stack::new(
rng.next_u32().expect("rng") as u16 | 1,
rng.next_u32().expect("rng") as u16,
rng.next_u32().expect("rng"),
);
let mut dispatcher: Dispatcher<4> = Dispatcher::new(PRODUCT.max_paths_per_invoke);
let mut interactions = Interactions::new();
let mut subscriptions = Subscriptions::new();
let mut group_peers = matter_kit::group::PeerTable::<4, 2>::new();
let mut joined: std::collections::BTreeSet<[u8; 16]> = std::collections::BTreeSet::new();
let mut reporting: heapless::Vec<(u32, matter_kit::exchange::ExchangeKey), 8> =
heapless::Vec::new();
let mut channel = matter_kit::sc::Channel::new();
let mut window_was_open = false;
println!("matter-kit light");
println!(" UDP :{}", matter_kit::PORT);
println!(" mDNS :{MDNS_PORT} (ff02::fb, interface {scope_id})");
println!(" passcode {PASSCODE}");
println!(" discriminator {DISCRIMINATOR}");
println!("\n chip-tool pairing onnetwork 1 {PASSCODE}\n");
block_on(async {
let mut matter_buf = [0u8; 1280];
let mut mdns_buf = [0u8; 1280];
let mut out = [0u8; 1280];
let mut payload = [0u8; matter_kit::config::MAX_UDP_PAYLOAD];
let mut scratch = [0u8; opcreds::max_nocs_len(DefaultConfig::FABRICS)];
let mut frame_buf = [0u8; 1280];
let mut evict_buf = [0u8; 1280];
loop {
let now = timer.now();
let window_open = window.borrow().open(now).is_some();
if window_open && !window_was_open {
channel.reopen();
println!(" commissioning window open — the channel admits PASE again");
}
window_was_open = window_open;
if window_open && channel.is_established() && fail_safe.borrow().armed(now).is_none() {
channel.release();
println!(" commissioning finished and the window is open — PASE admitted again");
}
for (endpoint, cluster) in versions.drain_changes() {
let dirtied = subscriptions.note_cluster_change(endpoint, cluster);
println!(
" change: endpoint {endpoint} cluster {cluster:#06x} -> {dirtied} subscription(s)"
);
}
let due_now: heapless::Vec<(u32, ReportReason), 15> = subscriptions
.due(now)
.filter(|(s, _)| !interactions.priming(s.id))
.map(|(s, reason)| (s.id, reason))
.collect();
for (id, reason) in due_now {
if reporting.iter().any(|(pending, _)| *pending == id) {
continue;
}
if reporting.is_full() {
println!(" reports already in flight; subscription {id} waits");
break;
}
let Some(session) = subscriptions.find(id).and_then(|s| s.session) else {
println!(" subscription {id} is due but has no session to report on");
continue;
};
let Some(subscription) = subscriptions.find(id) else {
continue;
};
let subject = match (subscription.fabric_index, subscription.peer_node_id) {
(Some(fabric), Some(node_id)) => SubjectDescriptor::case(fabric, node_id),
_ => SubjectDescriptor::unauthenticated(),
};
let access = AclAccess::new(&acl, node, &subject);
let server = Server::new(node, &access, &handler, 24)
.with_data_versions(&versions)
.with_events(&events);
let mut ctx = InteractionContext::new().at(now);
if let Some(fabric) = subscription.fabric_index {
ctx = ctx.with_fabric(fabric);
}
let Some(subscription) = subscriptions.find_mut(id) else {
continue;
};
let report =
server.report_chunk(subscription, reason, &ctx, &mut scratch, &mut payload);
let Ok((bytes, _)) = report else {
println!(" could not build a report for subscription {id}");
continue;
};
let len = bytes.len();
let Ok(exchange) = stack.open(session, ProtocolId::INTERACTION_MODEL, now) else {
println!(" no exchange for subscription {id}");
continue;
};
let randomness = rng.next_u32().expect("rng");
let framed = match stack.send(
exchange,
matter_kit::im::opcode::REPORT_DATA,
true,
&payload[..len],
now,
randomness,
&mut frame_buf,
&mut out,
) {
Ok((sent, _)) => Some(sent),
Err(e) => {
println!(" subscription {id}: report could not be framed: {e}");
None
}
};
let addr = match stack.peer(exchange) {
Some(Peer::Udp(addr)) => Some(addr),
other => {
println!(" subscription {id}: nowhere to send the report: {other:?}");
None
}
};
let mut delivered = false;
if let (Some(sent), Some(addr)) = (framed, addr) {
match matter_socket.send_to(&out[..sent], addr).await {
Ok(_) => {
let _ = reporting.push((id, exchange));
delivered = true;
}
Err(e) => println!(" subscription {id}: report not sent: {e}"),
}
}
if !delivered {
stack.close(exchange);
continue;
}
if let Some(subscription) = subscriptions.find_mut(id) {
subscription.reported(now);
}
}
while let Some(due) = stack.poll(now, rng.next_u32().expect("rng")) {
match due {
Due::Acknowledge { exchange } => {
if let Ok(len) = stack.acknowledge(exchange, now, &mut out)
&& len > 0
&& let Some(Peer::Udp(addr)) = stack.peer(exchange)
{
match matter_socket.send_to(&out[..len], addr).await {
Ok(()) => println!(" standalone ack"),
Err(e) => println!(" standalone ack failed: {e}"),
}
}
if matches!(exchange.role, matter_kit::exchange::Role::Responder)
&& interactions.idle(exchange)
{
interactions.forget(exchange);
stack.close(exchange);
}
}
Due::Retransmit { .. } => {}
Due::Abandoned { exchange } => {
reporting.retain(|(_, sent_on)| *sent_on != exchange);
interactions.forget(exchange);
println!(" gave up on exchange {:?}", exchange.id);
}
}
}
let deadline = [
stack.wake_at(),
channel.deadline(),
subscriptions.next_deadline(),
]
.into_iter()
.flatten()
.min()
.unwrap_or_else(|| now.saturating_add(matter_kit::platform::Duration::from_secs(1)));
let event = {
let mut matter = pin!(matter_socket.recv_from(&mut matter_buf));
let mut mdns = pin!(mdns_socket.recv_from(&mut mdns_buf));
let mut sleep = pin!(timer.sleep_until(deadline));
poll_fn(|cx| {
if let Poll::Ready(Ok((n, from))) = matter.as_mut().poll(cx) {
return Poll::Ready(Event::Matter(n, from));
}
if let Poll::Ready(Ok((n, from))) = mdns.as_mut().poll(cx) {
let _ = from;
return Poll::Ready(Event::Mdns(n));
}
if sleep.as_mut().poll(cx).is_ready() {
return Poll::Ready(Event::Deadline);
}
Poll::Pending
})
.await
};
let now = timer.now();
match event {
Event::Matter(n, from) => {
let received = match stack.receive(&mut matter_buf[..n], Peer::Udp(from), now) {
Ok(received) => received,
Err(e) => {
println!(" dropped a datagram: {e}");
let mut census: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
for open in stack.exchanges().iter() {
*census
.entry(format!("{:?}/{:?}", open.protocol, open.key.role))
.or_default() += 1;
}
println!(
" EXCHANGES {} open: {census:?} | interactions {}",
stack.exchanges().len(),
interactions.len()
);
continue;
}
};
for (fabric_id, group) in joined_groups(&fabrics, &groups_cluster) {
let address = matter_kit::group::multicast_address(fabric_id, group);
if joined.insert(address.addr) {
match matter_socket.join_multicast(address.addr, scope_id) {
Ok(()) => println!(" joined {group:?} at {address:?}"),
Err(e) => println!(" could not join {group:?}: {e}"),
}
}
}
if let Received::Group { .. } = received {
let mut original = [0u8; 1280];
let keys = group_keys.borrow();
let compressed = |index: matter_kit::msg::FabricIndex| {
fabrics.borrow().find(index).map(|f| f.compressed)
};
let inbound = matter_kit::group::wire::receive(
&mut matter_buf[..n],
from,
&keys,
&mut group_peers,
compressed,
&mut original,
);
match inbound {
Ok(matter_kit::group::wire::Received::Message(message)) => {
let request = Request {
opcode: message.protocol.opcode,
payload: message.payload,
session: None,
exchange: message.protocol.exchange_id,
groupcast: true,
};
let subject = SubjectDescriptor::group(
message.context.fabric_index,
message.context.group,
);
let access = AclAccess::new(&acl, node, &subject);
let server = Server::new(node, &access, &handler, 24)
.with_data_versions(&versions)
.with_events(&events);
let ctx = InteractionContext::new()
.at(now)
.with_fabric(message.context.fabric_index)
.with_group(message.context.group);
let mut dispatcher_cursor = ReadCursor::START;
match dispatcher.dispatch(
&server,
request,
&ctx,
&mut dispatcher_cursor,
&mut scratch,
&mut payload,
) {
Ok(Served::Silent) => println!(
" groupcast to {:?} acted on",
message.context.group
),
Ok(other) => println!(
" groupcast to {:?}: {other:?} — and nothing is sent",
message.context.group
),
Err(e) => println!(" groupcast refused: {e}"),
}
}
Ok(other) => println!(" group datagram dropped: {other:?}"),
Err(e) => println!(" group datagram refused: {e}"),
}
continue;
}
let (exchange, header, body) = match received {
Received::Message {
exchange,
header,
payload,
..
} => (exchange, header, payload.to_vec()),
Received::Duplicate { exchange, .. } => {
let len = stack.acknowledge(exchange, now, &mut out).unwrap_or(0);
if len > 0 {
let _ = matter_socket.send_to(&out[..len], from).await;
}
continue;
}
Received::SessionClosed { session } => {
let dropped = subscriptions.remove_for_session(Some(session));
reporting.retain(|(_, sent_on)| sent_on.session != session);
channel.closed(session);
println!(
" peer closed session {session:?} — {dropped} subscription(s) \
went with it"
);
continue;
}
Received::Acknowledged { exchange } => {
reporting.retain(|(_, sent_on)| *sent_on != exchange);
if interactions.idle(exchange) {
interactions.forget(exchange);
stack.close(exchange);
}
continue;
}
other => {
println!(" unhandled reception: {other:?}");
continue;
}
};
let mut evicted_report: Option<matter_kit::messaging::Evicted> = None;
let reply = if header.protocol == ProtocolId::SECURE_CHANNEL {
let ctx = matter_kit::sc::ChannelContext {
fabrics: &fabrics,
keys: &keys,
rng: &rng,
window: &window,
verifier: &verifier,
parameters: ¶meters,
now,
};
let mut buffers = matter_kit::sc::ChannelBuffers {
reply: &mut payload,
frame: &mut frame_buf,
evict: &mut evict_buf,
};
match channel.on_message(
&mut stack,
header.opcode,
&body,
&ctx,
&mut buffers,
) {
Ok(answered) => {
evicted_report = answered.evicted;
if let Some(established) = answered.established {
println!(
" {:?} complete — session {:?}",
established.kind, established.session
);
if established.kind == SessionKind::Case {
println!(" on fabric {:?}", established.fabric);
}
}
match answered.reply {
Some((opcode, len)) => Ok((opcode, len)),
None => continue,
}
}
Err(e) => Err(e),
}
} else if header.protocol == ProtocolId::INTERACTION_MODEL {
let continuation = interactions.get(exchange, now).pending_read.clone();
let (opcode, body) = if header.opcode
== matter_kit::im::opcode::STATUS_RESPONSE
&& !continuation.is_empty()
{
(matter_kit::im::opcode::READ_REQUEST, &continuation[..])
} else {
(header.opcode, &body[..])
};
let request = Request {
opcode,
payload: body,
session: Some(exchange.session),
exchange: exchange.id,
groupcast: false,
};
let accessing_fabric = stack
.sessions()
.find(exchange.session)
.map(|s| s.fabric_index)
.filter(|i| i.0 != 0);
let subject = match stack.sessions().find(exchange.session) {
Some(session) => SubjectDescriptor::from_session(
session,
fail_safe.borrow().armed(now).and_then(|a| a.fabric_index),
),
None => SubjectDescriptor::unauthenticated(),
};
let access = AclAccess::new(&acl, node, &subject);
let server = Server::new(node, &access, &handler, 24)
.with_data_versions(&versions)
.with_events(&events);
let subscription_ctx = SubscriptionContext {
session: Some(exchange.session),
fabric_index: accessing_fabric,
peer_node_id: stack
.sessions()
.find(exchange.session)
.map(|s| s.peer_node_id),
};
match dispatch_one(
&mut dispatcher,
&server,
request,
now,
accessing_fabric,
channel.attestation_challenge(),
interactions.get(exchange, now),
&mut subscriptions,
&subscription_ctx,
&mut scratch,
&mut payload,
) {
Ok(Some(reply)) => Ok(reply),
Ok(None) => {
if interactions.idle(exchange) {
interactions.forget(exchange);
stack.close(exchange);
}
continue;
}
Err(e) => Err(e),
}
} else {
continue;
};
let mut close_sessions_for: Option<matter_kit::msg::FabricIndex> = None;
if let Some(aftermath) = general_commissioning.take_aftermath() {
match aftermath {
matter_kit::clusters::general_commissioning::Aftermath::Rollback(
cleanup,
) => {
println!(" fail-safe rolled back: {cleanup:?}");
handler.on_lifecycle(Lifecycle::FailSafeExpired {
fabric: cleanup.remove_fabric,
});
close_sessions_for = cleanup.close_case_sessions_for;
if let Some(index) = cleanup.remove_fabric {
let ctx = InteractionContext::new().at(now);
let _ = opcreds.remove_fabric(index, &ctx);
}
if cleanup.discard_operational_key || cleanup.prune_trusted_roots {
opcreds.discard_pending();
}
}
matter_kit::clusters::general_commissioning::Aftermath::Commissioned => {
let committed = stack
.sessions()
.find(exchange.session)
.map(|s| s.fabric_index)
.filter(|i| i.0 != 0);
if let Some(fabric) = committed {
handler.on_lifecycle(Lifecycle::CommissioningComplete(fabric));
}
println!(" commissioning complete");
}
}
}
if let Some(change) = opcreds.take_change() {
match change {
opcreds::FabricChange::Added {
index,
case_admin_subject,
bind_pase_session,
} => {
let admin_ctx = InteractionContext::new().at(now);
if let Err(e) = access_control_cluster.add_admin_for_fabric(
index,
NodeId(case_admin_subject),
&admin_ctx,
) {
println!(" could not grant the administrator: {e}");
}
if bind_pase_session
&& let Some(session) =
stack.sessions_mut().find_mut(exchange.session)
{
session.fabric_index = index;
}
if let Some(ipk) =
fabrics.borrow().find(index).map(|f| f.ipk.clone())
{
let set = matter_kit::group::GroupKeySet::single(
index,
matter_kit::group::IPK_KEY_SET,
matter_kit::group::GroupKeySecurityPolicy::TrustFirst,
ipk,
0,
);
if let Err(e) = group_keys.borrow_mut().write_key_set(set) {
println!(" could not install the IPK key set: {e:?}");
}
}
println!(" fabric {index:?} joined — administrator granted");
}
opcreds::FabricChange::Updated { index } => {
println!(" fabric {index:?} rotated its identity");
}
opcreds::FabricChange::Removed { index, .. } => {
handler.on_lifecycle(Lifecycle::FabricRemoved(index));
subscriptions.remove_for_fabric(index);
window.borrow_mut().forget_fabric(index);
close_sessions_for = Some(index);
println!(" fabric {index:?} removed");
}
}
}
for change in access_control_cluster.take_changes() {
let mut payload = [0u8; 64];
let mut w = matter_kit::tlv::TlvWriter::new_in(
&mut payload,
matter_kit::tlv::ContainerKind::Structure,
);
if change
.encode(&mut w, matter_kit::tlv::Tag::Context(7))
.is_err()
{
println!(" could not encode an ACL change event");
continue;
}
let Ok(encoded) = w.finish() else {
continue;
};
let recorded =
events
.borrow_mut()
.record(&matter_kit::dm::events::NewEvent {
endpoint: 0,
cluster: access_control::ID,
event: access_control::ACCESS_CONTROL_ENTRY_CHANGED,
priority: matter_kit::dm::EventPriority::Info,
timestamp: matter_kit::dm::events::Timestamp::System(
now.as_millis(),
),
fabric_index: Some(change.fabric_index),
data: encoded,
});
if let Err(e) = recorded {
println!(" could not record an ACL change event: {e:?}");
continue;
}
subscriptions.note_event(
0,
access_control::ID,
access_control::ACCESS_CONTROL_ENTRY_CHANGED,
);
}
match reply {
Ok((opcode, len)) => {
let randomness = rng.next_u32().expect("rng");
match stack.send(
exchange,
opcode,
true,
&payload[..len],
now,
randomness,
&mut frame_buf,
&mut out,
) {
Ok((sent, _)) => {
let _ = matter_socket.send_to(&out[..sent], from).await;
}
Err(e) => println!(" could not send: {e}"),
}
}
Err(e) => println!(" refused: {e}"),
}
if let Some(evicted) = evicted_report {
subscriptions.remove_for_session(Some(evicted.session));
reporting.retain(|(_, sent_on)| sent_on.session != evicted.session);
match (evicted.peer, evicted.len) {
(Some(matter_kit::platform::Peer::Udp(addr)), len) if len > 0 => {
let _ = matter_socket.send_to(&evict_buf[..len], addr).await;
println!(" evicted session {:?} to make room", evicted.session);
}
_ => println!(
" evicted session {:?}, with nowhere to report it",
evicted.session
),
}
}
if let Some(index) = close_sessions_for {
let closed = stack.remove_fabric(index);
subscriptions.remove_for_fabric(index);
println!(" rollback closed {closed} session(s) for {index:?}");
}
}
Event::Mdns(n) => {
let operational: heapless::Vec<_, { DefaultConfig::FABRICS }> = fabrics
.borrow()
.iter()
.map(|f| (f.instance_name(), f.compressed.subtype()))
.collect();
let operational_txt = OperationalTxt::default()
.encode()
.expect("the advertisement fits");
let operational_txt = operational_txt.finish();
let (long, short, window_txt);
let mut advertisements: heapless::Vec<
Advertisement<'_>,
{ DefaultConfig::FABRICS + 1 },
> = heapless::Vec::new();
for (instance, subtype) in &operational {
let mut a = Advertisement::new(
instance,
OPERATIONAL_SERVICE,
"0011223344556677",
matter_kit::PORT,
operational_txt,
)
.with_subtype(subtype)
.expect("subtype");
if let Some(address) = advertise_addr {
a = a.with_address(address).expect("address");
}
let _ = advertisements.push(a);
}
if operational.is_empty() {
let _ = advertisements.push(commissionable.clone());
}
let open = window.borrow().open(now).map(|w| {
(
w.discriminator,
match w.status {
WindowStatus::EnhancedOpen => CommissioningMode::Enhanced,
_ => CommissioningMode::Basic,
},
)
});
let reopened = open.filter(|_| !operational.is_empty());
if let Some((discriminator, mode)) = reopened {
let encoded = CommissionableTxt {
discriminator,
vendor_id: Some(VENDOR),
product_id: Some(PRODUCT_ID),
commissioning_mode: mode,
..CommissionableTxt::default()
}
.encode()
.expect("the advertisement fits");
window_txt = encoded;
long = format!("_L{discriminator}");
short = format!("_S{}", discriminator >> 8);
let mut a = Advertisement::new(
"0011223344556677",
COMMISSIONABLE_SERVICE,
"0011223344556677",
matter_kit::PORT,
window_txt.finish(),
)
.with_subtype(&long)
.expect("subtype")
.with_subtype(&short)
.expect("subtype")
.with_subtype("_CM")
.expect("subtype");
if let Some(address) = advertise_addr {
a = a.with_address(address).expect("address");
}
let _ = advertisements.push(a);
}
let responder = Responder::new(&advertisements);
match responder.respond(&mdns_buf[..n], &mut out) {
Ok((bytes, answered)) if !answered.is_empty() => {
let len = bytes.len();
match mdns_socket.send_to(bytes, mdns_group).await {
Ok(()) => println!(" discovered — answered {len} octets"),
Err(e) => println!(" mDNS send failed: {e}"),
}
}
Ok(_) | Err(_) => {}
}
}
Event::Deadline => {
channel.poll(now, &window);
}
}
}
});
}
fn joined_groups(
fabrics: &RefCell<FabricTable<DefaultConfig, { DefaultConfig::FABRICS }>>,
groups: &GroupTable<'_>,
) -> Vec<(matter_kit::msg::FabricId, matter_kit::msg::GroupId)> {
let table = fabrics.borrow();
groups
.memberships()
.iter()
.filter_map(|membership| {
table
.find(membership.fabric)
.map(|fabric| (fabric.fabric_id, membership.group))
})
.collect()
}
#[allow(clippy::too_many_arguments)]
fn dispatch_one<A: matter_kit::im::AccessControl, H: matter_kit::im::ClusterHandler>(
dispatcher: &mut Dispatcher<4>,
server: &Server<'_, A, H>,
request: Request<'_>,
now: Instant,
fabric_index: Option<matter_kit::msg::FabricIndex>,
challenge: Option<&matter_kit::crypto::SymmetricKey>,
interaction: &mut Interaction,
subscriptions: &mut Subscriptions,
subscription_ctx: &SubscriptionContext,
scratch: &mut [u8],
out: &mut [u8],
) -> matter_kit::Result<Option<(u8, usize)>> {
let mut ctx = InteractionContext::new().at(now);
if let Some(index) = fabric_index {
ctx = ctx.with_fabric(index);
}
if let Some(challenge) = challenge {
ctx = ctx.with_attestation_challenge(challenge);
}
if let Some(peer) = subscription_ctx
.peer_node_id
.filter(|id| id.kind() == matter_kit::msg::NodeIdKind::Operational)
{
ctx = ctx.from_peer(peer);
}
let is_read = request.opcode == matter_kit::im::opcode::READ_REQUEST;
if is_read && interaction.pending_read.is_empty() {
interaction.read_cursor = ReadCursor::START;
}
let payload = request.payload;
match dispatcher.dispatch(
server,
request,
&ctx,
&mut interaction.read_cursor,
scratch,
out,
)? {
Served::Reply {
opcode,
len,
more_chunks,
} => {
if is_read {
if more_chunks {
interaction.pending_read.clear();
if interaction.pending_read.extend_from_slice(payload).is_err() {
println!(" a read too large to continue was truncated");
interaction.pending_read.clear();
}
} else {
interaction.pending_read.clear();
}
}
Ok(Some((opcode, len)))
}
Served::Silent => Ok(None),
Served::Subscribe(request) => {
let mut paths: heapless::Vec<
matter_kit::im::AttributePath,
{ <Subscriptions as matter_kit::SubscriptionCapacity>::PATHS },
> = heapless::Vec::new();
if let Some(iter) = request.attribute_paths()? {
for path in iter {
let _ = paths.push(path?);
}
}
let mut event_paths: heapless::Vec<
matter_kit::im::EventPath,
{ <Subscriptions as matter_kit::SubscriptionCapacity>::PATHS },
> = heapless::Vec::new();
if let Some(iter) = request.event_paths()? {
for path in iter {
let _ = event_paths.push(path?);
}
}
let policy = SubscriptionPolicy::default();
let new = NewSubscription {
session: subscription_ctx.session,
fabric_index: subscription_ctx.fabric_index,
peer_node_id: subscription_ctx.peer_node_id,
fabric_filtered: request.fabric_filtered,
keep_subscriptions: request.keep_subscriptions,
min_interval_s: request.min_interval_floor_s,
max_interval_s: policy
.max_interval(request.min_interval_floor_s, request.max_interval_ceiling_s),
paths: &paths,
event_paths: &event_paths,
min_event_number: 0,
};
let id = match subscriptions.subscribe(&new, now) {
Ok(id) => id,
Err(e) => {
println!(" subscription refused: {e:?}");
return Err(matter_kit::Error::from(e));
}
};
let Some(subscription) = subscriptions.find_mut(id) else {
return Ok(None);
};
subscription.reprime();
let priming = match request.data_version_filters_raw() {
Some(filters) => ctx.with_data_version_filters(filters),
None => ctx,
};
let (bytes, outcome) =
server.report_chunk(subscription, ReportReason::Data, &priming, scratch, out)?;
let len = bytes.len();
let granted = new.max_interval_s;
interaction.pending_subscribe = Some(PendingSubscribe {
id,
max_interval_s: granted,
more_chunks: outcome.truncated,
});
println!(
" subscription {id}: {} path(s), priming report {} attributes in {len} octets{}, \
max interval {granted}s",
paths.len(),
outcome.reports,
if outcome.truncated { ", chunked" } else { "" }
);
Ok(Some((matter_kit::im::opcode::REPORT_DATA, len)))
}
Served::Unhandled { opcode } => {
if opcode == matter_kit::im::opcode::STATUS_RESPONSE {
if let Some(pending) = interaction.pending_subscribe.take() {
if pending.more_chunks {
let Some(subscription) = subscriptions.find_mut(pending.id) else {
return Ok(None);
};
let (bytes, outcome) = server.report_chunk(
subscription,
ReportReason::Data,
&ctx,
scratch,
out,
)?;
let len = bytes.len();
println!(
" subscription {} chunk: {} attributes in {len} octets{}",
pending.id,
outcome.reports,
if outcome.truncated {
", more"
} else {
", last"
}
);
interaction.pending_subscribe = Some(PendingSubscribe {
more_chunks: outcome.truncated,
..pending
});
return Ok(Some((matter_kit::im::opcode::REPORT_DATA, len)));
}
if let Some(subscription) = subscriptions.find_mut(pending.id) {
subscription.reported(now);
}
let len = SubscribeResponse::new(pending.id, pending.max_interval_s)
.encode(out)?
.len();
println!(" subscription {} granted", pending.id);
return Ok(Some((matter_kit::im::opcode::SUBSCRIBE_RESPONSE, len)));
}
return Ok(None);
}
println!(" unhandled interaction model opcode {opcode:#04x}");
Ok(None)
}
}
}
struct Uptime<'a> {
timer: &'a StdTimer,
started: Instant,
}
impl<'a> Uptime<'a> {
fn new(timer: &'a StdTimer) -> Self {
let started = timer.now();
Self { timer, started }
}
}
impl Diagnostics for Uptime<'_> {
fn up_time(&self) -> u64 {
self.timer
.now()
.saturating_duration_since(self.started)
.as_secs()
}
fn boot_reason(&self) -> BootReason {
BootReason::Unspecified
}
}
#[derive(Debug, Default)]
struct Lamp {
on: RefCell<bool>,
}
impl OnOffHooks for Lamp {
fn set(&self, on: bool) {
*self.on.borrow_mut() = on;
println!(" light: {}", if on { "on" } else { "off" });
}
}
impl IdentifyHooks for Lamp {
fn identifying(&self, on: bool) {
println!(" identify: {}", if on { "started" } else { "stopped" });
}
fn trigger_effect(&self, effect: EffectIdentifierEnum, variant: EffectVariantEnum) {
println!(" effect: {effect:?} / {variant:?}");
}
}
impl SceneHooks for Lamp {
fn capture(&self, w: &mut matter_kit::tlv::TlvWriter<'_>) -> matter_kit::error::Result<()> {
w.start_structure(matter_kit::tlv::Tag::Anonymous)?;
w.unsigned(matter_kit::tlv::Tag::Context(0), u64::from(on_off::ID))?;
w.start_array(matter_kit::tlv::Tag::Context(1))?;
w.start_structure(matter_kit::tlv::Tag::Anonymous)?;
w.unsigned(matter_kit::tlv::Tag::Context(0), u64::from(on_off::ON_OFF))?;
w.unsigned(
matter_kit::tlv::Tag::Context(1),
u64::from(*self.on.borrow()),
)?;
w.end_container()?;
w.end_container()?;
w.end_container()
}
fn apply<'a>(
&self,
sets: matter_kit::tlv::TlvList<'a, ExtensionFieldSetStruct<'a>>,
transition: u32,
) {
for set in sets.iter() {
let Ok(set) = set else { continue };
if set.cluster_id != on_off::ID {
continue;
}
for pair in set.attribute_value_list.iter() {
let Ok(pair) = pair else { continue };
if pair.attribute_id == on_off::ON_OFF {
println!(" scene: over {transition} ms");
self.set(pair.value_unsigned8.unwrap_or(0) != 0);
}
}
}
}
}