matc 0.1.3

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for Ecosystem Information Cluster
//! Cluster ID: 0x0750
//!
//! This file is automatically generated from EcosystemInformationCluster.xml

#![allow(clippy::too_many_arguments)]

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


// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct DeviceType {
    pub device_type: Option<u32>,
    pub revision: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct EcosystemDevice {
    pub device_name: Option<String>,
    pub device_name_last_edit: Option<u64>,
    pub bridged_endpoint: Option<u16>,
    pub original_endpoint: Option<u16>,
    pub device_types: Option<Vec<DeviceType>>,
    pub unique_location_i_ds: Option<Vec<String>>,
    pub unique_location_i_ds_last_edit: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct EcosystemLocation {
    pub unique_location_id: Option<String>,
    pub location_descriptor: Option<LocationDescriptor>,
    pub location_descriptor_last_edit: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct LocationDescriptor {
    pub location_name: Option<String>,
    pub floor_number: Option<u16>,
    pub area_type: Option<u8>,
}

// Attribute decoders

/// Decode DeviceDirectory attribute (0x0000)
pub fn decode_device_directory(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<EcosystemDevice>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(EcosystemDevice {
                device_name: item.get_string_owned(&[0]),
                device_name_last_edit: item.get_int(&[1]),
                bridged_endpoint: item.get_int(&[2]).map(|v| v as u16),
                original_endpoint: item.get_int(&[3]).map(|v| v as u16),
                device_types: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[4]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(DeviceType {
                device_type: list_item.get_int(&[0]).map(|v| v as u32),
                revision: list_item.get_int(&[1]).map(|v| v as u16),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                unique_location_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[5]) {
                        let items: Vec<String> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::String(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                unique_location_i_ds_last_edit: item.get_int(&[6]),
            });
        }
    }
    Ok(res)
}

/// Decode LocationDirectory attribute (0x0001)
pub fn decode_location_directory(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<EcosystemLocation>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(EcosystemLocation {
                unique_location_id: item.get_string_owned(&[0]),
                location_descriptor: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(LocationDescriptor {
                location_name: nested_item.get_string_owned(&[0]),
                floor_number: nested_item.get_int(&[1]).map(|v| v as u16),
                area_type: nested_item.get_int(&[2]).map(|v| v as u8),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                location_descriptor_last_edit: item.get_int(&[2]),
            });
        }
    }
    Ok(res)
}


// 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 != 0x0750 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0750, got {}\"}}", cluster_id);
    }

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

// Typed facade (invokes + reads)

/// Read `DeviceDirectory` attribute from cluster `Ecosystem Information`.
pub async fn read_device_directory(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<EcosystemDevice>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ECOSYSTEM_INFORMATION, crate::clusters::defs::CLUSTER_ECOSYSTEM_INFORMATION_ATTR_ID_DEVICEDIRECTORY).await?;
    decode_device_directory(&tlv)
}

/// Read `LocationDirectory` attribute from cluster `Ecosystem Information`.
pub async fn read_location_directory(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<EcosystemLocation>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ECOSYSTEM_INFORMATION, crate::clusters::defs::CLUSTER_ECOSYSTEM_INFORMATION_ATTR_ID_LOCATIONDIRECTORY).await?;
    decode_location_directory(&tlv)
}