matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Wi-Fi Network Management Cluster
//! Cluster ID: 0x0451
//!
//! This file is automatically generated from WiFiNetworkManagement.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};

// Command encoders

// Attribute decoders

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

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

    match attribute_id {
        0x0000 => {
            match decode_ssid(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_passphrase_surrogate(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, "SSID"),
        (0x0001, "PassphraseSurrogate"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("NetworkPassphraseRequest"),
        _ => 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)),
    }
}

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

// Command response decoders

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

// Typed facade (invokes + reads)

/// Invoke `NetworkPassphraseRequest` command on cluster `Wi-Fi Network Management`.
pub async fn network_passphrase_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<NetworkPassphraseResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WI_FI_NETWORK_MANAGEMENT, crate::clusters::defs::CLUSTER_WI_FI_NETWORK_MANAGEMENT_CMD_ID_NETWORKPASSPHRASEREQUEST, &[]).await?;
    decode_network_passphrase_response(&tlv)
}

/// Read `SSID` attribute from cluster `Wi-Fi Network Management`.
pub async fn read_ssid(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Vec<u8>>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WI_FI_NETWORK_MANAGEMENT, crate::clusters::defs::CLUSTER_WI_FI_NETWORK_MANAGEMENT_ATTR_ID_SSID).await?;
    decode_ssid(&tlv)
}

/// Read `PassphraseSurrogate` attribute from cluster `Wi-Fi Network Management`.
pub async fn read_passphrase_surrogate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WI_FI_NETWORK_MANAGEMENT, crate::clusters::defs::CLUSTER_WI_FI_NETWORK_MANAGEMENT_ATTR_ID_PASSPHRASESURROGATE).await?;
    decode_passphrase_surrogate(&tlv)
}