matter-kit 0.3.0

Matter (CSA smart-home standard) protocol implementation in Rust: no_std, no-alloc, executor-agnostic
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// General Diagnostics — cluster 0x0033.
//
// Regenerate with `cargo xtask clusters --dm <checkout>/data_model/1.6`; `cargo xtask check`
// is the CI gate that keeps this file honest. The XML itself is not vendored here — it
// carries the CSA's own copyright notice and is not redistributable.

//! General Diagnostics (cluster `0x0033`, revision 3).
//!
//! 20 identifiers, 1 feature bits, and the specification's own conformance for
//! every element. `CLUSTER` is the whole table.

#![allow(unused_imports)]

use crate::dm::conformance::{Clause, Condition, Conform, Conformance};
use crate::dm::meta::{EventPriority, Reporting};
use crate::dm::spec::{Attribute, Cluster, Command, Event, Feature};
use crate::dm::{Access, AccessQualities, AttributeQualities, Privilege};
use crate::error::Result;
use crate::im::{AttributeId, ClusterId, CommandId, EventId};
use crate::tlv::{
    ContainerKind, Element, FromTlv, Nullable, Tag, TlvList, TlvReader, TlvWriter, ToTlv, Value,
};

/// The cluster id.
pub const ID: ClusterId = 0x0033;

/// The highest revision the specification's history defines — what `ClusterRevision`
/// must report (Core §7.13.1).
pub const REVISION: u16 = 3;

/// The PICS code, which a certification declaration names the cluster by.
pub const PICS: &str = "DGGEN";

/// The `FeatureMap` bits (Core §7.13.2).
///
/// A feature has conformance of its own: a device may not claim one the
/// specification forbids it alongside another.
pub mod feature {
    /// Support specific testing needs for extended Data Model features
    ///
    /// Code `DMTEST`, bit 0.
    pub const DATA_MODEL_TEST: u32 = 1 << 0;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[Feature {
    bit: 0,
    code: "DMTEST",
    name: "DataModelTest",
    conform: Conform::DESCRIBED,
}];

/// The attribute ids.
pub mod attribute {
    use crate::im::AttributeId;

    /// `NetworkInterfaces`.
    pub const NETWORK_INTERFACES: AttributeId = 0x00;
    /// `RebootCount`.
    pub const REBOOT_COUNT: AttributeId = 0x01;
    /// `UpTime`.
    pub const UP_TIME: AttributeId = 0x02;
    /// `TotalOperationalHours`.
    pub const TOTAL_OPERATIONAL_HOURS: AttributeId = 0x03;
    /// `BootReason`.
    pub const BOOT_REASON: AttributeId = 0x04;
    /// `ActiveHardwareFaults`.
    pub const ACTIVE_HARDWARE_FAULTS: AttributeId = 0x05;
    /// `ActiveRadioFaults`.
    pub const ACTIVE_RADIO_FAULTS: AttributeId = 0x06;
    /// `ActiveNetworkFaults`.
    pub const ACTIVE_NETWORK_FAULTS: AttributeId = 0x07;
    /// `TestEventTriggersEnabled`.
    pub const TEST_EVENT_TRIGGERS_ENABLED: AttributeId = 0x08;
    /// `DoNotUse`.
    pub const DO_NOT_USE: AttributeId = 0x09;
    /// `DeviceLoadStatus`.
    pub const DEVICE_LOAD_STATUS: AttributeId = 0x0A;
}

/// The command ids.
pub mod command {
    use crate::im::CommandId;

    /// `TestEventTrigger`.
    pub const TEST_EVENT_TRIGGER: CommandId = 0x00;
    /// `TimeSnapshot`.
    pub const TIME_SNAPSHOT: CommandId = 0x01;
    /// `TimeSnapshotResponse`.
    pub const TIME_SNAPSHOT_RESPONSE: CommandId = 0x02;
    /// `PayloadTestRequest`.
    pub const PAYLOAD_TEST_REQUEST: CommandId = 0x03;
    /// `PayloadTestResponse`.
    pub const PAYLOAD_TEST_RESPONSE: CommandId = 0x04;
}

/// The event ids.
pub mod event {
    use crate::im::EventId;

