matc 0.1.3

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

#![allow(clippy::too_many_arguments)]

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


// Command encoders

/// Encode SetCookingParameters command (0x00)
pub fn encode_set_cooking_parameters(cook_mode: Option<u8>, cook_time: Option<u32>, power_setting: Option<u8>, watt_setting_index: Option<u8>, start_after_setting: Option<bool>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    if let Some(x) = cook_mode { tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    if let Some(x) = cook_time { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    if let Some(x) = power_setting { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    if let Some(x) = watt_setting_index { tlv_fields.push((3, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    if let Some(x) = start_after_setting { tlv_fields.push((4, tlv::TlvItemValueEnc::Bool(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode AddMoreTime command (0x01)
pub fn encode_add_more_time(time_to_add: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(time_to_add)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

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

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

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

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

/// Decode SupportedWatts attribute (0x0006)
pub fn decode_supported_watts(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u16>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                res.push(*i as u16);
            }
        }
    }
    Ok(res)
}

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

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


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

    match attribute_id {
        0x0000 => {
            match decode_cook_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_max_cook_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_power_setting(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_min_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_max_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_power_step(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_supported_watts(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_selected_watt_index(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_watt_rating(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, "CookTime"),
        (0x0001, "MaxCookTime"),
        (0x0002, "PowerSetting"),
        (0x0003, "MinPower"),
        (0x0004, "MaxPower"),
        (0x0005, "PowerStep"),
        (0x0006, "SupportedWatts"),
        (0x0007, "SelectedWattIndex"),
        (0x0008, "WattRating"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SetCookingParameters"),
        0x01 => Some("AddMoreTime"),
        _ => 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: "cook_mode", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "cook_time", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "power_setting", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "watt_setting_index", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 4, name: "start_after_setting", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "time_to_add", kind: crate::clusters::codec::FieldKind::U32, 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 cook_mode = crate::clusters::codec::json_util::get_opt_u8(args, "cook_mode")?;
        let cook_time = crate::clusters::codec::json_util::get_opt_u32(args, "cook_time")?;
        let power_setting = crate::clusters::codec::json_util::get_opt_u8(args, "power_setting")?;
        let watt_setting_index = crate::clusters::codec::json_util::get_opt_u8(args, "watt_setting_index")?;
        let start_after_setting = crate::clusters::codec::json_util::get_opt_bool(args, "start_after_setting")?;
        encode_set_cooking_parameters(cook_mode, cook_time, power_setting, watt_setting_index, start_after_setting)
        }
        0x01 => {
        let time_to_add = crate::clusters::codec::json_util::get_u32(args, "time_to_add")?;
        encode_add_more_time(time_to_add)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `SetCookingParameters` command on cluster `Microwave Oven Control`.
pub async fn set_cooking_parameters(conn: &crate::controller::Connection, endpoint: u16, cook_mode: Option<u8>, cook_time: Option<u32>, power_setting: Option<u8>, watt_setting_index: Option<u8>, start_after_setting: Option<bool>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_CMD_ID_SETCOOKINGPARAMETERS, &encode_set_cooking_parameters(cook_mode, cook_time, power_setting, watt_setting_index, start_after_setting)?).await?;
    Ok(())
}

/// Invoke `AddMoreTime` command on cluster `Microwave Oven Control`.
pub async fn add_more_time(conn: &crate::controller::Connection, endpoint: u16, time_to_add: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_CMD_ID_ADDMORETIME, &encode_add_more_time(time_to_add)?).await?;
    Ok(())
}

/// Read `CookTime` attribute from cluster `Microwave Oven Control`.
pub async fn read_cook_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_COOKTIME).await?;
    decode_cook_time(&tlv)
}

/// Read `MaxCookTime` attribute from cluster `Microwave Oven Control`.
pub async fn read_max_cook_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_MAXCOOKTIME).await?;
    decode_max_cook_time(&tlv)
}

/// Read `PowerSetting` attribute from cluster `Microwave Oven Control`.
pub async fn read_power_setting(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_POWERSETTING).await?;
    decode_power_setting(&tlv)
}

/// Read `MinPower` attribute from cluster `Microwave Oven Control`.
pub async fn read_min_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_MINPOWER).await?;
    decode_min_power(&tlv)
}

/// Read `MaxPower` attribute from cluster `Microwave Oven Control`.
pub async fn read_max_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_MAXPOWER).await?;
    decode_max_power(&tlv)
}

/// Read `PowerStep` attribute from cluster `Microwave Oven Control`.
pub async fn read_power_step(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_POWERSTEP).await?;
    decode_power_step(&tlv)
}

/// Read `SupportedWatts` attribute from cluster `Microwave Oven Control`.
pub async fn read_supported_watts(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_SUPPORTEDWATTS).await?;
    decode_supported_watts(&tlv)
}

/// Read `SelectedWattIndex` attribute from cluster `Microwave Oven Control`.
pub async fn read_selected_watt_index(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_SELECTEDWATTINDEX).await?;
    decode_selected_watt_index(&tlv)
}

/// Read `WattRating` attribute from cluster `Microwave Oven Control`.
pub async fn read_watt_rating(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MICROWAVE_OVEN_CONTROL, crate::clusters::defs::CLUSTER_MICROWAVE_OVEN_CONTROL_ATTR_ID_WATTRATING).await?;
    decode_watt_rating(&tlv)
}