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 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 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 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 let answer = ctx.group.is_none();
505 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
506 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 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 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 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 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 self.table.note(fabric, decoded.group_id, decoded.scene_id);
676 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 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 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 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 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 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 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 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 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
841impl<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}