matc 0.1.2

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

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

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