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
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// Electrical Energy Measurement โ€” cluster 0x0091.
//
// 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.

//! Electrical Energy Measurement (cluster `0x0091`, revision 2).
//!
//! 8 identifiers, 6 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 = 0x0091;

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

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

/// 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 {
    /// Measurement of energy imported by the server
    ///
    /// Code `IMPE`, bit 0.
    pub const IMPORTED_ENERGY: u32 = 1 << 0;
    /// Measurement of energy provided by the server
    ///
    /// Code `EXPE`, bit 1.
    pub const EXPORTED_ENERGY: u32 = 1 << 1;
    /// Measurements are cumulative
    ///
    /// Code `CUME`, bit 2.
    pub const CUMULATIVE_ENERGY: u32 = 1 << 2;
    /// Measurements are periodic
    ///
    /// Code `PERE`, bit 3.
    pub const PERIODIC_ENERGY: u32 = 1 << 3;
    /// Measurements report apparent energy
    ///
    /// Code `APPE`, bit 4.
    pub const APPARENT_ENERGY: u32 = 1 << 4;
    /// Measurements report reactive energy
    ///
    /// Code `REAE`, bit 5.
    pub const REACTIVE_ENERGY: u32 = 1 << 5;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[
    Feature {
        bit: 0,
        code: "IMPE",
        name: "ImportedEnergy",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 1,
        code: "EXPE",
        name: "ExportedEnergy",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 2,
        code: "CUME",
        name: "CumulativeEnergy",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 3,
        code: "PERE",
        name: "PeriodicEnergy",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 4,
        code: "APPE",
        name: "ApparentEnergy",
        conform: Conform {
            clauses: &[
                Clause {
                    verdict: Conformance::Provisional,
                    when: Condition::Always,
                },
                Clause {
                    verdict: Conformance::Optional,
                    when: Condition::Always,
                },
            ],
        },
    },
    Feature {
        bit: 5,
        code: "REAE",
        name: "ReactiveEnergy",
        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;

    /// `Accuracy`.
    pub const ACCURACY: AttributeId = 0x00;
    /// `CumulativeEnergyImported`.
    pub const CUMULATIVE_ENERGY_IMPORTED: AttributeId = 0x01;
    /// `CumulativeEnergyExported`.
    pub const CUMULATIVE_ENERGY_EXPORTED: AttributeId = 0x02;
    /// `PeriodicEnergyImported`.
    pub const PERIODIC_ENERGY_IMPORTED: AttributeId = 0x03;
    /// `PeriodicEnergyExported`.
    pub const PERIODIC_ENERGY_EXPORTED: AttributeId = 0x04;
    /// `CumulativeEnergyReset`.
    pub const CUMULATIVE_ENERGY_RESET: AttributeId = 0x05;
}

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

    /// `CumulativeEnergyMeasured`.
    pub const CUMULATIVE_ENERGY_MEASURED: EventId = 0x00;
    /// `PeriodicEnergyMeasured`.
    pub const PERIODIC_ENERGY_MEASURED: EventId = 0x01;
}

/// `MeasurementTypeEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum MeasurementTypeEnum {
    /// `Unspecified`.
    Unspecified = 0,
    /// Voltage in millivolts (mV)
    Voltage = 1,
    /// Active current in milliamps (mA)
    ActiveCurrent = 2,
    /// Reactive current in milliamps (mA)
    ReactiveCurrent = 3,
    /// Apparent current in milliamps (mA)
    ApparentCurrent = 4,
    /// Active power in milliwatts (mW)
    ActivePower = 5,
    /// Reactive power in millivolt-amps reactive (mVAR)
    ReactivePower = 6,
    /// Apparent power in millivolt-amps (mVA)
    ApparentPower = 7,
    /// Root mean squared voltage in millivolts (mV)
    RMSVoltage = 8,
    /// Root mean squared current in milliamps (mA)
    RMSCurrent = 9,
    /// Root mean squared power in milliwatts (mW)
    RMSPower = 10,
    /// AC frequency in millihertz (mHz)
    Frequency = 11,
    /// Power Factor ratio in +/- 1/100ths of a percent.
    PowerFactor = 12,
    /// AC neutral current in milliamps (mA)
    NeutralCurrent = 13,
    /// Electrical energy in milliwatt-hours (mWh)
    ElectricalEnergy = 14,
    /// Reactive power in millivolt-amp-hours reactive (mVARh)
    ReactiveEnergy = 15,
    /// Apparent power in millivolt-amp-hours (mVAh)
    ApparentEnergy = 16,
}

