matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Temperature Control Cluster
//! Cluster ID: 0x0056
//!
//! This file is automatically generated from TemperatureControl.xml

#![allow(clippy::too_many_arguments)]

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


// Command encoders

/// Encode SetTemperature command (0x00)
pub fn encode_set_temperature(target_temperature: i16, target_temperature_level: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Int16(target_temperature)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(target_temperature_level)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

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

/// Decode Step attribute (0x0003)
pub fn decode_step(inp: &tlv::TlvItemValue) -> anyhow::Result<i16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as i16)
    } else {
        Err(anyhow::anyhow!("Expected Int16"))
    }
}

/// Decode SelectedTemperatureLevel attribute (0x0004)
pub fn decode_selected_temperature_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 SupportedTemperatureLevels attribute (0x0005)
pub fn decode_supported_temperature_levels(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<String>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::String(s) = &item.value {
                res.push(s.clone());
            }
        }
    }
    Ok(res)
}


// 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 != 0x0056 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0056, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_temperature_setpoint(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_min_temperature(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_max_temperature(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_step(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_selected_temperature_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_supported_temperature_levels(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, "TemperatureSetpoint"),
        (0x0001, "MinTemperature"),
        (0x0002, "MaxTemperature"),
        (0x0003, "Step"),
        (0x0004, "SelectedTemperatureLevel"),
        (0x0005, "SupportedTemperatureLevels"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SetTemperature"),
        _ => 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: "target_temperature", kind: crate::clusters::codec::FieldKind::I16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "target_temperature_level", 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 target_temperature = crate::clusters::codec::json_util::get_i16(args, "target_temperature")?;
        let target_temperature_level = crate::clusters::codec::json_util::get_u8(args, "target_temperature_level")?;
        encode_set_temperature(target_temperature, target_temperature_level)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `SetTemperature` command on cluster `Temperature Control`.
pub async fn set_temperature(conn: &crate::controller::Connection, endpoint: u16, target_temperature: i16, target_temperature_level: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_CMD_ID_SETTEMPERATURE, &encode_set_temperature(target_temperature, target_temperature_level)?).await?;
    Ok(())
}

/// Read `TemperatureSetpoint` attribute from cluster `Temperature Control`.
pub async fn read_temperature_setpoint(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<i16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_ATTR_ID_TEMPERATURESETPOINT).await?;
    decode_temperature_setpoint(&tlv)
}

/// Read `MinTemperature` attribute from cluster `Temperature Control`.
pub async fn read_min_temperature(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<i16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_ATTR_ID_MINTEMPERATURE).await?;
    decode_min_temperature(&tlv)
}

/// Read `MaxTemperature` attribute from cluster `Temperature Control`.
pub async fn read_max_temperature(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<i16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_ATTR_ID_MAXTEMPERATURE).await?;
    decode_max_temperature(&tlv)
}

/// Read `Step` attribute from cluster `Temperature Control`.
pub async fn read_step(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<i16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_ATTR_ID_STEP).await?;
    decode_step(&tlv)
}

/// Read `SelectedTemperatureLevel` attribute from cluster `Temperature Control`.
pub async fn read_selected_temperature_level(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_ATTR_ID_SELECTEDTEMPERATURELEVEL).await?;
    decode_selected_temperature_level(&tlv)
}

/// Read `SupportedTemperatureLevels` attribute from cluster `Temperature Control`.
pub async fn read_supported_temperature_levels(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<String>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TEMPERATURE_CONTROL, crate::clusters::defs::CLUSTER_TEMPERATURE_CONTROL_ATTR_ID_SUPPORTEDTEMPERATURELEVELS).await?;
    decode_supported_temperature_levels(&tlv)
}