matc/clusters/codec/
water_heater_management.rs

1//! Matter TLV encoders and decoders for Water Heater Management Cluster
2//! Cluster ID: 0x0094
3//!
4//! This file is automatically generated from WaterHeaterManagement.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Enum definitions
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16#[repr(u8)]
17pub enum BoostState {
18    /// Boost is not currently active
19    Inactive = 0,
20    /// Boost is currently active
21    Active = 1,
22}
23
24impl BoostState {
25    /// Convert from u8 value
26    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    /// Convert to u8 value
35    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
46// Bitmap definitions
47
48/// WaterHeaterHeatSource bitmap type
49pub type WaterHeaterHeatSource = u8;
50
51/// Constants for WaterHeaterHeatSource
52pub mod waterheaterheatsource {
53    /// Immersion Heating Element 1
54    pub const IMMERSION_ELEMENT1: u8 = 0x01;
55    /// Immersion Heating Element 2
56    pub const IMMERSION_ELEMENT2: u8 = 0x02;
57    /// Heat pump Heating
58    pub const HEAT_PUMP: u8 = 0x04;
59    /// Boiler Heating (e.g. Gas or Oil)
60    pub const BOILER: u8 = 0x08;
61    /// Other Heating
62    pub const OTHER: u8 = 0x10;
63}
64
65// Struct definitions
66
67#[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
77// Command encoders
78
79/// Encode Boost command (0x00)
80pub fn encode_boost(boost_info: WaterHeaterBoostInfo) -> anyhow::Result<Vec<u8>> {
81            // Encode struct WaterHeaterBoostInfoStruct
82            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            // TODO: encoding for field target_percentage (percent) not implemented
88            // TODO: encoding for field target_reheat (percent) not implemented
89    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
98// Attribute decoders
99
100/// Decode HeaterTypes attribute (0x0000)
101pub 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
109/// Decode HeatDemand attribute (0x0001)
110pub 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
118/// Decode TankVolume attribute (0x0002)
119pub 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
127/// Decode EstimatedHeatRequired attribute (0x0003)
128pub 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
136/// Decode TankPercentage attribute (0x0004)
137pub 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
145/// Decode BoostState attribute (0x0005)
146pub 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
155// JSON dispatcher function
156
157/// Decode attribute value and return as JSON string
158///
159/// # Parameters
160/// * `cluster_id` - The cluster identifier
161/// * `attribute_id` - The attribute identifier
162/// * `tlv_value` - The TLV value to decode
163///
164/// # Returns
165/// JSON string representation of the decoded value or error
166pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
167    // Verify this is the correct cluster
168    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
213/// Get list of all attributes supported by this cluster
214///
215/// # Returns
216/// Vector of tuples containing (attribute_id, attribute_name)
217pub 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
228// Command listing
229
230pub 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
263// Typed facade (invokes + reads)
264
265/// Invoke `Boost` command on cluster `Water Heater Management`.
266pub 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
271/// Invoke `CancelBoost` command on cluster `Water Heater Management`.
272pub 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
277/// Read `HeaterTypes` attribute from cluster `Water Heater Management`.
278pub 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
283/// Read `HeatDemand` attribute from cluster `Water Heater Management`.
284pub 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
289/// Read `TankVolume` attribute from cluster `Water Heater Management`.
290pub 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
295/// Read `EstimatedHeatRequired` attribute from cluster `Water Heater Management`.
296pub 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
301/// Read `TankPercentage` attribute from cluster `Water Heater Management`.
302pub 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
307/// Read `BoostState` attribute from cluster `Water Heater Management`.
308pub 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
318// Event decoders
319
320/// Decode BoostStarted event (0x00, priority: info)
321pub 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