matc 0.1.3

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

// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
    /// The endpoint is already installed.
    Endpointalreadyinstalled = 2,
    /// No root certificate exists for this CAID.
    Rootcertificatenotfound = 3,
    /// No client certificate exists for this CCDID.
    Clientcertificatenotfound = 4,
    /// The endpoint is in use and cannot be removed.
    Endpointinuse = 5,
    /// Time sync has not yet occurred.
    Invalidtime = 6,
}

impl StatusCode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            2 => Some(StatusCode::Endpointalreadyinstalled),
            3 => Some(StatusCode::Rootcertificatenotfound),
            4 => Some(StatusCode::Clientcertificatenotfound),
            5 => Some(StatusCode::Endpointinuse),
            6 => Some(StatusCode::Invalidtime),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<StatusCode> for u8 {
    fn from(val: StatusCode) -> Self {
        val as u8
    }
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct TLSEndpoint {
    pub endpoint_id: Option<u8>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub hostname: Option<Vec<u8>>,
    pub port: Option<u16>,
    pub caid: Option<u8>,
    pub ccdid: Option<u8>,
    pub reference_count: Option<u8>,
}

// Command encoders

/// Encode ProvisionEndpoint command (0x00)
pub fn encode_provision_endpoint(hostname: Vec<u8>, port: u16, caid: u8, ccdid: Option<u8>, endpoint_id: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(hostname)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(port)).into(),
        (2, tlv::TlvItemValueEnc::UInt8(caid)).into(),
        (3, tlv::TlvItemValueEnc::UInt8(ccdid.unwrap_or(0))).into(),
        (4, tlv::TlvItemValueEnc::UInt8(endpoint_id.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

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

// Attribute decoders

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

/// Decode ProvisionedEndpoints attribute (0x0001)
pub fn decode_provisioned_endpoints(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TLSEndpoint>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TLSEndpoint {
                endpoint_id: item.get_int(&[0]).map(|v| v as u8),
                hostname: item.get_octet_string_owned(&[1]),
                port: item.get_int(&[2]).map(|v| v as u16),
                caid: item.get_int(&[3]).map(|v| v as u8),
                ccdid: item.get_int(&[4]).map(|v| v as u8),
                reference_count: item.get_int(&[5]).map(|v| v as u8),
            });
        }
    }
    Ok(res)
}


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

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

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ProvisionEndpoint"),
        0x02 => Some("FindEndpoint"),
        0x04 => Some("RemoveEndpoint"),
        _ => 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: "hostname", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "port", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "caid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "ccdid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
            crate::clusters::codec::CommandField { tag: 4, name: "endpoint_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "endpoint_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "endpoint_id", kind: crate::clusters::codec::FieldKind::U32, 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 hostname = crate::clusters::codec::json_util::get_octstr(args, "hostname")?;
        let port = crate::clusters::codec::json_util::get_u16(args, "port")?;
        let caid = crate::clusters::codec::json_util::get_u8(args, "caid")?;
        let ccdid = crate::clusters::codec::json_util::get_opt_u8(args, "ccdid")?;
        let endpoint_id = crate::clusters::codec::json_util::get_opt_u8(args, "endpoint_id")?;
        encode_provision_endpoint(hostname, port, caid, ccdid, endpoint_id)
        }
        0x02 => {
        let endpoint_id = crate::clusters::codec::json_util::get_u8(args, "endpoint_id")?;
        encode_find_endpoint(endpoint_id)
        }
        0x04 => {
        let endpoint_id = crate::clusters::codec::json_util::get_u8(args, "endpoint_id")?;
        encode_remove_endpoint(endpoint_id)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct ProvisionEndpointResponse {
    pub endpoint_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct FindEndpointResponse {
    pub endpoint: Option<TLSEndpoint>,
}

// Command response decoders

/// Decode ProvisionEndpointResponse command response (01)
pub fn decode_provision_endpoint_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ProvisionEndpointResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ProvisionEndpointResponse {
                endpoint_id: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode FindEndpointResponse command response (03)
pub fn decode_find_endpoint_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindEndpointResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(FindEndpointResponse {
                endpoint: {
                    if let Some(nested_tlv) = item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(TLSEndpoint {
                endpoint_id: nested_item.get_int(&[0]).map(|v| v as u8),
                hostname: nested_item.get_octet_string_owned(&[1]),
                port: nested_item.get_int(&[2]).map(|v| v as u16),
                caid: nested_item.get_int(&[3]).map(|v| v as u8),
                ccdid: nested_item.get_int(&[4]).map(|v| v as u8),
                reference_count: nested_item.get_int(&[5]).map(|v| v as u8),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `ProvisionEndpoint` command on cluster `TLS Client Management`.
pub async fn provision_endpoint(conn: &crate::controller::Connection, endpoint: u16, hostname: Vec<u8>, port: u16, caid: u8, ccdid: Option<u8>, endpoint_id: Option<u8>) -> anyhow::Result<ProvisionEndpointResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CLIENT_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CLIENT_MANAGEMENT_CMD_ID_PROVISIONENDPOINT, &encode_provision_endpoint(hostname, port, caid, ccdid, endpoint_id)?).await?;
    decode_provision_endpoint_response(&tlv)
}

/// Invoke `FindEndpoint` command on cluster `TLS Client Management`.
pub async fn find_endpoint(conn: &crate::controller::Connection, endpoint: u16, endpoint_id: u8) -> anyhow::Result<FindEndpointResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CLIENT_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CLIENT_MANAGEMENT_CMD_ID_FINDENDPOINT, &encode_find_endpoint(endpoint_id)?).await?;
    decode_find_endpoint_response(&tlv)
}

/// Invoke `RemoveEndpoint` command on cluster `TLS Client Management`.
pub async fn remove_endpoint(conn: &crate::controller::Connection, endpoint: u16, endpoint_id: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CLIENT_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CLIENT_MANAGEMENT_CMD_ID_REMOVEENDPOINT, &encode_remove_endpoint(endpoint_id)?).await?;
    Ok(())
}

/// Read `MaxProvisioned` attribute from cluster `TLS Client Management`.
pub async fn read_max_provisioned(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CLIENT_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CLIENT_MANAGEMENT_ATTR_ID_MAXPROVISIONED).await?;
    decode_max_provisioned(&tlv)
}

/// Read `ProvisionedEndpoints` attribute from cluster `TLS Client Management`.
pub async fn read_provisioned_endpoints(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TLSEndpoint>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CLIENT_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CLIENT_MANAGEMENT_ATTR_ID_PROVISIONEDENDPOINTS).await?;
    decode_provisioned_endpoints(&tlv)
}