matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Energy Preference Cluster
//! Cluster ID: 0x009B
//!
//! This file is automatically generated from EnergyPreference.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 EnergyPriority {
    /// User comfort
    Comfort = 0,
    /// Speed of operation
    Speed = 1,
    /// Amount of Energy consumed by the device
    Efficiency = 2,
    /// Amount of water consumed by the device
    Waterconsumption = 3,
}

impl EnergyPriority {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(EnergyPriority::Comfort),
            1 => Some(EnergyPriority::Speed),
            2 => Some(EnergyPriority::Efficiency),
            3 => Some(EnergyPriority::Waterconsumption),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct Balance {
    pub step: Option<u8>,
    pub label: Option<String>,
}

// Attribute decoders

/// Decode EnergyBalances attribute (0x0000)
pub fn decode_energy_balances(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Balance>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Balance {
                step: item.get_int(&[0]).map(|v| v as u8),
                label: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode CurrentEnergyBalance attribute (0x0001)
pub fn decode_current_energy_balance(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

/// Decode EnergyPriorities attribute (0x0002)
pub fn decode_energy_priorities(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<EnergyPriority>> {
    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) = EnergyPriority::from_u8(*i as u8) {
                    res.push(enum_val);
                }
            }
        }
    }
    Ok(res)
}

/// Decode LowPowerModeSensitivities attribute (0x0003)
pub fn decode_low_power_mode_sensitivities(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Balance>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Balance {
                step: item.get_int(&[0]).map(|v| v as u8),
                label: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode CurrentLowPowerModeSensitivity attribute (0x0004)
pub fn decode_current_low_power_mode_sensitivity(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}


// 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 != 0x009B {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x009B, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_energy_balances(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_energy_balance(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_energy_priorities(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_low_power_mode_sensitivities(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_current_low_power_mode_sensitivity(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, "EnergyBalances"),
        (0x0001, "CurrentEnergyBalance"),
        (0x0002, "EnergyPriorities"),
        (0x0003, "LowPowerModeSensitivities"),
        (0x0004, "CurrentLowPowerModeSensitivity"),
    ]
}

// Typed facade (invokes + reads)

/// Read `EnergyBalances` attribute from cluster `Energy Preference`.
pub async fn read_energy_balances(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Balance>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_PREFERENCE, crate::clusters::defs::CLUSTER_ENERGY_PREFERENCE_ATTR_ID_ENERGYBALANCES).await?;
    decode_energy_balances(&tlv)
}

/// Read `CurrentEnergyBalance` attribute from cluster `Energy Preference`.
pub async fn read_current_energy_balance(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_PREFERENCE, crate::clusters::defs::CLUSTER_ENERGY_PREFERENCE_ATTR_ID_CURRENTENERGYBALANCE).await?;
    decode_current_energy_balance(&tlv)
}

/// Read `EnergyPriorities` attribute from cluster `Energy Preference`.
pub async fn read_energy_priorities(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<EnergyPriority>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_PREFERENCE, crate::clusters::defs::CLUSTER_ENERGY_PREFERENCE_ATTR_ID_ENERGYPRIORITIES).await?;
    decode_energy_priorities(&tlv)
}

/// Read `LowPowerModeSensitivities` attribute from cluster `Energy Preference`.
pub async fn read_low_power_mode_sensitivities(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Balance>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_PREFERENCE, crate::clusters::defs::CLUSTER_ENERGY_PREFERENCE_ATTR_ID_LOWPOWERMODESENSITIVITIES).await?;
    decode_low_power_mode_sensitivities(&tlv)
}

/// Read `CurrentLowPowerModeSensitivity` attribute from cluster `Energy Preference`.
pub async fn read_current_low_power_mode_sensitivity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_PREFERENCE, crate::clusters::defs::CLUSTER_ENERGY_PREFERENCE_ATTR_ID_CURRENTLOWPOWERMODESENSITIVITY).await?;
    decode_current_low_power_mode_sensitivity(&tlv)
}