matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Meter Identification Cluster
//! Cluster ID: 0x0B06
//!
//! This file is automatically generated from MeterIdentification.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 MeterType {
    /// Utility Meter
    Utility = 0,
    /// Private Meter
    Private = 1,
    /// Generic Meter
    Generic = 2,
}

impl MeterType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(MeterType::Utility),
            1 => Some(MeterType::Private),
            2 => Some(MeterType::Generic),
            _ => None,
        }
    }

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

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

// Attribute decoders

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

/// Decode PointOfDelivery attribute (0x0001)
pub fn decode_point_of_delivery(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<String>> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(Some(v.clone()))
    } else {
        Ok(None)
    }
}

/// Decode MeterSerialNumber attribute (0x0002)
pub fn decode_meter_serial_number(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<String>> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(Some(v.clone()))
    } else {
        Ok(None)
    }
}

/// Decode ProtocolVersion attribute (0x0003)
pub fn decode_protocol_version(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<String>> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(Some(v.clone()))
    } else {
        Ok(None)
    }
}

/// Decode PowerThreshold attribute (0x0004)
pub fn decode_power_threshold(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } 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 != 0x0B06 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0B06, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_meter_type(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_point_of_delivery(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_meter_serial_number(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_protocol_version(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_power_threshold(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, "MeterType"),
        (0x0001, "PointOfDelivery"),
        (0x0002, "MeterSerialNumber"),
        (0x0003, "ProtocolVersion"),
        (0x0004, "PowerThreshold"),
    ]
}

// Typed facade (invokes + reads)

/// Read `MeterType` attribute from cluster `Meter Identification`.
pub async fn read_meter_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<MeterType>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_METER_IDENTIFICATION, crate::clusters::defs::CLUSTER_METER_IDENTIFICATION_ATTR_ID_METERTYPE).await?;
    decode_meter_type(&tlv)
}

/// Read `PointOfDelivery` attribute from cluster `Meter Identification`.
pub async fn read_point_of_delivery(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<String>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_METER_IDENTIFICATION, crate::clusters::defs::CLUSTER_METER_IDENTIFICATION_ATTR_ID_POINTOFDELIVERY).await?;
    decode_point_of_delivery(&tlv)
}

/// Read `MeterSerialNumber` attribute from cluster `Meter Identification`.
pub async fn read_meter_serial_number(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<String>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_METER_IDENTIFICATION, crate::clusters::defs::CLUSTER_METER_IDENTIFICATION_ATTR_ID_METERSERIALNUMBER).await?;
    decode_meter_serial_number(&tlv)
}

/// Read `ProtocolVersion` attribute from cluster `Meter Identification`.
pub async fn read_protocol_version(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<String>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_METER_IDENTIFICATION, crate::clusters::defs::CLUSTER_METER_IDENTIFICATION_ATTR_ID_PROTOCOLVERSION).await?;
    decode_protocol_version(&tlv)
}

/// Read `PowerThreshold` attribute from cluster `Meter Identification`.
pub async fn read_power_threshold(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_METER_IDENTIFICATION, crate::clusters::defs::CLUSTER_METER_IDENTIFICATION_ATTR_ID_POWERTHRESHOLD).await?;
    decode_power_threshold(&tlv)
}