Skip to main content

matter_kit/clusters/
electrical_measurement.rs

1//! Electrical Power Measurement (`0x0090`, §2.13) and Electrical Energy Measurement
2//! (`0x0091`, §2.12) — what an appliance is drawing, and what it has drawn.
3//!
4//! Neither cluster has a command. They exist so that an energy manager can *see*, and §9.2.5
5//! makes them a dependency of the cluster that acts:
6//!
7//! > This cluster does not report electrical power and electrical energy. Devices that use this
8//! > cluster SHALL also support the Electrical Power Measurement and optionally support the
9//! > Electrical Energy Measurement cluster to allow an energy management system to perform its
10//! > role.
11//!
12//! So [`device_energy_management`](crate::clusters::device_energy_management) negotiates and
13//! these two answer "did it work?".
14//!
15//! # Null is the honest reading
16//!
17//! Every measured value here is nullable, and the specification means it: a meter that has not
18//! taken a reading yet, or whose sensor has failed, reports null rather than zero. Zero is a
19//! measurement — it says the appliance is drawing nothing — and an energy manager that could
20//! not tell the two apart would balance a house against a number nobody measured. That is why
21//! every hook returns `Option`.
22//!
23//! # Accuracy is mandatory, and it is not decoration
24//!
25//! §2.13.5.3 makes `Accuracy` a mandatory list. A current-transformer clamp is worth ±2% above
26//! a couple of amps and nearly nothing below; an EMS that treated a 15 W reading from one as
27//! exact would chase noise all evening. The struct is the appliance's honest statement of what
28//! its numbers are worth.
29
30use crate::clusters::generated::electrical_energy_measurement as spec_energy;
31use crate::clusters::generated::electrical_power_measurement as spec_power;
32use crate::clusters::generated::power_topology as spec_topology;
33use crate::dm::spec::{Conforming, Optional};
34use crate::dm::{Resolved, ResolvedCommand};
35use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
36use crate::tlv::{Tag, TlvWriter, ToTlv};
37
38use super::Cluster;
39
40/// Electrical Power Measurement, cluster `0x0090`.
41pub mod power {
42    pub use super::spec_power::attribute::{
43        ACCURACY, ACTIVE_CURRENT, ACTIVE_POWER, APPARENT_CURRENT, APPARENT_POWER, FREQUENCY,
44        HARMONIC_CURRENTS, HARMONIC_PHASES, NEUTRAL_CURRENT, NUMBER_OF_MEASUREMENT_TYPES,
45        POWER_FACTOR, POWER_MODE, RANGES, REACTIVE_CURRENT, REACTIVE_POWER, RMS_CURRENT, RMS_POWER,
46        RMS_VOLTAGE, VOLTAGE,
47    };
48    pub use super::spec_power::event::MEASUREMENT_PERIOD_RANGES;
49    pub use super::spec_power::{
50        HarmonicMeasurementStruct, ID, MeasurementAccuracyRangeStruct, MeasurementAccuracyStruct,
51        MeasurementRangeStruct, MeasurementTypeEnum, PICS, PowerModeEnum, REVISION, feature,
52    };
53}
54
55/// Electrical Energy Measurement, cluster `0x0091`.
56pub mod energy {
57    pub use super::spec_energy::attribute::{
58        ACCURACY, CUMULATIVE_ENERGY_EXPORTED, CUMULATIVE_ENERGY_IMPORTED, CUMULATIVE_ENERGY_RESET,
59        PERIODIC_ENERGY_EXPORTED, PERIODIC_ENERGY_IMPORTED,
60    };
61    pub use super::spec_energy::event::{CUMULATIVE_ENERGY_MEASURED, PERIODIC_ENERGY_MEASURED};
62    pub use super::spec_energy::{
63        CumulativeEnergyResetStruct, EnergyMeasurementStruct, ID, MeasurementAccuracyStruct, PICS,
64        REVISION, feature,
65    };
66}
67
68/// What the meter reads.
69///
70/// Every value is an `Option`, and `None` is §7.19's null rather than zero — "the meter has no
71/// reading" and "the appliance is drawing nothing" are different facts, and an energy manager
72/// that confused them would balance a house against a number nobody measured.
73pub trait PowerMeterHooks {
74    /// `PowerMode` (§2.13.5.1) — AC, DC, or unknown.
75    fn power_mode(&self) -> power::PowerModeEnum {
76        power::PowerModeEnum::Unknown
77    }
78
79    /// `Accuracy` (§2.13.5.3) — what each measurement is worth.
80    ///
81    /// Mandatory, and `NumberOfMeasurementTypes` is derived from its length so the two cannot
82    /// disagree: §2.13.5.2 defines that attribute as "the number of measurement types this
83    /// server provides", which is exactly this list.
84    fn accuracy(&self) -> &[power::MeasurementAccuracyStruct<'_>];
85
86    /// `Ranges` (§2.13.5.4) — the extremes seen over the measurement period.
87    fn ranges(&self) -> &[power::MeasurementRangeStruct] {
88        &[]
89    }
90
91    /// `Voltage`, in mV.
92    fn voltage(&self) -> Option<i64> {
93        None
94    }
95
96    /// `ActiveCurrent`, in mA.
97    fn active_current(&self) -> Option<i64> {
98        None
99    }
100
101    /// `ReactiveCurrent`, in mA — the `ALTC` feature.
102    fn reactive_current(&self) -> Option<i64> {
103        None
104    }
105
106    /// `ApparentCurrent`, in mA.
107    fn apparent_current(&self) -> Option<i64> {
108        None
109    }
110
111    /// `ActivePower`, in mW — the one mandatory measurement, and the one an EMS acts on.
112    ///
113    /// Signed: an appliance that generates reports a negative power, which is how a solar
114    /// inverter and a battery discharging are told apart from a load.
115    fn active_power(&self) -> Option<i64>;
116
117    /// `ReactivePower`, in mVAR.
118    fn reactive_power(&self) -> Option<i64> {
119        None
120    }
121
122    /// `ApparentPower`, in mVA.
123    fn apparent_power(&self) -> Option<i64> {
124        None
125    }
126
127    /// `RMSVoltage`, in mV.
128    fn rms_voltage(&self) -> Option<i64> {
129        None
130    }
131
132    /// `RMSCurrent`, in mA.
133    fn rms_current(&self) -> Option<i64> {
134        None
135    }
136
137    /// `RMSPower`, in mW.
138    fn rms_power(&self) -> Option<i64> {
139        None
140    }
141
142    /// `Frequency`, in mHz.
143    fn frequency(&self) -> Option<i64> {
144        None
145    }
146
147    /// `PowerFactor`, in hundredths of a percent.
148    fn power_factor(&self) -> Option<i64> {
149        None
150    }
151
152    /// `NeutralCurrent`, in mA — the `POLY` feature's imbalance reading.
153    fn neutral_current(&self) -> Option<i64> {
154        None
155    }
156
157    /// `HarmonicCurrents` and `HarmonicPhases` — the `HARM` and `PWRQ` features.
158    fn harmonic_currents(&self) -> &[power::HarmonicMeasurementStruct] {
159        &[]
160    }
161
162    /// `HarmonicPhases`.
163    fn harmonic_phases(&self) -> &[power::HarmonicMeasurementStruct] {
164        &[]
165    }
166}
167
168/// Electrical Power Measurement over a meter.
169#[derive(Debug)]
170pub struct ElectricalPowerMeasurement<'a, H: PowerMeterHooks> {
171    hooks: &'a H,
172}
173
174impl<'a, H: PowerMeterHooks> ElectricalPowerMeasurement<'a, H> {
175    /// A cluster over `hooks`.
176    #[must_use]
177    pub const fn new(hooks: &'a H) -> Self {
178        Self { hooks }
179    }
180
181    /// The descriptor for an instance, derived from the specification's tables.
182    pub fn conforming(
183        feature_map: u32,
184        optional: &Optional<'_>,
185    ) -> crate::error::Result<Conforming<19, 0, 0, 1>> {
186        Conforming::new(&spec_power::CLUSTER, feature_map, optional)
187    }
188
189    /// The measurements a meter with a voltage and a current sensor can offer.
190    pub const WITH_BASIC_READINGS: Optional<'static> = Optional {
191        attributes: &[
192            power::RANGES,
193            power::VOLTAGE,
194            power::ACTIVE_CURRENT,
195            power::APPARENT_CURRENT,
196        ],
197        commands: &[],
198        events: &[],
199    };
200}
201
202impl<H: PowerMeterHooks> ClusterHandler for ElectricalPowerMeasurement<'_, H> {
203    fn read(
204        &self,
205        resolved: &Resolved<'_>,
206        _ctx: &InteractionContext<'_>,
207        w: &mut TlvWriter<'_>,
208        tag: Tag,
209    ) -> Result<(), Status> {
210        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
211        let measured = |w: &mut TlvWriter<'_>, value: Option<i64>| match value {
212            Some(value) => full(w.signed(tag, value)),
213            None => full(w.null(tag)),
214        };
215        let list = |w: &mut TlvWriter<'_>, items: &[power::HarmonicMeasurementStruct]| {
216            full(w.start_array(tag))?;
217            for item in items {
218                full(item.to_tlv(w, Tag::Anonymous))?;
219            }
220            full(w.end_container())
221        };
222        match resolved.attribute {
223            power::POWER_MODE => full(w.unsigned(tag, u64::from(self.hooks.power_mode().value()))),
224            // §2.13.5.2 defines this as the length of `Accuracy`, so it is derived rather than
225            // reported: a meter cannot claim a count its own accuracy list does not support.
226            power::NUMBER_OF_MEASUREMENT_TYPES => full(w.unsigned(
227                tag,
228                u64::try_from(self.hooks.accuracy().len()).unwrap_or(u64::MAX),
229            )),
230            power::ACCURACY => {
231                full(w.start_array(tag))?;
232                for entry in self.hooks.accuracy() {
233                    full(entry.to_tlv(w, Tag::Anonymous))?;
234                }
235                full(w.end_container())
236            }
237            power::RANGES => {
238                full(w.start_array(tag))?;
239                for entry in self.hooks.ranges() {
240                    full(entry.to_tlv(w, Tag::Anonymous))?;
241                }
242                full(w.end_container())
243            }
244            power::VOLTAGE => measured(w, self.hooks.voltage()),
245            power::ACTIVE_CURRENT => measured(w, self.hooks.active_current()),
246            power::REACTIVE_CURRENT => measured(w, self.hooks.reactive_current()),
247            power::APPARENT_CURRENT => measured(w, self.hooks.apparent_current()),
248            power::ACTIVE_POWER => measured(w, self.hooks.active_power()),
249            power::REACTIVE_POWER => measured(w, self.hooks.reactive_power()),
250            power::APPARENT_POWER => measured(w, self.hooks.apparent_power()),
251            power::RMS_VOLTAGE => measured(w, self.hooks.rms_voltage()),
252            power::RMS_CURRENT => measured(w, self.hooks.rms_current()),
253            power::RMS_POWER => measured(w, self.hooks.rms_power()),
254            power::FREQUENCY => measured(w, self.hooks.frequency()),
255            power::POWER_FACTOR => measured(w, self.hooks.power_factor()),
256            power::NEUTRAL_CURRENT => measured(w, self.hooks.neutral_current()),
257            power::HARMONIC_CURRENTS => list(w, self.hooks.harmonic_currents()),
258            power::HARMONIC_PHASES => list(w, self.hooks.harmonic_phases()),
259            _ => Err(Status::UnsupportedAttribute),
260        }
261    }
262
263    fn invoke(
264        &self,
265        _resolved: &ResolvedCommand<'_>,
266        _fields: Option<&[u8]>,
267        _ctx: &InteractionContext<'_>,
268        _w: &mut TlvWriter<'_>,
269        _tag: Tag,
270    ) -> Result<Option<CommandId>, StatusIb> {
271        // §2.13 defines no commands at all: this cluster only ever answers.
272        Err(Status::UnsupportedCommand.into())
273    }
274}
275
276impl<H: PowerMeterHooks> Cluster for ElectricalPowerMeasurement<'_, H> {
277    const ID: ClusterId = power::ID;
278}
279
280/// What the energy meter has totalled.
281pub trait EnergyMeterHooks {
282    /// `Accuracy` (§2.12.6.1) — mandatory, the same argument as the power meter's.
283    fn accuracy(&self) -> energy::MeasurementAccuracyStruct<'_>;
284
285    /// `CumulativeEnergyImported`, in mWh — the `IMPE` and `CUME` features together.
286    fn cumulative_imported(&self) -> Option<energy::EnergyMeasurementStruct> {
287        None
288    }
289
290    /// `CumulativeEnergyExported` — `EXPE` and `CUME`.
291    fn cumulative_exported(&self) -> Option<energy::EnergyMeasurementStruct> {
292        None
293    }
294
295    /// `PeriodicEnergyImported` — `IMPE` and `PERE`.
296    ///
297    /// The reading an EMS actually uses moment to moment: a cumulative total says what the
298    /// meter has ever seen, and the difference between two of them is arithmetic the client
299    /// has to get right across a reset. This one carries its own window.
300    fn periodic_imported(&self) -> Option<energy::EnergyMeasurementStruct> {
301        None
302    }
303
304    /// `PeriodicEnergyExported` — `EXPE` and `PERE`.
305    fn periodic_exported(&self) -> Option<energy::EnergyMeasurementStruct> {
306        None
307    }
308
309    /// `CumulativeEnergyReset` (§2.12.6.6) — when the totals were last zeroed.
310    ///
311    /// Without it a client cannot tell a meter that has counted nothing from one that was
312    /// reset a second ago, and would read the next sample as a vast negative.
313    fn cumulative_reset(&self) -> Option<energy::CumulativeEnergyResetStruct> {
314        None
315    }
316}
317
318/// Electrical Energy Measurement over a meter.
319#[derive(Debug)]
320pub struct ElectricalEnergyMeasurement<'a, H: EnergyMeterHooks> {
321    hooks: &'a H,
322}
323
324impl<'a, H: EnergyMeterHooks> ElectricalEnergyMeasurement<'a, H> {
325    /// A cluster over `hooks`.
326    #[must_use]
327    pub const fn new(hooks: &'a H) -> Self {
328        Self { hooks }
329    }
330
331    /// The descriptor for an instance, derived from the specification's tables.
332    pub fn conforming(
333        feature_map: u32,
334        optional: &Optional<'_>,
335    ) -> crate::error::Result<Conforming<6, 0, 0, 2>> {
336        Conforming::new(&spec_energy::CLUSTER, feature_map, optional)
337    }
338}
339
340impl<H: EnergyMeterHooks> ClusterHandler for ElectricalEnergyMeasurement<'_, H> {
341    fn read(
342        &self,
343        resolved: &Resolved<'_>,
344        _ctx: &InteractionContext<'_>,
345        w: &mut TlvWriter<'_>,
346        tag: Tag,
347    ) -> Result<(), Status> {
348        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
349        let reading =
350            |w: &mut TlvWriter<'_>, value: Option<energy::EnergyMeasurementStruct>| match value {
351                Some(value) => full(value.to_tlv(w, tag)),
352                None => full(w.null(tag)),
353            };
354        match resolved.attribute {
355            energy::ACCURACY => full(self.hooks.accuracy().to_tlv(w, tag)),
356            energy::CUMULATIVE_ENERGY_IMPORTED => reading(w, self.hooks.cumulative_imported()),
357            energy::CUMULATIVE_ENERGY_EXPORTED => reading(w, self.hooks.cumulative_exported()),
358            energy::PERIODIC_ENERGY_IMPORTED => reading(w, self.hooks.periodic_imported()),
359            energy::PERIODIC_ENERGY_EXPORTED => reading(w, self.hooks.periodic_exported()),
360            energy::CUMULATIVE_ENERGY_RESET => match self.hooks.cumulative_reset() {
361                Some(reset) => full(reset.to_tlv(w, tag)),
362                None => full(w.null(tag)),
363            },
364            _ => Err(Status::UnsupportedAttribute),
365        }
366    }
367
368    fn invoke(
369        &self,
370        _resolved: &ResolvedCommand<'_>,
371        _fields: Option<&[u8]>,
372        _ctx: &InteractionContext<'_>,
373        _w: &mut TlvWriter<'_>,
374        _tag: Tag,
375    ) -> Result<Option<CommandId>, StatusIb> {
376        Err(Status::UnsupportedCommand.into())
377    }
378}
379
380impl<H: EnergyMeterHooks> Cluster for ElectricalEnergyMeasurement<'_, H> {
381    const ID: ClusterId = energy::ID;
382}
383
384// --- Power Topology --------------------------------------------------------------------------
385
386/// Power Topology, cluster `0x009C` (§2.14).
387pub mod topology {
388    pub use super::spec_topology::attribute::{ACTIVE_ENDPOINTS, AVAILABLE_ENDPOINTS};
389    pub use super::spec_topology::{ID, PICS, REVISION, feature};
390}
391
392/// Power Topology — *what* the meter on this endpoint is measuring.
393///
394/// A measurement without a scope is a number with no meaning: 400 W could be the whole house,
395/// one socket, or a circuit. §2.14's four features are the four answers, and they are mutually
396/// exclusive by construction:
397///
398/// * `NODE` — "this endpoint provides or consumes power to/from the entire node";
399/// * `TREE` — "itself and its child endpoints", which is the `PartsList` a bridge already has;
400/// * `SET` — "a specified set of endpoints", listed in `AvailableEndpoints`;
401/// * `DYPF` — that set can change, so `ActiveEndpoints` says which of them count right now.
402///
403/// The `NODE` and `TREE` forms serve no attributes at all: the answer is the node's own shape,
404/// which a client already knows from the Descriptor cluster.
405#[derive(Debug)]
406pub struct PowerTopology<'a> {
407    available: &'a [crate::im::EndpointId],
408    active: core::cell::RefCell<&'a [crate::im::EndpointId]>,
409}
410
411impl<'a> PowerTopology<'a> {
412    /// A topology over a fixed set of endpoints (`SET`), all of them active.
413    ///
414    /// `AvailableEndpoints` is `F` — fixed — so it is the product's `const` data; only
415    /// `ActiveEndpoints` moves, and only when the `DYPF` feature says it may.
416    #[must_use]
417    pub const fn new(available: &'a [crate::im::EndpointId]) -> Self {
418        Self {
419            available,
420            active: core::cell::RefCell::new(available),
421        }
422    }
423
424    /// The descriptor for an instance, derived from the specification's tables.
425    pub fn conforming(
426        feature_map: u32,
427        optional: &Optional<'_>,
428    ) -> crate::error::Result<Conforming<2, 0, 0, 0>> {
429        Conforming::new(&spec_topology::CLUSTER, feature_map, optional)
430    }
431
432    /// Narrows `ActiveEndpoints` to the ones drawing power now (`DYPF`).
433    ///
434    /// Refuses an endpoint `AvailableEndpoints` does not list: §2.14 makes the active set a
435    /// subset of the available one, and a meter that claimed to measure an endpoint it had
436    /// never declared would be reporting somebody else's power.
437    pub fn set_active(&self, active: &'a [crate::im::EndpointId]) -> Result<(), Status> {
438        if !active.iter().all(|id| self.available.contains(id)) {
439            return Err(Status::ConstraintError);
440        }
441        *self.active.borrow_mut() = active;
442        Ok(())
443    }
444
445    /// `ActiveEndpoints`.
446    #[must_use]
447    pub fn active(&self) -> &'a [crate::im::EndpointId] {
448        *self.active.borrow()
449    }
450}
451
452impl ClusterHandler for PowerTopology<'_> {
453    fn read(
454        &self,
455        resolved: &Resolved<'_>,
456        _ctx: &InteractionContext<'_>,
457        w: &mut TlvWriter<'_>,
458        tag: Tag,
459    ) -> Result<(), Status> {
460        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
461        let endpoints = |w: &mut TlvWriter<'_>, ids: &[crate::im::EndpointId]| {
462            full(w.start_array(tag))?;
463            for id in ids {
464                full(w.unsigned(Tag::Anonymous, u64::from(*id)))?;
465            }
466            full(w.end_container())
467        };
468        match resolved.attribute {
469            topology::AVAILABLE_ENDPOINTS => endpoints(w, self.available),
470            topology::ACTIVE_ENDPOINTS => endpoints(w, self.active()),
471            _ => Err(Status::UnsupportedAttribute),
472        }
473    }
474
475    fn invoke(
476        &self,
477        _resolved: &ResolvedCommand<'_>,
478        _fields: Option<&[u8]>,
479        _ctx: &InteractionContext<'_>,
480        _w: &mut TlvWriter<'_>,
481        _tag: Tag,
482    ) -> Result<Option<CommandId>, StatusIb> {
483        Err(Status::UnsupportedCommand.into())
484    }
485}
486
487impl Cluster for PowerTopology<'_> {
488    const ID: ClusterId = topology::ID;
489}