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 pub const fn size(&self) -> u16 {
133 if N > u16::MAX as usize {
136 u16::MAX
137 } else {
138 N as u16
139 }
140 }
141
142 #[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 #[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 #[must_use]
169 pub fn capacity(&self, fabric: FabricIndex) -> u8 {
170 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 #[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 #[must_use]
191 pub fn len(&self) -> usize {
192 self.entries.borrow().len()
193 }
194
195 #[must_use]
197 pub fn is_empty(&self) -> bool {
198 self.len() == 0
199 }
200
201 pub fn invalidate(&self) {
207 for info in self.info.borrow_mut().iter_mut() {
208 info.valid = false;
209 }
210 }
211
212 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 let _ = info.push(FabricInfo {
231 fabric,
232 current_scene: scene,
233 current_group: group,
234 valid: true,
235 });
236 }
237 }
238
239 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 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 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 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
300pub trait ScenePurge {
305 fn remove_group_scenes(&self, fabric: FabricIndex, group: GroupId);
307
308 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 self.entries
323 .borrow_mut()
324 .retain(|e| !(e.fabric == fabric && e.group.0 != 0));
325 }
326}
327
328#[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
337pub trait SceneHooks {
344 fn capture(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()>;
350
351 fn apply<'a>(&self, sets: TlvList<'a, ExtensionFieldSetStruct<'a>>, transition: u32);
362}
363
364#[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 #[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 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 pub const WITH_COPY_SCENE: Optional<'static> = Optional {
413 attributes: &[],
414 commands: &[COPY_SCENE],
415 events: &[],
416 };
417
418 #[must_use]
420 pub const fn table(&self) -> &'a SceneTable<N, EFS, F> {
421 self.table
422 }
423
424 fn group_known(&self, fabric: FabricIndex, group: GroupId) -> bool {
427 group.0 == 0 || self.groups.is_group_member(fabric, group)
428 }
429}
430
431fn 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 on_lifecycle(&self, event: crate::im::Lifecycle) {
454 if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
455 self.table.remove_fabric(fabric);
456 }
457 }
458 fn read(
459 &self,
460 resolved: &Resolved<'_>,
461 ctx: &InteractionContext<'_>,
462 w: &mut TlvWriter<'_>,
463 tag: Tag,
464 ) -> Result<(), Status> {
465 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
466 match resolved.attribute {
467 SCENE_TABLE_SIZE => full(w.unsigned(tag, u64::from(self.table.size()))),
468 FABRIC_SCENE_INFO => {
469 let fabric = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
472 full(w.start_array(tag))?;
473 let info = self.table.info.borrow();
474 for entry in info.iter() {
475 if ctx.fabric_filtered && entry.fabric != fabric {
478 continue;
479 }
480 let count = u8::try_from(self.table.len_of_fabric(entry.fabric))
481 .unwrap_or(CAPACITY_MAX);
482 full(
483 spec_scenes::SceneInfoStruct {
484 scene_count: count,
485 current_scene: entry.current_scene,
486 current_group: entry.current_group,
487 scene_valid: entry.valid,
488 remaining_capacity: self.table.capacity(entry.fabric),
489 fabric_index: entry.fabric,
490 }
491 .to_tlv(w, Tag::Anonymous),
492 )?;
493 }
494 full(w.end_container())
495 }
496 _ => Err(Status::UnsupportedAttribute),
497 }
498 }
499
500 #[allow(clippy::too_many_lines)]
501 fn invoke(
502 &self,
503 resolved: &ResolvedCommand<'_>,
504 fields: Option<&[u8]>,
505 ctx: &InteractionContext<'_>,
506 w: &mut TlvWriter<'_>,
507 tag: Tag,
508 ) -> Result<Option<CommandId>, StatusIb> {
509 let answer = ctx.group.is_none();
512 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
513 let Some(fabric) = ctx.fabric_index else {
517 return Err(Status::UnsupportedAccess.into());
518 };
519 let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
520
521 match resolved.command.id {
522 ADD_SCENE => {
523 let decoded: spec_scenes::AddSceneFields<'_> = super::decode_fields(payload()?)?;
524 let status = if !self.group_known(fabric, decoded.group_id) {
525 Status::InvalidCommand
527 } else if decoded.scene_id > SCENE_MAX || decoded.transition_time > TRANSITION_MAX {
528 Status::ConstraintError
529 } else if decoded
530 .extension_field_set_structs
531 .iter()
532 .any(|set| set.is_err())
533 {
534 Status::InvalidCommand
540 } else {
541 self.table.put(
542 fabric,
543 decoded.group_id,
544 decoded.scene_id,
545 decoded.scene_name,
546 decoded.transition_time,
547 decoded.extension_field_set_structs.members(),
548 )
549 };
550 if !answer {
551 return Ok(None);
552 }
553 full(status_response(
554 w,
555 tag,
556 status,
557 decoded.group_id,
558 decoded.scene_id,
559 ))?;
560 Ok(Some(ADD_SCENE_RESPONSE))
561 }
562 VIEW_SCENE => {
563 let decoded: spec_scenes::ViewSceneFields = super::decode_fields(payload()?)?;
564 let index = self.table.find(fabric, decoded.group_id, decoded.scene_id);
565 let status = if !self.group_known(fabric, decoded.group_id) {
566 Status::InvalidCommand
567 } else if index.is_none() {
568 Status::NotFound
569 } else {
570 Status::Success
571 };
572 if !answer {
573 return Ok(None);
574 }
575 let entries = self.table.entries.borrow();
576 let found = index
577 .filter(|_| status == Status::Success)
578 .and_then(|i| entries.get(i));
579 full(
580 spec_scenes::ViewSceneResponseFields {
581 status: status.value(),
582 group_id: decoded.group_id,
583 scene_id: decoded.scene_id,
584 transition_time: found.map(|e| e.transition),
588 scene_name: found.map(Entry::name),
589 extension_field_set_structs: found
590 .map(|e| TlvList::from_members(&e.fields)),
591 }
592 .to_tlv(w, tag),
593 )?;
594 Ok(Some(VIEW_SCENE_RESPONSE))
595 }
596 REMOVE_SCENE => {
597 let decoded: spec_scenes::RemoveSceneFields = super::decode_fields(payload()?)?;
598 let status = if !self.group_known(fabric, decoded.group_id) {
599 Status::InvalidCommand
600 } else {
601 match self.table.find(fabric, decoded.group_id, decoded.scene_id) {
602 None => Status::NotFound,
603 Some(index) => {
604 self.table.entries.borrow_mut().remove(index);
605 Status::Success
606 }
607 }
608 };
609 if !answer {
610 return Ok(None);
611 }
612 full(status_response(
613 w,
614 tag,
615 status,
616 decoded.group_id,
617 decoded.scene_id,
618 ))?;
619 Ok(Some(REMOVE_SCENE_RESPONSE))
620 }
621 REMOVE_ALL_SCENES => {
622 let decoded: spec_scenes::RemoveAllScenesFields = super::decode_fields(payload()?)?;
623 let status = if self.group_known(fabric, decoded.group_id) {
624 self.table
625 .entries
626 .borrow_mut()
627 .retain(|e| !(e.fabric == fabric && e.group == decoded.group_id));
628 Status::Success
629 } else {
630 Status::InvalidCommand
631 };
632 if !answer {
633 return Ok(None);
634 }
635 full(
636 spec_scenes::RemoveAllScenesResponseFields {
637 status: status.value(),
638 group_id: decoded.group_id,
639 }
640 .to_tlv(w, tag),
641 )?;
642 Ok(Some(REMOVE_ALL_SCENES_RESPONSE))
643 }
644 STORE_SCENE => {
645 let decoded: spec_scenes::StoreSceneFields = super::decode_fields(payload()?)?;
646 let status = self.store(fabric, decoded.group_id, decoded.scene_id);
647 if !answer {
648 return Ok(None);
649 }
650 full(status_response(
651 w,
652 tag,
653 status,
654 decoded.group_id,
655 decoded.scene_id,
656 ))?;
657 Ok(Some(STORE_SCENE_RESPONSE))
658 }
659 RECALL_SCENE => {
660 let decoded: spec_scenes::RecallSceneFields = super::decode_fields(payload()?)?;
661 if !self.group_known(fabric, decoded.group_id) {
662 return Err(Status::InvalidCommand.into());
663 }
664 let Some(index) = self.table.find(fabric, decoded.group_id, decoded.scene_id)
665 else {
666 return Err(Status::NotFound.into());
667 };
668 let (sets, stored) = {
673 let entries = self.table.entries.borrow();
674 let Some(entry) = entries.get(index) else {
675 return Err(Status::NotFound.into());
676 };
677 (entry.fields.clone(), entry.transition)
678 };
679 let transition = decoded.transition_time.and_then(|t| t.0).unwrap_or(stored);
680 self.hooks.apply(TlvList::from_members(&sets), transition);
681 self.table.note(fabric, decoded.group_id, decoded.scene_id);
683 Ok(None)
686 }
687 GET_SCENE_MEMBERSHIP => {
688 let decoded: spec_scenes::GetSceneMembershipFields =
689 super::decode_fields(payload()?)?;
690 let known = self.group_known(fabric, decoded.group_id);
691 if !answer {
692 return Ok(None);
693 }
694 let status = if known {
695 Status::Success
696 } else {
697 Status::InvalidCommand
698 };
699 full(w.start_structure(tag))?;
700 full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
701 full(w.unsigned(Tag::Context(1), u64::from(self.table.capacity(fabric))))?;
702 decoded
703 .group_id
704 .to_tlv(w, Tag::Context(2))
705 .map_err(|_| StatusIb::from(Status::Failure))?;
706 if known {
709 full(w.start_array(Tag::Context(3)))?;
710 for entry in self.table.entries.borrow().iter() {
711 if entry.fabric == fabric && entry.group == decoded.group_id {
712 full(w.unsigned(Tag::Anonymous, u64::from(entry.scene)))?;
713 }
714 }
715 full(w.end_container())?;
716 }
717 full(w.end_container())?;
718 Ok(Some(GET_SCENE_MEMBERSHIP_RESPONSE))
719 }
720 COPY_SCENE if self.copy_scene => {
721 let decoded: spec_scenes::CopySceneFields = super::decode_fields(payload()?)?;
722 let status = self.copy(fabric, &decoded);
723 if !answer {
724 return Ok(None);
725 }
726 full(
727 spec_scenes::CopySceneResponseFields {
728 status: status.value(),
729 group_identifier_from: decoded.group_identifier_from,
730 scene_identifier_from: decoded.scene_identifier_from,
731 }
732 .to_tlv(w, tag),
733 )?;
734 Ok(Some(COPY_SCENE_RESPONSE))
735 }
736 _ => Err(Status::UnsupportedCommand.into()),
737 }
738 }
739}
740
741impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
742 Scenes<'_, H, G, N, EFS, F>
743{
744 fn store(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> Status {
746 if !self.group_known(fabric, group) {
747 return Status::InvalidCommand;
748 }
749 if scene > SCENE_MAX {
750 return Status::ConstraintError;
751 }
752 let mut scratch = [0u8; EFS];
755 let mut w = TlvWriter::new_in(&mut scratch, crate::tlv::ContainerKind::Array);
756 if self.hooks.capture(&mut w).is_err() {
757 return Status::ResourceExhausted;
758 }
759 let Ok(captured) = w.finish() else {
760 return Status::ResourceExhausted;
761 };
762 let existing = self.table.find(fabric, group, scene);
763 let status = match existing {
764 Some(index) => {
768 let mut entries = self.table.entries.borrow_mut();
769 match entries.get_mut(index) {
770 Some(entry) => match heapless::Vec::from_slice(captured) {
771 Ok(fields) => {
772 entry.fields = fields;
773 Status::Success
774 }
775 Err(_) => Status::ResourceExhausted,
776 },
777 None => Status::NotFound,
778 }
779 }
780 None => self.table.put(fabric, group, scene, "", 0, captured),
783 };
784 if status == Status::Success {
785 self.table.note(fabric, group, scene);
786 }
787 status
788 }
789
790 fn copy(&self, fabric: FabricIndex, command: &spec_scenes::CopySceneFields) -> Status {
792 if !self.group_known(fabric, command.group_identifier_from)
793 || !self.group_known(fabric, command.group_identifier_to)
794 {
795 return Status::InvalidCommand;
796 }
797 let all = command.mode.contains(CopyModeBitmap::COPY_ALL_SCENES);
798 if !all {
799 if self
801 .table
802 .find(
803 fabric,
804 command.group_identifier_from,
805 command.scene_identifier_from,
806 )
807 .is_none()
808 {
809 return Status::NotFound;
810 }
811 }
812 let source: heapless::Vec<Entry<EFS>, N> = self
815 .table
816 .entries
817 .borrow()
818 .iter()
819 .filter(|e| {
820 e.fabric == fabric
821 && e.group == command.group_identifier_from
822 && (all || e.scene == command.scene_identifier_from)
823 })
824 .cloned()
825 .collect();
826 for entry in &source {
827 let scene = if all {
828 entry.scene
829 } else {
830 command.scene_identifier_to
831 };
832 let status = self.table.put(
833 fabric,
834 command.group_identifier_to,
835 scene,
836 entry.name(),
837 entry.transition,
838 &entry.fields,
839 );
840 if status != Status::Success {
841 return status;
842 }
843 }
844 Status::Success
845 }
846}
847
848impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize> Cluster
850 for Scenes<'_, H, G, N, EFS, F>
851{
852 const ID: ClusterId = ID;
853}