matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Thread Network Directory Cluster
//! Cluster ID: 0x0453
//!
//! This file is automatically generated from ThreadNetworkDirectory.xml

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 ThreadNetwork {
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub extended_pan_id: Option<Vec<u8>>,
    pub network_name: Option<String>,
    pub channel: Option<u16>,
    pub active_timestamp: Option<u64>,
}

// Command encoders

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

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

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

// Attribute decoders

/// Decode PreferredExtendedPanID attribute (0x0000)
pub fn decode_preferred_extended_pan_id(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Vec<u8>>> {
    if let tlv::TlvItemValue::OctetString(v) = inp {
        Ok(Some(v.clone()))
    } else {
        Ok(None)
    }
}

/// Decode ThreadNetworks attribute (0x0001)
pub fn decode_thread_networks(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ThreadNetwork>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ThreadNetwork {
                extended_pan_id: item.get_octet_string_owned(&[0]),
                network_name: item.get_string_owned(&[1]),
                channel: item.get_int(&[2]).map(|v| v as u16),
                active_timestamp: item.get_int(&[3]),
            });
        }
    }
    Ok(res)
}

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


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

    match attribute_id {
        0x0000 => {
            match decode_preferred_extended_pan_id(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_thread_networks(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_thread_network_table_size(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, "PreferredExtendedPanID"),
        (0x0001, "ThreadNetworks"),
        (0x0002, "ThreadNetworkTableSize"),
    ]
}

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

// Command response decoders

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