matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Ethernet Network Diagnostics Cluster
//! Cluster ID: 0x0037
//!
//! This file is automatically generated from DiagnosticsEthernet.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 PHYRate {
    /// PHY rate is 10Mbps
    Rate10m = 0,
    /// PHY rate is 100Mbps
    Rate100m = 1,
    /// PHY rate is 1Gbps
    Rate1g = 2,
    /// PHY rate is 2.5Gbps
    Rate25g = 3,
    /// PHY rate is 5Gbps
    Rate5g = 4,
    /// PHY rate is 10Gbps
    Rate10g = 5,
    /// PHY rate is 40Gbps
    Rate40g = 6,
    /// PHY rate is 100Gbps
    Rate100g = 7,
    /// PHY rate is 200Gbps
    Rate200g = 8,
    /// PHY rate is 400Gbps
    Rate400g = 9,
}

impl PHYRate {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(PHYRate::Rate10m),
            1 => Some(PHYRate::Rate100m),
            2 => Some(PHYRate::Rate1g),
            3 => Some(PHYRate::Rate25g),
            4 => Some(PHYRate::Rate5g),
            5 => Some(PHYRate::Rate10g),
            6 => Some(PHYRate::Rate40g),
            7 => Some(PHYRate::Rate100g),
            8 => Some(PHYRate::Rate200g),
            9 => Some(PHYRate::Rate400g),
            _ => None,
        }
    }

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

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

// Command encoders

// Attribute decoders

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

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

/// Decode PacketRxCount attribute (0x0002)
pub fn decode_packet_rx_count(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

/// Decode PacketTxCount attribute (0x0003)
pub fn decode_packet_tx_count(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

/// Decode TxErrCount attribute (0x0004)
pub fn decode_tx_err_count(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

/// Decode CollisionCount attribute (0x0005)
pub fn decode_collision_count(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

/// Decode OverrunCount attribute (0x0006)
pub fn decode_overrun_count(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

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

/// Decode TimeSinceReset attribute (0x0008)
pub fn decode_time_since_reset(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_phy_rate(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_full_duplex(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_packet_rx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_packet_tx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_tx_err_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_collision_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_overrun_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_carrier_detect(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_time_since_reset(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, "PHYRate"),
        (0x0001, "FullDuplex"),
        (0x0002, "PacketRxCount"),
        (0x0003, "PacketTxCount"),
        (0x0004, "TxErrCount"),
        (0x0005, "CollisionCount"),
        (0x0006, "OverrunCount"),
        (0x0007, "CarrierDetect"),
        (0x0008, "TimeSinceReset"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ResetCounts"),
        _ => 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 `ResetCounts` command on cluster `Ethernet Network Diagnostics`.
pub async fn reset_counts(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_CMD_ID_RESETCOUNTS, &[]).await?;
    Ok(())
}

/// Read `PHYRate` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_phy_rate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<PHYRate>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_PHYRATE).await?;
    decode_phy_rate(&tlv)
}

/// Read `FullDuplex` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_full_duplex(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<bool>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_FULLDUPLEX).await?;
    decode_full_duplex(&tlv)
}

/// Read `PacketRxCount` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_packet_rx_count(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_PACKETRXCOUNT).await?;
    decode_packet_rx_count(&tlv)
}

/// Read `PacketTxCount` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_packet_tx_count(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_PACKETTXCOUNT).await?;
    decode_packet_tx_count(&tlv)
}

/// Read `TxErrCount` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_tx_err_count(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_TXERRCOUNT).await?;
    decode_tx_err_count(&tlv)
}

/// Read `CollisionCount` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_collision_count(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_COLLISIONCOUNT).await?;
    decode_collision_count(&tlv)
}

/// Read `OverrunCount` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_overrun_count(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_OVERRUNCOUNT).await?;
    decode_overrun_count(&tlv)
}

/// Read `CarrierDetect` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_carrier_detect(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<bool>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_CARRIERDETECT).await?;
    decode_carrier_detect(&tlv)
}

/// Read `TimeSinceReset` attribute from cluster `Ethernet Network Diagnostics`.
pub async fn read_time_since_reset(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ETHERNET_NETWORK_DIAGNOSTICS, crate::clusters::defs::CLUSTER_ETHERNET_NETWORK_DIAGNOSTICS_ATTR_ID_TIMESINCERESET).await?;
    decode_time_since_reset(&tlv)
}