matc 0.1.2

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

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: String) -> 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(vendor_id)).into(),
        (2, tlv::TlvItemValueEnc::UInt16(product_id)).into(),
        (3, tlv::TlvItemValueEnc::String(label)).into(),
        ]),
    };
    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"),
    ]
}

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

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