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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Matter TLV encoders and decoders for General Diagnostics Cluster
//! Cluster ID: 0x0033
//!
//! This file is automatically generated from DiagnosticsGeneral.xml

#![allow(clippy::too_many_arguments)]

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


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum BootReason {
    /// The Node is unable to identify the Power-On reason as one of the other provided enumeration values.
    Unspecified = 0,
    /// The Node has booted as the result of physical interaction with the device resulting in a reboot.
    Poweronreboot = 1,
    /// The Node has rebooted as the result of a brown-out of the Node's power supply.
    Brownoutreset = 2,
    /// The Node has rebooted as the result of a software watchdog timer.
    Softwarewatchdogreset = 3,
    /// The Node has rebooted as the result of a hardware watchdog timer.
    Hardwarewatchdogreset = 4,
    /// The Node has rebooted as the result of a completed software update.
    Softwareupdatecompleted = 5,
    /// The Node has rebooted as the result of a software initiated reboot.
    Softwarereset = 6,
}

impl BootReason {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(BootReason::Unspecified),
            1 => Some(BootReason::Poweronreboot),
            2 => Some(BootReason::Brownoutreset),
            3 => Some(BootReason::Softwarewatchdogreset),
            4 => Some(BootReason::Hardwarewatchdogreset),
            5 => Some(BootReason::Softwareupdatecompleted),
            6 => Some(BootReason::Softwarereset),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum HardwareFault {
    /// The Node has encountered an unspecified fault.
    Unspecified = 0,
    /// The Node has encountered a fault with at least one of its radios.
    Radio = 1,
    /// The Node has encountered a fault with at least one of its sensors.
    Sensor = 2,
    /// The Node has encountered an over-temperature fault that is resettable.
    Resettableovertemp = 3,
    /// The Node has encountered an over-temperature fault that is not resettable.
    Nonresettableovertemp = 4,
    /// The Node has encountered a fault with at least one of its power sources.
    Powersource = 5,
    /// The Node has encountered a fault with at least one of its visual displays.
    Visualdisplayfault = 6,
    /// The Node has encountered a fault with at least one of its audio outputs.
    Audiooutputfault = 7,
    /// The Node has encountered a fault with at least one of its user interfaces.
    Userinterfacefault = 8,
    /// The Node has encountered a fault with its non-volatile memory.
    Nonvolatilememoryerror = 9,
    /// The Node has encountered disallowed physical tampering.
    Tamperdetected = 10,
}

impl HardwareFault {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(HardwareFault::Unspecified),
            1 => Some(HardwareFault::Radio),
            2 => Some(HardwareFault::Sensor),
            3 => Some(HardwareFault::Resettableovertemp),
            4 => Some(HardwareFault::Nonresettableovertemp),
            5 => Some(HardwareFault::Powersource),
            6 => Some(HardwareFault::Visualdisplayfault),
            7 => Some(HardwareFault::Audiooutputfault),
            8 => Some(HardwareFault::Userinterfacefault),
            9 => Some(HardwareFault::Nonvolatilememoryerror),
            10 => Some(HardwareFault::Tamperdetected),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum InterfaceType {
    /// Indicates an interface of an unspecified type.
    Unspecified = 0,
    /// Indicates a Wi-Fi interface.
    Wifi = 1,
    /// Indicates a Ethernet interface.
    Ethernet = 2,
    /// Indicates a Cellular interface.
    Cellular = 3,
    /// Indicates a Thread interface.
    Thread = 4,
}

impl InterfaceType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(InterfaceType::Unspecified),
            1 => Some(InterfaceType::Wifi),
            2 => Some(InterfaceType::Ethernet),
            3 => Some(InterfaceType::Cellular),
            4 => Some(InterfaceType::Thread),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum NetworkFault {
    /// The Node has encountered an unspecified fault.
    Unspecified = 0,
    /// The Node has encountered a network fault as a result of a hardware failure.
    Hardwarefailure = 1,
    /// The Node has encountered a network fault as a result of a jammed network.
    Networkjammed = 2,
    /// The Node has encountered a network fault as a result of a failure to establish a connection.
    Connectionfailed = 3,
}

impl NetworkFault {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(NetworkFault::Unspecified),
            1 => Some(NetworkFault::Hardwarefailure),
            2 => Some(NetworkFault::Networkjammed),
            3 => Some(NetworkFault::Connectionfailed),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum RadioFault {
    /// The Node has encountered an unspecified radio fault.
    Unspecified = 0,
    /// The Node has encountered a fault with its Wi-Fi radio.
    Wififault = 1,
    /// The Node has encountered a fault with its cellular radio.
    Cellularfault = 2,
    /// The Node has encountered a fault with its 802.15.4 radio.
    Threadfault = 3,
    /// The Node has encountered a fault with its NFC radio.
    Nfcfault = 4,
    /// The Node has encountered a fault with its BLE radio.
    Blefault = 5,
    /// The Node has encountered a fault with its Ethernet controller.
    Ethernetfault = 6,
}

impl RadioFault {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(RadioFault::Unspecified),
            1 => Some(RadioFault::Wififault),
            2 => Some(RadioFault::Cellularfault),
            3 => Some(RadioFault::Threadfault),
            4 => Some(RadioFault::Nfcfault),
            5 => Some(RadioFault::Blefault),
            6 => Some(RadioFault::Ethernetfault),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct NetworkInterface {
    pub name: Option<String>,
    pub is_operational: Option<bool>,
    pub off_premise_services_reachable_i_pv4: Option<bool>,
    pub off_premise_services_reachable_i_pv6: Option<bool>,
    pub hardware_address: Option<u8>,
    pub i_pv4_addresses: Option<Vec<u8>>,
    pub i_pv6_addresses: Option<Vec<u8>>,
    pub type_: Option<InterfaceType>,
}

// Command encoders

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

/// Encode PayloadTestRequest command (0x03)
pub fn encode_payload_test_request(enable_key: Vec<u8>, value: u8, count: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(enable_key)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(value)).into(),
        (2, tlv::TlvItemValueEnc::UInt16(count)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode NetworkInterfaces attribute (0x0000)
pub fn decode_network_interfaces(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<NetworkInterface>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(NetworkInterface {
                name: item.get_string_owned(&[0]),
                is_operational: item.get_bool(&[1]),
                off_premise_services_reachable_i_pv4: item.get_bool(&[2]),
                off_premise_services_reachable_i_pv6: item.get_bool(&[3]),
                hardware_address: item.get_int(&[4]).map(|v| v as u8),
                i_pv4_addresses: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[5]) {
                        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
                    }
                },
                i_pv6_addresses: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[6]) {
                        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
                    }
                },
                type_: item.get_int(&[7]).and_then(|v| InterfaceType::from_u8(v as u8)),
            });
        }
    }
    Ok(res)
}

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

