matter_kit/clusters/level_control.rs
1//! Level Control, cluster `0x0008` (Application Cluster §1.6).
2//!
3//! > This command will move the device to the specified level.
4//!
5//! Dimming. Also volume, fan speed, and how far a blind is open — §1.6.6.2 is careful to say
6//! "the meaning of 'level' is device dependent".
7//!
8//! # Two sets of commands, and the difference is the whole cluster
9//!
10//! `MoveToLevel` and `MoveToLevelWithOnOff` take identical fields and do nearly identical
11//! things. §1.6.4.1.2 says what separates them:
12//!
13//! > The first set is used to maintain independence between the CurrentLevel and OnOff
14//! > attributes ... As examples, this represents the behavior of a volume control with a
15//! > separate mute button, or a 'turn to set level and press to turn on/off' light dimmer.
16//! > The second set is used to link the CurrentLevel and OnOff attributes.
17//!
18//! A device that implemented one set and aliased the other would be one of those two products
19//! pretending to be the other.
20//!
21//! # A command to a light that is off
22//!
23//! §1.6.6.9: a `Move`, `MoveToLevel`, `Step` or `Stop` — the ones *without* On/Off — does
24//! nothing at all when the On/Off cluster on the same endpoint says the device is off, unless
25//! `ExecuteIfOff` is set. This is the rule that keeps a dimmer from silently winding a lamp up
26//! while it is switched off, so that turning it on later blinds somebody.
27//!
28//! The bit is not read from the attribute directly: every affected command carries
29//! `OptionsMask` and `OptionsOverride`, and the value in force is the attribute with the
30//! masked bits replaced. A client can therefore say "this once" without writing a
31//! commissioning-time attribute.
32//!
33//! # What this cluster does not do
34//!
35//! Fade a lamp when the *On/Off* cluster is commanded. §1.6.4.1 is explicit that the coupling
36//! is the product's choice — "dependencies MAY be introduced between them. Facilities are
37//! provided to introduce dependencies if required" — so [`LevelControl::on_off_changed`] is
38//! the facility, called by the device from its own `OnOffHooks::set`, and nothing happens
39//! unless it does.
40
41use core::cell::{Cell, RefCell};
42
43use crate::clusters::generated::level_control as spec_level;
44use crate::dm::spec::{Conforming, Optional};
45use crate::dm::{Resolved, ResolvedCommand};
46use crate::im::{
47 ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb, WriteOp,
48};
49use crate::platform::{Duration, Instant};
50use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
51
52use super::Cluster;
53
54pub use spec_level::attribute::{
55 CURRENT_FREQUENCY, CURRENT_LEVEL, DEFAULT_MOVE_RATE, MAX_FREQUENCY, MAX_LEVEL, MIN_FREQUENCY,
56 MIN_LEVEL, OFF_TRANSITION_TIME, ON_LEVEL, ON_OFF_TRANSITION_TIME, ON_TRANSITION_TIME, OPTIONS,
57 REMAINING_TIME, START_UP_CURRENT_LEVEL,
58};
59pub use spec_level::command::{
60 MOVE, MOVE_TO_CLOSEST_FREQUENCY, MOVE_TO_LEVEL, MOVE_TO_LEVEL_WITH_ON_OFF, MOVE_WITH_ON_OFF,
61 STEP, STEP_WITH_ON_OFF, STOP, STOP_WITH_ON_OFF,
62};
63pub use spec_level::{ID, MoveModeEnum, OptionsBitmap, PICS, REVISION, StepModeEnum, feature};
64
65/// §1.6.6.3's unit: `RemainingTime` and every `TransitionTime` field are in tenths of a second.
66pub const TICK: Duration = Duration::from_millis(100);
67
68/// §1.6.4.2's lighting range. `0x00` "SHALL NOT be used"; `0x01` is the minimum a device can
69/// attain and `0xFE` the maximum.
70pub const LIGHTING_MIN: u8 = 1;
71/// The top of §1.6.4.2's range.
72pub const LIGHTING_MAX: u8 = 254;
73
74/// How many ticks one `poll` catches up on — an hour, bounded so a device that slept for a
75/// week does not spin through a week of hundredth-second steps.
76const MAX_CATCH_UP: u32 = 36_000;
77
78/// What the device does when the level changes.
79pub trait LevelControlHooks {
80 /// The level changed.
81 ///
82 /// `None` is §1.6.4.2's null — "A value of null SHALL represent an undefined value" — which
83 /// a device reports before it knows its own level, not as a synonym for zero.
84 ///
85 /// Called for every step of a transition, because a transition is what the hardware is for:
86 /// §1.6.7.1.1 asks that "the movement SHALL be as continuous as technically practical, i.e.,
87 /// not a step function".
88 fn level(&self, level: Option<u8>);
89
90 /// §1.6.7.5: change to `frequency`, or to the closest the device can generate.
91 ///
92 /// Returns whether it could. "If the device cannot approximate the frequency, then it SHALL
93 /// return a default response with an error code of CONSTRAINT_ERROR. Determining if a
94 /// requested frequency can be approximated by a supported frequency is a
95 /// manufacturer-specific decision" — which is why it is the product's answer and not this
96 /// cluster's. The default refuses, which is right for a device with no `Frequency` feature.
97 fn frequency(&self, frequency: u16) -> bool {
98 let _ = frequency;
99 false
100 }
101}
102
103/// What Level Control needs from the On/Off cluster on the same endpoint.
104///
105/// Two different questions, and §1.6 asks them at different moments: whether the device is on
106/// (§1.6.6.9's gate, before a command without On/Off runs) and turning it on or off (§1.6.7.6,
107/// as a 'with On/Off' command crosses the minimum level).
108pub trait OnOffState {
109 /// Whether an On/Off cluster exists on this endpoint at all.
110 ///
111 /// §1.6.6.9's gate needs all four of its criteria, and this is the second. An endpoint with
112 /// no On/Off cluster never blocks a command, which is not the same as one whose lamp
113 /// happens to be on.
114 fn present(&self) -> bool {
115 true
116 }
117
118 /// `OnOff`, as the cluster on this endpoint reports it.
119 fn is_on(&self) -> bool;
120
121 /// §1.6.7.6: set `OnOff` because the level crossed the minimum.
122 ///
123 /// §1.6.4.1.4 makes this update `GlobalSceneControl` too, which is why it is a distinct
124 /// entry point rather than a plain setter: a level command that turns a light on is one of
125 /// the commands §1.5.6.3 lists as marking the global scene stale.
126 fn set_from_level(&self, on: bool);
127}
128
129/// An endpoint with no On/Off cluster.
130#[derive(Debug, Clone, Copy, Default)]
131pub struct NoOnOff;
132
133impl OnOffState for NoOnOff {
134 fn present(&self) -> bool {
135 false
136 }
137
138 fn is_on(&self) -> bool {
139 // There is no `OnOff` attribute to report, and saying "on" would be a convenient lie:
140 // §1.6.6.9's gate is closed by *present and off*, so `present` is what has to carry
141 // the fact. A second encoding of it here would mean an implementor who got `present`
142 // wrong still behaved correctly, which is a rule nothing can test.
143 false
144 }
145
146 fn set_from_level(&self, _on: bool) {}
147}
148
149/// What the level is doing.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151enum Motion {
152 /// Nothing; `RemainingTime` is zero.
153 Idle,
154 /// §1.6.7.1 — a timed move to a level.
155 Transition {
156 from: u8,
157 to: u8,
158 /// Total duration in ticks (tenths of a second); zero means "as fast as it is able".
159 ticks: u32,
160 elapsed: u32,
161 with_on_off: bool,
162 },
163 /// §1.6.7.2 — an open-ended move at a rate, until a boundary or a `Stop`.
164 Move {
165 up: bool,
166 /// Units per second.
167 rate: u8,
168 /// Accumulated hundredths of a unit, so a slow rate still moves.
169 fraction: u32,
170 with_on_off: bool,
171 },
172}
173
174#[derive(Debug)]
175struct State {
176 level: Option<u8>,
177 motion: Motion,
178 next_tick: Option<Instant>,
179}
180
181/// Level Control, with the device's hooks and whatever On/Off cluster shares the endpoint.
182#[derive(Debug)]
183pub struct LevelControl<'a, H: LevelControlHooks, O: OnOffState = NoOnOff> {
184 hooks: &'a H,
185 on_off: &'a O,
186 feature_map: u32,
187 min_level: u8,
188 max_level: u8,
189 state: RefCell<State>,
190 options: Cell<OptionsBitmap>,
191 on_off_transition_time: Cell<u16>,
192 on_level: Cell<Option<u8>>,
193 on_transition_time: Cell<Option<u16>>,
194 off_transition_time: Cell<Option<u16>>,
195 default_move_rate: Cell<Option<u8>>,
196 start_up_current_level: Cell<Option<u8>>,
197 frequency: Cell<u16>,
198 min_frequency: u16,
199 max_frequency: u16,
200 /// Whether the motion in progress was started by a 'with On/Off' command, so that
201 /// §1.6.7.6's "set OnOff to FALSE" applies when it lands on the minimum.
202 with_on_off_pending: Cell<bool>,
203}
204
205impl<'a, H: LevelControlHooks> LevelControl<'a, H, NoOnOff> {
206 /// A cluster on an endpoint with no On/Off — a volume control, say.
207 #[must_use]
208 pub fn new(hooks: &'a H, feature_map: u32) -> Self {
209 Self::with_on_off(hooks, &NoOnOff, feature_map)
210 }
211}
212
213impl<'a, H: LevelControlHooks, O: OnOffState> LevelControl<'a, H, O> {
214 /// A cluster coupled to the On/Off cluster `on_off` on the same endpoint.
215 #[must_use]
216 pub fn with_on_off(hooks: &'a H, on_off: &'a O, feature_map: u32) -> Self {
217 // §1.6.6.4 and §1.6.6.5: "This value is constrained by all lighting device types to 1
218 // ... when the Lighting feature is supported this value SHALL be 1", and likewise 254
219 // for the maximum. A device without Lighting may narrow them with `with_range`.
220 let (min_level, max_level) = (LIGHTING_MIN, LIGHTING_MAX);
221 Self {
222 hooks,
223 on_off,
224 feature_map,
225 min_level,
226 max_level,
227 state: RefCell::new(State {
228 level: None,
229 motion: Motion::Idle,
230 next_tick: None,
231 }),
232 options: Cell::new(OptionsBitmap::empty()),
233 on_off_transition_time: Cell::new(0),
234 on_level: Cell::new(None),
235 on_transition_time: Cell::new(None),
236 off_transition_time: Cell::new(None),
237 default_move_rate: Cell::new(None),
238 start_up_current_level: Cell::new(None),
239 frequency: Cell::new(0),
240 min_frequency: 0,
241 max_frequency: 0,
242 with_on_off_pending: Cell::new(false),
243 }
244 }
245
246 /// The same cluster over a narrower range (§1.6.6.4, §1.6.6.5).
247 ///
248 /// Only for a device *without* the Lighting feature: with it, the specification fixes the
249 /// range at 1..=254, and a lighting device that narrowed it would report a `MinLevel` its
250 /// own device type forbids.
251 #[must_use]
252 pub fn with_range(mut self, min_level: u8, max_level: u8) -> Self {
253 if self.feature_map & feature::LIGHTING == 0 && min_level <= max_level {
254 self.min_level = min_level;
255 self.max_level = max_level;
256 }
257 self
258 }
259
260 /// The same cluster with the `Frequency` feature's range (§1.6.6.7, §1.6.6.8).
261 #[must_use]
262 pub const fn with_frequency(mut self, min: u16, max: u16) -> Self {
263 self.min_frequency = min;
264 self.max_frequency = max;
265 self
266 }
267
268 /// The descriptor for an instance, derived from the specification's tables.
269 pub fn conforming(
270 feature_map: u32,
271 optional: &Optional<'_>,
272 ) -> crate::error::Result<Conforming<14, 9, 0, 0>> {
273 Conforming::new(&spec_level::CLUSTER, feature_map, optional)
274 }
275
276 /// Everything §1.6.6 leaves to the product.
277 pub const WITH_ALL_OPTIONAL: Optional<'static> = Optional {
278 attributes: &[
279 MIN_LEVEL,
280 MAX_LEVEL,
281 ON_OFF_TRANSITION_TIME,
282 ON_TRANSITION_TIME,
283 OFF_TRANSITION_TIME,
284 DEFAULT_MOVE_RATE,
285 ],
286 commands: &[],
287 events: &[],
288 };
289
290 /// Just the two range attributes, which a lighting device type requires.
291 pub const WITH_RANGE: Optional<'static> = Optional {
292 attributes: &[MIN_LEVEL, MAX_LEVEL],
293 commands: &[],
294 events: &[],
295 };
296
297 /// §1.6.6.15's start-up behaviour.
298 ///
299 /// | `StartUpCurrentLevel` | what `CurrentLevel` becomes |
300 /// |---|---|
301 /// | 0 | the minimum the device permits |
302 /// | null | `previous` — what it was before the power cut |
303 /// | anything else | that value |
304 ///
305 /// `previous` is the device's to remember; this cluster persists nothing. A device that
306 /// stores nothing passes `None`, which is the null level — honest for a lamp that does not
307 /// know how bright it was.
308 pub fn start(&self, previous: Option<u8>) {
309 let level = match self.start_up_current_level.get() {
310 Some(0) => Some(self.min_level),
311 Some(other) => Some(other.clamp(self.min_level, self.max_level)),
312 None => previous.map(|level| level.clamp(self.min_level, self.max_level)),
313 };
314 self.state.borrow_mut().level = level;
315 self.hooks.level(level);
316 }
317
318 /// `CurrentLevel` (§1.6.6.2).
319 #[must_use]
320 pub fn level(&self) -> Option<u8> {
321 self.state.borrow().level
322 }
323
324 /// `RemainingTime` (§1.6.6.3), in tenths of a second.
325 #[must_use]
326 pub fn remaining_time(&self) -> u16 {
327 match self.state.borrow().motion {
328 Motion::Idle => 0,
329 Motion::Transition { ticks, elapsed, .. } => {
330 u16::try_from(ticks.saturating_sub(elapsed)).unwrap_or(u16::MAX)
331 }
332 // §1.6.7.2 has no end: a Move runs to a boundary. The time to that boundary is
333 // what remains, which is what a client asking "how long" wants to know.
334 Motion::Move { up, rate, .. } => {
335 let level = self.state.borrow().level.unwrap_or(self.min_level);
336 let distance = if up {
337 u32::from(self.max_level.saturating_sub(level))
338 } else {
339 u32::from(level.saturating_sub(self.min_level))
340 };
341 // Rounded up, so "one tenth left" never reports zero — a client polling
342 // `RemainingTime` would otherwise see the move finish before it did.
343 let rate = u32::from(rate);
344 let Some(tenths) = distance
345 .saturating_mul(10)
346 .saturating_add(rate.saturating_sub(1))
347 .checked_div(rate)
348 else {
349 return 0;
350 };
351 u16::try_from(tenths).unwrap_or(u16::MAX)
352 }
353 }
354 }
355
356 /// `MinLevel` (§1.6.6.4).
357 #[must_use]
358 pub const fn min_level(&self) -> u8 {
359 self.min_level
360 }
361
362 /// `MaxLevel` (§1.6.6.5).
363 #[must_use]
364 pub const fn max_level(&self) -> u8 {
365 self.max_level
366 }
367
368 /// `Options` (§1.6.6.9).
369 #[must_use]
370 pub fn options(&self) -> OptionsBitmap {
371 self.options.get()
372 }
373
374 /// `OnLevel` (§1.6.6.11) — the level an `On` command restores, or null for none.
375 #[must_use]
376 pub fn on_level(&self) -> Option<u8> {
377 self.on_level.get()
378 }
379
380 /// Sets `OnLevel` without a write interaction, for a device with a fixed one.
381 pub fn set_on_level(&self, level: Option<u8>) {
382 self.on_level.set(level);
383 }
384
385 /// Sets `StartUpCurrentLevel` (§1.6.6.15) without a write interaction.
386 pub fn set_start_up_level(&self, level: Option<u8>) {
387 self.start_up_current_level.set(level);
388 }
389
390 /// When [`LevelControl::poll`] next has something to do.
391 ///
392 /// `None` while nothing is moving, which is the ordinary case — a lamp sitting at a level
393 /// needs no clock, and an intermittently connected device can sleep.
394 #[must_use]
395 pub fn wake_at(&self) -> Option<Instant> {
396 self.state.borrow().next_tick
397 }
398
399 /// Advances whatever is in motion.
400 ///
401 /// Catches up on elapsed time rather than counting calls, so a device that polls late
402 /// arrives at the level it promised rather than however many ticks behind.
403 pub fn poll(&self, now: Instant) {
404 let (level, finished) = {
405 let mut state = self.state.borrow_mut();
406 let Some(mut due) = state.next_tick else {
407 return;
408 };
409 if now < due {
410 return;
411 }
412 let mut ticks = 0u32;
413 while now >= due && ticks < MAX_CATCH_UP && state.motion != Motion::Idle {
414 ticks = ticks.saturating_add(1);
415 due = due.saturating_add(TICK);
416 self.advance(&mut state);
417 }
418 let finished = state.motion == Motion::Idle;
419 state.next_tick = if finished { None } else { Some(due) };
420 (state.level, finished)
421 };
422 self.hooks.level(level);
423 if finished {
424 self.settle(level);
425 }
426 }
427
428 /// One tick of whatever is in motion. `state` is already borrowed.
429 fn advance(&self, state: &mut State) {
430 match &mut state.motion {
431 Motion::Idle => {}
432 Motion::Transition {
433 from,
434 to,
435 ticks,
436 elapsed,
437 ..
438 } => {
439 *elapsed = elapsed.saturating_add(1);
440 if *elapsed >= *ticks {
441 state.level = Some(*to);
442 state.motion = Motion::Idle;
443 } else {
444 // §1.6.7.1.1: "as continuous as technically practical, i.e., not a step
445 // function" — so the level is interpolated every tenth of a second rather
446 // than jumped at the end.
447 let span = i32::from(*to).saturating_sub(i32::from(*from));
448 let moved = span
449 .saturating_mul(i32::try_from(*elapsed).unwrap_or(i32::MAX))
450 .checked_div(i32::try_from(*ticks).unwrap_or(1))
451 .unwrap_or(span);
452 let next = i32::from(*from).saturating_add(moved);
453 state.level = Some(u8::try_from(next.clamp(0, 255)).unwrap_or(*to));
454 }
455 }
456 Motion::Move {
457 up, rate, fraction, ..
458 } => {
459 // One tick is a tenth of a second, so a rate of R units/second moves R/10
460 // units. Accumulating tenths rather than rounding each tick is what lets a
461 // rate of 1 actually move: it would otherwise round to zero forever.
462 *fraction = fraction.saturating_add(u32::from(*rate));
463 let whole = *fraction / 10;
464 *fraction %= 10;
465 let level = state.level.unwrap_or(self.min_level);
466 let next = if *up {
467 u32::from(level)
468 .saturating_add(whole)
469 .min(u32::from(self.max_level))
470 } else {
471 u32::from(level)
472 .saturating_sub(whole)
473 .max(u32::from(self.min_level))
474 };
475 let next = u8::try_from(next).unwrap_or(level);
476 state.level = Some(next);
477 // §1.6.7.2.3: "If the level reaches the maximum allowed for the device, stop."
478 if (*up && next >= self.max_level) || (!*up && next <= self.min_level) {
479 state.motion = Motion::Idle;
480 }
481 }
482 }
483 }
484
485 /// §1.6.7.6's second half, applied when a motion ends.
486 ///
487 /// > If any command that has the effect of setting the CurrentLevel attribute to the
488 /// > minimum level allowed by the device, the OnOff attribute of the On/Off cluster on the
489 /// > same endpoint, if implemented, SHALL be set to FALSE ('Off').
490 fn settle(&self, level: Option<u8>) {
491 if !self.with_on_off_pending.get() {
492 return;
493 }
494 self.with_on_off_pending.set(false);
495 if level == Some(self.min_level) {
496 self.on_off.set_from_level(false);
497 }
498 }
499}
500
501impl<H: LevelControlHooks, O: OnOffState> LevelControl<'_, H, O> {
502 /// §1.6.7.1.1's temporary Options bitmap.
503 ///
504 /// > Each bit in the Options attribute SHALL determine the corresponding bit in the
505 /// > temporary Options bitmap, unless the OptionsMask field is present and has the
506 /// > corresponding bit set to 1, in which case the corresponding bit in the
507 /// > OptionsOverride field SHALL determine the corresponding bit.
508 ///
509 /// So a client can say "just this once" without writing an attribute §1.6.6.9 calls
510 /// "meant to be changed only during commissioning".
511 fn effective(&self, mask: OptionsBitmap, override_bits: OptionsBitmap) -> OptionsBitmap {
512 (self.options.get() & !mask) | (override_bits & mask)
513 }
514
515 /// §1.6.6.9's four criteria. All of them, or the command runs.
516 fn blocked(&self, options: OptionsBitmap) -> bool {
517 self.on_off.present()
518 && !self.on_off.is_on()
519 && !options.contains(OptionsBitmap::EXECUTE_IF_OFF)
520 }
521
522 /// §1.6.7.1.1: a null `TransitionTime` means `OnOffTransitionTime`, and an unimplemented
523 /// `OnOffTransitionTime` means "as fast as it is able".
524 fn transition_ticks(&self, requested: crate::tlv::Nullable<u16>) -> u32 {
525 match requested.0 {
526 Some(tenths) => u32::from(tenths),
527 None => u32::from(self.on_off_transition_time.get()),
528 }
529 }
530
531 /// Starts a timed move to `target`, clipped to the device's range.
532 fn begin_transition(&self, target: u8, ticks: u32, with_on_off: bool, now: Instant) {
533 // §1.6.7.1.1: "If the value of the Level field is below the MinLevel or above the
534 // MaxLevel for the device, the value SHALL be clipped to the applicable boundary
535 // value." Clipped, not refused — a client that asks for 255 gets the brightest the
536 // lamp has.
537 let target = target.clamp(self.min_level, self.max_level);
538 // §1.6.7.6: "Before commencing any command that has the effect of setting the
539 // CurrentLevel attribute above the minimum level allowed by the device, the OnOff
540 // attribute ... SHALL be set to TRUE." Before, so the lamp is already on when the fade
541 // starts rather than snapping on at the end of it.
542 if with_on_off && target > self.min_level {
543 self.on_off.set_from_level(true);
544 }
545 let level = {
546 let mut state = self.state.borrow_mut();
547 let from = state.level.unwrap_or(self.min_level);
548 if ticks == 0 || from == target {
549 state.level = Some(target);
550 state.motion = Motion::Idle;
551 state.next_tick = None;
552 } else {
553 state.motion = Motion::Transition {
554 from,
555 to: target,
556 ticks,
557 elapsed: 0,
558 with_on_off,
559 };
560 state.next_tick = Some(now.saturating_add(TICK));
561 }
562 state.level
563 };
564 self.with_on_off_pending.set(with_on_off);
565 self.hooks.level(level);
566 if self.state.borrow().motion == Motion::Idle {
567 self.settle(level);
568 }
569 }
570
571 /// Starts an open-ended move, or does nothing if the rate is unusable.
572 fn begin_move(&self, up: bool, rate: u8, with_on_off: bool, now: Instant) {
573 if with_on_off && up {
574 self.on_off.set_from_level(true);
575 }
576 if rate == 0 {
577 // "If the Rate field is null and the DefaultMoveRate attribute is either not
578 // supported or set to null, then the device SHOULD move as fast as it is able."
579 let target = if up { self.max_level } else { self.min_level };
580 self.begin_transition(target, 0, with_on_off, now);
581 return;
582 }
583 {
584 let mut state = self.state.borrow_mut();
585 state.motion = Motion::Move {
586 up,
587 rate,
588 fraction: 0,
589 with_on_off,
590 };
591 state.next_tick = Some(now.saturating_add(TICK));
592 }
593 self.with_on_off_pending.set(with_on_off);
594 }
595
596 /// §1.6.7.4: stop whatever is moving, and leave the level where it is.
597 fn stop(&self) {
598 let level = {
599 let mut state = self.state.borrow_mut();
600 state.motion = Motion::Idle;
601 state.next_tick = None;
602 state.level
603 };
604 // "The value of CurrentLevel SHALL be left at its value upon receipt of the Stop
605 // command" — so no `set_from_level(false)` here even if the level happens to be the
606 // minimum: nothing *commanded* it there.
607 self.with_on_off_pending.set(false);
608 let _ = level;
609 }
610
611 /// §1.6.4.1.1's coupling, for a device that wants it.
612 ///
613 /// Called by the product from its own `OnOffHooks::set`, because §1.6.4.1 makes the whole
614 /// dependency optional: "dependencies MAY be introduced between them. Facilities are
615 /// provided to introduce dependencies if required."
616 ///
617 /// > **On.** Temporarily store CurrentLevel. Set CurrentLevel to the minimum level allowed
618 /// > for the device. Change CurrentLevel to OnLevel, or to the stored level if OnLevel is
619 /// > not defined, over the time period OnOffTransitionTime.
620 ///
621 /// `stored` is the level to return to — what the device remembers from before it was
622 /// switched off. The specification's own note is the reason it is a parameter: "If another
623 /// of these commands is received, before the transition is completed, the originally
624 /// stored CurrentLevel SHALL be preserved and restored", and only the device knows which
625 /// value that is across a power cut.
626 pub fn on_off_changed(&self, on: bool, stored: Option<u8>, now: Instant) {
627 let ticks = if on {
628 u32::from(
629 self.on_transition_time
630 .get()
631 .unwrap_or_else(|| self.on_off_transition_time.get()),
632 )
633 } else {
634 u32::from(
635 self.off_transition_time
636 .get()
637 .unwrap_or_else(|| self.on_off_transition_time.get()),
638 )
639 };
640 if on {
641 let target = self.on_level.get().or(stored).unwrap_or(self.max_level);
642 // "Set CurrentLevel to the minimum level allowed for the device", then fade up
643 // from there — the lamp must not jump to the target and then fade.
644 self.state.borrow_mut().level = Some(self.min_level);
645 self.begin_transition(target, ticks, false, now);
646 } else {
647 self.begin_transition(self.min_level, ticks, false, now);
648 }
649 }
650}
651
652impl<H: LevelControlHooks, O: OnOffState> ClusterHandler for LevelControl<'_, H, O> {
653 fn read(
654 &self,
655 resolved: &Resolved<'_>,
656 _ctx: &InteractionContext<'_>,
657 w: &mut TlvWriter<'_>,
658 tag: Tag,
659 ) -> Result<(), Status> {
660 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
661 let nullable = |w: &mut TlvWriter<'_>, value: Option<u16>| match value {
662 Some(value) => full(w.unsigned(tag, u64::from(value))),
663 None => full(w.null(tag)),
664 };
665 match resolved.attribute {
666 CURRENT_LEVEL => match self.level() {
667 Some(level) => full(w.unsigned(tag, u64::from(level))),
668 None => full(w.null(tag)),
669 },
670 REMAINING_TIME => full(w.unsigned(tag, u64::from(self.remaining_time()))),
671 MIN_LEVEL => full(w.unsigned(tag, u64::from(self.min_level))),
672 MAX_LEVEL => full(w.unsigned(tag, u64::from(self.max_level))),
673 OPTIONS => full(w.unsigned(tag, u64::from(self.options.get().bits()))),
674 ON_OFF_TRANSITION_TIME => {
675 full(w.unsigned(tag, u64::from(self.on_off_transition_time.get())))
676 }
677 ON_LEVEL => match self.on_level.get() {
678 Some(level) => full(w.unsigned(tag, u64::from(level))),
679 None => full(w.null(tag)),
680 },
681 ON_TRANSITION_TIME => nullable(w, self.on_transition_time.get()),
682 OFF_TRANSITION_TIME => nullable(w, self.off_transition_time.get()),
683 DEFAULT_MOVE_RATE => match self.default_move_rate.get() {
684 Some(rate) => full(w.unsigned(tag, u64::from(rate))),
685 None => full(w.null(tag)),
686 },
687 START_UP_CURRENT_LEVEL => match self.start_up_current_level.get() {
688 Some(level) => full(w.unsigned(tag, u64::from(level))),
689 None => full(w.null(tag)),
690 },
691 CURRENT_FREQUENCY => full(w.unsigned(tag, u64::from(self.frequency.get()))),
692 MIN_FREQUENCY => full(w.unsigned(tag, u64::from(self.min_frequency))),
693 MAX_FREQUENCY => full(w.unsigned(tag, u64::from(self.max_frequency))),
694 _ => Err(Status::UnsupportedAttribute),
695 }
696 }
697
698 fn write(
699 &self,
700 resolved: &Resolved<'_>,
701 data: &[u8],
702 _op: WriteOp,
703 _ctx: &InteractionContext<'_>,
704 ) -> Result<(), Status> {
705 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
706 let element = reader
707 .next_element()
708 .map_err(|_| Status::InvalidAction)?
709 .ok_or(Status::InvalidAction)?;
710 let number = |value: &Value<'_>| -> Result<Option<u64>, Status> {
711 match value {
712 Value::Unsigned(value) => Ok(Some(*value)),
713 Value::Null => Ok(None),
714 _ => Err(Status::InvalidDataType),
715 }
716 };
717 let byte = |value: &Value<'_>| -> Result<Option<u8>, Status> {
718 match number(value)? {
719 Some(value) => Ok(Some(
720 u8::try_from(value).map_err(|_| Status::ConstraintError)?,
721 )),
722 None => Ok(None),
723 }
724 };
725 let short = |value: &Value<'_>| -> Result<Option<u16>, Status> {
726 match number(value)? {
727 Some(value) => Ok(Some(
728 u16::try_from(value).map_err(|_| Status::ConstraintError)?,
729 )),
730 None => Ok(None),
731 }
732 };
733 match resolved.attribute {
734 OPTIONS => {
735 let bits = byte(&element.value)?.ok_or(Status::InvalidDataType)?;
736 // §7.19.2: a bit this revision does not define is refused rather than stored
737 // and echoed back as if the device understood it.
738 let options = OptionsBitmap::from_bits(bits).ok_or(Status::ConstraintError)?;
739 self.options.set(options);
740 Ok(())
741 }
742 ON_OFF_TRANSITION_TIME => {
743 self.on_off_transition_time
744 .set(short(&element.value)?.ok_or(Status::InvalidDataType)?);
745 Ok(())
746 }
747 ON_LEVEL => {
748 // §1.6.6.11's constraint is "MinLevel to MaxLevel", and null "has no effect".
749 let level = byte(&element.value)?;
750 if let Some(level) = level
751 && (level < self.min_level || level > self.max_level)
752 {
753 return Err(Status::ConstraintError);
754 }
755 self.on_level.set(level);
756 Ok(())
757 }
758 ON_TRANSITION_TIME => {
759 self.on_transition_time.set(short(&element.value)?);
760 Ok(())
761 }
762 OFF_TRANSITION_TIME => {
763 self.off_transition_time.set(short(&element.value)?);
764 Ok(())
765 }
766 DEFAULT_MOVE_RATE => {
767 // §1.6.6.14's constraint is "min 1": a rate of zero is not a slow move, it is
768 // no move at all, and §1.6.7.2.3 already refuses it on the command.
769 let rate = byte(&element.value)?;
770 if rate == Some(0) {
771 return Err(Status::ConstraintError);
772 }
773 self.default_move_rate.set(rate);
774 Ok(())
775 }
776 START_UP_CURRENT_LEVEL => {
777 self.start_up_current_level.set(byte(&element.value)?);
778 Ok(())
779 }
780 _ => Err(Status::UnsupportedWrite),
781 }
782 }
783
784 fn invoke(
785 &self,
786 resolved: &ResolvedCommand<'_>,
787 fields: Option<&[u8]>,
788 ctx: &InteractionContext<'_>,
789 _w: &mut TlvWriter<'_>,
790 _tag: Tag,
791 ) -> Result<Option<CommandId>, StatusIb> {
792 let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
793 let id = resolved.command.id;
794 let with_on_off = matches!(
795 id,
796 MOVE_TO_LEVEL_WITH_ON_OFF | MOVE_WITH_ON_OFF | STEP_WITH_ON_OFF | STOP_WITH_ON_OFF
797 );
798 match id {
799 MOVE_TO_LEVEL | MOVE_TO_LEVEL_WITH_ON_OFF => {
800 let decoded: spec_level::MoveToLevelFields = super::decode_fields(payload()?)?;
801 let options = self.effective(decoded.options_mask, decoded.options_override);
802 // §1.6.6.9's gate applies only to the four commands *without* On/Off: the
803 // 'with' variants exist precisely to turn the device on.
804 if !with_on_off && self.blocked(options) {
805 return Ok(None);
806 }
807 let ticks = self.transition_ticks(decoded.transition_time);
808 self.begin_transition(decoded.level, ticks, with_on_off, ctx.now);
809 Ok(None)
810 }
811 MOVE | MOVE_WITH_ON_OFF => {
812 let decoded: spec_level::MoveFields = super::decode_fields(payload()?)?;
813 // §1.6.7.2.3: "if the Rate field has a value of zero, the command has no effect
814 // and a response SHALL be returned with the status code set to
815 // INVALID_COMMAND" — checked before the Options gate, because a zero rate is
816 // malformed whether or not the lamp is on.
817 if decoded.rate.0 == Some(0) {
818 return Err(Status::InvalidCommand.into());
819 }
820 let options = self.effective(decoded.options_mask, decoded.options_override);
821 if !with_on_off && self.blocked(options) {
822 return Ok(None);
823 }
824 // §1.6.7.2.2: null means `DefaultMoveRate`, and an absent or null
825 // `DefaultMoveRate` means as fast as the device can.
826 let rate = decoded
827 .rate
828 .0
829 .or_else(|| self.default_move_rate.get())
830 .unwrap_or(0);
831 self.begin_move(
832 decoded.move_mode == MoveModeEnum::Up,
833 rate,
834 with_on_off,
835 ctx.now,
836 );
837 Ok(None)
838 }
839 STEP | STEP_WITH_ON_OFF => {
840 let decoded: spec_level::StepFields = super::decode_fields(payload()?)?;
841 // §1.6.7.3.4: "if the StepSize field has a value of zero, the command has no
842 // effect and a response SHALL be returned with the status code set to
843 // INVALID_COMMAND".
844 if decoded.step_size == 0 {
845 return Err(Status::InvalidCommand.into());
846 }
847 let options = self.effective(decoded.options_mask, decoded.options_override);
848 if !with_on_off && self.blocked(options) {
849 return Ok(None);
850 }
851 let from = self.state.borrow().level.unwrap_or(self.min_level);
852 let up = decoded.step_mode == StepModeEnum::Up;
853 let unclipped = if up {
854 u32::from(from).saturating_add(u32::from(decoded.step_size))
855 } else {
856 u32::from(from).saturating_sub(u32::from(decoded.step_size))
857 };
858 let target = u8::try_from(unclipped.min(u32::from(self.max_level)))
859 .unwrap_or(self.max_level)
860 .clamp(self.min_level, self.max_level);
861 // §1.6.7.3.4: "or until it reaches the minimum level allowed for the device if
862 // this reached in the process. In the latter case, the transition time SHALL be
863 // proportionally reduced." A step that is half clipped takes half the time —
864 // otherwise a stepped-to-the-end dimmer crawls the last inch.
865 let requested = self.transition_ticks(decoded.transition_time);
866 let actual = u32::from(from.abs_diff(target));
867 let ticks = if decoded.step_size == 0 {
868 0
869 } else {
870 requested
871 .saturating_mul(actual)
872 .checked_div(u32::from(decoded.step_size))
873 .unwrap_or(requested)
874 };
875 self.begin_transition(target, ticks, with_on_off, ctx.now);
876 Ok(None)
877 }
878 STOP | STOP_WITH_ON_OFF => {
879 let decoded: spec_level::StopFields = super::decode_fields(payload()?)?;
880 let options = self.effective(decoded.options_mask, decoded.options_override);
881 if !with_on_off && self.blocked(options) {
882 return Ok(None);
883 }
884 self.stop();
885 Ok(None)
886 }
887 MOVE_TO_CLOSEST_FREQUENCY => {
888 let decoded: spec_level::MoveToClosestFrequencyFields =
889 super::decode_fields(payload()?)?;
890 if self.hooks.frequency(decoded.frequency) {
891 self.frequency.set(decoded.frequency);
892 Ok(None)
893 } else {
894 Err(Status::ConstraintError.into())
895 }
896 }
897 _ => Err(Status::UnsupportedCommand.into()),
898 }
899 }
900}
901
902/// So a tuple of clusters can dispatch to it by id.
903impl<H: LevelControlHooks, O: OnOffState> Cluster for LevelControl<'_, H, O> {
904 const ID: ClusterId = ID;
905}