matc/clusters/codec/
target_navigator.rs

1//! Matter TLV encoders and decoders for Target Navigator Cluster
2//! Cluster ID: 0x0505
3//!
4//! This file is automatically generated from TargetNavigator.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Import serialization helpers for octet strings
14use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
15
16// Enum definitions
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
19#[repr(u8)]
20pub enum Status {
21    /// Command succeeded
22    Success = 0,
23    /// Requested target was not found in the TargetList
24    Targetnotfound = 1,
25    /// Target request is not allowed in current state.
26    Notallowed = 2,
27}
28
29impl Status {
30    /// Convert from u8 value
31    pub fn from_u8(value: u8) -> Option<Self> {
32        match value {
33            0 => Some(Status::Success),
34            1 => Some(Status::Targetnotfound),
35            2 => Some(Status::Notallowed),
36            _ => None,
37        }
38    }
39
40    /// Convert to u8 value
41    pub fn to_u8(self) -> u8 {
42        self as u8
43    }
44}
45
46impl From<Status> for u8 {
47    fn from(val: Status) -> Self {
48        val as u8
49    }
50}
51
52// Struct definitions
53
54#[derive(Debug, serde::Serialize)]
55pub struct TargetInfo {
56    pub identifier: Option<u8>,
57    pub name: Option<String>,
58}
59
60// Command encoders
61
62/// Encode NavigateTarget command (0x00)
63pub fn encode_navigate_target(target: u8, data: String) -> anyhow::Result<Vec<u8>> {
64    let tlv = tlv::TlvItemEnc {
65        tag: 0,
66        value: tlv::TlvItemValueEnc::StructInvisible(vec![
67        (0, tlv::TlvItemValueEnc::UInt8(target)).into(),
68        (1, tlv::TlvItemValueEnc::String(data)).into(),
69        ]),
70    };
71    Ok(tlv.encode()?)
72}
73
74// Attribute decoders
75
76/// Decode TargetList attribute (0x0000)
77pub fn decode_target_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TargetInfo>> {
78    let mut res = Vec::new();
79    if let tlv::TlvItemValue::List(v) = inp {
80        for item in v {
81            res.push(TargetInfo {
82                identifier: item.get_int(&[0]).map(|v| v as u8),
83                name: item.get_string_owned(&[1]),
84            });
85        }
86    }
87    Ok(res)
88}
89
90/// Decode CurrentTarget attribute (0x0001)
91pub fn decode_current_target(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
92    if let tlv::TlvItemValue::Int(v) = inp {
93        Ok(*v as u8)
94    } else {
95        Err(anyhow::anyhow!("Expected UInt8"))
96    }
97}
98
99
100// JSON dispatcher function
101
102/// Decode attribute value and return as JSON string
103///
104/// # Parameters
105/// * `cluster_id` - The cluster identifier
106/// * `attribute_id` - The attribute identifier
107/// * `tlv_value` - The TLV value to decode
108///
109/// # Returns
110/// JSON string representation of the decoded value or error
111pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
112    // Verify this is the correct cluster
113    if cluster_id != 0x0505 {
114        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0505, got {}\"}}", cluster_id);
115    }
116
117    match attribute_id {
118        0x0000 => {
119            match decode_target_list(tlv_value) {
120                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
121                Err(e) => format!("{{\"error\": \"{}\"}}", e),
122            }
123        }
124        0x0001 => {
125            match decode_current_target(tlv_value) {
126                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
127                Err(e) => format!("{{\"error\": \"{}\"}}", e),
128            }
129        }
130        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
131    }
132}
133
134/// Get list of all attributes supported by this cluster
135///
136/// # Returns
137/// Vector of tuples containing (attribute_id, attribute_name)
138pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
139    vec![
140        (0x0000, "TargetList"),
141        (0x0001, "CurrentTarget"),
142    ]
143}
144
145// Command listing
146
147pub fn get_command_list() -> Vec<(u32, &'static str)> {
148    vec![
149        (0x00, "NavigateTarget"),
150    ]
151}
152
153pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
154    match cmd_id {
155        0x00 => Some("NavigateTarget"),
156        _ => None,
157    }
158}
159
160pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
161    match cmd_id {
162        0x00 => Some(vec![
163            crate::clusters::codec::CommandField { tag: 0, name: "target", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
164            crate::clusters::codec::CommandField { tag: 1, name: "data", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
165        ]),
166        _ => None,
167    }
168}
169
170pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
171    match cmd_id {
172        0x00 => {
173        let target = crate::clusters::codec::json_util::get_u8(args, "target")?;
174        let data = crate::clusters::codec::json_util::get_string(args, "data")?;
175        encode_navigate_target(target, data)
176        }
177        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
178    }
179}
180
181#[derive(Debug, serde::Serialize)]
182pub struct NavigateTargetResponse {
183    pub status: Option<Status>,
184    pub data: Option<String>,
185}
186
187// Command response decoders
188
189/// Decode NavigateTargetResponse command response (01)
190pub fn decode_navigate_target_response(inp: &tlv::TlvItemValue) -> anyhow::Result<NavigateTargetResponse> {
191    if let tlv::TlvItemValue::List(_fields) = inp {
192        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
193        Ok(NavigateTargetResponse {
194                status: item.get_int(&[0]).and_then(|v| Status::from_u8(v as u8)),
195                data: item.get_string_owned(&[1]),
196        })
197    } else {
198        Err(anyhow::anyhow!("Expected struct fields"))
199    }
200}
201
202// Typed facade (invokes + reads)
203
204/// Invoke `NavigateTarget` command on cluster `Target Navigator`.
205pub async fn navigate_target(conn: &crate::controller::Connection, endpoint: u16, target: u8, data: String) -> anyhow::Result<NavigateTargetResponse> {
206    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?;
207    decode_navigate_target_response(&tlv)
208}
209
210/// Read `TargetList` attribute from cluster `Target Navigator`.
211pub async fn read_target_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TargetInfo>> {
212    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TARGET_NAVIGATOR, crate::clusters::defs::CLUSTER_TARGET_NAVIGATOR_ATTR_ID_TARGETLIST).await?;
213    decode_target_list(&tlv)
214}
215
216/// Read `CurrentTarget` attribute from cluster `Target Navigator`.
217pub async fn read_current_target(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
218    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TARGET_NAVIGATOR, crate::clusters::defs::CLUSTER_TARGET_NAVIGATOR_ATTR_ID_CURRENTTARGET).await?;
219    decode_current_target(&tlv)
220}
221
222#[derive(Debug, serde::Serialize)]
223pub struct TargetUpdatedEvent {
224    pub target_list: Option<Vec<TargetInfo>>,
225    pub current_target: Option<u8>,
226    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
227    pub data: Option<Vec<u8>>,
228}
229
230// Event decoders
231
232/// Decode TargetUpdated event (0x00, priority: info)
233pub fn decode_target_updated_event(inp: &tlv::TlvItemValue) -> anyhow::Result<TargetUpdatedEvent> {
234    if let tlv::TlvItemValue::List(_fields) = inp {
235        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
236        Ok(TargetUpdatedEvent {
237                                target_list: {
238                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
239                        let mut items = Vec::new();
240                        for list_item in l {
241                            items.push(TargetInfo {
242                identifier: list_item.get_int(&[0]).map(|v| v as u8),
243                name: list_item.get_string_owned(&[1]),
244                            });
245                        }
246                        Some(items)
247                    } else {
248                        None
249                    }
250                },
251                                current_target: item.get_int(&[1]).map(|v| v as u8),
252                                data: item.get_octet_string_owned(&[2]),
253        })
254    } else {
255        Err(anyhow::anyhow!("Expected struct fields"))
256    }
257}
258