matter_kit/im/path.rs
1//! The paths that address things in the data model (Core §10.6.2, §10.6.7, §10.6.8,
2//! §10.6.11).
3//!
4//! A path names an attribute, event or command somewhere in a node's tree of endpoints and
5//! clusters. Three of the four are **wildcardable**: omitting a field means "all of them",
6//! which is how a client reads a whole endpoint in one action instead of enumerating it.
7//!
8//! # Why these are lists and not structures
9//!
10//! Every other information block is a TLV structure. The paths are `List`s, and the reason
11//! shows up in §10.6.2: `ListIndex` may repeat conceptually, and more importantly a list
12//! permits the tag-compression scheme where fields are *omitted* and inherited from an
13//! earlier path in the same action. A structure's "unique tags, all present that the schema
14//! requires" reading does not fit that.
15//!
16//! # Wildcards are absence, not a value
17//!
18//! There is no "wildcard" marker. §10.6.2.1: "omission of any of the tags in question (with
19//! the exception of Node) indicates wildcard semantics". So every wildcardable field here is
20//! an `Option`, and `None` means *all*, not *unknown* — which is why
21//! [`AttributePath::concrete`] exists to say whether a path names exactly one thing.
22//!
23//! # Tag compression is provisional and not implemented
24//!
25//! §10.6.2.1 defines an `EnableTagCompression` flag whose omitted fields inherit from "the
26//! last AttributePathIB that had EnableTagCompression not present or set to false … seen in
27//! a message that is part of the same interaction model Action". The specification marks it
28//! provisional. It is decoded and preserved — a path that sets it round-trips — but this
29//! crate does not *resolve* it, and [`AttributePath::enable_tag_compression`] being true is
30//! something a caller must refuse rather than misread, because the alternative is silently
31//! treating an inherited field as a wildcard.
32
33use crate::error::{Error, ErrorCode, Result, bail};
34use crate::msg::NodeId;
35use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value, set_once};
36
37/// An endpoint identifier (§7.5).
38pub type EndpointId = u16;
39/// A cluster identifier (§7.5).
40pub type ClusterId = u32;
41/// An attribute identifier (§7.5).
42pub type AttributeId = u32;
43/// An event identifier (§7.5).
44pub type EventId = u32;
45/// A command identifier (§7.5).
46pub type CommandId = u32;
47
48/// `ListIndex` when the path means "append to this list" (§10.6.4.3.1).
49///
50/// "Path SHALL refer to a list with ListIndex containing a value of null and Data containing
51/// the new value of the list item that will be added to the list."
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum ListIndex {
54 /// A specific item in a top-level list.
55 At(u16),
56 /// Null — a list append.
57 Append,
58}
59
60/// `AttributePathIB` (§10.6.2).
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub struct AttributePath {
63 /// `EnableTagCompression [0]` — provisional, decoded but not resolved.
64 pub enable_tag_compression: bool,
65 /// `Node [1]` — "MAY be omitted if the target node of the path matches the NodeID of
66 /// the server involved in the interaction", so `None` means *this* node and never
67 /// "every node".
68 pub node: Option<NodeId>,
69 /// `Endpoint [2]`; `None` is a wildcard.
70 pub endpoint: Option<EndpointId>,
71 /// `Cluster [3]`; `None` is a wildcard.
72 pub cluster: Option<ClusterId>,
73 /// `Attribute [4]`; `None` is a wildcard.
74 pub attribute: Option<AttributeId>,
75 /// `ListIndex [5]` — only meaningful when `attribute` is present.
76 pub list_index: Option<ListIndex>,
77 /// `WildcardPathFlags [6]` (§10.6.2, defined in §2.13.2), which narrows what a wildcard expands to.
78 pub wildcard_path_flags: Option<WildcardPathFlags>,
79 /// `WildcardFilterConfigurationVersion [7]`, added in interaction model revision 13.
80 pub wildcard_filter_configuration_version: Option<u32>,
81}
82
83bitflags::bitflags! {
84 /// `WildcardPathFlags` — which kinds of attribute a wildcard expansion skips
85 /// (§2.13.2).
86 ///
87 /// A client that only wants a device's own state can ask a wildcard not to expand into
88 /// the global attributes every cluster carries, which is most of what a naive wildcard
89 /// read returns.
90 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
91 pub struct WildcardPathFlags: u32 {
92 /// Bit 0 — "Skip the Root Node endpoint (endpoint 0) during wildcard expansion."
93 const SKIP_ROOT_NODE = 0x0000_0001;
94 /// Bit 1 — "Skip several large global attributes": §8.2.1.6 names exactly three,
95 /// `GeneratedCommandList`, `AcceptedCommandList` and `AttributeList`.
96 const SKIP_GLOBAL_ATTRIBUTES = 0x0000_0002;
97 /// Bit 2 — "Skip the AttributeList global attribute" (`0xFFFB`) alone.
98 const SKIP_ATTRIBUTE_LIST = 0x0000_0004;
99 /// Bit 4 — "Skip the AcceptedCommandList and GeneratedCommandList global attributes."
100 ///
101 /// **Bit 4, not bit 3.** §2.13.2's table reserves bit 3 as `DoNotUse`, and reading the
102 /// list of names without the bit numbers beside them puts this and every flag after it
103 /// one place too low — which is what this crate did, silently, for as long as nothing
104 /// honoured them.
105 const SKIP_COMMAND_LISTS = 0x0000_0010;
106 /// Bit 5 — "Skip any manufacturer-specific clusters or attributes."
107 const SKIP_CUSTOM_ELEMENTS = 0x0000_0020;
108 /// Bit 6 — "Skip any Fixed (F) quality attributes."
109 const SKIP_FIXED_ATTRIBUTES = 0x0000_0040;
110 /// Bit 7 — "Skip any Changes Omitted (C) quality attributes."
111 const SKIP_CHANGES_OMITTED = 0x0000_0080;
112 /// Bit 8 — "Skip all clusters with the Diagnostics (K) quality."
113 ///
114 /// Decoded and round-tripped, and **not** applied during expansion: `ClusterDescriptor`
115 /// carries no Diagnostics quality to test, and inventing one from the cluster id would
116 /// be a guess about which clusters the specification means. A flag this node cannot
117 /// honour is one it does not act on; see [`AttributePath::unsupported_flags`].
118 const SKIP_DIAGNOSTICS_CLUSTERS = 0x0000_0100;
119 }
120}
121
122impl AttributePath {
123 /// Whether §8.9.2.6's table admits this path in a Read or Subscribe.
124 ///
125 /// The table lists every legal wildcard combination, and one plausible-looking shape is
126 /// missing from it: a **wildcard cluster with a concrete attribute** is allowed only when
127 /// that attribute is a *global* one. The row reads "a specific **global** attribute data or
128 /// field for all clusters", and there is no row for a specific non-global attribute across
129 /// unspecified clusters.
130 ///
131 /// The reason is that attribute ids are only unique *within* a cluster. `0x0000` is
132 /// `OnOff` on one cluster and `CurrentLevel`-adjacent on another; asking for "attribute
133 /// 0x0000 on every cluster" asks for a set of unrelated values that happen to share a
134 /// number. Global attributes are the exception because their ids mean the same thing
135 /// everywhere, which is what makes them global.
136 ///
137 /// §8.4.3.2 step 1 makes a path the table does not admit a malformed *action*, so the whole
138 /// request is answered `INVALID_ACTION` rather than the path being given a status.
139 #[must_use]
140 pub const fn is_valid_for_read(&self) -> bool {
141 match (self.cluster, self.attribute) {
142 (None, Some(attribute)) => crate::dm::global::is_global(attribute),
143 _ => true,
144 }
145 }
146
147 /// A path naming exactly one attribute.
148 #[must_use]
149 pub const fn attribute(
150 endpoint: EndpointId,
151 cluster: ClusterId,
152 attribute: AttributeId,
153 ) -> Self {
154 Self {
155 enable_tag_compression: false,
156 node: None,
157 endpoint: Some(endpoint),
158 cluster: Some(cluster),
159 attribute: Some(attribute),
160 list_index: None,
161 wildcard_path_flags: None,
162 wildcard_filter_configuration_version: None,
163 }
164 }
165
166 /// A path naming every attribute of one cluster on one endpoint.
167 #[must_use]
168 pub const fn cluster(endpoint: EndpointId, cluster: ClusterId) -> Self {
169 Self {
170 endpoint: Some(endpoint),
171 cluster: Some(cluster),
172 ..Self::wildcard()
173 }
174 }
175
176 /// The path that names everything on the node — §10.6.2.5's `Path = [[ ]]`.
177 #[must_use]
178 pub const fn wildcard() -> Self {
179 Self {
180 enable_tag_compression: false,
181 node: None,
182 endpoint: None,
183 cluster: None,
184 attribute: None,
185 list_index: None,
186 wildcard_path_flags: None,
187 wildcard_filter_configuration_version: None,
188 }
189 }
190
191 /// The endpoint, cluster and attribute, if the path names exactly one of each.
192 ///
193 /// `None` when any of the three is wildcarded — which a server must expand rather than
194 /// reject, so this is a question and not a validation.
195 #[must_use]
196 pub const fn concrete(&self) -> Option<(EndpointId, ClusterId, AttributeId)> {
197 match (self.endpoint, self.cluster, self.attribute) {
198 (Some(e), Some(c), Some(a)) => Some((e, c, a)),
199 _ => None,
200 }
201 }
202
203 /// Whether any field is wildcarded.
204 #[must_use]
205 pub const fn has_wildcard(&self) -> bool {
206 self.concrete().is_none()
207 }
208
209 /// Writes the path as a `List` under `tag`.
210 ///
211 /// §10.6.1: "all context tags SHALL be emitted in the order as defined in the
212 /// appropriate specification. This is done to reduce receiver side complexity in having
213 /// to deal with arbitrary order tags." So the order here is the schema's, not a choice.
214 pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
215 w.start_list(tag)?;
216 if self.enable_tag_compression {
217 w.bool(Tag::Context(0), true)?;
218 }
219 if let Some(node) = self.node {
220 w.unsigned(Tag::Context(1), node.0)?;
221 }
222 if let Some(endpoint) = self.endpoint {
223 w.unsigned(Tag::Context(2), u64::from(endpoint))?;
224 }
225 if let Some(cluster) = self.cluster {
226 w.unsigned(Tag::Context(3), u64::from(cluster))?;
227 }
228 if let Some(attribute) = self.attribute {
229 w.unsigned(Tag::Context(4), u64::from(attribute))?;
230 }
231 match self.list_index {
232 Some(ListIndex::At(index)) => w.unsigned(Tag::Context(5), u64::from(index))?,
233 Some(ListIndex::Append) => w.null(Tag::Context(5))?,
234 None => {}
235 }
236 if let Some(flags) = self.wildcard_path_flags {
237 w.unsigned(Tag::Context(6), u64::from(flags.bits()))?;
238 }
239 if let Some(version) = self.wildcard_filter_configuration_version {
240 w.unsigned(Tag::Context(7), u64::from(version))?;
241 }
242 w.end_container()
243 }
244
245 /// Reads a path whose opening `List` element the caller has just taken.
246 pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
247 let mut out = Self::default();
248 let mut enable_tag_compression = None;
249 let mut node = None;
250 let mut endpoint = None;
251 let mut cluster = None;
252 let mut attribute = None;
253 let mut list_index = None;
254 let mut flags = None;
255 let mut version = None;
256
257 loop {
258 let Some(element) = reader.next_element()? else {
259 bail!(TlvTruncated)
260 };
261 if element.value == Value::EndOfContainer {
262 break;
263 }
264 match element.tag.context() {
265 Some(0) => set_once(&mut enable_tag_compression, element.bool()?)?,
266 Some(1) => set_once(&mut node, NodeId(element.unsigned()?))?,
267 Some(2) => set_once(&mut endpoint, narrow(element.unsigned()?)?)?,
268 Some(3) => set_once(&mut cluster, narrow32(element.unsigned()?)?)?,
269 Some(4) => set_once(&mut attribute, narrow32(element.unsigned()?)?)?,
270 Some(5) => {
271 // Nullable: null means append (§10.6.4.3.1), and "ListIndex is
272 // currently only allowed to be omitted or null. Any other value SHALL
273 // be interpreted as an error" — but that restriction belongs to the
274 // *write* path, and a read may legitimately index one, so the value is
275 // carried and the caller decides.
276 let value = match element.value {
277 Value::Null => ListIndex::Append,
278 Value::Unsigned(_) => ListIndex::At(narrow(element.unsigned()?)?),
279 _ => bail!(TlvWrongType),
280 };
281 set_once(&mut list_index, value)?;
282 }
283 Some(6) => {
284 let raw = narrow32(element.unsigned()?)?;
285 // An unknown flag is kept rather than refused: §10.2.2 makes unknown
286 // *tags* ignorable, and a flag this revision has not heard of should
287 // round-trip through a proxy rather than be dropped.
288 set_once(&mut flags, WildcardPathFlags::from_bits_retain(raw))?;
289 }
290 Some(7) => set_once(&mut version, narrow32(element.unsigned()?)?)?,
291 // §10.2.2: "any context-specific tag not listed in a given schema SHALL be
292 // reserved for future use and SHALL be silently ignored".
293 _ => reader.skip_value(&element)?,
294 }
295 }
296
297 out.enable_tag_compression = enable_tag_compression.unwrap_or(false);
298 out.node = node;
299 out.endpoint = endpoint;
300 out.cluster = cluster;
301 out.attribute = attribute;
302 out.list_index = list_index;
303 out.wildcard_path_flags = flags;
304 out.wildcard_filter_configuration_version = version;
305 Ok(out)
306 }
307
308 /// Reads a path from an element that should open a `List`.
309 pub fn from_element(reader: &mut TlvReader<'_>, element: &Element<'_>) -> Result<Self> {
310 if element.value.container() != Some(ContainerKind::List) {
311 bail!(TlvWrongType)
312 }
313 Self::decode(reader)
314 }
315}
316
317/// `ClusterPathIB` (§10.6.7) — a path with no attribute, used by data-version filters.
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
319pub struct ClusterPath {
320 /// `Node [0]`.
321 pub node: Option<NodeId>,
322 /// `Endpoint [1]`.
323 pub endpoint: Option<EndpointId>,
324 /// `Cluster [2]`.
325 pub cluster: Option<ClusterId>,
326}
327
328impl ClusterPath {
329 /// A path naming one cluster on one endpoint.
330 #[must_use]
331 pub const fn new(endpoint: EndpointId, cluster: ClusterId) -> Self {
332 Self {
333 node: None,
334 endpoint: Some(endpoint),
335 cluster: Some(cluster),
336 }
337 }
338
339 /// Writes the path as a `List` under `tag`.
340 pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
341 w.start_list(tag)?;
342 if let Some(node) = self.node {
343 w.unsigned(Tag::Context(0), node.0)?;
344 }
345 if let Some(endpoint) = self.endpoint {
346 w.unsigned(Tag::Context(1), u64::from(endpoint))?;
347 }
348 if let Some(cluster) = self.cluster {
349 w.unsigned(Tag::Context(2), u64::from(cluster))?;
350 }
351 w.end_container()
352 }
353
354 /// Reads a path whose opening `List` element the caller has just taken.
355 pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
356 let mut node = None;
357 let mut endpoint = None;
358 let mut cluster = None;
359 loop {
360 let Some(element) = reader.next_element()? else {
361 bail!(TlvTruncated)
362 };
363 if element.value == Value::EndOfContainer {
364 break;
365 }
366 match element.tag.context() {
367 Some(0) => set_once(&mut node, NodeId(element.unsigned()?))?,
368 Some(1) => set_once(&mut endpoint, narrow(element.unsigned()?)?)?,
369 Some(2) => set_once(&mut cluster, narrow32(element.unsigned()?)?)?,
370 _ => reader.skip_value(&element)?,
371 }
372 }
373 Ok(Self {
374 node,
375 endpoint,
376 cluster,
377 })
378 }
379}
380
381/// `EventPathIB` (§10.6.8).
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
383pub struct EventPath {
384 /// `Node [0]`.
385 pub node: Option<NodeId>,
386 /// `Endpoint [1]`; `None` is a wildcard.
387 pub endpoint: Option<EndpointId>,
388 /// `Cluster [2]`; `None` is a wildcard.
389 pub cluster: Option<ClusterId>,
390 /// `Event [3]`; `None` is a wildcard.
391 pub event: Option<EventId>,
392 /// `IsUrgent [4]` — a subscription asks for this event to be reported without waiting
393 /// for the next interval.
394 pub is_urgent: Option<bool>,
395}
396
397impl EventPath {
398 /// A path naming one event.
399 #[must_use]
400 pub const fn event(endpoint: EndpointId, cluster: ClusterId, event: EventId) -> Self {
401 Self {
402 node: None,
403 endpoint: Some(endpoint),
404 cluster: Some(cluster),
405 event: Some(event),
406 is_urgent: None,
407 }
408 }
409
410 /// Writes the path as a `List` under `tag`.
411 pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
412 w.start_list(tag)?;
413 if let Some(node) = self.node {
414 w.unsigned(Tag::Context(0), node.0)?;
415 }
416 if let Some(endpoint) = self.endpoint {
417 w.unsigned(Tag::Context(1), u64::from(endpoint))?;
418 }
419 if let Some(cluster) = self.cluster {
420 w.unsigned(Tag::Context(2), u64::from(cluster))?;
421 }
422 if let Some(event) = self.event {
423 w.unsigned(Tag::Context(3), u64::from(event))?;
424 }
425 if let Some(urgent) = self.is_urgent {
426 w.bool(Tag::Context(4), urgent)?;
427 }
428 w.end_container()
429 }
430
431 /// Reads a path whose opening `List` element the caller has just taken.
432 pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
433 let mut node = None;
434 let mut endpoint = None;
435 let mut cluster = None;
436 let mut event = None;
437 let mut is_urgent = None;
438 loop {
439 let Some(element) = reader.next_element()? else {
440 bail!(TlvTruncated)
441 };
442 if element.value == Value::EndOfContainer {
443 break;
444 }
445 match element.tag.context() {
446 Some(0) => set_once(&mut node, NodeId(element.unsigned()?))?,
447 Some(1) => set_once(&mut endpoint, narrow(element.unsigned()?)?)?,
448 Some(2) => set_once(&mut cluster, narrow32(element.unsigned()?)?)?,
449 Some(3) => set_once(&mut event, narrow32(element.unsigned()?)?)?,
450 Some(4) => set_once(&mut is_urgent, element.bool()?)?,
451 _ => reader.skip_value(&element)?,
452 }
453 }
454 Ok(Self {
455 node,
456 endpoint,
457 cluster,
458 event,
459 is_urgent,
460 })
461 }
462}
463
464/// `CommandPathIB` (§10.6.11).
465///
466/// Unlike the other three this has no `Node` field and no wildcards in practice: §8.9 makes
467/// a command invocation address one endpoint — a wildcard invoke is permitted only in the
468/// group case, where the endpoint comes from the group binding rather than the path.
469#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
470pub struct CommandPath {
471 /// `Endpoint [0]`; omitted for a group invoke.
472 pub endpoint: Option<EndpointId>,
473 /// `Cluster [1]`.
474 pub cluster: Option<ClusterId>,
475 /// `Command [2]`.
476 pub command: Option<CommandId>,
477}
478
479impl CommandPath {
480 /// A path naming one command.
481 #[must_use]
482 pub const fn command(endpoint: EndpointId, cluster: ClusterId, command: CommandId) -> Self {
483 Self {
484 endpoint: Some(endpoint),
485 cluster: Some(cluster),
486 command: Some(command),
487 }
488 }
489
490 /// The endpoint, cluster and command, if the path names all three.
491 #[must_use]
492 pub const fn concrete(&self) -> Option<(EndpointId, ClusterId, CommandId)> {
493 match (self.endpoint, self.cluster, self.command) {
494 (Some(e), Some(c), Some(cmd)) => Some((e, c, cmd)),
495 _ => None,
496 }
497 }
498
499 /// Writes the path as a `List` under `tag`.
500 pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
501 w.start_list(tag)?;
502 if let Some(endpoint) = self.endpoint {
503 w.unsigned(Tag::Context(0), u64::from(endpoint))?;
504 }
505 if let Some(cluster) = self.cluster {
506 w.unsigned(Tag::Context(1), u64::from(cluster))?;
507 }
508 if let Some(command) = self.command {
509 w.unsigned(Tag::Context(2), u64::from(command))?;
510 }
511 w.end_container()
512 }
513
514 /// Reads a path whose opening `List` element the caller has just taken.
515 pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
516 let mut endpoint = None;
517 let mut cluster = None;
518 let mut command = None;
519 loop {
520 let Some(element) = reader.next_element()? else {
521 bail!(TlvTruncated)
522 };
523 if element.value == Value::EndOfContainer {
524 break;
525 }
526 match element.tag.context() {
527 Some(0) => set_once(&mut endpoint, narrow(element.unsigned()?)?)?,
528 Some(1) => set_once(&mut cluster, narrow32(element.unsigned()?)?)?,
529 Some(2) => set_once(&mut command, narrow32(element.unsigned()?)?)?,
530 _ => reader.skip_value(&element)?,
531 }
532 }
533 Ok(Self {
534 endpoint,
535 cluster,
536 command,
537 })
538 }
539}
540
541fn narrow(value: u64) -> Result<u16> {
542 u16::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
543}
544
545fn narrow32(value: u64) -> Result<u32> {
546 u32::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
547}