matc 0.1.3

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

#![allow(clippy::too_many_arguments)]

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


// Attribute decoders

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

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

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


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

    match attribute_id {
        0x0000 => {
            match decode_number_of_positions(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_position(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_multi_press_max(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, "NumberOfPositions"),
        (0x0001, "CurrentPosition"),
        (0x0002, "MultiPressMax"),
    ]
}

// Typed facade (invokes + reads)

/// Read `NumberOfPositions` attribute from cluster `Switch`.
pub async fn read_number_of_positions(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SWITCH, crate::clusters::defs::CLUSTER_SWITCH_ATTR_ID_NUMBEROFPOSITIONS).await?;
    decode_number_of_positions(&tlv)
}

/// Read `CurrentPosition` attribute from cluster `Switch`.
pub async fn read_current_position(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SWITCH, crate::clusters::defs::CLUSTER_SWITCH_ATTR_ID_CURRENTPOSITION).await?;
    decode_current_position(&tlv)
}

/// Read `MultiPressMax` attribute from cluster `Switch`.
pub async fn read_multi_press_max(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SWITCH, crate::clusters::defs::CLUSTER_SWITCH_ATTR_ID_MULTIPRESSMAX).await?;
    decode_multi_press_max(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct SwitchLatchedEvent {
    pub new_position: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct InitialPressEvent {
    pub new_position: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct LongPressEvent {
    pub new_position: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct ShortReleaseEvent {
    pub previous_position: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct LongReleaseEvent {
    pub previous_position: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct MultiPressOngoingEvent {
    pub new_position: Option<u8>,
    pub current_number_of_presses_counted: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct MultiPressCompleteEvent {
    pub previous_position: Option<u8>,
    pub total_number_of_presses_counted: Option<u8>,
}

// Event decoders

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

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

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

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

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

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

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