#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
#[derive(Debug, serde::Serialize)]
pub struct ThreadNetwork {
#[serde(serialize_with = "serialize_opt_bytes_as_hex")]
pub extended_pan_id: Option<Vec<u8>>,
pub network_name: Option<String>,
pub channel: Option<u16>,
pub active_timestamp: Option<u64>,
}
pub fn encode_add_network(operational_dataset: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::OctetString(operational_dataset)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_remove_network(extended_pan_id: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::OctetString(extended_pan_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_get_operational_dataset(extended_pan_id: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::OctetString(extended_pan_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_preferred_extended_pan_id(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Vec<u8>>> {
if let tlv::TlvItemValue::OctetString(v) = inp {
Ok(Some(v.clone()))
} else {
Ok(None)
}
}
pub fn decode_thread_networks(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ThreadNetwork>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(ThreadNetwork {
extended_pan_id: item.get_octet_string_owned(&[0]),
network_name: item.get_string_owned(&[1]),
channel: item.get_int(&[2]).map(|v| v as u16),
active_timestamp: item.get_int(&[3]),
});
}
}
Ok(res)
}
pub fn decode_thread_network_table_size(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0453 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0453, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_preferred_extended_pan_id(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_thread_networks(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_thread_network_table_size(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
_ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
}
}
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
vec![
(0x0000, "PreferredExtendedPanID"),
(0x0001, "ThreadNetworks"),
(0x0002, "ThreadNetworkTableSize"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "AddNetwork"),
(0x01, "RemoveNetwork"),
(0x02, "GetOperationalDataset"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("AddNetwork"),
0x01 => Some("RemoveNetwork"),
0x02 => Some("GetOperationalDataset"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "operational_dataset", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
]),
0x01 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "extended_pan_id", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
]),
0x02 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "extended_pan_id", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x00 => {
let operational_dataset = crate::clusters::codec::json_util::get_octstr(args, "operational_dataset")?;
encode_add_network(operational_dataset)
}
0x01 => {
let extended_pan_id = crate::clusters::codec::json_util::get_octstr(args, "extended_pan_id")?;
encode_remove_network(extended_pan_id)
}
0x02 => {
let extended_pan_id = crate::clusters::codec::json_util::get_octstr(args, "extended_pan_id")?;
encode_get_operational_dataset(extended_pan_id)
}
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
#[derive(Debug, serde::Serialize)]
pub struct OperationalDatasetResponse {
#[serde(serialize_with = "serialize_opt_bytes_as_hex")]
pub operational_dataset: Option<Vec<u8>>,
}
pub fn decode_operational_dataset_response(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalDatasetResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(OperationalDatasetResponse {
operational_dataset: item.get_octet_string_owned(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub async fn add_network(conn: &crate::controller::Connection, endpoint: u16, operational_dataset: Vec<u8>) -> anyhow::Result<()> {
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?;
Ok(())
}
pub async fn remove_network(conn: &crate::controller::Connection, endpoint: u16, extended_pan_id: Vec<u8>) -> anyhow::Result<()> {
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?;
Ok(())
}
pub async fn get_operational_dataset(conn: &crate::controller::Connection, endpoint: u16, extended_pan_id: Vec<u8>) -> anyhow::Result<OperationalDatasetResponse> {
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?;
decode_operational_dataset_response(&tlv)
}
pub async fn read_preferred_extended_pan_id(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Vec<u8>>> {
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?;
decode_preferred_extended_pan_id(&tlv)
}
pub async fn read_thread_networks(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ThreadNetwork>> {
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?;
decode_thread_networks(&tlv)
}
pub async fn read_thread_network_table_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
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?;
decode_thread_network_table_size(&tlv)
}