1use 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
36pub const FIXED_LABEL_ID: ClusterId = 0x0040;
38pub const USER_LABEL_ID: ClusterId = 0x0041;
40
41pub const REVISION: u16 = 1;
43
44pub const LABEL_LIST: AttributeId = 0x0000;
46
47pub const LABEL_MAX: usize = 16;
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub struct Label<'a> {
57 pub label: &'a str,
59 pub value: &'a str,
61}
62
63impl<'a> Label<'a> {
64 #[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#[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 #[must_use]
97 pub fn label(&self) -> &str {
98 &self.label
99 }
100
101 #[must_use]
103 pub fn value(&self) -> &str {
104 &self.value
105 }
106
107 #[must_use]
109 pub fn as_label(&self) -> Label<'_> {
110 Label {
111 label: &self.label,
112 value: &self.value,
113 }
114 }
115
116 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
129fn 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
143fn 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 OwnedLabel::new(label.unwrap_or_default(), value.unwrap_or_default())
165}
166
167const FIXED_ATTRIBUTES: &[AttributeDescriptor] =
171 &[AttributeDescriptor::read_only(LABEL_LIST).with_qualities(AttributeQualities::NON_VOLATILE)];
172
173const NO_COMMANDS: &[CommandDescriptor] = &[];
174
175#[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#[derive(Debug, Clone, Copy)]
195pub struct FixedLabel<'a> {
196 labels: &'a [Label<'a>],
197}
198
199impl<'a> FixedLabel<'a> {
200 #[must_use]
202 pub const fn new(labels: &'a [Label<'a>]) -> Self {
203 Self { labels }
204 }
205
206 #[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
232const 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#[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#[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 #[must_use]
275 pub const fn new() -> Self {
276 Self {
277 labels: RefCell::new(heapless::Vec::new()),
278 }
279 }
280
281 #[must_use]
283 pub fn labels(&self) -> core::cell::Ref<'_, heapless::Vec<OwnedLabel, N>> {
284 self.labels.borrow()
285 }
286
287 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 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 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 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 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 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 assert_eq!(
446 OwnedLabel::new("this-label-is-far-too-long", "x").unwrap_err(),
447 Status::ConstraintError
448 );
449 }
450}