matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Commodity Metering Cluster
//! Cluster ID: 0x0B07
//!
//! This file is automatically generated from CommodityMetering.xml

#![allow(clippy::too_many_arguments)]

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


// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct MeteredQuantity {
    pub tariff_component_i_ds: Option<Vec<u32>>,
    pub quantity: Option<i64>,
}

// Attribute decoders

/// Decode MeteredQuantity attribute (0x0000)
pub fn decode_metered_quantity(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<MeteredQuantity>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(MeteredQuantity {
                tariff_component_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                quantity: item.get_int(&[1]).map(|v| v as i64),
            });
        }
    }
    Ok(res)
}

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

/// Decode TariffUnit attribute (0x0002)
pub fn decode_tariff_unit(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode MaximumMeteredQuantities attribute (0x0003)
pub fn decode_maximum_metered_quantities(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u16>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u16))
    } else {
        Ok(None)
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_metered_quantity(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_metered_quantity_timestamp(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_tariff_unit(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_maximum_metered_quantities(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, "MeteredQuantity"),
        (0x0001, "MeteredQuantityTimestamp"),
        (0x0002, "TariffUnit"),
        (0x0003, "MaximumMeteredQuantities"),
    ]
}

// Typed facade (invokes + reads)

/// Read `MeteredQuantity` attribute from cluster `Commodity Metering`.
pub async fn read_metered_quantity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<MeteredQuantity>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_METERING, crate::clusters::defs::CLUSTER_COMMODITY_METERING_ATTR_ID_METEREDQUANTITY).await?;
    decode_metered_quantity(&tlv)
}

/// Read `MeteredQuantityTimestamp` attribute from cluster `Commodity Metering`.
pub async fn read_metered_quantity_timestamp(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_METERING, crate::clusters::defs::CLUSTER_COMMODITY_METERING_ATTR_ID_METEREDQUANTITYTIMESTAMP).await?;
    decode_metered_quantity_timestamp(&tlv)
}

/// Read `TariffUnit` attribute from cluster `Commodity Metering`.
pub async fn read_tariff_unit(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_METERING, crate::clusters::defs::CLUSTER_COMMODITY_METERING_ATTR_ID_TARIFFUNIT).await?;
    decode_tariff_unit(&tlv)
}

/// Read `MaximumMeteredQuantities` attribute from cluster `Commodity Metering`.
pub async fn read_maximum_metered_quantities(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_METERING, crate::clusters::defs::CLUSTER_COMMODITY_METERING_ATTR_ID_MAXIMUMMETEREDQUANTITIES).await?;
    decode_maximum_metered_quantities(&tlv)
}