matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Identify Cluster
//! Cluster ID: 0x0003
//!
//! This file is automatically generated from Identify.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 EffectIdentifier {
    /// e.g., Light is turned on/off once.
    Blink = 0,
    /// e.g., Light is turned on/off over 1 second and repeated 15 times.
    Breathe = 1,
    /// e.g., Colored light turns green for 1 second; non-colored light flashes twice.
    Okay = 2,
    /// e.g., Colored light turns orange for 8 seconds; non-colored light switches to the maximum brightness for 0.5s and then minimum brightness for 7.5s.
    Channelchange = 11,
    /// Complete the current effect sequence before terminating. e.g., if in the middle of a breathe effect (as above), first complete the current 1s breathe effect and then terminate the effect.
    Finisheffect = 254,
    /// Terminate the effect as soon as possible.
    Stopeffect = 255,
}

impl EffectIdentifier {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(EffectIdentifier::Blink),
            1 => Some(EffectIdentifier::Breathe),
            2 => Some(EffectIdentifier::Okay),
            11 => Some(EffectIdentifier::Channelchange),
            254 => Some(EffectIdentifier::Finisheffect),
            255 => Some(EffectIdentifier::Stopeffect),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum EffectVariant {
    /// Indicates the default effect is used
    Default = 0,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum IdentifyType {
    /// No presentation.
    None = 0,
    /// Light output of a lighting product.
    Lightoutput = 1,
    /// Typically a small LED.
    Visibleindicator = 2,
    Audiblebeep = 3,
    /// Presentation will be visible on display screen.
    Display = 4,
    /// Presentation will be conveyed by actuator functionality such as through a window blind operation or in-wall relay.
    Actuator = 5,
}

impl IdentifyType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(IdentifyType::None),
            1 => Some(IdentifyType::Lightoutput),
            2 => Some(IdentifyType::Visibleindicator),
            3 => Some(IdentifyType::Audiblebeep),
            4 => Some(IdentifyType::Display),
            5 => Some(IdentifyType::Actuator),
            _ => None,
        }
    }

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

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

// Command encoders

/// Encode Identify command (0x00)
pub fn encode_identify(identify_time: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(identify_time)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode TriggerEffect command (0x40)
pub fn encode_trigger_effect(effect_identifier: EffectIdentifier, effect_variant: EffectVariant) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(effect_identifier.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(effect_variant.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

/// Decode IdentifyType attribute (0x0001)
pub fn decode_identify_type(inp: &tlv::TlvItemValue) -> anyhow::Result<IdentifyType> {
    if let tlv::TlvItemValue::Int(v) = inp {
        IdentifyType::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 != 0x0003 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0003, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_identify_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_identify_type(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, "IdentifyTime"),
        (0x0001, "IdentifyType"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Identify"),
        0x40 => Some("TriggerEffect"),
        _ => 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: "identify_time", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
        ]),
        0x40 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "effect_identifier", kind: crate::clusters::codec::FieldKind::Enum { name: "EffectIdentifier", variants: &[(0, "Blink"), (1, "Breathe"), (2, "Okay"), (11, "Channelchange"), (254, "Finisheffect"), (255, "Stopeffect")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "effect_variant", kind: crate::clusters::codec::FieldKind::Enum { name: "EffectVariant", variants: &[(0, "Default")] }, 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 identify_time = crate::clusters::codec::json_util::get_u16(args, "identify_time")?;
        encode_identify(identify_time)
        }
        0x40 => {
        let effect_identifier = {
            let n = crate::clusters::codec::json_util::get_u64(args, "effect_identifier")?;
            EffectIdentifier::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid EffectIdentifier: {}", n))?
        };
        let effect_variant = {
            let n = crate::clusters::codec::json_util::get_u64(args, "effect_variant")?;
            EffectVariant::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid EffectVariant: {}", n))?
        };
        encode_trigger_effect(effect_identifier, effect_variant)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `Identify` command on cluster `Identify`.
pub async fn identify(conn: &crate::controller::Connection, endpoint: u16, identify_time: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_CMD_ID_IDENTIFY, &encode_identify(identify_time)?).await?;
    Ok(())
}

/// Invoke `TriggerEffect` command on cluster `Identify`.
pub async fn trigger_effect(conn: &crate::controller::Connection, endpoint: u16, effect_identifier: EffectIdentifier, effect_variant: EffectVariant) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_CMD_ID_TRIGGEREFFECT, &encode_trigger_effect(effect_identifier, effect_variant)?).await?;
    Ok(())
}

/// Read `IdentifyTime` attribute from cluster `Identify`.
pub async fn read_identify_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_ATTR_ID_IDENTIFYTIME).await?;
    decode_identify_time(&tlv)
}

/// Read `IdentifyType` attribute from cluster `Identify`.
pub async fn read_identify_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<IdentifyType> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_ATTR_ID_IDENTIFYTYPE).await?;
    decode_identify_type(&tlv)
}