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
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// General Commissioning — cluster 0x0030.
//
// 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 Commissioning (cluster `0x0030`, revision 2).
//!
//! 21 identifiers, 2 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 = 0x0030;

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

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

/// 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 {
    /// Supports Terms & Conditions acknowledgement
    ///
    /// Code `TC`, bit 0.
    pub const TERMS_AND_CONDITIONS: u32 = 1 << 0;
    /// Supports Network Recovery
    ///
    /// Code `NR`, bit 1.
    pub const NETWORK_RECOVERY: u32 = 1 << 1;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[
    Feature {
        bit: 0,
        code: "TC",
        name: "TermsAndConditions",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 1,
        code: "NR",
        name: "NetworkRecovery",
        conform: Conform {
            clauses: &[
                Clause {
                    verdict: Conformance::Provisional,
                    when: Condition::Always,
                },
                Clause {
                    verdict: Conformance::Optional,
                    when: Condition::Always,
                },
            ],
        },
    },
];

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

    /// `Breadcrumb`.
    pub const BREADCRUMB: AttributeId = 0x00;
    /// `BasicCommissioningInfo`.
    pub const BASIC_COMMISSIONING_INFO: AttributeId = 0x01;
    /// `RegulatoryConfig`.
    pub const REGULATORY_CONFIG: AttributeId = 0x02;
    /// `LocationCapability`.
    pub const LOCATION_CAPABILITY: AttributeId = 0x03;
    /// `SupportsConcurrentConnection`.
    pub const SUPPORTS_CONCURRENT_CONNECTION: AttributeId = 0x04;
    /// `TCAcceptedVersion`.
    pub const TC_ACCEPTED_VERSION: AttributeId = 0x05;
    /// `TCMinRequiredVersion`.
    pub const TC_MIN_REQUIRED_VERSION: AttributeId = 0x06;
    /// `TCAcknowledgements`.
    pub const TC_ACKNOWLEDGEMENTS: AttributeId = 0x07;
    /// `TCAcknowledgementsRequired`.
    pub const TC_ACKNOWLEDGEMENTS_REQUIRED: AttributeId = 0x08;
    /// `TCUpdateDeadline`.
    pub const TC_UPDATE_DEADLINE: AttributeId = 0x09;
    /// `RecoveryIdentifier`.
    pub const RECOVERY_IDENTIFIER: AttributeId = 0x0A;
    /// `NetworkRecoveryReason`.
    pub const NETWORK_RECOVERY_REASON: AttributeId = 0x0B;
    /// `IsCommissioningWithoutPower`.
    pub const IS_COMMISSIONING_WITHOUT_POWER: AttributeId = 0x0C;
}

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

    /// `ArmFailSafe`.
    pub const ARM_FAIL_SAFE: CommandId = 0x00;
    /// `ArmFailSafeResponse`.
    pub const ARM_FAIL_SAFE_RESPONSE: CommandId = 0x01;
    /// `SetRegulatoryConfig`.
    pub const SET_REGULATORY_CONFIG: CommandId = 0x02;
    /// `SetRegulatoryConfigResponse`.
    pub const SET_REGULATORY_CONFIG_RESPONSE: CommandId = 0x03;
    /// `CommissioningComplete`.
    pub const COMMISSIONING_COMPLETE: CommandId = 0x04;
    /// `CommissioningCompleteResponse`.
    pub const COMMISSIONING_COMPLETE_RESPONSE: CommandId = 0x05;
    /// `SetTCAcknowledgements`.
    pub const SET_TC_ACKNOWLEDGEMENTS: CommandId = 0x06;
    /// `SetTCAcknowledgementsResponse`.
    pub const SET_TC_ACKNOWLEDGEMENTS_RESPONSE: CommandId = 0x07;
}

/// `CommissioningErrorEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum CommissioningErrorEnum {
    /// No error
    OK = 0,
    /// Attempting to set regulatory configuration to a region or indoor/outdoor mode for which the server does not have proper configuration.
    ValueOutsideRange = 1,
    /// Executed CommissioningComplete outside CASE session.
    InvalidAuthentication = 2,
    /// Executed CommissioningComplete when there was no active Fail-Safe context.
    NoFailSafe = 3,
    /// Attempting to arm fail-safe or execute CommissioningComplete from a fabric different than the one associated with the current fail-safe context.
    BusyWithOtherAdmin = 4,
    /// One or more required TC features from the Enhanced Setup Flow were not accepted.
    RequiredTCNotAccepted = 5,
    /// TCAcknowledgementsNotReceived No or insufficient acknowledgements from the user for the TC features were received.
    TCAcknowledgementsNotReceived = 6,
    /// TCMinVersionNotMet The version of the TC features acknowledged by the user did not meet the minimum required version.
    TCMinVersionNotMet = 7,
}

