use crate::tlv;
use anyhow;
use serde_json;
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
Endpointalreadyinstalled = 2,
Rootcertificatenotfound = 3,
Clientcertificatenotfound = 4,
Endpointinuse = 5,
Invalidtime = 6,
}
impl StatusCode {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
2 => Some(StatusCode::Endpointalreadyinstalled),
3 => Some(StatusCode::Rootcertificatenotfound),
4 => Some(StatusCode::Clientcertificatenotfound),
5 => Some(StatusCode::Endpointinuse),
6 => Some(StatusCode::Invalidtime),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<StatusCode> for u8 {
fn from(val: StatusCode) -> Self {
val as u8
}
}
#[derive(Debug, serde::Serialize)]
pub struct TLSEndpoint {
pub endpoint_id: Option<u8>,
#[serde(serialize_with = "serialize_opt_bytes_as_hex")]
pub hostname: Option<Vec<u8>>,
pub port: Option<u16>,
pub caid: Option<u8>,
pub ccdid: Option<u8>,
pub reference_count: Option<u8>,
}
pub fn encode_provision_endpoint(hostname: Vec<u8>, port: u16, caid: u8, ccdid: Option<u8>, endpoint_id: Option<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::OctetString(hostname)).into(),
(1, tlv::TlvItemValueEnc::UInt16(port)).into(),
(2, tlv::TlvItemValueEnc::UInt8(caid)).into(),
(3, tlv::TlvItemValueEnc::UInt8(ccdid.unwrap_or(0))).into(),
(4, tlv::TlvItemValueEnc::UInt8(endpoint_id.unwrap_or(0))).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_find_endpoint(endpoint_id: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(endpoint_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_remove_endpoint(endpoint_id: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(endpoint_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_max_provisioned(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_provisioned_endpoints(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TLSEndpoint>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(TLSEndpoint {
endpoint_id: item.get_int(&[0]).map(|v| v as u8),
hostname: item.get_octet_string_owned(&[1]),
port: item.get_int(&[2]).map(|v| v as u16),
caid: item.get_int(&[3]).map(|v| v as u8),
ccdid: item.get_int(&[4]).map(|v| v as u8),
reference_count: item.get_int(&[5]).map(|v| v as u8),
});
}
}
Ok(res)
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0802 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0802, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_max_provisioned(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_provisioned_endpoints(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, "MaxProvisioned"),
(0x0001, "ProvisionedEndpoints"),
]
}
#[derive(Debug, serde::Serialize)]
pub struct ProvisionEndpointResponse {
pub endpoint_id: Option<u8>,
}
#[derive(Debug, serde::Serialize)]
pub struct FindEndpointResponse {
pub endpoint: Option<TLSEndpoint>,
}
pub fn decode_provision_endpoint_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ProvisionEndpointResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(ProvisionEndpointResponse {
endpoint_id: item.get_int(&[0]).map(|v| v as u8),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_find_endpoint_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindEndpointResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(FindEndpointResponse {
endpoint: {
if let Some(nested_tlv) = item.get(&[0]) {
if let tlv::TlvItemValue::List(_) = nested_tlv {
let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
Some(TLSEndpoint {
endpoint_id: nested_item.get_int(&[0]).map(|v| v as u8),
hostname: nested_item.get_octet_string_owned(&[1]),
port: nested_item.get_int(&[2]).map(|v| v as u16),
caid: nested_item.get_int(&[3]).map(|v| v as u8),
ccdid: nested_item.get_int(&[4]).map(|v| v as u8),
reference_count: nested_item.get_int(&[5]).map(|v| v as u8),
})
} else {
None
}
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}