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

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


// Bitmap definitions

/// CopyMode bitmap type
pub type CopyMode = u8;

/// Constants for CopyMode
pub mod copymode {
    /// Copy all scenes in the scene table
    pub const COPY_ALL_SCENES: u8 = 0x01;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct AttributeValuePair {
    pub attribute_id: Option<u32>,
    pub value_unsigned8: Option<u8>,
    pub value_signed8: Option<i8>,
    pub value_unsigned16: Option<u16>,
    pub value_signed16: Option<i16>,
    pub value_unsigned32: Option<u32>,
    pub value_signed32: Option<i32>,
    pub value_unsigned64: Option<u64>,
    pub value_signed64: Option<i64>,
}

#[derive(Debug, serde::Serialize)]
pub struct ExtensionFieldSet {
    pub cluster_id: Option<u32>,
    pub attribute_value_list: Option<Vec<AttributeValuePair>>,
}

#[derive(Debug, serde::Serialize)]
pub struct SceneInfo {
    pub scene_count: Option<u8>,
    pub current_scene: Option<u8>,
    pub current_group: Option<u8>,
    pub scene_valid: Option<bool>,
    pub remaining_capacity: Option<u8>,
}

// Command encoders

/// Encode AddScene command (0x00)
pub fn encode_add_scene(group_id: u8, scene_id: u8, transition_time: u32, scene_name: String, extension_field_set_structs: Vec<ExtensionFieldSet>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(scene_id)).into(),
        (2, tlv::TlvItemValueEnc::UInt32(transition_time)).into(),
        (3, tlv::TlvItemValueEnc::String(scene_name)).into(),
        (4, tlv::TlvItemValueEnc::Array(extension_field_set_structs.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.cluster_id { fields.push((0, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                    if let Some(listv) = v.attribute_value_list {
                        let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
                            let mut nested_fields = Vec::new();
                                if let Some(x) = inner.attribute_id { nested_fields.push((0, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                                if let Some(x) = inner.value_unsigned8 { nested_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
                                if let Some(x) = inner.value_signed8 { nested_fields.push((2, tlv::TlvItemValueEnc::Int8(x)).into()); }
                                if let Some(x) = inner.value_unsigned16 { nested_fields.push((3, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                                if let Some(x) = inner.value_signed16 { nested_fields.push((4, tlv::TlvItemValueEnc::Int16(x)).into()); }
                                if let Some(x) = inner.value_unsigned32 { nested_fields.push((5, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                                if let Some(x) = inner.value_signed32 { nested_fields.push((6, tlv::TlvItemValueEnc::Int32(x)).into()); }
                                if let Some(x) = inner.value_unsigned64 { nested_fields.push((7, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                                if let Some(x) = inner.value_signed64 { nested_fields.push((8, tlv::TlvItemValueEnc::Int64(x)).into()); }
                            (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
                        }).collect();
                        fields.push((1, tlv::TlvItemValueEnc::Array(inner_vec)).into());
                    }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ViewScene command (0x01)
pub fn encode_view_scene(group_id: u8, scene_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(scene_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveScene command (0x02)
pub fn encode_remove_scene(group_id: u8, scene_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(scene_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

/// Encode StoreScene command (0x04)
pub fn encode_store_scene(group_id: u8, scene_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(scene_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RecallScene command (0x05)
pub fn encode_recall_scene(group_id: u8, scene_id: u8, transition_time: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(scene_id)).into(),
        (2, tlv::TlvItemValueEnc::UInt32(transition_time.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode GetSceneMembership command (0x06)
pub fn encode_get_scene_membership(group_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(group_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode CopyScene command (0x40)
pub fn encode_copy_scene(mode: CopyMode, group_identifier_from: u8, scene_identifier_from: u8, group_identifier_to: u8, scene_identifier_to: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(mode)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(group_identifier_from)).into(),
        (2, tlv::TlvItemValueEnc::UInt8(scene_identifier_from)).into(),
        (3, tlv::TlvItemValueEnc::UInt8(group_identifier_to)).into(),
        (4, tlv::TlvItemValueEnc::UInt8(scene_identifier_to)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

/// Decode FabricSceneInfo attribute (0x0002)
pub fn decode_fabric_scene_info(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<SceneInfo>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(SceneInfo {
                scene_count: item.get_int(&[0]).map(|v| v as u8),
                current_scene: item.get_int(&[1]).map(|v| v as u8),
                current_group: item.get_int(&[2]).map(|v| v as u8),
                scene_valid: item.get_bool(&[3]),
                remaining_capacity: item.get_int(&[4]).map(|v| v as u8),
            });
        }
    }
    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 != 0x0062 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0062, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_do_not_use(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_scene_table_size(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_fabric_scene_info(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, "DoNotUse"),
        (0x0001, "SceneTableSize"),
        (0x0002, "FabricSceneInfo"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct AddSceneResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
    pub scene_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct ViewSceneResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
    pub scene_id: Option<u8>,
    pub transition_time: Option<u32>,
    pub scene_name: Option<String>,
    pub extension_field_set_structs: Option<Vec<ExtensionFieldSet>>,
}

#[derive(Debug, serde::Serialize)]
pub struct RemoveSceneResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
    pub scene_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct RemoveAllScenesResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct StoreSceneResponse {
    pub status: Option<u8>,
    pub group_id: Option<u8>,
    pub scene_id: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct GetSceneMembershipResponse {
    pub status: Option<u8>,
    pub capacity: Option<u8>,
    pub group_id: Option<u8>,
    pub scene_list: Option<Vec<u8>>,
}

#[derive(Debug, serde::Serialize)]
pub struct CopySceneResponse {
    pub status: Option<u8>,
    pub group_identifier_from: Option<u8>,
    pub scene_identifier_from: Option<u8>,
}

// Command response decoders

/// Decode AddSceneResponse command response (00)
pub fn decode_add_scene_response(inp: &tlv::TlvItemValue) -> anyhow::Result<AddSceneResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(AddSceneResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_id: item.get_int(&[1]).map(|v| v as u8),
                scene_id: item.get_int(&[2]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ViewSceneResponse command response (01)
pub fn decode_view_scene_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ViewSceneResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ViewSceneResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_id: item.get_int(&[1]).map(|v| v as u8),
                scene_id: item.get_int(&[2]).map(|v| v as u8),
                transition_time: item.get_int(&[3]).map(|v| v as u32),
                scene_name: item.get_string_owned(&[4]),
                extension_field_set_structs: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[5]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(ExtensionFieldSet {
                cluster_id: list_item.get_int(&[0]).map(|v| v as u32),
                attribute_value_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[1]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(AttributeValuePair {
                attribute_id: list_item.get_int(&[0]).map(|v| v as u32),
                value_unsigned8: list_item.get_int(&[1]).map(|v| v as u8),
                value_signed8: list_item.get_int(&[2]).map(|v| v as i8),
                value_unsigned16: list_item.get_int(&[3]).map(|v| v as u16),
                value_signed16: list_item.get_int(&[4]).map(|v| v as i16),
                value_unsigned32: list_item.get_int(&[5]).map(|v| v as u32),
                value_signed32: list_item.get_int(&[6]).map(|v| v as i32),
                value_unsigned64: list_item.get_int(&[7]),
                value_signed64: list_item.get_int(&[8]).map(|v| v as i64),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode RemoveSceneResponse command response (02)
pub fn decode_remove_scene_response(inp: &tlv::TlvItemValue) -> anyhow::Result<RemoveSceneResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(RemoveSceneResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_id: item.get_int(&[1]).map(|v| v as u8),
                scene_id: item.get_int(&[2]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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

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

/// Decode GetSceneMembershipResponse command response (06)
pub fn decode_get_scene_membership_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetSceneMembershipResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(GetSceneMembershipResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                capacity: item.get_int(&[1]).map(|v| v as u8),
                group_id: item.get_int(&[2]).map(|v| v as u8),
                scene_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[3]) {
                        let items: Vec<u8> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode CopySceneResponse command response (40)
pub fn decode_copy_scene_response(inp: &tlv::TlvItemValue) -> anyhow::Result<CopySceneResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(CopySceneResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                group_identifier_from: item.get_int(&[1]).map(|v| v as u8),
                scene_identifier_from: item.get_int(&[2]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}