matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Water Heater Management Cluster
//! Cluster ID: 0x0094
//!
//! This file is automatically generated from WaterHeaterManagement.xml

#![allow(clippy::too_many_arguments)]

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum BoostState {
    /// Boost is not currently active
    Inactive = 0,
    /// Boost is currently active
    Active = 1,
}

impl BoostState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(BoostState::Inactive),
            1 => Some(BoostState::Active),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<BoostState> for u8 {
    fn from(val: BoostState) -> Self {
        val as u8
    }
}

// Bitmap definitions

/// WaterHeaterHeatSource bitmap type
pub type WaterHeaterHeatSource = u8;

/// Constants for WaterHeaterHeatSource
pub mod waterheaterheatsource {
    /// Immersion Heating Element 1
    pub const IMMERSION_ELEMENT1: u8 = 0x01;
    /// Immersion Heating Element 2
    pub const IMMERSION_ELEMENT2: u8 = 0x02;
    /// Heat pump Heating
    pub const HEAT_PUMP: u8 = 0x04;
    /// Boiler Heating (e.g. Gas or Oil)
    pub const BOILER: u8 = 0x08;
    /// Other Heating
    pub const OTHER: u8 = 0x10;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct WaterHeaterBoostInfo {
    pub duration: Option<u32>,
    pub one_shot: Option<bool>,
    pub emergency_boost: Option<bool>,
    pub temporary_setpoint: Option<i16>,
    pub target_percentage: Option<u8>,
    pub target_reheat: Option<u8>,
}

// Command encoders

/// Encode Boost command (0x00)
pub fn encode_boost(boost_info: WaterHeaterBoostInfo) -> anyhow::Result<Vec<u8>> {
            // Encode struct WaterHeaterBoostInfoStruct
            let mut boost_info_fields = Vec::new();
            if let Some(x) = boost_info.duration { boost_info_fields.push((0, tlv::TlvItemValueEnc::UInt32(x)).into()); }
            if let Some(x) = boost_info.one_shot { boost_info_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
            if let Some(x) = boost_info.emergency_boost { boost_info_fields.push((2, tlv::TlvItemValueEnc::Bool(x)).into()); }
            if let Some(x) = boost_info.temporary_setpoint { boost_info_fields.push((3, tlv::TlvItemValueEnc::Int16(x)).into()); }
            if let Some(x) = boost_info.target_percentage { boost_info_fields.push((4, tlv::TlvItemValueEnc::UInt8(x)).into()); }
            if let Some(x) = boost_info.target_reheat { boost_info_fields.push((5, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructInvisible(boost_info_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

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

/// Decode EstimatedHeatRequired attribute (0x0003)
pub fn decode_estimated_heat_required(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

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

/// Decode BoostState attribute (0x0005)
pub fn decode_boost_state(inp: &tlv::TlvItemValue) -> anyhow::Result<BoostState> {
    if let tlv::TlvItemValue::Int(v) = inp {
        BoostState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } 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 != 0x0094 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0094, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_heater_types(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_heat_demand(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_tank_volume(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_estimated_heat_required(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_tank_percentage(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_boost_state(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, "HeaterTypes"),
        (0x0001, "HeatDemand"),
        (0x0002, "TankVolume"),
        (0x0003, "EstimatedHeatRequired"),
        (0x0004, "TankPercentage"),
        (0x0005, "BoostState"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Boost"),
        0x01 => Some("CancelBoost"),
        _ => 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: "boost_info", kind: crate::clusters::codec::FieldKind::Struct { name: "WaterHeaterBoostInfoStruct" }, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, _args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => Err(anyhow::anyhow!("command \"Boost\" has complex args: use raw mode")),
        0x01 => Ok(vec![]),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `Boost` command on cluster `Water Heater Management`.
pub async fn boost(conn: &crate::controller::Connection, endpoint: u16, boost_info: WaterHeaterBoostInfo) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_CMD_ID_BOOST, &encode_boost(boost_info)?).await?;
    Ok(())
}

/// Invoke `CancelBoost` command on cluster `Water Heater Management`.
pub async fn cancel_boost(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_CMD_ID_CANCELBOOST, &[]).await?;
    Ok(())
}

/// Read `HeaterTypes` attribute from cluster `Water Heater Management`.
pub async fn read_heater_types(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<WaterHeaterHeatSource> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_HEATERTYPES).await?;
    decode_heater_types(&tlv)
}

/// Read `HeatDemand` attribute from cluster `Water Heater Management`.
pub async fn read_heat_demand(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<WaterHeaterHeatSource> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_HEATDEMAND).await?;
    decode_heat_demand(&tlv)
}

/// Read `TankVolume` attribute from cluster `Water Heater Management`.
pub async fn read_tank_volume(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_TANKVOLUME).await?;
    decode_tank_volume(&tlv)
}

/// Read `EstimatedHeatRequired` attribute from cluster `Water Heater Management`.
pub async fn read_estimated_heat_required(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_ESTIMATEDHEATREQUIRED).await?;
    decode_estimated_heat_required(&tlv)
}

/// Read `TankPercentage` attribute from cluster `Water Heater Management`.
pub async fn read_tank_percentage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_TANKPERCENTAGE).await?;
    decode_tank_percentage(&tlv)
}

/// Read `BoostState` attribute from cluster `Water Heater Management`.
pub async fn read_boost_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<BoostState> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WATER_HEATER_MANAGEMENT, crate::clusters::defs::CLUSTER_WATER_HEATER_MANAGEMENT_ATTR_ID_BOOSTSTATE).await?;
    decode_boost_state(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct BoostStartedEvent {
    pub boost_info: Option<WaterHeaterBoostInfo>,
}

// Event decoders

/// Decode BoostStarted event (0x00, priority: info)
pub fn decode_boost_started_event(inp: &tlv::TlvItemValue) -> anyhow::Result<BoostStartedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(BoostStartedEvent {
                                boost_info: {
                    if let Some(nested_tlv) = item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(WaterHeaterBoostInfo {
                duration: nested_item.get_int(&[0]).map(|v| v as u32),
                one_shot: nested_item.get_bool(&[1]),
                emergency_boost: nested_item.get_bool(&[2]),
                temporary_setpoint: nested_item.get_int(&[3]).map(|v| v as i16),
                target_percentage: nested_item.get_int(&[4]).map(|v| v as u8),
                target_reheat: nested_item.get_int(&[5]).map(|v| v as u8),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}