matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Joint Fabric Administrator Cluster
//! Cluster ID: 0x0753
//!
//! This file is automatically generated from JointFabricAdministratorCluster.xml

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 ICACResponseStatus {
    /// No error
    Ok = 0,
    /// Public Key in the ICAC is invalid
    Invalidpublickey = 1,
    /// ICAC chain validation failed / ICAC DN Encoding rules verification failed
    Invalidicac = 2,
}

impl ICACResponseStatus {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ICACResponseStatus::Ok),
            1 => Some(ICACResponseStatus::Invalidpublickey),
            2 => Some(ICACResponseStatus::Invalidicac),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
    /// Could not be completed because another commissioning is in progress
    Busy = 2,
    /// Provided PAKE parameters were incorrectly formatted or otherwise invalid
    Pakeparametererror = 3,
    /// No commissioning window was currently open
    Windownotopen = 4,
    /// ICACCSRRequest command has been invoked by a peer against which Fabric Table VID Verification hasn't been executed
    Vidnotverified = 5,
    /// OpenJointCommissioningWindow command has been invoked but the AdministratorFabricIndex field has the value of null
    Invalidadministratorfabricindex = 6,
}

impl StatusCode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            2 => Some(StatusCode::Busy),
            3 => Some(StatusCode::Pakeparametererror),
            4 => Some(StatusCode::Windownotopen),
            5 => Some(StatusCode::Vidnotverified),
            6 => Some(StatusCode::Invalidadministratorfabricindex),
            _ => 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
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TransferAnchorResponseStatus {
    /// No error
    Ok = 0,
    /// Anchor Transfer was not started due to on-going Datastore operations
    Transferanchorstatusdatastorebusy = 1,
    /// User has not consented for Anchor Transfer
    Transferanchorstatusnouserconsent = 2,
}

impl TransferAnchorResponseStatus {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(TransferAnchorResponseStatus::Ok),
            1 => Some(TransferAnchorResponseStatus::Transferanchorstatusdatastorebusy),
            2 => Some(TransferAnchorResponseStatus::Transferanchorstatusnouserconsent),
            _ => None,
        }
    }

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

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

// Command encoders

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

/// Encode OpenJointCommissioningWindow command (0x04)
pub fn encode_open_joint_commissioning_window(commissioning_timeout: u16, pake_passcode_verifier: Vec<u8>, discriminator: u16, iterations: u32, salt: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(commissioning_timeout)).into(),
        (1, tlv::TlvItemValueEnc::OctetString(pake_passcode_verifier)).into(),
        (2, tlv::TlvItemValueEnc::UInt16(discriminator)).into(),
        (3, tlv::TlvItemValueEnc::UInt32(iterations)).into(),
        (4, tlv::TlvItemValueEnc::OctetString(salt)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

// Attribute decoders

/// Decode AdministratorFabricIndex attribute (0x0000)
pub fn decode_administrator_fabric_index(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } 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 != 0x0753 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0753, got {}\"}}", cluster_id);
    }

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

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

#[derive(Debug, serde::Serialize)]
pub struct ICACResponse {
    pub status_code: Option<ICACResponseStatus>,
}

#[derive(Debug, serde::Serialize)]
pub struct TransferAnchorResponse {
    pub status_code: Option<TransferAnchorResponseStatus>,
}

// Command response decoders

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

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

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