matter-clusters 0.1.0

Matter protocol cluster definitions (generated from the spec).
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! OperationalCredentials cluster (0x003E).
//! @generated by `cargo xtask codegen` — do not edit.

#![allow(
    clippy::all,
    clippy::pedantic,
    dead_code,
    unreachable_pub,
    unused_imports
)]

use crate::datatypes::SemanticTagStruct;
use crate::error::ClusterError;
use crate::types::Nullable;
use matter_codec::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value};

/// Cluster ID.
pub const CLUSTER_ID: u32 = 0x003E;
/// Cluster revision.
pub const CLUSTER_REVISION: u16 = 2;

/// Command IDs (requests and responses).
pub mod command_id {
    /// `AttestationRequest` (request).
    pub const ATTESTATION_REQUEST: u32 = 0x00;
    /// `AttestationResponse` (response).
    pub const ATTESTATION_RESPONSE: u32 = 0x01;
    /// `CertificateChainRequest` (request).
    pub const CERTIFICATE_CHAIN_REQUEST: u32 = 0x02;
    /// `CertificateChainResponse` (response).
    pub const CERTIFICATE_CHAIN_RESPONSE: u32 = 0x03;
    /// `CsrRequest` (request).
    pub const CSR_REQUEST: u32 = 0x04;
    /// `CsrResponse` (response).
    pub const CSR_RESPONSE: u32 = 0x05;
    /// `AddNoc` (request).
    pub const ADD_NOC: u32 = 0x06;
    /// `UpdateNoc` (request).
    pub const UPDATE_NOC: u32 = 0x07;
    /// `NocResponse` (response).
    pub const NOC_RESPONSE: u32 = 0x08;
    /// `UpdateFabricLabel` (request).
    pub const UPDATE_FABRIC_LABEL: u32 = 0x09;
    /// `RemoveFabric` (request).
    pub const REMOVE_FABRIC: u32 = 0x0A;
    /// `AddTrustedRootCertificate` (request).
    pub const ADD_TRUSTED_ROOT_CERTIFICATE: u32 = 0x0B;
    /// `SetVidVerificationStatement` (request).
    pub const SET_VID_VERIFICATION_STATEMENT: u32 = 0x0C;
    /// `SignVidVerificationRequest` (request).
    pub const SIGN_VID_VERIFICATION_REQUEST: u32 = 0x0D;
    /// `SignVidVerificationResponse` (response).
    pub const SIGN_VID_VERIFICATION_RESPONSE: u32 = 0x0E;
}

/// Attribute IDs (cluster-specific).
pub mod attribute_id {
    /// `Nocs`.
    pub const NOCS: u32 = 0x0000;
    /// `Fabrics`.
    pub const FABRICS: u32 = 0x0001;
    /// `SupportedFabrics`.
    pub const SUPPORTED_FABRICS: u32 = 0x0002;
    /// `CommissionedFabrics`.
    pub const COMMISSIONED_FABRICS: u32 = 0x0003;
    /// `TrustedRootCertificates`.
    pub const TRUSTED_ROOT_CERTIFICATES: u32 = 0x0004;
    /// `CurrentFabricIndex`.
    pub const CURRENT_FABRIC_INDEX: u32 = 0x0005;
}

/// `CertificateChainTypeEnum` (enum8).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CertificateChainTypeEnum {
    /// DacCertificate = 1.
    DacCertificate,
    /// PaiCertificate = 2.
    PaiCertificate,
    /// A value not known to this codegen revision.
    Unknown(u8),
}

impl CertificateChainTypeEnum {
    /// Decode from its raw discriminant (unknown → `Unknown`).
    #[must_use]
    pub fn from_raw(v: u8) -> Self {
        match v {
            1 => Self::DacCertificate,
            2 => Self::PaiCertificate,
            other => Self::Unknown(other),
        }
    }
    /// The raw discriminant.
    #[must_use]
    pub fn to_raw(self) -> u8 {
        match self {
            Self::DacCertificate => 1,
            Self::PaiCertificate => 2,
            Self::Unknown(v) => v,
        }
    }
}

