#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ClientType {
Permanent = 0,
Ephemeral = 1,
}
impl ClientType {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ClientType::Permanent),
1 => Some(ClientType::Ephemeral),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ClientType> for u8 {
fn from(val: ClientType) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum OperatingMode {
Sit = 0,
Lit = 1,
}
impl OperatingMode {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(OperatingMode::Sit),
1 => Some(OperatingMode::Lit),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<OperatingMode> for u8 {
fn from(val: OperatingMode) -> Self {
val as u8
}
}
pub type UserActiveModeTrigger = u32;
pub mod useractivemodetrigger {
pub const POWER_CYCLE: u32 = 0x01;
pub const SETTINGS_MENU: u32 = 0x02;
pub const CUSTOM_INSTRUCTION: u32 = 0x04;
pub const DEVICE_MANUAL: u32 = 0x08;
pub const ACTUATE_SENSOR: u32 = 0x10;
pub const ACTUATE_SENSOR_SECONDS: u32 = 0x20;
pub const ACTUATE_SENSOR_TIMES: u32 = 0x40;
pub const ACTUATE_SENSOR_LIGHTS_BLINK: u32 = 0x80;
pub const RESET_BUTTON: u32 = 0x100;
pub const RESET_BUTTON_LIGHTS_BLINK: u32 = 0x200;
pub const RESET_BUTTON_SECONDS: u32 = 0x400;
pub const RESET_BUTTON_TIMES: u32 = 0x800;
pub const SETUP_BUTTON: u32 = 0x1000;
pub const SETUP_BUTTON_SECONDS: u32 = 0x2000;
pub const SETUP_BUTTON_LIGHTS_BLINK: u32 = 0x4000;
pub const SETUP_BUTTON_TIMES: u32 = 0x8000;
pub const APP_DEFINED_BUTTON: u32 = 0x10000;
}
#[derive(Debug, serde::Serialize)]
pub struct MonitoringRegistration {
pub check_in_node_id: Option<u64>,
pub monitored_subject: Option<u64>,
pub key: Option<u8>,
pub client_type: Option<ClientType>,
}
pub fn encode_register_client(check_in_node_id: u64, monitored_subject: u64, key: Vec<u8>, verification_key: Option<Vec<u8>>, client_type: ClientType) -> anyhow::Result<Vec<u8>> {
let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
tlv_fields.push((0, tlv::TlvItemValueEnc::UInt64(check_in_node_id)).into());
tlv_fields.push((1, tlv::TlvItemValueEnc::UInt64(monitored_subject)).into());
tlv_fields.push((2, tlv::TlvItemValueEnc::OctetString(key)).into());
if let Some(x) = verification_key { tlv_fields.push((3, tlv::TlvItemValueEnc::OctetString(x)).into()); }
tlv_fields.push((4, tlv::TlvItemValueEnc::UInt8(client_type.to_u8())).into());
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
};
Ok(tlv.encode()?)
}
pub fn encode_unregister_client(check_in_node_id: u64, verification_key: Option<Vec<u8>>) -> anyhow::Result<Vec<u8>> {
let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
tlv_fields.push((0, tlv::TlvItemValueEnc::UInt64(check_in_node_id)).into());
if let Some(x) = verification_key { tlv_fields.push((1, tlv::TlvItemValueEnc::OctetString(x)).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
};
Ok(tlv.encode()?)
}
pub fn encode_stay_active_request(stay_active_duration: u32) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt32(stay_active_duration)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_idle_mode_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u32)
} else {
Err(anyhow::anyhow!("Expected UInt32"))
}
}
pub fn decode_active_mode_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u32)
} else {
Err(anyhow::anyhow!("Expected UInt32"))
}
}
pub fn decode_active_mode_threshold(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u16)
} else {
Err(anyhow::anyhow!("Expected UInt16"))
}
}
pub fn decode_registered_clients(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<MonitoringRegistration>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(MonitoringRegistration {
check_in_node_id: item.get_int(&[1]),
monitored_subject: item.get_int(&[2]),
key: item.get_int(&[3]).map(|v| v as u8),
client_type: item.get_int(&[4]).and_then(|v| ClientType::from_u8(v as u8)),
});
}
}
Ok(res)
}
pub fn decode_icd_counter(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u32)
} else {
Err(anyhow::anyhow!("Expected UInt32"))
}
}
pub fn decode_clients_supported_per_fabric(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u16)
} else {
Err(anyhow::anyhow!("Expected UInt16"))
}
}
pub fn decode_user_active_mode_trigger_hint(inp: &tlv::TlvItemValue) -> anyhow::Result<UserActiveModeTrigger> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u32)
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_user_active_mode_trigger_instruction(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
if let tlv::TlvItemValue::String(v) = inp {
Ok(v.clone())
} else {
Err(anyhow::anyhow!("Expected String"))
}
}
pub fn decode_operating_mode(inp: &tlv::TlvItemValue) -> anyhow::Result<OperatingMode> {
if let tlv::TlvItemValue::Int(v) = inp {
OperatingMode::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_maximum_check_in_backoff(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u32)
} else {
Err(anyhow::anyhow!("Expected UInt32"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0046 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0046, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_idle_mode_duration(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_active_mode_duration(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_active_mode_threshold(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_registered_clients(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0004 => {
match decode_icd_counter(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0005 => {
match decode_clients_supported_per_fabric(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0006 => {
match decode_user_active_mode_trigger_hint(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0007 => {
match decode_user_active_mode_trigger_instruction(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0008 => {
match decode_operating_mode(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0009 => {
match decode_maximum_check_in_backoff(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
_ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
}
}
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
vec![
(0x0000, "IdleModeDuration"),
(0x0001, "ActiveModeDuration"),
(0x0002, "ActiveModeThreshold"),
(0x0003, "RegisteredClients"),
(0x0004, "ICDCounter"),
(0x0005, "ClientsSupportedPerFabric"),
(0x0006, "UserActiveModeTriggerHint"),
(0x0007, "UserActiveModeTriggerInstruction"),
(0x0008, "OperatingMode"),
(0x0009, "MaximumCheckInBackoff"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "RegisterClient"),
(0x02, "UnregisterClient"),
(0x03, "StayActiveRequest"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("RegisterClient"),
0x02 => Some("UnregisterClient"),
0x03 => Some("StayActiveRequest"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "check_in_node_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 1, name: "monitored_subject", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 2, name: "key", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 3, name: "verification_key", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
crate::clusters::codec::CommandField { tag: 4, name: "client_type", kind: crate::clusters::codec::FieldKind::Enum { name: "ClientType", variants: &[(0, "Permanent"), (1, "Ephemeral")] }, optional: false, nullable: false },
]),
0x02 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "check_in_node_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 1, name: "verification_key", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
]),
0x03 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "stay_active_duration", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x00 => {
let check_in_node_id = crate::clusters::codec::json_util::get_u64(args, "check_in_node_id")?;
let monitored_subject = crate::clusters::codec::json_util::get_u64(args, "monitored_subject")?;
let key = crate::clusters::codec::json_util::get_octstr(args, "key")?;
let verification_key = crate::clusters::codec::json_util::get_opt_octstr(args, "verification_key")?;
let client_type = {
let n = crate::clusters::codec::json_util::get_u64(args, "client_type")?;
ClientType::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid ClientType: {}", n))?
};
encode_register_client(check_in_node_id, monitored_subject, key, verification_key, client_type)
}
0x02 => {
let check_in_node_id = crate::clusters::codec::json_util::get_u64(args, "check_in_node_id")?;
let verification_key = crate::clusters::codec::json_util::get_opt_octstr(args, "verification_key")?;
encode_unregister_client(check_in_node_id, verification_key)
}
0x03 => {
let stay_active_duration = crate::clusters::codec::json_util::get_u32(args, "stay_active_duration")?;
encode_stay_active_request(stay_active_duration)
}
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
#[derive(Debug, serde::Serialize)]
pub struct RegisterClientResponse {
pub icd_counter: Option<u32>,
}
#[derive(Debug, serde::Serialize)]
pub struct StayActiveResponse {
pub promised_active_duration: Option<u32>,
}
pub fn decode_register_client_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RegisterClientResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(RegisterClientResponse {
icd_counter: item.get_int(&[0]).map(|v| v as u32),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_stay_active_response(inp: &tlv::TlvItemValue) -> anyhow::Result<StayActiveResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(StayActiveResponse {
promised_active_duration: item.get_int(&[0]).map(|v| v as u32),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub async fn register_client(conn: &crate::controller::Connection, endpoint: u16, check_in_node_id: u64, monitored_subject: u64, key: Vec<u8>, verification_key: Option<Vec<u8>>, client_type: ClientType) -> anyhow::Result<RegisterClientResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_CMD_ID_REGISTERCLIENT, &encode_register_client(check_in_node_id, monitored_subject, key, verification_key, client_type)?).await?;
decode_register_client_response(&tlv)
}
pub async fn unregister_client(conn: &crate::controller::Connection, endpoint: u16, check_in_node_id: u64, verification_key: Option<Vec<u8>>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_CMD_ID_UNREGISTERCLIENT, &encode_unregister_client(check_in_node_id, verification_key)?).await?;
Ok(())
}
pub async fn stay_active_request(conn: &crate::controller::Connection, endpoint: u16, stay_active_duration: u32) -> anyhow::Result<StayActiveResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_CMD_ID_STAYACTIVEREQUEST, &encode_stay_active_request(stay_active_duration)?).await?;
decode_stay_active_response(&tlv)
}
pub async fn read_idle_mode_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_IDLEMODEDURATION).await?;
decode_idle_mode_duration(&tlv)
}
pub async fn read_active_mode_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_ACTIVEMODEDURATION).await?;
decode_active_mode_duration(&tlv)
}
pub async fn read_active_mode_threshold(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_ACTIVEMODETHRESHOLD).await?;
decode_active_mode_threshold(&tlv)
}
pub async fn read_registered_clients(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<MonitoringRegistration>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_REGISTEREDCLIENTS).await?;
decode_registered_clients(&tlv)
}
pub async fn read_icd_counter(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_ICDCOUNTER).await?;
decode_icd_counter(&tlv)
}
pub async fn read_clients_supported_per_fabric(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_CLIENTSSUPPORTEDPERFABRIC).await?;
decode_clients_supported_per_fabric(&tlv)
}
pub async fn read_user_active_mode_trigger_hint(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<UserActiveModeTrigger> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_USERACTIVEMODETRIGGERHINT).await?;
decode_user_active_mode_trigger_hint(&tlv)
}
pub async fn read_user_active_mode_trigger_instruction(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<String> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_USERACTIVEMODETRIGGERINSTRUCTION).await?;
decode_user_active_mode_trigger_instruction(&tlv)
}
pub async fn read_operating_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<OperatingMode> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_OPERATINGMODE).await?;
decode_operating_mode(&tlv)
}
pub async fn read_maximum_check_in_backoff(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ICD_MANAGEMENT, crate::clusters::defs::CLUSTER_ICD_MANAGEMENT_ATTR_ID_MAXIMUMCHECKINBACKOFF).await?;
decode_maximum_check_in_backoff(&tlv)
}