matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for WebRTC Transport Provider Cluster
//! Cluster ID: 0x0553
//!
//! This file is automatically generated from WebRTC_Provider.xml

use crate::tlv;
use anyhow;
use serde_json;


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct SFrame {
    pub cipher_suite: Option<u16>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub base_key: Option<Vec<u8>>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub kid: Option<Vec<u8>>,
}

// Command encoders

/// Parameters for SolicitOffer command
pub struct SolicitOfferParams {
    pub stream_usage: u8,
    pub originating_endpoint_id: u16,
    pub video_stream_id: Option<u8>,
    pub audio_stream_id: Option<u8>,
    pub ice_transport_policy: String,
    pub metadata_enabled: bool,
    pub s_frame_config: SFrame,
    pub video_streams: Vec<u8>,
    pub audio_streams: Vec<u8>,
}

/// Encode SolicitOffer command (0x00)
pub fn encode_solicit_offer(params: SolicitOfferParams) -> anyhow::Result<Vec<u8>> {
            // Encode struct SFrameStruct
            let mut s_frame_config_fields = Vec::new();
            if let Some(x) = params.s_frame_config.cipher_suite { s_frame_config_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
            if let Some(x) = params.s_frame_config.base_key { s_frame_config_fields.push((1, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
            if let Some(x) = params.s_frame_config.kid { s_frame_config_fields.push((2, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(params.stream_usage)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(params.originating_endpoint_id)).into(),
        (2, tlv::TlvItemValueEnc::UInt8(params.video_stream_id.unwrap_or(0))).into(),
        (3, tlv::TlvItemValueEnc::UInt8(params.audio_stream_id.unwrap_or(0))).into(),
        (5, tlv::TlvItemValueEnc::String(params.ice_transport_policy)).into(),
        (6, tlv::TlvItemValueEnc::Bool(params.metadata_enabled)).into(),
        (7, tlv::TlvItemValueEnc::StructInvisible(s_frame_config_fields)).into(),
        (8, tlv::TlvItemValueEnc::StructAnon(params.video_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
        (9, tlv::TlvItemValueEnc::StructAnon(params.audio_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Parameters for ProvideOffer command
pub struct ProvideOfferParams {
    pub web_rtc_session_id: Option<u8>,
    pub sdp: String,
    pub stream_usage: u8,
    pub originating_endpoint_id: u16,
    pub video_stream_id: Option<u8>,
    pub audio_stream_id: Option<u8>,
    pub ice_transport_policy: String,
    pub metadata_enabled: bool,
    pub s_frame_config: SFrame,
    pub video_streams: Vec<u8>,
    pub audio_streams: Vec<u8>,
}

/// Encode ProvideOffer command (0x02)
pub fn encode_provide_offer(params: ProvideOfferParams) -> anyhow::Result<Vec<u8>> {
            // Encode struct SFrameStruct
            let mut s_frame_config_fields = Vec::new();
            if let Some(x) = params.s_frame_config.cipher_suite { s_frame_config_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
            if let Some(x) = params.s_frame_config.base_key { s_frame_config_fields.push((1, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
            if let Some(x) = params.s_frame_config.kid { s_frame_config_fields.push((2, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(params.web_rtc_session_id.unwrap_or(0))).into(),
        (1, tlv::TlvItemValueEnc::String(params.sdp)).into(),
        (2, tlv::TlvItemValueEnc::UInt8(params.stream_usage)).into(),
        (3, tlv::TlvItemValueEnc::UInt16(params.originating_endpoint_id)).into(),
        (4, tlv::TlvItemValueEnc::UInt8(params.video_stream_id.unwrap_or(0))).into(),
        (5, tlv::TlvItemValueEnc::UInt8(params.audio_stream_id.unwrap_or(0))).into(),
        (7, tlv::TlvItemValueEnc::String(params.ice_transport_policy)).into(),
        (8, tlv::TlvItemValueEnc::Bool(params.metadata_enabled)).into(),
        (9, tlv::TlvItemValueEnc::StructInvisible(s_frame_config_fields)).into(),
        (10, tlv::TlvItemValueEnc::StructAnon(params.video_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
        (11, tlv::TlvItemValueEnc::StructAnon(params.audio_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

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

/// Encode EndSession command (0x06)
pub fn encode_end_session(web_rtc_session_id: u8, reason: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(web_rtc_session_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(reason)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode CurrentSessions attribute (0x0000)
pub fn decode_current_sessions(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u8>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                res.push(*i 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 != 0x0553 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0553, got {}\"}}", cluster_id);
    }

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

#[derive(Debug, serde::Serialize)]
pub struct SolicitOfferResponse {
    pub web_rtc_session_id: Option<u8>,
    pub deferred_offer: Option<bool>,
    pub video_stream_id: Option<u8>,
    pub audio_stream_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct ProvideOfferResponse {
    pub web_rtc_session_id: Option<u8>,
    pub video_stream_id: Option<u8>,
    pub audio_stream_id: Option<u8>,
}

// Command response decoders

/// Decode SolicitOfferResponse command response (01)
pub fn decode_solicit_offer_response(inp: &tlv::TlvItemValue) -> anyhow::Result<SolicitOfferResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(SolicitOfferResponse {
                web_rtc_session_id: item.get_int(&[0]).map(|v| v as u8),
                deferred_offer: item.get_bool(&[1]),
                video_stream_id: item.get_int(&[2]).map(|v| v as u8),
                audio_stream_id: item.get_int(&[3]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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