matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Resource Monitoring Clusters
//! Cluster ID: 0x0000
//!
//! This file is automatically generated from ResourceMonitoring.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 ChangeIndication {
    /// Resource is in good condition, no intervention required
    Ok = 0,
    /// Resource will be exhausted soon, intervention will shortly be required
    Warning = 1,
    /// Resource is exhausted, immediate intervention is required
    Critical = 2,
}

impl ChangeIndication {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ChangeIndication::Ok),
            1 => Some(ChangeIndication::Warning),
            2 => Some(ChangeIndication::Critical),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum DegradationDirection {
    /// The degradation of the resource is indicated by an upwards moving/increasing value
    Up = 0,
    /// The degradation of the resource is indicated by a downwards moving/decreasing value
    Down = 1,
}

impl DegradationDirection {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(DegradationDirection::Up),
            1 => Some(DegradationDirection::Down),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ProductIdentifierType {
    /// 12-digit Universal Product Code
    Upc = 0,
    /// 8-digit Global Trade Item Number
    Gtin8 = 1,
    /// 13-digit European Article Number
    Ean = 2,
    /// 14-digit Global Trade Item Number
    Gtin14 = 3,
    /// Original Equipment Manufacturer part number
    Oem = 4,
}

impl ProductIdentifierType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ProductIdentifierType::Upc),
            1 => Some(ProductIdentifierType::Gtin8),
            2 => Some(ProductIdentifierType::Ean),
            3 => Some(ProductIdentifierType::Gtin14),
            4 => Some(ProductIdentifierType::Oem),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ReplacementProduct {
    pub product_identifier_type: Option<ProductIdentifierType>,
    pub product_identifier_value: Option<String>,
}

// Command encoders

// Attribute decoders

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

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

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

/// Decode InPlaceIndicator attribute (0x0003)
pub fn decode_in_place_indicator(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
    if let tlv::TlvItemValue::Bool(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected Bool"))
    }
}

/// Decode LastChangedTime attribute (0x0004)
pub fn decode_last_changed_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode ReplacementProductList attribute (0x0005)
pub fn decode_replacement_product_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ReplacementProduct>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ReplacementProduct {
                product_identifier_type: item.get_int(&[0]).and_then(|v| ProductIdentifierType::from_u8(v as u8)),
                product_identifier_value: item.get_string_owned(&[1]),
            });
        }
    }
    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 != 0x0000 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0000, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_condition(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_degradation_direction(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_change_indication(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_in_place_indicator(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_last_changed_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_replacement_product_list(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, "Condition"),
        (0x0001, "DegradationDirection"),
        (0x0002, "ChangeIndication"),
        (0x0003, "InPlaceIndicator"),
        (0x0004, "LastChangedTime"),
        (0x0005, "ReplacementProductList"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "ResetCondition"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ResetCondition"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, _args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => Ok(vec![]),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `ResetCondition` command on cluster `Water Tank Level Monitoring`.
pub async fn reset_condition(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_CMD_ID_RESETCONDITION, &[]).await?;
    Ok(())
}

/// Read `Condition` attribute from cluster `Water Tank Level Monitoring`.
pub async fn read_condition(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_ATTR_ID_CONDITION).await?;
    decode_condition(&tlv)
}

/// Read `DegradationDirection` attribute from cluster `Water Tank Level Monitoring`.
pub async fn read_degradation_direction(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<DegradationDirection> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_ATTR_ID_DEGRADATIONDIRECTION).await?;
    decode_degradation_direction(&tlv)
}

/// Read `ChangeIndication` attribute from cluster `Water Tank Level Monitoring`.
pub async fn read_change_indication(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ChangeIndication> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_ATTR_ID_CHANGEINDICATION).await?;
    decode_change_indication(&tlv)
}

/// Read `InPlaceIndicator` attribute from cluster `Water Tank Level Monitoring`.
pub async fn read_in_place_indicator(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_ATTR_ID_INPLACEINDICATOR).await?;
    decode_in_place_indicator(&tlv)
}

/// Read `LastChangedTime` attribute from cluster `Water Tank Level Monitoring`.
pub async fn read_last_changed_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_ATTR_ID_LASTCHANGEDTIME).await?;
    decode_last_changed_time(&tlv)
}

/// Read `ReplacementProductList` attribute from cluster `Water Tank Level Monitoring`.
pub async fn read_replacement_product_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ReplacementProduct>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_TANK_LEVEL_MONITORING, crate::clusters::defs::CLUSTER_WATER_TANK_LEVEL_MONITORING_ATTR_ID_REPLACEMENTPRODUCTLIST).await?;
    decode_replacement_product_list(&tlv)
}