use crate::tlv;
use anyhow;
use serde_json;
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
pub fn decode_ssid(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_passphrase_surrogate(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0451 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0451, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_ssid(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_passphrase_surrogate(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, "SSID"),
(0x0001, "PassphraseSurrogate"),
]
}
#[derive(Debug, serde::Serialize)]
pub struct NetworkPassphraseResponse {
#[serde(serialize_with = "serialize_opt_bytes_as_hex")]
pub passphrase: Option<Vec<u8>>,
}
pub fn decode_network_passphrase_response(inp: &tlv::TlvItemValue) -> anyhow::Result<NetworkPassphraseResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(NetworkPassphraseResponse {
passphrase: item.get_octet_string_owned(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}