matc 0.1.3

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

#![allow(clippy::too_many_arguments)]

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"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "AddGroup"),
        (0x01, "ViewGroup"),
        (0x02, "GetGroupMembership"),
        (0x03, "RemoveGroup"),
        (0x04, "RemoveAllGroups"),
        (0x05, "AddGroupIfIdentifying"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("AddGroup"),
        0x01 => Some("ViewGroup"),
        0x02 => Some("GetGroupMembership"),
        0x03 => Some("RemoveGroup"),
        0x04 => Some("RemoveAllGroups"),
        0x05 => Some("AddGroupIfIdentifying"),
        _ => 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: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "group_name", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_list", kind: crate::clusters::codec::FieldKind::List { entry_type: "group-id" }, optional: false, nullable: false },
        ]),
        0x03 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "group_name", kind: crate::clusters::codec::FieldKind::String, 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 group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        let group_name = crate::clusters::codec::json_util::get_string(args, "group_name")?;
        encode_add_group(group_id, group_name)
        }
        0x01 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        encode_view_group(group_id)
        }
        0x02 => Err(anyhow::anyhow!("command \"GetGroupMembership\" has complex args: use raw mode")),
        0x03 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        encode_remove_group(group_id)
        }
        0x04 => Ok(vec![]),
        0x05 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        let group_name = crate::clusters::codec::json_util::get_string(args, "group_name")?;
        encode_add_group_if_identifying(group_id, group_name)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[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"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `AddGroup` command on cluster `Groups`.
pub async fn add_group(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, group_name: String) -> anyhow::Result<AddGroupResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_ADDGROUP, &encode_add_group(group_id, group_name)?).await?;
    decode_add_group_response(&tlv)
}

/// Invoke `ViewGroup` command on cluster `Groups`.
pub async fn view_group(conn: &crate::controller::Connection, endpoint: u16, group_id: u8) -> anyhow::Result<ViewGroupResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_VIEWGROUP, &encode_view_group(group_id)?).await?;
    decode_view_group_response(&tlv)
}

/// Invoke `GetGroupMembership` command on cluster `Groups`.
pub async fn get_group_membership(conn: &crate::controller::Connection, endpoint: u16, group_list: Vec<u8>) -> anyhow::Result<GetGroupMembershipResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_GETGROUPMEMBERSHIP, &encode_get_group_membership(group_list)?).await?;
    decode_get_group_membership_response(&tlv)
}

/// Invoke `RemoveGroup` command on cluster `Groups`.
pub async fn remove_group(conn: &crate::controller::Connection, endpoint: u16, group_id: u8) -> anyhow::Result<RemoveGroupResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_REMOVEGROUP, &encode_remove_group(group_id)?).await?;
    decode_remove_group_response(&tlv)
}

/// Invoke `RemoveAllGroups` command on cluster `Groups`.
pub async fn remove_all_groups(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_REMOVEALLGROUPS, &[]).await?;
    Ok(())
}

/// Invoke `AddGroupIfIdentifying` command on cluster `Groups`.
pub async fn add_group_if_identifying(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, group_name: String) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_ADDGROUPIFIDENTIFYING, &encode_add_group_if_identifying(group_id, group_name)?).await?;
    Ok(())
}

/// Read `NameSupport` attribute from cluster `Groups`.
pub async fn read_name_support(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<NameSupport> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_ATTR_ID_NAMESUPPORT).await?;
    decode_name_support(&tlv)
}