matc 0.1.2

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
//! Matter TLV encoders and decoders for ICD Management Cluster
//! Cluster ID: 0x0046
//!
//! This file is automatically generated from ICDManagement.xml

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ClientType {
    /// The client is typically resident, always-on, fixed infrastructure in the home.
    Permanent = 0,
    /// The client is mobile or non-resident or not always-on and may not always be available in the home.
    Ephemeral = 1,
}

impl ClientType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ClientType::Permanent),
            1 => Some(ClientType::Ephemeral),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum OperatingMode {
    /// ICD is operating as a Short Idle Time ICD.
    Sit = 0,
    /// ICD is operating as a Long Idle Time ICD.
    Lit = 1,
}

impl OperatingMode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(OperatingMode::Sit),
            1 => Some(OperatingMode::Lit),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// UserActiveModeTrigger bitmap type
pub type UserActiveModeTrigger = u32;

/// Constants for UserActiveModeTrigger
pub mod useractivemodetrigger {
    /// Power Cycle to transition the device to ActiveMode
    pub const POWER_CYCLE: u32 = 0x01;
    /// Settings menu on the device informs how to transition the device to ActiveMode
    pub const SETTINGS_MENU: u32 = 0x02;
    /// Custom Instruction on how to transition the device to ActiveMode
    pub const CUSTOM_INSTRUCTION: u32 = 0x04;
    /// Device Manual informs how to transition the device to ActiveMode
    pub const DEVICE_MANUAL: u32 = 0x08;
    /// Actuate Sensor to transition the device to ActiveMode
    pub const ACTUATE_SENSOR: u32 = 0x10;
    /// Actuate Sensor for N seconds to transition the device to ActiveMode
    pub const ACTUATE_SENSOR_SECONDS: u32 = 0x20;
    /// Actuate Sensor N times to transition the device to ActiveMode
    pub const ACTUATE_SENSOR_TIMES: u32 = 0x40;
    /// Actuate Sensor until light blinks to transition the device to ActiveMode
    pub const ACTUATE_SENSOR_LIGHTS_BLINK: u32 = 0x80;
    /// Press Reset Button to transition the device to ActiveMode
    pub const RESET_BUTTON: u32 = 0x100;
    /// Press Reset Button until light blinks to transition the device to ActiveMode
    pub const RESET_BUTTON_LIGHTS_BLINK: u32 = 0x200;
    /// Press Reset Button for N seconds to transition the device to ActiveMode
    pub const RESET_BUTTON_SECONDS: u32 = 0x400;
    /// Press Reset Button N times to transition the device to ActiveMode
    pub const RESET_BUTTON_TIMES: u32 = 0x800;
    /// Press Setup Button to transition the device to ActiveMode
    pub const SETUP_BUTTON: u32 = 0x1000;
    /// Press Setup Button for N seconds to transition the device to ActiveMode
    pub const SETUP_BUTTON_SECONDS: u32 = 0x2000;
    /// Press Setup Button until light blinks to transition the device to ActiveMode
    pub const SETUP_BUTTON_LIGHTS_BLINK: u32 = 0x4000;
    /// Press Setup Button N times to transition the device to ActiveMode
    pub const SETUP_BUTTON_TIMES: u32 = 0x8000;
    /// Press the N Button to transition the device to ActiveMode
    pub const APP_DEFINED_BUTTON: u32 = 0x10000;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct MonitoringRegistration {
    pub check_in_node_id: Option<u64>,
    pub monitored_subject: Option<u64>,
    pub key: Option<u8>,
    pub client_type: Option<ClientType>,
}

// Command encoders

/// Encode RegisterClient command (0x00)
pub fn encode_register_client(check_in_node_id: u64, monitored_subject: u64, key: Vec<u8>, verification_key: Vec<u8>, client_type: ClientType) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(check_in_node_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt64(monitored_subject)).into(),
        (2, tlv::TlvItemValueEnc::OctetString(key)).into(),
        (3, tlv::TlvItemValueEnc::OctetString(verification_key)).into(),
        (4, tlv::TlvItemValueEnc::UInt8(client_type.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode UnregisterClient command (0x02)
pub fn encode_unregister_client(check_in_node_id: u64, verification_key: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(check_in_node_id)).into(),
        (1, tlv::TlvItemValueEnc::OctetString(verification_key)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode StayActiveRequest command (0x03)
pub fn encode_stay_active_request(stay_active_duration: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(stay_active_duration)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode IdleModeDuration attribute (0x0000)
pub fn decode_idle_mode_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u32)
    } else {
        Err(anyhow::anyhow!("Expected UInt32"))
    }
}

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

/// Decode ActiveModeThreshold attribute (0x0002)
pub fn decode_active_mode_threshold(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode RegisteredClients attribute (0x0003)
pub fn decode_registered_clients(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<MonitoringRegistration>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(MonitoringRegistration {
                check_in_node_id: item.get_int(&[1]),
                monitored_subject: item.get_int(&[2]),
                key: item.get_int(&[3]).map(|v| v as u8),
                client_type: item.get_int(&[4]).and_then(|v| ClientType::from_u8(v as u8)),
            });
        }
    }
    Ok(res)
}

/// Decode ICDCounter attribute (0x0004)
pub fn decode_icd_counter(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u32)
    } else {
        Err(anyhow::anyhow!("Expected UInt32"))
    }
}

/// Decode ClientsSupportedPerFabric attribute (0x0005)
pub fn decode_clients_supported_per_fabric(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode UserActiveModeTriggerHint attribute (0x0006)
pub fn decode_user_active_mode_trigger_hint(inp: &tlv::TlvItemValue) -> anyhow::Result<UserActiveModeTrigger> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u32)
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode UserActiveModeTriggerInstruction attribute (0x0007)
pub fn decode_user_active_mode_trigger_instruction(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected String"))
    }
}

/// Decode OperatingMode attribute (0x0008)
pub fn decode_operating_mode(inp: &tlv::TlvItemValue) -> anyhow::Result<OperatingMode> {
    if let tlv::TlvItemValue::Int(v) = inp {
        OperatingMode::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

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


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

    match attribute_id {
        0x0000 => {
            match decode_idle_mode_duration(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_active_mode_duration(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_active_mode_threshold(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_registered_clients(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_icd_counter(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_clients_supported_per_fabric(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_user_active_mode_trigger_hint(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_user_active_mode_trigger_instruction(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_operating_mode(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_maximum_check_in_backoff(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, "IdleModeDuration"),
        (0x0001, "ActiveModeDuration"),
        (0x0002, "ActiveModeThreshold"),
        (0x0003, "RegisteredClients"),
        (0x0004, "ICDCounter"),
        (0x0005, "ClientsSupportedPerFabric"),
        (0x0006, "UserActiveModeTriggerHint"),
        (0x0007, "UserActiveModeTriggerInstruction"),
        (0x0008, "OperatingMode"),
        (0x0009, "MaximumCheckInBackoff"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct RegisterClientResponse {
    pub icd_counter: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct StayActiveResponse {
    pub promised_active_duration: Option<u32>,
}

// Command response decoders

/// Decode RegisterClientResponse command response (01)
pub fn decode_register_client_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RegisterClientResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(RegisterClientResponse {
                icd_counter: item.get_int(&[0]).map(|v| v as u32),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode StayActiveResponse command response (04)
pub fn decode_stay_active_response(inp: &tlv::TlvItemValue) -> anyhow::Result<StayActiveResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(StayActiveResponse {
                promised_active_duration: item.get_int(&[0]).map(|v| v as u32),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}