matc 0.1.3

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

#![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 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"),
    ]
}

// 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)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `ChangeToMode` command on cluster `Mode Select`.
pub async fn change_to_mode(conn: &crate::controller::Connection, endpoint: u16, new_mode: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_CMD_ID_CHANGETOMODE, &encode_change_to_mode(new_mode)?).await?;
    Ok(())
}

/// Read `Description` attribute from cluster `Mode Select`.
pub async fn read_description(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<String> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_DESCRIPTION).await?;
    decode_description(&tlv)
}

/// Read `StandardNamespace` attribute from cluster `Mode Select`.
pub async fn read_standard_namespace(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_STANDARDNAMESPACE).await?;
    decode_standard_namespace(&tlv)
}

/// Read `SupportedModes` attribute from cluster `Mode Select`.
pub async fn read_supported_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ModeOption>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_SUPPORTEDMODES).await?;
    decode_supported_modes(&tlv)
}

/// Read `CurrentMode` attribute from cluster `Mode Select`.
pub async fn read_current_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_CURRENTMODE).await?;
    decode_current_mode(&tlv)
}

/// Read `StartUpMode` attribute from cluster `Mode Select`.
pub async fn read_start_up_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_STARTUPMODE).await?;
    decode_start_up_mode(&tlv)
}

/// Read `OnMode` attribute from cluster `Mode Select`.
pub async fn read_on_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_ONMODE).await?;
    decode_on_mode(&tlv)
}