matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Target Navigator Cluster
//! Cluster ID: 0x0505
//!
//! This file is automatically generated from TargetNavigator.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 Status {
    /// Command succeeded
    Success = 0,
    /// Requested target was not found in the TargetList
    Targetnotfound = 1,
    /// Target request is not allowed in current state.
    Notallowed = 2,
}

impl Status {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Status::Success),
            1 => Some(Status::Targetnotfound),
            2 => Some(Status::Notallowed),
            _ => 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
    }
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct TargetInfo {
    pub identifier: Option<u8>,
    pub name: Option<String>,
}

// Command encoders

/// Encode NavigateTarget command (0x00)
pub fn encode_navigate_target(target: u8, data: Option<String>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(target)).into());
    if let Some(x) = data { tlv_fields.push((1, tlv::TlvItemValueEnc::String(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode TargetList attribute (0x0000)
pub fn decode_target_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TargetInfo>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TargetInfo {
                identifier: item.get_int(&[0]).map(|v| v as u8),
                name: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode CurrentTarget attribute (0x0001)
pub fn decode_current_target(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}


// JSON dispatcher function

/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
    // Verify this is the correct cluster
    if cluster_id != 0x0505 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0505, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_target_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_current_target(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),
    }
}

/// Get list of all attributes supported by this cluster
///
/// # Returns
/// Vector of tuples containing (attribute_id, attribute_name)
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x0000, "TargetList"),
        (0x0001, "CurrentTarget"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("NavigateTarget"),
        _ => 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: "target", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "data", 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 target = crate::clusters::codec::json_util::get_u8(args, "target")?;
        let data = crate::clusters::codec::json_util::get_opt_string(args, "data")?;
        encode_navigate_target(target, data)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct NavigateTargetResponse {
    pub status: Option<Status>,
    pub data: Option<String>,
}

// Command response decoders

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

// Typed facade (invokes + reads)

/// Invoke `NavigateTarget` command on cluster `Target Navigator`.
pub async fn navigate_target(conn: &crate::controller::Connection, endpoint: u16, target: u8, data: Option<String>) -> anyhow::Result<NavigateTargetResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TARGET_NAVIGATOR, crate::clusters::defs::CLUSTER_TARGET_NAVIGATOR_CMD_ID_NAVIGATETARGET, &encode_navigate_target(target, data)?).await?;
    decode_navigate_target_response(&tlv)
}

/// Read `TargetList` attribute from cluster `Target Navigator`.
pub async fn read_target_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TargetInfo>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TARGET_NAVIGATOR, crate::clusters::defs::CLUSTER_TARGET_NAVIGATOR_ATTR_ID_TARGETLIST).await?;
    decode_target_list(&tlv)
}

/// Read `CurrentTarget` attribute from cluster `Target Navigator`.
pub async fn read_current_target(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TARGET_NAVIGATOR, crate::clusters::defs::CLUSTER_TARGET_NAVIGATOR_ATTR_ID_CURRENTTARGET).await?;
    decode_current_target(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct TargetUpdatedEvent {
    pub target_list: Option<Vec<TargetInfo>>,
    pub current_target: Option<u8>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub data: Option<Vec<u8>>,
}

// Event decoders

/// Decode TargetUpdated event (0x00, priority: info)
pub fn decode_target_updated_event(inp: &tlv::TlvItemValue) -> anyhow::Result<TargetUpdatedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(TargetUpdatedEvent {
                                target_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TargetInfo {
                identifier: list_item.get_int(&[0]).map(|v| v as u8),
                name: list_item.get_string_owned(&[1]),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                                current_target: item.get_int(&[1]).map(|v| v as u8),
                                data: item.get_octet_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}