matter-clusters 0.3.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
//! ElectricalEnergyMeasurement cluster (0x0091).
//! @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 = 0x0091;
/// Cluster revision.
pub const CLUSTER_REVISION: u16 = 2;

/// Command IDs (requests and responses).
pub mod command_id {}

/// Attribute IDs (cluster-specific).
pub mod attribute_id {
    /// `Accuracy`.
    pub const ACCURACY: u32 = 0x0000;
    /// `CumulativeEnergyImported`.
    pub const CUMULATIVE_ENERGY_IMPORTED: u32 = 0x0001;
    /// `CumulativeEnergyExported`.
    pub const CUMULATIVE_ENERGY_EXPORTED: u32 = 0x0002;
    /// `PeriodicEnergyImported`.
    pub const PERIODIC_ENERGY_IMPORTED: u32 = 0x0003;
    /// `PeriodicEnergyExported`.
    pub const PERIODIC_ENERGY_EXPORTED: u32 = 0x0004;
    /// `CumulativeEnergyReset`.
    pub const CUMULATIVE_ENERGY_RESET: u32 = 0x0005;
}

bitflags::bitflags! {
    /// `ElectricalEnergyMeasurement` feature bits (FeatureMap).
    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
    pub struct Feature: u32 {
        /// ImportedEnergy (IMPE).
        const IMPE = 1 << 0;
        /// ExportedEnergy (EXPE).
        const EXPE = 1 << 1;
        /// CumulativeEnergy (CUME).
        const CUME = 1 << 2;
        /// PeriodicEnergy (PERE).
        const PERE = 1 << 3;
        /// ApparentEnergy (APPE).
        const APPE = 1 << 4;
        /// ReactiveEnergy (REAE).
        const REAE = 1 << 5;
    }
}

/// `CumulativeEnergyResetStruct` struct.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct CumulativeEnergyResetStruct {
    /// Field ImportedResetTimestamp (tag 0).
    pub imported_reset_timestamp: Option<Nullable<u32>>,
    /// Field ExportedResetTimestamp (tag 1).
    pub exported_reset_timestamp: Option<Nullable<u32>>,
    /// Field ImportedResetSystime (tag 2).
    pub imported_reset_systime: Option<Nullable<u64>>,
    /// Field ExportedResetSystime (tag 3).
    pub exported_reset_systime: Option<Nullable<u64>>,
}

/// `EnergyMeasurementStruct` struct.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct EnergyMeasurementStruct {
    /// Field Energy (tag 0).
    pub energy: i64,
    /// Field StartTimestamp (tag 1).
    pub start_timestamp: Option<u32>,
    /// Field EndTimestamp (tag 2).
    pub end_timestamp: Option<u32>,
    /// Field StartSystime (tag 3).
    pub start_systime: Option<u64>,
    /// Field EndSystime (tag 4).
    pub end_systime: Option<u64>,
    /// Field ApparentEnergy (tag 5).
    pub apparent_energy: Option<i64>,
    /// Field ReactiveEnergy (tag 6).
    pub reactive_energy: Option<i64>,
}

/// `MeasurementAccuracyRangeStruct` struct.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct MeasurementAccuracyRangeStruct {
    /// Field RangeMin (tag 0).
    pub range_min: i64,
    /// Field RangeMax (tag 1).
    pub range_max: i64,
    /// Field PercentMax (tag 2).
    pub percent_max: Option<u16>,
    /// Field PercentMin (tag 3).
    pub percent_min: Option<u16>,
    /// Field PercentTypical (tag 4).
    pub percent_typical: Option<u16>,
    /// Field FixedMax (tag 5).
    pub fixed_max: Option<u64>,
    /// Field FixedMin (tag 6).
    pub fixed_min: Option<u64>,
    /// Field FixedTypical (tag 7).
    pub fixed_typical: Option<u64>,
}

