matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Audio Output Cluster
//! Cluster ID: 0x050B
//!
//! This file is automatically generated from AudioOutput.xml

#![allow(clippy::too_many_arguments)]

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum OutputType {
    /// HDMI
    Hdmi = 0,
    Bt = 1,
    Optical = 2,
    Headphone = 3,
    Internal = 4,
    Other = 5,
}

impl OutputType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(OutputType::Hdmi),
            1 => Some(OutputType::Bt),
            2 => Some(OutputType::Optical),
            3 => Some(OutputType::Headphone),
            4 => Some(OutputType::Internal),
            5 => Some(OutputType::Other),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct OutputInfo {
    pub index: Option<u8>,
    pub output_type: Option<OutputType>,
    pub name: Option<String>,
}

// Command encoders

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

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

// Attribute decoders

/// Decode OutputList attribute (0x0000)
pub fn decode_output_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<OutputInfo>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(OutputInfo {
                index: item.get_int(&[0]).map(|v| v as u8),
                output_type: item.get_int(&[1]).and_then(|v| OutputType::from_u8(v as u8)),
                name: item.get_string_owned(&[2]),
            });
        }
    }
    Ok(res)
}

/// Decode CurrentOutput attribute (0x0001)
pub fn decode_current_output(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_output_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_output(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, "OutputList"),
        (0x0001, "CurrentOutput"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SelectOutput"),
        0x01 => Some("RenameOutput"),
        _ => 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: "index", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "index", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "name", kind: crate::clusters::codec::FieldKind::String, 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 index = crate::clusters::codec::json_util::get_u8(args, "index")?;
        encode_select_output(index)
        }
        0x01 => {
        let index = crate::clusters::codec::json_util::get_u8(args, "index")?;
        let name = crate::clusters::codec::json_util::get_string(args, "name")?;
        encode_rename_output(index, name)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `SelectOutput` command on cluster `Audio Output`.
pub async fn select_output(conn: &crate::controller::Connection, endpoint: u16, index: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_CMD_ID_SELECTOUTPUT, &encode_select_output(index)?).await?;
    Ok(())
}

/// Invoke `RenameOutput` command on cluster `Audio Output`.
pub async fn rename_output(conn: &crate::controller::Connection, endpoint: u16, index: u8, name: String) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_CMD_ID_RENAMEOUTPUT, &encode_rename_output(index, name)?).await?;
    Ok(())
}

/// Read `OutputList` attribute from cluster `Audio Output`.
pub async fn read_output_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<OutputInfo>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_ATTR_ID_OUTPUTLIST).await?;
    decode_output_list(&tlv)
}

/// Read `CurrentOutput` attribute from cluster `Audio Output`.
pub async fn read_current_output(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_ATTR_ID_CURRENTOUTPUT).await?;
    decode_current_output(&tlv)
}