matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Application Basic Cluster
//! Cluster ID: 0x050D
//!
//! This file is automatically generated from ApplicationBasic.xml

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ApplicationStatus {
    /// Application is not running.
    Stopped = 0,
    /// Application is running, is visible to the user, and is the active target for input.
    Activevisiblefocus = 1,
    /// Application is running but not visible to the user.
    Activehidden = 2,
    /// Application is running and visible, but is not the active target for input.
    Activevisiblenotfocus = 3,
}

impl ApplicationStatus {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ApplicationStatus::Stopped),
            1 => Some(ApplicationStatus::Activevisiblefocus),
            2 => Some(ApplicationStatus::Activehidden),
            3 => Some(ApplicationStatus::Activevisiblenotfocus),
            _ => None,
        }
    }

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

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

// Struct definitions

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

// Attribute decoders

/// Decode VendorName attribute (0x0000)
pub fn decode_vendor_name(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected String"))
    }
}

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

/// Decode ApplicationName attribute (0x0002)
pub fn decode_application_name(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected String"))
    }
}

/// Decode ProductID attribute (0x0003)
pub fn decode_product_id(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode Application attribute (0x0004)
pub fn decode_application(inp: &tlv::TlvItemValue) -> anyhow::Result<Application> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Application {
                catalog_vendor_id: item.get_int(&[0]).map(|v| v as u16),
                application_id: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode Status attribute (0x0005)
pub fn decode_status(inp: &tlv::TlvItemValue) -> anyhow::Result<ApplicationStatus> {
    if let tlv::TlvItemValue::Int(v) = inp {
        ApplicationStatus::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode ApplicationVersion attribute (0x0006)
pub fn decode_application_version(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected String"))
    }
}

/// Decode AllowedVendorList attribute (0x0007)
pub fn decode_allowed_vendor_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)
}


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

    match attribute_id {
        0x0000 => {
            match decode_vendor_name(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_vendor_id(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_application_name(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_product_id(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_application(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_status(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_application_version(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_allowed_vendor_list(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, "VendorName"),
        (0x0001, "VendorID"),
        (0x0002, "ApplicationName"),
        (0x0003, "ProductID"),
        (0x0004, "Application"),
        (0x0005, "Status"),
        (0x0006, "ApplicationVersion"),
        (0x0007, "AllowedVendorList"),
    ]
}