/// `MeasurementAccuracyStruct` struct.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct MeasurementAccuracyStruct {
    /// Field MeasurementType (tag 0).
    pub measurement_type: MeasurementTypeEnum,
    /// Field Measured (tag 1).
    pub measured: bool,
    /// Field MinMeasuredValue (tag 2).
    pub min_measured_value: i64,
    /// Field MaxMeasuredValue (tag 3).
    pub max_measured_value: i64,
    /// Field AccuracyRanges (tag 4).
    pub accuracy_ranges: Vec<MeasurementAccuracyRangeStruct>,
}

/// `MeasurementTypeEnum` (enum16).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum MeasurementTypeEnum {
    /// Unspecified = 0.
    Unspecified,
    /// Voltage = 1.
    Voltage,
    /// ActiveCurrent = 2.
    ActiveCurrent,
    /// ReactiveCurrent = 3.
    ReactiveCurrent,
    /// ApparentCurrent = 4.
    ApparentCurrent,
    /// ActivePower = 5.
    ActivePower,
    /// ReactivePower = 6.
    ReactivePower,
    /// ApparentPower = 7.
    ApparentPower,
    /// RmsVoltage = 8.
    RmsVoltage,
    /// RmsCurrent = 9.
    RmsCurrent,
    /// RmsPower = 10.
    RmsPower,
    /// Frequency = 11.
    Frequency,
    /// PowerFactor = 12.
    PowerFactor,
    /// NeutralCurrent = 13.
    NeutralCurrent,
    /// ElectricalEnergy = 14.
    ElectricalEnergy,
    /// ReactiveEnergy = 15.
    ReactiveEnergy,
    /// ApparentEnergy = 16.
    ApparentEnergy,
    /// A value not known to this codegen revision.
    Unknown(u16),
}

impl MeasurementTypeEnum {
    /// Decode from its raw discriminant (unknown → `Unknown`).
    #[must_use]
    pub fn from_raw(v: u16) -> Self {
        match v {
            0 => Self::Unspecified,
            1 => Self::Voltage,
            2 => Self::ActiveCurrent,
            3 => Self::ReactiveCurrent,
            4 => Self::ApparentCurrent,
            5 => Self::ActivePower,
            6 => Self::ReactivePower,
            7 => Self::ApparentPower,
            8 => Self::RmsVoltage,
            9 => Self::RmsCurrent,
            10 => Self::RmsPower,
            11 => Self::Frequency,
            12 => Self::PowerFactor,
            13 => Self::NeutralCurrent,
            14 => Self::ElectricalEnergy,
            15 => Self::ReactiveEnergy,
            16 => Self::ApparentEnergy,
            other => Self::Unknown(other),
        }
    }
    /// The raw discriminant.
    #[must_use]
    pub fn to_raw(self) -> u16 {
        match self {
            Self::Unspecified => 0,
            Self::Voltage => 1,
            Self::ActiveCurrent => 2,
            Self::ReactiveCurrent => 3,
            Self::ApparentCurrent => 4,
            Self::ActivePower => 5,
            Self::ReactivePower => 6,
            Self::ApparentPower => 7,
            Self::RmsVoltage => 8,
            Self::RmsCurrent => 9,
            Self::RmsPower => 10,
            Self::Frequency => 11,
            Self::PowerFactor => 12,
            Self::NeutralCurrent => 13,
            Self::ElectricalEnergy => 14,
            Self::ReactiveEnergy => 15,
            Self::ApparentEnergy => 16,
            Self::Unknown(v) => v,
        }
    }
}

