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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Matter TLV encoders and decoders for Scenes Management Cluster
//! Cluster ID: 0x0062
//!
//! This file is automatically generated from Scenes.xml

#![allow(clippy::too_many_arguments)]

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"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "AddScene"),
        (0x01, "ViewScene"),
        (0x02, "RemoveScene"),
        (0x03, "RemoveAllScenes"),
        (0x04, "StoreScene"),
        (0x05, "RecallScene"),
        (0x06, "GetSceneMembership"),
        (0x40, "CopyScene"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("AddScene"),
        0x01 => Some("ViewScene"),
        0x02 => Some("RemoveScene"),
        0x03 => Some("RemoveAllScenes"),
        0x04 => Some("StoreScene"),
        0x05 => Some("RecallScene"),
        0x06 => Some("GetSceneMembership"),
        0x40 => Some("CopyScene"),
        _ => 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: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "scene_id", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "transition_time", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "scene_name", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 4, name: "extension_field_set_structs", kind: crate::clusters::codec::FieldKind::List { entry_type: "ExtensionFieldSetStruct" }, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "scene_id", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "scene_id", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
        ]),
        0x03 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "scene_id", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
        ]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "scene_id", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "transition_time", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: true },
        ]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "group_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x40 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "mode", kind: crate::clusters::codec::FieldKind::Bitmap { name: "CopyMode", bits: &[(1, "COPY_ALL_SCENES")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "group_identifier_from", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "scene_identifier_from", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "group_identifier_to", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 4, name: "scene_identifier_to", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => Err(anyhow::anyhow!("command \"AddScene\" has complex args: use raw mode")),
        0x01 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        let scene_id = crate::clusters::codec::json_util::get_u8(args, "scene_id")?;
        encode_view_scene(group_id, scene_id)
        }
        0x02 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        let scene_id = crate::clusters::codec::json_util::get_u8(args, "scene_id")?;
        encode_remove_scene(group_id, scene_id)
        }
        0x03 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        encode_remove_all_scenes(group_id)
        }
        0x04 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        let scene_id = crate::clusters::codec::json_util::get_u8(args, "scene_id")?;
        encode_store_scene(group_id, scene_id)
        }
        0x05 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        let scene_id = crate::clusters::codec::json_util::get_u8(args, "scene_id")?;
        let transition_time = crate::clusters::codec::json_util::get_opt_u32(args, "transition_time")?;
        encode_recall_scene(group_id, scene_id, transition_time)
        }
        0x06 => {
        let group_id = crate::clusters::codec::json_util::get_u8(args, "group_id")?;
        encode_get_scene_membership(group_id)
        }
        0x40 => {
        let mode = crate::clusters::codec::json_util::get_u8(args, "mode")?;
        let group_identifier_from = crate::clusters::codec::json_util::get_u8(args, "group_identifier_from")?;
        let scene_identifier_from = crate::clusters::codec::json_util::get_u8(args, "scene_identifier_from")?;
        let group_identifier_to = crate::clusters::codec::json_util::get_u8(args, "group_identifier_to")?;
        let scene_identifier_to = crate::clusters::codec::json_util::get_u8(args, "scene_identifier_to")?;
        encode_copy_scene(mode, group_identifier_from, scene_identifier_from, group_identifier_to, scene_identifier_to)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[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"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `AddScene` command on cluster `Scenes Management`.
pub async fn add_scene(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, scene_id: u8, transition_time: u32, scene_name: String, extension_field_set_structs: Vec<ExtensionFieldSet>) -> anyhow::Result<AddSceneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_ADDSCENE, &encode_add_scene(group_id, scene_id, transition_time, scene_name, extension_field_set_structs)?).await?;
    decode_add_scene_response(&tlv)
}

/// Invoke `ViewScene` command on cluster `Scenes Management`.
pub async fn view_scene(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, scene_id: u8) -> anyhow::Result<ViewSceneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_VIEWSCENE, &encode_view_scene(group_id, scene_id)?).await?;
    decode_view_scene_response(&tlv)
}

/// Invoke `RemoveScene` command on cluster `Scenes Management`.
pub async fn remove_scene(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, scene_id: u8) -> anyhow::Result<RemoveSceneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_REMOVESCENE, &encode_remove_scene(group_id, scene_id)?).await?;
    decode_remove_scene_response(&tlv)
}

/// Invoke `RemoveAllScenes` command on cluster `Scenes Management`.
pub async fn remove_all_scenes(conn: &crate::controller::Connection, endpoint: u16, group_id: u8) -> anyhow::Result<RemoveAllScenesResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_REMOVEALLSCENES, &encode_remove_all_scenes(group_id)?).await?;
    decode_remove_all_scenes_response(&tlv)
}

/// Invoke `StoreScene` command on cluster `Scenes Management`.
pub async fn store_scene(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, scene_id: u8) -> anyhow::Result<StoreSceneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_STORESCENE, &encode_store_scene(group_id, scene_id)?).await?;
    decode_store_scene_response(&tlv)
}

/// Invoke `RecallScene` command on cluster `Scenes Management`.
pub async fn recall_scene(conn: &crate::controller::Connection, endpoint: u16, group_id: u8, scene_id: u8, transition_time: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_RECALLSCENE, &encode_recall_scene(group_id, scene_id, transition_time)?).await?;
    Ok(())
}

/// Invoke `GetSceneMembership` command on cluster `Scenes Management`.
pub async fn get_scene_membership(conn: &crate::controller::Connection, endpoint: u16, group_id: u8) -> anyhow::Result<GetSceneMembershipResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_GETSCENEMEMBERSHIP, &encode_get_scene_membership(group_id)?).await?;
    decode_get_scene_membership_response(&tlv)
}

/// Invoke `CopyScene` command on cluster `Scenes Management`.
pub async fn copy_scene(conn: &crate::controller::Connection, endpoint: u16, mode: CopyMode, group_identifier_from: u8, scene_identifier_from: u8, group_identifier_to: u8, scene_identifier_to: u8) -> anyhow::Result<CopySceneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_CMD_ID_COPYSCENE, &encode_copy_scene(mode, group_identifier_from, scene_identifier_from, group_identifier_to, scene_identifier_to)?).await?;
    decode_copy_scene_response(&tlv)
}

/// Read `DoNotUse` attribute from cluster `Scenes Management`.
pub async fn read_do_not_use(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_ATTR_ID_DONOTUSE).await?;
    decode_do_not_use(&tlv)
}

/// Read `SceneTableSize` attribute from cluster `Scenes Management`.
pub async fn read_scene_table_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_ATTR_ID_SCENETABLESIZE).await?;
    decode_scene_table_size(&tlv)
}

/// Read `FabricSceneInfo` attribute from cluster `Scenes Management`.
pub async fn read_fabric_scene_info(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<SceneInfo>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SCENES_MANAGEMENT, crate::clusters::defs::CLUSTER_SCENES_MANAGEMENT_ATTR_ID_FABRICSCENEINFO).await?;
    decode_fabric_scene_info(&tlv)
}