matc/clusters/codec/
localization_unit.rs

1//! Matter TLV encoders and decoders for Unit Localization Cluster
2//! Cluster ID: 0x002D
3//!
4//! This file is automatically generated from LocalizationUnit.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 TempUnit {
18    /// Temperature conveyed in Fahrenheit
19    Fahrenheit = 0,
20    /// Temperature conveyed in Celsius
21    Celsius = 1,
22    /// Temperature conveyed in Kelvin
23    Kelvin = 2,
24}
25
26impl TempUnit {
27    /// Convert from u8 value
28    pub fn from_u8(value: u8) -> Option<Self> {
29        match value {
30            0 => Some(TempUnit::Fahrenheit),
31            1 => Some(TempUnit::Celsius),
32            2 => Some(TempUnit::Kelvin),
33            _ => None,
34        }
35    }
36
37    /// Convert to u8 value
38    pub fn to_u8(self) -> u8 {
39        self as u8
40    }
41}
42
43impl From<TempUnit> for u8 {
44    fn from(val: TempUnit) -> Self {
45        val as u8
46    }
47}
48
49// Attribute decoders
50
51/// Decode TemperatureUnit attribute (0x0000)
52pub fn decode_temperature_unit(inp: &tlv::TlvItemValue) -> anyhow::Result<TempUnit> {
53    if let tlv::TlvItemValue::Int(v) = inp {
54        TempUnit::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
55    } else {
56        Err(anyhow::anyhow!("Expected Integer"))
57    }
58}
59
60/// Decode SupportedTemperatureUnits attribute (0x0001)
61pub fn decode_supported_temperature_units(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TempUnit>> {
62    let mut res = Vec::new();
63    if let tlv::TlvItemValue::List(v) = inp {
64        for item in v {
65            if let tlv::TlvItemValue::Int(i) = &item.value {
66                if let Some(enum_val) = TempUnit::from_u8(*i as u8) {
67                    res.push(enum_val);
68                }
69            }
70        }
71    }
72    Ok(res)
73}
74
75
76// JSON dispatcher function
77
78/// Decode attribute value and return as JSON string
79///
80/// # Parameters
81/// * `cluster_id` - The cluster identifier
82/// * `attribute_id` - The attribute identifier
83/// * `tlv_value` - The TLV value to decode
84///
85/// # Returns
86/// JSON string representation of the decoded value or error
87pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
88    // Verify this is the correct cluster
89    if cluster_id != 0x002D {
90        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x002D, got {}\"}}", cluster_id);
91    }
92
93    match attribute_id {
94        0x0000 => {
95            match decode_temperature_unit(tlv_value) {
96                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
97                Err(e) => format!("{{\"error\": \"{}\"}}", e),
98            }
99        }
100        0x0001 => {
101            match decode_supported_temperature_units(tlv_value) {
102                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
103                Err(e) => format!("{{\"error\": \"{}\"}}", e),
104            }
105        }
106        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
107    }
108}
109
110/// Get list of all attributes supported by this cluster
111///
112/// # Returns
113/// Vector of tuples containing (attribute_id, attribute_name)
114pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
115    vec![
116        (0x0000, "TemperatureUnit"),
117        (0x0001, "SupportedTemperatureUnits"),
118    ]
119}
120
121// Typed facade (invokes + reads)
122
123/// Read `TemperatureUnit` attribute from cluster `Unit Localization`.
124pub async fn read_temperature_unit(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TempUnit> {
125    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_UNIT_LOCALIZATION, crate::clusters::defs::CLUSTER_UNIT_LOCALIZATION_ATTR_ID_TEMPERATUREUNIT).await?;
126    decode_temperature_unit(&tlv)
127}
128
129/// Read `SupportedTemperatureUnits` attribute from cluster `Unit Localization`.
130pub async fn read_supported_temperature_units(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TempUnit>> {
131    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_UNIT_LOCALIZATION, crate::clusters::defs::CLUSTER_UNIT_LOCALIZATION_ATTR_ID_SUPPORTEDTEMPERATUREUNITS).await?;
132    decode_supported_temperature_units(&tlv)
133}
134