matc 0.1.3

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

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

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "ICACCSRRequest"),
        (0x02, "AddICAC"),
        (0x04, "OpenJointCommissioningWindow"),
        (0x05, "TransferAnchorRequest"),
        (0x07, "TransferAnchorComplete"),
        (0x08, "AnnounceJointFabricAdministrator"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ICACCSRRequest"),
        0x02 => Some("AddICAC"),
        0x04 => Some("OpenJointCommissioningWindow"),
        0x05 => Some("TransferAnchorRequest"),
        0x07 => Some("TransferAnchorComplete"),
        0x08 => Some("AnnounceJointFabricAdministrator"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 1, name: "icac_value", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "commissioning_timeout", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "pake_passcode_verifier", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "discriminator", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "iterations", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 4, name: "salt", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        0x05 => Some(vec![]),
        0x07 => Some(vec![]),
        0x08 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "endpoint_id", 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 => Ok(vec![]),
        0x02 => {
        let icac_value = crate::clusters::codec::json_util::get_octstr(args, "icac_value")?;
        encode_add_icac(icac_value)
        }
        0x04 => {
        let commissioning_timeout = crate::clusters::codec::json_util::get_u16(args, "commissioning_timeout")?;
        let pake_passcode_verifier = crate::clusters::codec::json_util::get_octstr(args, "pake_passcode_verifier")?;
        let discriminator = crate::clusters::codec::json_util::get_u16(args, "discriminator")?;
        let iterations = crate::clusters::codec::json_util::get_u32(args, "iterations")?;
        let salt = crate::clusters::codec::json_util::get_octstr(args, "salt")?;
        encode_open_joint_commissioning_window(commissioning_timeout, pake_passcode_verifier, discriminator, iterations, salt)
        }
        0x05 => Ok(vec![]),
        0x07 => Ok(vec![]),
        0x08 => {
        let endpoint_id = crate::clusters::codec::json_util::get_u16(args, "endpoint_id")?;
        encode_announce_joint_fabric_administrator(endpoint_id)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

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

// Typed facade (invokes + reads)

/// Invoke `ICACCSRRequest` command on cluster `Joint Fabric Administrator`.
pub async fn icaccsr_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ICACCSRResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_ICACCSRREQUEST, &[]).await?;
    decode_icaccsr_response(&tlv)
}

/// Invoke `AddICAC` command on cluster `Joint Fabric Administrator`.
pub async fn add_icac(conn: &crate::controller::Connection, endpoint: u16, icac_value: Vec<u8>) -> anyhow::Result<ICACResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_ADDICAC, &encode_add_icac(icac_value)?).await?;
    decode_icac_response(&tlv)
}

/// Invoke `OpenJointCommissioningWindow` command on cluster `Joint Fabric Administrator`.
pub async fn open_joint_commissioning_window(conn: &crate::controller::Connection, endpoint: u16, commissioning_timeout: u16, pake_passcode_verifier: Vec<u8>, discriminator: u16, iterations: u32, salt: Vec<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_OPENJOINTCOMMISSIONINGWINDOW, &encode_open_joint_commissioning_window(commissioning_timeout, pake_passcode_verifier, discriminator, iterations, salt)?).await?;
    Ok(())
}

/// Invoke `TransferAnchorRequest` command on cluster `Joint Fabric Administrator`.
pub async fn transfer_anchor_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TransferAnchorResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_TRANSFERANCHORREQUEST, &[]).await?;
    decode_transfer_anchor_response(&tlv)
}

/// Invoke `TransferAnchorComplete` command on cluster `Joint Fabric Administrator`.
pub async fn transfer_anchor_complete(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_TRANSFERANCHORCOMPLETE, &[]).await?;
    Ok(())
}

/// Invoke `AnnounceJointFabricAdministrator` command on cluster `Joint Fabric Administrator`.
pub async fn announce_joint_fabric_administrator(conn: &crate::controller::Connection, endpoint: u16, endpoint_id: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_ANNOUNCEJOINTFABRICADMINISTRATOR, &encode_announce_joint_fabric_administrator(endpoint_id)?).await?;
    Ok(())
}

/// Read `AdministratorFabricIndex` attribute from cluster `Joint Fabric Administrator`.
pub async fn read_administrator_fabric_index(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_ATTR_ID_ADMINISTRATORFABRICINDEX).await?;
    decode_administrator_fabric_index(&tlv)
}