1#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16#[repr(u8)]
17pub enum BoostState {
18 Inactive = 0,
20 Active = 1,
22}
23
24impl BoostState {
25 pub fn from_u8(value: u8) -> Option<Self> {
27 match value {
28 0 => Some(BoostState::Inactive),
29 1 => Some(BoostState::Active),
30 _ => None,
31 }
32 }
33
34 pub fn to_u8(self) -> u8 {
36 self as u8
37 }
38}
39
40impl From<BoostState> for u8 {
41 fn from(val: BoostState) -> Self {
42 val as u8
43 }
44}
45
46pub type WaterHeaterHeatSource = u8;
50
51pub mod waterheaterheatsource {
53 pub const IMMERSION_ELEMENT1: u8 = 0x01;
55 pub const IMMERSION_ELEMENT2: u8 = 0x02;
57 pub const HEAT_PUMP: u8 = 0x04;
59 pub const BOILER: u8 = 0x08;
61 pub const OTHER: u8 = 0x10;
63}
64
65#[derive(Debug, serde::Serialize)]
68pub struct WaterHeaterBoostInfo {
69 pub duration: Option<u32>,
70 pub one_shot: Option<bool>,
71 pub emergency_boost: Option<bool>,
72 pub temporary_setpoint: Option<i16>,
73 pub target_percentage: Option<u8>,
74 pub target_reheat: Option<u8>,
75}
76
77pub fn encode_boost(boost_info: WaterHeaterBoostInfo) -> anyhow::Result<Vec<u8>> {
81 let mut boost_info_fields = Vec::new();
83 if let Some(x) = boost_info.duration { boost_info_fields.push((0, tlv::TlvItemValueEnc::UInt32(x)).into()); }
84 if let Some(x) = boost_info.one_shot { boost_info_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
85 if let Some(x) = boost_info.emergency_boost { boost_info_fields.push((2, tlv::TlvItemValueEnc::Bool(x)).into()); }
86 if let Some(x) = boost_info.temporary_setpoint { boost_info_fields.push((3, tlv::TlvItemValueEnc::Int16(x)).into()); }
87 let tlv = tlv::TlvItemEnc {
90 tag: 0,
91 value: tlv::TlvItemValueEnc::StructInvisible(vec![
92 (0, tlv::TlvItemValueEnc::StructInvisible(boost_info_fields)).into(),
93 ]),
94 };
95 Ok(tlv.encode()?)
96}
97
98pub fn decode_heater_types(inp: &tlv::TlvItemValue) -> anyhow::Result<WaterHeaterHeatSource> {
102 if let tlv::TlvItemValue::Int(v) = inp {
103 Ok(*v as u8)
104 } else {
105 Err(anyhow::anyhow!("Expected Integer"))
106 }
107}
108
109pub fn decode_heat_demand(inp: &tlv::TlvItemValue) -> anyhow::Result<WaterHeaterHeatSource> {
111 if let tlv::TlvItemValue::Int(v) = inp {
112 Ok(*v as u8)
113 } else {
114 Err(anyhow::anyhow!("Expected Integer"))
115 }
116}
117
118pub fn decode_tank_volume(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
120 if let tlv::TlvItemValue::Int(v) = inp {
121 Ok(*v as u16)
122 } else {
123 Err(anyhow::anyhow!("Expected UInt16"))
124 }
125}
126
127pub fn decode_estimated_heat_required(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
129 if let tlv::TlvItemValue::Int(v) = inp {
130 Ok(*v)
131 } else {
132 Err(anyhow::anyhow!("Expected UInt64"))
133 }
134}
135
136pub fn decode_tank_percentage(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
138 if let tlv::TlvItemValue::Int(v) = inp {
139 Ok(*v as u8)
140 } else {
141 Err(anyhow::anyhow!("Expected UInt8"))
142 }
143}
144
145pub fn decode_boost_state(inp: &tlv::TlvItemValue) -> anyhow::Result<BoostState> {
147 if let tlv::TlvItemValue::Int(v) = inp {
148 BoostState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
149 } else {
150 Err(anyhow::anyhow!("Expected Integer"))
151 }
152}
153
154
155pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
167 if cluster_id != 0x0094 {
169 return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0094, got {}\"}}", cluster_id);
170 }
171
172 match attribute_id {
173 0x0000 => {
174 match decode_heater_types(tlv_value) {
175 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
176 Err(e) => format!("{{\"error\": \"{}\"}}", e),
177 }
178 }
179 0x0001 => {
180 match decode_heat_demand(tlv_value) {
181 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
182 Err(e) => format!("{{\"error\": \"{}\"}}", e),
183 }
184 }
185 0x0002 => {
186 match decode_tank_volume(tlv_value) {
187 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
188 Err(e) => format!("{{\"error\": \"{}\"}}", e),
189 }
190 }
191 0x0003 => {
192 match decode_estimated_heat_required(tlv_value) {
193 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
194 Err(e) => format!("{{\"error\": \"{}\"}}", e),
195 }
196 }
197 0x0004 => {
198 match decode_tank_percentage(tlv_value) {
199 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
200 Err(e) => format!("{{\"error\": \"{}\"}}", e),
201 }
202 }
203 0x0005 => {
204 match decode_boost_state(tlv_value) {
205 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
206 Err(e) => format!("{{\"error\": \"{}\"}}", e),
207 }
208 }
209 _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
210 }
211}
212
213pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
218 vec![
219 (0x0000, "HeaterTypes"),
220 (0x0001, "HeatDemand"),
221 (0x0002, "TankVolume"),
222 (0x0003, "EstimatedHeatRequired"),
223 (0x0004, "TankPercentage"),
224 (0x0005, "BoostState"),
225 ]
226}
227
228pub fn get_command_list() -> Vec<(u32, &'static str)> {
231 vec![
232 (0x00, "Boost"),
233 (0x01, "CancelBoost"),
234 ]
235}
236
237pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
238 match cmd_id {
239 0x00 => Some("Boost"),
240 0x01 => Some("CancelBoost"),
241 _ => None,
242 }
243}
244
245pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
246 match cmd_id {
247 0x00 => Some(vec![
248 crate::clusters::codec::CommandField { tag: 0, name: "boost_info", kind: crate::clusters::codec::FieldKind::Struct { name: "WaterHeaterBoostInfoStruct" }, optional: false, nullable: false },
249 ]),
250 0x01 => Some(vec![]),
251 _ => None,
252 }
253}
254
255pub fn encode_command_json(cmd_id: u32, _args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
256 match cmd_id {
257 0x00 => Err(anyhow::anyhow!("command \"Boost\" has complex args: use raw mode")),
258 0x01 => Ok(vec![]),
259 _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
260 }
261}
262
263pub async fn boost(conn: &crate::controller::Connection, endpoint: u16, boost_info: WaterHeaterBoostInfo) -> anyhow::Result<()> {
267 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?;
268 Ok(())
269}
270
271pub async fn cancel_boost(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
273 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_CMD_ID_CANCELBOOST, &[]).await?;
274 Ok(())
275}
276
277pub async fn read_heater_types(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<WaterHeaterHeatSource> {
279 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?;
280 decode_heater_types(&tlv)
281}
282
283pub async fn read_heat_demand(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<WaterHeaterHeatSource> {
285 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?;
286 decode_heat_demand(&tlv)
287}
288
289pub async fn read_tank_volume(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
291 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?;
292 decode_tank_volume(&tlv)
293}
294
295pub async fn read_estimated_heat_required(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
297 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?;
298 decode_estimated_heat_required(&tlv)
299}
300
301pub async fn read_tank_percentage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
303 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?;
304 decode_tank_percentage(&tlv)
305}
306
307pub async fn read_boost_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<BoostState> {
309 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?;
310 decode_boost_state(&tlv)
311}
312
313#[derive(Debug, serde::Serialize)]
314pub struct BoostStartedEvent {
315 pub boost_info: Option<WaterHeaterBoostInfo>,
316}
317
318pub fn decode_boost_started_event(inp: &tlv::TlvItemValue) -> anyhow::Result<BoostStartedEvent> {
322 if let tlv::TlvItemValue::List(_fields) = inp {
323 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
324 Ok(BoostStartedEvent {
325 boost_info: {
326 if let Some(nested_tlv) = item.get(&[0]) {
327 if let tlv::TlvItemValue::List(_) = nested_tlv {
328 let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
329 Some(WaterHeaterBoostInfo {
330 duration: nested_item.get_int(&[0]).map(|v| v as u32),
331 one_shot: nested_item.get_bool(&[1]),
332 emergency_boost: nested_item.get_bool(&[2]),
333 temporary_setpoint: nested_item.get_int(&[3]).map(|v| v as i16),
334 target_percentage: nested_item.get_int(&[4]).map(|v| v as u8),
335 target_reheat: nested_item.get_int(&[5]).map(|v| v as u8),
336 })
337 } else {
338 None
339 }
340 } else {
341 None
342 }
343 },
344 })
345 } else {
346 Err(anyhow::anyhow!("Expected struct fields"))
347 }
348}
349