matc/clusters/codec/
groups.rs

1//! Matter TLV encoders and decoders for Groups Cluster
2//! Cluster ID: 0x0004
3//!
4//! This file is automatically generated from Groups.xml
5
6use crate::tlv;
7use anyhow;
8use serde_json;
9
10
11// Bitmap definitions
12
13/// NameSupport bitmap type
14pub type NameSupport = u8;
15
16/// Constants for NameSupport
17pub mod namesupport {
18    /// The ability to store a name for a group.
19    pub const GROUP_NAMES: u8 = 0x80;
20}
21
22// Command encoders
23
24/// Encode AddGroup command (0x00)
25pub fn encode_add_group(group_id: u8, group_name: String) -> anyhow::Result<Vec<u8>> {
26    let tlv = tlv::TlvItemEnc {
27        tag: 0,
28        value: tlv::TlvItemValueEnc::StructInvisible(vec![
29        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
30        (1, tlv::TlvItemValueEnc::String(group_name)).into(),
31        ]),
32    };
33    Ok(tlv.encode()?)
34}
35
36/// Encode ViewGroup command (0x01)
37pub fn encode_view_group(group_id: u8) -> anyhow::Result<Vec<u8>> {
38    let tlv = tlv::TlvItemEnc {
39        tag: 0,
40        value: tlv::TlvItemValueEnc::StructInvisible(vec![
41        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
42        ]),
43    };
44    Ok(tlv.encode()?)
45}
46
47/// Encode GetGroupMembership command (0x02)
48pub fn encode_get_group_membership(group_list: Vec<u8>) -> anyhow::Result<Vec<u8>> {
49    let tlv = tlv::TlvItemEnc {
50        tag: 0,
51        value: tlv::TlvItemValueEnc::StructInvisible(vec![
52        (0, tlv::TlvItemValueEnc::StructAnon(group_list.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
53        ]),
54    };
55    Ok(tlv.encode()?)
56}
57
58/// Encode RemoveGroup command (0x03)
59pub fn encode_remove_group(group_id: u8) -> anyhow::Result<Vec<u8>> {
60    let tlv = tlv::TlvItemEnc {
61        tag: 0,
62        value: tlv::TlvItemValueEnc::StructInvisible(vec![
63        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
64        ]),
65    };
66    Ok(tlv.encode()?)
67}
68
69/// Encode AddGroupIfIdentifying command (0x05)
70pub fn encode_add_group_if_identifying(group_id: u8, group_name: String) -> anyhow::Result<Vec<u8>> {
71    let tlv = tlv::TlvItemEnc {
72        tag: 0,
73        value: tlv::TlvItemValueEnc::StructInvisible(vec![
74        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
75        (1, tlv::TlvItemValueEnc::String(group_name)).into(),
76        ]),
77    };
78    Ok(tlv.encode()?)
79}
80
81// Attribute decoders
82
83/// Decode NameSupport attribute (0x0000)
84pub fn decode_name_support(inp: &tlv::TlvItemValue) -> anyhow::Result<NameSupport> {
85    if let tlv::TlvItemValue::Int(v) = inp {
86        Ok(*v as u8)
87    } else {
88        Err(anyhow::anyhow!("Expected Integer"))
89    }
90}
91
92
93// JSON dispatcher function
94
95/// Decode attribute value and return as JSON string
96///
97/// # Parameters
98/// * `cluster_id` - The cluster identifier
99/// * `attribute_id` - The attribute identifier
100/// * `tlv_value` - The TLV value to decode
101///
102/// # Returns
103/// JSON string representation of the decoded value or error
104pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
105    // Verify this is the correct cluster
106    if cluster_id != 0x0004 {
107        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0004, got {}\"}}", cluster_id);
108    }
109
110    match attribute_id {
111        0x0000 => {
112            match decode_name_support(tlv_value) {
113                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
114                Err(e) => format!("{{\"error\": \"{}\"}}", e),
115            }
116        }
117        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
118    }
119}
120
121/// Get list of all attributes supported by this cluster
122///
123/// # Returns
124/// Vector of tuples containing (attribute_id, attribute_name)
125pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
126    vec![
127        (0x0000, "NameSupport"),
128    ]
129}
130
131#[derive(Debug, serde::Serialize)]
132pub struct AddGroupResponse {
133    pub status: Option<u8>,
134    pub group_id: Option<u8>,
135}
136
137#[derive(Debug, serde::Serialize)]
138pub struct ViewGroupResponse {
139    pub status: Option<u8>,
140    pub group_id: Option<u8>,
141    pub group_name: Option<String>,
142}
143
144#[derive(Debug, serde::Serialize)]
145pub struct GetGroupMembershipResponse {
146    pub capacity: Option<u8>,
147    pub group_list: Option<Vec<u8>>,
148}
149
150#[derive(Debug, serde::Serialize)]
151pub struct RemoveGroupResponse {
152    pub status: Option<u8>,
153    pub group_id: Option<u8>,
154}
155
156// Command response decoders
157
158/// Decode AddGroupResponse command response (00)
159pub fn decode_add_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<AddGroupResponse> {
160    if let tlv::TlvItemValue::List(_fields) = inp {
161        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
162        Ok(AddGroupResponse {
163                status: item.get_int(&[0]).map(|v| v as u8),
164                group_id: item.get_int(&[1]).map(|v| v as u8),
165        })
166    } else {
167        Err(anyhow::anyhow!("Expected struct fields"))
168    }
169}
170
171/// Decode ViewGroupResponse command response (01)
172pub fn decode_view_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ViewGroupResponse> {
173    if let tlv::TlvItemValue::List(_fields) = inp {
174        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
175        Ok(ViewGroupResponse {
176                status: item.get_int(&[0]).map(|v| v as u8),
177                group_id: item.get_int(&[1]).map(|v| v as u8),
178                group_name: item.get_string_owned(&[2]),
179        })
180    } else {
181        Err(anyhow::anyhow!("Expected struct fields"))
182    }
183}
184
185/// Decode GetGroupMembershipResponse command response (02)
186pub fn decode_get_group_membership_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetGroupMembershipResponse> {
187    if let tlv::TlvItemValue::List(_fields) = inp {
188        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
189        Ok(GetGroupMembershipResponse {
190                capacity: item.get_int(&[0]).map(|v| v as u8),
191                group_list: {
192                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
193                        let items: Vec<u8> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u8) } else { None } }).collect();
194                        Some(items)
195                    } else {
196                        None
197                    }
198                },
199        })
200    } else {
201        Err(anyhow::anyhow!("Expected struct fields"))
202    }
203}
204
205/// Decode RemoveGroupResponse command response (03)
206pub fn decode_remove_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RemoveGroupResponse> {
207    if let tlv::TlvItemValue::List(_fields) = inp {
208        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
209        Ok(RemoveGroupResponse {
210                status: item.get_int(&[0]).map(|v| v as u8),
211                group_id: item.get_int(&[1]).map(|v| v as u8),
212        })
213    } else {
214        Err(anyhow::anyhow!("Expected struct fields"))
215    }
216}
217