/// `FabricDescriptorStruct` struct.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FabricDescriptorStruct {
    /// Field RootPublicKey (tag 1).
    pub root_public_key: Vec<u8>,
    /// Field VendorId (tag 2).
    pub vendor_id: u16,
    /// Field FabricId (tag 3).
    pub fabric_id: u64,
    /// Field NodeId (tag 4).
    pub node_id: u64,
    /// Field Label (tag 5).
    pub label: String,
    /// Field VidVerificationStatement (tag 6).
    pub vid_verification_statement: Option<Vec<u8>>,
    /// Field FabricIndex (tag 254).
    pub fabric_index: u8,
}

/// `NOCStruct` struct.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct NOCStruct {
    /// Field Noc (tag 1).
    pub noc: Vec<u8>,
    /// Field Icac (tag 2).
    pub icac: Nullable<Vec<u8>>,
    /// Field Vvsc (tag 3).
    pub vvsc: Option<Vec<u8>>,
    /// Field FabricIndex (tag 254).
    pub fabric_index: u8,
}

/// `NodeOperationalCertStatusEnum` (enum8).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum NodeOperationalCertStatusEnum {
    /// Ok = 0.
    Ok,
    /// InvalidPublicKey = 1.
    InvalidPublicKey,
    /// InvalidNodeOpId = 2.
    InvalidNodeOpId,
    /// InvalidNoc = 3.
    InvalidNoc,
    /// MissingCsr = 4.
    MissingCsr,
    /// TableFull = 5.
    TableFull,
    /// InvalidAdminSubject = 6.
    InvalidAdminSubject,
    /// FabricConflict = 9.
    FabricConflict,
    /// LabelConflict = 10.
    LabelConflict,
    /// InvalidFabricIndex = 11.
    InvalidFabricIndex,
    /// A value not known to this codegen revision.
    Unknown(u8),
}

impl NodeOperationalCertStatusEnum {
    /// Decode from its raw discriminant (unknown → `Unknown`).
    #[must_use]
    pub fn from_raw(v: u8) -> Self {
        match v {
            0 => Self::Ok,
            1 => Self::InvalidPublicKey,
            2 => Self::InvalidNodeOpId,
            3 => Self::InvalidNoc,
            4 => Self::MissingCsr,
            5 => Self::TableFull,
            6 => Self::InvalidAdminSubject,
            9 => Self::FabricConflict,
            10 => Self::LabelConflict,
            11 => Self::InvalidFabricIndex,
            other => Self::Unknown(other),
        }
    }
    /// The raw discriminant.
    #[must_use]
    pub fn to_raw(self) -> u8 {
        match self {
            Self::Ok => 0,
            Self::InvalidPublicKey => 1,
            Self::InvalidNodeOpId => 2,
            Self::InvalidNoc => 3,
            Self::MissingCsr => 4,
            Self::TableFull => 5,
            Self::InvalidAdminSubject => 6,
            Self::FabricConflict => 9,
            Self::LabelConflict => 10,
            Self::InvalidFabricIndex => 11,
            Self::Unknown(v) => v,
        }
    }
}

