matc 0.1.3

Matter protocol library (controller side)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Matter TLV encoders and decoders for Valve Configuration and Control Cluster
//! Cluster ID: 0x0081
//!
//! This file is automatically generated from ValveConfigurationControl.xml

#![allow(clippy::too_many_arguments)]

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
    /// The requested action could not be performed due to a fault on the valve.
    Failureduetofault = 2,
}

impl StatusCode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            2 => Some(StatusCode::Failureduetofault),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ValveState {
    /// Valve is in closed position
    Closed = 0,
    /// Valve is in open position
    Open = 1,
    /// Valve is transitioning between closed and open positions or between levels
    Transitioning = 2,
}

impl ValveState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ValveState::Closed),
            1 => Some(ValveState::Open),
            2 => Some(ValveState::Transitioning),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// ValveFault bitmap type
pub type ValveFault = u8;

/// Constants for ValveFault
pub mod valvefault {
    /// Unspecified fault detected
    pub const GENERAL_FAULT: u8 = 0x01;
    /// Valve is blocked
    pub const BLOCKED: u8 = 0x02;
    /// Valve has detected a leak
    pub const LEAKING: u8 = 0x04;
    /// No valve is connected to controller
    pub const NOT_CONNECTED: u8 = 0x08;
    /// Short circuit is detected
    pub const SHORT_CIRCUIT: u8 = 0x10;
    /// The available current has been exceeded
    pub const CURRENT_EXCEEDED: u8 = 0x20;
}

// Command encoders

/// Encode Open command (0x00)
pub fn encode_open(open_duration: Option<u32>, target_level: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt32(open_duration.unwrap_or(0))).into());
    if let Some(x) = target_level { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode OpenDuration attribute (0x0000)
pub fn decode_open_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u32))
    } else {
        Ok(None)
    }
}

/// Decode DefaultOpenDuration attribute (0x0001)
pub fn decode_default_open_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u32))
    } else {
        Ok(None)
    }
}

/// Decode AutoCloseTime attribute (0x0002)
pub fn decode_auto_close_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode RemainingDuration attribute (0x0003)
pub fn decode_remaining_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u32))
    } else {
        Ok(None)
    }
}

/// Decode CurrentState attribute (0x0004)
pub fn decode_current_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<ValveState>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(ValveState::from_u8(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode TargetState attribute (0x0005)
pub fn decode_target_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<ValveState>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(ValveState::from_u8(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode CurrentLevel attribute (0x0006)
pub fn decode_current_level(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode TargetLevel attribute (0x0007)
pub fn decode_target_level(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}

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

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

/// Decode LevelStep attribute (0x000A)
pub fn decode_level_step(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 != 0x0081 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0081, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_open_duration(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_default_open_duration(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_auto_close_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_remaining_duration(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_current_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_target_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_current_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_target_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_default_open_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_valve_fault(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_level_step(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, "OpenDuration"),
        (0x0001, "DefaultOpenDuration"),
        (0x0002, "AutoCloseTime"),
        (0x0003, "RemainingDuration"),
        (0x0004, "CurrentState"),
        (0x0005, "TargetState"),
        (0x0006, "CurrentLevel"),
        (0x0007, "TargetLevel"),
        (0x0008, "DefaultOpenLevel"),
        (0x0009, "ValveFault"),
        (0x000A, "LevelStep"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Open"),
        0x01 => Some("Close"),
        _ => 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: "open_duration", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: true },
            crate::clusters::codec::CommandField { tag: 1, name: "target_level", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let open_duration = crate::clusters::codec::json_util::get_opt_u32(args, "open_duration")?;
        let target_level = crate::clusters::codec::json_util::get_opt_u8(args, "target_level")?;
        encode_open(open_duration, target_level)
        }
        0x01 => Ok(vec![]),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `Open` command on cluster `Valve Configuration and Control`.
pub async fn open(conn: &crate::controller::Connection, endpoint: u16, open_duration: Option<u32>, target_level: Option<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_CMD_ID_OPEN, &encode_open(open_duration, target_level)?).await?;
    Ok(())
}

/// Invoke `Close` command on cluster `Valve Configuration and Control`.
pub async fn close(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_CMD_ID_CLOSE, &[]).await?;
    Ok(())
}

/// Read `OpenDuration` attribute from cluster `Valve Configuration and Control`.
pub async fn read_open_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_OPENDURATION).await?;
    decode_open_duration(&tlv)
}

/// Read `DefaultOpenDuration` attribute from cluster `Valve Configuration and Control`.
pub async fn read_default_open_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_DEFAULTOPENDURATION).await?;
    decode_default_open_duration(&tlv)
}

/// Read `AutoCloseTime` attribute from cluster `Valve Configuration and Control`.
pub async fn read_auto_close_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_AUTOCLOSETIME).await?;
    decode_auto_close_time(&tlv)
}

/// Read `RemainingDuration` attribute from cluster `Valve Configuration and Control`.
pub async fn read_remaining_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_REMAININGDURATION).await?;
    decode_remaining_duration(&tlv)
}

/// Read `CurrentState` attribute from cluster `Valve Configuration and Control`.
pub async fn read_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<ValveState>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_CURRENTSTATE).await?;
    decode_current_state(&tlv)
}

/// Read `TargetState` attribute from cluster `Valve Configuration and Control`.
pub async fn read_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<ValveState>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_TARGETSTATE).await?;
    decode_target_state(&tlv)
}

/// Read `CurrentLevel` attribute from cluster `Valve Configuration and Control`.
pub async fn read_current_level(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_CURRENTLEVEL).await?;
    decode_current_level(&tlv)
}

/// Read `TargetLevel` attribute from cluster `Valve Configuration and Control`.
pub async fn read_target_level(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_TARGETLEVEL).await?;
    decode_target_level(&tlv)
}

/// Read `DefaultOpenLevel` attribute from cluster `Valve Configuration and Control`.
pub async fn read_default_open_level(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_DEFAULTOPENLEVEL).await?;
    decode_default_open_level(&tlv)
}

/// Read `ValveFault` attribute from cluster `Valve Configuration and Control`.
pub async fn read_valve_fault(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ValveFault> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_VALVEFAULT).await?;
    decode_valve_fault(&tlv)
}

/// Read `LevelStep` attribute from cluster `Valve Configuration and Control`.
pub async fn read_level_step(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_VALVE_CONFIGURATION_AND_CONTROL, crate::clusters::defs::CLUSTER_VALVE_CONFIGURATION_AND_CONTROL_ATTR_ID_LEVELSTEP).await?;
    decode_level_step(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct ValveStateChangedEvent {
    pub valve_state: Option<ValveState>,
    pub valve_level: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct ValveFaultEvent {
    pub valve_fault: Option<ValveFault>,
}

// Event decoders

/// Decode ValveStateChanged event (0x00, priority: info)
pub fn decode_valve_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ValveStateChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ValveStateChangedEvent {
                                valve_state: item.get_int(&[0]).and_then(|v| ValveState::from_u8(v as u8)),
                                valve_level: item.get_int(&[1]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ValveFault event (0x01, priority: info)
pub fn decode_valve_fault_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ValveFaultEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ValveFaultEvent {
                                valve_fault: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}