matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Application Launcher Cluster
//! Cluster ID: 0x050C
//!
//! This file is automatically generated from ApplicationLauncher.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 Status {
    /// Command succeeded
    Success = 0,
    /// Requested app is not available
    Appnotavailable = 1,
    /// Video platform unable to honor command
    Systembusy = 2,
    /// User approval for app download is pending
    Pendinguserapproval = 3,
    /// Downloading the requested app
    Downloading = 4,
    /// Installing the requested app
    Installing = 5,
}

impl Status {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Status::Success),
            1 => Some(Status::Appnotavailable),
            2 => Some(Status::Systembusy),
            3 => Some(Status::Pendinguserapproval),
            4 => Some(Status::Downloading),
            5 => Some(Status::Installing),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ApplicationEP {
    pub application: Option<Application>,
    pub endpoint: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct Application {
    pub catalog_vendor_id: Option<u16>,
    pub application_id: Option<String>,
}

// Command encoders

/// Encode LaunchApp command (0x00)
pub fn encode_launch_app(application: Application, data: Option<Vec<u8>>) -> anyhow::Result<Vec<u8>> {
            // Encode struct ApplicationStruct
            let mut application_fields = Vec::new();
            if let Some(x) = application.catalog_vendor_id { application_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
            if let Some(x) = application.application_id { application_fields.push((1, tlv::TlvItemValueEnc::String(x.clone())).into()); }
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::StructInvisible(application_fields)).into());
    if let Some(x) = data { tlv_fields.push((1, tlv::TlvItemValueEnc::OctetString(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode StopApp command (0x01)
pub fn encode_stop_app(application: Application) -> anyhow::Result<Vec<u8>> {
            // Encode struct ApplicationStruct
            let mut application_fields = Vec::new();
            if let Some(x) = application.catalog_vendor_id { application_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
            if let Some(x) = application.application_id { application_fields.push((1, tlv::TlvItemValueEnc::String(x.clone())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructInvisible(application_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode HideApp command (0x02)
pub fn encode_hide_app(application: Application) -> anyhow::Result<Vec<u8>> {
            // Encode struct ApplicationStruct
            let mut application_fields = Vec::new();
            if let Some(x) = application.catalog_vendor_id { application_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
            if let Some(x) = application.application_id { application_fields.push((1, tlv::TlvItemValueEnc::String(x.clone())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructInvisible(application_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode CatalogList attribute (0x0000)
pub fn decode_catalog_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u16>> {
    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 u16);
            }
        }
    }
    Ok(res)
}

/// Decode CurrentApp attribute (0x0001)
pub fn decode_current_app(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<ApplicationEP>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(ApplicationEP {
                application: {
                    if let Some(nested_tlv) = item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(Application {
                catalog_vendor_id: nested_item.get_int(&[0]).map(|v| v as u16),
                application_id: nested_item.get_string_owned(&[1]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                endpoint: item.get_int(&[1]).map(|v| v as u16),
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_catalog_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_app(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, "CatalogList"),
        (0x0001, "CurrentApp"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("LaunchApp"),
        0x01 => Some("StopApp"),
        0x02 => Some("HideApp"),
        _ => 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: "application", kind: crate::clusters::codec::FieldKind::Struct { name: "ApplicationStruct" }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "data", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "application", kind: crate::clusters::codec::FieldKind::Struct { name: "ApplicationStruct" }, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "application", kind: crate::clusters::codec::FieldKind::Struct { name: "ApplicationStruct" }, 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 => Err(anyhow::anyhow!("command \"LaunchApp\" has complex args: use raw mode")),
        0x01 => Err(anyhow::anyhow!("command \"StopApp\" has complex args: use raw mode")),
        0x02 => Err(anyhow::anyhow!("command \"HideApp\" has complex args: use raw mode")),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

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

// Command response decoders

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

// Typed facade (invokes + reads)

/// Invoke `LaunchApp` command on cluster `Application Launcher`.
pub async fn launch_app(conn: &crate::controller::Connection, endpoint: u16, application: Application, data: Option<Vec<u8>>) -> anyhow::Result<LauncherResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_APPLICATION_LAUNCHER, crate::clusters::defs::CLUSTER_APPLICATION_LAUNCHER_CMD_ID_LAUNCHAPP, &encode_launch_app(application, data)?).await?;
    decode_launcher_response(&tlv)
}

/// Invoke `StopApp` command on cluster `Application Launcher`.
pub async fn stop_app(conn: &crate::controller::Connection, endpoint: u16, application: Application) -> anyhow::Result<LauncherResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_APPLICATION_LAUNCHER, crate::clusters::defs::CLUSTER_APPLICATION_LAUNCHER_CMD_ID_STOPAPP, &encode_stop_app(application)?).await?;
    decode_launcher_response(&tlv)
}

/// Invoke `HideApp` command on cluster `Application Launcher`.
pub async fn hide_app(conn: &crate::controller::Connection, endpoint: u16, application: Application) -> anyhow::Result<LauncherResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_APPLICATION_LAUNCHER, crate::clusters::defs::CLUSTER_APPLICATION_LAUNCHER_CMD_ID_HIDEAPP, &encode_hide_app(application)?).await?;
    decode_launcher_response(&tlv)
}

/// Read `CatalogList` attribute from cluster `Application Launcher`.
pub async fn read_catalog_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_APPLICATION_LAUNCHER, crate::clusters::defs::CLUSTER_APPLICATION_LAUNCHER_ATTR_ID_CATALOGLIST).await?;
    decode_catalog_list(&tlv)
}

/// Read `CurrentApp` attribute from cluster `Application Launcher`.
pub async fn read_current_app(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<ApplicationEP>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_APPLICATION_LAUNCHER, crate::clusters::defs::CLUSTER_APPLICATION_LAUNCHER_ATTR_ID_CURRENTAPP).await?;
    decode_current_app(&tlv)
}