impl CommissioningErrorEnum {
    /// 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::OK),
            1 => Some(Self::ValueOutsideRange),
            2 => Some(Self::InvalidAuthentication),
            3 => Some(Self::NoFailSafe),
            4 => Some(Self::BusyWithOtherAdmin),
            5 => Some(Self::RequiredTCNotAccepted),
            6 => Some(Self::TCAcknowledgementsNotReceived),
            7 => Some(Self::TCMinVersionNotMet),
            _ => None,
        }
    }

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

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

impl<'a> FromTlv<'a> for CommissioningErrorEnum {
    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))
    }
}

/// `NetworkRecoveryReasonEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum NetworkRecoveryReasonEnum {
    /// Unspecified / unknown reason of network failure
    Unspecified = 0,
    /// Credentials for the configured operational network are not valid
    Auth = 1,
    /// Configured network cannot be found (e.g. the device cannot see the configured Wi-Fi SSID, Thread end-node is unable to find a parent router on the PAN)
    Visibility = 2,
}

impl NetworkRecoveryReasonEnum {
    /// 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::Auth),
            2 => Some(Self::Visibility),
            _ => None,
        }
    }

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

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

impl<'a> FromTlv<'a> for NetworkRecoveryReasonEnum {
    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))
    }
}

/// `RegulatoryLocationTypeEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum RegulatoryLocationTypeEnum {
    /// Indoor only
    Indoor = 0,
    /// Outdoor only
    Outdoor = 1,
    /// Indoor/Outdoor
    IndoorOutdoor = 2,
}

impl RegulatoryLocationTypeEnum {
    /// 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::Indoor),
            1 => Some(Self::Outdoor),
            2 => Some(Self::IndoorOutdoor),
            _ => None,
        }
    }

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

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

impl<'a> FromTlv<'a> for RegulatoryLocationTypeEnum {
    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))
    }
}

/// `BasicCommissioningInfo`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BasicCommissioningInfo {
    /// `FailSafeExpiryLengthSeconds`, field 0.
    pub fail_safe_expiry_length_seconds: u16,
    /// `MaxCumulativeFailsafeSeconds`, field 1.
    pub max_cumulative_failsafe_seconds: u16,
}

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