/// Decode UpTime attribute (0x0002)
pub fn decode_up_time(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

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

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

/// Decode ActiveHardwareFaults attribute (0x0005)
pub fn decode_active_hardware_faults(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<HardwareFault>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                if let Some(enum_val) = HardwareFault::from_u8(*i as u8) {
                    res.push(enum_val);
                }
            }
        }
    }
    Ok(res)
}

/// Decode ActiveRadioFaults attribute (0x0006)
pub fn decode_active_radio_faults(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<RadioFault>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                if let Some(enum_val) = RadioFault::from_u8(*i as u8) {
                    res.push(enum_val);
                }
            }
        }
    }
    Ok(res)
}

/// Decode ActiveNetworkFaults attribute (0x0007)
pub fn decode_active_network_faults(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<NetworkFault>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                if let Some(enum_val) = NetworkFault::from_u8(*i as u8) {
                    res.push(enum_val);
                }
            }
        }
    }
    Ok(res)
}

/// Decode TestEventTriggersEnabled attribute (0x0008)
pub fn decode_test_event_triggers_enabled(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
    if let tlv::TlvItemValue::Bool(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected Bool"))
    }
}

/// Decode DoNotUse attribute (0x0009)
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"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_network_interfaces(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_reboot_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_up_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_total_operational_hours(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_boot_reason(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_active_hardware_faults(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_active_radio_faults(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_active_network_faults(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_test_event_triggers_enabled(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            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),
            }
        }
        _ => 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, "NetworkInterfaces"),
        (0x0001, "RebootCount"),
        (0x0002, "UpTime"),
        (0x0003, "TotalOperationalHours"),
        (0x0004, "BootReason"),
        (0x0005, "ActiveHardwareFaults"),
        (0x0006, "ActiveRadioFaults"),
        (0x0007, "ActiveNetworkFaults"),
        (0x0008, "TestEventTriggersEnabled"),
        (0x0009, "DoNotUse"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("TestEventTrigger"),
        0x01 => Some("TimeSnapshot"),
        0x03 => Some("PayloadTestRequest"),
        _ => 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: "enable_key", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "event_trigger", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![]),
        0x03 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "enable_key", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "value", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "count", kind: crate::clusters::codec::FieldKind::U16, 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 => {
        let enable_key = crate::clusters::codec::json_util::get_octstr(args, "enable_key")?;
        let event_trigger = crate::clusters::codec::json_util::get_u64(args, "event_trigger")?;
        encode_test_event_trigger(enable_key, event_trigger)
        }
        0x01 => Ok(vec![]),
        0x03 => {
        let enable_key = crate::clusters::codec::json_util::get_octstr(args, "enable_key")?;
        let value = crate::clusters::codec::json_util::get_u8(args, "value")?;
        let count = crate::clusters::codec::json_util::get_u16(args, "count")?;
        encode_payload_test_request(enable_key, value, count)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct TimeSnapshotResponse {
    pub system_time_ms: Option<u8>,
    pub posix_time_ms: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct PayloadTestResponse {
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub payload: Option<Vec<u8>>,
}

// Command response decoders

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

/// Decode PayloadTestResponse command response (04)
pub fn decode_payload_test_response(inp: &tlv::TlvItemValue) -> anyhow::Result<PayloadTestResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(PayloadTestResponse {
                payload: item.get_octet_string_owned(&[0]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `TestEventTrigger` command on cluster `General Diagnostics`.
pub async fn test_event_trigger(conn: &crate::controller::Connection, endpoint: u16, enable_key: Vec<u8>, event_trigger: u64) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_CMD_ID_TESTEVENTTRIGGER, &encode_test_event_trigger(enable_key, event_trigger)?).await?;
    Ok(())
}

/// Invoke `TimeSnapshot` command on cluster `General Diagnostics`.
pub async fn time_snapshot(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TimeSnapshotResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_CMD_ID_TIMESNAPSHOT, &[]).await?;
    decode_time_snapshot_response(&tlv)
}

/// Invoke `PayloadTestRequest` command on cluster `General Diagnostics`.
pub async fn payload_test_request(conn: &crate::controller::Connection, endpoint: u16, enable_key: Vec<u8>, value: u8, count: u16) -> anyhow::Result<PayloadTestResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_CMD_ID_PAYLOADTESTREQUEST, &encode_payload_test_request(enable_key, value, count)?).await?;
    decode_payload_test_response(&tlv)
}

