matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Mode Select Cluster
//! Cluster ID: 0x0050
//!
//! This file is automatically generated from ModeSelect.xml

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


// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ModeOption {
    pub label: Option<String>,
    pub mode: Option<u8>,
    pub semantic_tags: Option<Vec<SemanticTag>>,
}

#[derive(Debug, serde::Serialize)]
pub struct SemanticTag {
    pub mfg_code: Option<u16>,
    pub value: Option<u16>,
}

// Command encoders

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

// Attribute decoders

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

/// Decode StandardNamespace attribute (0x0001)
pub fn decode_standard_namespace(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u16>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u16))
    } else {
        Ok(None)
    }
}

/// Decode SupportedModes attribute (0x0002)
pub fn decode_supported_modes(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ModeOption>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ModeOption {
                label: item.get_string_owned(&[0]),
                mode: item.get_int(&[1]).map(|v| v as u8),
                semantic_tags: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(SemanticTag {
                mfg_code: list_item.get_int(&[0]).map(|v| v as u16),
                value: list_item.get_int(&[1]).map(|v| v as u16),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

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

/// Decode StartUpMode attribute (0x0004)
pub fn decode_start_up_mode(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode OnMode attribute (0x0005)
pub fn decode_on_mode(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 != 0x0050 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0050, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_description(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_standard_namespace(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_supported_modes(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_current_mode(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_start_up_mode(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_on_mode(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, "Description"),
        (0x0001, "StandardNamespace"),
        (0x0002, "SupportedModes"),
        (0x0003, "CurrentMode"),
        (0x0004, "StartUpMode"),
        (0x0005, "OnMode"),
    ]
}