matc 0.1.2

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

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ErrorStateEnum {
    /// The device is not in an error state
    Noerror = 0,
    /// The device is unable to start or resume operation
    Unabletostartorresume = 1,
    /// The device was unable to complete the current operation
    Unabletocompleteoperation = 2,
    /// The device cannot process the command in its current state
    Commandinvalidinstate = 3,
}

impl ErrorStateEnum {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ErrorStateEnum::Noerror),
            1 => Some(ErrorStateEnum::Unabletostartorresume),
            2 => Some(ErrorStateEnum::Unabletocompleteoperation),
            3 => Some(ErrorStateEnum::Commandinvalidinstate),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum OperationalStateEnum {
    /// The device is stopped
    Stopped = 0,
    /// The device is operating
    Running = 1,
    /// The device is paused during an operation
    Paused = 2,
    /// The device is in an error state
    Error = 3,
}

impl OperationalStateEnum {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(OperationalStateEnum::Stopped),
            1 => Some(OperationalStateEnum::Running),
            2 => Some(OperationalStateEnum::Paused),
            3 => Some(OperationalStateEnum::Error),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ErrorState {
    pub error_state_id: Option<ErrorStateEnum>,
    pub error_state_label: Option<String>,
    pub error_state_details: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct OperationalState {
    pub operational_state_id: Option<OperationalStateEnum>,
    pub operational_state_label: Option<String>,
}

// Command encoders

// Attribute decoders

/// Decode PhaseList attribute (0x0000)
pub fn decode_phase_list(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)
}

/// Decode CurrentPhase attribute (0x0001)
pub fn decode_current_phase(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode CountdownTime attribute (0x0002)
pub fn decode_countdown_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u32))
    } else {
        Ok(None)
    }
}

/// Decode OperationalStateList attribute (0x0003)
pub fn decode_operational_state_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<OperationalState>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(OperationalState {
                operational_state_id: item.get_int(&[0]).and_then(|v| OperationalStateEnum::from_u8(v as u8)),
                operational_state_label: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode OperationalState attribute (0x0004)
pub fn decode_operational_state(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalStateEnum> {
    if let tlv::TlvItemValue::Int(v) = inp {
        OperationalStateEnum::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode OperationalError attribute (0x0005)
pub fn decode_operational_error(inp: &tlv::TlvItemValue) -> anyhow::Result<ErrorState> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ErrorState {
                error_state_id: item.get_int(&[0]).and_then(|v| ErrorStateEnum::from_u8(v as u8)),
                error_state_label: item.get_string_owned(&[1]),
                error_state_details: item.get_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_phase_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_phase(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_countdown_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_operational_state_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_operational_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_operational_error(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, "PhaseList"),
        (0x0001, "CurrentPhase"),
        (0x0002, "CountdownTime"),
        (0x0003, "OperationalStateList"),
        (0x0004, "OperationalState"),
        (0x0005, "OperationalError"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct OperationalCommandResponse {
    pub command_response_state: Option<ErrorState>,
}

// Command response decoders

/// Decode OperationalCommandResponse command response (04)
pub fn decode_operational_command_response(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalCommandResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(OperationalCommandResponse {
                command_response_state: {
                    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(ErrorState {
                error_state_id: nested_item.get_int(&[0]).and_then(|v| ErrorStateEnum::from_u8(v as u8)),
                error_state_label: nested_item.get_string_owned(&[1]),
                error_state_details: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

#[derive(Debug, serde::Serialize)]
pub struct OperationalErrorEvent {
    pub error_state: Option<ErrorState>,
}

#[derive(Debug, serde::Serialize)]
pub struct OperationCompletionEvent {
    pub completion_error_code: Option<u8>,
    pub total_operational_time: Option<u32>,
    pub paused_time: Option<u32>,
}

// Event decoders

/// Decode OperationalError event (0x00, priority: critical)
pub fn decode_operational_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalErrorEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(OperationalErrorEvent {
                                error_state: {
                    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(ErrorState {
                error_state_id: nested_item.get_int(&[0]).and_then(|v| ErrorStateEnum::from_u8(v as u8)),
                error_state_label: nested_item.get_string_owned(&[1]),
                error_state_details: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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