use core::cell::RefCell;
use crate::clusters::generated::scenes_management as spec_scenes;
use crate::dm::spec::{Conforming, Optional};
use crate::dm::{Resolved, ResolvedCommand};
use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
use crate::msg::{FabricIndex, GroupId};
use crate::tlv::{Tag, TlvList, TlvWriter, ToTlv};
use super::Cluster;
use super::groups::GroupMembership;
pub use spec_scenes::attribute::{FABRIC_SCENE_INFO, SCENE_TABLE_SIZE};
pub use spec_scenes::command::{
ADD_SCENE, ADD_SCENE_RESPONSE, COPY_SCENE, COPY_SCENE_RESPONSE, GET_SCENE_MEMBERSHIP,
GET_SCENE_MEMBERSHIP_RESPONSE, RECALL_SCENE, REMOVE_ALL_SCENES, REMOVE_ALL_SCENES_RESPONSE,
REMOVE_SCENE, REMOVE_SCENE_RESPONSE, STORE_SCENE, STORE_SCENE_RESPONSE, VIEW_SCENE,
VIEW_SCENE_RESPONSE,
};
pub use spec_scenes::{
AttributeValuePairStruct, CopyModeBitmap, ExtensionFieldSetStruct, ID, PICS, REVISION, feature,
};
pub const NAME_MAX: usize = 16;
pub const GLOBAL_SCENE: u8 = 0;
pub const UNDEFINED_SCENE: u8 = 0xFF;
pub const SCENE_MAX: u8 = 254;
pub const TRANSITION_MAX: u32 = 60_000_000;
pub const CAPACITY_MAX: u8 = 253;
#[derive(Debug, Clone)]
struct Entry<const EFS: usize> {
fabric: FabricIndex,
group: GroupId,
scene: u8,
name: [u8; NAME_MAX],
name_len: usize,
transition: u32,
fields: heapless::Vec<u8, EFS>,
}
impl<const EFS: usize> Entry<EFS> {
fn name(&self) -> &str {
core::str::from_utf8(self.name.get(..self.name_len).unwrap_or(&[])).unwrap_or("")
}
}
#[derive(Debug, Clone, Copy)]
struct FabricInfo {
fabric: FabricIndex,
current_scene: u8,
current_group: GroupId,
valid: bool,
}
#[derive(Debug)]
pub struct SceneTable<const N: usize, const EFS: usize, const F: usize = 5> {
entries: RefCell<heapless::Vec<Entry<EFS>, N>>,
info: RefCell<heapless::Vec<FabricInfo, F>>,
names: bool,
}
impl<const N: usize, const EFS: usize, const F: usize> SceneTable<N, EFS, F> {
#[must_use]
pub const fn new(names: bool) -> Self {
Self {
entries: RefCell::new(heapless::Vec::new()),
info: RefCell::new(heapless::Vec::new()),
names,
}
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "§1.4.8.1's scene table length is a uint16, and N is asserted to fit one"
)]
pub const fn size(&self) -> u16 {
if N > u16::MAX as usize {
u16::MAX
} else {
N as u16
}
}
#[must_use]
pub const fn per_fabric(&self) -> usize {
let half = N / 2;
if half > CAPACITY_MAX as usize {
CAPACITY_MAX as usize
} else {
half
}
}
#[must_use]
pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
self.entries
.borrow()
.iter()
.filter(|e| e.fabric == fabric)
.count()
}
#[must_use]
pub fn capacity(&self, fabric: FabricIndex) -> u8 {
let mine = self.per_fabric().saturating_sub(self.len_of_fabric(fabric));
let whole = N.saturating_sub(self.entries.borrow().len());
u8::try_from(mine.min(whole).min(CAPACITY_MAX as usize)).unwrap_or(CAPACITY_MAX)
}
#[must_use]
pub fn contains(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> bool {
self.find(fabric, group, scene).is_some()
}
fn find(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> Option<usize> {
self.entries
.borrow()
.iter()
.position(|e| e.fabric == fabric && e.group == group && e.scene == scene)
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.borrow().len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn invalidate(&self) {
for info in self.info.borrow_mut().iter_mut() {
info.valid = false;
}
}
fn note(&self, fabric: FabricIndex, group: GroupId, scene: u8) {
let mut info = self.info.borrow_mut();
for entry in info.iter_mut() {
if entry.fabric == fabric {
entry.current_scene = scene;
entry.current_group = group;
entry.valid = true;
} else {
entry.valid = false;
}
}
if !info.iter().any(|e| e.fabric == fabric) {
let _ = info.push(FabricInfo {
fabric,
current_scene: scene,
current_group: group,
valid: true,
});
}
}
fn put(
&self,
fabric: FabricIndex,
group: GroupId,
scene: u8,
name: &str,
transition: u32,
fields: &[u8],
) -> Status {
let mut stored = [0u8; NAME_MAX];
let kept = if self.names { name } else { "" };
let len = kept.len().min(NAME_MAX);
if let (Some(slot), Some(source)) = (stored.get_mut(..len), kept.as_bytes().get(..len)) {
slot.copy_from_slice(source);
}
let Ok(fields) = heapless::Vec::from_slice(fields) else {
return Status::ResourceExhausted;
};
let mut entries = self.entries.borrow_mut();
if let Some(index) = entries
.iter()
.position(|e| e.fabric == fabric && e.group == group && e.scene == scene)
{
if let Some(existing) = entries.get_mut(index) {
existing.name = stored;
existing.name_len = len;
existing.transition = transition;
existing.fields = fields;
}
return Status::Success;
}
if entries.iter().filter(|e| e.fabric == fabric).count() >= self.per_fabric() {
return Status::ResourceExhausted;
}
match entries.push(Entry {
fabric,
group,
scene,
name: stored,
name_len: len,
transition,
fields,
}) {
Ok(()) => Status::Success,
Err(_) => Status::ResourceExhausted,
}
}
pub fn remove_fabric(&self, fabric: FabricIndex) {
self.entries.borrow_mut().retain(|e| e.fabric != fabric);
self.info.borrow_mut().retain(|i| i.fabric != fabric);
}
}
pub trait ScenePurge {
fn remove_group_scenes(&self, fabric: FabricIndex, group: GroupId);
fn remove_grouped_scenes(&self, fabric: FabricIndex);
}
impl<const N: usize, const EFS: usize, const F: usize> ScenePurge for SceneTable<N, EFS, F> {
fn remove_group_scenes(&self, fabric: FabricIndex, group: GroupId) {
self.entries
.borrow_mut()
.retain(|e| !(e.fabric == fabric && e.group == group));
}
fn remove_grouped_scenes(&self, fabric: FabricIndex) {
self.entries
.borrow_mut()
.retain(|e| !(e.fabric == fabric && e.group.0 != 0));
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoScenes;
impl ScenePurge for NoScenes {
fn remove_group_scenes(&self, _fabric: FabricIndex, _group: GroupId) {}
fn remove_grouped_scenes(&self, _fabric: FabricIndex) {}
}
pub trait SceneHooks {
fn capture(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()>;
fn apply<'a>(&self, sets: TlvList<'a, ExtensionFieldSetStruct<'a>>, transition: u32);
}
#[derive(Debug)]
pub struct Scenes<
'a,
H: SceneHooks,
G: GroupMembership,
const N: usize,
const EFS: usize,
const F: usize = 5,
> {
table: &'a SceneTable<N, EFS, F>,
groups: &'a G,
hooks: &'a H,
copy_scene: bool,
}
impl<'a, H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
Scenes<'a, H, G, N, EFS, F>
{
#[must_use]
pub const fn new(
table: &'a SceneTable<N, EFS, F>,
groups: &'a G,
hooks: &'a H,
copy_scene: bool,
) -> Self {
Self {
table,
groups,
hooks,
copy_scene,
}
}
pub fn conforming(
feature_map: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Conforming<2, 8, 7, 0>> {
Conforming::new(&spec_scenes::CLUSTER, feature_map, optional)
}
pub const WITH_COPY_SCENE: Optional<'static> = Optional {
attributes: &[],
commands: &[COPY_SCENE],
events: &[],
};
#[must_use]
pub const fn table(&self) -> &'a SceneTable<N, EFS, F> {
self.table
}
fn group_known(&self, fabric: FabricIndex, group: GroupId) -> bool {
group.0 == 0 || self.groups.is_group_member(fabric, group)
}
}
fn status_response(
w: &mut TlvWriter<'_>,
tag: Tag,
status: Status,
group: GroupId,
scene: u8,
) -> crate::error::Result<()> {
spec_scenes::AddSceneResponseFields {
status: status.value(),
group_id: group,
scene_id: scene,
}
.to_tlv(w, tag)
}
impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
ClusterHandler for Scenes<'_, H, G, N, EFS, F>
{
fn on_lifecycle(&self, event: crate::im::Lifecycle) {
if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
self.table.remove_fabric(fabric);
}
}
fn read(
&self,
resolved: &Resolved<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
match resolved.attribute {
SCENE_TABLE_SIZE => full(w.unsigned(tag, u64::from(self.table.size()))),
FABRIC_SCENE_INFO => {
let fabric = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
full(w.start_array(tag))?;
let info = self.table.info.borrow();
for entry in info.iter() {
if ctx.fabric_filtered && entry.fabric != fabric {
continue;
}
let count = u8::try_from(self.table.len_of_fabric(entry.fabric))
.unwrap_or(CAPACITY_MAX);
full(
spec_scenes::SceneInfoStruct {
scene_count: count,
current_scene: entry.current_scene,
current_group: entry.current_group,
scene_valid: entry.valid,
remaining_capacity: self.table.capacity(entry.fabric),
fabric_index: entry.fabric,
}
.to_tlv(w, Tag::Anonymous),
)?;
}
full(w.end_container())
}
_ => Err(Status::UnsupportedAttribute),
}
}
#[allow(clippy::too_many_lines)]
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<Option<CommandId>, StatusIb> {
let answer = ctx.group.is_none();
let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
let Some(fabric) = ctx.fabric_index else {
return Err(Status::UnsupportedAccess.into());
};
let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
match resolved.command.id {
ADD_SCENE => {
let decoded: spec_scenes::AddSceneFields<'_> = super::decode_fields(payload()?)?;
let status = if !self.group_known(fabric, decoded.group_id) {
Status::InvalidCommand
} else if decoded.scene_id > SCENE_MAX || decoded.transition_time > TRANSITION_MAX {
Status::ConstraintError
} else if decoded
.extension_field_set_structs
.iter()
.any(|set| set.is_err())
{
Status::InvalidCommand
} else {
self.table.put(
fabric,
decoded.group_id,
decoded.scene_id,
decoded.scene_name,
decoded.transition_time,
decoded.extension_field_set_structs.members(),
)
};
if !answer {
return Ok(None);
}
full(status_response(
w,
tag,
status,
decoded.group_id,
decoded.scene_id,
))?;
Ok(Some(ADD_SCENE_RESPONSE))
}
VIEW_SCENE => {
let decoded: spec_scenes::ViewSceneFields = super::decode_fields(payload()?)?;
let index = self.table.find(fabric, decoded.group_id, decoded.scene_id);
let status = if !self.group_known(fabric, decoded.group_id) {
Status::InvalidCommand
} else if index.is_none() {
Status::NotFound
} else {
Status::Success
};
if !answer {
return Ok(None);
}
let entries = self.table.entries.borrow();
let found = index
.filter(|_| status == Status::Success)
.and_then(|i| entries.get(i));
full(
spec_scenes::ViewSceneResponseFields {
status: status.value(),
group_id: decoded.group_id,
scene_id: decoded.scene_id,
transition_time: found.map(|e| e.transition),
scene_name: found.map(Entry::name),
extension_field_set_structs: found
.map(|e| TlvList::from_members(&e.fields)),
}
.to_tlv(w, tag),
)?;
Ok(Some(VIEW_SCENE_RESPONSE))
}
REMOVE_SCENE => {
let decoded: spec_scenes::RemoveSceneFields = super::decode_fields(payload()?)?;
let status = if !self.group_known(fabric, decoded.group_id) {
Status::InvalidCommand
} else {
match self.table.find(fabric, decoded.group_id, decoded.scene_id) {
None => Status::NotFound,
Some(index) => {
self.table.entries.borrow_mut().remove(index);
Status::Success
}
}
};
if !answer {
return Ok(None);
}
full(status_response(
w,
tag,
status,
decoded.group_id,
decoded.scene_id,
))?;
Ok(Some(REMOVE_SCENE_RESPONSE))
}
REMOVE_ALL_SCENES => {
let decoded: spec_scenes::RemoveAllScenesFields = super::decode_fields(payload()?)?;
let status = if self.group_known(fabric, decoded.group_id) {
self.table
.entries
.borrow_mut()
.retain(|e| !(e.fabric == fabric && e.group == decoded.group_id));
Status::Success
} else {
Status::InvalidCommand
};
if !answer {
return Ok(None);
}
full(
spec_scenes::RemoveAllScenesResponseFields {
status: status.value(),
group_id: decoded.group_id,
}
.to_tlv(w, tag),
)?;
Ok(Some(REMOVE_ALL_SCENES_RESPONSE))
}
STORE_SCENE => {
let decoded: spec_scenes::StoreSceneFields = super::decode_fields(payload()?)?;
let status = self.store(fabric, decoded.group_id, decoded.scene_id);
if !answer {
return Ok(None);
}
full(status_response(
w,
tag,
status,
decoded.group_id,
decoded.scene_id,
))?;
Ok(Some(STORE_SCENE_RESPONSE))
}
RECALL_SCENE => {
let decoded: spec_scenes::RecallSceneFields = super::decode_fields(payload()?)?;
if !self.group_known(fabric, decoded.group_id) {
return Err(Status::InvalidCommand.into());
}
let Some(index) = self.table.find(fabric, decoded.group_id, decoded.scene_id)
else {
return Err(Status::NotFound.into());
};
let (sets, stored) = {
let entries = self.table.entries.borrow();
let Some(entry) = entries.get(index) else {
return Err(Status::NotFound.into());
};
(entry.fields.clone(), entry.transition)
};
let transition = decoded.transition_time.and_then(|t| t.0).unwrap_or(stored);
self.hooks.apply(TlvList::from_members(&sets), transition);
self.table.note(fabric, decoded.group_id, decoded.scene_id);
Ok(None)
}
GET_SCENE_MEMBERSHIP => {
let decoded: spec_scenes::GetSceneMembershipFields =
super::decode_fields(payload()?)?;
let known = self.group_known(fabric, decoded.group_id);
if !answer {
return Ok(None);
}
let status = if known {
Status::Success
} else {
Status::InvalidCommand
};
full(w.start_structure(tag))?;
full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
full(w.unsigned(Tag::Context(1), u64::from(self.table.capacity(fabric))))?;
decoded
.group_id
.to_tlv(w, Tag::Context(2))
.map_err(|_| StatusIb::from(Status::Failure))?;
if known {
full(w.start_array(Tag::Context(3)))?;
for entry in self.table.entries.borrow().iter() {
if entry.fabric == fabric && entry.group == decoded.group_id {
full(w.unsigned(Tag::Anonymous, u64::from(entry.scene)))?;
}
}
full(w.end_container())?;
}
full(w.end_container())?;
Ok(Some(GET_SCENE_MEMBERSHIP_RESPONSE))
}
COPY_SCENE if self.copy_scene => {
let decoded: spec_scenes::CopySceneFields = super::decode_fields(payload()?)?;
let status = self.copy(fabric, &decoded);
if !answer {
return Ok(None);
}
full(
spec_scenes::CopySceneResponseFields {
status: status.value(),
group_identifier_from: decoded.group_identifier_from,
scene_identifier_from: decoded.scene_identifier_from,
}
.to_tlv(w, tag),
)?;
Ok(Some(COPY_SCENE_RESPONSE))
}
_ => Err(Status::UnsupportedCommand.into()),
}
}
}
impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize>
Scenes<'_, H, G, N, EFS, F>
{
fn store(&self, fabric: FabricIndex, group: GroupId, scene: u8) -> Status {
if !self.group_known(fabric, group) {
return Status::InvalidCommand;
}
if scene > SCENE_MAX {
return Status::ConstraintError;
}
let mut scratch = [0u8; EFS];
let mut w = TlvWriter::new_in(&mut scratch, crate::tlv::ContainerKind::Array);
if self.hooks.capture(&mut w).is_err() {
return Status::ResourceExhausted;
}
let Ok(captured) = w.finish() else {
return Status::ResourceExhausted;
};
let existing = self.table.find(fabric, group, scene);
let status = match existing {
Some(index) => {
let mut entries = self.table.entries.borrow_mut();
match entries.get_mut(index) {
Some(entry) => match heapless::Vec::from_slice(captured) {
Ok(fields) => {
entry.fields = fields;
Status::Success
}
Err(_) => Status::ResourceExhausted,
},
None => Status::NotFound,
}
}
None => self.table.put(fabric, group, scene, "", 0, captured),
};
if status == Status::Success {
self.table.note(fabric, group, scene);
}
status
}
fn copy(&self, fabric: FabricIndex, command: &spec_scenes::CopySceneFields) -> Status {
if !self.group_known(fabric, command.group_identifier_from)
|| !self.group_known(fabric, command.group_identifier_to)
{
return Status::InvalidCommand;
}
let all = command.mode.contains(CopyModeBitmap::COPY_ALL_SCENES);
if !all {
if self
.table
.find(
fabric,
command.group_identifier_from,
command.scene_identifier_from,
)
.is_none()
{
return Status::NotFound;
}
}
let source: heapless::Vec<Entry<EFS>, N> = self
.table
.entries
.borrow()
.iter()
.filter(|e| {
e.fabric == fabric
&& e.group == command.group_identifier_from
&& (all || e.scene == command.scene_identifier_from)
})
.cloned()
.collect();
for entry in &source {
let scene = if all {
entry.scene
} else {
command.scene_identifier_to
};
let status = self.table.put(
fabric,
command.group_identifier_to,
scene,
entry.name(),
entry.transition,
&entry.fields,
);
if status != Status::Success {
return status;
}
}
Status::Success
}
}
impl<H: SceneHooks, G: GroupMembership, const N: usize, const EFS: usize, const F: usize> Cluster
for Scenes<'_, H, G, N, EFS, F>
{
const ID: ClusterId = ID;
}