#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
pub fn decode_state_value(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
if let tlv::TlvItemValue::Bool(v) = inp {
Ok(*v)
} else {
Err(anyhow::anyhow!("Expected Bool"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0045 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0045, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_state_value(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, "StateValue"),
]
}
pub async fn read_state_value(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_ATTR_ID_STATEVALUE).await?;
decode_state_value(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct StateChangeEvent {
pub state_value: Option<bool>,
}
pub fn decode_state_change_event(inp: &tlv::TlvItemValue) -> anyhow::Result<StateChangeEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(StateChangeEvent {
state_value: item.get_bool(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}