impl FabricDescriptorStruct {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_root_public_key: Option<Vec<u8>> = None;
        let mut f_vendor_id: Option<u16> = None;
        let mut f_fabric_id: Option<u64> = None;
        let mut f_node_id: Option<u64> = None;
        let mut f_label: Option<String> = None;
        let mut f_vid_verification_statement: Option<Vec<u8>> = None;
        let mut f_fabric_index: Option<u8> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Bytes(v),
                }) => f_root_public_key = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Uint(v),
                }) => {
                    f_vendor_id = Some(
                        u16::try_from(v).map_err(|_| ClusterError::InvalidLength("VendorId"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Uint(v),
                }) => {
                    f_fabric_id = Some(
                        u64::try_from(v).map_err(|_| ClusterError::InvalidLength("FabricId"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(4),
                    value: Value::Uint(v),
                }) => {
                    f_node_id =
                        Some(u64::try_from(v).map_err(|_| ClusterError::InvalidLength("NodeId"))?)
                }
                Some(Element::Scalar {
                    tag: Tag::Context(5),
                    value: Value::Utf8(v),
                }) => f_label = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(6),
                    value: Value::Bytes(v),
                }) => f_vid_verification_statement = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(254),
                    value: Value::Uint(v),
                }) => {
                    f_fabric_index = Some(
                        u8::try_from(v).map_err(|_| ClusterError::InvalidLength("FabricIndex"))?,
                    )
                }
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            root_public_key: f_root_public_key
                .ok_or(ClusterError::MissingField("RootPublicKey"))?,
            vendor_id: f_vendor_id.ok_or(ClusterError::MissingField("VendorId"))?,
            fabric_id: f_fabric_id.ok_or(ClusterError::MissingField("FabricId"))?,
            node_id: f_node_id.ok_or(ClusterError::MissingField("NodeId"))?,
            label: f_label.ok_or(ClusterError::MissingField("Label"))?,
            vid_verification_statement: f_vid_verification_statement,
            fabric_index: f_fabric_index.ok_or(ClusterError::MissingField("FabricIndex"))?,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "FabricDescriptorStruct",
                })
            }
        }
        Self::decode_from(&mut r)
    }
    /// Write this struct's fields into an already-open container.
    #[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible.
    pub fn write_fields(&self, w: &mut TlvWriter<'_>) {
        w.put_bytes(Tag::Context(1), &self.root_public_key)
            .expect("infallible: vec writer");
        w.put_uint(Tag::Context(2), u64::from(self.vendor_id))
            .expect("infallible: vec writer");
        w.put_uint(Tag::Context(3), u64::from(self.fabric_id))
            .expect("infallible: vec writer");
        w.put_uint(Tag::Context(4), u64::from(self.node_id))
            .expect("infallible: vec writer");
        w.put_utf8(Tag::Context(5), &self.label)
            .expect("infallible: vec writer");
        if let Some(vid_verification_statement) = &self.vid_verification_statement {
            w.put_bytes(Tag::Context(6), &*vid_verification_statement)
                .expect("infallible: vec writer");
        }
        w.put_uint(Tag::Context(254), u64::from(self.fabric_index))
            .expect("infallible: vec writer");
    }
    /// Encode as a standalone anonymous TLV structure.
    #[must_use]
    #[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible.
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous)
            .expect("infallible: vec writer");
        self.write_fields(&mut w);
        w.end_container().expect("infallible: vec writer");
        buf
    }
}

impl NOCStruct {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_noc: Option<Vec<u8>> = None;
        let mut f_icac: Option<Nullable<Vec<u8>>> = None;
        let mut f_vvsc: Option<Vec<u8>> = None;
        let mut f_fabric_index: Option<u8> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Bytes(v),
                }) => f_noc = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Null,
                }) => f_icac = Some(Nullable::Null),
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Bytes(v),
                }) => f_icac = Some(Nullable::Value(v)),
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Bytes(v),
                }) => f_vvsc = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(254),
                    value: Value::Uint(v),
                }) => {
                    f_fabric_index = Some(
                        u8::try_from(v).map_err(|_| ClusterError::InvalidLength("FabricIndex"))?,
                    )
                }
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            noc: f_noc.ok_or(ClusterError::MissingField("Noc"))?,
            icac: f_icac.ok_or(ClusterError::MissingField("Icac"))?,
            vvsc: f_vvsc,
            fabric_index: f_fabric_index.ok_or(ClusterError::MissingField("FabricIndex"))?,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "NOCStruct",
                })
            }
        }
        Self::decode_from(&mut r)
    }
    /// Write this struct's fields into an already-open container.
    #[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible.
    pub fn write_fields(&self, w: &mut TlvWriter<'_>) {
        w.put_bytes(Tag::Context(1), &self.noc)
            .expect("infallible: vec writer");
        match &self.icac {
            Nullable::Null => w.put_null(Tag::Context(2)).expect("infallible: vec writer"),
            Nullable::Value(icac) => {
                w.put_bytes(Tag::Context(2), &*icac)
                    .expect("infallible: vec writer");
            }
        }
        if let Some(vvsc) = &self.vvsc {
            w.put_bytes(Tag::Context(3), &*vvsc)
                .expect("infallible: vec writer");
        }
        w.put_uint(Tag::Context(254), u64::from(self.fabric_index))
            .expect("infallible: vec writer");
    }
    /// Encode as a standalone anonymous TLV structure.
    #[must_use]
    #[allow(clippy::expect_used)] // Vec-backed TlvWriter is infallible.
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous)
            .expect("infallible: vec writer");
        self.write_fields(&mut w);
        w.end_container().expect("infallible: vec writer");
        buf
    }
}

