1#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
15
16#[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
27pub 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
40pub 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
51pub 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
62pub 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
73pub 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
89pub 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
99pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
111 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
139pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
144 vec![
145 (0x0000, "PreferredExtendedPanID"),
146 (0x0001, "ThreadNetworks"),
147 (0x0002, "ThreadNetworkTableSize"),
148 ]
149}
150
151pub 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
209pub 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
223pub 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
231pub 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
237pub 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
243pub 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
249pub 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
255pub 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