Skip to main content

matter_kit/clusters/
label.rs

1//! Fixed Label `0x0040` and User Label `0x0041` (Core §9.7–9.9).
2//!
3//! Both are instances of §9.7's Label cluster, which "provides a feature to tag an endpoint
4//! with zero or more labels" and is a *base* cluster — it has no cluster id of its own and
5//! exists only through the two derived ones. They differ in exactly one thing, and it is the
6//! access quality:
7//!
8//! | | id | `LabelList` access |
9//! |---|---|---|
10//! | [`FixedLabel`] | `0x0040` | `RV` — read-only, the manufacturer's |
11//! | [`UserLabel`]  | `0x0041` | `RW VM` — writable at Manage, the owner's |
12//!
13//! That is the whole distinction and it is worth stating plainly: a fixed label is what the
14//! factory burned in ("serial", "model"), and a user label is what somebody with a phone
15//! typed ("room": "kitchen"). Making the fixed one writable would let a commissioner rewrite
16//! a device's identity; making the user one read-only would leave every ecosystem unable to
17//! name the thing it just commissioned.
18//!
19//! # Why they share a file
20//!
21//! §9.7.4.1's `LabelStruct` is the same in both, and so is the encoding. Two files would
22//! mean two copies of the same TLV, which is two places for the max-16 constraint to be got
23//! wrong.
24
25use core::cell::RefCell;
26
27use crate::dm::{
28    Access, AttributeDescriptor, AttributeQualities, ClusterDescriptor, CommandDescriptor,
29    Privilege, Resolved,
30};
31use crate::im::{AttributeId, ClusterHandler, ClusterId, InteractionContext, Status, WriteOp};
32use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
33
34use super::Cluster;
35
36/// `0x0040` (§9.8.3).
37pub const FIXED_LABEL_ID: ClusterId = 0x0040;
38/// `0x0041` (§9.9.3).
39pub const USER_LABEL_ID: ClusterId = 0x0041;
40
41/// The revision both derived clusters are at (§9.8.1, §9.9.1).
42pub const REVISION: u16 = 1;
43
44/// `LabelList` (§9.7.5.1) — the only attribute either cluster has.
45pub const LABEL_LIST: AttributeId = 0x0000;
46
47/// The longest a `Label` or a `Value` may be (§9.7.4.1: "max 16").
48pub const LABEL_MAX: usize = 16;
49
50/// One `LabelStruct` (§9.7.4.1): "a string tuple with strings that are user defined".
51///
52/// The specification declines to give either half a meaning — "The Label or Value semantic is
53/// not defined here" — and offers `"room":"bedroom 2"` and `"orientation":"North"` as
54/// examples. So this is deliberately two strings and no interpretation.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub struct Label<'a> {
57    /// `Label [0]` — the key. "room", "zone", "direction".
58    pub label: &'a str,
59    /// `Value [1]` — "a discriminator for a Label that may have multiple instances".
60    pub value: &'a str,
61}
62
63impl<'a> Label<'a> {
64    /// A label, or `None` if either half exceeds §9.7.4.1's 16 characters.
65    ///
66    /// Checked here rather than at write time so a `const` device model cannot declare a
67    /// label it would be unable to report.
68    #[must_use]
69    pub const fn new(label: &'a str, value: &'a str) -> Option<Self> {
70        if label.len() > LABEL_MAX || value.len() > LABEL_MAX {
71            return None;
72        }
73        Some(Self { label, value })
74    }
75
76    fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
77        w.start_structure(Tag::Anonymous)?;
78        w.utf8(Tag::Context(0), self.label)?;
79        w.utf8(Tag::Context(1), self.value)?;
80        w.end_container()
81    }
82}
83
84/// An owned label, for the list a [`UserLabel`] holds.
85///
86/// Owned rather than borrowed because a user label arrives over the wire and has to outlive
87/// the message it came in — which a `&str` into the receive buffer would not.
88#[derive(Debug, Clone, PartialEq, Eq, Default)]
89pub struct OwnedLabel {
90    label: heapless::String<LABEL_MAX>,
91    value: heapless::String<LABEL_MAX>,
92}
93
94impl OwnedLabel {
95    /// The key half.
96    #[must_use]
97    pub fn label(&self) -> &str {
98        &self.label
99    }
100
101    /// The value half.
102    #[must_use]
103    pub fn value(&self) -> &str {
104        &self.value
105    }
106
107    /// Borrows it as a [`Label`].
108    #[must_use]
109    pub fn as_label(&self) -> Label<'_> {
110        Label {
111            label: &self.label,
112            value: &self.value,
113        }
114    }
115
116    /// Builds one, refusing anything past §9.7.4.1's 16 characters.
117    pub fn new(label: &str, value: &str) -> Result<Self, Status> {
118        let mut out = Self::default();
119        out.label
120            .push_str(label)
121            .map_err(|_| Status::ConstraintError)?;
122        out.value
123            .push_str(value)
124            .map_err(|_| Status::ConstraintError)?;
125        Ok(out)
126    }
127}
128
129/// Writes a `LabelList` as the array §9.7.5.1 describes.
130fn write_list<'a>(
131    labels: impl Iterator<Item = Label<'a>>,
132    w: &mut TlvWriter<'_>,
133    tag: Tag,
134) -> Result<(), Status> {
135    let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
136    full(w.start_array(tag))?;
137    for label in labels {
138        full(label.encode(w))?;
139    }
140    full(w.end_container())
141}
142
143/// Reads one `LabelStruct` whose opening structure the caller has taken.
144fn decode_label(reader: &mut TlvReader<'_>) -> Result<OwnedLabel, Status> {
145    let mut label = None;
146    let mut value = None;
147    loop {
148        let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
149            return Err(Status::InvalidAction);
150        };
151        if element.value == Value::EndOfContainer {
152            break;
153        }
154        match element.tag.context() {
155            Some(0) => label = Some(element.utf8().map_err(|_| Status::InvalidAction)?),
156            Some(1) => value = Some(element.utf8().map_err(|_| Status::InvalidAction)?),
157            _ => reader
158                .skip_value(&element)
159                .map_err(|_| Status::InvalidAction)?,
160        }
161    }
162    // §9.7.4.1 gives both fields a fallback of "empty", so an absent one is the empty string
163    // rather than a malformed struct.
164    OwnedLabel::new(label.unwrap_or_default(), value.unwrap_or_default())
165}
166
167// --- Fixed Label -------------------------------------------------------------------------------
168
169/// §9.8.5's one attribute: `RV`, and `N` because a fixed label survives a reboot by definition.
170const FIXED_ATTRIBUTES: &[AttributeDescriptor] =
171    &[AttributeDescriptor::read_only(LABEL_LIST).with_qualities(AttributeQualities::NON_VOLATILE)];
172
173const NO_COMMANDS: &[CommandDescriptor] = &[];
174
175/// The descriptor for Fixed Label.
176#[must_use]
177pub const fn fixed_cluster() -> ClusterDescriptor<'static> {
178    ClusterDescriptor {
179        id: FIXED_LABEL_ID,
180        revision: REVISION,
181        feature_map: 0,
182        attributes: FIXED_ATTRIBUTES,
183        accepted_commands: NO_COMMANDS,
184        generated_commands: &[],
185        events: &[],
186    }
187}
188
189/// Fixed Label `0x0040` (§9.8): the labels the manufacturer burned in.
190///
191/// Read-only over the wire — §9.8.5 gives `LabelList` access `RV` — so the list is `&'static`
192/// data alongside the rest of the device's `const` model, and there is no path by which a
193/// commissioner could rewrite it.
194#[derive(Debug, Clone, Copy)]
195pub struct FixedLabel<'a> {
196    labels: &'a [Label<'a>],
197}
198
199impl<'a> FixedLabel<'a> {
200    /// A cluster over the manufacturer's labels.
201    #[must_use]
202    pub const fn new(labels: &'a [Label<'a>]) -> Self {
203        Self { labels }
204    }
205
206    /// The labels it reports.
207    #[must_use]
208    pub const fn labels(&self) -> &'a [Label<'a>] {
209        self.labels
210    }
211}
212
213impl ClusterHandler for FixedLabel<'_> {
214    fn read(
215        &self,
216        resolved: &Resolved<'_>,
217        _ctx: &InteractionContext<'_>,
218        w: &mut TlvWriter<'_>,
219        tag: Tag,
220    ) -> Result<(), Status> {
221        if resolved.attribute != LABEL_LIST {
222            return Err(Status::UnsupportedAttribute);
223        }
224        write_list(self.labels.iter().copied(), w, tag)
225    }
226}
227
228impl Cluster for FixedLabel<'_> {
229    const ID: ClusterId = FIXED_LABEL_ID;
230}
231
232// --- User Label --------------------------------------------------------------------------------
233
234/// §9.9.5's one attribute: `RW VM`, writable at Manage, and `N`.
235///
236/// Manage rather than Operate is the point: renaming a device is configuration, not use, so
237/// §9.9.5 puts it above the privilege an ordinary occupant holds.
238const USER_ATTRIBUTES: &[AttributeDescriptor] = &[AttributeDescriptor::read_write(LABEL_LIST)
239    .with_access(Access::read_write_with(Privilege::View, Privilege::Manage))
240    .with_qualities(AttributeQualities::NON_VOLATILE)];
241
242/// The descriptor for User Label.
243#[must_use]
244pub const fn user_cluster() -> ClusterDescriptor<'static> {
245    ClusterDescriptor {
246        id: USER_LABEL_ID,
247        revision: REVISION,
248        feature_map: 0,
249        attributes: USER_ATTRIBUTES,
250        accepted_commands: NO_COMMANDS,
251        generated_commands: &[],
252        events: &[],
253    }
254}
255
256/// User Label `0x0041` (§9.9): the labels the owner set.
257///
258/// `N` is a claim this type cannot make good on its own — §9.9.5 says the list survives a
259/// reboot, and nothing here writes to storage. [`UserLabel::labels`] is what a device
260/// persists, and [`UserLabel::restore`] is how it comes back.
261#[derive(Debug)]
262pub struct UserLabel<const N: usize> {
263    labels: RefCell<heapless::Vec<OwnedLabel, N>>,
264}
265
266impl<const N: usize> Default for UserLabel<N> {
267    fn default() -> Self {
268        Self::new()
269    }
270}
271
272impl<const N: usize> UserLabel<N> {
273    /// A cluster with no labels — a factory-fresh device's empty list (§9.9.5's fallback).
274    #[must_use]
275    pub const fn new() -> Self {
276        Self {
277            labels: RefCell::new(heapless::Vec::new()),
278        }
279    }
280
281    /// The labels, for a device about to persist them.
282    #[must_use]
283    pub fn labels(&self) -> core::cell::Ref<'_, heapless::Vec<OwnedLabel, N>> {
284        self.labels.borrow()
285    }
286
287    /// Restores the list a device persisted.
288    pub fn restore(&self, labels: impl IntoIterator<Item = OwnedLabel>) -> Result<(), Status> {
289        let mut held = self.labels.borrow_mut();
290        held.clear();
291        for label in labels {
292            held.push(label).map_err(|_| Status::ResourceExhausted)?;
293        }
294        Ok(())
295    }
296}
297
298impl<const N: usize> ClusterHandler for UserLabel<N> {
299    fn read(
300        &self,
301        resolved: &Resolved<'_>,
302        _ctx: &InteractionContext<'_>,
303        w: &mut TlvWriter<'_>,
304        tag: Tag,
305    ) -> Result<(), Status> {
306        if resolved.attribute != LABEL_LIST {
307            return Err(Status::UnsupportedAttribute);
308        }
309        let labels = self.labels.borrow();
310        write_list(labels.iter().map(OwnedLabel::as_label), w, tag)
311    }
312
313    fn write(
314        &self,
315        resolved: &Resolved<'_>,
316        data: &[u8],
317        op: WriteOp,
318        _ctx: &InteractionContext<'_>,
319    ) -> Result<(), Status> {
320        if resolved.attribute != LABEL_LIST {
321            return Err(Status::UnsupportedWrite);
322        }
323        let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
324        let element = reader
325            .next_element()
326            .map_err(|_| Status::InvalidAction)?
327            .ok_or(Status::InvalidAction)?;
328
329        match op {
330            // §10.6.4.3.1's REPLACE: the array is the new contents of the list.
331            WriteOp::Replace => {
332                if element.value.container() != Some(ContainerKind::Array) {
333                    return Err(Status::InvalidAction);
334                }
335                let mut replacement: heapless::Vec<OwnedLabel, N> = heapless::Vec::new();
336                loop {
337                    let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
338                    else {
339                        return Err(Status::InvalidAction);
340                    };
341                    if item.value == Value::EndOfContainer {
342                        break;
343                    }
344                    if item.value.container() != Some(ContainerKind::Structure) {
345                        return Err(Status::InvalidAction);
346                    }
347                    replacement
348                        .push(decode_label(&mut reader)?)
349                        .map_err(|_| Status::ResourceExhausted)?;
350                }
351                *self.labels.borrow_mut() = replacement;
352            }
353            // §10.6.4.3.1's ADD: one more label.
354            WriteOp::Append => {
355                if element.value.container() != Some(ContainerKind::Structure) {
356                    return Err(Status::InvalidAction);
357                }
358                let label = decode_label(&mut reader)?;
359                self.labels
360                    .borrow_mut()
361                    .push(label)
362                    .map_err(|_| Status::ResourceExhausted)?;
363            }
364        }
365        Ok(())
366    }
367}
368
369impl<const N: usize> Cluster for UserLabel<N> {
370    const ID: ClusterId = USER_LABEL_ID;
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn a_label_longer_than_sixteen_is_refused_when_the_model_is_built() {
379        assert!(Label::new("room", "kitchen").is_some());
380        assert!(Label::new("room", "seventeen chars!!").is_none());
381        assert!(Label::new("a-seventeen-char!", "x").is_none());
382        // Exactly sixteen is the limit, not one short of it.
383        assert!(Label::new("sixteen-chars-ok", "sixteen-chars-ok").is_some());
384    }
385
386    #[test]
387    fn the_two_clusters_differ_only_in_whether_the_list_can_be_written() {
388        // The whole point of there being two derived clusters. A writable fixed label would
389        // let a commissioner rewrite a device's identity; a read-only user label would leave
390        // every ecosystem unable to name what it just commissioned.
391        let fixed = fixed_cluster();
392        let user = user_cluster();
393        assert_eq!(fixed.id, 0x0040);
394        assert_eq!(user.id, 0x0041);
395
396        let fixed_list = fixed.attribute(LABEL_LIST).expect("LabelList");
397        assert_eq!(fixed_list.access.read, Some(Privilege::View));
398        assert_eq!(fixed_list.access.write, None, "§9.8.5 gives it `RV`");
399
400        let user_list = user.attribute(LABEL_LIST).expect("LabelList");
401        assert_eq!(user_list.access.read, Some(Privilege::View));
402        assert_eq!(
403            user_list.access.write,
404            Some(Privilege::Manage),
405            "§9.9.5 gives it `RW VM` — renaming is configuration, not use"
406        );
407        // Both survive a reboot.
408        assert!(
409            fixed_list
410                .qualities
411                .contains(AttributeQualities::NON_VOLATILE)
412        );
413        assert!(
414            user_list
415                .qualities
416                .contains(AttributeQualities::NON_VOLATILE)
417        );
418    }
419
420    #[test]
421    fn a_user_label_list_is_bounded_by_its_capacity() {
422        let cluster = UserLabel::<2>::new();
423        cluster
424            .restore([
425                OwnedLabel::new("room", "kitchen").expect("fits"),
426                OwnedLabel::new("floor", "1").expect("fits"),
427            ])
428            .expect("two fit");
429        assert_eq!(
430            cluster
431                .restore([
432                    OwnedLabel::new("a", "1").expect("fits"),
433                    OwnedLabel::new("b", "2").expect("fits"),
434                    OwnedLabel::new("c", "3").expect("fits"),
435                ])
436                .unwrap_err(),
437            Status::ResourceExhausted,
438            "§9.6.1's rule for a full list, and the only honest answer without an allocator"
439        );
440    }
441
442    #[test]
443    fn an_over_long_label_is_a_constraint_error_not_a_truncation() {
444        // Truncating would store something the client never asked for and report success.
445        assert_eq!(
446            OwnedLabel::new("this-label-is-far-too-long", "x").unwrap_err(),
447            Status::ConstraintError
448        );
449    }
450}