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
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Bitmap definitions
14
15/// NameSupport bitmap type
16pub type NameSupport = u8;
17
18/// Constants for NameSupport
19pub mod namesupport {
20    /// The ability to store a name for a group.
21    pub const GROUP_NAMES: u8 = 0x80;
22}
23
24// Command encoders
25
26/// Encode AddGroup command (0x00)
27pub fn encode_add_group(group_id: u8, group_name: String) -> anyhow::Result<Vec<u8>> {
28    let tlv = tlv::TlvItemEnc {
29        tag: 0,
30        value: tlv::TlvItemValueEnc::StructInvisible(vec![
31        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
32        (1, tlv::TlvItemValueEnc::String(group_name)).into(),
33        ]),
34    };
35    Ok(tlv.encode()?)
36}
37
38/// Encode ViewGroup command (0x01)
39pub fn encode_view_group(group_id: u8) -> anyhow::Result<Vec<u8>> {
40    let tlv = tlv::TlvItemEnc {
41        tag: 0,
42        value: tlv::TlvItemValueEnc::StructInvisible(vec![
43        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
44        ]),
45    };
46    Ok(tlv.encode()?)
47}
48
49/// Encode GetGroupMembership command (0x02)
50pub fn encode_get_group_membership(group_list: Vec<u8>) -> anyhow::Result<Vec<u8>> {
51    let tlv = tlv::TlvItemEnc {
52        tag: 0,
53        value: tlv::TlvItemValueEnc::StructInvisible(vec![
54        (0, tlv::TlvItemValueEnc::StructAnon(group_list.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
55        ]),
56    };
57    Ok(tlv.encode()?)
58}
59
60/// Encode RemoveGroup command (0x03)
61pub fn encode_remove_group(group_id: u8) -> anyhow::Result<Vec<u8>> {
62    let tlv = tlv::TlvItemEnc {
63        tag: 0,
64        value: tlv::TlvItemValueEnc::StructInvisible(vec![
65        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
66        ]),
67    };
68    Ok(tlv.encode()?)
69}
70
71/// Encode AddGroupIfIdentifying command (0x05)
72pub fn encode_add_group_if_identifying(group_id: u8, group_name: String) -> anyhow::Result<Vec<u8>> {
73    let tlv = tlv::TlvItemEnc {
74        tag: 0,
75        value: tlv::TlvItemValueEnc::StructInvisible(vec![
76        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
77        (1, tlv::TlvItemValueEnc::String(group_name)).into(),
78        ]),
79    };
80    Ok(tlv.encode()?)
81}
82
83// Attribute decoders
84
85/// Decode NameSupport attribute (0x0000)
86pub fn decode_name_support(inp: &tlv::TlvItemValue) -> anyhow::Result<NameSupport> {
87    if let tlv::TlvItemValue::Int(v) = inp {
88        Ok(*v as u8)
89    } else {
90        Err(anyhow::anyhow!("Expected Integer"))
91    }
92}
93
94
95// JSON dispatcher function
96
97/// Decode attribute value and return as JSON string
98///
99/// # Parameters
100/// * `cluster_id` - The cluster identifier
101/// * `attribute_id` - The attribute identifier
102/// * `tlv_value` - The TLV value to decode
103///
104/// # Returns
105/// JSON string representation of the decoded value or error
106pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
107    // Verify this is the correct cluster
108    if cluster_id != 0x0004 {
109        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0004, got {}\"}}", cluster_id);
110    }
111
112    match attribute_id {
113        0x0000 => {
114            match decode_name_support(tlv_value) {
115                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
116                Err(e) => format!("{{\"error\": \"{}\"}}", e),
117            }
118        }
119        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
120    }
121}
122
123/// Get list of all attributes supported by this cluster
124///
125/// # Returns
126/// Vector of tuples containing (attribute_id, attribute_name)
127pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
128    vec![
129        (0x0000, "NameSupport"),
130    ]
131}
132
133// Command listing
134
135pub fn get_command_list() -> Vec<(u32, &'static str)> {
136    vec![
137        (0x00, "AddGroup"),
138        (0x01, "ViewGroup"),
139        (0x02, "GetGroupMembership"),
140        (0x03, "RemoveGroup"),
141        (0x04, "RemoveAllGroups"),
142        (0x05, "AddGroupIfIdentifying"),
143    ]
144}
145
146pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
147    match cmd_id {
148        0x00 => Some("AddGroup"),
149        0x01 => Some("ViewGroup"),
150        0x02 => Some("GetGroupMembership"),
151        0x03 => Some("RemoveGroup"),
152        0x04 => Some("RemoveAllGroups"),
153        0x05 => Some("AddGroupIfIdentifying"),
154        _ => None,
155    }
156}
157
158pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
159    match cmd_id {
160        0x00 => Some(vec![
161            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
162            crate::clusters::codec::CommandField { tag: 1, name: "group_name", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
163        ]),
164        0x01 => Some(vec![
165            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
166        ]),
167        0x02 => Some(vec![
168            crate::clusters::codec::CommandField { tag: 0, name: "group_list", kind: crate::clusters::codec::FieldKind::List { entry_type: "group-id" }, optional: false, nullable: false },
169        ]),
170        0x03 => Some(vec![
171            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
172        ]),
173        0x04 => Some(vec![]),
174        0x05 => Some(vec![
175            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
176            crate::clusters::codec::CommandField { tag: 1, name: "group_name", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
177        ]),
178        _ => None,
179    }
180}
181
182pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
183    match cmd_id {
184        0x00 => {
185        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
186        let group_name = crate::clusters::codec::json_util::get_string(args, "group_name")?;
187        encode_add_group(group_id, group_name)
188        }
189        0x01 => {
190        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
191        encode_view_group(group_id)
192        }
193        0x02 => Err(anyhow::anyhow!("command \"GetGroupMembership\" has complex args: use raw mode")),
194        0x03 => {
195        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
196        encode_remove_group(group_id)
197        }
198        0x04 => Ok(vec![]),
199        0x05 => {
200        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
201        let group_name = crate::clusters::codec::json_util::get_string(args, "group_name")?;
202        encode_add_group_if_identifying(group_id, group_name)
203        }
204        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
205    }
206}
207
208#[derive(Debug, serde::Serialize)]
209pub struct AddGroupResponse {
210    pub status: Option<u8>,
211    pub group_id: Option<u8>,
212}
213
214#[derive(Debug, serde::Serialize)]
215pub struct ViewGroupResponse {
216    pub status: Option<u8>,
217    pub group_id: Option<u8>,
218    pub group_name: Option<String>,
219}
220
221#[derive(Debug, serde::Serialize)]
222pub struct GetGroupMembershipResponse {
223    pub capacity: Option<u8>,
224    pub group_list: Option<Vec<u8>>,
225}
226
227#[derive(Debug, serde::Serialize)]
228pub struct RemoveGroupResponse {
229    pub status: Option<u8>,
230    pub group_id: Option<u8>,
231}
232
233// Command response decoders
234
235/// Decode AddGroupResponse command response (00)
236pub fn decode_add_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<AddGroupResponse> {
237    if let tlv::TlvItemValue::List(_fields) = inp {
238        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
239        Ok(AddGroupResponse {
240                status: item.get_int(&[0]).map(|v| v as u8),
241                group_id: item.get_int(&[1]).map(|v| v as u8),
242        })
243    } else {
244        Err(anyhow::anyhow!("Expected struct fields"))
245    }
246}
247
248/// Decode ViewGroupResponse command response (01)
249pub fn decode_view_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ViewGroupResponse> {
250    if let tlv::TlvItemValue::List(_fields) = inp {
251        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
252        Ok(ViewGroupResponse {
253                status: item.get_int(&[0]).map(|v| v as u8),
254                group_id: item.get_int(&[1]).map(|v| v as u8),
255                group_name: item.get_string_owned(&[2]),
256        })
257    } else {
258        Err(anyhow::anyhow!("Expected struct fields"))
259    }
260}
261
262/// Decode GetGroupMembershipResponse command response (02)
263pub fn decode_get_group_membership_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetGroupMembershipResponse> {
264    if let tlv::TlvItemValue::List(_fields) = inp {
265        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
266        Ok(GetGroupMembershipResponse {
267                capacity: item.get_int(&[0]).map(|v| v as u8),
268                group_list: {
269                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
270                        let items: Vec<u8> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u8) } else { None } }).collect();
271                        Some(items)
272                    } else {
273                        None
274                    }
275                },
276        })
277    } else {
278        Err(anyhow::anyhow!("Expected struct fields"))
279    }
280}
281
282/// Decode RemoveGroupResponse command response (03)
283pub fn decode_remove_group_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RemoveGroupResponse> {
284    if let tlv::TlvItemValue::List(_fields) = inp {
285        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
286        Ok(RemoveGroupResponse {
287                status: item.get_int(&[0]).map(|v| v as u8),
288                group_id: item.get_int(&[1]).map(|v| v as u8),
289        })
290    } else {
291        Err(anyhow::anyhow!("Expected struct fields"))
292    }
293}
294
295// Typed facade (invokes + reads)
296
297/// Invoke `AddGroup` command on cluster `Groups`.
298pub async fn add_group(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, group_name: String) -> anyhow::Result<AddGroupResponse> {
299    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?;
300    decode_add_group_response(&tlv)
301}
302
303/// Invoke `ViewGroup` command on cluster `Groups`.
304pub async fn view_group(conn: &crate::controller::Connection, endpoint: u16, group_id: u8) -> anyhow::Result<ViewGroupResponse> {
305    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?;
306    decode_view_group_response(&tlv)
307}
308
309/// Invoke `GetGroupMembership` command on cluster `Groups`.
310pub async fn get_group_membership(conn: &crate::controller::Connection, endpoint: u16, group_list: Vec<u8>) -> anyhow::Result<GetGroupMembershipResponse> {
311    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?;
312    decode_get_group_membership_response(&tlv)
313}
314
315/// Invoke `RemoveGroup` command on cluster `Groups`.
316pub async fn remove_group(conn: &crate::controller::Connection, endpoint: u16, group_id: u8) -> anyhow::Result<RemoveGroupResponse> {
317    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?;
318    decode_remove_group_response(&tlv)
319}
320
321/// Invoke `RemoveAllGroups` command on cluster `Groups`.
322pub async fn remove_all_groups(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
323    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_CMD_ID_REMOVEALLGROUPS, &[]).await?;
324    Ok(())
325}
326
327/// Invoke `AddGroupIfIdentifying` command on cluster `Groups`.
328pub async fn add_group_if_identifying(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, group_name: String) -> anyhow::Result<()> {
329    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?;
330    Ok(())
331}
332
333/// Read `NameSupport` attribute from cluster `Groups`.
334pub async fn read_name_support(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<NameSupport> {
335    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GROUPS, crate::clusters::defs::CLUSTER_GROUPS_ATTR_ID_NAMESUPPORT).await?;
336    decode_name_support(&tlv)
337}
338