Skip to main content

matter_kit/clusters/
mode.rs

1//! Mode Base (Application Cluster §1.10) — one implementation for every cluster derived from
2//! it.
3//!
4//! §1.10 is not a cluster a device serves. It is a *shape*: about fifteen clusters in the 1.6
5//! library are "derived from the Mode Base cluster and define additional mode tags and
6//! namespaced enumerated values" — Energy EVSE Mode, Water Heater Mode, Dishwasher Mode,
7//! Laundry Washer Mode, and so on. They differ in their id, their PICS code and the mode tags
8//! they define, and in nothing else at all.
9//!
10//! So [`Mode`] takes the derived cluster's table as an argument and serves it. A device gains
11//! a new mode cluster by naming one, not by writing one.
12//!
13//! # A mode is a list the product writes, not an enumeration
14//!
15//! `SupportedModes` is `F` — fixed — and §1.10.6.1 constrains it hard: every entry's `Mode`
16//! must be unique, every `Label` must be unique, and the *sets* of mode tags must be distinct
17//! from one another. [`Mode::new`] checks all three, because a device that shipped two modes
18//! with the same tag set would give a controller no way to tell them apart and no way to know
19//! that it could not.
20//!
21//! # `ChangeToMode` answers in its response, not in its status
22//!
23//! §1.10.7.1.1 is careful about this: an unsupported mode is `SUCCESS` at the interaction
24//! layer with `UnsupportedMode` *inside* the `ChangeToModeResponse`, alongside a human-readable
25//! `StatusText`. The command was delivered and understood; the mode was refused. A cluster
26//! that answered with an IM status instead would lose the text, which §1.10.7.1.1 exists to
27//! carry: "Provide a human readable string in the StatusText field."
28
29use core::cell::Cell;
30
31use crate::clusters::generated::energy_evse_mode as spec_mode;
32use crate::dm::spec::{Conforming, Optional};
33use crate::dm::{Resolved, ResolvedCommand};
34use crate::im::{
35    ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb, WriteOp,
36};
37use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, ToTlv, Value};
38
39use super::Cluster;
40
41pub use spec_mode::attribute::{CURRENT_MODE, ON_MODE, START_UP_MODE, SUPPORTED_MODES};
42pub use spec_mode::command::{CHANGE_TO_MODE, CHANGE_TO_MODE_RESPONSE};
43pub use spec_mode::{ModeOptionStruct, ModeTagStruct, feature};
44
45/// §1.10.7.1.1's `Status` values, as the ChangeToModeResponse carries them.
46///
47/// > Have the Status set to a product-specific Status value representing the error, or
48/// > GenericFailure if a more specific error cannot be provided.
49pub mod status {
50    /// The transition happened.
51    pub const SUCCESS: u8 = 0x00;
52    /// "the NewMode field doesn't match the Mode field of any entry of the SupportedModes list".
53    pub const UNSUPPORTED_MODE: u8 = 0x01;
54    /// The mode exists but the device will not go there, and has nothing more specific to say.
55    pub const GENERIC_FAILURE: u8 = 0x02;
56    /// The first value a derived cluster may define for itself (§1.10.7.2.1).
57    pub const MANUFACTURER_SPECIFIC: u8 = 0x40;
58}
59
60/// §1.10.6.1's constraint on `SupportedModes`: "2 to 255".
61///
62/// Two is the floor because a cluster with one mode offers no choice, and a client that could
63/// not change anything would be reading a constant dressed as a control.
64pub const MODES_MIN: usize = 2;
65
66/// What the product does when the mode changes.
67pub trait ModeHooks {
68    /// §1.10.7.1.1: go to `mode`.
69    ///
70    /// Return `Err((status, text))` to refuse: the status is `GenericFailure` or one of the
71    /// derived cluster's own values, and the text is what a person reads. A dishwasher that
72    /// will not switch to Heavy mid-cycle has a reason, and this is where it says it.
73    fn change_to(&self, mode: u8) -> Result<(), (u8, &'static str)>;
74}
75
76/// One cluster derived from Mode Base.
77///
78/// `CLUSTER` is the derived cluster's id — a const parameter rather than a field, because
79/// [`Cluster::ID`] is an associated constant and that is what lets a tuple of clusters
80/// dispatch to this one. One implementation therefore serves fifteen *distinct types*, which
81/// is exactly right: an endpoint with both an Energy EVSE Mode and a Water Heater Mode has two
82/// clusters, not one cluster twice.
83///
84/// The `SupportedModes` list is borrowed rather than copied — §1.10.6.1 makes it `F`, fixed,
85/// so it is the product's `const` data.
86#[derive(Debug)]
87pub struct Mode<'a, H: ModeHooks, const CLUSTER: ClusterId> {
88    spec: &'static crate::dm::spec::Cluster,
89    hooks: &'a H,
90    supported: &'a [ModeOptionStruct<'a>],
91    current: Cell<u8>,
92    start_up: Cell<Option<u8>>,
93    on_mode: Cell<Option<u8>>,
94}
95
96impl<'a, H: ModeHooks, const CLUSTER: ClusterId> Mode<'a, H, CLUSTER> {
97    /// A mode cluster over `spec` — one of the generated derived tables.
98    ///
99    /// ```rust,ignore
100    /// use matter_kit::clusters::generated::energy_evse_mode;
101    /// use matter_kit::clusters::mode::Mode;
102    ///
103    /// let mode = Mode::<_, { energy_evse_mode::ID }>::new(
104    ///     &energy_evse_mode::CLUSTER, &hooks, SUPPORTED, 0,
105    /// )?;
106    /// ```
107    ///
108    /// Fails when `spec` is not the table for `CLUSTER` — the two are separate arguments and a
109    /// device that crossed them would answer one cluster's paths with another's elements — or
110    /// when `supported` breaks §1.10.6.1: fewer than two entries, a repeated `Mode`, a repeated
111    /// `Label`, or two entries whose mode-tag *sets* are equal. A controller shown two modes it
112    /// cannot tell apart has no way to know that it cannot.
113    pub fn new(
114        spec: &'static crate::dm::spec::Cluster,
115        hooks: &'a H,
116        supported: &'a [ModeOptionStruct<'a>],
117        current: u8,
118    ) -> crate::error::Result<Self> {
119        if spec.id != CLUSTER {
120            return Err(crate::Error::new(crate::ErrorCode::InvalidArgument));
121        }
122        if supported.len() < MODES_MIN {
123            return Err(crate::Error::new(crate::ErrorCode::InvalidArgument));
124        }
125        for (index, entry) in supported.iter().enumerate() {
126            for other in supported.iter().skip(index.saturating_add(1)) {
127                if entry.mode == other.mode
128                    || entry.label == other.label
129                    || same_tags(entry, other)?
130                {
131                    return Err(crate::Error::new(crate::ErrorCode::InvalidArgument));
132                }
133            }
134        }
135        if !supported.iter().any(|entry| entry.mode == current) {
136            // §1.10.6.2: "The value of this field SHALL match the Mode field of one of the
137            // entries in the SupportedModes attribute."
138            return Err(crate::Error::new(crate::ErrorCode::InvalidArgument));
139        }
140        Ok(Self {
141            spec,
142            hooks,
143            supported,
144            current: Cell::new(current),
145            start_up: Cell::new(None),
146            on_mode: Cell::new(None),
147        })
148    }
149
150    /// The descriptor for an instance, derived from the specification's tables.
151    pub fn conforming(
152        spec: &'static crate::dm::spec::Cluster,
153        feature_map: u32,
154        optional: &Optional<'_>,
155    ) -> crate::error::Result<Conforming<4, 1, 1, 0>> {
156        Conforming::new(spec, feature_map, optional)
157    }
158
159    /// Everything §1.10.6 leaves to the product: `StartUpMode`.
160    pub const WITH_START_UP_MODE: Optional<'static> = Optional {
161        attributes: &[START_UP_MODE],
162        commands: &[],
163        events: &[],
164    };
165
166    /// The specification table this instance serves.
167    #[must_use]
168    pub const fn spec(&self) -> &'static crate::dm::spec::Cluster {
169        self.spec
170    }
171
172    /// `CurrentMode` (§1.10.6.2).
173    #[must_use]
174    pub fn current(&self) -> u8 {
175        self.current.get()
176    }
177
178    /// `SupportedModes` (§1.10.6.1).
179    #[must_use]
180    pub const fn supported(&self) -> &'a [ModeOptionStruct<'a>] {
181        self.supported
182    }
183
184    /// `StartUpMode` (§1.10.6.3), `None` for null.
185    #[must_use]
186    pub fn start_up_mode(&self) -> Option<u8> {
187        self.start_up.get()
188    }
189
190    /// Sets `StartUpMode` without a write interaction.
191    ///
192    /// Refuses a mode `SupportedModes` does not list, the same as a write does.
193    pub fn set_start_up_mode(&self, mode: Option<u8>) -> Result<(), Status> {
194        self.checked(mode)?;
195        self.start_up.set(mode);
196        Ok(())
197    }
198
199    /// Sets `OnMode` (§1.10.6.4) without a write interaction.
200    pub fn set_on_mode(&self, mode: Option<u8>) -> Result<(), Status> {
201        self.checked(mode)?;
202        self.on_mode.set(mode);
203        Ok(())
204    }
205
206    /// §1.10.6.3's start-up behaviour.
207    ///
208    /// > If this attribute is not null, the CurrentMode attribute SHALL be set to the
209    /// > StartUpMode value, when the server is powered up, except in the case when the OnMode
210    /// > attribute overrides the StartUpMode attribute.
211    ///
212    /// `start_up_on_off` is On/Off's `StartUpOnOff` where the endpoint has one: §1.10.6.4.1
213    /// makes `OnMode` win when the device is configured to come up *on*, because the endpoint
214    /// is then doing the thing `OnMode` describes.
215    pub fn start(&self, start_up_on_off_is_on: bool) {
216        let chosen = if start_up_on_off_is_on {
217            self.on_mode.get().or_else(|| self.start_up.get())
218        } else {
219            self.start_up.get()
220        };
221        if let Some(mode) = chosen
222            && self.supported.iter().any(|entry| entry.mode == mode)
223        {
224            self.current.set(mode);
225        }
226    }
227
228    /// §1.10.6.4's table: the On/Off cluster on this endpoint changed.
229    ///
230    /// Only `OFF → ON` moves the mode. A device that also acted on `ON → ON` would jump out of
231    /// whatever mode a user had just chosen every time an `On` command was re-sent, which for
232    /// a groupcast is every time anybody turns the room on.
233    pub fn on_off_changed(&self, was_on: bool, is_on: bool) {
234        if was_on || !is_on {
235            return;
236        }
237        if let Some(mode) = self.on_mode.get()
238            && self.hooks.change_to(mode).is_ok()
239        {
240            self.current.set(mode);
241        }
242    }
243
244    /// Whether `mode` is null or one `SupportedModes` lists.
245    fn checked(&self, mode: Option<u8>) -> Result<(), Status> {
246        match mode {
247            None => Ok(()),
248            Some(mode) if self.supported.iter().any(|entry| entry.mode == mode) => Ok(()),
249            // §1.10.6.3: "The value of this field SHALL match the Mode field of one of the
250            // entries in the SupportedModes attribute." A start-up mode the device does not
251            // have would leave it stuck at power-up with nothing to report.
252            Some(_) => Err(Status::ConstraintError),
253        }
254    }
255}
256
257/// Whether two entries carry the same *set* of mode tags (§1.10.6.1).
258///
259/// > This comparison SHALL NOT depend on the order of the ModeTags in the lists. Two sets SHALL
260/// > be considered distinct if one of them contains an element that the other one does not.
261fn same_tags(a: &ModeOptionStruct<'_>, b: &ModeOptionStruct<'_>) -> crate::error::Result<bool> {
262    let contains = |list: &crate::tlv::TlvList<'_, ModeTagStruct>,
263                    tag: &ModeTagStruct|
264     -> crate::error::Result<bool> {
265        for entry in list.iter() {
266            let entry = entry?;
267            if entry.value == tag.value && entry.mfg_code == tag.mfg_code {
268                return Ok(true);
269            }
270        }
271        Ok(false)
272    };
273    for tag in a.mode_tags.iter() {
274        if !contains(&b.mode_tags, &tag?)? {
275            return Ok(false);
276        }
277    }
278    for tag in b.mode_tags.iter() {
279        if !contains(&a.mode_tags, &tag?)? {
280            return Ok(false);
281        }
282    }
283    Ok(true)
284}
285
286impl<H: ModeHooks, const CLUSTER: ClusterId> ClusterHandler for Mode<'_, H, CLUSTER> {
287    fn read(
288        &self,
289        resolved: &Resolved<'_>,
290        _ctx: &InteractionContext<'_>,
291        w: &mut TlvWriter<'_>,
292        tag: Tag,
293    ) -> Result<(), Status> {
294        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
295        let nullable = |w: &mut TlvWriter<'_>, value: Option<u8>| match value {
296            Some(value) => full(w.unsigned(tag, u64::from(value))),
297            None => full(w.null(tag)),
298        };
299        match resolved.attribute {
300            SUPPORTED_MODES => {
301                full(w.start_array(tag))?;
302                for entry in self.supported {
303                    full(entry.to_tlv(w, Tag::Anonymous))?;
304                }
305                full(w.end_container())
306            }
307            CURRENT_MODE => full(w.unsigned(tag, u64::from(self.current.get()))),
308            START_UP_MODE => nullable(w, self.start_up.get()),
309            ON_MODE => nullable(w, self.on_mode.get()),
310            _ => Err(Status::UnsupportedAttribute),
311        }
312    }
313
314    fn write(
315        &self,
316        resolved: &Resolved<'_>,
317        data: &[u8],
318        _op: WriteOp,
319        _ctx: &InteractionContext<'_>,
320    ) -> Result<(), Status> {
321        let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
322        let element = reader
323            .next_element()
324            .map_err(|_| Status::InvalidAction)?
325            .ok_or(Status::InvalidAction)?;
326        let mode = match element.value {
327            Value::Unsigned(value) => {
328                Some(u8::try_from(value).map_err(|_| Status::ConstraintError)?)
329            }
330            Value::Null => None,
331            _ => return Err(Status::InvalidDataType),
332        };
333        match resolved.attribute {
334            START_UP_MODE => self.set_start_up_mode(mode),
335            ON_MODE => self.set_on_mode(mode),
336            // §1.10.6.2's access is `RV`: a client changes the mode with `ChangeToMode`, which
337            // is the only path that can refuse with a reason a person can read.
338            _ => Err(Status::UnsupportedWrite),
339        }
340    }
341
342    fn invoke(
343        &self,
344        resolved: &ResolvedCommand<'_>,
345        fields: Option<&[u8]>,
346        _ctx: &InteractionContext<'_>,
347        w: &mut TlvWriter<'_>,
348        tag: Tag,
349    ) -> Result<Option<CommandId>, StatusIb> {
350        if resolved.command.id != CHANGE_TO_MODE {
351            return Err(Status::UnsupportedCommand.into());
352        }
353        let decoded: spec_mode::ChangeToModeFields =
354            super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
355        let (code, text) = if !self
356            .supported
357            .iter()
358            .any(|entry| entry.mode == decoded.new_mode)
359        {
360            // §1.10.7.1.1: "the ChangeToModeResponse command's Status field SHALL indicate
361            // UnsupportedMode and the StatusText field SHALL be included".
362            (status::UNSUPPORTED_MODE, "no such mode")
363        } else if decoded.new_mode == self.current.get() {
364            // "If the NewMode field is the same as the value of the CurrentMode attribute the
365            // ChangeToModeResponse command SHALL have the Status field set to Success" — not a
366            // transition, and the hooks are not troubled with it.
367            (status::SUCCESS, "")
368        } else {
369            match self.hooks.change_to(decoded.new_mode) {
370                Ok(()) => {
371                    self.current.set(decoded.new_mode);
372                    (status::SUCCESS, "")
373                }
374                Err((code, text)) => (code, text),
375            }
376        };
377        spec_mode::ChangeToModeResponseFields {
378            status: code,
379            status_text: text,
380        }
381        .to_tlv(w, tag)
382        .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
383        Ok(Some(CHANGE_TO_MODE_RESPONSE))
384    }
385}
386
387/// So a tuple of clusters can dispatch to it by id — a different type per derived cluster.
388impl<H: ModeHooks, const CLUSTER: ClusterId> Cluster for Mode<'_, H, CLUSTER> {
389    const ID: ClusterId = CLUSTER;
390}