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
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// Group Key Management โ€” cluster 0x003F.
//
// 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.

//! Group Key Management (cluster `0x003F`, revision 3).
//!
//! 11 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 = 0x003F;

/// 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 = "GRPKEY";

/// 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 {
    /// The ability to support CacheAndSync security policy and MCSP.
    ///
    /// Code `CS`, bit 0.
    pub const CACHE_AND_SYNC: u32 = 1 << 0;
    /// The device supports groups using the Groupcast cluster.
    ///
    /// Code `GCAST`, bit 1.
    pub const GROUPCAST: u32 = 1 << 1;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[
    Feature {
        bit: 0,
        code: "CS",
        name: "CacheAndSync",
        conform: Conform {
            clauses: &[Clause::always(Conformance::Provisional)],
        },
    },
    Feature {
        bit: 1,
        code: "GCAST",
        name: "Groupcast",
        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;

    /// `GroupKeyMap`.
    pub const GROUP_KEY_MAP: AttributeId = 0x00;
    /// `GroupTable`.
    pub const GROUP_TABLE: AttributeId = 0x01;
    /// `MaxGroupsPerFabric`.
    pub const MAX_GROUPS_PER_FABRIC: AttributeId = 0x02;
    /// `MaxGroupKeysPerFabric`.
    pub const MAX_GROUP_KEYS_PER_FABRIC: AttributeId = 0x03;
    /// `GroupcastAdoption`.
    pub const GROUPCAST_ADOPTION: AttributeId = 0x04;
}

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

    /// `KeySetWrite`.
    pub const KEY_SET_WRITE: CommandId = 0x00;
    /// `KeySetRead`.
    pub const KEY_SET_READ: CommandId = 0x01;
    /// `KeySetReadResponse`.
    pub const KEY_SET_READ_RESPONSE: CommandId = 0x02;
    /// `KeySetRemove`.
    pub const KEY_SET_REMOVE: CommandId = 0x03;
    /// `KeySetReadAllIndices`.
    pub const KEY_SET_READ_ALL_INDICES: CommandId = 0x04;
    /// `KeySetReadAllIndicesResponse`.
    pub const KEY_SET_READ_ALL_INDICES_RESPONSE: CommandId = 0x05;
}

/// `GroupKeyMulticastPolicyEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum GroupKeyMulticastPolicyEnum {
    /// Indicates filtering of multicast messages for a specific Group ID
    PerGroupID = 0,
    /// Indicates not filtering of multicast messages
    AllNodes = 1,
}

impl GroupKeyMulticastPolicyEnum {
    /// 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::PerGroupID),
            1 => Some(Self::AllNodes),
            _ => None,
        }
    }

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

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

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

/// `GroupKeySecurityPolicyEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum GroupKeySecurityPolicyEnum {
    /// Message counter synchronization using trust-first
    TrustFirst = 0,
    /// Message counter synchronization using cache-and-sync
    CacheAndSync = 1,
}

impl GroupKeySecurityPolicyEnum {
    /// 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::TrustFirst),
            1 => Some(Self::CacheAndSync),
            _ => None,
        }
    }

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

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

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

/// `GroupInfoMapStruct`, fabric-scoped โ€” ยง7.19.1.9's `FabricIndex` is field 254.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroupInfoMapStruct<'a> {
    /// `GroupId`, field 1.
    pub group_id: crate::msg::GroupId,
    /// `Endpoints`, field 2.
    pub endpoints: TlvList<'a, u16>,
    /// `GroupName`, field 3.
    pub group_name: Option<&'a str>,
    /// `FabricIndex`, field 254.
    pub fabric_index: crate::msg::FabricIndex,
}

