matc 0.1.2

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

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


// Bitmap definitions

/// NameSupport bitmap type
pub type NameSupport = u8;

/// Constants for NameSupport
pub mod namesupport {
    /// The ability to store a name for a group.
    pub const GROUP_NAMES: u8 = 0x80;
}

// Command encoders

/// Encode AddGroup command (0x00)
pub fn encode_add_group(group_id: u8, group_name: String) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::String(group_name)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

/// Encode GetGroupMembership command (0x02)
pub fn encode_get_group_membership(group_list: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructAnon(group_list.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveGroup command (0x03)
pub fn encode_remove_group(group_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode AddGroupIfIdentifying command (0x05)
pub fn encode_add_group_if_identifying(group_id: u8, group_name: String) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::String(group_name)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode NameSupport attribute (0x0000)
pub fn decode_name_support(inp: &tlv::TlvItemValue) -> anyhow::Result<NameSupport> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } 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 != 0x0004 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0004, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_name_support(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, "NameSupport"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct AddGroupResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct ViewGroupResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
    pub group_name: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct GetGroupMembershipResponse {
    pub capacity: Option<u8>,
    pub group_list: Option<Vec<u8>>,
}

#[derive(Debug, serde::Serialize)]
pub struct RemoveGroupResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
}

// Command response decoders

/// Decode AddGroupResponse command response (00)
pub fn decode_add_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<AddGroupResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(AddGroupResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_id: item.get_int(&[1]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ViewGroupResponse command response (01)
pub fn decode_view_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ViewGroupResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ViewGroupResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_id: item.get_int(&[1]).map(|v| v as u8),
                group_name: item.get_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode GetGroupMembershipResponse command response (02)
pub fn decode_get_group_membership_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetGroupMembershipResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(GetGroupMembershipResponse {
                capacity: item.get_int(&[0]).map(|v| v as u8),
                group_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<u8> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode RemoveGroupResponse command response (03)
pub fn decode_remove_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RemoveGroupResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(RemoveGroupResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_id: item.get_int(&[1]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}