    /// `HardwareFaultChange`.
    pub const HARDWARE_FAULT_CHANGE: EventId = 0x00;
    /// `RadioFaultChange`.
    pub const RADIO_FAULT_CHANGE: EventId = 0x01;
    /// `NetworkFaultChange`.
    pub const NETWORK_FAULT_CHANGE: EventId = 0x02;
    /// `BootReason`.
    pub const BOOT_REASON: EventId = 0x03;
}

/// `BootReasonEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum BootReasonEnum {
    /// 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 BootReasonEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Unspecified),
            1 => Some(Self::PowerOnReboot),
            2 => Some(Self::BrownOutReset),
            3 => Some(Self::SoftwareWatchdogReset),
            4 => Some(Self::HardwareWatchdogReset),
            5 => Some(Self::SoftwareUpdateCompleted),
            6 => Some(Self::SoftwareReset),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for BootReasonEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for BootReasonEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `HardwareFaultEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum HardwareFaultEnum {
    /// 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 HardwareFaultEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Unspecified),
            1 => Some(Self::Radio),
            2 => Some(Self::Sensor),
            3 => Some(Self::ResettableOverTemp),
            4 => Some(Self::NonResettableOverTemp),
            5 => Some(Self::PowerSource),
            6 => Some(Self::VisualDisplayFault),
            7 => Some(Self::AudioOutputFault),
            8 => Some(Self::UserInterfaceFault),
            9 => Some(Self::NonVolatileMemoryError),
            10 => Some(Self::TamperDetected),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for HardwareFaultEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for HardwareFaultEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `InterfaceTypeEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum InterfaceTypeEnum {
    /// 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 InterfaceTypeEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Unspecified),
            1 => Some(Self::WiFi),
            2 => Some(Self::Ethernet),
            3 => Some(Self::Cellular),
            4 => Some(Self::Thread),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for InterfaceTypeEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for InterfaceTypeEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `NetworkFaultEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum NetworkFaultEnum {
    /// 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 NetworkFaultEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Unspecified),
            1 => Some(Self::HardwareFailure),
            2 => Some(Self::NetworkJammed),
            3 => Some(Self::ConnectionFailed),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for NetworkFaultEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for NetworkFaultEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `RadioFaultEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum RadioFaultEnum {
    /// 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 RadioFaultEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Unspecified),
            1 => Some(Self::WiFiFault),
            2 => Some(Self::CellularFault),
            3 => Some(Self::ThreadFault),
            4 => Some(Self::NFCFault),
            5 => Some(Self::BLEFault),
            6 => Some(Self::EthernetFault),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for RadioFaultEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for RadioFaultEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `DeviceLoadStruct`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DeviceLoadStruct {
    /// `CurrentSubscriptions`, field 0.
    pub current_subscriptions: u16,
    /// `CurrentSubscriptionsForFabric`, field 1.
    pub current_subscriptions_for_fabric: u16,
    /// `TotalSubscriptionsEstablished`, field 2.
    pub total_subscriptions_established: u32,
    /// `TotalInteractionModelMessagesSent`, field 3.
    pub total_interaction_model_messages_sent: u32,
    /// `TotalInteractionModelMessagesReceived`, field 4.
    pub total_interaction_model_messages_received: u32,
}

impl ToTlv for DeviceLoadStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.current_subscriptions.to_tlv(w, Tag::Context(0))?;
        self.current_subscriptions_for_fabric
            .to_tlv(w, Tag::Context(1))?;
        self.total_subscriptions_established
            .to_tlv(w, Tag::Context(2))?;
        self.total_interaction_model_messages_sent
            .to_tlv(w, Tag::Context(3))?;
        self.total_interaction_model_messages_received
            .to_tlv(w, Tag::Context(4))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for DeviceLoadStruct {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut current_subscriptions = None;
        let mut current_subscriptions_for_fabric = None;
        let mut total_subscriptions_established = None;
        let mut total_interaction_model_messages_sent = None;
        let mut total_interaction_model_messages_received = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => current_subscriptions = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => {
                    current_subscriptions_for_fabric = Some(<u16>::from_tlv(reader, &field)?)
                }
                Some(2) => total_subscriptions_established = Some(<u32>::from_tlv(reader, &field)?),
                Some(3) => {
                    total_interaction_model_messages_sent = Some(<u32>::from_tlv(reader, &field)?)
                }
                Some(4) => {
                    total_interaction_model_messages_received =
                        Some(<u32>::from_tlv(reader, &field)?)
                }
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            current_subscriptions: current_subscriptions
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            current_subscriptions_for_fabric: current_subscriptions_for_fabric
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            total_subscriptions_established: total_subscriptions_established
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            total_interaction_model_messages_sent: total_interaction_model_messages_sent
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            total_interaction_model_messages_received: total_interaction_model_messages_received
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// `NetworkInterface`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NetworkInterface<'a> {
    /// `Name`, field 0.
    pub name: &'a str,
    /// `IsOperational`, field 1.
    pub is_operational: bool,
    /// `OffPremiseServicesReachableIPv4`, field 2.
    pub off_premise_services_reachable_i_pv4: Nullable<bool>,
    /// `OffPremiseServicesReachableIPv6`, field 3.
    pub off_premise_services_reachable_i_pv6: Nullable<bool>,
    /// `HardwareAddress`, field 4.
    pub hardware_address: &'a [u8],
    /// `IPv4Addresses`, field 5.
    pub i_pv4_addresses: TlvList<'a, &'a [u8]>,
    /// `IPv6Addresses`, field 6.
    pub i_pv6_addresses: TlvList<'a, &'a [u8]>,
    /// `Type`, field 7.
    pub type_: InterfaceTypeEnum,
}

impl<'a> ToTlv for NetworkInterface<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.name.to_tlv(w, Tag::Context(0))?;
        self.is_operational.to_tlv(w, Tag::Context(1))?;
        self.off_premise_services_reachable_i_pv4
            .to_tlv(w, Tag::Context(2))?;
        self.off_premise_services_reachable_i_pv6
            .to_tlv(w, Tag::Context(3))?;
        self.hardware_address.to_tlv(w, Tag::Context(4))?;
        self.i_pv4_addresses.to_tlv(w, Tag::Context(5))?;
        self.i_pv6_addresses.to_tlv(w, Tag::Context(6))?;
        self.type_.to_tlv(w, Tag::Context(7))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for NetworkInterface<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut name = None;
        let mut is_operational = None;
        let mut off_premise_services_reachable_i_pv4 = None;
        let mut off_premise_services_reachable_i_pv6 = None;
        let mut hardware_address = None;
        let mut i_pv4_addresses = None;
        let mut i_pv6_addresses = None;
        let mut type_ = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => name = Some(<&'a str>::from_tlv(reader, &field)?),
                Some(1) => is_operational = Some(<bool>::from_tlv(reader, &field)?),
                Some(2) => {
                    off_premise_services_reachable_i_pv4 =
                        Some(<Nullable<bool>>::from_tlv(reader, &field)?)
                }
                Some(3) => {
                    off_premise_services_reachable_i_pv6 =
                        Some(<Nullable<bool>>::from_tlv(reader, &field)?)
                }
                Some(4) => hardware_address = Some(<&'a [u8]>::from_tlv(reader, &field)?),
                Some(5) => {
                    i_pv4_addresses = Some(<TlvList<'a, &'a [u8]>>::from_tlv(reader, &field)?)
                }
                Some(6) => {
                    i_pv6_addresses = Some(<TlvList<'a, &'a [u8]>>::from_tlv(reader, &field)?)
                }
                Some(7) => type_ = Some(<InterfaceTypeEnum>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            name: name.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            is_operational: is_operational
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            off_premise_services_reachable_i_pv4: off_premise_services_reachable_i_pv4
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            off_premise_services_reachable_i_pv6: off_premise_services_reachable_i_pv6
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            hardware_address: hardware_address
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            i_pv4_addresses: i_pv4_addresses
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            i_pv6_addresses: i_pv6_addresses
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            type_: type_.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `TestEventTrigger` (command `0x00`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TestEventTriggerFields<'a> {
    /// `EnableKey`, field 0.
    pub enable_key: &'a [u8],
    /// `EventTrigger`, field 1.
    pub event_trigger: u64,
}

impl<'a> ToTlv for TestEventTriggerFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.enable_key.to_tlv(w, Tag::Context(0))?;
        self.event_trigger.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for TestEventTriggerFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut enable_key = None;
        let mut event_trigger = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => enable_key = Some(<&'a [u8]>::from_tlv(reader, &field)?),
                Some(1) => event_trigger = Some(<u64>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            enable_key: enable_key.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            event_trigger: event_trigger.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `TimeSnapshotResponse` (command `0x02`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TimeSnapshotResponseFields {
    /// `SystemTimeMs`, field 0.
    pub system_time_ms: u64,
    /// `PosixTimeMs`, field 1.
    pub posix_time_ms: Nullable<u64>,
}

impl ToTlv for TimeSnapshotResponseFields {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.system_time_ms.to_tlv(w, Tag::Context(0))?;
        self.posix_time_ms.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for TimeSnapshotResponseFields {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut system_time_ms = None;
        let mut posix_time_ms = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => system_time_ms = Some(<u64>::from_tlv(reader, &field)?),
                Some(1) => posix_time_ms = Some(<Nullable<u64>>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            system_time_ms: system_time_ms
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            posix_time_ms: posix_time_ms.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `PayloadTestRequest` (command `0x03`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PayloadTestRequestFields<'a> {
    /// `EnableKey`, field 0.
    pub enable_key: &'a [u8],
    /// `Value`, field 1.
    pub value: u8,
    /// `Count`, field 2.
    pub count: u16,
}

impl<'a> ToTlv for PayloadTestRequestFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.enable_key.to_tlv(w, Tag::Context(0))?;
        self.value.to_tlv(w, Tag::Context(1))?;
        self.count.to_tlv(w, Tag::Context(2))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for PayloadTestRequestFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut enable_key = None;
        let mut value = None;
        let mut count = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => enable_key = Some(<&'a [u8]>::from_tlv(reader, &field)?),
                Some(1) => value = Some(<u8>::from_tlv(reader, &field)?),
                Some(2) => count = Some(<u16>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            enable_key: enable_key.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            value: value.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            count: count.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `PayloadTestResponse` (command `0x04`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PayloadTestResponseFields<'a> {
    /// `Payload`, field 0.
    pub payload: &'a [u8],
}

impl<'a> ToTlv for PayloadTestResponseFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.payload.to_tlv(w, Tag::Context(0))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for PayloadTestResponseFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut payload = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => payload = Some(<&'a [u8]>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            payload: payload.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "NetworkInterfaces",
        kind: "list[NetworkInterface]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0001,
        name: "RebootCount",
        kind: "uint16",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0002,
        name: "UpTime",
        kind: "uint64",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::ChangesOmitted,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0003,
        name: "TotalOperationalHours",
        kind: "uint32",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::ChangesOmitted,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x0004,
        name: "BootReason",
        kind: "BootReasonEnum",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x0005,
        name: "ActiveHardwareFaults",
        kind: "list[HardwareFaultEnum]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x0006,
        name: "ActiveRadioFaults",
        kind: "list[RadioFaultEnum]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x0007,
        name: "ActiveNetworkFaults",
        kind: "list[NetworkFaultEnum]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x0008,
        name: "TestEventTriggersEnabled",
        kind: "bool",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0009,
        name: "DoNotUse",
        kind: "",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::DISALLOWED,
    },
    Attribute {
        id: 0x000A,
        name: "DeviceLoadStatus",
        kind: "DeviceLoadStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::ChangesOmitted,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Described,
                when: Condition::Named("comparison"),
            }],
        },
    },
];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[
    Command {
        id: 0x00,
        name: "TestEventTrigger",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Manage),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x01,
        name: "TimeSnapshot",
        to_server: true,
        response: Some(0x02),
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x02,
        name: "TimeSnapshotResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x03,
        name: "PayloadTestRequest",
        to_server: true,
        response: Some(0x04),
        access: Access::invoke(Privilege::Manage),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Command {
        id: 0x04,
        name: "PayloadTestResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
];

/// Every event, with its conformance.
pub const EVENTS: &[Event] = &[
    Event {
        id: 0x00,
        name: "HardwareFaultChange",
        priority: EventPriority::Critical,
        access: Access::read_only(Privilege::View),
        conform: Conform::OPTIONAL,
    },
    Event {
        id: 0x01,
        name: "RadioFaultChange",
        priority: EventPriority::Critical,
        access: Access::read_only(Privilege::View),
        conform: Conform::OPTIONAL,
    },
    Event {
        id: 0x02,
        name: "NetworkFaultChange",
        priority: EventPriority::Critical,
        access: Access::read_only(Privilege::View),
        conform: Conform::OPTIONAL,
    },
    Event {
        id: 0x03,
        name: "BootReason",
        priority: EventPriority::Critical,
        access: Access::read_only(Privilege::View),
        conform: Conform::MANDATORY,
    },
];

/// The whole cluster, as the specification defines it.
pub const CLUSTER: Cluster = Cluster {
    id: ID,
    name: "General Diagnostics",
    revision: REVISION,
    pics: "DGGEN",
    derived_from: None,
    features: FEATURES,
    attributes: ATTRIBUTES,
    commands: COMMANDS,
    events: EVENTS,
};