impl<'a> ToTlv for GroupInfoMapStruct<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.group_id.to_tlv(w, Tag::Context(1))?;
        self.endpoints.to_tlv(w, Tag::Context(2))?;
        if let Some(value) = &self.group_name {
            value.to_tlv(w, Tag::Context(3))?;
        }
        self.fabric_index.to_tlv(w, Tag::Context(254))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for GroupInfoMapStruct<'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 group_id = None;
        let mut endpoints = None;
        let mut group_name = None;
        let mut fabric_index = 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(1) => group_id = Some(<crate::msg::GroupId>::from_tlv(reader, &field)?),
                Some(2) => endpoints = Some(<TlvList<'a, u16>>::from_tlv(reader, &field)?),
                Some(3) => group_name = Some(<&'a str>::from_tlv(reader, &field)?),
                Some(254) => {
                    fabric_index = Some(<crate::msg::FabricIndex>::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 {
            group_id: group_id.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            endpoints: endpoints.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            group_name,
            fabric_index: fabric_index.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// `GroupKeyMapStruct`, fabric-scoped โ€” ยง7.19.1.9's `FabricIndex` is field 254.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroupKeyMapStruct {
    /// `GroupId`, field 1.
    pub group_id: crate::msg::GroupId,
    /// `GroupKeySetID`, field 2.
    pub group_key_set_id: u16,
    /// `FabricIndex`, field 254.
    pub fabric_index: crate::msg::FabricIndex,
}

impl ToTlv for GroupKeyMapStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.group_id.to_tlv(w, Tag::Context(1))?;
        self.group_key_set_id.to_tlv(w, Tag::Context(2))?;
        self.fabric_index.to_tlv(w, Tag::Context(254))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for GroupKeyMapStruct {
    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 group_id = None;
        let mut group_key_set_id = None;
        let mut fabric_index = 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(1) => group_id = Some(<crate::msg::GroupId>::from_tlv(reader, &field)?),
                Some(2) => group_key_set_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(254) => {
                    fabric_index = Some(<crate::msg::FabricIndex>::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 {
            group_id: group_id.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            group_key_set_id: group_key_set_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            fabric_index: fabric_index.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// `GroupKeySetStruct`, fabric-scoped โ€” ยง7.19.1.9's `FabricIndex` is field 254.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroupKeySetStruct<'a> {
    /// `GroupKeySetID`, field 0.
    pub group_key_set_id: u16,
    /// `GroupKeySecurityPolicy`, field 1.
    pub group_key_security_policy: GroupKeySecurityPolicyEnum,
    /// `EpochKey0`, field 2.
    pub epoch_key0: Nullable<&'a [u8]>,
    /// `EpochStartTime0`, field 3.
    pub epoch_start_time0: Nullable<u64>,
    /// `EpochKey1`, field 4.
    pub epoch_key1: Nullable<&'a [u8]>,
    /// `EpochStartTime1`, field 5.
    pub epoch_start_time1: Nullable<u64>,
    /// `EpochKey2`, field 6.
    pub epoch_key2: Nullable<&'a [u8]>,
    /// `EpochStartTime2`, field 7.
    pub epoch_start_time2: Nullable<u64>,
    /// `GroupKeyMulticastPolicy`, field 8.
    pub group_key_multicast_policy: Option<GroupKeyMulticastPolicyEnum>,
    /// `FabricIndex`, field 254.
    pub fabric_index: crate::msg::FabricIndex,
}

impl<'a> ToTlv for GroupKeySetStruct<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.group_key_set_id.to_tlv(w, Tag::Context(0))?;
        self.group_key_security_policy.to_tlv(w, Tag::Context(1))?;
        self.epoch_key0.to_tlv(w, Tag::Context(2))?;
        self.epoch_start_time0.to_tlv(w, Tag::Context(3))?;
        self.epoch_key1.to_tlv(w, Tag::Context(4))?;
        self.epoch_start_time1.to_tlv(w, Tag::Context(5))?;
        self.epoch_key2.to_tlv(w, Tag::Context(6))?;
        self.epoch_start_time2.to_tlv(w, Tag::Context(7))?;
        if let Some(value) = &self.group_key_multicast_policy {
            value.to_tlv(w, Tag::Context(8))?;
        }
        self.fabric_index.to_tlv(w, Tag::Context(254))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for GroupKeySetStruct<'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 group_key_set_id = None;
        let mut group_key_security_policy = None;
        let mut epoch_key0 = None;
        let mut epoch_start_time0 = None;
        let mut epoch_key1 = None;
        let mut epoch_start_time1 = None;
        let mut epoch_key2 = None;
        let mut epoch_start_time2 = None;
        let mut group_key_multicast_policy = None;
        let mut fabric_index = 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) => group_key_set_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => {
                    group_key_security_policy =
                        Some(<GroupKeySecurityPolicyEnum>::from_tlv(reader, &field)?)
                }
                Some(2) => epoch_key0 = Some(<Nullable<&'a [u8]>>::from_tlv(reader, &field)?),
                Some(3) => epoch_start_time0 = Some(<Nullable<u64>>::from_tlv(reader, &field)?),
                Some(4) => epoch_key1 = Some(<Nullable<&'a [u8]>>::from_tlv(reader, &field)?),
                Some(5) => epoch_start_time1 = Some(<Nullable<u64>>::from_tlv(reader, &field)?),
                Some(6) => epoch_key2 = Some(<Nullable<&'a [u8]>>::from_tlv(reader, &field)?),
                Some(7) => epoch_start_time2 = Some(<Nullable<u64>>::from_tlv(reader, &field)?),
                Some(8) => {
                    group_key_multicast_policy =
                        Some(<GroupKeyMulticastPolicyEnum>::from_tlv(reader, &field)?)
                }
                Some(254) => {
                    fabric_index = Some(<crate::msg::FabricIndex>::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 {
            group_key_set_id: group_key_set_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            group_key_security_policy: group_key_security_policy
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            epoch_key0: epoch_key0.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            epoch_start_time0: epoch_start_time0
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            epoch_key1: epoch_key1.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            epoch_start_time1: epoch_start_time1
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            epoch_key2: epoch_key2.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            epoch_start_time2: epoch_start_time2
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            group_key_multicast_policy,
            fabric_index: fabric_index.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// `GroupcastAdoptionStruct`, fabric-scoped โ€” ยง7.19.1.9's `FabricIndex` is field 254.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroupcastAdoptionStruct {
    /// `GroupcastAdopted`, field 0.
    pub groupcast_adopted: bool,
    /// `FabricIndex`, field 254.
    pub fabric_index: crate::msg::FabricIndex,
}

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

impl<'a> FromTlv<'a> for GroupcastAdoptionStruct {
    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 groupcast_adopted = None;
        let mut fabric_index = 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) => groupcast_adopted = Some(<bool>::from_tlv(reader, &field)?),
                Some(254) => {
                    fabric_index = Some(<crate::msg::FabricIndex>::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 {
            groupcast_adopted: groupcast_adopted
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            fabric_index: fabric_index.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `KeySetWrite` (command `0x00`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeySetWriteFields<'a> {
    /// `GroupKeySet`, field 0.
    pub group_key_set: GroupKeySetStruct<'a>,
}

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

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

/// The fields of `KeySetRead` (command `0x01`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeySetReadFields {
    /// `GroupKeySetID`, field 0.
    pub group_key_set_id: u16,
}

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

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

/// The fields of `KeySetReadResponse` (command `0x02`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeySetReadResponseFields<'a> {
    /// `GroupKeySet`, field 0.
    pub group_key_set: GroupKeySetStruct<'a>,
}

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

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

/// The fields of `KeySetRemove` (command `0x03`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeySetRemoveFields {
    /// `GroupKeySetID`, field 0.
    pub group_key_set_id: u16,
}

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

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

/// The fields of `KeySetReadAllIndicesResponse` (command `0x05`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeySetReadAllIndicesResponseFields<'a> {
    /// `GroupKeySetIDs`, field 0.
    pub group_key_set_i_ds: TlvList<'a, u16>,
}

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

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

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "GroupKeyMap",
        kind: "list[GroupKeyMapStruct]",
        access: Access::read_write_with(Privilege::View, Privilege::Manage)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0001,
        name: "GroupTable",
        kind: "list[GroupInfoMapStruct]",
        access: Access::read_only(Privilege::View).with_qualities(AccessQualities::FABRIC_SCOPED),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0002,
        name: "MaxGroupsPerFabric",
        kind: "uint16",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0003,
        name: "MaxGroupKeysPerFabric",
        kind: "uint16",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0004,
        name: "GroupcastAdoption",
        kind: "list[GroupcastAdoptionStruct]",
        access: Access::read_write_with(Privilege::Administer, Privilege::Administer)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        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),
                },
            ],
        },
    },
];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[
    Command {
        id: 0x00,
        name: "KeySetWrite",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Administer)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x01,
        name: "KeySetRead",
        to_server: true,
        response: Some(0x02),
        access: Access::invoke(Privilege::Administer)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x02,
        name: "KeySetReadResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x03,
        name: "KeySetRemove",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Administer)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x04,
        name: "KeySetReadAllIndices",
        to_server: true,
        response: Some(0x05),
        access: Access::invoke(Privilege::Administer)
            .with_qualities(AccessQualities::FABRIC_SCOPED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x05,
        name: "KeySetReadAllIndicesResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform::MANDATORY,
    },
];

/// 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: "Group Key Management",
    revision: REVISION,
    pics: "GRPKEY",
    derived_from: None,
    features: FEATURES,
    attributes: ATTRIBUTES,
    commands: COMMANDS,
    events: EVENTS,
};