matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Diagnostic Logs Cluster
//! Cluster ID: 0x0032
//!
//! This file is automatically generated from DiagnosticLogsCluster.xml

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Intent {
    /// Logs to be used for end-user support
    Endusersupport = 0,
    /// Logs to be used for network diagnostics
    Networkdiag = 1,
    /// Obtain crash logs from the Node
    Crashlogs = 2,
}

impl Intent {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Intent::Endusersupport),
            1 => Some(Intent::Networkdiag),
            2 => Some(Intent::Crashlogs),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<Intent> for u8 {
    fn from(val: Intent) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Status {
    /// Successful transfer of logs
    Success = 0,
    /// All logs have been transferred
    Exhausted = 1,
    /// No logs of the requested type available
    Nologs = 2,
    /// Unable to handle request, retry later
    Busy = 3,
    /// The request is denied, no logs being transferred
    Denied = 4,
}

impl Status {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Status::Success),
            1 => Some(Status::Exhausted),
            2 => Some(Status::Nologs),
            3 => Some(Status::Busy),
            4 => Some(Status::Denied),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<Status> for u8 {
    fn from(val: Status) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TransferProtocol {
    /// Logs to be returned as a response
    Responsepayload = 0,
    /// Logs to be returned using BDX
    Bdx = 1,
}

impl TransferProtocol {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(TransferProtocol::Responsepayload),
            1 => Some(TransferProtocol::Bdx),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<TransferProtocol> for u8 {
    fn from(val: TransferProtocol) -> Self {
        val as u8
    }
}

// Command encoders

/// Encode RetrieveLogsRequest command (0x00)
pub fn encode_retrieve_logs_request(intent: Intent, requested_protocol: TransferProtocol, transfer_file_designator: Option<String>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(intent.to_u8())).into());
    tlv_fields.push((1, tlv::TlvItemValueEnc::UInt8(requested_protocol.to_u8())).into());
    if let Some(x) = transfer_file_designator { tlv_fields.push((2, tlv::TlvItemValueEnc::String(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "RetrieveLogsRequest"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("RetrieveLogsRequest"),
        _ => 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: "intent", kind: crate::clusters::codec::FieldKind::Enum { name: "Intent", variants: &[(0, "Endusersupport"), (1, "Networkdiag"), (2, "Crashlogs")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "requested_protocol", kind: crate::clusters::codec::FieldKind::Enum { name: "TransferProtocol", variants: &[(0, "Responsepayload"), (1, "Bdx")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "transfer_file_designator", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let intent = {
            let n = crate::clusters::codec::json_util::get_u64(args, "intent")?;
            Intent::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid Intent: {}", n))?
        };
        let requested_protocol = {
            let n = crate::clusters::codec::json_util::get_u64(args, "requested_protocol")?;
            TransferProtocol::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid TransferProtocol: {}", n))?
        };
        let transfer_file_designator = crate::clusters::codec::json_util::get_opt_string(args, "transfer_file_designator")?;
        encode_retrieve_logs_request(intent, requested_protocol, transfer_file_designator)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct RetrieveLogsResponse {
    pub status: Option<Status>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub log_content: Option<Vec<u8>>,
    pub utc_time_stamp: Option<u64>,
    pub time_since_boot: Option<u8>,
}

// Command response decoders

/// Decode RetrieveLogsResponse command response (01)
pub fn decode_retrieve_logs_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RetrieveLogsResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(RetrieveLogsResponse {
                status: item.get_int(&[0]).and_then(|v| Status::from_u8(v as u8)),
                log_content: item.get_octet_string_owned(&[1]),
                utc_time_stamp: item.get_int(&[2]),
                time_since_boot: item.get_int(&[3]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `RetrieveLogsRequest` command on cluster `Diagnostic Logs`.
pub async fn retrieve_logs_request(conn: &crate::controller::Connection, endpoint: u16, intent: Intent, requested_protocol: TransferProtocol, transfer_file_designator: Option<String>) -> anyhow::Result<RetrieveLogsResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DIAGNOSTIC_LOGS, crate::clusters::defs::CLUSTER_DIAGNOSTIC_LOGS_CMD_ID_RETRIEVELOGSREQUEST, &encode_retrieve_logs_request(intent, requested_protocol, transfer_file_designator)?).await?;
    decode_retrieve_logs_response(&tlv)
}