matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Software Diagnostics Cluster
//! Cluster ID: 0x0034
//!
//! This file is automatically generated from DiagnosticsSoftware.xml

#![allow(clippy::too_many_arguments)]

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


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ThreadMetrics {
    pub id: Option<u64>,
    pub name: Option<String>,
    pub stack_free_current: Option<u32>,
    pub stack_free_minimum: Option<u32>,
    pub stack_size: Option<u32>,
}

// Command encoders

// Attribute decoders

/// Decode ThreadMetrics attribute (0x0000)
pub fn decode_thread_metrics(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ThreadMetrics>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ThreadMetrics {
                id: item.get_int(&[0]),
                name: item.get_string_owned(&[1]),
                stack_free_current: item.get_int(&[2]).map(|v| v as u32),
                stack_free_minimum: item.get_int(&[3]).map(|v| v as u32),
                stack_size: item.get_int(&[4]).map(|v| v as u32),
            });
        }
    }
    Ok(res)
}

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

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

/// Decode CurrentHeapHighWatermark attribute (0x0003)
pub fn decode_current_heap_high_watermark(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 != 0x0034 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0034, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_thread_metrics(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_heap_free(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_current_heap_used(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_current_heap_high_watermark(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, "ThreadMetrics"),
        (0x0001, "CurrentHeapFree"),
        (0x0002, "CurrentHeapUsed"),
        (0x0003, "CurrentHeapHighWatermark"),
    ]
}

// Command listing

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

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

/// Read `ThreadMetrics` attribute from cluster `Software Diagnostics`.
pub async fn read_thread_metrics(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ThreadMetrics>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SOFTWARE_DIAGNOSTICS, crate::clusters::defs::CLUSTER_SOFTWARE_DIAGNOSTICS_ATTR_ID_THREADMETRICS).await?;
    decode_thread_metrics(&tlv)
}

/// Read `CurrentHeapFree` attribute from cluster `Software Diagnostics`.
pub async fn read_current_heap_free(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SOFTWARE_DIAGNOSTICS, crate::clusters::defs::CLUSTER_SOFTWARE_DIAGNOSTICS_ATTR_ID_CURRENTHEAPFREE).await?;
    decode_current_heap_free(&tlv)
}

/// Read `CurrentHeapUsed` attribute from cluster `Software Diagnostics`.
pub async fn read_current_heap_used(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SOFTWARE_DIAGNOSTICS, crate::clusters::defs::CLUSTER_SOFTWARE_DIAGNOSTICS_ATTR_ID_CURRENTHEAPUSED).await?;
    decode_current_heap_used(&tlv)
}

/// Read `CurrentHeapHighWatermark` attribute from cluster `Software Diagnostics`.
pub async fn read_current_heap_high_watermark(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SOFTWARE_DIAGNOSTICS, crate::clusters::defs::CLUSTER_SOFTWARE_DIAGNOSTICS_ATTR_ID_CURRENTHEAPHIGHWATERMARK).await?;
    decode_current_heap_high_watermark(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct SoftwareFaultEvent {
    pub id: Option<u64>,
    pub name: Option<String>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub fault_recording: Option<Vec<u8>>,
}

// Event decoders

/// Decode SoftwareFault event (0x00, priority: info)
pub fn decode_software_fault_event(inp: &tlv::TlvItemValue) -> anyhow::Result<SoftwareFaultEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(SoftwareFaultEvent {
                                id: item.get_int(&[0]),
                                name: item.get_string_owned(&[1]),
                                fault_recording: item.get_octet_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}