matc/clusters/codec/
commissioner_control_cluster.rs

1//! Matter TLV encoders and decoders for Commissioner Control Cluster
2//! Cluster ID: 0x0751
3//!
4//! This file is automatically generated from CommissionerControlCluster.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Import serialization helpers for octet strings
14use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
15
16// Bitmap definitions
17
18/// SupportedDeviceCategory bitmap type
19pub type SupportedDeviceCategory = u8;
20
21/// Constants for SupportedDeviceCategory
22pub mod supporteddevicecategory {
23    /// Aggregators which support Fabric Synchronization may be commissioned.
24    pub const FABRIC_SYNCHRONIZATION: u8 = 0x01;
25}
26
27// Command encoders
28
29/// Encode RequestCommissioningApproval command (0x00)
30pub fn encode_request_commissioning_approval(request_id: u64, vendor_id: u16, product_id: u16, label: String) -> anyhow::Result<Vec<u8>> {
31    let tlv = tlv::TlvItemEnc {
32        tag: 0,
33        value: tlv::TlvItemValueEnc::StructInvisible(vec![
34        (0, tlv::TlvItemValueEnc::UInt64(request_id)).into(),
35        (1, tlv::TlvItemValueEnc::UInt16(vendor_id)).into(),
36        (2, tlv::TlvItemValueEnc::UInt16(product_id)).into(),
37        (3, tlv::TlvItemValueEnc::String(label)).into(),
38        ]),
39    };
40    Ok(tlv.encode()?)
41}
42
43/// Encode CommissionNode command (0x01)
44pub fn encode_commission_node(request_id: u64, response_timeout_seconds: u16) -> anyhow::Result<Vec<u8>> {
45    let tlv = tlv::TlvItemEnc {
46        tag: 0,
47        value: tlv::TlvItemValueEnc::StructInvisible(vec![
48        (0, tlv::TlvItemValueEnc::UInt64(request_id)).into(),
49        (1, tlv::TlvItemValueEnc::UInt16(response_timeout_seconds)).into(),
50        ]),
51    };
52    Ok(tlv.encode()?)
53}
54
55// Attribute decoders
56
57/// Decode SupportedDeviceCategories attribute (0x0000)
58pub fn decode_supported_device_categories(inp: &tlv::TlvItemValue) -> anyhow::Result<SupportedDeviceCategory> {
59    if let tlv::TlvItemValue::Int(v) = inp {
60        Ok(*v as u8)
61    } else {
62        Err(anyhow::anyhow!("Expected Integer"))
63    }
64}
65
66
67// JSON dispatcher function
68
69/// Decode attribute value and return as JSON string
70///
71/// # Parameters
72/// * `cluster_id` - The cluster identifier
73/// * `attribute_id` - The attribute identifier
74/// * `tlv_value` - The TLV value to decode
75///
76/// # Returns
77/// JSON string representation of the decoded value or error
78pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
79    // Verify this is the correct cluster
80    if cluster_id != 0x0751 {
81        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0751, got {}\"}}", cluster_id);
82    }
83
84    match attribute_id {
85        0x0000 => {
86            match decode_supported_device_categories(tlv_value) {
87                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
88                Err(e) => format!("{{\"error\": \"{}\"}}", e),
89            }
90        }
91        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
92    }
93}
94
95/// Get list of all attributes supported by this cluster
96///
97/// # Returns
98/// Vector of tuples containing (attribute_id, attribute_name)
99pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
100    vec![
101        (0x0000, "SupportedDeviceCategories"),
102    ]
103}
104
105// Command listing
106
107pub fn get_command_list() -> Vec<(u32, &'static str)> {
108    vec![
109        (0x00, "RequestCommissioningApproval"),
110        (0x01, "CommissionNode"),
111    ]
112}
113
114pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
115    match cmd_id {
116        0x00 => Some("RequestCommissioningApproval"),
117        0x01 => Some("CommissionNode"),
118        _ => None,
119    }
120}
121
122pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
123    match cmd_id {
124        0x00 => Some(vec![
125            crate::clusters::codec::CommandField { tag: 0, name: "request_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
126            crate::clusters::codec::CommandField { tag: 1, name: "vendor_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
127            crate::clusters::codec::CommandField { tag: 2, name: "product_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
128            crate::clusters::codec::CommandField { tag: 3, name: "label", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
129        ]),
130        0x01 => Some(vec![
131            crate::clusters::codec::CommandField { tag: 0, name: "request_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
132            crate::clusters::codec::CommandField { tag: 1, name: "response_timeout_seconds", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
133        ]),
134        _ => None,
135    }
136}
137
138pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
139    match cmd_id {
140        0x00 => {
141        let request_id = crate::clusters::codec::json_util::get_u64(args, "request_id")?;
142        let vendor_id = crate::clusters::codec::json_util::get_u16(args, "vendor_id")?;
143        let product_id = crate::clusters::codec::json_util::get_u16(args, "product_id")?;
144        let label = crate::clusters::codec::json_util::get_string(args, "label")?;
145        encode_request_commissioning_approval(request_id, vendor_id, product_id, label)
146        }
147        0x01 => {
148        let request_id = crate::clusters::codec::json_util::get_u64(args, "request_id")?;
149        let response_timeout_seconds = crate::clusters::codec::json_util::get_u16(args, "response_timeout_seconds")?;
150        encode_commission_node(request_id, response_timeout_seconds)
151        }
152        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
153    }
154}
155
156#[derive(Debug, serde::Serialize)]
157pub struct ReverseOpenCommissioningWindow {
158    pub commissioning_timeout: Option<u16>,
159    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
160    pub pake_passcode_verifier: Option<Vec<u8>>,
161    pub discriminator: Option<u16>,
162    pub iterations: Option<u32>,
163    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
164    pub salt: Option<Vec<u8>>,
165}
166
167// Command response decoders
168
169/// Decode ReverseOpenCommissioningWindow command response (02)
170pub fn decode_reverse_open_commissioning_window(inp: &tlv::TlvItemValue) -> anyhow::Result<ReverseOpenCommissioningWindow> {
171    if let tlv::TlvItemValue::List(_fields) = inp {
172        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
173        Ok(ReverseOpenCommissioningWindow {
174                commissioning_timeout: item.get_int(&[0]).map(|v| v as u16),
175                pake_passcode_verifier: item.get_octet_string_owned(&[1]),
176                discriminator: item.get_int(&[2]).map(|v| v as u16),
177                iterations: item.get_int(&[3]).map(|v| v as u32),
178                salt: item.get_octet_string_owned(&[4]),
179        })
180    } else {
181        Err(anyhow::anyhow!("Expected struct fields"))
182    }
183}
184
185// Typed facade (invokes + reads)
186
187/// Invoke `RequestCommissioningApproval` command on cluster `Commissioner Control`.
188pub async fn request_commissioning_approval(conn: &crate::controller::Connection, endpoint: u16, request_id: u64, vendor_id: u16, product_id: u16, label: String) -> anyhow::Result<()> {
189    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_COMMISSIONER_CONTROL, crate::clusters::defs::CLUSTER_COMMISSIONER_CONTROL_CMD_ID_REQUESTCOMMISSIONINGAPPROVAL, &encode_request_commissioning_approval(request_id, vendor_id, product_id, label)?).await?;
190    Ok(())
191}
192
193/// Invoke `CommissionNode` command on cluster `Commissioner Control`.
194pub async fn commission_node(conn: &crate::controller::Connection, endpoint: u16, request_id: u64, response_timeout_seconds: u16) -> anyhow::Result<ReverseOpenCommissioningWindow> {
195    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMISSIONER_CONTROL, crate::clusters::defs::CLUSTER_COMMISSIONER_CONTROL_CMD_ID_COMMISSIONNODE, &encode_commission_node(request_id, response_timeout_seconds)?).await?;
196    decode_reverse_open_commissioning_window(&tlv)
197}
198
199/// Read `SupportedDeviceCategories` attribute from cluster `Commissioner Control`.
200pub async fn read_supported_device_categories(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<SupportedDeviceCategory> {
201    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMISSIONER_CONTROL, crate::clusters::defs::CLUSTER_COMMISSIONER_CONTROL_ATTR_ID_SUPPORTEDDEVICECATEGORIES).await?;
202    decode_supported_device_categories(&tlv)
203}
204
205#[derive(Debug, serde::Serialize)]
206pub struct CommissioningRequestResultEvent {
207    pub request_id: Option<u64>,
208    pub client_node_id: Option<u64>,
209    pub status_code: Option<u8>,
210}
211
212// Event decoders
213
214/// Decode CommissioningRequestResult event (0x00, priority: info)
215pub fn decode_commissioning_request_result_event(inp: &tlv::TlvItemValue) -> anyhow::Result<CommissioningRequestResultEvent> {
216    if let tlv::TlvItemValue::List(_fields) = inp {
217        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
218        Ok(CommissioningRequestResultEvent {
219                                request_id: item.get_int(&[0]),
220                                client_node_id: item.get_int(&[1]),
221                                status_code: item.get_int(&[2]).map(|v| v as u8),
222        })
223    } else {
224        Err(anyhow::anyhow!("Expected struct fields"))
225    }
226}
227