Skip to main content

matter_kit/clusters/
water_heater_management.rs

1//! Water Heater Management, cluster `0x0094` (Application Cluster §9.5).
2//!
3//! > Heating of hot water is one of the main energy uses in homes, and when coupled with the
4//! > Energy Management cluster, it can help consumers save cost (e.g. using power at cheaper
5//! > times or from local solar PV generation).
6//!
7//! A hot water tank is a battery that stores heat, and this cluster is the interface that lets
8//! something else decide *when* to charge it. Most of the time the tank runs itself off the
9//! Thermostat cluster on the same endpoint (§9.5.5 requires one); this cluster adds the two
10//! things an energy manager needs — a way to say "heat it now, whatever the schedule says",
11//! and enough information to work out what that will cost.
12//!
13//! # Boost is an override with an end
14//!
15//! §9.5.8.1: a `Boost` heats the water "which may override other settings, for example, if the
16//! Water Heater Mode is set to Off, or Timed and it is during one of the Off periods". Every
17//! boost carries a `Duration`, and it stops when that runs out even if nothing else stops it.
18//! A boost that could not expire would be a tariff-blind immersion heater with a network
19//! interface.
20//!
21//! # The device may refuse
22//!
23//! > If the duration field is too short for the water heater to accept, for example a heat pump
24//! > may take several minutes to ramp up in operation, then the boost command SHALL be
25//! > rejected with a status of INVALID_IN_STATE.
26//!
27//! Only the appliance knows its own ramp, so [`WaterHeaterHooks::boost`] is what decides, and
28//! this cluster never invents a minimum of its own.
29
30use core::cell::{Cell, RefCell};
31
32use crate::clusters::generated::water_heater_management as spec_water;
33use crate::dm::spec::{Conforming, Optional};
34use crate::dm::{Resolved, ResolvedCommand};
35use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
36use crate::platform::{Duration, Instant};
37use crate::tlv::{Tag, TlvWriter};
38
39use super::Cluster;
40
41pub use spec_water::attribute::{
42    BOOST_STATE, ESTIMATED_HEAT_REQUIRED, HEAT_DEMAND, HEATER_TYPES, TANK_PERCENTAGE, TANK_VOLUME,
43};
44pub use spec_water::command::{BOOST, CANCEL_BOOST};
45pub use spec_water::event::{BOOST_ENDED, BOOST_STARTED};
46pub use spec_water::{
47    BoostStateEnum, ID, PICS, REVISION, WaterHeaterBoostInfoStruct, WaterHeaterHeatSourceBitmap,
48    feature,
49};
50
51/// What §9.5.6.3's `Duration` is measured in.
52pub const SECOND: Duration = Duration::from_secs(1);
53
54/// What the appliance decides for itself.
55pub trait WaterHeaterHooks {
56    /// `HeatDemand` (§9.5.7.2) — which heat sources are running right now.
57    ///
58    /// > This attribute SHALL indicate if the water heater is heating water. If a bit is set
59    /// > then the corresponding heat source is active.
60    fn heat_demand(&self) -> WaterHeaterHeatSourceBitmap;
61
62    /// `TankVolume` (§9.5.7.3), in litres — what the `EnergyManagement` feature adds.
63    fn tank_volume(&self) -> u16 {
64        0
65    }
66
67    /// `EstimatedHeatRequired` (§9.5.7.4), in mWh.
68    ///
69    /// The energy needed to bring the tank to its setpoint. §9.5.7.4 works the sum out in full
70    /// — specific heat capacity, tank volume, temperature difference — and then notes that the
71    /// *electrical* energy is a different number entirely: "Heat pumps can be produce 3kWh of
72    /// heat output for 1kWh of electrical energy input. The conversion between heat energy and
73    /// electrical energy is outside the scope of this cluster."
74    fn estimated_heat_required(&self) -> u64 {
75        0
76    }
77
78    /// `TankPercentage` (§9.5.7.5) — roughly how much of the tank is hot.
79    ///
80    /// Not a measurement so much as an estimate: hot water stratifies above cold, and §9.5.7.5
81    /// gives an algorithm for a tank with a single probe and notes that "the accuracy of this
82    /// attribute is manufacturer specific".
83    fn tank_percentage(&self) -> u8 {
84        0
85    }
86
87    /// §9.5.8.1: start heating on the terms in `info`.
88    ///
89    /// Return `Err(Status::InvalidInState)` when the appliance cannot honour it — §9.5.8.1
90    /// names exactly that case: "If the duration field is too short for the water heater to
91    /// accept, for example a heat pump may take several minutes to ramp up in operation". No
92    /// other code is defined for a boost the appliance will not do.
93    fn boost(&self, info: &WaterHeaterBoostInfoStruct) -> Result<(), Status>;
94
95    /// §9.5.8.2: stop, and go back to whatever the Water Heater Mode says.
96    fn cancel_boost(&self) {}
97}
98
99/// An event this cluster produced, for the device to record in its own store (§7.14).
100#[derive(Debug, Clone, Copy, PartialEq)]
101pub enum Event {
102    /// §9.5.9.1 — "generated whenever a Boost command is accepted", carrying the command's own
103    /// fields so a client can see the terms that were accepted rather than the ones it sent.
104    BoostStarted(WaterHeaterBoostInfoStruct),
105    /// §9.5.9.2 — "generated whenever the BoostState transitions from Active to Inactive".
106    BoostEnded,
107}
108
109/// Water Heater Management over a tank the device owns.
110#[derive(Debug)]
111pub struct WaterHeaterManagement<'a, H: WaterHeaterHooks> {
112    hooks: &'a H,
113    heater_types: WaterHeaterHeatSourceBitmap,
114    boost: Cell<Option<WaterHeaterBoostInfoStruct>>,
115    /// When the running boost's `Duration` runs out.
116    expires: Cell<Option<Instant>>,
117    events: RefCell<heapless::Vec<Event, 4>>,
118}
119
120impl<'a, H: WaterHeaterHooks> WaterHeaterManagement<'a, H> {
121    /// A cluster over an appliance with the given heat sources.
122    ///
123    /// `heater_types` is `F` — fixed (§9.5.7.1) — because it is what the tank physically has:
124    /// an immersion element, a heat pump, a boiler, or several.
125    #[must_use]
126    pub fn new(hooks: &'a H, heater_types: WaterHeaterHeatSourceBitmap) -> Self {
127        Self {
128            hooks,
129            heater_types,
130            boost: Cell::new(None),
131            expires: Cell::new(None),
132            events: RefCell::new(heapless::Vec::new()),
133        }
134    }
135
136    /// The descriptor for an instance, derived from the specification's tables.
137    pub fn conforming(
138        feature_map: u32,
139        optional: &Optional<'_>,
140    ) -> crate::error::Result<Conforming<6, 2, 0, 2>> {
141        Conforming::new(&spec_water::CLUSTER, feature_map, optional)
142    }
143
144    /// `HeaterTypes` (§9.5.7.1).
145    #[must_use]
146    pub const fn heater_types(&self) -> WaterHeaterHeatSourceBitmap {
147        self.heater_types
148    }
149
150    /// `BoostState` (§9.5.7.6).
151    #[must_use]
152    pub fn boost_state(&self) -> BoostStateEnum {
153        if self.boost.get().is_some() {
154            BoostStateEnum::Active
155        } else {
156            BoostStateEnum::Inactive
157        }
158    }
159
160    /// The terms of the boost currently running, if any.
161    #[must_use]
162    pub fn boost_info(&self) -> Option<WaterHeaterBoostInfoStruct> {
163        self.boost.get()
164    }
165
166    /// When [`WaterHeaterManagement::poll`] next has something to do.
167    #[must_use]
168    pub fn wake_at(&self) -> Option<Instant> {
169        self.expires.get()
170    }
171
172    /// Ends a boost whose `Duration` has run out.
173    ///
174    /// §9.5.8.1: "or the boost command's duration times out after the specified Duration, then
175    /// BoostState transitions to Inactive". A boost with no end is an immersion heater that
176    /// ignores the tariff it was installed to follow.
177    pub fn poll(&self, now: Instant) {
178        if let Some(expires) = self.expires.get()
179            && now >= expires
180        {
181            self.end();
182        }
183    }
184
185    /// The appliance reached the target by itself — a `OneShot` boost is over (§9.5.8.1).
186    ///
187    /// > If OneShot is specified then once the hot water has reached the set point temperature
188    /// > (or the TemporarySetpoint temperature, if specified) or the TargetPercentage (if
189    /// > specified) ... BoostState transitions to Inactive.
190    ///
191    /// Only the appliance knows it got there, so it says so; and without `OneShot` reaching the
192    /// target is *not* the end, because §9.5.6.3.6's `TargetReheat` exists precisely so the
193    /// tank keeps topping itself up until the duration runs out.
194    pub fn target_reached(&self) {
195        if self
196            .boost
197            .get()
198            .is_some_and(|info| info.one_shot == Some(true))
199        {
200            self.end();
201        }
202    }
203
204    /// Takes the event records the cluster has produced, for the device's own store.
205    pub fn take_events(&self) -> heapless::Vec<Event, 4> {
206        core::mem::take(&mut self.events.borrow_mut())
207    }
208
209    fn push(&self, event: Event) {
210        let mut events = self.events.borrow_mut();
211        if events.is_full() {
212            events.remove(0);
213        }
214        let _ = events.push(event);
215    }
216
217    /// Transitions to Inactive, if it was not already.
218    fn end(&self) {
219        if self.boost.take().is_some() {
220            self.expires.set(None);
221            self.hooks.cancel_boost();
222            self.push(Event::BoostEnded);
223        }
224    }
225}
226
227impl<H: WaterHeaterHooks> ClusterHandler for WaterHeaterManagement<'_, H> {
228    fn read(
229        &self,
230        resolved: &Resolved<'_>,
231        _ctx: &InteractionContext<'_>,
232        w: &mut TlvWriter<'_>,
233        tag: Tag,
234    ) -> Result<(), Status> {
235        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
236        match resolved.attribute {
237            HEATER_TYPES => full(w.unsigned(tag, u64::from(self.heater_types.bits()))),
238            HEAT_DEMAND => full(w.unsigned(tag, u64::from(self.hooks.heat_demand().bits()))),
239            TANK_VOLUME => full(w.unsigned(tag, u64::from(self.hooks.tank_volume()))),
240            ESTIMATED_HEAT_REQUIRED => full(w.unsigned(tag, self.hooks.estimated_heat_required())),
241            TANK_PERCENTAGE => full(w.unsigned(tag, u64::from(self.hooks.tank_percentage()))),
242            BOOST_STATE => full(w.unsigned(tag, u64::from(self.boost_state().value()))),
243            _ => Err(Status::UnsupportedAttribute),
244        }
245    }
246
247    fn invoke(
248        &self,
249        resolved: &ResolvedCommand<'_>,
250        fields: Option<&[u8]>,
251        ctx: &InteractionContext<'_>,
252        _w: &mut TlvWriter<'_>,
253        _tag: Tag,
254    ) -> Result<Option<CommandId>, StatusIb> {
255        match resolved.command.id {
256            BOOST => {
257                let decoded: spec_water::BoostFields =
258                    super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
259                let info = decoded.boost_info;
260                // §9.5.6.3's constraint on `Duration` is "min 1": a boost for no time is not a
261                // boost, and it would expire on the tick it started.
262                if info.duration == 0 {
263                    return Err(Status::ConstraintError.into());
264                }
265                // §9.5.6.3.6: "This field SHALL be less than or equal to the TargetPercentage
266                // field." Reheating to a level above the target would never stop.
267                if let (Some(target), Some(reheat)) = (info.target_percentage, info.target_reheat)
268                    && reheat > target
269                {
270                    return Err(Status::ConstraintError.into());
271                }
272                // Both are percentages; §7.19.2's rule about values a type cannot hold applies
273                // to a `percent` just as much as to an enumeration.
274                if info.target_percentage.is_some_and(|p| p > 100)
275                    || info.target_reheat.is_some_and(|p| p > 100)
276                {
277                    return Err(Status::ConstraintError.into());
278                }
279                // §9.5.8.1: the appliance may refuse, and `INVALID_IN_STATE` is the only code
280                // the specification gives it.
281                self.hooks.boost(&info).map_err(StatusIb::from)?;
282                // "If the Water Heater was already in the BoostState 'Active' when this command
283                // is received, it SHALL continue in this BoostState, but SHALL discard the
284                // effect of the values of the fields from the previous Boost commands" — so a
285                // second boost replaces the terms without an intervening `BoostEnded`.
286                self.boost.set(Some(info));
287                self.expires
288                    .set(Some(ctx.now.saturating_add(
289                        SECOND.saturating_mul(u64::from(info.duration)),
290                    )));
291                self.push(Event::BoostStarted(info));
292                Ok(None)
293            }
294            CANCEL_BOOST => {
295                // §9.5.8.2: "If the BoostState attribute value was already Inactive when this
296                // command is received, the BoostState attribute value shall remain Inactive and
297                // the server SHALL return SUCCESS." Not an error — cancelling nothing is the
298                // state the client asked for.
299                self.end();
300                Ok(None)
301            }
302            _ => Err(Status::UnsupportedCommand.into()),
303        }
304    }
305}
306
307/// So a tuple of clusters can dispatch to it by id.
308impl<H: WaterHeaterHooks> Cluster for WaterHeaterManagement<'_, H> {
309    const ID: ClusterId = ID;
310}