matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Boolean State Configuration Cluster
//! Cluster ID: 0x0080
//!
//! This file is automatically generated from BooleanStateConfiguration.xml

#![allow(clippy::too_many_arguments)]

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


// Bitmap definitions

/// AlarmMode bitmap type
pub type AlarmMode = u8;

/// Constants for AlarmMode
pub mod alarmmode {
    /// Visual alarming
    pub const VISUAL: u8 = 0x01;
    /// Audible alarming
    pub const AUDIBLE: u8 = 0x02;
}

/// SensorFault bitmap type
pub type SensorFault = u8;

/// Constants for SensorFault
pub mod sensorfault {
    /// Unspecified fault detected
    pub const GENERAL_FAULT: u8 = 0x01;
}

// Command encoders

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

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

// Attribute decoders

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

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

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

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

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

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

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

/// Decode SensorFault attribute (0x0007)
pub fn decode_sensor_fault(inp: &tlv::TlvItemValue) -> anyhow::Result<SensorFault> {
    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 != 0x0080 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0080, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_current_sensitivity_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_supported_sensitivity_levels(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_default_sensitivity_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_alarms_active(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_alarms_suppressed(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_alarms_enabled(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_alarms_supported(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_sensor_fault(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, "CurrentSensitivityLevel"),
        (0x0001, "SupportedSensitivityLevels"),
        (0x0002, "DefaultSensitivityLevel"),
        (0x0003, "AlarmsActive"),
        (0x0004, "AlarmsSuppressed"),
        (0x0005, "AlarmsEnabled"),
        (0x0006, "AlarmsSupported"),
        (0x0007, "SensorFault"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SuppressAlarm"),
        0x01 => Some("EnableDisableAlarm"),
        _ => 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_to_suppress", kind: crate::clusters::codec::FieldKind::Bitmap { name: "AlarmMode", bits: &[(1, "VISUAL"), (2, "AUDIBLE")] }, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "alarms_to_enable_disable", kind: crate::clusters::codec::FieldKind::Bitmap { name: "AlarmMode", bits: &[(1, "VISUAL"), (2, "AUDIBLE")] }, 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_to_suppress = crate::clusters::codec::json_util::get_u8(args, "alarms_to_suppress")?;
        encode_suppress_alarm(alarms_to_suppress)
        }
        0x01 => {
        let alarms_to_enable_disable = crate::clusters::codec::json_util::get_u8(args, "alarms_to_enable_disable")?;
        encode_enable_disable_alarm(alarms_to_enable_disable)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `SuppressAlarm` command on cluster `Boolean State Configuration`.
pub async fn suppress_alarm(conn: &crate::controller::Connection, endpoint: u16, alarms_to_suppress: AlarmMode) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_CMD_ID_SUPPRESSALARM, &encode_suppress_alarm(alarms_to_suppress)?).await?;
    Ok(())
}

/// Invoke `EnableDisableAlarm` command on cluster `Boolean State Configuration`.
pub async fn enable_disable_alarm(conn: &crate::controller::Connection, endpoint: u16, alarms_to_enable_disable: AlarmMode) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_CMD_ID_ENABLEDISABLEALARM, &encode_enable_disable_alarm(alarms_to_enable_disable)?).await?;
    Ok(())
}

/// Read `CurrentSensitivityLevel` attribute from cluster `Boolean State Configuration`.
pub async fn read_current_sensitivity_level(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_CURRENTSENSITIVITYLEVEL).await?;
    decode_current_sensitivity_level(&tlv)
}

/// Read `SupportedSensitivityLevels` attribute from cluster `Boolean State Configuration`.
pub async fn read_supported_sensitivity_levels(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_SUPPORTEDSENSITIVITYLEVELS).await?;
    decode_supported_sensitivity_levels(&tlv)
}

/// Read `DefaultSensitivityLevel` attribute from cluster `Boolean State Configuration`.
pub async fn read_default_sensitivity_level(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_DEFAULTSENSITIVITYLEVEL).await?;
    decode_default_sensitivity_level(&tlv)
}

/// Read `AlarmsActive` attribute from cluster `Boolean State Configuration`.
pub async fn read_alarms_active(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<AlarmMode> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_ALARMSACTIVE).await?;
    decode_alarms_active(&tlv)
}

/// Read `AlarmsSuppressed` attribute from cluster `Boolean State Configuration`.
pub async fn read_alarms_suppressed(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<AlarmMode> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_ALARMSSUPPRESSED).await?;
    decode_alarms_suppressed(&tlv)
}

/// Read `AlarmsEnabled` attribute from cluster `Boolean State Configuration`.
pub async fn read_alarms_enabled(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<AlarmMode> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_ALARMSENABLED).await?;
    decode_alarms_enabled(&tlv)
}

/// Read `AlarmsSupported` attribute from cluster `Boolean State Configuration`.
pub async fn read_alarms_supported(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<AlarmMode> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_ALARMSSUPPORTED).await?;
    decode_alarms_supported(&tlv)
}

/// Read `SensorFault` attribute from cluster `Boolean State Configuration`.
pub async fn read_sensor_fault(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<SensorFault> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_BOOLEAN_STATE_CONFIGURATION, crate::clusters::defs::CLUSTER_BOOLEAN_STATE_CONFIGURATION_ATTR_ID_SENSORFAULT).await?;
    decode_sensor_fault(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct AlarmsStateChangedEvent {
    pub alarms_active: Option<AlarmMode>,
    pub alarms_suppressed: Option<AlarmMode>,
}

#[derive(Debug, serde::Serialize)]
pub struct SensorFaultEvent {
    pub sensor_fault: Option<SensorFault>,
}

// Event decoders

/// Decode AlarmsStateChanged event (0x00, priority: info)
pub fn decode_alarms_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<AlarmsStateChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(AlarmsStateChangedEvent {
                                alarms_active: item.get_int(&[0]).map(|v| v as u8),
                                alarms_suppressed: item.get_int(&[1]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode SensorFault event (0x01, priority: info)
pub fn decode_sensor_fault_event(inp: &tlv::TlvItemValue) -> anyhow::Result<SensorFaultEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(SensorFaultEvent {
                                sensor_fault: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}