matc 0.1.3

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

#![allow(clippy::too_many_arguments)]

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


// Bitmap definitions

/// Alarm bitmap type
pub type Alarm = u8;

// Command encoders

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

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

// Attribute decoders

/// Decode Mask attribute (0x0000)
pub fn decode_mask(inp: &tlv::TlvItemValue) -> anyhow::Result<Alarm> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode Latch attribute (0x0001)
pub fn decode_latch(inp: &tlv::TlvItemValue) -> anyhow::Result<Alarm> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode State attribute (0x0002)
pub fn decode_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Alarm> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

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


// 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_mask(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_latch(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_supported(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, "Mask"),
        (0x0001, "Latch"),
        (0x0002, "State"),
        (0x0003, "Supported"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Reset"),
        0x01 => Some("ModifyEnabledAlarms"),
        _ => 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: "alarms", kind: crate::clusters::codec::FieldKind::Bitmap { name: "Alarm", bits: &[] }, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "mask", kind: crate::clusters::codec::FieldKind::Bitmap { name: "Alarm", bits: &[] }, 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 alarms = crate::clusters::codec::json_util::get_u8(args, "alarms")?;
        encode_reset(alarms)
        }
        0x01 => {
        let mask = crate::clusters::codec::json_util::get_u8(args, "mask")?;
        encode_modify_enabled_alarms(mask)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct NotifyEvent {
    pub active: Option<Alarm>,
    pub inactive: Option<Alarm>,
    pub state: Option<Alarm>,
    pub mask: Option<Alarm>,
}

// Event decoders

/// Decode Notify event (0x00, priority: info)
pub fn decode_notify_event(inp: &tlv::TlvItemValue) -> anyhow::Result<NotifyEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(NotifyEvent {
                                active: item.get_int(&[0]).map(|v| v as u8),
                                inactive: item.get_int(&[1]).map(|v| v as u8),
                                state: item.get_int(&[2]).map(|v| v as u8),
                                mask: item.get_int(&[3]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}