impl MeasurementTypeEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Unspecified),
            1 => Some(Self::Voltage),
            2 => Some(Self::ActiveCurrent),
            3 => Some(Self::ReactiveCurrent),
            4 => Some(Self::ApparentCurrent),
            5 => Some(Self::ActivePower),
            6 => Some(Self::ReactivePower),
            7 => Some(Self::ApparentPower),
            8 => Some(Self::RMSVoltage),
            9 => Some(Self::RMSCurrent),
            10 => Some(Self::RMSPower),
            11 => Some(Self::Frequency),
            12 => Some(Self::PowerFactor),
            13 => Some(Self::NeutralCurrent),
            14 => Some(Self::ElectricalEnergy),
            15 => Some(Self::ReactiveEnergy),
            16 => Some(Self::ApparentEnergy),
            _ => None,
        }
    }

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

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

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

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

impl ToTlv for CumulativeEnergyResetStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        if let Some(value) = &self.imported_reset_timestamp {
            value.to_tlv(w, Tag::Context(0))?;
        }
        if let Some(value) = &self.exported_reset_timestamp {
            value.to_tlv(w, Tag::Context(1))?;
        }
        if let Some(value) = &self.imported_reset_systime {
            value.to_tlv(w, Tag::Context(2))?;
        }
        if let Some(value) = &self.exported_reset_systime {
            value.to_tlv(w, Tag::Context(3))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for CumulativeEnergyResetStruct {
    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 imported_reset_timestamp = None;
        let mut exported_reset_timestamp = None;
        let mut imported_reset_systime = None;
        let mut exported_reset_systime = 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) => {
                    imported_reset_timestamp = Some(<Nullable<u32>>::from_tlv(reader, &field)?)
                }
                Some(1) => {
                    exported_reset_timestamp = Some(<Nullable<u32>>::from_tlv(reader, &field)?)
                }
                Some(2) => {
                    imported_reset_systime = Some(<Nullable<u64>>::from_tlv(reader, &field)?)
                }
                Some(3) => {
                    exported_reset_systime = Some(<Nullable<u64>>::from_tlv(reader, &field)?)
                }
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            imported_reset_timestamp,
            exported_reset_timestamp,
            imported_reset_systime,
            exported_reset_systime,
        })
    }
}

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

impl ToTlv for EnergyMeasurementStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.energy.to_tlv(w, Tag::Context(0))?;
        if let Some(value) = &self.start_timestamp {
            value.to_tlv(w, Tag::Context(1))?;
        }
        if let Some(value) = &self.end_timestamp {
            value.to_tlv(w, Tag::Context(2))?;
        }
        if let Some(value) = &self.start_systime {
            value.to_tlv(w, Tag::Context(3))?;
        }
        if let Some(value) = &self.end_systime {
            value.to_tlv(w, Tag::Context(4))?;
        }
        if let Some(value) = &self.apparent_energy {
            value.to_tlv(w, Tag::Context(5))?;
        }
        if let Some(value) = &self.reactive_energy {
            value.to_tlv(w, Tag::Context(6))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for EnergyMeasurementStruct {
    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 energy = None;
        let mut start_timestamp = None;
        let mut end_timestamp = None;
        let mut start_systime = None;
        let mut end_systime = None;
        let mut apparent_energy = None;
        let mut reactive_energy = 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) => energy = Some(<i64>::from_tlv(reader, &field)?),
                Some(1) => start_timestamp = Some(<u32>::from_tlv(reader, &field)?),
                Some(2) => end_timestamp = Some(<u32>::from_tlv(reader, &field)?),
                Some(3) => start_systime = Some(<u64>::from_tlv(reader, &field)?),
                Some(4) => end_systime = Some(<u64>::from_tlv(reader, &field)?),
                Some(5) => apparent_energy = Some(<i64>::from_tlv(reader, &field)?),
                Some(6) => reactive_energy = Some(<i64>::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 {
            energy: energy.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            start_timestamp,
            end_timestamp,
            start_systime,
            end_systime,
            apparent_energy,
            reactive_energy,
        })
    }
}

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

impl ToTlv for MeasurementAccuracyRangeStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.range_min.to_tlv(w, Tag::Context(0))?;
        self.range_max.to_tlv(w, Tag::Context(1))?;
        if let Some(value) = &self.percent_max {
            value.to_tlv(w, Tag::Context(2))?;
        }
        if let Some(value) = &self.percent_min {
            value.to_tlv(w, Tag::Context(3))?;
        }
        if let Some(value) = &self.percent_typical {
            value.to_tlv(w, Tag::Context(4))?;
        }
        if let Some(value) = &self.fixed_max {
            value.to_tlv(w, Tag::Context(5))?;
        }
        if let Some(value) = &self.fixed_min {
            value.to_tlv(w, Tag::Context(6))?;
        }
        if let Some(value) = &self.fixed_typical {
            value.to_tlv(w, Tag::Context(7))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for MeasurementAccuracyRangeStruct {
    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 range_min = None;
        let mut range_max = None;
        let mut percent_max = None;
        let mut percent_min = None;
        let mut percent_typical = None;
        let mut fixed_max = None;
        let mut fixed_min = None;
        let mut fixed_typical = 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) => range_min = Some(<i64>::from_tlv(reader, &field)?),
                Some(1) => range_max = Some(<i64>::from_tlv(reader, &field)?),
                Some(2) => percent_max = Some(<u16>::from_tlv(reader, &field)?),
                Some(3) => percent_min = Some(<u16>::from_tlv(reader, &field)?),
                Some(4) => percent_typical = Some(<u16>::from_tlv(reader, &field)?),
                Some(5) => fixed_max = Some(<u64>::from_tlv(reader, &field)?),
                Some(6) => fixed_min = Some(<u64>::from_tlv(reader, &field)?),
                Some(7) => fixed_typical = Some(<u64>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            range_min: range_min.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            range_max: range_max.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            percent_max,
            percent_min,
            percent_typical,
            fixed_max,
            fixed_min,
            fixed_typical,
        })
    }
}

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

impl<'a> ToTlv for MeasurementAccuracyStruct<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.measurement_type.to_tlv(w, Tag::Context(0))?;
        self.measured.to_tlv(w, Tag::Context(1))?;
        self.min_measured_value.to_tlv(w, Tag::Context(2))?;
        self.max_measured_value.to_tlv(w, Tag::Context(3))?;
        self.accuracy_ranges.to_tlv(w, Tag::Context(4))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for MeasurementAccuracyStruct<'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 measurement_type = None;
        let mut measured = None;
        let mut min_measured_value = None;
        let mut max_measured_value = None;
        let mut accuracy_ranges = 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) => {
                    measurement_type = Some(<MeasurementTypeEnum>::from_tlv(reader, &field)?)
                }
                Some(1) => measured = Some(<bool>::from_tlv(reader, &field)?),
                Some(2) => min_measured_value = Some(<i64>::from_tlv(reader, &field)?),
                Some(3) => max_measured_value = Some(<i64>::from_tlv(reader, &field)?),
                Some(4) => {
                    accuracy_ranges = Some(<TlvList<'a, MeasurementAccuracyRangeStruct>>::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 {
            measurement_type: measurement_type
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            measured: measured.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            min_measured_value: min_measured_value
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            max_measured_value: max_measured_value
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            accuracy_ranges: accuracy_ranges
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "Accuracy",
        kind: "MeasurementAccuracyStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0001,
        name: "CumulativeEnergyImported",
        kind: "EnergyMeasurementStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::Quieter,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::All(&[Condition::Feature(0), Condition::Feature(2)]),
            }],
        },
    },
    Attribute {
        id: 0x0002,
        name: "CumulativeEnergyExported",
        kind: "EnergyMeasurementStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::Quieter,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::All(&[Condition::Feature(1), Condition::Feature(2)]),
            }],
        },
    },
    Attribute {
        id: 0x0003,
        name: "PeriodicEnergyImported",
        kind: "EnergyMeasurementStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::Quieter,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::All(&[Condition::Feature(0), Condition::Feature(3)]),
            }],
        },
    },
    Attribute {
        id: 0x0004,
        name: "PeriodicEnergyExported",
        kind: "EnergyMeasurementStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::Quieter,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::All(&[Condition::Feature(1), Condition::Feature(3)]),
            }],
        },
    },
    Attribute {
        id: 0x0005,
        name: "CumulativeEnergyReset",
        kind: "CumulativeEnergyResetStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Optional,
                when: Condition::Feature(2),
            }],
        },
    },
];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[];

/// Every event, with its conformance.
pub const EVENTS: &[Event] = &[
    Event {
        id: 0x00,
        name: "CumulativeEnergyMeasured",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(2),
            }],
        },
    },
    Event {
        id: 0x01,
        name: "PeriodicEnergyMeasured",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(3),
            }],
        },
    },
];

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