matc 0.1.3

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

#![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 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"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("AddNetwork"),
        0x01 => Some("RemoveNetwork"),
        0x02 => Some("GetOperationalDataset"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "operational_dataset", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "extended_pan_id", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "extended_pan_id", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let operational_dataset = crate::clusters::codec::json_util::get_octstr(args, "operational_dataset")?;
        encode_add_network(operational_dataset)
        }
        0x01 => {
        let extended_pan_id = crate::clusters::codec::json_util::get_octstr(args, "extended_pan_id")?;
        encode_remove_network(extended_pan_id)
        }
        0x02 => {
        let extended_pan_id = crate::clusters::codec::json_util::get_octstr(args, "extended_pan_id")?;
        encode_get_operational_dataset(extended_pan_id)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[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"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `AddNetwork` command on cluster `Thread Network Directory`.
pub async fn add_network(conn: &crate::controller::Connection, endpoint: u16, operational_dataset: Vec<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_CMD_ID_ADDNETWORK, &encode_add_network(operational_dataset)?).await?;
    Ok(())
}

/// Invoke `RemoveNetwork` command on cluster `Thread Network Directory`.
pub async fn remove_network(conn: &crate::controller::Connection, endpoint: u16, extended_pan_id: Vec<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_CMD_ID_REMOVENETWORK, &encode_remove_network(extended_pan_id)?).await?;
    Ok(())
}

/// Invoke `GetOperationalDataset` command on cluster `Thread Network Directory`.
pub async fn get_operational_dataset(conn: &crate::controller::Connection, endpoint: u16, extended_pan_id: Vec<u8>) -> anyhow::Result<OperationalDatasetResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_CMD_ID_GETOPERATIONALDATASET, &encode_get_operational_dataset(extended_pan_id)?).await?;
    decode_operational_dataset_response(&tlv)
}

/// Read `PreferredExtendedPanID` attribute from cluster `Thread Network Directory`.
pub async fn read_preferred_extended_pan_id(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Vec<u8>>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_ATTR_ID_PREFERREDEXTENDEDPANID).await?;
    decode_preferred_extended_pan_id(&tlv)
}

/// Read `ThreadNetworks` attribute from cluster `Thread Network Directory`.
pub async fn read_thread_networks(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ThreadNetwork>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_ATTR_ID_THREADNETWORKS).await?;
    decode_thread_networks(&tlv)
}

/// Read `ThreadNetworkTableSize` attribute from cluster `Thread Network Directory`.
pub async fn read_thread_network_table_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_ATTR_ID_THREADNETWORKTABLESIZE).await?;
    decode_thread_network_table_size(&tlv)
}