/// Read `NetworkInterfaces` attribute from cluster `General Diagnostics`.
pub async fn read_network_interfaces(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<NetworkInterface>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_NETWORKINTERFACES).await?;
    decode_network_interfaces(&tlv)
}

/// Read `RebootCount` attribute from cluster `General Diagnostics`.
pub async fn read_reboot_count(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_REBOOTCOUNT).await?;
    decode_reboot_count(&tlv)
}

/// Read `UpTime` attribute from cluster `General Diagnostics`.
pub async fn read_up_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_UPTIME).await?;
    decode_up_time(&tlv)
}

/// Read `TotalOperationalHours` attribute from cluster `General Diagnostics`.
pub async fn read_total_operational_hours(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_TOTALOPERATIONALHOURS).await?;
    decode_total_operational_hours(&tlv)
}

/// Read `BootReason` attribute from cluster `General Diagnostics`.
pub async fn read_boot_reason(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<BootReason> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_BOOTREASON).await?;
    decode_boot_reason(&tlv)
}

/// Read `ActiveHardwareFaults` attribute from cluster `General Diagnostics`.
pub async fn read_active_hardware_faults(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<HardwareFault>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_ACTIVEHARDWAREFAULTS).await?;
    decode_active_hardware_faults(&tlv)
}

/// Read `ActiveRadioFaults` attribute from cluster `General Diagnostics`.
pub async fn read_active_radio_faults(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<RadioFault>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_ACTIVERADIOFAULTS).await?;
    decode_active_radio_faults(&tlv)
}

