matter_kit/clusters/identify.rs
1//! Identify, cluster `0x0003` (Application Cluster §1.2).
2//!
3//! > This cluster supports an endpoint identification state (e.g., flashing a light), that
4//! > indicates to an observer (e.g., an installer) which of several nodes and/or endpoints it
5//! > is.
6//!
7//! Small, mandatory on almost every device type, and the one a commissioner uses to ask "which
8//! of these four identical bulbs am I about to name". A device that does not implement it is a
9//! device an installer cannot tell apart from its neighbour.
10//!
11//! # The attribute that deliberately does not report
12//!
13//! `IdentifyTime` counts down every second, and §1.2.5.1 says a subscriber must *not* be told
14//! about it:
15//!
16//! > Changes to this attribute SHALL only be marked as reportable in the following cases:
17//! > when it changes from 0 to any other value and vice versa, or when it is written by a
18//! > client, or when the value is set by an Identify command.
19//!
20//! That is §7.12's `Q` quality — quieter reporting — and the reason is arithmetic: a
21//! thirty-second identify would otherwise send thirty reports to every subscriber, for a
22//! number the client already knows how to compute. [`Identify::poll`] therefore reports the
23//! *transition* and not the tick, and a client is told so plainly: "clients SHOULD NOT rely on
24//! the reporting of this attribute in order to keep track of the remaining duration".
25
26use core::cell::RefCell;
27
28use crate::clusters::generated::identify as spec_identify;
29use crate::dm::spec::{Conforming, Optional};
30use crate::dm::{Resolved, ResolvedCommand};
31use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
32use crate::platform::{Duration, Instant};
33use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter};
34
35use super::Cluster;
36
37pub use spec_identify::attribute::{IDENTIFY_TIME, IDENTIFY_TYPE};
38pub use spec_identify::command::{IDENTIFY, TRIGGER_EFFECT};
39pub use spec_identify::{
40 EffectIdentifierEnum, EffectVariantEnum, ID, IdentifyTypeEnum, PICS, REVISION,
41};
42
43/// §1.2.5.1's countdown: "The IdentifyTime attribute SHALL be decremented every second".
44pub const TICK: Duration = Duration::from_secs(1);
45
46/// What the device does while it is identifying itself.
47///
48/// The cluster owns the countdown; the hardware is the application's. §1.2.5.1 recommends
49/// "flashing a light with a period of 0.5 seconds", but what an endpoint actually has —
50/// [`IdentifyTypeEnum`] ranges from a lighting output to a beep to a window blind — is
51/// something only the product knows.
52pub trait IdentifyHooks {
53 /// The endpoint has started or stopped identifying itself.
54 ///
55 /// Called on the *transition* only, which is the same rule §1.2.5.1 gives for reporting:
56 /// a device that re-armed its blink every second would blink in lockstep with the tick
57 /// rather than at the half-second the specification asks for.
58 fn identifying(&self, on: bool);
59
60 /// §1.2.6.2's `TriggerEffect` — a one-off piece of feedback, not the identify state.
61 ///
62 /// "it is not the same as and does not replace the identify mechanism used during
63 /// commissioning": this is the green flash when a light joins a network. The default does
64 /// nothing, because a device with no way to show an effect is not obliged to invent one —
65 /// and the command is optional.
66 fn trigger_effect(&self, effect: EffectIdentifierEnum, variant: EffectVariantEnum) {
67 let _ = (effect, variant);
68 }
69}
70
71/// Identify, with the device's hooks.
72#[derive(Debug)]
73pub struct Identify<'a, H: IdentifyHooks> {
74 hooks: &'a H,
75 kind: IdentifyTypeEnum,
76 state: RefCell<State>,
77}
78
79#[derive(Debug, Clone, Copy)]
80struct State {
81 remaining: u16,
82 next_tick: Option<Instant>,
83}
84
85impl<'a, H: IdentifyHooks> Identify<'a, H> {
86 /// A cluster over `hooks`, presenting itself the way `kind` says.
87 ///
88 /// §1.2.5.2: "The value None SHALL NOT be used if the device is capable of presenting its
89 /// identification state using one of the other methods" — a device that can flash a light
90 /// and says `None` has told a commissioner not to bother asking, which is the opposite of
91 /// what the cluster is for.
92 #[must_use]
93 pub const fn new(hooks: &'a H, kind: IdentifyTypeEnum) -> Self {
94 Self {
95 hooks,
96 kind,
97 state: RefCell::new(State {
98 remaining: 0,
99 next_tick: None,
100 }),
101 }
102 }
103
104 /// The descriptor for an instance, derived from the specification's own tables.
105 pub fn conforming(optional: &Optional<'_>) -> crate::error::Result<Conforming<2, 2, 0, 0>> {
106 Conforming::new(&spec_identify::CLUSTER, 0, optional)
107 }
108
109 /// Everything §1.2.6 leaves to the product: `TriggerEffect`.
110 pub const WITH_TRIGGER_EFFECT: Optional<'static> = Optional {
111 attributes: &[],
112 commands: &[TRIGGER_EFFECT],
113 events: &[],
114 };
115
116 /// `IdentifyTime` — seconds remaining.
117 #[must_use]
118 pub fn remaining(&self) -> u16 {
119 self.state.borrow().remaining
120 }
121
122 /// Whether the endpoint is identifying itself.
123 #[must_use]
124 pub fn is_identifying(&self) -> bool {
125 self.remaining() > 0
126 }
127
128 /// How this endpoint presents itself.
129 #[must_use]
130 pub const fn kind(&self) -> IdentifyTypeEnum {
131 self.kind
132 }
133
134 /// Sets `IdentifyTime`, starting or stopping the state (§1.2.5.1).
135 ///
136 /// The one place the hook is called, so a write from a client and an `Identify` command
137 /// cannot behave differently — which they would if each did its own bookkeeping.
138 pub fn set_time(&self, seconds: u16, now: Instant) {
139 let transition = {
140 let mut state = self.state.borrow_mut();
141 let was = state.remaining > 0;
142 state.remaining = seconds;
143 state.next_tick = (seconds > 0).then(|| now.saturating_add(TICK));
144 let is = seconds > 0;
145 (was != is).then_some(is)
146 };
147 if let Some(on) = transition {
148 self.hooks.identifying(on);
149 }
150 }
151
152 /// When [`Identify::poll`] next has something to do.
153 #[must_use]
154 pub fn wake_at(&self) -> Option<Instant> {
155 self.state.borrow().next_tick
156 }
157
158 /// Runs §1.2.5.1's one-second countdown.
159 ///
160 /// Catches up on elapsed time rather than counting calls, so a device that polls late —
161 /// or was asleep — stops identifying when it said it would rather than however many
162 /// wake-ups later.
163 pub fn poll(&self, now: Instant) {
164 let stopped = {
165 let mut state = self.state.borrow_mut();
166 let Some(mut due) = state.next_tick else {
167 return;
168 };
169 let mut ticks = 0u32;
170 while now >= due && state.remaining > 0 && ticks < MAX_CATCH_UP {
171 ticks = ticks.saturating_add(1);
172 due = due.saturating_add(TICK);
173 state.remaining = state.remaining.saturating_sub(1);
174 }
175 if state.remaining == 0 {
176 state.next_tick = None;
177 true
178 } else {
179 state.next_tick = Some(due);
180 false
181 }
182 };
183 if stopped {
184 self.hooks.identifying(false);
185 }
186 }
187}
188
189/// How many missed seconds one `poll` catches up on — an hour's worth, which is longer than
190/// `IdentifyTime`'s useful range and bounded so a device that slept for a week does not spin.
191const MAX_CATCH_UP: u32 = 3600;
192
193impl<H: IdentifyHooks> ClusterHandler for Identify<'_, H> {
194 fn read(
195 &self,
196 resolved: &Resolved<'_>,
197 _ctx: &InteractionContext<'_>,
198 w: &mut TlvWriter<'_>,
199 tag: Tag,
200 ) -> Result<(), Status> {
201 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
202 match resolved.attribute {
203 IDENTIFY_TIME => full(w.unsigned(tag, u64::from(self.remaining()))),
204 IDENTIFY_TYPE => full(w.unsigned(tag, u64::from(self.kind.value()))),
205 _ => Err(Status::UnsupportedAttribute),
206 }
207 }
208
209 fn write(
210 &self,
211 resolved: &Resolved<'_>,
212 data: &[u8],
213 _op: crate::im::WriteOp,
214 ctx: &InteractionContext<'_>,
215 ) -> Result<(), Status> {
216 if resolved.attribute != IDENTIFY_TIME {
217 return Err(Status::UnsupportedWrite);
218 }
219 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
220 let element = reader
221 .next_element()
222 .map_err(|_| Status::InvalidAction)?
223 .ok_or(Status::InvalidAction)?;
224 let seconds = u16::try_from(element.unsigned().map_err(|_| Status::ConstraintError)?)
225 .map_err(|_| Status::ConstraintError)?;
226 self.set_time(seconds, ctx.now);
227 Ok(())
228 }
229
230 fn invoke(
231 &self,
232 resolved: &ResolvedCommand<'_>,
233 fields: Option<&[u8]>,
234 ctx: &InteractionContext<'_>,
235 _w: &mut TlvWriter<'_>,
236 _tag: Tag,
237 ) -> Result<Option<CommandId>, StatusIb> {
238 let fields = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
239 match resolved.command.id {
240 IDENTIFY => {
241 let decoded: spec_identify::IdentifyFields = super::decode_fields(fields)?;
242 self.set_time(decoded.identify_time, ctx.now);
243 Ok(None)
244 }
245 TRIGGER_EFFECT => {
246 // §1.2.6.2.1: "SHALL contain one of the non-reserved values" — a reserved one
247 // is refused rather than shown as whichever effect is nearest, because what a
248 // future revision assigns must not decide what this device does today. The
249 // generated enumeration's `from_tlv` is what enforces it.
250 let decoded: spec_identify::TriggerEffectFields = super::decode_fields(fields)?;
251 self.hooks
252 .trigger_effect(decoded.effect_identifier, decoded.effect_variant);
253 Ok(None)
254 }
255 _ => Err(Status::UnsupportedCommand.into()),
256 }
257 }
258}
259
260/// §1.3.7.6's `AddGroupIfIdentifying` asks the endpoint whether it is identifying; this is
261/// the answer when the endpoint has an Identify cluster.
262impl<H: IdentifyHooks> crate::clusters::groups::Identifying for Identify<'_, H> {
263 fn is_identifying(&self) -> bool {
264 Self::is_identifying(self)
265 }
266}
267
268/// So a tuple of clusters can dispatch to it by id.
269impl<H: IdentifyHooks> Cluster for Identify<'_, H> {
270 const ID: ClusterId = ID;
271}