matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Electrical Grid Conditions Cluster
//! Cluster ID: 0x00A0
//!
//! This file is automatically generated from ElectricalGridConditions.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 ThreeLevel {
    /// Low
    Low = 0,
    /// Medium
    Medium = 1,
    /// High
    High = 2,
}

impl ThreeLevel {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ThreeLevel::Low),
            1 => Some(ThreeLevel::Medium),
            2 => Some(ThreeLevel::High),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ElectricalGridConditions {
    pub period_start: Option<u64>,
    pub period_end: Option<u64>,
    pub grid_carbon_intensity: Option<i16>,
    pub grid_carbon_level: Option<ThreeLevel>,
    pub local_carbon_intensity: Option<i16>,
    pub local_carbon_level: Option<ThreeLevel>,
}

// Attribute decoders

/// Decode LocalGenerationAvailable attribute (0x0000)
pub fn decode_local_generation_available(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<bool>> {
    if let tlv::TlvItemValue::Bool(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode CurrentConditions attribute (0x0001)
pub fn decode_current_conditions(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<ElectricalGridConditions>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(ElectricalGridConditions {
                period_start: item.get_int(&[0]),
                period_end: item.get_int(&[1]),
                grid_carbon_intensity: item.get_int(&[2]).map(|v| v as i16),
                grid_carbon_level: item.get_int(&[3]).and_then(|v| ThreeLevel::from_u8(v as u8)),
                local_carbon_intensity: item.get_int(&[4]).map(|v| v as i16),
                local_carbon_level: item.get_int(&[5]).and_then(|v| ThreeLevel::from_u8(v as u8)),
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode ForecastConditions attribute (0x0002)
pub fn decode_forecast_conditions(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ElectricalGridConditions>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ElectricalGridConditions {
                period_start: item.get_int(&[0]),
                period_end: item.get_int(&[1]),
                grid_carbon_intensity: item.get_int(&[2]).map(|v| v as i16),
                grid_carbon_level: item.get_int(&[3]).and_then(|v| ThreeLevel::from_u8(v as u8)),
                local_carbon_intensity: item.get_int(&[4]).map(|v| v as i16),
                local_carbon_level: item.get_int(&[5]).and_then(|v| ThreeLevel::from_u8(v as u8)),
            });
        }
    }
    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 != 0x00A0 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x00A0, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_local_generation_available(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_conditions(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_forecast_conditions(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, "LocalGenerationAvailable"),
        (0x0001, "CurrentConditions"),
        (0x0002, "ForecastConditions"),
    ]
}

// Typed facade (invokes + reads)

/// Read `LocalGenerationAvailable` attribute from cluster `Electrical Grid Conditions`.
pub async fn read_local_generation_available(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<bool>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_GRID_CONDITIONS, crate::clusters::defs::CLUSTER_ELECTRICAL_GRID_CONDITIONS_ATTR_ID_LOCALGENERATIONAVAILABLE).await?;
    decode_local_generation_available(&tlv)
}

/// Read `CurrentConditions` attribute from cluster `Electrical Grid Conditions`.
pub async fn read_current_conditions(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<ElectricalGridConditions>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_GRID_CONDITIONS, crate::clusters::defs::CLUSTER_ELECTRICAL_GRID_CONDITIONS_ATTR_ID_CURRENTCONDITIONS).await?;
    decode_current_conditions(&tlv)
}

/// Read `ForecastConditions` attribute from cluster `Electrical Grid Conditions`.
pub async fn read_forecast_conditions(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ElectricalGridConditions>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_GRID_CONDITIONS, crate::clusters::defs::CLUSTER_ELECTRICAL_GRID_CONDITIONS_ATTR_ID_FORECASTCONDITIONS).await?;
    decode_forecast_conditions(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct CurrentConditionsChangedEvent {
    pub current_conditions: Option<ElectricalGridConditions>,
}

// Event decoders

/// Decode CurrentConditionsChanged event (0x00, priority: info)
pub fn decode_current_conditions_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<CurrentConditionsChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(CurrentConditionsChangedEvent {
                                current_conditions: {
                    if let Some(nested_tlv) = item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(ElectricalGridConditions {
                period_start: nested_item.get_int(&[0]),
                period_end: nested_item.get_int(&[1]),
                grid_carbon_intensity: nested_item.get_int(&[2]).map(|v| v as i16),
                grid_carbon_level: nested_item.get_int(&[3]).and_then(|v| ThreeLevel::from_u8(v as u8)),
                local_carbon_intensity: nested_item.get_int(&[4]).map(|v| v as i16),
                local_carbon_level: nested_item.get_int(&[5]).and_then(|v| ThreeLevel::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}