matc/clusters/codec/
thread_network_directory.rs

1//! Matter TLV encoders and decoders for Thread Network Directory Cluster
2//! Cluster ID: 0x0453
3//!
4//! This file is automatically generated from ThreadNetworkDirectory.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// Struct definitions
17
18#[derive(Debug, serde::Serialize)]
19pub struct ThreadNetwork {
20    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
21    pub extended_pan_id: Option<Vec<u8>>,
22    pub network_name: Option<String>,
23    pub channel: Option<u16>,
24    pub active_timestamp: Option<u64>,
25}
26
27// Command encoders
28
29/// Encode AddNetwork command (0x00)
30pub fn encode_add_network(operational_dataset: Vec<u8>) -> anyhow::Result<Vec<u8>> {
31    let tlv = tlv::TlvItemEnc {
32        tag: 0,
33        value: tlv::TlvItemValueEnc::StructInvisible(vec![
34        (0, tlv::TlvItemValueEnc::OctetString(operational_dataset)).into(),
35        ]),
36    };
37    Ok(tlv.encode()?)
38}
39
40/// Encode RemoveNetwork command (0x01)
41pub fn encode_remove_network(extended_pan_id: Vec<u8>) -> anyhow::Result<Vec<u8>> {
42    let tlv = tlv::TlvItemEnc {
43        tag: 0,
44        value: tlv::TlvItemValueEnc::StructInvisible(vec![
45        (0, tlv::TlvItemValueEnc::OctetString(extended_pan_id)).into(),
46        ]),
47    };
48    Ok(tlv.encode()?)
49}
50
51/// Encode GetOperationalDataset command (0x02)
52pub fn encode_get_operational_dataset(extended_pan_id: Vec<u8>) -> anyhow::Result<Vec<u8>> {
53    let tlv = tlv::TlvItemEnc {
54        tag: 0,
55        value: tlv::TlvItemValueEnc::StructInvisible(vec![
56        (0, tlv::TlvItemValueEnc::OctetString(extended_pan_id)).into(),
57        ]),
58    };
59    Ok(tlv.encode()?)
60}
61
62// Attribute decoders
63
64/// Decode PreferredExtendedPanID attribute (0x0000)
65pub fn decode_preferred_extended_pan_id(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Vec<u8>>> {
66    if let tlv::TlvItemValue::OctetString(v) = inp {
67        Ok(Some(v.clone()))
68    } else {
69        Ok(None)
70    }
71}
72
73/// Decode ThreadNetworks attribute (0x0001)
74pub fn decode_thread_networks(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ThreadNetwork>> {
75    let mut res = Vec::new();
76    if let tlv::TlvItemValue::List(v) = inp {
77        for item in v {
78            res.push(ThreadNetwork {
79                extended_pan_id: item.get_octet_string_owned(&[0]),
80                network_name: item.get_string_owned(&[1]),
81                channel: item.get_int(&[2]).map(|v| v as u16),
82                active_timestamp: item.get_int(&[3]),
83            });
84        }
85    }
86    Ok(res)
87}
88
89/// Decode ThreadNetworkTableSize attribute (0x0002)
90pub fn decode_thread_network_table_size(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
91    if let tlv::TlvItemValue::Int(v) = inp {
92        Ok(*v as u8)
93    } else {
94        Err(anyhow::anyhow!("Expected UInt8"))
95    }
96}
97
98
99// JSON dispatcher function
100
101/// Decode attribute value and return as JSON string
102///
103/// # Parameters
104/// * `cluster_id` - The cluster identifier
105/// * `attribute_id` - The attribute identifier
106/// * `tlv_value` - The TLV value to decode
107///
108/// # Returns
109/// JSON string representation of the decoded value or error
110pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
111    // Verify this is the correct cluster
112    if cluster_id != 0x0453 {
113        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0453, got {}\"}}", cluster_id);
114    }
115
116    match attribute_id {
117        0x0000 => {
118            match decode_preferred_extended_pan_id(tlv_value) {
119                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
120                Err(e) => format!("{{\"error\": \"{}\"}}", e),
121            }
122        }
123        0x0001 => {
124            match decode_thread_networks(tlv_value) {
125                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
126                Err(e) => format!("{{\"error\": \"{}\"}}", e),
127            }
128        }
129        0x0002 => {
130            match decode_thread_network_table_size(tlv_value) {
131                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
132                Err(e) => format!("{{\"error\": \"{}\"}}", e),
133            }
134        }
135        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
136    }
137}
138
139/// Get list of all attributes supported by this cluster
140///
141/// # Returns
142/// Vector of tuples containing (attribute_id, attribute_name)
143pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
144    vec![
145        (0x0000, "PreferredExtendedPanID"),
146        (0x0001, "ThreadNetworks"),
147        (0x0002, "ThreadNetworkTableSize"),
148    ]
149}
150
151// Command listing
152
153pub fn get_command_list() -> Vec<(u32, &'static str)> {
154    vec![
155        (0x00, "AddNetwork"),
156        (0x01, "RemoveNetwork"),
157        (0x02, "GetOperationalDataset"),
158    ]
159}
160
161pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
162    match cmd_id {
163        0x00 => Some("AddNetwork"),
164        0x01 => Some("RemoveNetwork"),
165        0x02 => Some("GetOperationalDataset"),
166        _ => None,
167    }
168}
169
170pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
171    match cmd_id {
172        0x00 => Some(vec![
173            crate::clusters::codec::CommandField { tag: 0, name: "operational_dataset", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
174        ]),
175        0x01 => Some(vec![
176            crate::clusters::codec::CommandField { tag: 0, name: "extended_pan_id", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
177        ]),
178        0x02 => Some(vec![
179            crate::clusters::codec::CommandField { tag: 0, name: "extended_pan_id", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
180        ]),
181        _ => None,
182    }
183}
184
185pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
186    match cmd_id {
187        0x00 => {
188        let operational_dataset = crate::clusters::codec::json_util::get_octstr(args, "operational_dataset")?;
189        encode_add_network(operational_dataset)
190        }
191        0x01 => {
192        let extended_pan_id = crate::clusters::codec::json_util::get_octstr(args, "extended_pan_id")?;
193        encode_remove_network(extended_pan_id)
194        }
195        0x02 => {
196        let extended_pan_id = crate::clusters::codec::json_util::get_octstr(args, "extended_pan_id")?;
197        encode_get_operational_dataset(extended_pan_id)
198        }
199        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
200    }
201}
202
203#[derive(Debug, serde::Serialize)]
204pub struct OperationalDatasetResponse {
205    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
206    pub operational_dataset: Option<Vec<u8>>,
207}
208
209// Command response decoders
210
211/// Decode OperationalDatasetResponse command response (03)
212pub fn decode_operational_dataset_response(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalDatasetResponse> {
213    if let tlv::TlvItemValue::List(_fields) = inp {
214        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
215        Ok(OperationalDatasetResponse {
216                operational_dataset: item.get_octet_string_owned(&[0]),
217        })
218    } else {
219        Err(anyhow::anyhow!("Expected struct fields"))
220    }
221}
222
223// Typed facade (invokes + reads)
224
225/// Invoke `AddNetwork` command on cluster `Thread Network Directory`.
226pub async fn add_network(conn: &crate::controller::Connection, endpoint: u16, operational_dataset: Vec<u8>) -> anyhow::Result<()> {
227    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_CMD_ID_ADDNETWORK, &encode_add_network(operational_dataset)?).await?;
228    Ok(())
229}
230
231/// Invoke `RemoveNetwork` command on cluster `Thread Network Directory`.
232pub async fn remove_network(conn: &crate::controller::Connection, endpoint: u16, extended_pan_id: Vec<u8>) -> anyhow::Result<()> {
233    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_CMD_ID_REMOVENETWORK, &encode_remove_network(extended_pan_id)?).await?;
234    Ok(())
235}
236
237/// Invoke `GetOperationalDataset` command on cluster `Thread Network Directory`.
238pub async fn get_operational_dataset(conn: &crate::controller::Connection, endpoint: u16, extended_pan_id: Vec<u8>) -> anyhow::Result<OperationalDatasetResponse> {
239    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_CMD_ID_GETOPERATIONALDATASET, &encode_get_operational_dataset(extended_pan_id)?).await?;
240    decode_operational_dataset_response(&tlv)
241}
242
243/// Read `PreferredExtendedPanID` attribute from cluster `Thread Network Directory`.
244pub async fn read_preferred_extended_pan_id(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Vec<u8>>> {
245    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_ATTR_ID_PREFERREDEXTENDEDPANID).await?;
246    decode_preferred_extended_pan_id(&tlv)
247}
248
249/// Read `ThreadNetworks` attribute from cluster `Thread Network Directory`.
250pub async fn read_thread_networks(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ThreadNetwork>> {
251    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_ATTR_ID_THREADNETWORKS).await?;
252    decode_thread_networks(&tlv)
253}
254
255/// Read `ThreadNetworkTableSize` attribute from cluster `Thread Network Directory`.
256pub async fn read_thread_network_table_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
257    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_THREAD_NETWORK_DIRECTORY, crate::clusters::defs::CLUSTER_THREAD_NETWORK_DIRECTORY_ATTR_ID_THREADNETWORKTABLESIZE).await?;
258    decode_thread_network_table_size(&tlv)
259}
260