impl<'a> FromTlv<'a> for BasicCommissioningInfo {
    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 fail_safe_expiry_length_seconds = None;
        let mut max_cumulative_failsafe_seconds = 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) => fail_safe_expiry_length_seconds = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => max_cumulative_failsafe_seconds = 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 {
            fail_safe_expiry_length_seconds: fail_safe_expiry_length_seconds
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            max_cumulative_failsafe_seconds: max_cumulative_failsafe_seconds
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `ArmFailSafe` (command `0x00`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ArmFailSafeFields {
    /// `ExpiryLengthSeconds`, field 0.
    pub expiry_length_seconds: u16,
    /// `Breadcrumb`, field 1.
    pub breadcrumb: u64,
}

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

impl<'a> FromTlv<'a> for ArmFailSafeFields {
    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 expiry_length_seconds = None;
        let mut breadcrumb = 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) => expiry_length_seconds = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => breadcrumb = 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 {
            expiry_length_seconds: expiry_length_seconds
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            breadcrumb: breadcrumb.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `ArmFailSafeResponse` (command `0x01`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ArmFailSafeResponseFields<'a> {
    /// `ErrorCode`, field 0.
    pub error_code: CommissioningErrorEnum,
    /// `DebugText`, field 1.
    pub debug_text: &'a str,
}

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

impl<'a> FromTlv<'a> for ArmFailSafeResponseFields<'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 error_code = None;
        let mut debug_text = 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) => error_code = Some(<CommissioningErrorEnum>::from_tlv(reader, &field)?),
                Some(1) => debug_text = Some(<&'a str>::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 {
            error_code: error_code.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            debug_text: debug_text.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `SetRegulatoryConfig` (command `0x02`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SetRegulatoryConfigFields<'a> {
    /// `NewRegulatoryConfig`, field 0.
    pub new_regulatory_config: RegulatoryLocationTypeEnum,
    /// `CountryCode`, field 1.
    pub country_code: &'a str,
    /// `Breadcrumb`, field 2.
    pub breadcrumb: u64,
}

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

impl<'a> FromTlv<'a> for SetRegulatoryConfigFields<'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 new_regulatory_config = None;
        let mut country_code = None;
        let mut breadcrumb = 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) => {
                    new_regulatory_config =
                        Some(<RegulatoryLocationTypeEnum>::from_tlv(reader, &field)?)
                }
                Some(1) => country_code = Some(<&'a str>::from_tlv(reader, &field)?),
                Some(2) => breadcrumb = 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 {
            new_regulatory_config: new_regulatory_config
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            country_code: country_code.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            breadcrumb: breadcrumb.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `SetRegulatoryConfigResponse` (command `0x03`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SetRegulatoryConfigResponseFields<'a> {
    /// `ErrorCode`, field 0.
    pub error_code: CommissioningErrorEnum,
    /// `DebugText`, field 1.
    pub debug_text: &'a str,
}

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

impl<'a> FromTlv<'a> for SetRegulatoryConfigResponseFields<'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 error_code = None;
        let mut debug_text = 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) => error_code = Some(<CommissioningErrorEnum>::from_tlv(reader, &field)?),
                Some(1) => debug_text = Some(<&'a str>::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 {
            error_code: error_code.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            debug_text: debug_text.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `CommissioningCompleteResponse` (command `0x05`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CommissioningCompleteResponseFields<'a> {
    /// `ErrorCode`, field 0.
    pub error_code: CommissioningErrorEnum,
    /// `DebugText`, field 1.
    pub debug_text: &'a str,
}

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

impl<'a> FromTlv<'a> for CommissioningCompleteResponseFields<'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 error_code = None;
        let mut debug_text = 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) => error_code = Some(<CommissioningErrorEnum>::from_tlv(reader, &field)?),
                Some(1) => debug_text = Some(<&'a str>::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 {
            error_code: error_code.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            debug_text: debug_text.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `SetTCAcknowledgements` (command `0x06`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SetTCAcknowledgementsFields {
    /// `TCVersion`, field 0.
    pub tc_version: u16,
    /// `TCUserResponse`, field 1.
    pub tc_user_response: u16,
}

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

impl<'a> FromTlv<'a> for SetTCAcknowledgementsFields {
    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 tc_version = None;
        let mut tc_user_response = 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) => tc_version = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => tc_user_response = 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 {
            tc_version: tc_version.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            tc_user_response: tc_user_response
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `SetTCAcknowledgementsResponse` (command `0x07`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SetTCAcknowledgementsResponseFields {
    /// `ErrorCode`, field 0.
    pub error_code: CommissioningErrorEnum,
}

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

impl<'a> FromTlv<'a> for SetTCAcknowledgementsResponseFields {
    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 error_code = 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) => error_code = Some(<CommissioningErrorEnum>::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 {
            error_code: error_code.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "Breadcrumb",
        kind: "uint64",
        access: Access::read_write_with(Privilege::View, Privilege::Administer),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0001,
        name: "BasicCommissioningInfo",
        kind: "BasicCommissioningInfo",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0002,
        name: "RegulatoryConfig",
        kind: "RegulatoryLocationTypeEnum",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0003,
        name: "LocationCapability",
        kind: "RegulatoryLocationTypeEnum",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0004,
        name: "SupportsConcurrentConnection",
        kind: "bool",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0005,
        name: "TCAcceptedVersion",
        kind: "uint16",
        access: Access::read_only(Privilege::Administer),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0006,
        name: "TCMinRequiredVersion",
        kind: "uint16",
        access: Access::read_only(Privilege::Administer),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0007,
        name: "TCAcknowledgements",
        kind: "map16",
        access: Access::read_only(Privilege::Administer),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0008,
        name: "TCAcknowledgementsRequired",
        kind: "bool",
        access: Access::read_only(Privilege::Administer),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0009,
        name: "TCUpdateDeadline",
        kind: "uint32",
        access: Access::read_only(Privilege::Administer),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x000A,
        name: "RecoveryIdentifier",
        kind: "octstr",
        access: Access::read_only(Privilege::Manage),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[
                Clause {
                    verdict: Conformance::Provisional,
                    when: Condition::Always,
                },
                Clause {
                    verdict: Conformance::Mandatory,
                    when: Condition::Feature(1),
                },
            ],
        },
    },
    Attribute {
        id: 0x000B,
        name: "NetworkRecoveryReason",
        kind: "NetworkRecoveryReasonEnum",
        access: Access::read_only(Privilege::Manage),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[
                Clause {
                    verdict: Conformance::Provisional,
                    when: Condition::Always,
                },
                Clause {
                    verdict: Conformance::Mandatory,
                    when: Condition::Feature(1),
                },
            ],
        },
    },
    Attribute {
        id: 0x000C,
        name: "IsCommissioningWithoutPower",
        kind: "bool",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[
                Clause {
                    verdict: Conformance::Provisional,
                    when: Condition::Always,
                },
                Clause {
                    verdict: Conformance::Optional,
                    when: Condition::Always,
                },
            ],
        },
    },
];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[
    Command {
        id: 0x00,
        name: "ArmFailSafe",
        to_server: true,
        response: Some(0x01),
        access: Access::invoke(Privilege::Administer),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x01,
        name: "ArmFailSafeResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x02,
        name: "SetRegulatoryConfig",
        to_server: true,
        response: Some(0x03),
        access: Access::invoke(Privilege::Administer),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x03,
        name: "SetRegulatoryConfigResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x04,
        name: "CommissioningComplete",
        to_server: true,
        response: Some(0x05),
        access: Access::invoke(Privilege::Administer)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x05,
        name: "CommissioningCompleteResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x06,
        name: "SetTCAcknowledgements",
        to_server: true,
        response: Some(0x07),
        access: Access::invoke(Privilege::Administer),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Command {
        id: 0x07,
        name: "SetTCAcknowledgementsResponse",
        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] = &[];

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