Skip to main content

matter_kit/clusters/
device_energy_management.rs

1//! Device Energy Management, cluster `0x0098` (Application Cluster §9.2).
2//!
3//! > For Energy Smart Appliances (ESA) the definition of being 'smart' mandates that they can
4//! > report their current power adjustment capability and have an EMS request a temporary
5//! > adjustment.
6//!
7//! The cluster an energy manager talks to. Everything else in the energy chapter says what an
8//! appliance *is* — a car charger, a hot water tank — and this one says what it is willing to
9//! have done to it: run at less power for a while, start later, pause, or re-plan around a
10//! window of cheap wind.
11//!
12//! # Seven features, seven negotiating positions
13//!
14//! §9.2.4 splits flexibility into things an appliance may or may not be able to offer, and the
15//! division is physical rather than arbitrary: "typically, appliances with a heating element
16//! cannot have their power consumption adjusted and can only be paused or delayed". A washing
17//! machine offers `STA` and `PAU`; an inverter-driven heat pump offers `PA`. An EMS reads the
18//! feature map and knows which conversation it can have.
19//!
20//! # The user can always say no
21//!
22//! `OptOutState` (§9.2.8.8) is the householder's veto, and it is not advisory: every command
23//! here carries an `AdjustmentCauseEnum`, and one the opt-out forbids is `CONSTRAINT_ERROR`
24//! before anything else is considered. `LocalOptOut` refuses local optimisation and still
25//! permits grid optimisation; `GridOptOut` is the mirror; `OptOut` refuses both.
26//!
27//! # Overlapping adjustments do not each end
28//!
29//! §9.2.9.1.4 is unusually specific about why:
30//!
31//! > a battery inverter ESA may be sent a new request every 5 seconds to adjust its discharge
32//! > power based on real-time meter readings. Each command may have a 60 second duration, but
33//! > this command is superseded after 5 seconds by a new request.
34//!
35//! So a replacement emits no `PowerAdjustEnd`; only the last one to expire does. A cluster that
36//! ended each would fill the event ring twelve times a minute and push everything else out of
37//! it.
38//!
39//! # What lives here and what does not
40//!
41//! The `Forecast` and `PowerAdjustmentCapability` attributes describe the appliance's own plan,
42//! which this cluster cannot size or invent. [`DemHooks`] supplies both — the ranges as data,
43//! because the cluster validates against them, and the forecast as TLV, because only the
44//! appliance knows how many slots it has. §9.2.5 also puts the meter elsewhere: "This cluster
45//! does not report electrical power and electrical energy. Devices that use this cluster SHALL
46//! also support the Electrical Power Measurement ... cluster."
47
48use core::cell::{Cell, RefCell};
49
50use crate::clusters::generated::device_energy_management as spec_dem;
51use crate::dm::spec::{Conforming, Optional};
52use crate::dm::{Resolved, ResolvedCommand};
53use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
54use crate::platform::{Duration, Instant};
55use crate::tlv::{Tag, TlvList, TlvWriter, ToTlv};
56
57use super::Cluster;
58
59pub use spec_dem::attribute::{
60    ABS_MAX_POWER, ABS_MIN_POWER, ESA_CAN_GENERATE, ESA_STATE, ESA_TYPE, FORECAST, OPT_OUT_STATE,
61    POWER_ADJUSTMENT_CAPABILITY,
62};
63pub use spec_dem::command::{
64    CANCEL_POWER_ADJUST_REQUEST, CANCEL_REQUEST, MODIFY_FORECAST_REQUEST, PAUSE_REQUEST,
65    POWER_ADJUST_REQUEST, REQUEST_CONSTRAINT_BASED_FORECAST, RESUME_REQUEST,
66    START_TIME_ADJUST_REQUEST,
67};
68pub use spec_dem::event::{PAUSED, POWER_ADJUST_END, POWER_ADJUST_START, RESUMED};
69pub use spec_dem::{
70    AdjustmentCauseEnum, CauseEnum, ConstraintsStruct, ESAStateEnum, ESATypeEnum, ForecastStruct,
71    ID, OptOutStateEnum, PICS, PowerAdjustReasonEnum, PowerAdjustStruct, REVISION,
72    SlotAdjustmentStruct, feature,
73};
74
75/// §9.2.9.6's constraint on `SlotAdjustments`, and §9.2.9.7's on `Constraints`: "max 10".
76pub const ADJUSTMENTS_MAX: usize = 10;
77
78/// What the appliance must tell the cluster about the forecast it is running.
79///
80/// The `Forecast` attribute itself is a list of slots this cluster cannot size, so it is
81/// written straight to the wire by [`DemHooks::write_forecast`]. These are the handful of
82/// fields §9.2.9 makes the *cluster* check a command against.
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84pub struct ForecastSummary {
85    /// `ForecastID` (§9.2.7.13.1) — what `ModifyForecastRequest` names.
86    pub forecast_id: u32,
87    /// `StartTime` and `EndTime`, as `epoch-s`.
88    pub start_time: u32,
89    /// `EndTime`.
90    pub end_time: u32,
91    /// `EarliestStartTime` (§9.2.7.13.5) — `None` when the forecast cannot be moved earlier.
92    pub earliest_start_time: Option<u32>,
93    /// `LatestEndTime` (§9.2.7.13.6).
94    pub latest_end_time: Option<u32>,
95    /// Whether the *active* slot may be paused (§9.2.7.14's `SlotIsPausable`).
96    pub slot_is_pausable: bool,
97    /// The active slot's `MinPauseDuration` and `MaxPauseDuration`, in seconds.
98    pub min_pause_duration: u32,
99    /// `MaxPauseDuration`.
100    pub max_pause_duration: u32,
101    /// `ForecastUpdateReason` (§9.2.7.13.9), which decides whether `CancelRequest` has
102    /// anything to cancel.
103    pub adjusted: bool,
104}
105
106/// What the appliance knows and decides.
107pub trait DemHooks {
108    /// `ESAType` (§9.2.8.1) — what kind of appliance this is.
109    fn esa_type(&self) -> ESATypeEnum;
110
111    /// `ESACanGenerate` (§9.2.8.2) — whether it can export as well as consume.
112    fn can_generate(&self) -> bool {
113        false
114    }
115
116    /// The appliance's own state, before this cluster overlays an adjustment or a pause.
117    ///
118    /// `Offline` and `Fault` are the appliance's to report and nothing here overrides them:
119    /// §9.2.9.1.4 requires "the ESAState is Online" before an adjustment can start at all.
120    fn base_state(&self) -> ESAStateEnum;
121
122    /// `AbsMinPower` and `AbsMaxPower` (§9.2.8.3, §9.2.8.4), in mW.
123    fn abs_min_power(&self) -> i64;
124
125    /// `AbsMaxPower`.
126    fn abs_max_power(&self) -> i64;
127
128    /// `OptOutState` (§9.2.8.8) — the householder's veto.
129    fn opt_out_state(&self) -> OptOutStateEnum {
130        OptOutStateEnum::NoOptOut
131    }
132
133    /// The `PowerAdjustStruct` ranges currently on offer (§9.2.7.11).
134    ///
135    /// Data rather than TLV, because §9.2.9.1.4 makes this cluster check a request against
136    /// them: "the ESA SHALL validate that the Power and Duration specified in the command are
137    /// within the limits of its current operation and advertised PowerAdjustmentCapability
138    /// attribute". An empty slice is §9.2.7.12's null — nothing is adjustable right now.
139    fn power_adjust_ranges(&self) -> &[PowerAdjustStruct] {
140        &[]
141    }
142
143    /// What the appliance is planning (§9.2.7.13), for the commands that check against it.
144    fn forecast(&self) -> Option<ForecastSummary> {
145        None
146    }
147
148    /// Writes the `Forecast` attribute.
149    ///
150    /// A forecast is a list of slots with a cost list inside each, which is a shape this
151    /// cluster cannot size for every appliance that will ever exist. Writing it here keeps the
152    /// slot table where it belongs — with the appliance that computed it.
153    fn write_forecast(&self, w: &mut TlvWriter<'_>, tag: Tag) -> crate::error::Result<()> {
154        w.null(tag)
155    }
156
157    /// §9.2.9.1: run at `power_mw` for `duration_s`. `Err` becomes the command's status.
158    fn power_adjust(
159        &self,
160        power_mw: i64,
161        duration_s: u32,
162        cause: AdjustmentCauseEnum,
163    ) -> Result<(), Status> {
164        let _ = (power_mw, duration_s, cause);
165        Err(Status::Failure)
166    }
167
168    /// Whether a *new* `PowerAdjustRequest` may interrupt one already running (§9.2.9.1.4).
169    ///
170    /// > If the ESA does not permit this new PowerAdjustmentRequest command to interrupt the
171    /// > adjustment that is in progress, it SHALL return BUSY.
172    fn may_interrupt_adjustment(&self) -> bool {
173        true
174    }
175
176    /// The adjustment ended; go back to normal power.
177    fn end_power_adjust(&self, cause: CauseEnum) {
178        let _ = cause;
179    }
180
181    /// §9.2.9.3: shift the whole forecast to start at `requested_start_time`.
182    fn adjust_start_time(
183        &self,
184        requested_start_time: u32,
185        cause: AdjustmentCauseEnum,
186    ) -> Result<(), Status> {
187        let _ = (requested_start_time, cause);
188        Err(Status::Failure)
189    }
190
191    /// §9.2.9.4: pause for `duration_s`.
192    fn pause(&self, duration_s: u32, cause: AdjustmentCauseEnum) -> Result<(), Status> {
193        let _ = (duration_s, cause);
194        Err(Status::Failure)
195    }
196
197    /// §9.2.9.5: resume.
198    ///
199    /// > the ESA MAY decide not to resume immediately if the MinPauseDuration has not yet
200    /// > elapsed. This behavior is manufacturer specific.
201    fn resume(&self) -> Result<(), Status> {
202        Ok(())
203    }
204
205    /// §9.2.9.6: apply the slot adjustments, or reject the whole list.
206    ///
207    /// > If for any reason the ESA cannot accept the entire requested forecast adjustments then
208    /// > it SHALL reject the entire command.
209    fn modify_forecast(
210        &self,
211        adjustments: &[SlotAdjustmentStruct],
212        cause: AdjustmentCauseEnum,
213    ) -> Result<(), Status> {
214        let _ = (adjustments, cause);
215        Err(Status::Failure)
216    }
217
218    /// §9.2.9.7: re-plan around the constraints.
219    fn constraint_based_forecast(
220        &self,
221        constraints: &[ConstraintsStruct],
222        cause: AdjustmentCauseEnum,
223    ) -> Result<(), Status> {
224        let _ = (constraints, cause);
225        Err(Status::Failure)
226    }
227
228    /// §9.2.9.8: forget every adjustment and re-plan from the appliance's own preferences.
229    fn cancel_adjustments(&self) -> Result<(), Status> {
230        Ok(())
231    }
232}
233
234/// An event this cluster produced, for the device to record in its own store (§7.14).
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum Event {
237    /// §9.2.10.1 — the adjustment began, carrying its power and duration.
238    PowerAdjustStart,
239    /// §9.2.10.2 — the adjustment ended, and why.
240    PowerAdjustEnd(CauseEnum),
241    /// §9.2.10.3 — the appliance paused.
242    Paused,
243    /// §9.2.10.4 — it resumed, however that came about.
244    Resumed(CauseEnum),
245}
246
247/// Device Energy Management over one Energy Smart Appliance.
248#[derive(Debug)]
249pub struct DeviceEnergyManagement<'a, H: DemHooks> {
250    hooks: &'a H,
251    feature_map: u32,
252    /// The reason a power adjustment is running, or `NoAdjustment` (§9.2.7.12.1).
253    adjust_reason: Cell<PowerAdjustReasonEnum>,
254    adjust_until: Cell<Option<Instant>>,
255    paused_until: Cell<Option<Instant>>,
256    events: RefCell<heapless::Vec<Event, 8>>,
257}
258
259impl<'a, H: DemHooks> DeviceEnergyManagement<'a, H> {
260    /// A cluster over `hooks`.
261    #[must_use]
262    pub fn new(hooks: &'a H, feature_map: u32) -> Self {
263        Self {
264            hooks,
265            feature_map,
266            adjust_reason: Cell::new(PowerAdjustReasonEnum::NoAdjustment),
267            adjust_until: Cell::new(None),
268            paused_until: Cell::new(None),
269            events: RefCell::new(heapless::Vec::new()),
270        }
271    }
272
273    /// The descriptor for an instance, derived from the specification's tables.
274    pub fn conforming(
275        feature_map: u32,
276        optional: &Optional<'_>,
277    ) -> crate::error::Result<Conforming<8, 8, 0, 4>> {
278        Conforming::new(&spec_dem::CLUSTER, feature_map, optional)
279    }
280
281    /// `ESAState` (§9.2.8.3).
282    ///
283    /// The appliance's own state wins whenever it is not simply running: §9.2.9.4.3 says that
284    /// if "the ESA develops a fault whilst Paused, the ESAState SHALL be set to Fault", so a
285    /// cluster that reported `Paused` over the top of a fault would hide it from the one client
286    /// that could do something about it.
287    #[must_use]
288    pub fn state(&self) -> ESAStateEnum {
289        let base = self.hooks.base_state();
290        if base != ESAStateEnum::Online {
291            return base;
292        }
293        if self.paused_until.get().is_some() {
294            return ESAStateEnum::Paused;
295        }
296        if self.adjust_reason.get() != PowerAdjustReasonEnum::NoAdjustment {
297            return ESAStateEnum::PowerAdjustActive;
298        }
299        ESAStateEnum::Online
300    }
301
302    /// `PowerAdjustmentCapability`'s `Cause` field (§9.2.7.12.1).
303    #[must_use]
304    pub fn adjust_reason(&self) -> PowerAdjustReasonEnum {
305        self.adjust_reason.get()
306    }
307
308    /// When [`DeviceEnergyManagement::poll`] next has something to do.
309    #[must_use]
310    pub fn wake_at(&self) -> Option<Instant> {
311        match (self.adjust_until.get(), self.paused_until.get()) {
312            (Some(a), Some(p)) => Some(if a < p { a } else { p }),
313            (Some(a), None) => Some(a),
314            (None, Some(p)) => Some(p),
315            (None, None) => None,
316        }
317    }
318
319    /// Ends an adjustment or a pause whose duration has run out.
320    pub fn poll(&self, now: Instant) {
321        if let Some(until) = self.adjust_until.get()
322            && now >= until
323        {
324            // §9.2.9.1.4: "After the elapsed duration, the ESA SHALL revert to normal (or idle)
325            // power levels. The ESA SHALL also generate a PowerAdjustEnd Event with a cause
326            // code to indicate a 'Normal completion'."
327            self.finish_adjust(CauseEnum::NormalCompletion);
328        }
329        if let Some(until) = self.paused_until.get()
330            && now >= until
331        {
332            // §9.2.9.4.3: "When the Pause timer expires the ESA SHALL automatically resume
333            // operation. When it does this, then it SHALL also generate a Resumed Event."
334            self.paused_until.set(None);
335            let _ = self.hooks.resume();
336            self.push(Event::Resumed(CauseEnum::NormalCompletion));
337        }
338    }
339
340    /// The householder changed their mind, or the appliance failed (§9.2.9.1.4).
341    ///
342    /// > If during the power adjustment session a failure or other condition occurs (such as the
343    /// > user deciding to opt-out by updating the OptOutState) then the ESA SHALL generate a
344    /// > PowerAdjustEnd Event to indicate the end of the session, with the appropriate cause
345    /// > code.
346    pub fn abort(&self, cause: CauseEnum) {
347        if self.paused_until.take().is_some() {
348            // §9.2.9.4.3: "On change of ESAState (from Paused to another state), the ESA SHALL
349            // generate a Resumed Event."
350            self.push(Event::Resumed(cause));
351        }
352        self.finish_adjust(cause);
353    }
354
355    /// Takes the event records the cluster has collected.
356    pub fn take_events(&self) -> heapless::Vec<Event, 8> {
357        core::mem::take(&mut self.events.borrow_mut())
358    }
359
360    fn push(&self, event: Event) {
361        let mut events = self.events.borrow_mut();
362        if events.is_full() {
363            events.remove(0);
364        }
365        let _ = events.push(event);
366    }
367
368    fn finish_adjust(&self, cause: CauseEnum) {
369        if self.adjust_reason.get() == PowerAdjustReasonEnum::NoAdjustment {
370            return;
371        }
372        self.adjust_reason.set(PowerAdjustReasonEnum::NoAdjustment);
373        self.adjust_until.set(None);
374        self.hooks.end_power_adjust(cause);
375        self.push(Event::PowerAdjustEnd(cause));
376    }
377
378    /// §9.2.9 makes every command conditional on a feature: `PA` for the two power-adjust
379    /// commands, `STA` for the start-time one, `PAU` for the pair, `FA` and `CON` for the
380    /// forecast ones.
381    ///
382    /// The derived descriptor already leaves an unsupported command out of
383    /// `AcceptedCommandList`, so the server refuses it before this handler sees it. This is
384    /// the second half of the same fact, for a handler used without that descriptor — and it
385    /// is not redundant, because the feature map here and the one the descriptor was derived
386    /// from are two separate arguments a device can get out of step.
387    const fn supports(&self, bit: u32) -> bool {
388        self.feature_map & bit != 0
389    }
390
391    /// §9.2.8.8: whether `OptOutState` permits an adjustment made for `cause`.
392    ///
393    /// The householder's veto is per *reason*: someone who has opted out of grid optimisation
394    /// may still want their own solar used, and a cluster that treated the opt-out as a single
395    /// switch would take that away.
396    fn permits(&self, cause: AdjustmentCauseEnum) -> bool {
397        match (self.hooks.opt_out_state(), cause) {
398            (OptOutStateEnum::NoOptOut, _) => true,
399            (OptOutStateEnum::OptOut, _) => false,
400            (OptOutStateEnum::LocalOptOut, cause) => {
401                cause != AdjustmentCauseEnum::LocalOptimization
402            }
403            (OptOutStateEnum::GridOptOut, cause) => cause != AdjustmentCauseEnum::GridOptimization,
404        }
405    }
406}
407
408/// Reads at most `N` structures out of a list, refusing one that is longer or malformed.
409fn collect<'a, T: crate::tlv::FromTlv<'a> + Copy, const N: usize>(
410    list: TlvList<'a, T>,
411) -> Result<heapless::Vec<T, N>, Status> {
412    let mut out: heapless::Vec<T, N> = heapless::Vec::new();
413    for entry in list.iter() {
414        let entry = entry.map_err(|_| Status::ConstraintError)?;
415        // §9.2.9.6's constraint is "max 10". A longer list is a request the specification does
416        // not permit a client to send, not a device that ran out of room.
417        out.push(entry).map_err(|_| Status::ConstraintError)?;
418    }
419    Ok(out)
420}
421
422impl<H: DemHooks> ClusterHandler for DeviceEnergyManagement<'_, H> {
423    fn read(
424        &self,
425        resolved: &Resolved<'_>,
426        _ctx: &InteractionContext<'_>,
427        w: &mut TlvWriter<'_>,
428        tag: Tag,
429    ) -> Result<(), Status> {
430        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
431        match resolved.attribute {
432            ESA_TYPE => full(w.unsigned(tag, u64::from(self.hooks.esa_type().value()))),
433            ESA_CAN_GENERATE => full(w.bool(tag, self.hooks.can_generate())),
434            ESA_STATE => full(w.unsigned(tag, u64::from(self.state().value()))),
435            ABS_MIN_POWER => full(w.signed(tag, self.hooks.abs_min_power())),
436            ABS_MAX_POWER => full(w.signed(tag, self.hooks.abs_max_power())),
437            POWER_ADJUSTMENT_CAPABILITY => {
438                let ranges = self.hooks.power_adjust_ranges();
439                // §9.2.7.12: null when the appliance is offering nothing right now, which is a
440                // different thing from an empty list of ranges.
441                if ranges.is_empty() {
442                    return full(w.null(tag));
443                }
444                full(w.start_structure(tag))?;
445                full(w.start_array(Tag::Context(0)))?;
446                for range in ranges {
447                    full(range.to_tlv(w, Tag::Anonymous))?;
448                }
449                full(w.end_container())?;
450                // §9.2.9.1.4: "the PowerAdjustmentCapability attribute SHALL be updated to set
451                // the Cause value from the Cause field of this command" — so the cause belongs
452                // to the cluster, and the ranges to the appliance.
453                full(w.unsigned(Tag::Context(1), u64::from(self.adjust_reason.get().value())))?;
454                full(w.end_container())
455            }
456            FORECAST => self
457                .hooks
458                .write_forecast(w, tag)
459                .map_err(|_| Status::ResourceExhausted),
460            OPT_OUT_STATE => full(w.unsigned(tag, u64::from(self.hooks.opt_out_state().value()))),
461            _ => Err(Status::UnsupportedAttribute),
462        }
463    }
464
465    #[allow(clippy::too_many_lines)]
466    fn invoke(
467        &self,
468        resolved: &ResolvedCommand<'_>,
469        fields: Option<&[u8]>,
470        ctx: &InteractionContext<'_>,
471        _w: &mut TlvWriter<'_>,
472        _tag: Tag,
473    ) -> Result<Option<CommandId>, StatusIb> {
474        let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
475        match resolved.command.id {
476            POWER_ADJUST_REQUEST => {
477                if !self.supports(feature::POWER_ADJUSTMENT) {
478                    return Err(Status::UnsupportedCommand.into());
479                }
480                let decoded: spec_dem::PowerAdjustRequestFields = super::decode_fields(payload()?)?;
481                if !self.permits(decoded.cause) {
482                    return Err(Status::ConstraintError.into());
483                }
484                // §9.2.9.1.4: "the ESAState is Online". `PowerAdjustActive` is the one exception
485                // — that is the overlapping-request case below.
486                let running = self.adjust_reason.get() != PowerAdjustReasonEnum::NoAdjustment;
487                if self.hooks.base_state() != ESAStateEnum::Online {
488                    return Err(Status::Failure.into());
489                }
490                // "the ESA SHALL validate that the Power and Duration specified in the command
491                // are within the limits of its ... advertised PowerAdjustmentCapability".
492                let power = i64::from(decoded.power);
493                let fits = self.hooks.power_adjust_ranges().iter().any(|range| {
494                    power >= i64::from(range.min_power)
495                        && power <= i64::from(range.max_power)
496                        && decoded.duration >= range.min_duration
497                        && decoded.duration <= range.max_duration
498                });
499                if !fits {
500                    return Err(Status::ConstraintError.into());
501                }
502                if running && !self.hooks.may_interrupt_adjustment() {
503                    // §9.2.9.1.4: "If the ESA does not permit this new PowerAdjustmentRequest
504                    // command to interrupt the adjustment that is in progress, it SHALL return
505                    // BUSY."
506                    return Err(Status::Busy.into());
507                }
508                self.hooks
509                    .power_adjust(power, decoded.duration, decoded.cause)
510                    .map_err(StatusIb::from)?;
511                self.adjust_reason.set(match decoded.cause {
512                    AdjustmentCauseEnum::LocalOptimization => {
513                        PowerAdjustReasonEnum::LocalOptimizationAdjustment
514                    }
515                    AdjustmentCauseEnum::GridOptimization => {
516                        PowerAdjustReasonEnum::GridOptimizationAdjustment
517                    }
518                });
519                self.adjust_until
520                    .set(Some(ctx.now.saturating_add(Duration::from_secs(
521                        u64::from(decoded.duration),
522                    ))));
523                // "Note that if the new command is accepted, then the ESA SHALL NOT generate a
524                // new PowerAdjustEnd Event until the new duration has elapsed" — and no new
525                // *Start* either, or a battery inverter retuned every five seconds would emit
526                // twelve events a minute and push everything else out of the event ring.
527                if !running {
528                    self.push(Event::PowerAdjustStart);
529                }
530                Ok(None)
531            }
532            CANCEL_POWER_ADJUST_REQUEST => {
533                if !self.supports(feature::POWER_ADJUSTMENT) {
534                    return Err(Status::UnsupportedCommand.into());
535                }
536                // §9.2.9.2.1: "If the ESAState is not PowerAdjustActive, then the command SHALL
537                // be rejected with INVALID_IN_STATE."
538                if self.adjust_reason.get() == PowerAdjustReasonEnum::NoAdjustment {
539                    return Err(Status::InvalidInState.into());
540                }
541                self.finish_adjust(CauseEnum::Cancelled);
542                Ok(None)
543            }
544            START_TIME_ADJUST_REQUEST => {
545                if !self.supports(feature::START_TIME_ADJUSTMENT) {
546                    return Err(Status::UnsupportedCommand.into());
547                }
548                let decoded: spec_dem::StartTimeAdjustRequestFields =
549                    super::decode_fields(payload()?)?;
550                if !self.permits(decoded.cause) {
551                    return Err(Status::ConstraintError.into());
552                }
553                let Some(forecast) = self.hooks.forecast() else {
554                    return Err(Status::Failure.into());
555                };
556                // §9.2.9.3.1: "This value SHALL be after the EarliestStartTime in the Forecast
557                // attribute. The new EndTime, that can be computed from the RequestedStartTime
558                // and the Forecast sequence duration, SHALL be before the LatestEndTime."
559                let span = forecast.end_time.saturating_sub(forecast.start_time);
560                let new_end = decoded.requested_start_time.saturating_add(span);
561                let too_early = forecast
562                    .earliest_start_time
563                    .is_some_and(|earliest| decoded.requested_start_time < earliest);
564                let too_late = forecast
565                    .latest_end_time
566                    .is_some_and(|latest| new_end > latest);
567                if too_early || too_late {
568                    return Err(Status::ConstraintError.into());
569                }
570                self.hooks
571                    .adjust_start_time(decoded.requested_start_time, decoded.cause)
572                    .map_err(StatusIb::from)?;
573                Ok(None)
574            }
575            PAUSE_REQUEST => {
576                if !self.supports(feature::PAUSABLE) {
577                    return Err(Status::UnsupportedCommand.into());
578                }
579                let decoded: spec_dem::PauseRequestFields = super::decode_fields(payload()?)?;
580                if !self.permits(decoded.cause) {
581                    return Err(Status::ConstraintError.into());
582                }
583                let Some(forecast) = self.hooks.forecast() else {
584                    return Err(Status::Failure.into());
585                };
586                // §9.2.9.4.3: "If the ESA SlotIsPausable field is false for the
587                // ActiveSlotNumber, then the command SHALL be rejected with FAILURE." A spin
588                // cycle cannot be stopped half way; a water-heating step can.
589                if !forecast.slot_is_pausable {
590                    return Err(Status::Failure.into());
591                }
592                // "The ESA SHALL validate that the Duration field is within the range of
593                // MinPauseDuration and MaxPauseDuration. If it is outside of this range then
594                // the command SHALL be rejected with CONSTRAINT_ERROR."
595                if decoded.duration < forecast.min_pause_duration
596                    || decoded.duration > forecast.max_pause_duration
597                {
598                    return Err(Status::ConstraintError.into());
599                }
600                // "the OptOutState is Online or PowerAdjustActive" — the specification names
601                // `OptOutState` there, but the states it lists are `ESAState`'s, and an
602                // appliance that is Offline or in Fault cannot be paused in any case.
603                let state = self.state();
604                if !matches!(
605                    state,
606                    ESAStateEnum::Online | ESAStateEnum::PowerAdjustActive | ESAStateEnum::Paused
607                ) {
608                    return Err(Status::Failure.into());
609                }
610                self.hooks
611                    .pause(decoded.duration, decoded.cause)
612                    .map_err(StatusIb::from)?;
613                // "If a further Pause Request is received in the same forecast slot whilst
614                // already in the paused state ... the pause timer SHALL be extended by the new
615                // Duration" — extended, not replaced.
616                let extra = Duration::from_secs(u64::from(decoded.duration));
617                let already_paused = self.paused_until.get();
618                self.paused_until.set(Some(match already_paused {
619                    Some(until) => until.saturating_add(extra),
620                    None => ctx.now.saturating_add(extra),
621                }));
622                if already_paused.is_none() {
623                    self.push(Event::Paused);
624                }
625                Ok(None)
626            }
627            RESUME_REQUEST => {
628                if !self.supports(feature::PAUSABLE) {
629                    return Err(Status::UnsupportedCommand.into());
630                }
631                // §9.2.9.5.1: "the command SHALL be rejected with the response INVALID_IN_STATE
632                // if the ESA is not currently Paused".
633                if self.paused_until.get().is_none() {
634                    return Err(Status::InvalidInState.into());
635                }
636                self.hooks.resume().map_err(StatusIb::from)?;
637                self.paused_until.set(None);
638                self.push(Event::Resumed(CauseEnum::Cancelled));
639                Ok(None)
640            }
641            MODIFY_FORECAST_REQUEST => {
642                if !self.supports(feature::FORECAST_ADJUSTMENT) {
643                    return Err(Status::UnsupportedCommand.into());
644                }
645                let decoded: spec_dem::ModifyForecastRequestFields<'_> =
646                    super::decode_fields(payload()?)?;
647                if !self.permits(decoded.cause) {
648                    return Err(Status::ConstraintError.into());
649                }
650                let adjustments: heapless::Vec<SlotAdjustmentStruct, ADJUSTMENTS_MAX> =
651                    collect(decoded.slot_adjustments).map_err(StatusIb::from)?;
652                // §9.2.9.6.4: "otherwise if the ForecastID is valid ... the command status
653                // returned SHALL be SUCCESS, otherwise the command SHALL be rejected with
654                // FAILURE". A stale id means the EMS optimised a plan the appliance has already
655                // replaced, and applying it would undo whatever replaced it.
656                let Some(forecast) = self.hooks.forecast() else {
657                    return Err(Status::Failure.into());
658                };
659                if forecast.forecast_id != decoded.forecast_id {
660                    return Err(Status::Failure.into());
661                }
662                self.hooks
663                    .modify_forecast(&adjustments, decoded.cause)
664                    .map_err(StatusIb::from)?;
665                Ok(None)
666            }
667            REQUEST_CONSTRAINT_BASED_FORECAST => {
668                if !self.supports(feature::CONSTRAINT_BASED_ADJUSTMENT) {
669                    return Err(Status::UnsupportedCommand.into());
670                }
671                let decoded: spec_dem::RequestConstraintBasedForecastFields<'_> =
672                    super::decode_fields(payload()?)?;
673                if !self.permits(decoded.cause) {
674                    return Err(Status::ConstraintError.into());
675                }
676                let constraints: heapless::Vec<ConstraintsStruct, ADJUSTMENTS_MAX> =
677                    collect(decoded.constraints).map_err(StatusIb::from)?;
678                self.hooks
679                    .constraint_based_forecast(&constraints, decoded.cause)
680                    .map_err(StatusIb::from)?;
681                Ok(None)
682            }
683            CANCEL_REQUEST => {
684                // §9.2.9's conformance for this one is `STA | FA | CON`: it cancels whatever
685                // those three set, so an appliance with none of them has nothing to cancel.
686                if !(self.supports(feature::START_TIME_ADJUSTMENT)
687                    || self.supports(feature::FORECAST_ADJUSTMENT)
688                    || self.supports(feature::CONSTRAINT_BASED_ADJUSTMENT))
689                {
690                    return Err(Status::UnsupportedCommand.into());
691                }
692                // §9.2.9.8.1: "If the ESA ForecastUpdateReason was already Internal
693                // Optimization, then the command SHALL be rejected with INVALID_IN_STATE."
694                // There is nothing to cancel: the plan is already the appliance's own.
695                let adjusted = self.hooks.forecast().is_some_and(|f| f.adjusted);
696                if !adjusted {
697                    return Err(Status::InvalidInState.into());
698                }
699                self.hooks.cancel_adjustments().map_err(StatusIb::from)?;
700                Ok(None)
701            }
702            _ => Err(Status::UnsupportedCommand.into()),
703        }
704    }
705}
706
707/// So a tuple of clusters can dispatch to it by id.
708impl<H: DemHooks> Cluster for DeviceEnergyManagement<'_, H> {
709    const ID: ClusterId = ID;
710}