#![allow(clippy::too_many_arguments)]
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 ICACResponseStatus {
Ok = 0,
Invalidpublickey = 1,
Invalidicac = 2,
}
impl ICACResponseStatus {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ICACResponseStatus::Ok),
1 => Some(ICACResponseStatus::Invalidpublickey),
2 => Some(ICACResponseStatus::Invalidicac),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ICACResponseStatus> for u8 {
fn from(val: ICACResponseStatus) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
Busy = 2,
Pakeparametererror = 3,
Windownotopen = 4,
Vidnotverified = 5,
Invalidadministratorfabricindex = 6,
}
impl StatusCode {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
2 => Some(StatusCode::Busy),
3 => Some(StatusCode::Pakeparametererror),
4 => Some(StatusCode::Windownotopen),
5 => Some(StatusCode::Vidnotverified),
6 => Some(StatusCode::Invalidadministratorfabricindex),
_ => 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, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TransferAnchorResponseStatus {
Ok = 0,
Transferanchorstatusdatastorebusy = 1,
Transferanchorstatusnouserconsent = 2,
}
impl TransferAnchorResponseStatus {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(TransferAnchorResponseStatus::Ok),
1 => Some(TransferAnchorResponseStatus::Transferanchorstatusdatastorebusy),
2 => Some(TransferAnchorResponseStatus::Transferanchorstatusnouserconsent),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<TransferAnchorResponseStatus> for u8 {
fn from(val: TransferAnchorResponseStatus) -> Self {
val as u8
}
}
pub fn encode_add_icac(icac_value: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(1, tlv::TlvItemValueEnc::OctetString(icac_value)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_open_joint_commissioning_window(commissioning_timeout: u16, pake_passcode_verifier: Vec<u8>, discriminator: u16, iterations: u32, salt: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt16(commissioning_timeout)).into(),
(1, tlv::TlvItemValueEnc::OctetString(pake_passcode_verifier)).into(),
(2, tlv::TlvItemValueEnc::UInt16(discriminator)).into(),
(3, tlv::TlvItemValueEnc::UInt32(iterations)).into(),
(4, tlv::TlvItemValueEnc::OctetString(salt)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_announce_joint_fabric_administrator(endpoint_id: u16) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt16(endpoint_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_administrator_fabric_index(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v as u8))
} else {
Ok(None)
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0753 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0753, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_administrator_fabric_index(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, "AdministratorFabricIndex"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "ICACCSRRequest"),
(0x02, "AddICAC"),
(0x04, "OpenJointCommissioningWindow"),
(0x05, "TransferAnchorRequest"),
(0x07, "TransferAnchorComplete"),
(0x08, "AnnounceJointFabricAdministrator"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("ICACCSRRequest"),
0x02 => Some("AddICAC"),
0x04 => Some("OpenJointCommissioningWindow"),
0x05 => Some("TransferAnchorRequest"),
0x07 => Some("TransferAnchorComplete"),
0x08 => Some("AnnounceJointFabricAdministrator"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![]),
0x02 => Some(vec![
crate::clusters::codec::CommandField { tag: 1, name: "icac_value", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
]),
0x04 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "commissioning_timeout", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 1, name: "pake_passcode_verifier", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 2, name: "discriminator", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 3, name: "iterations", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 4, name: "salt", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
]),
0x05 => Some(vec![]),
0x07 => Some(vec![]),
0x08 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "endpoint_id", kind: crate::clusters::codec::FieldKind::U16, 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 => Ok(vec![]),
0x02 => {
let icac_value = crate::clusters::codec::json_util::get_octstr(args, "icac_value")?;
encode_add_icac(icac_value)
}
0x04 => {
let commissioning_timeout = crate::clusters::codec::json_util::get_u16(args, "commissioning_timeout")?;
let pake_passcode_verifier = crate::clusters::codec::json_util::get_octstr(args, "pake_passcode_verifier")?;
let discriminator = crate::clusters::codec::json_util::get_u16(args, "discriminator")?;
let iterations = crate::clusters::codec::json_util::get_u32(args, "iterations")?;
let salt = crate::clusters::codec::json_util::get_octstr(args, "salt")?;
encode_open_joint_commissioning_window(commissioning_timeout, pake_passcode_verifier, discriminator, iterations, salt)
}
0x05 => Ok(vec![]),
0x07 => Ok(vec![]),
0x08 => {
let endpoint_id = crate::clusters::codec::json_util::get_u16(args, "endpoint_id")?;
encode_announce_joint_fabric_administrator(endpoint_id)
}
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
#[derive(Debug, serde::Serialize)]
pub struct ICACCSRResponse {
#[serde(serialize_with = "serialize_opt_bytes_as_hex")]
pub icaccsr: Option<Vec<u8>>,
}
#[derive(Debug, serde::Serialize)]
pub struct ICACResponse {
pub status_code: Option<ICACResponseStatus>,
}
#[derive(Debug, serde::Serialize)]
pub struct TransferAnchorResponse {
pub status_code: Option<TransferAnchorResponseStatus>,
}
pub fn decode_icaccsr_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ICACCSRResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(ICACCSRResponse {
icaccsr: item.get_octet_string_owned(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_icac_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ICACResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(ICACResponse {
status_code: item.get_int(&[0]).and_then(|v| ICACResponseStatus::from_u8(v as u8)),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_transfer_anchor_response(inp: &tlv::TlvItemValue) -> anyhow::Result<TransferAnchorResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(TransferAnchorResponse {
status_code: item.get_int(&[0]).and_then(|v| TransferAnchorResponseStatus::from_u8(v as u8)),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub async fn icaccsr_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ICACCSRResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_ICACCSRREQUEST, &[]).await?;
decode_icaccsr_response(&tlv)
}
pub async fn add_icac(conn: &crate::controller::Connection, endpoint: u16, icac_value: Vec<u8>) -> anyhow::Result<ICACResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_ADDICAC, &encode_add_icac(icac_value)?).await?;
decode_icac_response(&tlv)
}
pub async fn open_joint_commissioning_window(conn: &crate::controller::Connection, endpoint: u16, commissioning_timeout: u16, pake_passcode_verifier: Vec<u8>, discriminator: u16, iterations: u32, salt: Vec<u8>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_OPENJOINTCOMMISSIONINGWINDOW, &encode_open_joint_commissioning_window(commissioning_timeout, pake_passcode_verifier, discriminator, iterations, salt)?).await?;
Ok(())
}
pub async fn transfer_anchor_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TransferAnchorResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_TRANSFERANCHORREQUEST, &[]).await?;
decode_transfer_anchor_response(&tlv)
}
pub async fn transfer_anchor_complete(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_TRANSFERANCHORCOMPLETE, &[]).await?;
Ok(())
}
pub async fn announce_joint_fabric_administrator(conn: &crate::controller::Connection, endpoint: u16, endpoint_id: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_CMD_ID_ANNOUNCEJOINTFABRICADMINISTRATOR, &encode_announce_joint_fabric_administrator(endpoint_id)?).await?;
Ok(())
}
pub async fn read_administrator_fabric_index(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_JOINT_FABRIC_ADMINISTRATOR, crate::clusters::defs::CLUSTER_JOINT_FABRIC_ADMINISTRATOR_ATTR_ID_ADMINISTRATORFABRICINDEX).await?;
decode_administrator_fabric_index(&tlv)
}