/// Read `ActiveNetworkFaults` attribute from cluster `General Diagnostics`.
pub async fn read_active_network_faults(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<NetworkFault>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_ACTIVENETWORKFAULTS).await?;
    decode_active_network_faults(&tlv)
}

/// Read `TestEventTriggersEnabled` attribute from cluster `General Diagnostics`.
pub async fn read_test_event_triggers_enabled(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_TESTEVENTTRIGGERSENABLED).await?;
    decode_test_event_triggers_enabled(&tlv)
}

/// Read `DoNotUse` attribute from cluster `General Diagnostics`.
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_GENERAL_DIAGNOSTICS, crate::clusters::defs::CLUSTER_GENERAL_DIAGNOSTICS_ATTR_ID_DONOTUSE).await?;
    decode_do_not_use(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct HardwareFaultChangeEvent {
    pub current: Option<Vec<HardwareFault>>,
    pub previous: Option<Vec<HardwareFault>>,
}

#[derive(Debug, serde::Serialize)]
pub struct RadioFaultChangeEvent {
    pub current: Option<Vec<RadioFault>>,
    pub previous: Option<Vec<RadioFault>>,
}

#[derive(Debug, serde::Serialize)]
pub struct NetworkFaultChangeEvent {
    pub current: Option<Vec<NetworkFault>>,
    pub previous: Option<Vec<NetworkFault>>,
}

#[derive(Debug, serde::Serialize)]
pub struct BootReasonEvent {
    pub boot_reason: Option<BootReason>,
}

// Event decoders

/// Decode HardwareFaultChange event (0x00, priority: critical)
pub fn decode_hardware_fault_change_event(inp: &tlv::TlvItemValue) -> anyhow::Result<HardwareFaultChangeEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(HardwareFaultChangeEvent {
                                current: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let items: Vec<HardwareFault> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { HardwareFault::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                                previous: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<HardwareFault> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { HardwareFault::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode RadioFaultChange event (0x01, priority: critical)
pub fn decode_radio_fault_change_event(inp: &tlv::TlvItemValue) -> anyhow::Result<RadioFaultChangeEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(RadioFaultChangeEvent {
                                current: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let items: Vec<RadioFault> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { RadioFault::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                                previous: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<RadioFault> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { RadioFault::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode NetworkFaultChange event (0x02, priority: critical)
pub fn decode_network_fault_change_event(inp: &tlv::TlvItemValue) -> anyhow::Result<NetworkFaultChangeEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(NetworkFaultChangeEvent {
                                current: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let items: Vec<NetworkFault> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { NetworkFault::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                                previous: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<NetworkFault> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { NetworkFault::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode BootReason event (0x03, priority: critical)
pub fn decode_boot_reason_event(inp: &tlv::TlvItemValue) -> anyhow::Result<BootReasonEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(BootReasonEvent {
                                boot_reason: item.get_int(&[0]).and_then(|v| BootReason::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}