/// Decode the `Nocs` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_nocs(tlv: &[u8]) -> Result<Vec<NOCStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::ContainerStart {
            kind: ContainerKind::Array,
            ..
        }) => {}
        _ => return Err(ClusterError::UnexpectedType { context: "Nocs" }),
    }
    let r = &mut r;
    let mut out = Vec::new();
    loop {
        match r.next()? {
            Some(Element::ContainerEnd) => break,
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {
                out.push(NOCStruct::decode_from(r)?);
            }
            None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
            Some(Element::ContainerStart { .. }) => r.skip_container()?,
            Some(_) => {} // skip unknown scalar
        }
    }
    Ok(out)
}

/// Decode the `Fabrics` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_fabrics(tlv: &[u8]) -> Result<Vec<FabricDescriptorStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::ContainerStart {
            kind: ContainerKind::Array,
            ..
        }) => {}
        _ => return Err(ClusterError::UnexpectedType { context: "Fabrics" }),
    }
    let r = &mut r;
    let mut out = Vec::new();
    loop {
        match r.next()? {
            Some(Element::ContainerEnd) => break,
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {
                out.push(FabricDescriptorStruct::decode_from(r)?);
            }
            None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
            Some(Element::ContainerStart { .. }) => r.skip_container()?,
            Some(_) => {} // skip unknown scalar
        }
    }
    Ok(out)
}

/// Decode the `SupportedFabrics` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_supported_fabrics(tlv: &[u8]) -> Result<u8, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Uint(v),
            ..
        }) => Ok(u8::try_from(v).map_err(|_| ClusterError::InvalidLength("SupportedFabrics"))?),
        _ => Err(ClusterError::UnexpectedType {
            context: "SupportedFabrics",
        }),
    }
}

/// Decode the `CommissionedFabrics` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_commissioned_fabrics(tlv: &[u8]) -> Result<u8, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Uint(v),
            ..
        }) => Ok(u8::try_from(v).map_err(|_| ClusterError::InvalidLength("CommissionedFabrics"))?),
        _ => Err(ClusterError::UnexpectedType {
            context: "CommissionedFabrics",
        }),
    }
}

/// Decode the `TrustedRootCertificates` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_trusted_root_certificates(tlv: &[u8]) -> Result<Vec<Vec<u8>>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::ContainerStart {
            kind: ContainerKind::Array,
            ..
        }) => {}
        _ => {
            return Err(ClusterError::UnexpectedType {
                context: "TrustedRootCertificates",
            })
        }
    }
    let r = &mut r;
    let mut out = Vec::new();
    loop {
        match r.next()? {
            Some(Element::ContainerEnd) => break,
            Some(Element::Scalar {
                value: Value::Bytes(v),
                ..
            }) => out.push(v),
            None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
            Some(Element::ContainerStart { .. }) => r.skip_container()?,
            Some(_) => {} // skip unknown scalar
        }
    }
    Ok(out)
}

/// Decode the `CurrentFabricIndex` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_current_fabric_index(tlv: &[u8]) -> Result<u8, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Uint(v),
            ..
        }) => Ok(u8::try_from(v).map_err(|_| ClusterError::InvalidLength("CurrentFabricIndex"))?),
        _ => Err(ClusterError::UnexpectedType {
            context: "CurrentFabricIndex",
        }),
    }
}

/// Encode the `AttestationRequest` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_attestation_request(attestation_nonce: &Vec<u8>) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bytes(Tag::Context(0), &attestation_nonce)
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Decoded `AttestationResponse` payload.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct AttestationResponse {
    /// Field AttestationElements (tag 0).
    pub attestation_elements: Vec<u8>,
    /// Field AttestationSignature (tag 1).
    pub attestation_signature: Vec<u8>,
}

impl AttestationResponse {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_attestation_elements: Option<Vec<u8>> = None;
        let mut f_attestation_signature: Option<Vec<u8>> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Bytes(v),
                }) => f_attestation_elements = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Bytes(v),
                }) => f_attestation_signature = Some(v),
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            attestation_elements: f_attestation_elements
                .ok_or(ClusterError::MissingField("AttestationElements"))?,
            attestation_signature: f_attestation_signature
                .ok_or(ClusterError::MissingField("AttestationSignature"))?,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "AttestationResponse",
                })
            }
        }
        Self::decode_from(&mut r)
    }
}

