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: Vec<u8>, client_type: ClientType) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt64(check_in_node_id)).into(),
(1, tlv::TlvItemValueEnc::UInt64(monitored_subject)).into(),
(2, tlv::TlvItemValueEnc::OctetString(key)).into(),
(3, tlv::TlvItemValueEnc::OctetString(verification_key)).into(),
(4, tlv::TlvItemValueEnc::UInt8(client_type.to_u8())).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_unregister_client(check_in_node_id: u64, verification_key: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt64(check_in_node_id)).into(),
(1, tlv::TlvItemValueEnc::OctetString(verification_key)).into(),
]),
};
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"),
]
}
#[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"))
}
}