matc 0.1.3

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

// Bitmap definitions

/// SupportedDeviceCategory bitmap type
pub type SupportedDeviceCategory = u8;

/// Constants for SupportedDeviceCategory
pub mod supporteddevicecategory {
    /// Aggregators which support Fabric Synchronization may be commissioned.
    pub const FABRIC_SYNCHRONIZATION: u8 = 0x01;
}

// Command encoders

/// Encode RequestCommissioningApproval command (0x00)
pub fn encode_request_commissioning_approval(request_id: u64, vendor_id: u16, product_id: u16, label: Option<String>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt64(request_id)).into());
    tlv_fields.push((1, tlv::TlvItemValueEnc::UInt16(vendor_id)).into());
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt16(product_id)).into());
    if let Some(x) = label { tlv_fields.push((3, tlv::TlvItemValueEnc::String(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode CommissionNode command (0x01)
pub fn encode_commission_node(request_id: u64, response_timeout_seconds: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(request_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(response_timeout_seconds)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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


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

    match attribute_id {
        0x0000 => {
            match decode_supported_device_categories(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, "SupportedDeviceCategories"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("RequestCommissioningApproval"),
        0x01 => Some("CommissionNode"),
        _ => 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: "request_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "vendor_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "product_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "label", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "request_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "response_timeout_seconds", kind: crate::clusters::codec::FieldKind::U16, 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 request_id = crate::clusters::codec::json_util::get_u64(args, "request_id")?;
        let vendor_id = crate::clusters::codec::json_util::get_u16(args, "vendor_id")?;
        let product_id = crate::clusters::codec::json_util::get_u16(args, "product_id")?;
        let label = crate::clusters::codec::json_util::get_opt_string(args, "label")?;
        encode_request_commissioning_approval(request_id, vendor_id, product_id, label)
        }
        0x01 => {
        let request_id = crate::clusters::codec::json_util::get_u64(args, "request_id")?;
        let response_timeout_seconds = crate::clusters::codec::json_util::get_u16(args, "response_timeout_seconds")?;
        encode_commission_node(request_id, response_timeout_seconds)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct ReverseOpenCommissioningWindow {
    pub commissioning_timeout: Option<u16>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub pake_passcode_verifier: Option<Vec<u8>>,
    pub discriminator: Option<u16>,
    pub iterations: Option<u32>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub salt: Option<Vec<u8>>,
}

// Command response decoders

/// Decode ReverseOpenCommissioningWindow command response (02)
pub fn decode_reverse_open_commissioning_window(inp: &tlv::TlvItemValue) -> anyhow::Result<ReverseOpenCommissioningWindow> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ReverseOpenCommissioningWindow {
                commissioning_timeout: item.get_int(&[0]).map(|v| v as u16),
                pake_passcode_verifier: item.get_octet_string_owned(&[1]),
                discriminator: item.get_int(&[2]).map(|v| v as u16),
                iterations: item.get_int(&[3]).map(|v| v as u32),
                salt: item.get_octet_string_owned(&[4]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `RequestCommissioningApproval` command on cluster `Commissioner Control`.
pub async fn request_commissioning_approval(conn: &crate::controller::Connection, endpoint: u16, request_id: u64, vendor_id: u16, product_id: u16, label: Option<String>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_COMMISSIONER_CONTROL, crate::clusters::defs::CLUSTER_COMMISSIONER_CONTROL_CMD_ID_REQUESTCOMMISSIONINGAPPROVAL, &encode_request_commissioning_approval(request_id, vendor_id, product_id, label)?).await?;
    Ok(())
}

/// Invoke `CommissionNode` command on cluster `Commissioner Control`.
pub async fn commission_node(conn: &crate::controller::Connection, endpoint: u16, request_id: u64, response_timeout_seconds: u16) -> anyhow::Result<ReverseOpenCommissioningWindow> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMISSIONER_CONTROL, crate::clusters::defs::CLUSTER_COMMISSIONER_CONTROL_CMD_ID_COMMISSIONNODE, &encode_commission_node(request_id, response_timeout_seconds)?).await?;
    decode_reverse_open_commissioning_window(&tlv)
}

/// Read `SupportedDeviceCategories` attribute from cluster `Commissioner Control`.
pub async fn read_supported_device_categories(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<SupportedDeviceCategory> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMISSIONER_CONTROL, crate::clusters::defs::CLUSTER_COMMISSIONER_CONTROL_ATTR_ID_SUPPORTEDDEVICECATEGORIES).await?;
    decode_supported_device_categories(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct CommissioningRequestResultEvent {
    pub request_id: Option<u64>,
    pub client_node_id: Option<u64>,
    pub status_code: Option<u8>,
}

// Event decoders

/// Decode CommissioningRequestResult event (0x00, priority: info)
pub fn decode_commissioning_request_result_event(inp: &tlv::TlvItemValue) -> anyhow::Result<CommissioningRequestResultEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(CommissioningRequestResultEvent {
                                request_id: item.get_int(&[0]),
                                client_node_id: item.get_int(&[1]),
                                status_code: item.get_int(&[2]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}