matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Thread Border Router Management Cluster
//! Cluster ID: 0x0452
//!
//! This file is automatically generated from ThreadBorderRouterManagement.xml

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


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

// Command encoders

/// Encode SetActiveDatasetRequest command (0x03)
pub fn encode_set_active_dataset_request(active_dataset: Vec<u8>, breadcrumb: u64) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(active_dataset)).into(),
        (1, tlv::TlvItemValueEnc::UInt64(breadcrumb)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetPendingDatasetRequest command (0x04)
pub fn encode_set_pending_dataset_request(pending_dataset: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(pending_dataset)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode BorderRouterName attribute (0x0000)
pub fn decode_border_router_name(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected String"))
    }
}

/// Decode BorderAgentID attribute (0x0001)
pub fn decode_border_agent_id(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u8>> {
    if let tlv::TlvItemValue::OctetString(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected OctetString"))
    }
}

/// Decode ThreadVersion attribute (0x0002)
pub fn decode_thread_version(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

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

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

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

    match attribute_id {
        0x0000 => {
            match decode_border_router_name(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_border_agent_id(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_thread_version(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_interface_enabled(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_active_dataset_timestamp(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_pending_dataset_timestamp(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, "BorderRouterName"),
        (0x0001, "BorderAgentID"),
        (0x0002, "ThreadVersion"),
        (0x0003, "InterfaceEnabled"),
        (0x0004, "ActiveDatasetTimestamp"),
        (0x0005, "PendingDatasetTimestamp"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct DatasetResponse {
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub dataset: Option<Vec<u8>>,
}

// Command response decoders

/// Decode DatasetResponse command response (02)
pub fn decode_dataset_response(inp: &tlv::TlvItemValue) -> anyhow::Result<DatasetResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(DatasetResponse {
                dataset: item.get_octet_string_owned(&[0]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}