use core::cell::{Cell, RefCell};
use crate::clusters::basic_information::Location;
use crate::commissioning::failsafe::{Cleanup, CommissioningError, FailSafe};
use crate::dm::Resolved;
use crate::dm::ResolvedCommand;
use crate::dm::access::{Access, AccessQualities, Privilege};
use crate::dm::meta::{
AttributeDescriptor, AttributeQualities, ClusterDescriptor, CommandDescriptor,
};
use crate::im::{
AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
WriteOp,
};
use crate::msg::FabricIndex;
use crate::platform::{Duration, Instant};
use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, set_once};
use super::Cluster;
pub const ID: ClusterId = 0x0030;
pub const REVISION: u16 = 2;
pub const FEATURE_TERMS_AND_CONDITIONS: u32 = 1 << 0;
pub const FEATURE_NETWORK_RECOVERY: u32 = 1 << 1;
pub const BREADCRUMB: AttributeId = 0x0000;
pub const BASIC_COMMISSIONING_INFO: AttributeId = 0x0001;
pub const REGULATORY_CONFIG: AttributeId = 0x0002;
pub const LOCATION_CAPABILITY: AttributeId = 0x0003;
pub const SUPPORTS_CONCURRENT_CONNECTION: AttributeId = 0x0004;
pub const RECOVERY_IDENTIFIER: AttributeId = 0x000A;
pub const NETWORK_RECOVERY_REASON: AttributeId = 0x000B;
pub const ARM_FAIL_SAFE: CommandId = 0x00;
pub const ARM_FAIL_SAFE_RESPONSE: CommandId = 0x01;
pub const SET_REGULATORY_CONFIG: CommandId = 0x02;
pub const SET_REGULATORY_CONFIG_RESPONSE: CommandId = 0x03;
pub const COMMISSIONING_COMPLETE: CommandId = 0x04;
pub const COMMISSIONING_COMPLETE_RESPONSE: CommandId = 0x05;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum RegulatoryLocation {
Indoor = 0,
Outdoor = 1,
IndoorOutdoor = 2,
}
impl RegulatoryLocation {
#[must_use]
pub const fn value(self) -> u8 {
self as u8
}
#[must_use]
pub const fn from_value(value: u8) -> Option<Self> {
match value {
0 => Some(Self::Indoor),
1 => Some(Self::Outdoor),
2 => Some(Self::IndoorOutdoor),
_ => None,
}
}
}
#[derive(Debug)]
pub struct Recovery {
identifier: u64,
lost_at: Cell<Option<Instant>>,
reason: Cell<Option<NetworkRecoveryReason>>,
announcing: Cell<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum NetworkRecoveryReason {
Unspecified = 0,
Auth = 1,
Visibility = 2,
}
impl NetworkRecoveryReason {
#[must_use]
pub const fn value(self) -> u8 {
self as u8
}
}
pub const RECOVERY_HOLD_OFF: Duration = Duration::from_secs(120);
pub const RECOVERY_FAIL_SAFE_SECONDS: u16 = 60;
impl Recovery {
#[must_use]
pub const fn new(identifier: u64) -> Self {
Self {
identifier,
lost_at: Cell::new(None),
reason: Cell::new(None),
announcing: Cell::new(false),
}
}
#[must_use]
pub const fn identifier(&self) -> u64 {
self.identifier
}
#[must_use]
pub fn reason(&self) -> Option<NetworkRecoveryReason> {
self.reason.get()
}
#[must_use]
pub fn is_announcing(&self) -> bool {
self.announcing.get()
}
pub fn network_lost(&self, now: Instant, reason: NetworkRecoveryReason) {
if self.lost_at.get().is_none() {
self.lost_at.set(Some(now));
self.reason.set(Some(reason));
}
}
pub fn network_restored(&self) {
self.lost_at.set(None);
self.reason.set(None);
self.announcing.set(false);
}
#[must_use]
pub fn may_announce(&self, now: Instant) -> bool {
self.lost_at
.get()
.is_some_and(|lost| now.saturating_duration_since(lost) >= RECOVERY_HOLD_OFF)
}
pub fn begin_announcing(&self, now: Instant) -> bool {
let allowed = self.may_announce(now);
if allowed {
self.announcing.set(true);
}
allowed
}
#[must_use]
pub fn may_complete(&self, over_operational_network: bool) -> bool {
!self.announcing.get() || over_operational_network
}
}
const ATTRIBUTES: &[AttributeDescriptor] = &[
AttributeDescriptor::read_write(BREADCRUMB).with_access(Access::read_write_with(
Privilege::View,
Privilege::Administer,
)),
AttributeDescriptor::read_only(BASIC_COMMISSIONING_INFO)
.with_qualities(AttributeQualities::FIXED),
AttributeDescriptor::read_only(REGULATORY_CONFIG),
AttributeDescriptor::read_only(LOCATION_CAPABILITY).with_qualities(AttributeQualities::FIXED),
AttributeDescriptor::read_only(SUPPORTS_CONCURRENT_CONNECTION)
.with_qualities(AttributeQualities::FIXED),
];
#[cfg(feature = "provisional")]
const RECOVERY_ATTRIBUTES: &[AttributeDescriptor] = &[
AttributeDescriptor::read_write(BREADCRUMB).with_access(Access::read_write_with(
Privilege::View,
Privilege::Administer,
)),
AttributeDescriptor::read_only(BASIC_COMMISSIONING_INFO)
.with_qualities(AttributeQualities::FIXED),
AttributeDescriptor::read_only(REGULATORY_CONFIG),
AttributeDescriptor::read_only(LOCATION_CAPABILITY).with_qualities(AttributeQualities::FIXED),
AttributeDescriptor::read_only(SUPPORTS_CONCURRENT_CONNECTION)
.with_qualities(AttributeQualities::FIXED),
AttributeDescriptor::read_only(RECOVERY_IDENTIFIER)
.with_access(Access::read_only(Privilege::Administer))
.with_qualities(AttributeQualities::FIXED),
AttributeDescriptor::read_only(NETWORK_RECOVERY_REASON)
.with_access(Access::read_only(Privilege::Administer))
.with_qualities(AttributeQualities::NULLABLE),
];
const COMMANDS: &[CommandDescriptor] = &[
CommandDescriptor::new(ARM_FAIL_SAFE)
.with_access(Access::invoke(Privilege::Administer))
.with_response(ARM_FAIL_SAFE_RESPONSE),
CommandDescriptor::new(SET_REGULATORY_CONFIG)
.with_access(Access::invoke(Privilege::Administer))
.with_response(SET_REGULATORY_CONFIG_RESPONSE),
CommandDescriptor::new(COMMISSIONING_COMPLETE)
.with_access(
Access::invoke(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
)
.with_response(COMMISSIONING_COMPLETE_RESPONSE),
];
#[must_use]
pub const fn cluster() -> ClusterDescriptor<'static> {
ClusterDescriptor {
id: ID,
revision: REVISION,
feature_map: 0,
attributes: ATTRIBUTES,
accepted_commands: COMMANDS,
generated_commands: &[],
events: &[],
}
}
#[cfg(feature = "provisional")]
#[cfg_attr(docsrs, doc(cfg(feature = "provisional")))]
#[must_use]
pub const fn cluster_with_recovery() -> ClusterDescriptor<'static> {
ClusterDescriptor {
id: ID,
revision: REVISION,
feature_map: FEATURE_NETWORK_RECOVERY,
attributes: RECOVERY_ATTRIBUTES,
accepted_commands: COMMANDS,
generated_commands: &[],
events: &[],
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArmFailSafeOutcome {
pub error: CommissioningError,
pub cleanup: Option<Cleanup>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Completion {
pub error: CommissioningError,
pub close_pase_sessions: bool,
pub cleanup: Option<Cleanup>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Aftermath {
Rollback(Cleanup),
Commissioned,
}
#[derive(Debug)]
pub struct GeneralCommissioning<'a> {
pub location: &'a Location,
pub location_capability: RegulatoryLocation,
pub supports_concurrent_connection: bool,
pub fail_safe: &'a RefCell<FailSafe>,
regulatory_config: Cell<RegulatoryLocation>,
pub window: &'a RefCell<crate::commissioning::window::CommissioningWindow>,
pub recovery: Option<&'a Recovery>,
aftermath: Cell<Option<Aftermath>>,
}
impl<'a> GeneralCommissioning<'a> {
#[must_use]
pub fn new(
location: &'a Location,
location_capability: RegulatoryLocation,
fail_safe: &'a RefCell<FailSafe>,
window: &'a RefCell<crate::commissioning::window::CommissioningWindow>,
) -> Self {
Self {
location,
location_capability,
supports_concurrent_connection: true,
fail_safe,
window,
regulatory_config: Cell::new(location_capability),
recovery: None,
aftermath: Cell::new(None),
}
}
#[must_use]
pub const fn with_recovery(mut self, recovery: &'a Recovery) -> Self {
self.recovery = Some(recovery);
self
}
#[must_use]
pub fn without_concurrent_connection(mut self) -> Self {
self.supports_concurrent_connection = false;
self
}
#[must_use]
pub fn fail_safe(&self) -> core::cell::Ref<'_, FailSafe> {
self.fail_safe.borrow()
}
#[must_use]
pub fn fail_safe_mut(&self) -> core::cell::RefMut<'_, FailSafe> {
self.fail_safe.borrow_mut()
}
#[must_use]
pub fn regulatory_config(&self) -> RegulatoryLocation {
self.regulatory_config.get()
}
#[must_use]
pub fn is_window_open(&self, now: crate::platform::Instant) -> bool {
self.window.borrow().open(now).is_some()
}
#[must_use]
pub fn take_aftermath(&self) -> Option<Aftermath> {
self.aftermath.take()
}
pub fn arm_fail_safe(
&self,
expiry_length_seconds: u16,
breadcrumb: u64,
accessing_fabric: Option<FabricIndex>,
over_case: bool,
now: crate::platform::Instant,
) -> ArmFailSafeOutcome {
let result = self.fail_safe.borrow_mut().arm(
expiry_length_seconds,
breadcrumb,
accessing_fabric,
now,
self.is_window_open(now) && over_case,
);
ArmFailSafeOutcome {
error: result.outcome.error_code(),
cleanup: result.cleanup,
}
}
pub fn set_regulatory_config(
&self,
new_config: RegulatoryLocation,
country_code: &str,
breadcrumb: u64,
) -> CommissioningError {
if self.location.set(country_code).is_err() {
return CommissioningError::ValueOutsideRange;
}
if self.location_capability != RegulatoryLocation::IndoorOutdoor
&& new_config != self.location_capability
{
return CommissioningError::ValueOutsideRange;
}
self.regulatory_config.set(new_config);
self.fail_safe.borrow_mut().set_breadcrumb(breadcrumb);
CommissioningError::Ok
}
pub fn commissioning_complete(
&self,
over_case: bool,
accessing_fabric: Option<FabricIndex>,
now: crate::platform::Instant,
) -> Completion {
let result = self
.fail_safe
.borrow_mut()
.complete(over_case, accessing_fabric, now);
if result.error.is_ok() {
self.window.borrow_mut().close();
}
Completion {
error: result.error,
close_pase_sessions: result.error.is_ok(),
cleanup: result.cleanup,
}
}
}
impl ClusterHandler for GeneralCommissioning<'_> {
fn read(
&self,
resolved: &Resolved<'_>,
_ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
match resolved.attribute {
BREADCRUMB => full(w.unsigned(tag, self.fail_safe.borrow().breadcrumb())),
BASIC_COMMISSIONING_INFO => {
let info = self.fail_safe.borrow().info();
full(w.start_structure(tag))?;
full(w.unsigned(Tag::Context(0), u64::from(info.expiry_length_seconds)))?;
full(w.unsigned(Tag::Context(1), u64::from(info.max_cumulative_seconds)))?;
full(w.end_container())
}
REGULATORY_CONFIG => {
full(w.unsigned(tag, u64::from(self.regulatory_config.get().value())))
}
LOCATION_CAPABILITY => {
full(w.unsigned(tag, u64::from(self.location_capability.value())))
}
SUPPORTS_CONCURRENT_CONNECTION => {
full(w.bool(tag, self.supports_concurrent_connection))
}
RECOVERY_IDENTIFIER => {
let recovery = self.recovery.ok_or(Status::UnsupportedAttribute)?;
full(w.unsigned(tag, recovery.identifier()))
}
NETWORK_RECOVERY_REASON => {
let recovery = self.recovery.ok_or(Status::UnsupportedAttribute)?;
match recovery.reason() {
Some(reason) => full(w.unsigned(tag, u64::from(reason.value()))),
None => full(w.null(tag)),
}
}
_ => Err(Status::UnsupportedAttribute),
}
}
fn write(
&self,
resolved: &Resolved<'_>,
data: &[u8],
_op: WriteOp,
_ctx: &InteractionContext<'_>,
) -> Result<(), Status> {
match resolved.attribute {
BREADCRUMB => {
let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
let value = reader
.next_element()
.ok()
.flatten()
.and_then(|element| element.unsigned().ok())
.ok_or(Status::InvalidDataType)?;
self.fail_safe.borrow_mut().set_breadcrumb(value);
Ok(())
}
_ => Err(Status::UnsupportedWrite),
}
}
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<Option<CommandId>, StatusIb> {
match resolved.command.id {
ARM_FAIL_SAFE => {
let request = ArmFailSafeRequest::decode(fields)?;
let outcome = self.arm_fail_safe(
request.expiry_length_seconds,
request.breadcrumb,
ctx.fabric_index,
ctx.fabric_index.is_some(),
ctx.now,
);
if let Some(cleanup) = outcome.cleanup {
self.aftermath.set(Some(Aftermath::Rollback(cleanup)));
}
write_error_response(w, tag, outcome.error)?;
Ok(Some(ARM_FAIL_SAFE_RESPONSE))
}
SET_REGULATORY_CONFIG => {
let request = SetRegulatoryConfigRequest::decode(fields)?;
let error = self.set_regulatory_config(
request.new_config,
request.country_code,
request.breadcrumb,
);
write_error_response(w, tag, error)?;
Ok(Some(SET_REGULATORY_CONFIG_RESPONSE))
}
COMMISSIONING_COMPLETE => {
let completion = self.commissioning_complete(
ctx.fabric_index.is_some(),
ctx.fabric_index,
ctx.now,
);
match completion.cleanup {
Some(cleanup) => self.aftermath.set(Some(Aftermath::Rollback(cleanup))),
None if completion.close_pase_sessions => {
self.aftermath.set(Some(Aftermath::Commissioned));
}
None => {}
}
write_error_response(w, tag, completion.error)?;
Ok(Some(COMMISSIONING_COMPLETE_RESPONSE))
}
_ => Err(Status::UnsupportedCommand.into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ArmFailSafeRequest {
expiry_length_seconds: u16,
breadcrumb: u64,
}
impl ArmFailSafeRequest {
fn decode(fields: Option<&[u8]>) -> Result<Self, Status> {
let fields = fields.ok_or(Status::InvalidCommand)?;
let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidCommand)?
.ok_or(Status::InvalidCommand)?;
if element.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidCommand);
}
let mut expiry: Option<u16> = None;
let mut breadcrumb: Option<u64> = None;
let start_depth = reader.depth();
loop {
let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
return Err(Status::InvalidCommand);
};
if reader.depth() < start_depth {
break;
}
match field.tag {
Tag::Context(0) => {
let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
set_once(
&mut expiry,
u16::try_from(value).map_err(|_| Status::ConstraintError)?,
)
.map_err(|_| Status::InvalidCommand)?;
}
Tag::Context(1) => {
let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
set_once(&mut breadcrumb, value).map_err(|_| Status::InvalidCommand)?;
}
_ => reader
.skip_value(&field)
.map_err(|_| Status::InvalidCommand)?,
}
}
Ok(Self {
expiry_length_seconds: expiry
.unwrap_or(crate::commissioning::failsafe::DEFAULT_EXPIRY_SECONDS),
breadcrumb: breadcrumb.ok_or(Status::InvalidCommand)?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SetRegulatoryConfigRequest<'a> {
new_config: RegulatoryLocation,
country_code: &'a str,
breadcrumb: u64,
}
impl<'a> SetRegulatoryConfigRequest<'a> {
fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
let fields = fields.ok_or(Status::InvalidCommand)?;
let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidCommand)?
.ok_or(Status::InvalidCommand)?;
if element.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidCommand);
}
let mut new_config: Option<RegulatoryLocation> = None;
let mut country_code: Option<&str> = None;
let mut breadcrumb: Option<u64> = None;
let start_depth = reader.depth();
loop {
let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
return Err(Status::InvalidCommand);
};
if reader.depth() < start_depth {
break;
}
match field.tag {
Tag::Context(0) => {
let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
let location =
RegulatoryLocation::from_value(value).ok_or(Status::ConstraintError)?;
set_once(&mut new_config, location).map_err(|_| Status::InvalidCommand)?;
}
Tag::Context(1) => {
let text = field.utf8().map_err(|_| Status::InvalidCommand)?;
set_once(&mut country_code, text).map_err(|_| Status::InvalidCommand)?;
}
Tag::Context(2) => {
let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
set_once(&mut breadcrumb, value).map_err(|_| Status::InvalidCommand)?;
}
_ => reader
.skip_value(&field)
.map_err(|_| Status::InvalidCommand)?,
}
}
Ok(Self {
new_config: new_config.ok_or(Status::InvalidCommand)?,
country_code: country_code.ok_or(Status::InvalidCommand)?,
breadcrumb: breadcrumb.ok_or(Status::InvalidCommand)?,
})
}
}
fn write_error_response(
w: &mut TlvWriter<'_>,
tag: Tag,
error: CommissioningError,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
full(w.start_structure(tag))?;
full(w.unsigned(Tag::Context(0), u64::from(error.value())))?;
full(w.utf8(Tag::Context(1), ""))?;
full(w.end_container())
}
impl Cluster for GeneralCommissioning<'_> {
const ID: ClusterId = ID;
}