matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Unit Localization Cluster
//! Cluster ID: 0x002D
//!
//! This file is automatically generated from LocalizationUnit.xml

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TempUnit {
    /// Temperature conveyed in Fahrenheit
    Fahrenheit = 0,
    /// Temperature conveyed in Celsius
    Celsius = 1,
    /// Temperature conveyed in Kelvin
    Kelvin = 2,
}

impl TempUnit {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(TempUnit::Fahrenheit),
            1 => Some(TempUnit::Celsius),
            2 => Some(TempUnit::Kelvin),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<TempUnit> for u8 {
    fn from(val: TempUnit) -> Self {
        val as u8
    }
}

// Attribute decoders

/// Decode TemperatureUnit attribute (0x0000)
pub fn decode_temperature_unit(inp: &tlv::TlvItemValue) -> anyhow::Result<TempUnit> {
    if let tlv::TlvItemValue::Int(v) = inp {
        TempUnit::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode SupportedTemperatureUnits attribute (0x0001)
pub fn decode_supported_temperature_units(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TempUnit>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                if let Some(enum_val) = TempUnit::from_u8(*i as u8) {
                    res.push(enum_val);
                }
            }
        }
    }
    Ok(res)
}


// JSON dispatcher function

/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
    // Verify this is the correct cluster
    if cluster_id != 0x002D {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x002D, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_temperature_unit(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_supported_temperature_units(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
    }
}

/// Get list of all attributes supported by this cluster
///
/// # Returns
/// Vector of tuples containing (attribute_id, attribute_name)
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x0000, "TemperatureUnit"),
        (0x0001, "SupportedTemperatureUnits"),
    ]
}

// Typed facade (invokes + reads)

/// Read `TemperatureUnit` attribute from cluster `Unit Localization`.
pub async fn read_temperature_unit(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TempUnit> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_UNIT_LOCALIZATION, crate::clusters::defs::CLUSTER_UNIT_LOCALIZATION_ATTR_ID_TEMPERATUREUNIT).await?;
    decode_temperature_unit(&tlv)
}

/// Read `SupportedTemperatureUnits` attribute from cluster `Unit Localization`.
pub async fn read_supported_temperature_units(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TempUnit>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_UNIT_LOCALIZATION, crate::clusters::defs::CLUSTER_UNIT_LOCALIZATION_ATTR_ID_SUPPORTEDTEMPERATUREUNITS).await?;
    decode_supported_temperature_units(&tlv)
}