matc/clusters/codec/
closure_control.rs

1//! Matter TLV encoders and decoders for Closure Control Cluster
2//! Cluster ID: 0x0104
3//!
4//! This file is automatically generated from ClosureControl.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Enum definitions
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16#[repr(u8)]
17pub enum ClosureError {
18    /// An obstacle is blocking the closure movement
19    Physicallyblocked = 0,
20    /// The closure is unsafe to move, as determined by a sensor (e.g. photoelectric sensor) before attempting movement
21    Blockedbysensor = 1,
22    /// A warning raised by the closure that indicates an over-temperature, e.g. due to excessive drive or stall current
23    Temperaturelimited = 2,
24    /// Some malfunctions that are not easily recoverable are detected, or urgent servicing is needed
25    Maintenancerequired = 3,
26    /// An internal element is prohibiting motion, e.g. an integrated door within a bigger garage door is open and prevents motion
27    Internalinterference = 4,
28}
29
30impl ClosureError {
31    /// Convert from u8 value
32    pub fn from_u8(value: u8) -> Option<Self> {
33        match value {
34            0 => Some(ClosureError::Physicallyblocked),
35            1 => Some(ClosureError::Blockedbysensor),
36            2 => Some(ClosureError::Temperaturelimited),
37            3 => Some(ClosureError::Maintenancerequired),
38            4 => Some(ClosureError::Internalinterference),
39            _ => None,
40        }
41    }
42
43    /// Convert to u8 value
44    pub fn to_u8(self) -> u8 {
45        self as u8
46    }
47}
48
49impl From<ClosureError> for u8 {
50    fn from(val: ClosureError) -> Self {
51        val as u8
52    }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
56#[repr(u8)]
57pub enum CurrentPosition {
58    /// Fully closed state
59    Fullyclosed = 0,
60    /// Fully opened state
61    Fullyopened = 1,
62    /// Partially opened state (closure is not fully opened or fully closed)
63    Partiallyopened = 2,
64    /// Closure is in the Pedestrian position
65    Openedforpedestrian = 3,
66    /// Closure is in the Ventilation position
67    Openedforventilation = 4,
68    /// Closure is in its "Signature position"
69    Openedatsignature = 5,
70}
71
72impl CurrentPosition {
73    /// Convert from u8 value
74    pub fn from_u8(value: u8) -> Option<Self> {
75        match value {
76            0 => Some(CurrentPosition::Fullyclosed),
77            1 => Some(CurrentPosition::Fullyopened),
78            2 => Some(CurrentPosition::Partiallyopened),
79            3 => Some(CurrentPosition::Openedforpedestrian),
80            4 => Some(CurrentPosition::Openedforventilation),
81            5 => Some(CurrentPosition::Openedatsignature),
82            _ => None,
83        }
84    }
85
86    /// Convert to u8 value
87    pub fn to_u8(self) -> u8 {
88        self as u8
89    }
90}
91
92impl From<CurrentPosition> for u8 {
93    fn from(val: CurrentPosition) -> Self {
94        val as u8
95    }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
99#[repr(u8)]
100pub enum MainState {
101    /// Closure is stopped
102    Stopped = 0,
103    /// Closure is actively moving
104    Moving = 1,
105    /// Closure is waiting before a motion (e.g. pre-heat, pre-check)
106    Waitingformotion = 2,
107    /// Closure is in an error state
108    Error = 3,
109    /// Closure is currently calibrating its Opened and Closed limits to determine effective physical range
110    Calibrating = 4,
111    /// Some protective measures are activated to prevent damage to the closure. Commands MAY be rejected.
112    Protected = 5,
113    /// Closure has a disengaged element preventing any actuator movements
114    Disengaged = 6,
115    /// Movement commands are ignored since the closure is not operational and requires further setup and/or calibration
116    Setuprequired = 7,
117}
118
119impl MainState {
120    /// Convert from u8 value
121    pub fn from_u8(value: u8) -> Option<Self> {
122        match value {
123            0 => Some(MainState::Stopped),
124            1 => Some(MainState::Moving),
125            2 => Some(MainState::Waitingformotion),
126            3 => Some(MainState::Error),
127            4 => Some(MainState::Calibrating),
128            5 => Some(MainState::Protected),
129            6 => Some(MainState::Disengaged),
130            7 => Some(MainState::Setuprequired),
131            _ => None,
132        }
133    }
134
135    /// Convert to u8 value
136    pub fn to_u8(self) -> u8 {
137        self as u8
138    }
139}
140
141impl From<MainState> for u8 {
142    fn from(val: MainState) -> Self {
143        val as u8
144    }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
148#[repr(u8)]
149pub enum TargetPosition {
150    /// Move to a fully closed state
151    Movetofullyclosed = 0,
152    /// Move to a fully open state
153    Movetofullyopen = 1,
154    /// Move to the Pedestrian position
155    Movetopedestrianposition = 2,
156    /// Move to the Ventilation position
157    Movetoventilationposition = 3,
158    /// Move to the Signature position
159    Movetosignatureposition = 4,
160}
161
162impl TargetPosition {
163    /// Convert from u8 value
164    pub fn from_u8(value: u8) -> Option<Self> {
165        match value {
166            0 => Some(TargetPosition::Movetofullyclosed),
167            1 => Some(TargetPosition::Movetofullyopen),
168            2 => Some(TargetPosition::Movetopedestrianposition),
169            3 => Some(TargetPosition::Movetoventilationposition),
170            4 => Some(TargetPosition::Movetosignatureposition),
171            _ => None,
172        }
173    }
174
175    /// Convert to u8 value
176    pub fn to_u8(self) -> u8 {
177        self as u8
178    }
179}
180
181impl From<TargetPosition> for u8 {
182    fn from(val: TargetPosition) -> Self {
183        val as u8
184    }
185}
186
187// Bitmap definitions
188
189/// LatchControlModes bitmap type
190pub type LatchControlModes = u8;
191
192/// Constants for LatchControlModes
193pub mod latchcontrolmodes {
194    /// Remote latching capability
195    pub const REMOTE_LATCHING: u8 = 0x01;
196    /// Remote unlatching capability
197    pub const REMOTE_UNLATCHING: u8 = 0x02;
198}
199
200// Struct definitions
201
202#[derive(Debug, serde::Serialize)]
203pub struct OverallCurrentState {
204    pub position: Option<CurrentPosition>,
205    pub latch: Option<bool>,
206    pub speed: Option<u8>,
207    pub secure_state: Option<bool>,
208}
209
210#[derive(Debug, serde::Serialize)]
211pub struct OverallTargetState {
212    pub position: Option<TargetPosition>,
213    pub latch: Option<bool>,
214    pub speed: Option<u8>,
215}
216
217// Command encoders
218
219/// Encode MoveTo command (0x01)
220pub fn encode_move_to(position: TargetPosition, latch: bool, speed: u8) -> anyhow::Result<Vec<u8>> {
221    let tlv = tlv::TlvItemEnc {
222        tag: 0,
223        value: tlv::TlvItemValueEnc::StructInvisible(vec![
224        (0, tlv::TlvItemValueEnc::UInt8(position.to_u8())).into(),
225        (1, tlv::TlvItemValueEnc::Bool(latch)).into(),
226        (2, tlv::TlvItemValueEnc::UInt8(speed)).into(),
227        ]),
228    };
229    Ok(tlv.encode()?)
230}
231
232// Attribute decoders
233
234/// Decode CountdownTime attribute (0x0000)
235pub fn decode_countdown_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
236    if let tlv::TlvItemValue::Int(v) = inp {
237        Ok(Some(*v as u32))
238    } else {
239        Ok(None)
240    }
241}
242
243/// Decode MainState attribute (0x0001)
244pub fn decode_main_state(inp: &tlv::TlvItemValue) -> anyhow::Result<MainState> {
245    if let tlv::TlvItemValue::Int(v) = inp {
246        MainState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
247    } else {
248        Err(anyhow::anyhow!("Expected Integer"))
249    }
250}
251
252/// Decode CurrentErrorList attribute (0x0002)
253pub fn decode_current_error_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ClosureError>> {
254    let mut res = Vec::new();
255    if let tlv::TlvItemValue::List(v) = inp {
256        for item in v {
257            if let tlv::TlvItemValue::Int(i) = &item.value {
258                if let Some(enum_val) = ClosureError::from_u8(*i as u8) {
259                    res.push(enum_val);
260                }
261            }
262        }
263    }
264    Ok(res)
265}
266
267/// Decode OverallCurrentState attribute (0x0003)
268pub fn decode_overall_current_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallCurrentState>> {
269    if let tlv::TlvItemValue::List(_fields) = inp {
270        // Struct with fields
271        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
272        Ok(Some(OverallCurrentState {
273                position: item.get_int(&[0]).and_then(|v| CurrentPosition::from_u8(v as u8)),
274                latch: item.get_bool(&[1]),
275                speed: item.get_int(&[2]).map(|v| v as u8),
276                secure_state: item.get_bool(&[3]),
277        }))
278    //} else if let tlv::TlvItemValue::Null = inp {
279    //    // Null value for nullable struct
280    //    Ok(None)
281    } else {
282    Ok(None)
283    //    Err(anyhow::anyhow!("Expected struct fields or null"))
284    }
285}
286
287/// Decode OverallTargetState attribute (0x0004)
288pub fn decode_overall_target_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallTargetState>> {
289    if let tlv::TlvItemValue::List(_fields) = inp {
290        // Struct with fields
291        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
292        Ok(Some(OverallTargetState {
293                position: item.get_int(&[0]).and_then(|v| TargetPosition::from_u8(v as u8)),
294                latch: item.get_bool(&[1]),
295                speed: item.get_int(&[2]).map(|v| v as u8),
296        }))
297    //} else if let tlv::TlvItemValue::Null = inp {
298    //    // Null value for nullable struct
299    //    Ok(None)
300    } else {
301    Ok(None)
302    //    Err(anyhow::anyhow!("Expected struct fields or null"))
303    }
304}
305
306/// Decode LatchControlModes attribute (0x0005)
307pub fn decode_latch_control_modes(inp: &tlv::TlvItemValue) -> anyhow::Result<LatchControlModes> {
308    if let tlv::TlvItemValue::Int(v) = inp {
309        Ok(*v as u8)
310    } else {
311        Err(anyhow::anyhow!("Expected Integer"))
312    }
313}
314
315
316// JSON dispatcher function
317
318/// Decode attribute value and return as JSON string
319///
320/// # Parameters
321/// * `cluster_id` - The cluster identifier
322/// * `attribute_id` - The attribute identifier
323/// * `tlv_value` - The TLV value to decode
324///
325/// # Returns
326/// JSON string representation of the decoded value or error
327pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
328    // Verify this is the correct cluster
329    if cluster_id != 0x0104 {
330        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0104, got {}\"}}", cluster_id);
331    }
332
333    match attribute_id {
334        0x0000 => {
335            match decode_countdown_time(tlv_value) {
336                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
337                Err(e) => format!("{{\"error\": \"{}\"}}", e),
338            }
339        }
340        0x0001 => {
341            match decode_main_state(tlv_value) {
342                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
343                Err(e) => format!("{{\"error\": \"{}\"}}", e),
344            }
345        }
346        0x0002 => {
347            match decode_current_error_list(tlv_value) {
348                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
349                Err(e) => format!("{{\"error\": \"{}\"}}", e),
350            }
351        }
352        0x0003 => {
353            match decode_overall_current_state(tlv_value) {
354                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
355                Err(e) => format!("{{\"error\": \"{}\"}}", e),
356            }
357        }
358        0x0004 => {
359            match decode_overall_target_state(tlv_value) {
360                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
361                Err(e) => format!("{{\"error\": \"{}\"}}", e),
362            }
363        }
364        0x0005 => {
365            match decode_latch_control_modes(tlv_value) {
366                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
367                Err(e) => format!("{{\"error\": \"{}\"}}", e),
368            }
369        }
370        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
371    }
372}
373
374/// Get list of all attributes supported by this cluster
375///
376/// # Returns
377/// Vector of tuples containing (attribute_id, attribute_name)
378pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
379    vec![
380        (0x0000, "CountdownTime"),
381        (0x0001, "MainState"),
382        (0x0002, "CurrentErrorList"),
383        (0x0003, "OverallCurrentState"),
384        (0x0004, "OverallTargetState"),
385        (0x0005, "LatchControlModes"),
386    ]
387}
388
389// Command listing
390
391pub fn get_command_list() -> Vec<(u32, &'static str)> {
392    vec![
393        (0x00, "Stop"),
394        (0x01, "MoveTo"),
395        (0x02, "Calibrate"),
396    ]
397}
398
399pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
400    match cmd_id {
401        0x00 => Some("Stop"),
402        0x01 => Some("MoveTo"),
403        0x02 => Some("Calibrate"),
404        _ => None,
405    }
406}
407
408pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
409    match cmd_id {
410        0x00 => Some(vec![]),
411        0x01 => Some(vec![
412            crate::clusters::codec::CommandField { tag: 0, name: "position", kind: crate::clusters::codec::FieldKind::Enum { name: "TargetPosition", variants: &[(0, "Movetofullyclosed"), (1, "Movetofullyopen"), (2, "Movetopedestrianposition"), (3, "Movetoventilationposition"), (4, "Movetosignatureposition")] }, optional: true, nullable: false },
413            crate::clusters::codec::CommandField { tag: 1, name: "latch", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
414            crate::clusters::codec::CommandField { tag: 2, name: "speed", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
415        ]),
416        0x02 => Some(vec![]),
417        _ => None,
418    }
419}
420
421pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
422    match cmd_id {
423        0x00 => Ok(vec![]),
424        0x01 => {
425        let position = {
426            let n = crate::clusters::codec::json_util::get_u64(args, "position")?;
427            TargetPosition::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid TargetPosition: {}", n))?
428        };
429        let latch = crate::clusters::codec::json_util::get_bool(args, "latch")?;
430        let speed = crate::clusters::codec::json_util::get_u8(args, "speed")?;
431        encode_move_to(position, latch, speed)
432        }
433        0x02 => Ok(vec![]),
434        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
435    }
436}
437
438// Typed facade (invokes + reads)
439
440/// Invoke `Stop` command on cluster `Closure Control`.
441pub async fn stop(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
442    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_STOP, &[]).await?;
443    Ok(())
444}
445
446/// Invoke `MoveTo` command on cluster `Closure Control`.
447pub async fn move_to(conn: &crate::controller::Connection, endpoint: u16, position: TargetPosition, latch: bool, speed: u8) -> anyhow::Result<()> {
448    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_MOVETO, &encode_move_to(position, latch, speed)?).await?;
449    Ok(())
450}
451
452/// Invoke `Calibrate` command on cluster `Closure Control`.
453pub async fn calibrate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
454    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_CALIBRATE, &[]).await?;
455    Ok(())
456}
457
458/// Read `CountdownTime` attribute from cluster `Closure Control`.
459pub async fn read_countdown_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
460    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_COUNTDOWNTIME).await?;
461    decode_countdown_time(&tlv)
462}
463
464/// Read `MainState` attribute from cluster `Closure Control`.
465pub async fn read_main_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<MainState> {
466    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_MAINSTATE).await?;
467    decode_main_state(&tlv)
468}
469
470/// Read `CurrentErrorList` attribute from cluster `Closure Control`.
471pub async fn read_current_error_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ClosureError>> {
472    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_CURRENTERRORLIST).await?;
473    decode_current_error_list(&tlv)
474}
475
476/// Read `OverallCurrentState` attribute from cluster `Closure Control`.
477pub async fn read_overall_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallCurrentState>> {
478    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLCURRENTSTATE).await?;
479    decode_overall_current_state(&tlv)
480}
481
482/// Read `OverallTargetState` attribute from cluster `Closure Control`.
483pub async fn read_overall_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallTargetState>> {
484    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLTARGETSTATE).await?;
485    decode_overall_target_state(&tlv)
486}
487
488/// Read `LatchControlModes` attribute from cluster `Closure Control`.
489pub async fn read_latch_control_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<LatchControlModes> {
490    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_LATCHCONTROLMODES).await?;
491    decode_latch_control_modes(&tlv)
492}
493
494#[derive(Debug, serde::Serialize)]
495pub struct OperationalErrorEvent {
496    pub error_state: Option<Vec<ClosureError>>,
497}
498
499#[derive(Debug, serde::Serialize)]
500pub struct EngageStateChangedEvent {
501    pub engage_value: Option<bool>,
502}
503
504#[derive(Debug, serde::Serialize)]
505pub struct SecureStateChangedEvent {
506    pub secure_value: Option<bool>,
507}
508
509// Event decoders
510
511/// Decode OperationalError event (0x00, priority: critical)
512pub fn decode_operational_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalErrorEvent> {
513    if let tlv::TlvItemValue::List(_fields) = inp {
514        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
515        Ok(OperationalErrorEvent {
516                                error_state: {
517                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
518                        let items: Vec<ClosureError> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { ClosureError::from_u8(*v as u8) } else { None } }).collect();
519                        Some(items)
520                    } else {
521                        None
522                    }
523                },
524        })
525    } else {
526        Err(anyhow::anyhow!("Expected struct fields"))
527    }
528}
529
530/// Decode EngageStateChanged event (0x02, priority: info)
531pub fn decode_engage_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EngageStateChangedEvent> {
532    if let tlv::TlvItemValue::List(_fields) = inp {
533        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
534        Ok(EngageStateChangedEvent {
535                                engage_value: item.get_bool(&[0]),
536        })
537    } else {
538        Err(anyhow::anyhow!("Expected struct fields"))
539    }
540}
541
542/// Decode SecureStateChanged event (0x03, priority: info)
543pub fn decode_secure_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<SecureStateChangedEvent> {
544    if let tlv::TlvItemValue::List(_fields) = inp {
545        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
546        Ok(SecureStateChangedEvent {
547                                secure_value: item.get_bool(&[0]),
548        })
549    } else {
550        Err(anyhow::anyhow!("Expected struct fields"))
551    }
552}
553