/// Encode the `CertificateChainRequest` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_certificate_chain_request(certificate_type: CertificateChainTypeEnum) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(0), u64::from(certificate_type.to_raw()))
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Decoded `CertificateChainResponse` payload.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct CertificateChainResponse {
    /// Field Certificate (tag 0).
    pub certificate: Vec<u8>,
}

impl CertificateChainResponse {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_certificate: Option<Vec<u8>> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Bytes(v),
                }) => f_certificate = Some(v),
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            certificate: f_certificate.ok_or(ClusterError::MissingField("Certificate"))?,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "CertificateChainResponse",
                })
            }
        }
        Self::decode_from(&mut r)
    }
}

/// Encode the `CsrRequest` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_csr_request(csr_nonce: &Vec<u8>, is_for_update_noc: Option<bool>) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bytes(Tag::Context(0), &csr_nonce)
        .expect("infallible: vec writer");
    if let Some(is_for_update_noc) = is_for_update_noc {
        w.put_bool(Tag::Context(1), is_for_update_noc)
            .expect("infallible: vec writer");
    }
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Decoded `CsrResponse` payload.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct CsrResponse {
    /// Field NocsrElements (tag 0).
    pub nocsr_elements: Vec<u8>,
    /// Field AttestationSignature (tag 1).
    pub attestation_signature: Vec<u8>,
}

impl CsrResponse {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_nocsr_elements: Option<Vec<u8>> = None;
        let mut f_attestation_signature: Option<Vec<u8>> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Bytes(v),
                }) => f_nocsr_elements = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Bytes(v),
                }) => f_attestation_signature = Some(v),
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            nocsr_elements: f_nocsr_elements.ok_or(ClusterError::MissingField("NocsrElements"))?,
            attestation_signature: f_attestation_signature
                .ok_or(ClusterError::MissingField("AttestationSignature"))?,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "CsrResponse",
                })
            }
        }
        Self::decode_from(&mut r)
    }
}

/// Encode the `AddNoc` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_add_noc(
    noc_value: &Vec<u8>,
    icac_value: Option<Vec<u8>>,
    ipk_value: &Vec<u8>,
    case_admin_subject: u64,
    admin_vendor_id: u16,
) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bytes(Tag::Context(0), &noc_value)
        .expect("infallible: vec writer");
    if let Some(icac_value) = icac_value {
        w.put_bytes(Tag::Context(1), &icac_value)
            .expect("infallible: vec writer");
    }
    w.put_bytes(Tag::Context(2), &ipk_value)
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(3), u64::from(case_admin_subject))
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(4), u64::from(admin_vendor_id))
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Encode the `UpdateNoc` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_update_noc(noc_value: &Vec<u8>, icac_value: Option<Vec<u8>>) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bytes(Tag::Context(0), &noc_value)
        .expect("infallible: vec writer");
    if let Some(icac_value) = icac_value {
        w.put_bytes(Tag::Context(1), &icac_value)
            .expect("infallible: vec writer");
    }
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Decoded `NocResponse` payload.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct NocResponse {
    /// Field StatusCode (tag 0).
    pub status_code: NodeOperationalCertStatusEnum,
    /// Field FabricIndex (tag 1).
    pub fabric_index: Option<u8>,
    /// Field DebugText (tag 2).
    pub debug_text: Option<String>,
}

impl NocResponse {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_status_code: Option<NodeOperationalCertStatusEnum> = None;
        let mut f_fabric_index: Option<u8> = None;
        let mut f_debug_text: Option<String> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Uint(v),
                }) => {
                    f_status_code = Some(NodeOperationalCertStatusEnum::from_raw(
                        u8::try_from(v).map_err(|_| ClusterError::InvalidLength("StatusCode"))?,
                    ))
                }
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Uint(v),
                }) => {
                    f_fabric_index = Some(
                        u8::try_from(v).map_err(|_| ClusterError::InvalidLength("FabricIndex"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Utf8(v),
                }) => f_debug_text = Some(v),
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            status_code: f_status_code.ok_or(ClusterError::MissingField("StatusCode"))?,
            fabric_index: f_fabric_index,
            debug_text: f_debug_text,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "NocResponse",
                })
            }
        }
        Self::decode_from(&mut r)
    }
}