impl CumulativeEnergyResetStruct {
    /// 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_imported_reset_timestamp: Option<Nullable<u32>> = None;
        let mut f_exported_reset_timestamp: Option<Nullable<u32>> = None;
        let mut f_imported_reset_systime: Option<Nullable<u64>> = None;
        let mut f_exported_reset_systime: Option<Nullable<u64>> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Null,
                }) => f_imported_reset_timestamp = Some(Nullable::Null),
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Uint(v),
                }) => {
                    f_imported_reset_timestamp =
                        Some(Nullable::Value(u32::try_from(v).map_err(|_| {
                            ClusterError::InvalidLength("ImportedResetTimestamp")
                        })?))
                }
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Null,
                }) => f_exported_reset_timestamp = Some(Nullable::Null),
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Uint(v),
                }) => {
                    f_exported_reset_timestamp =
                        Some(Nullable::Value(u32::try_from(v).map_err(|_| {
                            ClusterError::InvalidLength("ExportedResetTimestamp")
                        })?))
                }
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Null,
                }) => f_imported_reset_systime = Some(Nullable::Null),
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Uint(v),
                }) => {
                    f_imported_reset_systime =
                        Some(Nullable::Value(u64::try_from(v).map_err(|_| {
                            ClusterError::InvalidLength("ImportedResetSystime")
                        })?))
                }
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Null,
                }) => f_exported_reset_systime = Some(Nullable::Null),
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Uint(v),
                }) => {
                    f_exported_reset_systime =
                        Some(Nullable::Value(u64::try_from(v).map_err(|_| {
                            ClusterError::InvalidLength("ExportedResetSystime")
                        })?))
                }
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            imported_reset_timestamp: f_imported_reset_timestamp,
            exported_reset_timestamp: f_exported_reset_timestamp,
            imported_reset_systime: f_imported_reset_systime,
            exported_reset_systime: f_exported_reset_systime,
        })
    }
    /// 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: "CumulativeEnergyResetStruct",
                })
            }
        }
        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<'_>) {
        if let Some(imported_reset_timestamp) = &self.imported_reset_timestamp {
            match imported_reset_timestamp {
                Nullable::Null => w.put_null(Tag::Context(0)).expect("infallible: vec writer"),
                Nullable::Value(imported_reset_timestamp) => {
                    w.put_uint(Tag::Context(0), u64::from(*imported_reset_timestamp))
                        .expect("infallible: vec writer");
                }
            }
        }
        if let Some(exported_reset_timestamp) = &self.exported_reset_timestamp {
            match exported_reset_timestamp {
                Nullable::Null => w.put_null(Tag::Context(1)).expect("infallible: vec writer"),
                Nullable::Value(exported_reset_timestamp) => {
                    w.put_uint(Tag::Context(1), u64::from(*exported_reset_timestamp))
                        .expect("infallible: vec writer");
                }
            }
        }
        if let Some(imported_reset_systime) = &self.imported_reset_systime {
            match imported_reset_systime {
                Nullable::Null => w.put_null(Tag::Context(2)).expect("infallible: vec writer"),
                Nullable::Value(imported_reset_systime) => {
                    w.put_uint(Tag::Context(2), u64::from(*imported_reset_systime))
                        .expect("infallible: vec writer");
                }
            }
        }
        if let Some(exported_reset_systime) = &self.exported_reset_systime {
            match exported_reset_systime {
                Nullable::Null => w.put_null(Tag::Context(3)).expect("infallible: vec writer"),
                Nullable::Value(exported_reset_systime) => {
                    w.put_uint(Tag::Context(3), u64::from(*exported_reset_systime))
                        .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 EnergyMeasurementStruct {
    /// 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_energy: Option<i64> = None;
        let mut f_start_timestamp: Option<u32> = None;
        let mut f_end_timestamp: Option<u32> = None;
        let mut f_start_systime: Option<u64> = None;
        let mut f_end_systime: Option<u64> = None;
        let mut f_apparent_energy: Option<i64> = None;
        let mut f_reactive_energy: Option<i64> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Int(v),
                }) => {
                    f_energy =
                        Some(i64::try_from(v).map_err(|_| ClusterError::InvalidLength("Energy"))?)
                }
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Uint(v),
                }) => {
                    f_start_timestamp = Some(
                        u32::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("StartTimestamp"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Uint(v),
                }) => {
                    f_end_timestamp = Some(
                        u32::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("EndTimestamp"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Uint(v),
                }) => {
                    f_start_systime = Some(
                        u64::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("StartSystime"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(4),
                    value: Value::Uint(v),
                }) => {
                    f_end_systime = Some(
                        u64::try_from(v).map_err(|_| ClusterError::InvalidLength("EndSystime"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(5),
                    value: Value::Int(v),
                }) => {
                    f_apparent_energy = Some(
                        i64::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("ApparentEnergy"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(6),
                    value: Value::Int(v),
                }) => {
                    f_reactive_energy = Some(
                        i64::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("ReactiveEnergy"))?,
                    )
                }
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            energy: f_energy.ok_or(ClusterError::MissingField("Energy"))?,
            start_timestamp: f_start_timestamp,
            end_timestamp: f_end_timestamp,
            start_systime: f_start_systime,
            end_systime: f_end_systime,
            apparent_energy: f_apparent_energy,
            reactive_energy: f_reactive_energy,
        })
    }
    /// 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: "EnergyMeasurementStruct",
                })
            }
        }
        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_int(Tag::Context(0), i64::from(self.energy))
            .expect("infallible: vec writer");
        if let Some(start_timestamp) = &self.start_timestamp {
            w.put_uint(Tag::Context(1), u64::from(*start_timestamp))
                .expect("infallible: vec writer");
        }
        if let Some(end_timestamp) = &self.end_timestamp {
            w.put_uint(Tag::Context(2), u64::from(*end_timestamp))
                .expect("infallible: vec writer");
        }
        if let Some(start_systime) = &self.start_systime {
            w.put_uint(Tag::Context(3), u64::from(*start_systime))
                .expect("infallible: vec writer");
        }
        if let Some(end_systime) = &self.end_systime {
            w.put_uint(Tag::Context(4), u64::from(*end_systime))
                .expect("infallible: vec writer");
        }
        if let Some(apparent_energy) = &self.apparent_energy {
            w.put_int(Tag::Context(5), i64::from(*apparent_energy))
                .expect("infallible: vec writer");
        }
        if let Some(reactive_energy) = &self.reactive_energy {
            w.put_int(Tag::Context(6), i64::from(*reactive_energy))
                .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 MeasurementAccuracyRangeStruct {
    /// 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_range_min: Option<i64> = None;
        let mut f_range_max: Option<i64> = None;
        let mut f_percent_max: Option<u16> = None;
        let mut f_percent_min: Option<u16> = None;
        let mut f_percent_typical: Option<u16> = None;
        let mut f_fixed_max: Option<u64> = None;
        let mut f_fixed_min: Option<u64> = None;
        let mut f_fixed_typical: Option<u64> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Int(v),
                }) => {
                    f_range_min = Some(
                        i64::try_from(v).map_err(|_| ClusterError::InvalidLength("RangeMin"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Int(v),
                }) => {
                    f_range_max = Some(
                        i64::try_from(v).map_err(|_| ClusterError::InvalidLength("RangeMax"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Uint(v),
                }) => {
                    f_percent_max = Some(
                        u16::try_from(v).map_err(|_| ClusterError::InvalidLength("PercentMax"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Uint(v),
                }) => {
                    f_percent_min = Some(
                        u16::try_from(v).map_err(|_| ClusterError::InvalidLength("PercentMin"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(4),
                    value: Value::Uint(v),
                }) => {
                    f_percent_typical = Some(
                        u16::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("PercentTypical"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(5),
                    value: Value::Uint(v),
                }) => {
                    f_fixed_max = Some(
                        u64::try_from(v).map_err(|_| ClusterError::InvalidLength("FixedMax"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(6),
                    value: Value::Uint(v),
                }) => {
                    f_fixed_min = Some(
                        u64::try_from(v).map_err(|_| ClusterError::InvalidLength("FixedMin"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(7),
                    value: Value::Uint(v),
                }) => {
                    f_fixed_typical = Some(
                        u64::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("FixedTypical"))?,
                    )
                }
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            range_min: f_range_min.ok_or(ClusterError::MissingField("RangeMin"))?,
            range_max: f_range_max.ok_or(ClusterError::MissingField("RangeMax"))?,
            percent_max: f_percent_max,
            percent_min: f_percent_min,
            percent_typical: f_percent_typical,
            fixed_max: f_fixed_max,
            fixed_min: f_fixed_min,
            fixed_typical: f_fixed_typical,
        })
    }
    /// 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: "MeasurementAccuracyRangeStruct",
                })
            }
        }
        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_int(Tag::Context(0), i64::from(self.range_min))
            .expect("infallible: vec writer");
        w.put_int(Tag::Context(1), i64::from(self.range_max))
            .expect("infallible: vec writer");
        if let Some(percent_max) = &self.percent_max {
            w.put_uint(Tag::Context(2), u64::from(*percent_max))
                .expect("infallible: vec writer");
        }
        if let Some(percent_min) = &self.percent_min {
            w.put_uint(Tag::Context(3), u64::from(*percent_min))
                .expect("infallible: vec writer");
        }
        if let Some(percent_typical) = &self.percent_typical {
            w.put_uint(Tag::Context(4), u64::from(*percent_typical))
                .expect("infallible: vec writer");
        }
        if let Some(fixed_max) = &self.fixed_max {
            w.put_uint(Tag::Context(5), u64::from(*fixed_max))
                .expect("infallible: vec writer");
        }
        if let Some(fixed_min) = &self.fixed_min {
            w.put_uint(Tag::Context(6), u64::from(*fixed_min))
                .expect("infallible: vec writer");
        }
        if let Some(fixed_typical) = &self.fixed_typical {
            w.put_uint(Tag::Context(7), u64::from(*fixed_typical))
                .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 MeasurementAccuracyStruct {
    /// 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_measurement_type: Option<MeasurementTypeEnum> = None;
        let mut f_measured: Option<bool> = None;
        let mut f_min_measured_value: Option<i64> = None;
        let mut f_max_measured_value: Option<i64> = None;
        let mut f_accuracy_ranges: Option<Vec<MeasurementAccuracyRangeStruct>> = None;
        loop {
            match r.next()? {
                Some(Element::ContainerEnd) => break,
                Some(Element::Scalar {
                    tag: Tag::Context(0),
                    value: Value::Uint(v),
                }) => {
                    f_measurement_type = Some(MeasurementTypeEnum::from_raw(
                        u16::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("MeasurementType"))?,
                    ))
                }
                Some(Element::Scalar {
                    tag: Tag::Context(1),
                    value: Value::Bool(v),
                }) => f_measured = Some(v),
                Some(Element::Scalar {
                    tag: Tag::Context(2),
                    value: Value::Int(v),
                }) => {
                    f_min_measured_value = Some(
                        i64::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("MinMeasuredValue"))?,
                    )
                }
                Some(Element::Scalar {
                    tag: Tag::Context(3),
                    value: Value::Int(v),
                }) => {
                    f_max_measured_value = Some(
                        i64::try_from(v)
                            .map_err(|_| ClusterError::InvalidLength("MaxMeasuredValue"))?,
                    )
                }
                Some(Element::ContainerStart {
                    tag: Tag::Context(4),
                    kind: ContainerKind::Array,
                }) => {
                    let mut out = Vec::new();
                    loop {
                        match r.next()? {
                            Some(Element::ContainerEnd) => break,
                            Some(Element::ContainerStart {
                                kind: ContainerKind::Structure,
                                ..
                            }) => {
                                out.push(MeasurementAccuracyRangeStruct::decode_from(r)?);
                            }
                            None => {
                                return Err(ClusterError::Tlv(
                                    matter_codec::Error::UnclosedContainer,
                                ))
                            }
                            Some(Element::ContainerStart { .. }) => r.skip_container()?,
                            Some(_) => {} // skip unknown scalar
                        }
                    }
                    f_accuracy_ranges = Some(out);
                }
                None => return Err(ClusterError::Tlv(matter_codec::Error::UnclosedContainer)),
                Some(Element::ContainerStart { .. }) => r.skip_container()?,
                Some(_) => {} // unknown/future scalar — skip
            }
        }
        Ok(Self {
            measurement_type: f_measurement_type
                .ok_or(ClusterError::MissingField("MeasurementType"))?,
            measured: f_measured.ok_or(ClusterError::MissingField("Measured"))?,
            min_measured_value: f_min_measured_value
                .ok_or(ClusterError::MissingField("MinMeasuredValue"))?,
            max_measured_value: f_max_measured_value
                .ok_or(ClusterError::MissingField("MaxMeasuredValue"))?,
            accuracy_ranges: f_accuracy_ranges
                .ok_or(ClusterError::MissingField("AccuracyRanges"))?,
        })
    }
    /// 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: "MeasurementAccuracyStruct",
                })
            }
        }
        Self::decode_from(&mut r)
    }
}

