1use 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
54pub const NAME_MAX: usize = 16;
56
57pub const GLOBAL_SCENE: u8 = 0;
60
61pub const UNDEFINED_SCENE: u8 = 0xFF;
63
64pub const SCENE_MAX: u8 = 254;
66
67pub const TRANSITION_MAX: u32 = 60_000_000;
70
71pub const CAPACITY_MAX: u8 = 253;
73
74#[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 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#[derive(Debug, Clone, Copy)]
99struct FabricInfo {
100 fabric: FabricIndex,
101 current_scene: u8,
102 current_group: GroupId,
103 valid: bool,
104}
105
106#[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 #[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 #[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 if N > u16::MAX as usize {
140 u16::MAX
141 } else {
142 N as u16
143 }
144 }
145
146 #[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 #[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 #[must_use]
173 pub fn capacity(&self, fabric: FabricIndex) -> u8 {
174 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 #[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 #[must_use]
195 pub fn len(&self) -> usize {
196 self.entries.borrow().len()
197 }
198
199 #[must_use]
201 pub fn is_empty(&self) -> bool {
202 self.len() == 0
203 }
204
205 pub fn invalidate(&self) {
211 for info in self.info.borrow_mut().iter_mut() {
212 info.valid = false;
213 }
214 }
215
216 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 let _ = info.push(FabricInfo {
235 fabric,
236 current_scene: scene,
237 current_group: group,
238 valid: true,
239 });
240 }
241 }
242
243 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 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 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 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
304pub trait ScenePurge {
309 fn remove_group_scenes(&self, fabric: FabricIndex, group: GroupId);
311
312 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 self.entries
327 .borrow_mut()
328 .retain(|e| !(e.fabric == fabric && e.group.0 != 0));
329 }
330}
331
332#[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
341pub trait SceneHooks {
348 fn capture(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()>;
354
355 fn apply<'a>(&self, sets: TlvList<'a, ExtensionFieldSetStruct<'a>>, transition: u32);
366}
367
368#[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 #[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 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 pub const WITH_COPY_SCENE: Optional<'static> = Optional {
417 attributes: &[],
418 commands: &[COPY_SCENE],
419 events: &[],
420 };
421
422 #[must_use]
424 pub const fn table(&self) -> &'a SceneTable<N, EFS, F> {
425 self.table
426 }
427
428 fn group_known(&self, fabric: FabricIndex, group: GroupId) -> bool {
431 group.0 == 0 || self.groups.is_group_member(fabric, group)
432 }
433}
434
435fn 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 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 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 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 let answer = ctx.group.is_none();
516 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
517 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 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 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 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 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 self.table.note(fabric, decoded.group_id, decoded.scene_id);
687 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 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 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 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 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 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 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 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 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
852impl<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}