/// Encode the `UpdateFabricLabel` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_update_fabric_label(label: &String) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_utf8(Tag::Context(0), &label)
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Encode the `RemoveFabric` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_remove_fabric(fabric_index: u8) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(0), u64::from(fabric_index))
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Encode the `AddTrustedRootCertificate` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_add_trusted_root_certificate(root_ca_certificate: &Vec<u8>) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_bytes(Tag::Context(0), &root_ca_certificate)
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Encode the `SetVidVerificationStatement` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_set_vid_verification_statement(
    vendor_id: Option<u16>,
    vid_verification_statement: Option<Vec<u8>>,
    vvsc: Option<Vec<u8>>,
) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    if let Some(vendor_id) = vendor_id {
        w.put_uint(Tag::Context(0), u64::from(vendor_id))
            .expect("infallible: vec writer");
    }
    if let Some(vid_verification_statement) = vid_verification_statement {
        w.put_bytes(Tag::Context(1), &vid_verification_statement)
            .expect("infallible: vec writer");
    }
    if let Some(vvsc) = vvsc {
        w.put_bytes(Tag::Context(2), &vvsc)
            .expect("infallible: vec writer");
    }
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Encode the `SignVidVerificationRequest` command request payload.
#[must_use]
#[allow(clippy::expect_used, clippy::missing_panics_doc)] // Vec-backed TlvWriter is infallible.
pub fn encode_sign_vid_verification_request(
    fabric_index: u8,
    client_challenge: &Vec<u8>,
) -> Vec<u8> {
    let mut buf = Vec::new();
    let mut w = TlvWriter::new(&mut buf);
    w.start_structure(Tag::Anonymous)
        .expect("infallible: vec writer");
    w.put_uint(Tag::Context(0), u64::from(fabric_index))
        .expect("infallible: vec writer");
    w.put_bytes(Tag::Context(1), &client_challenge)
        .expect("infallible: vec writer");
    w.end_container().expect("infallible: vec writer");
    buf
}

/// Decoded `SignVidVerificationResponse` payload.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct SignVidVerificationResponse {
    /// Field FabricIndex (tag 0).
    pub fabric_index: u8,
    /// Field FabricBindingVersion (tag 1).
    pub fabric_binding_version: u8,
    /// Field Signature (tag 2).
    pub signature: Vec<u8>,
}

impl SignVidVerificationResponse {
    /// Decode the fields of an already-opened anonymous structure
    /// (reader positioned after the struct start; consumes to its end).
    ///
    /// # Errors
    /// Returns [`ClusterError`] on a malformed structure or missing required field.
    pub fn decode_from(r: &mut TlvReader<'_>) -> Result<Self, ClusterError> {
        let mut f_fabric_index: Option<u8> = None;
        let mut f_fabric_binding_version: Option<u8> = None;
        let mut f_signature: Option<Vec<u8>> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Uint(v),
                }) => {
                    f_fabric_index = Some(
                        u8::try_from(v).map_err(|_| ClusterError::InvalidLength("FabricIndex"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Uint(v),
                }) => {
                    f_fabric_binding_version = Some(
                        u8::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("FabricBindingVersion"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Bytes(v),
                }) => f_signature = Some(v),
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            fabric_index: f_fabric_index.ok_or(ClusterError::MissingField("FabricIndex"))?,
            fabric_binding_version: f_fabric_binding_version
                .ok_or(ClusterError::MissingField("FabricBindingVersion"))?,
            signature: f_signature.ok_or(ClusterError::MissingField("Signature"))?,
        })
    }
    /// Decode from a standalone anonymous TLV structure.
    ///
    /// # Errors
    /// Returns [`ClusterError`] if the bytes are not an anonymous structure or a field is malformed.
    pub fn decode(tlv: &[u8]) -> Result<Self, ClusterError> {
        let mut r = TlvReader::new(tlv);
        match r.next()? {
            Some(Element::ContainerStart {
                kind: ContainerKind::Structure,
                ..
            }) => {}
            _ => {
                return Err(ClusterError::UnexpectedType {
                    context: "SignVidVerificationResponse",
                })
            }
        }
        Self::decode_from(&mut r)
    }
}