/// Decode the `Accuracy` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_accuracy(tlv: &[u8]) -> Result<MeasurementAccuracyStruct, ClusterError> {
    MeasurementAccuracyStruct::decode(tlv)
}

/// Decode the `CumulativeEnergyImported` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_cumulative_energy_imported(
    tlv: &[u8],
) -> Result<Nullable<EnergyMeasurementStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Null, ..
        }) => Ok(Nullable::Null),
        Some(Element::ContainerStart {
            kind: ContainerKind::Structure,
            ..
        }) => Ok(Nullable::Value(EnergyMeasurementStruct::decode_from(
            &mut r,
        )?)),
        _ => Err(ClusterError::UnexpectedType {
            context: "CumulativeEnergyImported",
        }),
    }
}

/// Decode the `CumulativeEnergyExported` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_cumulative_energy_exported(
    tlv: &[u8],
) -> Result<Nullable<EnergyMeasurementStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Null, ..
        }) => Ok(Nullable::Null),
        Some(Element::ContainerStart {
            kind: ContainerKind::Structure,
            ..
        }) => Ok(Nullable::Value(EnergyMeasurementStruct::decode_from(
            &mut r,
        )?)),
        _ => Err(ClusterError::UnexpectedType {
            context: "CumulativeEnergyExported",
        }),
    }
}

