matc/clusters/codec/
localization_unit.rs1use crate::tlv;
7use anyhow;
8use serde_json;
9
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
14#[repr(u8)]
15pub enum TempUnit {
16 Fahrenheit = 0,
18 Celsius = 1,
20 Kelvin = 2,
22}
23
24impl TempUnit {
25 pub fn from_u8(value: u8) -> Option<Self> {
27 match value {
28 0 => Some(TempUnit::Fahrenheit),
29 1 => Some(TempUnit::Celsius),
30 2 => Some(TempUnit::Kelvin),
31 _ => None,
32 }
33 }
34
35 pub fn to_u8(self) -> u8 {
37 self as u8
38 }
39}
40
41impl From<TempUnit> for u8 {
42 fn from(val: TempUnit) -> Self {
43 val as u8
44 }
45}
46
47pub fn decode_temperature_unit(inp: &tlv::TlvItemValue) -> anyhow::Result<TempUnit> {
51 if let tlv::TlvItemValue::Int(v) = inp {
52 TempUnit::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
53 } else {
54 Err(anyhow::anyhow!("Expected Integer"))
55 }
56}
57
58pub fn decode_supported_temperature_units(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TempUnit>> {
60 let mut res = Vec::new();
61 if let tlv::TlvItemValue::List(v) = inp {
62 for item in v {
63 if let tlv::TlvItemValue::Int(i) = &item.value {
64 if let Some(enum_val) = TempUnit::from_u8(*i as u8) {
65 res.push(enum_val);
66 }
67 }
68 }
69 }
70 Ok(res)
71}
72
73
74pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
86 if cluster_id != 0x002D {
88 return format!("{{\"error\": \"Invalid cluster ID. Expected 0x002D, got {}\"}}", cluster_id);
89 }
90
91 match attribute_id {
92 0x0000 => {
93 match decode_temperature_unit(tlv_value) {
94 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
95 Err(e) => format!("{{\"error\": \"{}\"}}", e),
96 }
97 }
98 0x0001 => {
99 match decode_supported_temperature_units(tlv_value) {
100 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
101 Err(e) => format!("{{\"error\": \"{}\"}}", e),
102 }
103 }
104 _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
105 }
106}
107
108pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
113 vec![
114 (0x0000, "TemperatureUnit"),
115 (0x0001, "SupportedTemperatureUnits"),
116 ]
117}
118