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