matc 0.1.3

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

#![allow(clippy::too_many_arguments)]

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 mode_tags: Option<Vec<ModeTag>>,
}

#[derive(Debug, serde::Serialize)]
pub struct ModeTag {
    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 SupportedModes attribute (0x0000)
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),
                mode_tags: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(ModeTag {
                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 (0x0001)
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 (0x0002)
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 (0x0003)
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 != 0x0000 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0000, got {}\"}}", cluster_id);
    }

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

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ChangeToMode"),
        _ => 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: "new_mode", kind: crate::clusters::codec::FieldKind::U8, 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 new_mode = crate::clusters::codec::json_util::get_u8(args, "new_mode")?;
        encode_change_to_mode(new_mode)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct ChangeToModeResponse {
    pub status: Option<u8>,
    pub status_text: Option<String>,
}

// Command response decoders

/// Decode ChangeToModeResponse command response (01)
pub fn decode_change_to_mode_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ChangeToModeResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ChangeToModeResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                status_text: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}