/// Decode the `PeriodicEnergyImported` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_periodic_energy_imported(
    tlv: &[u8],
) -> Result<Nullable<EnergyMeasurementStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Null, ..
        }) => Ok(Nullable::Null),
        Some(Element::ContainerStart {
            kind: ContainerKind::Structure,
            ..
        }) => Ok(Nullable::Value(EnergyMeasurementStruct::decode_from(
            &mut r,
        )?)),
        _ => Err(ClusterError::UnexpectedType {
            context: "PeriodicEnergyImported",
        }),
    }
}

/// Decode the `PeriodicEnergyExported` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_periodic_energy_exported(
    tlv: &[u8],
) -> Result<Nullable<EnergyMeasurementStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Null, ..
        }) => Ok(Nullable::Null),
        Some(Element::ContainerStart {
            kind: ContainerKind::Structure,
            ..
        }) => Ok(Nullable::Value(EnergyMeasurementStruct::decode_from(
            &mut r,
        )?)),
        _ => Err(ClusterError::UnexpectedType {
            context: "PeriodicEnergyExported",
        }),
    }
}

/// Decode the `CumulativeEnergyReset` attribute value.
///
/// # Errors
/// Returns [`ClusterError`] on a type mismatch or out-of-range value.
pub fn decode_cumulative_energy_reset(
    tlv: &[u8],
) -> Result<Nullable<CumulativeEnergyResetStruct>, ClusterError> {
    let mut r = TlvReader::new(tlv);
    match r.next()? {
        Some(Element::Scalar {
            value: Value::Null, ..
        }) => Ok(Nullable::Null),
        Some(Element::ContainerStart {
            kind: ContainerKind::Structure,
            ..
        }) => Ok(Nullable::Value(CumulativeEnergyResetStruct::decode_from(
            &mut r,
        )?)),
        _ => Err(ClusterError::UnexpectedType {
            context: "CumulativeEnergyReset",
        }),
    }
}