Skip to main content

matter_kit/clusters/
groups.rs

1//! Groups, cluster `0x0004` (Application Cluster §1.3).
2//!
3//! > The Groups cluster manages, per endpoint, the content of the node-wide Group Table that
4//! > is part of the underlying interaction layer.
5//!
6//! What makes "turn off the kitchen" one message rather than six. An endpoint joins a group,
7//! and a groupcast to that group reaches every member at once.
8//!
9//! # The table is per endpoint and scoped to a fabric
10//!
11//! Two scopes at once, and both matter. **Per endpoint**, because a two-gang switch has two
12//! endpoints and they belong to different rooms. **Per fabric**, because §1.3 says so —
13//! "group IDs referenced by attributes or other elements of this cluster are scoped to the
14//! accessing fabric" — and a device that let one ecosystem see or remove another's groups
15//! would leak the layout of somebody's house to whoever commissioned it second.
16//!
17//! # A groupcast gets no answer
18//!
19//! Every command here says the same thing: "If the ... command was received as a groupcast,
20//! the server SHALL NOT generate a ... Response command." Six lights answering one multicast
21//! is six unicasts the client did not ask for, arriving at once — the classic broadcast storm,
22//! and the reason [`Groups::invoke`] consults [`InteractionContext`]'s group destination
23//! rather than always replying.
24//!
25//! # What this cluster is not
26//!
27//! It does not route anything. §1.3: "configuration of group addresses for outgoing commands
28//! is achieved using the Message Layer mechanisms where the Group Table is not involved."
29//! This is the *membership* list; delivering a groupcast is [`crate::msg`]'s.
30
31use core::cell::RefCell;
32
33use crate::clusters::generated::groups as spec_groups;
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, TlvWriter, ToTlv};
39
40use super::Cluster;
41use super::scenes::{NoScenes, ScenePurge};
42
43/// What the Scenes Management cluster needs from the Group Table (§1.4.9's step 1).
44///
45/// Every Scenes command begins the same way: "If the value of the GroupID field is non-zero,
46/// the server verifies that the endpoint has an entry for that GroupID in the Group Table."
47/// A trait, so an endpoint may hold its memberships somewhere other than [`Groups`] — a
48/// bridge, for instance, whose group table lives on the far side.
49pub trait GroupMembership {
50    /// Whether the endpoint is in `group` on `fabric`.
51    fn is_group_member(&self, fabric: FabricIndex, group: GroupId) -> bool;
52}
53
54pub use spec_groups::attribute::NAME_SUPPORT;
55pub use spec_groups::command::{
56    ADD_GROUP, ADD_GROUP_IF_IDENTIFYING, ADD_GROUP_RESPONSE, GET_GROUP_MEMBERSHIP,
57    GET_GROUP_MEMBERSHIP_RESPONSE, REMOVE_ALL_GROUPS, REMOVE_GROUP, REMOVE_GROUP_RESPONSE,
58    VIEW_GROUP, VIEW_GROUP_RESPONSE,
59};
60pub use spec_groups::{ID, NameSupportBitmap, PICS, REVISION, feature};
61
62/// §1.3.7.1's constraint on `GroupName`: "max 16".
63pub const NAME_MAX: usize = 16;
64
65/// One membership.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct Membership {
68    /// The group. §1.3.7.1.1's constraint is "min 1": zero is the null group.
69    pub group: GroupId,
70    /// Which fabric's group this is.
71    pub fabric: FabricIndex,
72    name: [u8; NAME_MAX],
73    name_len: usize,
74}
75
76impl Membership {
77    /// The group's name, empty when the device does not store names.
78    #[must_use]
79    pub fn name(&self) -> &str {
80        // Written from a `&str`, so the prefix is always valid UTF-8.
81        core::str::from_utf8(self.name.get(..self.name_len).unwrap_or(&[])).unwrap_or("")
82    }
83}
84
85/// What the endpoint must tell the cluster for `AddGroupIfIdentifying` to work.
86///
87/// §1.3.7.6 makes that command conditional on the *Identify* cluster's state on the same
88/// endpoint, which is the only coupling this cluster has. A device without Identify answers
89/// `false` and the command is silently ignored — which is what the specification asks for.
90pub trait Identifying {
91    /// Whether the endpoint is identifying itself right now.
92    fn is_identifying(&self) -> bool;
93}
94
95/// A device with no Identify cluster, for which `AddGroupIfIdentifying` never applies.
96#[derive(Debug, Clone, Copy, Default)]
97pub struct NeverIdentifying;
98
99impl Identifying for NeverIdentifying {
100    fn is_identifying(&self) -> bool {
101        false
102    }
103}
104
105/// The Groups cluster's table.
106///
107/// `N` is the total across every fabric. §1.3 gives no minimum, but a device type usually
108/// does, and `per_fabric` is what stops the first ecosystem to commission filling the table
109/// and leaving the second unable to make a single group.
110#[derive(Debug)]
111pub struct Groups<'a, const N: usize, I: Identifying = NeverIdentifying, S: ScenePurge = NoScenes> {
112    memberships: RefCell<heapless::Vec<Membership, N>>,
113    per_fabric: usize,
114    names: bool,
115    identifying: &'a I,
116    scenes: &'a S,
117}
118
119impl<const N: usize> Groups<'static, N, NeverIdentifying, NoScenes> {
120    /// A table for an endpoint with neither an Identify nor a Scenes Management cluster.
121    #[must_use]
122    pub const fn new(per_fabric: usize, names: bool) -> Self {
123        Self::with(per_fabric, names, &NeverIdentifying, &NoScenes)
124    }
125}
126
127impl<'a, const N: usize, I: Identifying, S: ScenePurge> Groups<'a, N, I, S> {
128    /// A table for an endpoint whose Identify cluster `identifying` reports and whose scenes
129    /// live in `scenes`.
130    ///
131    /// Both are what the *rest of the endpoint* contributes: §1.3.7.6 makes
132    /// `AddGroupIfIdentifying` conditional on Identify, and §1.3.7.4 makes `RemoveGroup`
133    /// remove that group's scenes. Pass [`NeverIdentifying`] or [`NoScenes`] for an endpoint
134    /// that has neither — they compile to nothing.
135    #[must_use]
136    pub const fn with(per_fabric: usize, names: bool, identifying: &'a I, scenes: &'a S) -> Self {
137        Self {
138            memberships: RefCell::new(heapless::Vec::new()),
139            per_fabric,
140            names,
141            identifying,
142            scenes,
143        }
144    }
145
146    /// The descriptor for an instance, derived from the specification's tables.
147    pub fn conforming(
148        feature_map: u32,
149        optional: &Optional<'_>,
150    ) -> crate::error::Result<Conforming<1, 6, 4, 0>> {
151        Conforming::new(&spec_groups::CLUSTER, feature_map, optional)
152    }
153
154    /// `NameSupport` (§1.3.6.1).
155    ///
156    /// "The most significant bit, bit 7 (GroupNames), SHALL be equal to bit 0 of the FeatureMap
157    /// attribute (GN Feature). All other bits SHALL be 0." A legacy view of one feature bit,
158    /// kept in step here so the two cannot disagree.
159    #[must_use]
160    pub fn name_support(&self) -> NameSupportBitmap {
161        if self.names {
162            NameSupportBitmap::GROUP_NAMES
163        } else {
164            NameSupportBitmap::empty()
165        }
166    }
167
168    /// The `FeatureMap` this instance should declare.
169    #[must_use]
170    pub const fn feature_map(&self) -> u32 {
171        if self.names { feature::GROUP_NAMES } else { 0 }
172    }
173
174    /// Every membership, for a device about to persist them.
175    #[must_use]
176    pub fn memberships(&self) -> core::cell::Ref<'_, heapless::Vec<Membership, N>> {
177        self.memberships.borrow()
178    }
179
180    /// Whether the endpoint is in a group, on a fabric.
181    #[must_use]
182    pub fn is_member(&self, fabric: FabricIndex, group: GroupId) -> bool {
183        self.memberships
184            .borrow()
185            .iter()
186            .any(|m| m.fabric == fabric && m.group == group)
187    }
188
189    /// How many groups one fabric holds on this endpoint.
190    #[must_use]
191    pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
192        self.memberships
193            .borrow()
194            .iter()
195            .filter(|m| m.fabric == fabric)
196            .count()
197    }
198
199    /// §1.3.7.9.1's `Capacity`: how many more groups this fabric may add.
200    #[must_use]
201    pub fn capacity(&self, fabric: FabricIndex) -> u8 {
202        let used = self.len_of_fabric(fabric);
203        let free = self.per_fabric.saturating_sub(used);
204        // "0xFE - At least 1 further group MAY be added (exact number is unknown)" is for a
205        // device that cannot count; this one can, so it says the number.
206        u8::try_from(free.min(0xFD)).unwrap_or(0xFD)
207    }
208
209    /// Removes every membership of one fabric — what `RemoveFabric` must do.
210    ///
211    /// The fabric's scenes go with them: §1.4.6 says "Upon leaving a fabric with the
212    /// RemoveFabric command ... all scenes data for the associated fabric SHALL be removed",
213    /// and a group's scenes outliving the group is the same leak `RemoveGroup` avoids.
214    pub fn remove_fabric(&self, fabric: FabricIndex) {
215        self.memberships.borrow_mut().retain(|m| m.fabric != fabric);
216        self.scenes.remove_grouped_scenes(fabric);
217    }
218
219    /// §1.3.7.1's steps 1–5.
220    fn add(&self, fabric: FabricIndex, group: GroupId, name: &str) -> Status {
221        // Step 1. "min 1": group 0 is the null group and is not a group to join.
222        if group.0 == 0 || name.len() > NAME_MAX {
223            return Status::ConstraintError;
224        }
225        let mut stored = [0u8; NAME_MAX];
226        // "If the server does not support group names, the GroupName field SHALL be ignored."
227        let kept = if self.names { name } else { "" };
228        let len = kept.len().min(NAME_MAX);
229        if let (Some(slot), Some(source)) = (stored.get_mut(..len), kept.as_bytes().get(..len)) {
230            slot.copy_from_slice(source);
231        }
232
233        let mut memberships = self.memberships.borrow_mut();
234        // Step 3: already a member — update the name and succeed. Not an error, because a
235        // client re-sending `AddGroup` is how §1.3.7.1.3's step 5a renames a group.
236        if let Some(existing) = memberships
237            .iter_mut()
238            .find(|m| m.fabric == fabric && m.group == group)
239        {
240            existing.name = stored;
241            existing.name_len = len;
242            return Status::Success;
243        }
244        // Step 4.
245        if memberships.iter().filter(|m| m.fabric == fabric).count() >= self.per_fabric {
246            return Status::ResourceExhausted;
247        }
248        // Step 5.
249        match memberships.push(Membership {
250            group,
251            fabric,
252            name: stored,
253            name_len: len,
254        }) {
255            Ok(()) => Status::Success,
256            Err(_) => Status::ResourceExhausted,
257        }
258    }
259
260    /// §1.3.7.4's steps 1–3.
261    fn remove(&self, fabric: FabricIndex, group: GroupId) -> Status {
262        if group.0 == 0 {
263            return Status::ConstraintError;
264        }
265        let removed = {
266            let mut memberships = self.memberships.borrow_mut();
267            let before = memberships.len();
268            memberships.retain(|m| !(m.fabric == fabric && m.group == group));
269            memberships.len() != before
270        };
271        if !removed {
272            return Status::NotFound;
273        }
274        // §1.3.7.4: "if the Scenes Management cluster is supported on the same endpoint,
275        // scenes associated with the indicated group SHALL be removed on that endpoint." A
276        // rule about the Scene Table, written in this cluster's chapter — and a device that
277        // skipped it would keep scenes addressed to a group it has left.
278        self.scenes.remove_group_scenes(fabric, group);
279        Status::Success
280    }
281}
282
283impl<const N: usize, I: Identifying, S: ScenePurge> ClusterHandler for Groups<'_, N, I, S> {
284    /// §1.3: group membership is fabric-scoped, and §1.3.7.4's rule that a group's scenes go
285    /// with the group applies here too — `remove_fabric` takes both.
286    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
287        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
288            self.remove_fabric(fabric);
289        }
290    }
291    fn read(
292        &self,
293        resolved: &Resolved<'_>,
294        _ctx: &InteractionContext<'_>,
295        w: &mut TlvWriter<'_>,
296        tag: Tag,
297    ) -> Result<(), Status> {
298        if resolved.attribute != NAME_SUPPORT {
299            return Err(Status::UnsupportedAttribute);
300        }
301        w.unsigned(tag, u64::from(self.name_support().bits()))
302            .map_err(|_| Status::ResourceExhausted)
303    }
304
305    fn invoke(
306        &self,
307        resolved: &ResolvedCommand<'_>,
308        fields: Option<&[u8]>,
309        ctx: &InteractionContext<'_>,
310        w: &mut TlvWriter<'_>,
311        tag: Tag,
312    ) -> Result<Option<CommandId>, StatusIb> {
313        // §1.3.7.*: "If the ... command was received as a groupcast, the server SHALL NOT
314        // generate a ... Response command." Six lights answering one multicast at once is the
315        // storm the rule exists to prevent.
316        let answer = ctx.group.is_none();
317        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
318        // §1.3: "All commands defined in this cluster SHALL only affect groups scoped to the
319        // accessing fabric." Without one there is nothing to scope to.
320        let Some(fabric) = ctx.fabric_index else {
321            return Err(Status::UnsupportedAccess.into());
322        };
323
324        match resolved.command.id {
325            ADD_GROUP_IF_IDENTIFYING => {
326                let decoded: spec_groups::AddGroupIfIdentifyingFields<'_> =
327                    super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
328                // §1.3.7.6: the conditional form does nothing at all unless the endpoint is
329                // identifying itself, and says nothing either way — the specification defines
330                // no response command for it, so even a unicast gets only a status.
331                if self.identifying.is_identifying() {
332                    self.add(fabric, decoded.group_id, decoded.group_name);
333                }
334                Ok(None)
335            }
336            ADD_GROUP => {
337                let decoded: spec_groups::AddGroupFields<'_> =
338                    super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
339                let status = self.add(fabric, decoded.group_id, decoded.group_name);
340                if !answer {
341                    return Ok(None);
342                }
343                full(
344                    spec_groups::AddGroupResponseFields {
345                        status: status.value(),
346                        group_id: decoded.group_id,
347                    }
348                    .to_tlv(w, tag),
349                )?;
350                Ok(Some(ADD_GROUP_RESPONSE))
351            }
352            VIEW_GROUP => {
353                let decoded: spec_groups::ViewGroupFields =
354                    super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
355                let memberships = self.memberships.borrow();
356                let found = memberships
357                    .iter()
358                    .find(|m| m.fabric == fabric && m.group == decoded.group_id);
359                let status = match (decoded.group_id.0, found) {
360                    (0, _) => Status::ConstraintError,
361                    (_, Some(_)) => Status::Success,
362                    (_, None) => Status::NotFound,
363                };
364                let name = found.map_or("", Membership::name);
365                if !answer {
366                    return Ok(None);
367                }
368                full(
369                    spec_groups::ViewGroupResponseFields {
370                        status: status.value(),
371                        group_id: decoded.group_id,
372                        group_name: name,
373                    }
374                    .to_tlv(w, tag),
375                )?;
376                Ok(Some(VIEW_GROUP_RESPONSE))
377            }
378            GET_GROUP_MEMBERSHIP => {
379                let decoded: spec_groups::GetGroupMembershipFields<'_> =
380                    super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
381                // A groupcast gets nothing back — including the "no match" case §1.3.7.3
382                // singles out ("the server SHALL only respond if the command is unicast"),
383                // which this covers by never reaching the writer at all.
384                if !answer {
385                    return Ok(None);
386                }
387                // §1.3.7.3.1: "If the GroupList field is empty, the server SHALL respond with
388                // all group IDs indicating the groups of which the server endpoint is a
389                // member"; otherwise the intersection. Both readings are one pass over the
390                // table, with the request's list re-read per candidate rather than copied into
391                // a buffer this cluster would then have to size — a client may name more
392                // groups than the endpoint could ever hold.
393                let everything = decoded.group_list.is_empty();
394                let memberships = self.memberships.borrow();
395                full(w.start_structure(tag))?;
396                full(w.unsigned(Tag::Context(0), u64::from(self.capacity(fabric))))?;
397                full(w.start_array(Tag::Context(1)))?;
398                for membership in memberships.iter().filter(|m| m.fabric == fabric) {
399                    if !everything {
400                        let mut asked = false;
401                        for entry in decoded.group_list.iter() {
402                            let group: GroupId =
403                                entry.map_err(|_| StatusIb::from(Status::ConstraintError))?;
404                            if group == membership.group {
405                                asked = true;
406                                break;
407                            }
408                        }
409                        if !asked {
410                            continue;
411                        }
412                    }
413                    full(w.unsigned(Tag::Anonymous, u64::from(membership.group.0)))?;
414                }
415                full(w.end_container())?;
416                full(w.end_container())?;
417                Ok(Some(GET_GROUP_MEMBERSHIP_RESPONSE))
418            }
419            REMOVE_GROUP => {
420                let decoded: spec_groups::RemoveGroupFields =
421                    super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
422                let status = self.remove(fabric, decoded.group_id);
423                if !answer {
424                    return Ok(None);
425                }
426                full(
427                    spec_groups::RemoveGroupResponseFields {
428                        status: status.value(),
429                        group_id: decoded.group_id,
430                    }
431                    .to_tlv(w, tag),
432                )?;
433                Ok(Some(REMOVE_GROUP_RESPONSE))
434            }
435            REMOVE_ALL_GROUPS => {
436                // §1.3.7.5: every membership *for this fabric*. A device that cleared the
437                // whole table would remove another ecosystem's groups on a command it has no
438                // business acting on.
439                self.memberships.borrow_mut().retain(|m| m.fabric != fabric);
440                // "all scenes, except for scenes associated with group ID 0, SHALL be
441                // removed" — group 0's scenes were never reachable through a group, so
442                // leaving every group has not stranded them.
443                self.scenes.remove_grouped_scenes(fabric);
444                Ok(None)
445            }
446            _ => Err(Status::UnsupportedCommand.into()),
447        }
448    }
449}
450
451impl<const N: usize, I: Identifying, S: ScenePurge> GroupMembership for Groups<'_, N, I, S> {
452    fn is_group_member(&self, fabric: FabricIndex, group: GroupId) -> bool {
453        self.is_member(fabric, group)
454    }
455}
456
457/// So a tuple of clusters can dispatch to it by id.
458impl<const N: usize, I: Identifying, S: ScenePurge> Cluster for Groups<'_, N, I, S> {
459    const ID: ClusterId = ID;
460}