Skip to main content

matter_kit/clusters/
scenes.rs

1//! Scenes Management, cluster `0x0062` (Application Cluster §1.4).
2//!
3//! > Each scene corresponds to a set of stored values of specified attributes for one or more
4//! > clusters on the same end point as the Scenes Management cluster.
5//!
6//! "Movie night" — the lights at 15%, warm, and the blind down — stored once and recalled with
7//! one command. What a scene actually holds is an *extension field set* per cluster: a list of
8//! attribute ids and values, restricted to attributes carrying §7.13's Scenes ("S") quality.
9//!
10//! # The table is shared with Groups
11//!
12//! §1.3.7.4 makes `RemoveGroup` remove that group's scenes, and §1.3.7.5 makes
13//! `RemoveAllGroups` remove every scene but group 0's. That is a rule about *this* cluster's
14//! data written in *that* cluster's chapter, so the Scene Table is a value of its own —
15//! [`SceneTable`] — that the device gives to both clusters, rather than state hidden inside
16//! one of them. A device that skipped the wiring would accumulate scenes addressed to groups
17//! it has left: storage nobody can reach and nobody can reclaim.
18//!
19//! # Half the table, per fabric
20//!
21//! §1.4.6: "The Scene Table capacity for a given fabric SHALL be less than half (rounded down
22//! towards 0) of the Scene Table entries". Not a nicety — without it the first ecosystem to
23//! commission can fill the table and the second cannot store a single scene.
24//!
25//! # What the cluster does not know
26//!
27//! Which attributes have the Scenes quality, and what setting them means. That lives with the
28//! clusters that own them, behind [`SceneHooks`]: this cluster stores bytes and hands them
29//! back in the right order.
30
31use core::cell::RefCell;
32
33use crate::clusters::generated::scenes_management as spec_scenes;
34use crate::dm::spec::{Conforming, Optional};
35use crate::dm::{Resolved, ResolvedCommand};
36use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
37use crate::msg::{FabricIndex, GroupId};
38use crate::tlv::{Tag, TlvList, TlvWriter, ToTlv};
39
40use super::Cluster;
41use super::groups::GroupMembership;
42
43pub use spec_scenes::attribute::{FABRIC_SCENE_INFO, SCENE_TABLE_SIZE};
44pub use spec_scenes::command::{
45    ADD_SCENE, ADD_SCENE_RESPONSE, COPY_SCENE, COPY_SCENE_RESPONSE, GET_SCENE_MEMBERSHIP,
46    GET_SCENE_MEMBERSHIP_RESPONSE, RECALL_SCENE, REMOVE_ALL_SCENES, REMOVE_ALL_SCENES_RESPONSE,
47    REMOVE_SCENE, REMOVE_SCENE_RESPONSE, STORE_SCENE, STORE_SCENE_RESPONSE, VIEW_SCENE,
48    VIEW_SCENE_RESPONSE,
49};
50pub use spec_scenes::{
51    AttributeValuePairStruct, CopyModeBitmap, ExtensionFieldSetStruct, ID, PICS, REVISION, feature,
52};
53
54/// §1.4.7.5's constraint on `SceneName`: "max 16".
55pub const NAME_MAX: usize = 16;
56
57/// §1.4.9.1: "The scene identifier 0, when used with group identifier 0, is reserved for the
58/// global scene used by the On/Off cluster."
59pub const GLOBAL_SCENE: u8 = 0;
60
61/// §1.4.7.2.2's "undefined scene identifier", which `CurrentScene` reports before any recall.
62pub const UNDEFINED_SCENE: u8 = 0xFF;
63
64/// §1.4.7.5's constraint on `SceneID`: "max 254". 255 is [`UNDEFINED_SCENE`].
65pub const SCENE_MAX: u8 = 254;
66
67/// §1.4.9.2's constraint on `TransitionTime`: "max 60000000" milliseconds — a little over
68/// sixteen hours, which is the longest fade the specification admits.
69pub const TRANSITION_MAX: u32 = 60_000_000;
70
71/// §1.4.7.2.5's constraint on `RemainingCapacity`: "max 253".
72pub const CAPACITY_MAX: u8 = 253;
73
74/// One row of §1.4.7.5's logical Scene Table.
75#[derive(Debug, Clone)]
76struct Entry<const EFS: usize> {
77    fabric: FabricIndex,
78    group: GroupId,
79    scene: u8,
80    name: [u8; NAME_MAX],
81    name_len: usize,
82    transition: u32,
83    /// The encoded members of the `ExtensionFieldSetStructs` array, exactly as they arrived.
84    ///
85    /// Kept as bytes rather than decoded, because what they *mean* belongs to the clusters
86    /// that own the attributes — and because re-encoding a structure this cluster does not
87    /// interpret is a chance to change it.
88    fields: heapless::Vec<u8, EFS>,
89}
90
91impl<const EFS: usize> Entry<EFS> {
92    fn name(&self) -> &str {
93        core::str::from_utf8(self.name.get(..self.name_len).unwrap_or(&[])).unwrap_or("")
94    }
95}
96
97/// §1.4.7.2's `SceneInfoStruct`, per fabric.
98#[derive(Debug, Clone, Copy)]
99struct FabricInfo {
100    fabric: FabricIndex,
101    current_scene: u8,
102    current_group: GroupId,
103    valid: bool,
104}
105
106/// The Scene Table (§1.4.7.5), shared by the Scenes Management and Groups clusters.
107///
108/// `N` is the number of entries across every fabric — §1.4.8.1 sets the minimum at 16 — `EFS`
109/// the bytes one scene's extension field sets may occupy, and `F` the fabrics whose
110/// `SceneInfoStruct` is tracked. §1.4.8.2: "The number of list entries for this attribute
111/// SHALL NOT exceed the number of supported fabrics by the device."
112#[derive(Debug)]
113pub struct SceneTable<const N: usize, const EFS: usize, const F: usize = 5> {
114    entries: RefCell<heapless::Vec<Entry<EFS>, N>>,
115    info: RefCell<heapless::Vec<FabricInfo, F>>,
116    names: bool,
117}
118
119impl<const N: usize, const EFS: usize, const F: usize> SceneTable<N, EFS, F> {
120    /// An empty table. `names` is the `SceneNames` feature.
121    #[must_use]
122    pub const fn new(names: bool) -> Self {
123        Self {
124            entries: RefCell::new(heapless::Vec::new()),
125            info: RefCell::new(heapless::Vec::new()),
126            names,
127        }
128    }
129
130    /// `SceneTableSize` (§1.4.8.1) — the total across all fabrics.
131    #[must_use]
132    #[expect(
133        clippy::cast_possible_truncation,
134        reason = "§1.4.8.1's scene table length is a uint16, and N is asserted to fit one"
135    )]
136    pub const fn size(&self) -> u16 {
137        // A table larger than 65 535 cannot be reported, so it is not a table this cluster
138        // can honestly serve; saturating says the largest number it can.
139        if N > u16::MAX as usize {
140            u16::MAX
141        } else {
142            N as u16
143        }
144    }
145
146    /// §1.4.6's per-fabric ceiling: "less than half (rounded down towards 0) of the Scene
147    /// Table entries ... with a maximum of 253".
148    ///
149    /// The point of the rule is that no single fabric can take enough of the table to leave
150    /// another with nothing, so the bound is half rather than some tuned fraction.
151    #[must_use]
152    pub const fn per_fabric(&self) -> usize {
153        let half = N / 2;
154        if half > CAPACITY_MAX as usize {
155            CAPACITY_MAX as usize
156        } else {
157            half
158        }
159    }
160
161    /// How many scenes one fabric holds.
162    #[must_use]
163    pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
164        self.entries
165            .borrow()
166            .iter()
167            .filter(|e| e.fabric == fabric)
168            .count()
169    }
170
171    /// §1.4.7.2.5's `RemainingCapacity` for one fabric.
172    #[must_use]
173    pub fn capacity(&self, fabric: FabricIndex) -> u8 {
174        // Bounded by whichever runs out first: this fabric's share, or the table itself.
175        let mine = self.per_fabric().saturating_sub(self.len_of_fabric(fabric));
176        let whole = N.saturating_sub(self.entries.borrow().len());
177        u8::try_from(mine.min(whole).min(CAPACITY_MAX as usize)).unwrap_or(CAPACITY_MAX)
178    }
179
180    /// Whether a scene exists.
181    #[must_use]
182    pub fn contains(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> bool {
183        self.find(fabric, group, scene).is_some()
184    }
185
186    fn find(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> Option<usize> {
187        self.entries
188            .borrow()
189            .iter()
190            .position(|e| e.fabric == fabric && e.group == group && e.scene == scene)
191    }
192
193    /// How many scenes the table holds in total.
194    #[must_use]
195    pub fn len(&self) -> usize {
196        self.entries.borrow().len()
197    }
198
199    /// Whether the table holds no scenes at all.
200    #[must_use]
201    pub fn is_empty(&self) -> bool {
202        self.len() == 0
203    }
204
205    /// §1.4.7.2.4: an S-quality attribute on this endpoint changed, so no fabric's
206    /// `CurrentScene` describes the endpoint any more.
207    ///
208    /// The device calls this from the cluster that changed — turning a light on by hand
209    /// invalidates the scene just as surely as recalling a different one does.
210    pub fn invalidate(&self) {
211        for info in self.info.borrow_mut().iter_mut() {
212            info.valid = false;
213        }
214    }
215
216    /// Records that `fabric` just recalled or stored `group`/`scene`.
217    ///
218    /// §1.4.7.2.4 makes this invalidate *every other* fabric's view: the endpoint now matches
219    /// one fabric's idea of the scene, and by construction not the others'.
220    fn note(&self, fabric: FabricIndex, group: GroupId, scene: u8) {
221        let mut info = self.info.borrow_mut();
222        for entry in info.iter_mut() {
223            if entry.fabric == fabric {
224                entry.current_scene = scene;
225                entry.current_group = group;
226                entry.valid = true;
227            } else {
228                entry.valid = false;
229            }
230        }
231        if !info.iter().any(|e| e.fabric == fabric) {
232            // A full info list is not a reason to refuse the recall: the scene was applied,
233            // and only the bookkeeping §1.4.8.2 caps is lost.
234            let _ = info.push(FabricInfo {
235                fabric,
236                current_scene: scene,
237                current_group: group,
238                valid: true,
239            });
240        }
241    }
242
243    /// §1.4.9.2's steps 3 and 4 — add or replace, honouring the per-fabric ceiling.
244    fn put(
245        &self,
246        fabric: FabricIndex,
247        group: GroupId,
248        scene: u8,
249        name: &str,
250        transition: u32,
251        fields: &[u8],
252    ) -> Status {
253        let mut stored = [0u8; NAME_MAX];
254        let kept = if self.names { name } else { "" };
255        let len = kept.len().min(NAME_MAX);
256        if let (Some(slot), Some(source)) = (stored.get_mut(..len), kept.as_bytes().get(..len)) {
257            slot.copy_from_slice(source);
258        }
259        let Ok(fields) = heapless::Vec::from_slice(fields) else {
260            // The scene is larger than this device reserved for one. §1.4.9.2.6 has no code
261            // for "too big to hold", and RESOURCE_EXHAUSTED is what step 3 says when the
262            // table cannot take the scene — which is the truth here too.
263            return Status::ResourceExhausted;
264        };
265
266        let mut entries = self.entries.borrow_mut();
267        if let Some(index) = entries
268            .iter()
269            .position(|e| e.fabric == fabric && e.group == group && e.scene == scene)
270        {
271            // Step 3: "the already existing scene entry SHALL be replaced".
272            if let Some(existing) = entries.get_mut(index) {
273                existing.name = stored;
274                existing.name_len = len;
275                existing.transition = transition;
276                existing.fields = fields;
277            }
278            return Status::Success;
279        }
280        if entries.iter().filter(|e| e.fabric == fabric).count() >= self.per_fabric() {
281            return Status::ResourceExhausted;
282        }
283        match entries.push(Entry {
284            fabric,
285            group,
286            scene,
287            name: stored,
288            name_len: len,
289            transition,
290            fields,
291        }) {
292            Ok(()) => Status::Success,
293            Err(_) => Status::ResourceExhausted,
294        }
295    }
296
297    /// Removes every scene a fabric owns — what `RemoveFabric` must do (§1.4.6).
298    pub fn remove_fabric(&self, fabric: FabricIndex) {
299        self.entries.borrow_mut().retain(|e| e.fabric != fabric);
300        self.info.borrow_mut().retain(|i| i.fabric != fabric);
301    }
302}
303
304/// What the Groups cluster needs from a Scene Table when a group goes away.
305///
306/// A trait rather than a direct call, so that a device with no Scenes Management cluster
307/// carries none of it: [`NoScenes`] is the default and compiles to nothing.
308pub trait ScenePurge {
309    /// §1.3.7.4: "scenes associated with the indicated group SHALL be removed".
310    fn remove_group_scenes(&self, fabric: FabricIndex, group: GroupId);
311
312    /// §1.3.7.5: "all scenes, except for scenes associated with group ID 0, SHALL be removed".
313    fn remove_grouped_scenes(&self, fabric: FabricIndex);
314}
315
316impl<const N: usize, const EFS: usize, const F: usize> ScenePurge for SceneTable<N, EFS, F> {
317    fn remove_group_scenes(&self, fabric: FabricIndex, group: GroupId) {
318        self.entries
319            .borrow_mut()
320            .retain(|e| !(e.fabric == fabric && e.group == group));
321    }
322
323    fn remove_grouped_scenes(&self, fabric: FabricIndex) {
324        // Group 0's scenes survive: they were never reachable through a group in the first
325        // place, so leaving every group has not made them unreachable.
326        self.entries
327            .borrow_mut()
328            .retain(|e| !(e.fabric == fabric && e.group.0 != 0));
329    }
330}
331
332/// An endpoint with no Scenes Management cluster, for which nothing has to be purged.
333#[derive(Debug, Clone, Copy, Default)]
334pub struct NoScenes;
335
336impl ScenePurge for NoScenes {
337    fn remove_group_scenes(&self, _fabric: FabricIndex, _group: GroupId) {}
338    fn remove_grouped_scenes(&self, _fabric: FabricIndex) {}
339}
340
341/// What the endpoint's other clusters contribute to a scene.
342///
343/// §1.4.7.5.5: "A Scene Table Extension SHALL only use attributes with the Scene quality."
344/// Which attributes those are is the *other* clusters' knowledge, not this one's — On/Off
345/// contributes `OnOff`, Level Control contributes `CurrentLevel`, and a device that wired the
346/// mapping into Scenes Management would have to change this cluster every time it gained one.
347pub trait SceneHooks {
348    /// Writes the endpoint's current S-quality state as the members of an
349    /// `ExtensionFieldSetStructs` array — one structure per cluster, no array header.
350    ///
351    /// Called by `StoreScene` (§1.4.9.10), which stores "the current state of other clusters
352    /// on the same endpoint" rather than anything the client sent.
353    fn capture(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()>;
354
355    /// Applies a stored scene's extension field sets over `transition` milliseconds.
356    ///
357    /// §1.4.9.12.4: "If there is no extension field set for a cluster, the state of that
358    /// cluster SHALL remain unchanged... If an extension field set would cause an unknown or
359    /// missing attribute to be set for any reason, that attribute SHALL be skipped." Both are
360    /// the implementer's to honour, because both are about clusters this one cannot see.
361    ///
362    /// Sets arrive in the order they were stored, so where a client sent the same cluster
363    /// twice, §1.4.9.2.6 step 4c's "the last one within the list SHALL be the one recorded"
364    /// falls out of applying them in order.
365    fn apply<'a>(&self, sets: TlvList<'a, ExtensionFieldSetStruct<'a>>, transition: u32);
366}
367
368/// Scenes Management over a shared [`SceneTable`].
369#[derive(Debug)]
370pub struct Scenes<
371    'a,
372    H: SceneHooks,
373    G: GroupMembership,
374    const N: usize,
375    const EFS: usize,
376    const F: usize = 5,
377> {
378    table: &'a SceneTable<N, EFS, F>,
379    groups: &'a G,
380    hooks: &'a H,
381    copy_scene: bool,
382}
383
384impl<'a, H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
385    Scenes<'a, H, G, N, EFS, F>
386{
387    /// A cluster over `table`, checking group membership against `groups`.
388    ///
389    /// §1.4.5: "Any endpoint that implements the Scenes Management server cluster SHALL also
390    /// implement the Groups server cluster" — so the dependency is a constructor argument
391    /// rather than an option, and an endpoint cannot be assembled without it.
392    #[must_use]
393    pub const fn new(
394        table: &'a SceneTable<N, EFS, F>,
395        groups: &'a G,
396        hooks: &'a H,
397        copy_scene: bool,
398    ) -> Self {
399        Self {
400            table,
401            groups,
402            hooks,
403            copy_scene,
404        }
405    }
406
407    /// The descriptor for an instance, derived from the specification's tables.
408    pub fn conforming(
409        feature_map: u32,
410        optional: &Optional<'_>,
411    ) -> crate::error::Result<Conforming<2, 8, 7, 0>> {
412        Conforming::new(&spec_scenes::CLUSTER, feature_map, optional)
413    }
414
415    /// Everything §1.4.9 leaves to the product: `CopyScene`.
416    pub const WITH_COPY_SCENE: Optional<'static> = Optional {
417        attributes: &[],
418        commands: &[COPY_SCENE],
419        events: &[],
420    };
421
422    /// The table this cluster serves, for a device persisting it or wiring it into Groups.
423    #[must_use]
424    pub const fn table(&self) -> &'a SceneTable<N, EFS, F> {
425        self.table
426    }
427
428    /// §1.4.9's step 1, shared by every command: a non-zero group must be one this endpoint
429    /// has actually joined, or the command names a group it cannot act for.
430    fn group_known(&self, fabric: FabricIndex, group: GroupId) -> bool {
431        group.0 == 0 || self.groups.is_group_member(fabric, group)
432    }
433}
434
435/// Writes a `(Status, GroupID, SceneID)` response — the shape `AddSceneResponse`,
436/// `RemoveSceneResponse` and `StoreSceneResponse` share.
437fn status_response(
438    w: &mut TlvWriter<'_>,
439    tag: Tag,
440    status: Status,
441    group: GroupId,
442    scene: u8,
443) -> crate::error::Result<()> {
444    spec_scenes::AddSceneResponseFields {
445        status: status.value(),
446        group_id: group,
447        scene_id: scene,
448    }
449    .to_tlv(w, tag)
450}
451
452impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
453    ClusterHandler for Scenes<'_, H, G, N, EFS, F>
454{
455    /// §1.4.6: the Scene Table is fabric-scoped, so a removed fabric's scenes go with it —
456    /// including the ones stored against its groups.
457    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
458        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
459            self.table.remove_fabric(fabric);
460        }
461    }
462    fn read(
463        &self,
464        resolved: &Resolved<'_>,
465        ctx: &InteractionContext<'_>,
466        w: &mut TlvWriter<'_>,
467        tag: Tag,
468    ) -> Result<(), Status> {
469        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
470        match resolved.attribute {
471            SCENE_TABLE_SIZE => full(w.unsigned(tag, u64::from(self.table.size()))),
472            FABRIC_SCENE_INFO => {
473                // §1.4.6: "Any attribute read ... when no accessing fabric is available SHALL
474                // fail with a status code of UNSUPPORTED_ACCESS."
475                let fabric = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
476                full(w.start_array(tag))?;
477                let info = self.table.info.borrow();
478                for entry in info.iter() {
479                    // §7.19.1.8.2: a filtered read reports only the accessing fabric's
480                    // entries; an unfiltered one reports all, each carrying its FabricIndex.
481                    if ctx.fabric_filtered && entry.fabric != fabric {
482                        continue;
483                    }
484                    let count = u8::try_from(self.table.len_of_fabric(entry.fabric))
485                        .unwrap_or(CAPACITY_MAX);
486                    full(
487                        spec_scenes::SceneInfoStruct {
488                            scene_count: count,
489                            current_scene: entry.current_scene,
490                            current_group: entry.current_group,
491                            scene_valid: entry.valid,
492                            remaining_capacity: self.table.capacity(entry.fabric),
493                            fabric_index: entry.fabric,
494                        }
495                        .to_tlv(w, Tag::Anonymous),
496                    )?;
497                }
498                full(w.end_container())
499            }
500            _ => Err(Status::UnsupportedAttribute),
501        }
502    }
503
504    #[allow(clippy::too_many_lines)]
505    fn invoke(
506        &self,
507        resolved: &ResolvedCommand<'_>,
508        fields: Option<&[u8]>,
509        ctx: &InteractionContext<'_>,
510        w: &mut TlvWriter<'_>,
511        tag: Tag,
512    ) -> Result<Option<CommandId>, StatusIb> {
513        // §1.4.9: every command's last step is "If the ... command was received as a unicast,
514        // the server SHALL then generate a ... Response". A groupcast gets none.
515        let answer = ctx.group.is_none();
516        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
517        // §1.4.6: "Any attribute read, attribute write or command invoked on the server when
518        // no accessing fabric is available SHALL fail with a status code of
519        // UNSUPPORTED_ACCESS."
520        let Some(fabric) = ctx.fabric_index else {
521            return Err(Status::UnsupportedAccess.into());
522        };
523        let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
524
525        match resolved.command.id {
526            ADD_SCENE => {
527                let decoded: spec_scenes::AddSceneFields<'_> = super::decode_fields(payload()?)?;
528                let status = if !self.group_known(fabric, decoded.group_id) {
529                    // Step 1.
530                    Status::InvalidCommand
531                } else if decoded.scene_id > SCENE_MAX || decoded.transition_time > TRANSITION_MAX {
532                    Status::ConstraintError
533                } else if decoded
534                    .extension_field_set_structs
535                    .iter()
536                    .any(|set| set.is_err())
537                {
538                    // Step 2: "If the ExtensionFieldSetStructs list is formatted in a way
539                    // deemed invalid ... the status SHALL be INVALID_COMMAND". Checked here
540                    // rather than at recall, so a scene that cannot be applied is never
541                    // stored — a device that discovered it at recall would fail silently, at
542                    // the one moment the person is watching.
543                    Status::InvalidCommand
544                } else {
545                    self.table.put(
546                        fabric,
547                        decoded.group_id,
548                        decoded.scene_id,
549                        decoded.scene_name,
550                        decoded.transition_time,
551                        decoded.extension_field_set_structs.members(),
552                    )
553                };
554                if !answer {
555                    return Ok(None);
556                }
557                full(status_response(
558                    w,
559                    tag,
560                    status,
561                    decoded.group_id,
562                    decoded.scene_id,
563                ))?;
564                Ok(Some(ADD_SCENE_RESPONSE))
565            }
566            VIEW_SCENE => {
567                let decoded: spec_scenes::ViewSceneFields = super::decode_fields(payload()?)?;
568                let index = self.table.find(fabric, decoded.group_id, decoded.scene_id);
569                let status = if !self.group_known(fabric, decoded.group_id) {
570                    Status::InvalidCommand
571                } else if index.is_none() {
572                    Status::NotFound
573                } else {
574                    Status::Success
575                };
576                if !answer {
577                    return Ok(None);
578                }
579                let entries = self.table.entries.borrow();
580                let found = index
581                    .filter(|_| status == Status::Success)
582                    .and_then(|i| entries.get(i));
583                full(
584                    spec_scenes::ViewSceneResponseFields {
585                        status: status.value(),
586                        group_id: decoded.group_id,
587                        scene_id: decoded.scene_id,
588                        // §1.4.9.5's last three fields are conformant on "Status == SUCCESS",
589                        // so a failure omits them rather than sending zeroes a client might
590                        // mistake for a scene.
591                        transition_time: found.map(|e| e.transition),
592                        scene_name: found.map(Entry::name),
593                        extension_field_set_structs: found
594                            .map(|e| TlvList::from_members(&e.fields)),
595                    }
596                    .to_tlv(w, tag),
597                )?;
598                Ok(Some(VIEW_SCENE_RESPONSE))
599            }
600            REMOVE_SCENE => {
601                let decoded: spec_scenes::RemoveSceneFields = super::decode_fields(payload()?)?;
602                let status = if !self.group_known(fabric, decoded.group_id) {
603                    Status::InvalidCommand
604                } else {
605                    match self.table.find(fabric, decoded.group_id, decoded.scene_id) {
606                        None => Status::NotFound,
607                        Some(index) => {
608                            self.table.entries.borrow_mut().remove(index);
609                            Status::Success
610                        }
611                    }
612                };
613                if !answer {
614                    return Ok(None);
615                }
616                full(status_response(
617                    w,
618                    tag,
619                    status,
620                    decoded.group_id,
621                    decoded.scene_id,
622                ))?;
623                Ok(Some(REMOVE_SCENE_RESPONSE))
624            }
625            REMOVE_ALL_SCENES => {
626                let decoded: spec_scenes::RemoveAllScenesFields = super::decode_fields(payload()?)?;
627                let status = if self.group_known(fabric, decoded.group_id) {
628                    self.table
629                        .entries
630                        .borrow_mut()
631                        .retain(|e| !(e.fabric == fabric && e.group == decoded.group_id));
632                    Status::Success
633                } else {
634                    Status::InvalidCommand
635                };
636                if !answer {
637                    return Ok(None);
638                }
639                full(
640                    spec_scenes::RemoveAllScenesResponseFields {
641                        status: status.value(),
642                        group_id: decoded.group_id,
643                    }
644                    .to_tlv(w, tag),
645                )?;
646                Ok(Some(REMOVE_ALL_SCENES_RESPONSE))
647            }
648            STORE_SCENE => {
649                let decoded: spec_scenes::StoreSceneFields = super::decode_fields(payload()?)?;
650                let status = self.store(fabric, decoded.group_id, decoded.scene_id);
651                if !answer {
652                    return Ok(None);
653                }
654                full(status_response(
655                    w,
656                    tag,
657                    status,
658                    decoded.group_id,
659                    decoded.scene_id,
660                ))?;
661                Ok(Some(STORE_SCENE_RESPONSE))
662            }
663            RECALL_SCENE => {
664                let decoded: spec_scenes::RecallSceneFields = super::decode_fields(payload()?)?;
665                if !self.group_known(fabric, decoded.group_id) {
666                    return Err(Status::InvalidCommand.into());
667                }
668                let Some(index) = self.table.find(fabric, decoded.group_id, decoded.scene_id)
669                else {
670                    return Err(Status::NotFound.into());
671                };
672                // §1.4.9.12.4: "If the TransitionTime data field is present in the command and
673                // its value is not equal to null, this field SHALL indicate the transition
674                // time... In all other cases... the SceneTransitionTime field of the Scene
675                // Table entry" — absent and explicitly null mean the same thing.
676                let (sets, stored) = {
677                    let entries = self.table.entries.borrow();
678                    let Some(entry) = entries.get(index) else {
679                        return Err(Status::NotFound.into());
680                    };
681                    (entry.fields.clone(), entry.transition)
682                };
683                let transition = decoded.transition_time.and_then(|t| t.0).unwrap_or(stored);
684                self.hooks.apply(TlvList::from_members(&sets), transition);
685                // §1.4.7.2.4: the endpoint now matches this fabric's scene, and no other's.
686                self.table.note(fabric, decoded.group_id, decoded.scene_id);
687                // §1.4.9's command table gives RecallScene response "Y" — a plain status, no
688                // response command of its own.
689                Ok(None)
690            }
691            GET_SCENE_MEMBERSHIP => {
692                let decoded: spec_scenes::GetSceneMembershipFields =
693                    super::decode_fields(payload()?)?;
694                let known = self.group_known(fabric, decoded.group_id);
695                if !answer {
696                    return Ok(None);
697                }
698                let status = if known {
699                    Status::Success
700                } else {
701                    Status::InvalidCommand
702                };
703                full(w.start_structure(tag))?;
704                full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
705                full(w.unsigned(Tag::Context(1), u64::from(self.table.capacity(fabric))))?;
706                decoded
707                    .group_id
708                    .to_tlv(w, Tag::Context(2))
709                    .map_err(|_| StatusIb::from(Status::Failure))?;
710                // §1.4.9.14.4: "If the status is not SUCCESS then this field SHALL be
711                // omitted".
712                if known {
713                    full(w.start_array(Tag::Context(3)))?;
714                    for entry in self.table.entries.borrow().iter() {
715                        if entry.fabric == fabric && entry.group == decoded.group_id {
716                            full(w.unsigned(Tag::Anonymous, u64::from(entry.scene)))?;
717                        }
718                    }
719                    full(w.end_container())?;
720                }
721                full(w.end_container())?;
722                Ok(Some(GET_SCENE_MEMBERSHIP_RESPONSE))
723            }
724            COPY_SCENE if self.copy_scene => {
725                let decoded: spec_scenes::CopySceneFields = super::decode_fields(payload()?)?;
726                let status = self.copy(fabric, &decoded);
727                if !answer {
728                    return Ok(None);
729                }
730                full(
731                    spec_scenes::CopySceneResponseFields {
732                        status: status.value(),
733                        group_identifier_from: decoded.group_identifier_from,
734                        scene_identifier_from: decoded.scene_identifier_from,
735                    }
736                    .to_tlv(w, tag),
737                )?;
738                Ok(Some(COPY_SCENE_RESPONSE))
739            }
740            _ => Err(Status::UnsupportedCommand.into()),
741        }
742    }
743}
744
745impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
746    Scenes<'_, H, G, N, EFS, F>
747{
748    /// §1.4.9.10.3's steps 1–3.
749    fn store(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> Status {
750        if !self.group_known(fabric, group) {
751            return Status::InvalidCommand;
752        }
753        if scene > SCENE_MAX {
754            return Status::ConstraintError;
755        }
756        // Step 3: the stored scene is "the current state of other clusters on the same
757        // endpoint" — nothing the client sent.
758        let mut scratch = [0u8; EFS];
759        let mut w = TlvWriter::new_in(&mut scratch, crate::tlv::ContainerKind::Array);
760        if self.hooks.capture(&mut w).is_err() {
761            return Status::ResourceExhausted;
762        }
763        let Ok(captured) = w.finish() else {
764            return Status::ResourceExhausted;
765        };
766        let existing = self.table.find(fabric, group, scene);
767        let status = match existing {
768            // "the ExtensionFieldSets of the stored scene SHALL be replaced ... and the other
769            // fields of the scene table entry SHALL remain unchanged" — the name and
770            // transition time a prior AddScene set are not the client's to lose here.
771            Some(index) => {
772                let mut entries = self.table.entries.borrow_mut();
773                match entries.get_mut(index) {
774                    Some(entry) => match heapless::Vec::from_slice(captured) {
775                        Ok(fields) => {
776                            entry.fields = fields;
777                            Status::Success
778                        }
779                        Err(_) => Status::ResourceExhausted,
780                    },
781                    None => Status::NotFound,
782                }
783            }
784            // "a new entry SHALL be added ... with SceneTransitionTime set to 0, with
785            // SceneName set to the empty string".
786            None => self.table.put(fabric, group, scene, "", 0, captured),
787        };
788        if status == Status::Success {
789            self.table.note(fabric, group, scene);
790        }
791        status
792    }
793
794    /// §1.4.9.15.6's steps 1–4.
795    fn copy(&self, fabric: FabricIndex, command: &spec_scenes::CopySceneFields) -> Status {
796        if !self.group_known(fabric, command.group_identifier_from)
797            || !self.group_known(fabric, command.group_identifier_to)
798        {
799            return Status::InvalidCommand;
800        }
801        let all = command.mode.contains(CopyModeBitmap::COPY_ALL_SCENES);
802        if !all {
803            // Step 2: one named scene must exist.
804            if self
805                .table
806                .find(
807                    fabric,
808                    command.group_identifier_from,
809                    command.scene_identifier_from,
810                )
811                .is_none()
812            {
813                return Status::NotFound;
814            }
815        }
816        // Snapshotting first keeps the copy from reading entries it is in the middle of
817        // writing — copying a group onto itself would otherwise grow without end.
818        let source: heapless::Vec<Entry<EFS>, N> = self
819            .table
820            .entries
821            .borrow()
822            .iter()
823            .filter(|e| {
824                e.fabric == fabric
825                    && e.group == command.group_identifier_from
826                    && (all || e.scene == command.scene_identifier_from)
827            })
828            .cloned()
829            .collect();
830        for entry in &source {
831            let scene = if all {
832                entry.scene
833            } else {
834                command.scene_identifier_to
835            };
836            let status = self.table.put(
837                fabric,
838                command.group_identifier_to,
839                scene,
840                entry.name(),
841                entry.transition,
842                &entry.fields,
843            );
844            if status != Status::Success {
845                return status;
846            }
847        }
848        Status::Success
849    }
850}
851
852/// So a tuple of clusters can dispatch to it by id.
853impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize> Cluster
854    for Scenes<'_, H, G, N, EFS, F>
855{
856    const ID: ClusterId = ID;
857}