Skip to main content

matter_kit/clusters/generated/
device_energy_management.rs

1// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
2//
3// Device Energy Management — cluster 0x0098.
4//
5// Regenerate with `cargo xtask clusters --dm <checkout>/data_model/1.6`; `cargo xtask check`
6// is the CI gate that keeps this file honest. The XML itself is not vendored here — it
7// carries the CSA's own copyright notice and is not redistributable.
8
9//! Device Energy Management (cluster `0x0098`, revision 4).
10//!
11//! 20 identifiers, 7 feature bits, and the specification's own conformance for
12//! every element. `CLUSTER` is the whole table.
13
14#![allow(unused_imports)]
15
16use crate::dm::conformance::{Clause, Condition, Conform, Conformance};
17use crate::dm::meta::{EventPriority, Reporting};
18use crate::dm::spec::{Attribute, Cluster, Command, Event, Feature};
19use crate::dm::{Access, AccessQualities, AttributeQualities, Privilege};
20use crate::error::Result;
21use crate::im::{AttributeId, ClusterId, CommandId, EventId};
22use crate::tlv::{
23    ContainerKind, Element, FromTlv, Nullable, Tag, TlvList, TlvReader, TlvWriter, ToTlv, Value,
24};
25
26/// The cluster id.
27pub const ID: ClusterId = 0x0098;
28
29/// The highest revision the specification's history defines — what `ClusterRevision`
30/// must report (Core §7.13.1).
31pub const REVISION: u16 = 4;
32
33/// The PICS code, which a certification declaration names the cluster by.
34pub const PICS: &str = "DEM";
35
36/// The `FeatureMap` bits (Core §7.13.2).
37///
38/// A feature has conformance of its own: a device may not claim one the
39/// specification forbids it alongside another.
40pub mod feature {
41    /// Allows an EMS to make a temporary power adjustment (within the limits offered by the ESA).
42    ///
43    /// Code `PA`, bit 0.
44    pub const POWER_ADJUSTMENT: u32 = 1 << 0;
45    /// Allows an ESA to advertise its indicative future power consumption vs time.
46    ///
47    /// Code `PFR`, bit 1.
48    pub const POWER_FORECAST_REPORTING: u32 = 1 << 1;
49    /// Allows an ESA to advertise its indicative future state vs time.
50    ///
51    /// Code `SFR`, bit 2.
52    pub const STATE_FORECAST_REPORTING: u32 = 1 << 2;
53    /// Allows an EMS to delay an ESA's planned operation.
54    ///
55    /// Code `STA`, bit 3.
56    pub const START_TIME_ADJUSTMENT: u32 = 1 << 3;
57    /// Allows an EMS to pause an ESA's planned operation.
58    ///
59    /// Code `PAU`, bit 4.
60    pub const PAUSABLE: u32 = 1 << 4;
61    /// Allows an EMS to adjust an ESA's planned operation.
62    ///
63    /// Code `FA`, bit 5.
64    pub const FORECAST_ADJUSTMENT: u32 = 1 << 5;
65    /// Allows an EMS to request constraints to an ESA's planned operation.
66    ///
67    /// Code `CON`, bit 6.
68    pub const CONSTRAINT_BASED_ADJUSTMENT: u32 = 1 << 6;
69}
70
71/// Every feature bit, with its conformance.
72pub const FEATURES: &[Feature] = &[
73    Feature {
74        bit: 0,
75        code: "PA",
76        name: "PowerAdjustment",
77        conform: Conform::OPTIONAL,
78    },
79    Feature {
80        bit: 1,
81        code: "PFR",
82        name: "PowerForecastReporting",
83        conform: Conform {
84            clauses: &[
85                Clause {
86                    verdict: Conformance::Optional,
87                    when: Condition::Not(&Condition::Feature(0)),
88                },
89                Clause {
90                    verdict: Conformance::Mandatory,
91                    when: Condition::Any(&[
92                        Condition::Feature(3),
93                        Condition::Feature(4),
94                        Condition::Feature(5),
95                        Condition::Feature(6),
96                    ]),
97                },
98                Clause {
99                    verdict: Conformance::Optional,
100                    when: Condition::Always,
101                },
102            ],
103        },
104    },
105    Feature {
106        bit: 2,
107        code: "SFR",
108        name: "StateForecastReporting",
109        conform: Conform {
110            clauses: &[Clause {
111                verdict: Conformance::Optional,
112                when: Condition::Not(&Condition::Feature(0)),
113            }],
114        },
115    },
116    Feature {
117        bit: 3,
118        code: "STA",
119        name: "StartTimeAdjustment",
120        conform: Conform::OPTIONAL,
121    },
122    Feature {
123        bit: 4,
124        code: "PAU",
125        name: "Pausable",
126        conform: Conform::OPTIONAL,
127    },
128    Feature {
129        bit: 5,
130        code: "FA",
131        name: "ForecastAdjustment",
132        conform: Conform::OPTIONAL,
133    },
134    Feature {
135        bit: 6,
136        code: "CON",
137        name: "ConstraintBasedAdjustment",
138        conform: Conform::OPTIONAL,
139    },
140];
141
142/// The attribute ids.
143pub mod attribute {
144    use crate::im::AttributeId;
145
146    /// `ESAType`.
147    pub const ESA_TYPE: AttributeId = 0x00;
148    /// `ESACanGenerate`.
149    pub const ESA_CAN_GENERATE: AttributeId = 0x01;
150    /// `ESAState`.
151    pub const ESA_STATE: AttributeId = 0x02;
152    /// `AbsMinPower`.
153    pub const ABS_MIN_POWER: AttributeId = 0x03;
154    /// `AbsMaxPower`.
155    pub const ABS_MAX_POWER: AttributeId = 0x04;
156    /// `PowerAdjustmentCapability`.
157    pub const POWER_ADJUSTMENT_CAPABILITY: AttributeId = 0x05;
158    /// `Forecast`.
159    pub const FORECAST: AttributeId = 0x06;
160    /// `OptOutState`.
161    pub const OPT_OUT_STATE: AttributeId = 0x07;
162}
163
164/// The command ids.
165pub mod command {
166    use crate::im::CommandId;
167
168    /// `PowerAdjustRequest`.
169    pub const POWER_ADJUST_REQUEST: CommandId = 0x00;
170    /// `CancelPowerAdjustRequest`.
171    pub const CANCEL_POWER_ADJUST_REQUEST: CommandId = 0x01;
172    /// `StartTimeAdjustRequest`.
173    pub const START_TIME_ADJUST_REQUEST: CommandId = 0x02;
174    /// `PauseRequest`.
175    pub const PAUSE_REQUEST: CommandId = 0x03;
176    /// `ResumeRequest`.
177    pub const RESUME_REQUEST: CommandId = 0x04;
178    /// `ModifyForecastRequest`.
179    pub const MODIFY_FORECAST_REQUEST: CommandId = 0x05;
180    /// `RequestConstraintBasedForecast`.
181    pub const REQUEST_CONSTRAINT_BASED_FORECAST: CommandId = 0x06;
182    /// `CancelRequest`.
183    pub const CANCEL_REQUEST: CommandId = 0x07;
184}
185
186/// The event ids.
187pub mod event {
188    use crate::im::EventId;
189
190    /// `PowerAdjustStart`.
191    pub const POWER_ADJUST_START: EventId = 0x00;
192    /// `PowerAdjustEnd`.
193    pub const POWER_ADJUST_END: EventId = 0x01;
194    /// `Paused`.
195    pub const PAUSED: EventId = 0x02;
196    /// `Resumed`.
197    pub const RESUMED: EventId = 0x03;
198}
199
200/// `AdjustmentCauseEnum`.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
202#[repr(u8)]
203pub enum AdjustmentCauseEnum {
204    /// The adjustment is to optimize the local energy usage
205    LocalOptimization = 0,
206    /// The adjustment is to optimize the grid energy usage
207    GridOptimization = 1,
208}
209
210impl AdjustmentCauseEnum {
211    /// Reads a wire value, or `None` for one this revision does not define.
212    #[must_use]
213    pub const fn from_value(value: u8) -> Option<Self> {
214        match value {
215            0 => Some(Self::LocalOptimization),
216            1 => Some(Self::GridOptimization),
217            _ => None,
218        }
219    }
220
221    /// Its wire value.
222    #[must_use]
223    pub const fn value(self) -> u8 {
224        self as u8
225    }
226}
227
228impl ToTlv for AdjustmentCauseEnum {
229    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
230        self.value().to_tlv(w, tag)
231    }
232}
233
234impl<'a> FromTlv<'a> for AdjustmentCauseEnum {
235    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
236        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
237        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
238    }
239}
240
241/// `CauseEnum`.
242#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
243#[repr(u8)]
244pub enum CauseEnum {
245    /// The ESA completed the power adjustment as requested
246    NormalCompletion = 0,
247    /// The ESA was set to offline
248    Offline = 1,
249    /// The ESA has developed a fault could not complete the adjustment
250    Fault = 2,
251    /// The user has disabled the ESA's flexibility capability
252    UserOptOut = 3,
253    /// The adjustment was cancelled by a client
254    Cancelled = 4,
255}
256
257impl CauseEnum {
258    /// Reads a wire value, or `None` for one this revision does not define.
259    #[must_use]
260    pub const fn from_value(value: u8) -> Option<Self> {
261        match value {
262            0 => Some(Self::NormalCompletion),
263            1 => Some(Self::Offline),
264            2 => Some(Self::Fault),
265            3 => Some(Self::UserOptOut),
266            4 => Some(Self::Cancelled),
267            _ => None,
268        }
269    }
270
271    /// Its wire value.
272    #[must_use]
273    pub const fn value(self) -> u8 {
274        self as u8
275    }
276}
277
278impl ToTlv for CauseEnum {
279    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
280        self.value().to_tlv(w, tag)
281    }
282}
283
284impl<'a> FromTlv<'a> for CauseEnum {
285    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
286        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
287        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
288    }
289}
290
291/// `CostTypeEnum`.
292#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
293#[repr(u8)]
294pub enum CostTypeEnum {
295    /// Financial cost
296    Financial = 0,
297    /// Grid CO2e grams cost
298    GHGEmissions = 1,
299    /// Consumer comfort impact cost
300    Comfort = 2,
301    /// Temperature impact cost
302    Temperature = 3,
303}
304
305impl CostTypeEnum {
306    /// Reads a wire value, or `None` for one this revision does not define.
307    #[must_use]
308    pub const fn from_value(value: u8) -> Option<Self> {
309        match value {
310            0 => Some(Self::Financial),
311            1 => Some(Self::GHGEmissions),
312            2 => Some(Self::Comfort),
313            3 => Some(Self::Temperature),
314            _ => None,
315        }
316    }
317
318    /// Its wire value.
319    #[must_use]
320    pub const fn value(self) -> u8 {
321        self as u8
322    }
323}
324
325impl ToTlv for CostTypeEnum {
326    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
327        self.value().to_tlv(w, tag)
328    }
329}
330
331impl<'a> FromTlv<'a> for CostTypeEnum {
332    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
333        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
334        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
335    }
336}
337
338/// `ESAStateEnum`.
339#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
340#[repr(u8)]
341pub enum ESAStateEnum {
342    /// The ESA is not available to the EMS (e.g. start-up, maintenance mode)
343    Offline = 0,
344    /// The ESA is working normally and can be controlled by the EMS
345    Online = 1,
346    /// The ESA has developed a fault and cannot provide service
347    Fault = 2,
348    /// The ESA is in the middle of a power adjustment event
349    PowerAdjustActive = 3,
350    /// The ESA is currently paused by a client using the PauseRequest command
351    Paused = 4,
352}
353
354impl ESAStateEnum {
355    /// Reads a wire value, or `None` for one this revision does not define.
356    #[must_use]
357    pub const fn from_value(value: u8) -> Option<Self> {
358        match value {
359            0 => Some(Self::Offline),
360            1 => Some(Self::Online),
361            2 => Some(Self::Fault),
362            3 => Some(Self::PowerAdjustActive),
363            4 => Some(Self::Paused),
364            _ => None,
365        }
366    }
367
368    /// Its wire value.
369    #[must_use]
370    pub const fn value(self) -> u8 {
371        self as u8
372    }
373}
374
375impl ToTlv for ESAStateEnum {
376    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
377        self.value().to_tlv(w, tag)
378    }
379}
380
381impl<'a> FromTlv<'a> for ESAStateEnum {
382    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
383        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
384        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
385    }
386}
387
388/// `ESATypeEnum`.
389#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
390#[repr(u8)]
391pub enum ESATypeEnum {
392    /// EV Supply Equipment
393    EVSE = 0,
394    /// Space heating appliance
395    SpaceHeating = 1,
396    /// Water heating appliance
397    WaterHeating = 2,
398    /// Space cooling appliance
399    SpaceCooling = 3,
400    /// Space heating and cooling appliance
401    SpaceHeatingCooling = 4,
402    /// Battery Electric Storage System
403    BatteryStorage = 5,
404    /// Solar PV inverter
405    SolarPV = 6,
406    /// Fridge / Freezer
407    FridgeFreezer = 7,
408    /// Washing Machine
409    WashingMachine = 8,
410    /// Dishwasher
411    Dishwasher = 9,
412    /// Cooking appliance
413    Cooking = 10,
414    /// Home water pump (e.g. drinking well)
415    HomeWaterPump = 11,
416    /// Irrigation water pump
417    IrrigationWaterPump = 12,
418    /// Pool pump
419    PoolPump = 13,
420    /// Other appliance type
421    Other = 255,
422}
423
424impl ESATypeEnum {
425    /// Reads a wire value, or `None` for one this revision does not define.
426    #[must_use]
427    pub const fn from_value(value: u8) -> Option<Self> {
428        match value {
429            0 => Some(Self::EVSE),
430            1 => Some(Self::SpaceHeating),
431            2 => Some(Self::WaterHeating),
432            3 => Some(Self::SpaceCooling),
433            4 => Some(Self::SpaceHeatingCooling),
434            5 => Some(Self::BatteryStorage),
435            6 => Some(Self::SolarPV),
436            7 => Some(Self::FridgeFreezer),
437            8 => Some(Self::WashingMachine),
438            9 => Some(Self::Dishwasher),
439            10 => Some(Self::Cooking),
440            11 => Some(Self::HomeWaterPump),
441            12 => Some(Self::IrrigationWaterPump),
442            13 => Some(Self::PoolPump),
443            255 => Some(Self::Other),
444            _ => None,
445        }
446    }
447
448    /// Its wire value.
449    #[must_use]
450    pub const fn value(self) -> u8 {
451        self as u8
452    }
453}
454
455impl ToTlv for ESATypeEnum {
456    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
457        self.value().to_tlv(w, tag)
458    }
459}
460
461impl<'a> FromTlv<'a> for ESATypeEnum {
462    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
463        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
464        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
465    }
466}
467
468/// `ForecastUpdateReasonEnum`.
469#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
470#[repr(u8)]
471pub enum ForecastUpdateReasonEnum {
472    /// The update was due to internal ESA device optimization
473    InternalOptimization = 0,
474    /// The update was due to local EMS optimization
475    LocalOptimization = 1,
476    /// The update was due to grid optimization
477    GridOptimization = 2,
478}
479
480impl ForecastUpdateReasonEnum {
481    /// Reads a wire value, or `None` for one this revision does not define.
482    #[must_use]
483    pub const fn from_value(value: u8) -> Option<Self> {
484        match value {
485            0 => Some(Self::InternalOptimization),
486            1 => Some(Self::LocalOptimization),
487            2 => Some(Self::GridOptimization),
488            _ => None,
489        }
490    }
491
492    /// Its wire value.
493    #[must_use]
494    pub const fn value(self) -> u8 {
495        self as u8
496    }
497}
498
499impl ToTlv for ForecastUpdateReasonEnum {
500    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
501        self.value().to_tlv(w, tag)
502    }
503}
504
505impl<'a> FromTlv<'a> for ForecastUpdateReasonEnum {
506    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
507        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
508        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
509    }
510}
511
512/// `OptOutStateEnum`.
513#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
514#[repr(u8)]
515pub enum OptOutStateEnum {
516    /// The user has not opted out of either local or grid optimizations
517    NoOptOut = 0,
518    /// The user has opted out of local EMS optimizations only
519    LocalOptOut = 1,
520    /// The user has opted out of grid EMS optimizations only
521    GridOptOut = 2,
522    /// The user has opted out of all external optimizations
523    OptOut = 3,
524}
525
526impl OptOutStateEnum {
527    /// Reads a wire value, or `None` for one this revision does not define.
528    #[must_use]
529    pub const fn from_value(value: u8) -> Option<Self> {
530        match value {
531            0 => Some(Self::NoOptOut),
532            1 => Some(Self::LocalOptOut),
533            2 => Some(Self::GridOptOut),
534            3 => Some(Self::OptOut),
535            _ => None,
536        }
537    }
538
539    /// Its wire value.
540    #[must_use]
541    pub const fn value(self) -> u8 {
542        self as u8
543    }
544}
545
546impl ToTlv for OptOutStateEnum {
547    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
548        self.value().to_tlv(w, tag)
549    }
550}
551
552impl<'a> FromTlv<'a> for OptOutStateEnum {
553    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
554        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
555        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
556    }
557}
558
559/// `PowerAdjustReasonEnum`.
560#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
561#[repr(u8)]
562pub enum PowerAdjustReasonEnum {
563    /// There is no Power Adjustment active
564    NoAdjustment = 0,
565    /// There is PowerAdjustment active due to local EMS optimization
566    LocalOptimizationAdjustment = 1,
567    /// There is PowerAdjustment active due to grid optimization
568    GridOptimizationAdjustment = 2,
569}
570
571impl PowerAdjustReasonEnum {
572    /// Reads a wire value, or `None` for one this revision does not define.
573    #[must_use]
574    pub const fn from_value(value: u8) -> Option<Self> {
575        match value {
576            0 => Some(Self::NoAdjustment),
577            1 => Some(Self::LocalOptimizationAdjustment),
578            2 => Some(Self::GridOptimizationAdjustment),
579            _ => None,
580        }
581    }
582
583    /// Its wire value.
584    #[must_use]
585    pub const fn value(self) -> u8 {
586        self as u8
587    }
588}
589
590impl ToTlv for PowerAdjustReasonEnum {
591    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
592        self.value().to_tlv(w, tag)
593    }
594}
595
596impl<'a> FromTlv<'a> for PowerAdjustReasonEnum {
597    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
598        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
599        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
600    }
601}
602
603/// `ConstraintsStruct`.
604#[derive(Debug, Clone, Copy, PartialEq)]
605pub struct ConstraintsStruct {
606    /// `StartTime`, field 0.
607    pub start_time: u32,
608    /// `Duration`, field 1.
609    pub duration: u32,
610    /// `NominalPower`, field 2.
611    pub nominal_power: Option<i32>,
612    /// `MaximumEnergy`, field 3.
613    pub maximum_energy: Option<i64>,
614    /// `LoadControl`, field 4.
615    pub load_control: Option<i8>,
616}
617
618impl ToTlv for ConstraintsStruct {
619    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
620        w.start_structure(tag)?;
621        self.start_time.to_tlv(w, Tag::Context(0))?;
622        self.duration.to_tlv(w, Tag::Context(1))?;
623        if let Some(value) = &self.nominal_power {
624            value.to_tlv(w, Tag::Context(2))?;
625        }
626        if let Some(value) = &self.maximum_energy {
627            value.to_tlv(w, Tag::Context(3))?;
628        }
629        if let Some(value) = &self.load_control {
630            value.to_tlv(w, Tag::Context(4))?;
631        }
632        w.end_container()
633    }
634}
635
636impl<'a> FromTlv<'a> for ConstraintsStruct {
637    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
638        if element.value.container() != Some(ContainerKind::Structure) {
639            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
640        }
641        let mut start_time = None;
642        let mut duration = None;
643        let mut nominal_power = None;
644        let mut maximum_energy = None;
645        let mut load_control = None;
646        loop {
647            let Some(field) = reader.next_element()? else {
648                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
649            };
650            if field.value == Value::EndOfContainer {
651                break;
652            }
653            match field.tag.context() {
654                Some(0) => start_time = Some(<u32>::from_tlv(reader, &field)?),
655                Some(1) => duration = Some(<u32>::from_tlv(reader, &field)?),
656                Some(2) => nominal_power = Some(<i32>::from_tlv(reader, &field)?),
657                Some(3) => maximum_energy = Some(<i64>::from_tlv(reader, &field)?),
658                Some(4) => load_control = Some(<i8>::from_tlv(reader, &field)?),
659                // A field this revision does not define. §7.19.2: a receiver
660                // ignores what it does not know rather than refusing the whole
661                // structure, which is what lets a newer peer talk to an older one.
662                _ => reader.skip_value(&field)?,
663            }
664        }
665        Ok(Self {
666            start_time: start_time.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
667            duration: duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
668            nominal_power,
669            maximum_energy,
670            load_control,
671        })
672    }
673}
674
675/// `CostStruct`.
676#[derive(Debug, Clone, Copy, PartialEq)]
677pub struct CostStruct {
678    /// `CostType`, field 0.
679    pub cost_type: CostTypeEnum,
680    /// `Value`, field 1.
681    pub value: i32,
682    /// `DecimalPoints`, field 2.
683    pub decimal_points: u8,
684    /// `Currency`, field 3.
685    pub currency: Option<u16>,
686}
687
688impl ToTlv for CostStruct {
689    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
690        w.start_structure(tag)?;
691        self.cost_type.to_tlv(w, Tag::Context(0))?;
692        self.value.to_tlv(w, Tag::Context(1))?;
693        self.decimal_points.to_tlv(w, Tag::Context(2))?;
694        if let Some(value) = &self.currency {
695            value.to_tlv(w, Tag::Context(3))?;
696        }
697        w.end_container()
698    }
699}
700
701impl<'a> FromTlv<'a> for CostStruct {
702    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
703        if element.value.container() != Some(ContainerKind::Structure) {
704            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
705        }
706        let mut cost_type = None;
707        let mut value = None;
708        let mut decimal_points = None;
709        let mut currency = None;
710        loop {
711            let Some(field) = reader.next_element()? else {
712                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
713            };
714            if field.value == Value::EndOfContainer {
715                break;
716            }
717            match field.tag.context() {
718                Some(0) => cost_type = Some(<CostTypeEnum>::from_tlv(reader, &field)?),
719                Some(1) => value = Some(<i32>::from_tlv(reader, &field)?),
720                Some(2) => decimal_points = Some(<u8>::from_tlv(reader, &field)?),
721                Some(3) => currency = Some(<u16>::from_tlv(reader, &field)?),
722                // A field this revision does not define. §7.19.2: a receiver
723                // ignores what it does not know rather than refusing the whole
724                // structure, which is what lets a newer peer talk to an older one.
725                _ => reader.skip_value(&field)?,
726            }
727        }
728        Ok(Self {
729            cost_type: cost_type.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
730            value: value.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
731            decimal_points: decimal_points
732                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
733            currency,
734        })
735    }
736}
737
738/// `ForecastStruct`.
739#[derive(Debug, Clone, Copy, PartialEq)]
740pub struct ForecastStruct<'a> {
741    /// `ForecastID`, field 0.
742    pub forecast_id: u32,
743    /// `ActiveSlotNumber`, field 1.
744    pub active_slot_number: Nullable<u16>,
745    /// `StartTime`, field 2.
746    pub start_time: u32,
747    /// `EndTime`, field 3.
748    pub end_time: u32,
749    /// `EarliestStartTime`, field 4.
750    pub earliest_start_time: Option<Nullable<u32>>,
751    /// `LatestEndTime`, field 5.
752    pub latest_end_time: Option<u32>,
753    /// `IsPausable`, field 6.
754    pub is_pausable: bool,
755    /// `Slots`, field 7.
756    pub slots: TlvList<'a, SlotStruct<'a>>,
757    /// `ForecastUpdateReason`, field 8.
758    pub forecast_update_reason: ForecastUpdateReasonEnum,
759}
760
761impl<'a> ToTlv for ForecastStruct<'a> {
762    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
763        w.start_structure(tag)?;
764        self.forecast_id.to_tlv(w, Tag::Context(0))?;
765        self.active_slot_number.to_tlv(w, Tag::Context(1))?;
766        self.start_time.to_tlv(w, Tag::Context(2))?;
767        self.end_time.to_tlv(w, Tag::Context(3))?;
768        if let Some(value) = &self.earliest_start_time {
769            value.to_tlv(w, Tag::Context(4))?;
770        }
771        if let Some(value) = &self.latest_end_time {
772            value.to_tlv(w, Tag::Context(5))?;
773        }
774        self.is_pausable.to_tlv(w, Tag::Context(6))?;
775        self.slots.to_tlv(w, Tag::Context(7))?;
776        self.forecast_update_reason.to_tlv(w, Tag::Context(8))?;
777        w.end_container()
778    }
779}
780
781impl<'a> FromTlv<'a> for ForecastStruct<'a> {
782    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
783        if element.value.container() != Some(ContainerKind::Structure) {
784            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
785        }
786        let mut forecast_id = None;
787        let mut active_slot_number = None;
788        let mut start_time = None;
789        let mut end_time = None;
790        let mut earliest_start_time = None;
791        let mut latest_end_time = None;
792        let mut is_pausable = None;
793        let mut slots = None;
794        let mut forecast_update_reason = None;
795        loop {
796            let Some(field) = reader.next_element()? else {
797                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
798            };
799            if field.value == Value::EndOfContainer {
800                break;
801            }
802            match field.tag.context() {
803                Some(0) => forecast_id = Some(<u32>::from_tlv(reader, &field)?),
804                Some(1) => active_slot_number = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
805                Some(2) => start_time = Some(<u32>::from_tlv(reader, &field)?),
806                Some(3) => end_time = Some(<u32>::from_tlv(reader, &field)?),
807                Some(4) => earliest_start_time = Some(<Nullable<u32>>::from_tlv(reader, &field)?),
808                Some(5) => latest_end_time = Some(<u32>::from_tlv(reader, &field)?),
809                Some(6) => is_pausable = Some(<bool>::from_tlv(reader, &field)?),
810                Some(7) => slots = Some(<TlvList<'a, SlotStruct<'a>>>::from_tlv(reader, &field)?),
811                Some(8) => {
812                    forecast_update_reason =
813                        Some(<ForecastUpdateReasonEnum>::from_tlv(reader, &field)?)
814                }
815                // A field this revision does not define. §7.19.2: a receiver
816                // ignores what it does not know rather than refusing the whole
817                // structure, which is what lets a newer peer talk to an older one.
818                _ => reader.skip_value(&field)?,
819            }
820        }
821        Ok(Self {
822            forecast_id: forecast_id.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
823            active_slot_number: active_slot_number
824                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
825            start_time: start_time.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
826            end_time: end_time.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
827            earliest_start_time,
828            latest_end_time,
829            is_pausable: is_pausable.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
830            slots: slots.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
831            forecast_update_reason: forecast_update_reason
832                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
833        })
834    }
835}
836
837/// `PowerAdjustCapabilityStruct`.
838#[derive(Debug, Clone, Copy, PartialEq)]
839pub struct PowerAdjustCapabilityStruct<'a> {
840    /// `PowerAdjustCapability`, field 0.
841    pub power_adjust_capability: Nullable<TlvList<'a, PowerAdjustStruct>>,
842    /// `Cause`, field 1.
843    pub cause: PowerAdjustReasonEnum,
844}
845
846impl<'a> ToTlv for PowerAdjustCapabilityStruct<'a> {
847    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
848        w.start_structure(tag)?;
849        self.power_adjust_capability.to_tlv(w, Tag::Context(0))?;
850        self.cause.to_tlv(w, Tag::Context(1))?;
851        w.end_container()
852    }
853}
854
855impl<'a> FromTlv<'a> for PowerAdjustCapabilityStruct<'a> {
856    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
857        if element.value.container() != Some(ContainerKind::Structure) {
858            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
859        }
860        let mut power_adjust_capability = None;
861        let mut cause = None;
862        loop {
863            let Some(field) = reader.next_element()? else {
864                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
865            };
866            if field.value == Value::EndOfContainer {
867                break;
868            }
869            match field.tag.context() {
870                Some(0) => {
871                    power_adjust_capability = Some(
872                        <Nullable<TlvList<'a, PowerAdjustStruct>>>::from_tlv(reader, &field)?,
873                    )
874                }
875                Some(1) => cause = Some(<PowerAdjustReasonEnum>::from_tlv(reader, &field)?),
876                // A field this revision does not define. §7.19.2: a receiver
877                // ignores what it does not know rather than refusing the whole
878                // structure, which is what lets a newer peer talk to an older one.
879                _ => reader.skip_value(&field)?,
880            }
881        }
882        Ok(Self {
883            power_adjust_capability: power_adjust_capability
884                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
885            cause: cause.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
886        })
887    }
888}
889
890/// `PowerAdjustStruct`.
891#[derive(Debug, Clone, Copy, PartialEq)]
892pub struct PowerAdjustStruct {
893    /// `MinPower`, field 0.
894    pub min_power: i32,
895    /// `MaxPower`, field 1.
896    pub max_power: i32,
897    /// `MinDuration`, field 2.
898    pub min_duration: u32,
899    /// `MaxDuration`, field 3.
900    pub max_duration: u32,
901}
902
903impl ToTlv for PowerAdjustStruct {
904    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
905        w.start_structure(tag)?;
906        self.min_power.to_tlv(w, Tag::Context(0))?;
907        self.max_power.to_tlv(w, Tag::Context(1))?;
908        self.min_duration.to_tlv(w, Tag::Context(2))?;
909        self.max_duration.to_tlv(w, Tag::Context(3))?;
910        w.end_container()
911    }
912}
913
914impl<'a> FromTlv<'a> for PowerAdjustStruct {
915    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
916        if element.value.container() != Some(ContainerKind::Structure) {
917            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
918        }
919        let mut min_power = None;
920        let mut max_power = None;
921        let mut min_duration = None;
922        let mut max_duration = None;
923        loop {
924            let Some(field) = reader.next_element()? else {
925                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
926            };
927            if field.value == Value::EndOfContainer {
928                break;
929            }
930            match field.tag.context() {
931                Some(0) => min_power = Some(<i32>::from_tlv(reader, &field)?),
932                Some(1) => max_power = Some(<i32>::from_tlv(reader, &field)?),
933                Some(2) => min_duration = Some(<u32>::from_tlv(reader, &field)?),
934                Some(3) => max_duration = Some(<u32>::from_tlv(reader, &field)?),
935                // A field this revision does not define. §7.19.2: a receiver
936                // ignores what it does not know rather than refusing the whole
937                // structure, which is what lets a newer peer talk to an older one.
938                _ => reader.skip_value(&field)?,
939            }
940        }
941        Ok(Self {
942            min_power: min_power.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
943            max_power: max_power.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
944            min_duration: min_duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
945            max_duration: max_duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
946        })
947    }
948}
949
950/// `SlotAdjustmentStruct`.
951#[derive(Debug, Clone, Copy, PartialEq)]
952pub struct SlotAdjustmentStruct {
953    /// `SlotIndex`, field 0.
954    pub slot_index: u8,
955    /// `NominalPower`, field 1.
956    pub nominal_power: Option<i32>,
957    /// `Duration`, field 2.
958    pub duration: u32,
959}
960
961impl ToTlv for SlotAdjustmentStruct {
962    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
963        w.start_structure(tag)?;
964        self.slot_index.to_tlv(w, Tag::Context(0))?;
965        if let Some(value) = &self.nominal_power {
966            value.to_tlv(w, Tag::Context(1))?;
967        }
968        self.duration.to_tlv(w, Tag::Context(2))?;
969        w.end_container()
970    }
971}
972
973impl<'a> FromTlv<'a> for SlotAdjustmentStruct {
974    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
975        if element.value.container() != Some(ContainerKind::Structure) {
976            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
977        }
978        let mut slot_index = None;
979        let mut nominal_power = None;
980        let mut duration = None;
981        loop {
982            let Some(field) = reader.next_element()? else {
983                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
984            };
985            if field.value == Value::EndOfContainer {
986                break;
987            }
988            match field.tag.context() {
989                Some(0) => slot_index = Some(<u8>::from_tlv(reader, &field)?),
990                Some(1) => nominal_power = Some(<i32>::from_tlv(reader, &field)?),
991                Some(2) => duration = Some(<u32>::from_tlv(reader, &field)?),
992                // A field this revision does not define. §7.19.2: a receiver
993                // ignores what it does not know rather than refusing the whole
994                // structure, which is what lets a newer peer talk to an older one.
995                _ => reader.skip_value(&field)?,
996            }
997        }
998        Ok(Self {
999            slot_index: slot_index.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1000            nominal_power,
1001            duration: duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1002        })
1003    }
1004}
1005
1006/// `SlotStruct`.
1007#[derive(Debug, Clone, Copy, PartialEq)]
1008pub struct SlotStruct<'a> {
1009    /// `MinDuration`, field 0.
1010    pub min_duration: u32,
1011    /// `MaxDuration`, field 1.
1012    pub max_duration: u32,
1013    /// `DefaultDuration`, field 2.
1014    pub default_duration: u32,
1015    /// `ElapsedSlotTime`, field 3.
1016    pub elapsed_slot_time: u32,
1017    /// `RemainingSlotTime`, field 4.
1018    pub remaining_slot_time: u32,
1019    /// `SlotIsPausable`, field 5.
1020    pub slot_is_pausable: Option<bool>,
1021    /// `MinPauseDuration`, field 6.
1022    pub min_pause_duration: Option<u32>,
1023    /// `MaxPauseDuration`, field 7.
1024    pub max_pause_duration: Option<u32>,
1025    /// `ManufacturerESAState`, field 8.
1026    pub manufacturer_esa_state: Option<u16>,
1027    /// `NominalPower`, field 9.
1028    pub nominal_power: Option<i32>,
1029    /// `MinPower`, field 10.
1030    pub min_power: Option<i32>,
1031    /// `MaxPower`, field 11.
1032    pub max_power: Option<i32>,
1033    /// `NominalEnergy`, field 12.
1034    pub nominal_energy: Option<i64>,
1035    /// `Costs`, field 13.
1036    pub costs: Option<TlvList<'a, CostStruct>>,
1037    /// `MinPowerAdjustment`, field 14.
1038    pub min_power_adjustment: Option<i32>,
1039    /// `MaxPowerAdjustment`, field 15.
1040    pub max_power_adjustment: Option<i32>,
1041    /// `MinDurationAdjustment`, field 16.
1042    pub min_duration_adjustment: Option<u32>,
1043    /// `MaxDurationAdjustment`, field 17.
1044    pub max_duration_adjustment: Option<u32>,
1045}
1046
1047impl<'a> ToTlv for SlotStruct<'a> {
1048    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
1049        w.start_structure(tag)?;
1050        self.min_duration.to_tlv(w, Tag::Context(0))?;
1051        self.max_duration.to_tlv(w, Tag::Context(1))?;
1052        self.default_duration.to_tlv(w, Tag::Context(2))?;
1053        self.elapsed_slot_time.to_tlv(w, Tag::Context(3))?;
1054        self.remaining_slot_time.to_tlv(w, Tag::Context(4))?;
1055        if let Some(value) = &self.slot_is_pausable {
1056            value.to_tlv(w, Tag::Context(5))?;
1057        }
1058        if let Some(value) = &self.min_pause_duration {
1059            value.to_tlv(w, Tag::Context(6))?;
1060        }
1061        if let Some(value) = &self.max_pause_duration {
1062            value.to_tlv(w, Tag::Context(7))?;
1063        }
1064        if let Some(value) = &self.manufacturer_esa_state {
1065            value.to_tlv(w, Tag::Context(8))?;
1066        }
1067        if let Some(value) = &self.nominal_power {
1068            value.to_tlv(w, Tag::Context(9))?;
1069        }
1070        if let Some(value) = &self.min_power {
1071            value.to_tlv(w, Tag::Context(10))?;
1072        }
1073        if let Some(value) = &self.max_power {
1074            value.to_tlv(w, Tag::Context(11))?;
1075        }
1076        if let Some(value) = &self.nominal_energy {
1077            value.to_tlv(w, Tag::Context(12))?;
1078        }
1079        if let Some(value) = &self.costs {
1080            value.to_tlv(w, Tag::Context(13))?;
1081        }
1082        if let Some(value) = &self.min_power_adjustment {
1083            value.to_tlv(w, Tag::Context(14))?;
1084        }
1085        if let Some(value) = &self.max_power_adjustment {
1086            value.to_tlv(w, Tag::Context(15))?;
1087        }
1088        if let Some(value) = &self.min_duration_adjustment {
1089            value.to_tlv(w, Tag::Context(16))?;
1090        }
1091        if let Some(value) = &self.max_duration_adjustment {
1092            value.to_tlv(w, Tag::Context(17))?;
1093        }
1094        w.end_container()
1095    }
1096}
1097
1098impl<'a> FromTlv<'a> for SlotStruct<'a> {
1099    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
1100        if element.value.container() != Some(ContainerKind::Structure) {
1101            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
1102        }
1103        let mut min_duration = None;
1104        let mut max_duration = None;
1105        let mut default_duration = None;
1106        let mut elapsed_slot_time = None;
1107        let mut remaining_slot_time = None;
1108        let mut slot_is_pausable = None;
1109        let mut min_pause_duration = None;
1110        let mut max_pause_duration = None;
1111        let mut manufacturer_esa_state = None;
1112        let mut nominal_power = None;
1113        let mut min_power = None;
1114        let mut max_power = None;
1115        let mut nominal_energy = None;
1116        let mut costs = None;
1117        let mut min_power_adjustment = None;
1118        let mut max_power_adjustment = None;
1119        let mut min_duration_adjustment = None;
1120        let mut max_duration_adjustment = None;
1121        loop {
1122            let Some(field) = reader.next_element()? else {
1123                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
1124            };
1125            if field.value == Value::EndOfContainer {
1126                break;
1127            }
1128            match field.tag.context() {
1129                Some(0) => min_duration = Some(<u32>::from_tlv(reader, &field)?),
1130                Some(1) => max_duration = Some(<u32>::from_tlv(reader, &field)?),
1131                Some(2) => default_duration = Some(<u32>::from_tlv(reader, &field)?),
1132                Some(3) => elapsed_slot_time = Some(<u32>::from_tlv(reader, &field)?),
1133                Some(4) => remaining_slot_time = Some(<u32>::from_tlv(reader, &field)?),
1134                Some(5) => slot_is_pausable = Some(<bool>::from_tlv(reader, &field)?),
1135                Some(6) => min_pause_duration = Some(<u32>::from_tlv(reader, &field)?),
1136                Some(7) => max_pause_duration = Some(<u32>::from_tlv(reader, &field)?),
1137                Some(8) => manufacturer_esa_state = Some(<u16>::from_tlv(reader, &field)?),
1138                Some(9) => nominal_power = Some(<i32>::from_tlv(reader, &field)?),
1139                Some(10) => min_power = Some(<i32>::from_tlv(reader, &field)?),
1140                Some(11) => max_power = Some(<i32>::from_tlv(reader, &field)?),
1141                Some(12) => nominal_energy = Some(<i64>::from_tlv(reader, &field)?),
1142                Some(13) => costs = Some(<TlvList<'a, CostStruct>>::from_tlv(reader, &field)?),
1143                Some(14) => min_power_adjustment = Some(<i32>::from_tlv(reader, &field)?),
1144                Some(15) => max_power_adjustment = Some(<i32>::from_tlv(reader, &field)?),
1145                Some(16) => min_duration_adjustment = Some(<u32>::from_tlv(reader, &field)?),
1146                Some(17) => max_duration_adjustment = Some(<u32>::from_tlv(reader, &field)?),
1147                // A field this revision does not define. §7.19.2: a receiver
1148                // ignores what it does not know rather than refusing the whole
1149                // structure, which is what lets a newer peer talk to an older one.
1150                _ => reader.skip_value(&field)?,
1151            }
1152        }
1153        Ok(Self {
1154            min_duration: min_duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1155            max_duration: max_duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1156            default_duration: default_duration
1157                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1158            elapsed_slot_time: elapsed_slot_time
1159                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1160            remaining_slot_time: remaining_slot_time
1161                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1162            slot_is_pausable,
1163            min_pause_duration,
1164            max_pause_duration,
1165            manufacturer_esa_state,
1166            nominal_power,
1167            min_power,
1168            max_power,
1169            nominal_energy,
1170            costs,
1171            min_power_adjustment,
1172            max_power_adjustment,
1173            min_duration_adjustment,
1174            max_duration_adjustment,
1175        })
1176    }
1177}
1178
1179/// The fields of `PowerAdjustRequest` (command `0x00`).
1180#[derive(Debug, Clone, Copy, PartialEq)]
1181pub struct PowerAdjustRequestFields {
1182    /// `Power`, field 0.
1183    pub power: i32,
1184    /// `Duration`, field 1.
1185    pub duration: u32,
1186    /// `Cause`, field 2.
1187    pub cause: AdjustmentCauseEnum,
1188}
1189
1190impl ToTlv for PowerAdjustRequestFields {
1191    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
1192        w.start_structure(tag)?;
1193        self.power.to_tlv(w, Tag::Context(0))?;
1194        self.duration.to_tlv(w, Tag::Context(1))?;
1195        self.cause.to_tlv(w, Tag::Context(2))?;
1196        w.end_container()
1197    }
1198}
1199
1200impl<'a> FromTlv<'a> for PowerAdjustRequestFields {
1201    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
1202        if element.value.container() != Some(ContainerKind::Structure) {
1203            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
1204        }
1205        let mut power = None;
1206        let mut duration = None;
1207        let mut cause = None;
1208        loop {
1209            let Some(field) = reader.next_element()? else {
1210                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
1211            };
1212            if field.value == Value::EndOfContainer {
1213                break;
1214            }
1215            match field.tag.context() {
1216                Some(0) => power = Some(<i32>::from_tlv(reader, &field)?),
1217                Some(1) => duration = Some(<u32>::from_tlv(reader, &field)?),
1218                Some(2) => cause = Some(<AdjustmentCauseEnum>::from_tlv(reader, &field)?),
1219                // A field this revision does not define. §7.19.2: a receiver
1220                // ignores what it does not know rather than refusing the whole
1221                // structure, which is what lets a newer peer talk to an older one.
1222                _ => reader.skip_value(&field)?,
1223            }
1224        }
1225        Ok(Self {
1226            power: power.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1227            duration: duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1228            cause: cause.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1229        })
1230    }
1231}
1232
1233/// The fields of `StartTimeAdjustRequest` (command `0x02`).
1234#[derive(Debug, Clone, Copy, PartialEq)]
1235pub struct StartTimeAdjustRequestFields {
1236    /// `RequestedStartTime`, field 0.
1237    pub requested_start_time: u32,
1238    /// `Cause`, field 1.
1239    pub cause: AdjustmentCauseEnum,
1240}
1241
1242impl ToTlv for StartTimeAdjustRequestFields {
1243    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
1244        w.start_structure(tag)?;
1245        self.requested_start_time.to_tlv(w, Tag::Context(0))?;
1246        self.cause.to_tlv(w, Tag::Context(1))?;
1247        w.end_container()
1248    }
1249}
1250
1251impl<'a> FromTlv<'a> for StartTimeAdjustRequestFields {
1252    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
1253        if element.value.container() != Some(ContainerKind::Structure) {
1254            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
1255        }
1256        let mut requested_start_time = None;
1257        let mut cause = None;
1258        loop {
1259            let Some(field) = reader.next_element()? else {
1260                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
1261            };
1262            if field.value == Value::EndOfContainer {
1263                break;
1264            }
1265            match field.tag.context() {
1266                Some(0) => requested_start_time = Some(<u32>::from_tlv(reader, &field)?),
1267                Some(1) => cause = Some(<AdjustmentCauseEnum>::from_tlv(reader, &field)?),
1268                // A field this revision does not define. §7.19.2: a receiver
1269                // ignores what it does not know rather than refusing the whole
1270                // structure, which is what lets a newer peer talk to an older one.
1271                _ => reader.skip_value(&field)?,
1272            }
1273        }
1274        Ok(Self {
1275            requested_start_time: requested_start_time
1276                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1277            cause: cause.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1278        })
1279    }
1280}
1281
1282/// The fields of `PauseRequest` (command `0x03`).
1283#[derive(Debug, Clone, Copy, PartialEq)]
1284pub struct PauseRequestFields {
1285    /// `Duration`, field 0.
1286    pub duration: u32,
1287    /// `Cause`, field 1.
1288    pub cause: AdjustmentCauseEnum,
1289}
1290
1291impl ToTlv for PauseRequestFields {
1292    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
1293        w.start_structure(tag)?;
1294        self.duration.to_tlv(w, Tag::Context(0))?;
1295        self.cause.to_tlv(w, Tag::Context(1))?;
1296        w.end_container()
1297    }
1298}
1299
1300impl<'a> FromTlv<'a> for PauseRequestFields {
1301    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
1302        if element.value.container() != Some(ContainerKind::Structure) {
1303            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
1304        }
1305        let mut duration = None;
1306        let mut cause = None;
1307        loop {
1308            let Some(field) = reader.next_element()? else {
1309                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
1310            };
1311            if field.value == Value::EndOfContainer {
1312                break;
1313            }
1314            match field.tag.context() {
1315                Some(0) => duration = Some(<u32>::from_tlv(reader, &field)?),
1316                Some(1) => cause = Some(<AdjustmentCauseEnum>::from_tlv(reader, &field)?),
1317                // A field this revision does not define. §7.19.2: a receiver
1318                // ignores what it does not know rather than refusing the whole
1319                // structure, which is what lets a newer peer talk to an older one.
1320                _ => reader.skip_value(&field)?,
1321            }
1322        }
1323        Ok(Self {
1324            duration: duration.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1325            cause: cause.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1326        })
1327    }
1328}
1329
1330/// The fields of `ModifyForecastRequest` (command `0x05`).
1331#[derive(Debug, Clone, Copy, PartialEq)]
1332pub struct ModifyForecastRequestFields<'a> {
1333    /// `ForecastID`, field 0.
1334    pub forecast_id: u32,
1335    /// `SlotAdjustments`, field 1.
1336    pub slot_adjustments: TlvList<'a, SlotAdjustmentStruct>,
1337    /// `Cause`, field 2.
1338    pub cause: AdjustmentCauseEnum,
1339}
1340
1341impl<'a> ToTlv for ModifyForecastRequestFields<'a> {
1342    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
1343        w.start_structure(tag)?;
1344        self.forecast_id.to_tlv(w, Tag::Context(0))?;
1345        self.slot_adjustments.to_tlv(w, Tag::Context(1))?;
1346        self.cause.to_tlv(w, Tag::Context(2))?;
1347        w.end_container()
1348    }
1349}
1350
1351impl<'a> FromTlv<'a> for ModifyForecastRequestFields<'a> {
1352    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
1353        if element.value.container() != Some(ContainerKind::Structure) {
1354            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
1355        }
1356        let mut forecast_id = None;
1357        let mut slot_adjustments = None;
1358        let mut cause = None;
1359        loop {
1360            let Some(field) = reader.next_element()? else {
1361                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
1362            };
1363            if field.value == Value::EndOfContainer {
1364                break;
1365            }
1366            match field.tag.context() {
1367                Some(0) => forecast_id = Some(<u32>::from_tlv(reader, &field)?),
1368                Some(1) => {
1369                    slot_adjustments = Some(<TlvList<'a, SlotAdjustmentStruct>>::from_tlv(
1370                        reader, &field,
1371                    )?)
1372                }
1373                Some(2) => cause = Some(<AdjustmentCauseEnum>::from_tlv(reader, &field)?),
1374                // A field this revision does not define. §7.19.2: a receiver
1375                // ignores what it does not know rather than refusing the whole
1376                // structure, which is what lets a newer peer talk to an older one.
1377                _ => reader.skip_value(&field)?,
1378            }
1379        }
1380        Ok(Self {
1381            forecast_id: forecast_id.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1382            slot_adjustments: slot_adjustments
1383                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1384            cause: cause.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1385        })
1386    }
1387}
1388
1389/// The fields of `RequestConstraintBasedForecast` (command `0x06`).
1390#[derive(Debug, Clone, Copy, PartialEq)]
1391pub struct RequestConstraintBasedForecastFields<'a> {
1392    /// `Constraints`, field 0.
1393    pub constraints: TlvList<'a, ConstraintsStruct>,
1394    /// `Cause`, field 1.
1395    pub cause: AdjustmentCauseEnum,
1396}
1397
1398impl<'a> ToTlv for RequestConstraintBasedForecastFields<'a> {
1399    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
1400        w.start_structure(tag)?;
1401        self.constraints.to_tlv(w, Tag::Context(0))?;
1402        self.cause.to_tlv(w, Tag::Context(1))?;
1403        w.end_container()
1404    }
1405}
1406
1407impl<'a> FromTlv<'a> for RequestConstraintBasedForecastFields<'a> {
1408    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
1409        if element.value.container() != Some(ContainerKind::Structure) {
1410            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
1411        }
1412        let mut constraints = None;
1413        let mut cause = None;
1414        loop {
1415            let Some(field) = reader.next_element()? else {
1416                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
1417            };
1418            if field.value == Value::EndOfContainer {
1419                break;
1420            }
1421            match field.tag.context() {
1422                Some(0) => {
1423                    constraints = Some(<TlvList<'a, ConstraintsStruct>>::from_tlv(reader, &field)?)
1424                }
1425                Some(1) => cause = Some(<AdjustmentCauseEnum>::from_tlv(reader, &field)?),
1426                // A field this revision does not define. §7.19.2: a receiver
1427                // ignores what it does not know rather than refusing the whole
1428                // structure, which is what lets a newer peer talk to an older one.
1429                _ => reader.skip_value(&field)?,
1430            }
1431        }
1432        Ok(Self {
1433            constraints: constraints.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1434            cause: cause.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
1435        })
1436    }
1437}
1438
1439/// Every attribute the specification defines, with its conformance.
1440pub const ATTRIBUTES: &[Attribute] = &[
1441    Attribute {
1442        id: 0x0000,
1443        name: "ESAType",
1444        kind: "ESATypeEnum",
1445        access: Access::read_only(Privilege::View),
1446        qualities: AttributeQualities::FIXED,
1447        reporting: Reporting::OnChange,
1448        conform: Conform::MANDATORY,
1449    },
1450    Attribute {
1451        id: 0x0001,
1452        name: "ESACanGenerate",
1453        kind: "bool",
1454        access: Access::read_only(Privilege::View),
1455        qualities: AttributeQualities::FIXED,
1456        reporting: Reporting::OnChange,
1457        conform: Conform::MANDATORY,
1458    },
1459    Attribute {
1460        id: 0x0002,
1461        name: "ESAState",
1462        kind: "ESAStateEnum",
1463        access: Access::read_only(Privilege::View),
1464        qualities: AttributeQualities::empty(),
1465        reporting: Reporting::OnChange,
1466        conform: Conform::MANDATORY,
1467    },
1468    Attribute {
1469        id: 0x0003,
1470        name: "AbsMinPower",
1471        kind: "power-mW",
1472        access: Access::read_only(Privilege::View),
1473        qualities: AttributeQualities::empty(),
1474        reporting: Reporting::OnChange,
1475        conform: Conform::MANDATORY,
1476    },
1477    Attribute {
1478        id: 0x0004,
1479        name: "AbsMaxPower",
1480        kind: "power-mW",
1481        access: Access::read_only(Privilege::View),
1482        qualities: AttributeQualities::empty(),
1483        reporting: Reporting::OnChange,
1484        conform: Conform::MANDATORY,
1485    },
1486    Attribute {
1487        id: 0x0005,
1488        name: "PowerAdjustmentCapability",
1489        kind: "PowerAdjustCapabilityStruct",
1490        access: Access::read_only(Privilege::View),
1491        qualities: AttributeQualities::NULLABLE,
1492        reporting: Reporting::Quieter,
1493        conform: Conform {
1494            clauses: &[Clause {
1495                verdict: Conformance::Mandatory,
1496                when: Condition::Feature(0),
1497            }],
1498        },
1499    },
1500    Attribute {
1501        id: 0x0006,
1502        name: "Forecast",
1503        kind: "ForecastStruct",
1504        access: Access::read_only(Privilege::View),
1505        qualities: AttributeQualities::NULLABLE,
1506        reporting: Reporting::Quieter,
1507        conform: Conform {
1508            clauses: &[Clause {
1509                verdict: Conformance::Mandatory,
1510                when: Condition::Any(&[Condition::Feature(1), Condition::Feature(2)]),
1511            }],
1512        },
1513    },
1514    Attribute {
1515        id: 0x0007,
1516        name: "OptOutState",
1517        kind: "OptOutStateEnum",
1518        access: Access::read_only(Privilege::View),
1519        qualities: AttributeQualities::empty(),
1520        reporting: Reporting::OnChange,
1521        conform: Conform {
1522            clauses: &[Clause {
1523                verdict: Conformance::Mandatory,
1524                when: Condition::Any(&[
1525                    Condition::Feature(0),
1526                    Condition::Feature(3),
1527                    Condition::Feature(4),
1528                    Condition::Feature(5),
1529                    Condition::Feature(6),
1530                ]),
1531            }],
1532        },
1533    },
1534];
1535
1536/// Every command, with its conformance.
1537pub const COMMANDS: &[Command] = &[
1538    Command {
1539        id: 0x00,
1540        name: "PowerAdjustRequest",
1541        to_server: true,
1542        response: None,
1543        access: Access::invoke(Privilege::Operate),
1544        conform: Conform {
1545            clauses: &[Clause {
1546                verdict: Conformance::Mandatory,
1547                when: Condition::Feature(0),
1548            }],
1549        },
1550    },
1551    Command {
1552        id: 0x01,
1553        name: "CancelPowerAdjustRequest",
1554        to_server: true,
1555        response: None,
1556        access: Access::invoke(Privilege::Operate),
1557        conform: Conform {
1558            clauses: &[Clause {
1559                verdict: Conformance::Mandatory,
1560                when: Condition::Feature(0),
1561            }],
1562        },
1563    },
1564    Command {
1565        id: 0x02,
1566        name: "StartTimeAdjustRequest",
1567        to_server: true,
1568        response: None,
1569        access: Access::invoke(Privilege::Operate),
1570        conform: Conform {
1571            clauses: &[Clause {
1572                verdict: Conformance::Mandatory,
1573                when: Condition::Feature(3),
1574            }],
1575        },
1576    },
1577    Command {
1578        id: 0x03,
1579        name: "PauseRequest",
1580        to_server: true,
1581        response: None,
1582        access: Access::invoke(Privilege::Operate),
1583        conform: Conform {
1584            clauses: &[Clause {
1585                verdict: Conformance::Mandatory,
1586                when: Condition::Feature(4),
1587            }],
1588        },
1589    },
1590    Command {
1591        id: 0x04,
1592        name: "ResumeRequest",
1593        to_server: true,
1594        response: None,
1595        access: Access::invoke(Privilege::Operate),
1596        conform: Conform {
1597            clauses: &[Clause {
1598                verdict: Conformance::Mandatory,
1599                when: Condition::Feature(4),
1600            }],
1601        },
1602    },
1603    Command {
1604        id: 0x05,
1605        name: "ModifyForecastRequest",
1606        to_server: true,
1607        response: None,
1608        access: Access::invoke(Privilege::Operate),
1609        conform: Conform {
1610            clauses: &[Clause {
1611                verdict: Conformance::Mandatory,
1612                when: Condition::Feature(5),
1613            }],
1614        },
1615    },
1616    Command {
1617        id: 0x06,
1618        name: "RequestConstraintBasedForecast",
1619        to_server: true,
1620        response: None,
1621        access: Access::invoke(Privilege::Operate),
1622        conform: Conform {
1623            clauses: &[Clause {
1624                verdict: Conformance::Mandatory,
1625                when: Condition::Feature(6),
1626            }],
1627        },
1628    },
1629    Command {
1630        id: 0x07,
1631        name: "CancelRequest",
1632        to_server: true,
1633        response: None,
1634        access: Access::invoke(Privilege::Operate),
1635        conform: Conform {
1636            clauses: &[Clause {
1637                verdict: Conformance::Mandatory,
1638                when: Condition::Any(&[
1639                    Condition::Feature(3),
1640                    Condition::Feature(5),
1641                    Condition::Feature(6),
1642                ]),
1643            }],
1644        },
1645    },
1646];
1647
1648/// Every event, with its conformance.
1649pub const EVENTS: &[Event] = &[
1650    Event {
1651        id: 0x00,
1652        name: "PowerAdjustStart",
1653        priority: EventPriority::Info,
1654        access: Access::read_only(Privilege::View),
1655        conform: Conform {
1656            clauses: &[Clause {
1657                verdict: Conformance::Mandatory,
1658                when: Condition::Feature(0),
1659            }],
1660        },
1661    },
1662    Event {
1663        id: 0x01,
1664        name: "PowerAdjustEnd",
1665        priority: EventPriority::Info,
1666        access: Access::read_only(Privilege::View),
1667        conform: Conform {
1668            clauses: &[Clause {
1669                verdict: Conformance::Mandatory,
1670                when: Condition::Feature(0),
1671            }],
1672        },
1673    },
1674    Event {
1675        id: 0x02,
1676        name: "Paused",
1677        priority: EventPriority::Info,
1678        access: Access::read_only(Privilege::View),
1679        conform: Conform {
1680            clauses: &[Clause {
1681                verdict: Conformance::Mandatory,
1682                when: Condition::Feature(4),
1683            }],
1684        },
1685    },
1686    Event {
1687        id: 0x03,
1688        name: "Resumed",
1689        priority: EventPriority::Info,
1690        access: Access::read_only(Privilege::View),
1691        conform: Conform {
1692            clauses: &[Clause {
1693                verdict: Conformance::Mandatory,
1694                when: Condition::Feature(4),
1695            }],
1696        },
1697    },
1698];
1699
1700/// The whole cluster, as the specification defines it.
1701pub const CLUSTER: Cluster = Cluster {
1702    id: ID,
1703    name: "Device Energy Management",
1704    revision: REVISION,
1705    pics: "DEM",
1706    derived_from: None,
1707    features: FEATURES,
1708    attributes: ATTRIBUTES,
1709    commands: COMMANDS,
1710    events: EVENTS,
1711};