#![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 BoostState {
Inactive = 0,
Active = 1,
}
impl BoostState {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(BoostState::Inactive),
1 => Some(BoostState::Active),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<BoostState> for u8 {
fn from(val: BoostState) -> Self {
val as u8
}
}
pub type WaterHeaterHeatSource = u8;
pub mod waterheaterheatsource {
pub const IMMERSION_ELEMENT1: u8 = 0x01;
pub const IMMERSION_ELEMENT2: u8 = 0x02;
pub const HEAT_PUMP: u8 = 0x04;
pub const BOILER: u8 = 0x08;
pub const OTHER: u8 = 0x10;
}
#[derive(Debug, serde::Serialize)]
pub struct WaterHeaterBoostInfo {
pub duration: Option<u32>,
pub one_shot: Option<bool>,
pub emergency_boost: Option<bool>,
pub temporary_setpoint: Option<i16>,
pub target_percentage: Option<u8>,
pub target_reheat: Option<u8>,
}
pub fn encode_boost(boost_info: WaterHeaterBoostInfo) -> anyhow::Result<Vec<u8>> {
let mut boost_info_fields = Vec::new();
if let Some(x) = boost_info.duration { boost_info_fields.push((0, tlv::TlvItemValueEnc::UInt32(x)).into()); }
if let Some(x) = boost_info.one_shot { boost_info_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
if let Some(x) = boost_info.emergency_boost { boost_info_fields.push((2, tlv::TlvItemValueEnc::Bool(x)).into()); }
if let Some(x) = boost_info.temporary_setpoint { boost_info_fields.push((3, tlv::TlvItemValueEnc::Int16(x)).into()); }
if let Some(x) = boost_info.target_percentage { boost_info_fields.push((4, tlv::TlvItemValueEnc::UInt8(x)).into()); }
if let Some(x) = boost_info.target_reheat { boost_info_fields.push((5, tlv::TlvItemValueEnc::UInt8(x)).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::StructInvisible(boost_info_fields)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_heater_types(inp: &tlv::TlvItemValue) -> anyhow::Result<WaterHeaterHeatSource> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_heat_demand(inp: &tlv::TlvItemValue) -> anyhow::Result<WaterHeaterHeatSource> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_tank_volume(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_estimated_heat_required(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v)
} else {
Err(anyhow::anyhow!("Expected UInt64"))
}
}
pub fn decode_tank_percentage(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
pub fn decode_boost_state(inp: &tlv::TlvItemValue) -> anyhow::Result<BoostState> {
if let tlv::TlvItemValue::Int(v) = inp {
BoostState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0094 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0094, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_heater_types(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_heat_demand(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_tank_volume(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_estimated_heat_required(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0004 => {
match decode_tank_percentage(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0005 => {
match decode_boost_state(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, "HeaterTypes"),
(0x0001, "HeatDemand"),
(0x0002, "TankVolume"),
(0x0003, "EstimatedHeatRequired"),
(0x0004, "TankPercentage"),
(0x0005, "BoostState"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "Boost"),
(0x01, "CancelBoost"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("Boost"),
0x01 => Some("CancelBoost"),
_ => 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: "boost_info", kind: crate::clusters::codec::FieldKind::Struct { name: "WaterHeaterBoostInfoStruct" }, optional: false, nullable: false },
]),
0x01 => Some(vec![]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, _args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x00 => Err(anyhow::anyhow!("command \"Boost\" has complex args: use raw mode")),
0x01 => Ok(vec![]),
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
pub async fn boost(conn: &crate::controller::Connection, endpoint: u16, boost_info: WaterHeaterBoostInfo) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_CMD_ID_BOOST, &encode_boost(boost_info)?).await?;
Ok(())
}
pub async fn cancel_boost(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_CMD_ID_CANCELBOOST, &[]).await?;
Ok(())
}
pub async fn read_heater_types(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<WaterHeaterHeatSource> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_HEATERTYPES).await?;
decode_heater_types(&tlv)
}
pub async fn read_heat_demand(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<WaterHeaterHeatSource> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_HEATDEMAND).await?;
decode_heat_demand(&tlv)
}
pub async fn read_tank_volume(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_TANKVOLUME).await?;
decode_tank_volume(&tlv)
}
pub async fn read_estimated_heat_required(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_ESTIMATEDHEATREQUIRED).await?;
decode_estimated_heat_required(&tlv)
}
pub async fn read_tank_percentage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_TANKPERCENTAGE).await?;
decode_tank_percentage(&tlv)
}
pub async fn read_boost_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<BoostState> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_BOOSTSTATE).await?;
decode_boost_state(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct BoostStartedEvent {
pub boost_info: Option<WaterHeaterBoostInfo>,
}
pub fn decode_boost_started_event(inp: &tlv::TlvItemValue) -> anyhow::Result<BoostStartedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(BoostStartedEvent {
boost_info: {
if let Some(nested_tlv) = item.get(&[0]) {
if let tlv::TlvItemValue::List(_) = nested_tlv {
let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
Some(WaterHeaterBoostInfo {
duration: nested_item.get_int(&[0]).map(|v| v as u32),
one_shot: nested_item.get_bool(&[1]),
emergency_boost: nested_item.get_bool(&[2]),
temporary_setpoint: nested_item.get_int(&[3]).map(|v| v as i16),
target_percentage: nested_item.get_int(&[4]).map(|v| v as u8),
target_reheat: nested_item.get_int(&[5]).map(|v| v as u8),
})
} else {
None
}
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}