matc/clusters/codec/
energy_preference.rs

1//! Matter TLV encoders and decoders for Energy Preference Cluster
2//! Cluster ID: 0x009B
3//!
4//! This file is automatically generated from EnergyPreference.xml
5
6use crate::tlv;
7use anyhow;
8use serde_json;
9
10
11// Enum definitions
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
14#[repr(u8)]
15pub enum EnergyPriority {
16    /// User comfort
17    Comfort = 0,
18    /// Speed of operation
19    Speed = 1,
20    /// Amount of Energy consumed by the device
21    Efficiency = 2,
22    /// Amount of water consumed by the device
23    Waterconsumption = 3,
24}
25
26impl EnergyPriority {
27    /// Convert from u8 value
28    pub fn from_u8(value: u8) -> Option<Self> {
29        match value {
30            0 => Some(EnergyPriority::Comfort),
31            1 => Some(EnergyPriority::Speed),
32            2 => Some(EnergyPriority::Efficiency),
33            3 => Some(EnergyPriority::Waterconsumption),
34            _ => None,
35        }
36    }
37
38    /// Convert to u8 value
39    pub fn to_u8(self) -> u8 {
40        self as u8
41    }
42}
43
44impl From<EnergyPriority> for u8 {
45    fn from(val: EnergyPriority) -> Self {
46        val as u8
47    }
48}
49
50// Struct definitions
51
52#[derive(Debug, serde::Serialize)]
53pub struct Balance {
54    pub step: Option<u8>,
55    pub label: Option<String>,
56}
57
58// Attribute decoders
59
60/// Decode EnergyBalances attribute (0x0000)
61pub fn decode_energy_balances(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Balance>> {
62    let mut res = Vec::new();
63    if let tlv::TlvItemValue::List(v) = inp {
64        for item in v {
65            res.push(Balance {
66                step: item.get_int(&[0]).map(|v| v as u8),
67                label: item.get_string_owned(&[1]),
68            });
69        }
70    }
71    Ok(res)
72}
73
74/// Decode CurrentEnergyBalance attribute (0x0001)
75pub fn decode_current_energy_balance(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
76    if let tlv::TlvItemValue::Int(v) = inp {
77        Ok(*v as u8)
78    } else {
79        Err(anyhow::anyhow!("Expected UInt8"))
80    }
81}
82
83/// Decode EnergyPriorities attribute (0x0002)
84pub fn decode_energy_priorities(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<EnergyPriority>> {
85    let mut res = Vec::new();
86    if let tlv::TlvItemValue::List(v) = inp {
87        for item in v {
88            if let tlv::TlvItemValue::Int(i) = &item.value {
89                if let Some(enum_val) = EnergyPriority::from_u8(*i as u8) {
90                    res.push(enum_val);
91                }
92            }
93        }
94    }
95    Ok(res)
96}
97
98/// Decode LowPowerModeSensitivities attribute (0x0003)
99pub fn decode_low_power_mode_sensitivities(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Balance>> {
100    let mut res = Vec::new();
101    if let tlv::TlvItemValue::List(v) = inp {
102        for item in v {
103            res.push(Balance {
104                step: item.get_int(&[0]).map(|v| v as u8),
105                label: item.get_string_owned(&[1]),
106            });
107        }
108    }
109    Ok(res)
110}
111
112/// Decode CurrentLowPowerModeSensitivity attribute (0x0004)
113pub fn decode_current_low_power_mode_sensitivity(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
114    if let tlv::TlvItemValue::Int(v) = inp {
115        Ok(*v as u8)
116    } else {
117        Err(anyhow::anyhow!("Expected UInt8"))
118    }
119}
120
121
122// JSON dispatcher function
123
124/// Decode attribute value and return as JSON string
125///
126/// # Parameters
127/// * `cluster_id` - The cluster identifier
128/// * `attribute_id` - The attribute identifier
129/// * `tlv_value` - The TLV value to decode
130///
131/// # Returns
132/// JSON string representation of the decoded value or error
133pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
134    // Verify this is the correct cluster
135    if cluster_id != 0x009B {
136        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x009B, got {}\"}}", cluster_id);
137    }
138
139    match attribute_id {
140        0x0000 => {
141            match decode_energy_balances(tlv_value) {
142                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
143                Err(e) => format!("{{\"error\": \"{}\"}}", e),
144            }
145        }
146        0x0001 => {
147            match decode_current_energy_balance(tlv_value) {
148                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
149                Err(e) => format!("{{\"error\": \"{}\"}}", e),
150            }
151        }
152        0x0002 => {
153            match decode_energy_priorities(tlv_value) {
154                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
155                Err(e) => format!("{{\"error\": \"{}\"}}", e),
156            }
157        }
158        0x0003 => {
159            match decode_low_power_mode_sensitivities(tlv_value) {
160                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
161                Err(e) => format!("{{\"error\": \"{}\"}}", e),
162            }
163        }
164        0x0004 => {
165            match decode_current_low_power_mode_sensitivity(tlv_value) {
166                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
167                Err(e) => format!("{{\"error\": \"{}\"}}", e),
168            }
169        }
170        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
171    }
172}
173
174/// Get list of all attributes supported by this cluster
175///
176/// # Returns
177/// Vector of tuples containing (attribute_id, attribute_name)
178pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
179    vec![
180        (0x0000, "EnergyBalances"),
181        (0x0001, "CurrentEnergyBalance"),
182        (0x0002, "EnergyPriorities"),
183        (0x0003, "LowPowerModeSensitivities"),
184        (0x0004, "CurrentLowPowerModeSensitivity"),
185    ]
186}
187