Skip to main content

matter_kit/im/
ib.rs

1//! Information blocks — the pieces every interaction model action is built from
2//! (Core §10.6).
3//!
4//! §10.6: "These are elements that may apply to multiple message types, and are defined in
5//! a common way to permit re-use as a definition."
6//!
7//! # Data is carried, not interpreted
8//!
9//! An attribute's value has a *cluster's* type, not the interaction model's. §10.6.4.3 makes
10//! the `Data` field "Variable", and what it holds is whatever the cluster's schema says. So
11//! every IB here keeps that field as the **encoded TLV element**, borrowed from the buffer
12//! it arrived in, and hands it on with
13//! [`TlvWriter::raw_element`](crate::tlv::TlvWriter::raw_element).
14//!
15//! That is not laziness, it is the only correct shape at this layer: a proxy forwarding a
16//! report must not need to know the cluster to forward it, and a server reading a value must
17//! hand the cluster exactly the octets the client sent rather than a re-encoding of them.
18//! The writer still validates that the bytes are one well-formed element carrying a tag this
19//! position admits, so a forwarding path cannot launder invalid TLV.
20//!
21//! # Status or data, never both
22//!
23//! [`AttributeReport`] and [`InvokeResponse`] are the two places the specification models a
24//! choice as a structure with two optional fields. A report carries an `AttributeStatusIB`
25//! *or* an `AttributeDataIB`; §8.4.3 is clear that one of them is always present. They are
26//! modelled as enums here, so "neither" and "both" are unrepresentable rather than merely
27//! discouraged.
28
29use crate::error::{Error, ErrorCode, Result, bail};
30use crate::im::path::{AttributePath, ClusterPath, CommandPath, EventPath};
31use crate::im::status::Status;
32use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value, set_once};
33
34/// A cluster's data version (§7.10.3), which a client caches and filters on.
35pub type DataVersion = u32;
36
37/// `StatusIB` (§10.6.17).
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub struct StatusIb {
40    /// `Status [0]` — an interaction model status (§8.10).
41    pub status: Status,
42    /// `ClusterStatus [1]` — a cluster-defined code, meaningful only when `status` is
43    /// `FAILURE` and the cluster defines one.
44    pub cluster_status: Option<u8>,
45}
46
47impl From<Status> for StatusIb {
48    fn from(status: Status) -> Self {
49        Self::new(status)
50    }
51}
52
53impl StatusIb {
54    /// A cluster-defined failure — §8.10's `FAILURE` with a `ClusterStatus` beside it.
55    ///
56    /// §8.10.1: `FAILURE` is "the sender has failed to execute the request for an unspecified
57    /// reason", and the cluster-specific code is what specifies it. §11.19.6's `Busy`,
58    /// `PAKEParameterError` and `WindowNotOpen` are the ones this crate uses.
59    ///
60    /// The status must be `FAILURE` for the code to mean anything: §10.6.17 makes
61    /// `ClusterStatus` "meaningful only when the Status is FAILURE".
62    #[must_use]
63    pub const fn cluster_failure(cluster_status: u8) -> Self {
64        Self {
65            status: Status::Failure,
66            cluster_status: Some(cluster_status),
67        }
68    }
69
70    /// A plain status with no cluster-specific code.
71    #[must_use]
72    pub const fn new(status: Status) -> Self {
73        Self {
74            status,
75            cluster_status: None,
76        }
77    }
78
79    /// Writes the block as a `Structure` under `tag`.
80    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
81        w.start_structure(tag)?;
82        w.unsigned(Tag::Context(0), u64::from(self.status.value()))?;
83        if let Some(cluster_status) = self.cluster_status {
84            w.unsigned(Tag::Context(1), u64::from(cluster_status))?;
85        }
86        w.end_container()
87    }
88
89    /// Reads a block whose opening `Structure` element the caller has just taken.
90    pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
91        let mut status = None;
92        let mut cluster_status = None;
93        loop {
94            let Some(element) = reader.next_element()? else {
95                bail!(TlvTruncated)
96            };
97            if element.value == Value::EndOfContainer {
98                break;
99            }
100            match element.tag.context() {
101                Some(0) => set_once(
102                    &mut status,
103                    Status::from_value(narrow8(element.unsigned()?)?),
104                )?,
105                Some(1) => set_once(&mut cluster_status, narrow8(element.unsigned()?)?)?,
106                _ => reader.skip_value(&element)?,
107            }
108        }
109        Ok(Self {
110            status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
111            cluster_status,
112        })
113    }
114}
115
116/// `AttributeDataIB` (§10.6.4) — a path and the value at it.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct AttributeData<'a> {
119    /// `DataVersion [0]` — "the data version of the cluster instance", present in a report
120    /// and absent in a write.
121    pub data_version: Option<DataVersion>,
122    /// `Path [1]`.
123    pub path: AttributePath,
124    /// `Data [2]` — the encoded TLV element, tag included, exactly as it arrived.
125    pub data: &'a [u8],
126}
127
128impl<'a> AttributeData<'a> {
129    /// Writes the block as a `Structure` under `tag`.
130    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
131        w.start_structure(tag)?;
132        if let Some(version) = self.data_version {
133            w.unsigned(Tag::Context(0), u64::from(version))?;
134        }
135        self.path.encode(w, Tag::Context(1))?;
136        // The data already carries its context-2 tag; `raw_element` checks that it is one
137        // well-formed element and that the tag is legal here before copying it.
138        w.raw_element(self.data)?;
139        w.end_container()
140    }
141
142    /// Reads a block whose opening `Structure` element the caller has just taken.
143    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
144        let mut data_version = None;
145        let mut path = None;
146        let mut data = None;
147        loop {
148            let start = reader.position();
149            let Some(element) = reader.next_element()? else {
150                bail!(TlvTruncated)
151            };
152            if element.value == Value::EndOfContainer {
153                break;
154            }
155            match element.tag.context() {
156                Some(0) => set_once(&mut data_version, narrow32(element.unsigned()?)?)?,
157                Some(1) => {
158                    if element.value.container() != Some(ContainerKind::List) {
159                        bail!(TlvWrongType)
160                    }
161                    set_once(&mut path, AttributePath::decode(reader)?)?;
162                }
163                Some(2) => {
164                    reader.skip_value(&element)?;
165                    set_once(&mut data, reader.slice_from(start)?)?;
166                }
167                _ => reader.skip_value(&element)?,
168            }
169        }
170        Ok(Self {
171            data_version,
172            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
173            data: data.ok_or(Error::new(ErrorCode::TlvNotFound))?,
174        })
175    }
176}
177
178/// `AttributeStatusIB` (§10.6.16).
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub struct AttributeStatus {
181    /// `Path [0]`.
182    pub path: AttributePath,
183    /// `Status [1]`.
184    pub status: StatusIb,
185}
186
187impl AttributeStatus {
188    /// Writes the block as a `Structure` under `tag`.
189    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
190        w.start_structure(tag)?;
191        self.path.encode(w, Tag::Context(0))?;
192        self.status.encode(w, Tag::Context(1))?;
193        w.end_container()
194    }
195
196    /// Reads a block whose opening `Structure` element the caller has just taken.
197    pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
198        let mut path = None;
199        let mut status = None;
200        loop {
201            let Some(element) = reader.next_element()? else {
202                bail!(TlvTruncated)
203            };
204            if element.value == Value::EndOfContainer {
205                break;
206            }
207            match element.tag.context() {
208                Some(0) => {
209                    if element.value.container() != Some(ContainerKind::List) {
210                        bail!(TlvWrongType)
211                    }
212                    set_once(&mut path, AttributePath::decode(reader)?)?;
213                }
214                Some(1) => {
215                    if element.value.container() != Some(ContainerKind::Structure) {
216                        bail!(TlvWrongType)
217                    }
218                    set_once(&mut status, StatusIb::decode(reader)?)?;
219                }
220                _ => reader.skip_value(&element)?,
221            }
222        }
223        Ok(Self {
224            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
225            status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
226        })
227    }
228}
229
230/// `AttributeReportIB` (§10.6.5) — one attribute's outcome in a report.
231///
232/// The schema is a structure with two optional fields; §8.4.3 gives exactly one of them.
233/// Modelling it as a choice makes "neither" and "both" unrepresentable.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum AttributeReport<'a> {
236    /// `AttributeStatus [0]` — the path could not be served.
237    Status(AttributeStatus),
238    /// `AttributeData [1]` — the value.
239    Data(AttributeData<'a>),
240}
241
242impl<'a> AttributeReport<'a> {
243    /// The path this report is about, whichever arm it is.
244    #[must_use]
245    pub const fn path(&self) -> AttributePath {
246        match self {
247            Self::Status(s) => s.path,
248            Self::Data(d) => d.path,
249        }
250    }
251
252    /// Writes the block as an anonymous `Structure`, which is what an array member is.
253    pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
254        w.start_structure(Tag::Anonymous)?;
255        match self {
256            Self::Status(status) => status.encode(w, Tag::Context(0))?,
257            Self::Data(data) => data.encode(w, Tag::Context(1))?,
258        }
259        w.end_container()
260    }
261
262    /// Reads a block whose opening `Structure` element the caller has just taken.
263    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
264        let mut out = None;
265        loop {
266            let Some(element) = reader.next_element()? else {
267                bail!(TlvTruncated)
268            };
269            if element.value == Value::EndOfContainer {
270                break;
271            }
272            match element.tag.context() {
273                Some(0) => {
274                    expect_structure(&element)?;
275                    set_once(&mut out, Self::Status(AttributeStatus::decode(reader)?))?;
276                }
277                Some(1) => {
278                    expect_structure(&element)?;
279                    set_once(&mut out, Self::Data(AttributeData::decode(reader)?))?;
280                }
281                _ => reader.skip_value(&element)?,
282            }
283        }
284        // A report with neither arm says nothing about the path it names, which no reader
285        // could act on.
286        out.ok_or(Error::new(ErrorCode::TlvNotFound))
287    }
288}
289
290/// `DataVersionFilterIB` (§10.6.3) — "I already have version V of this cluster; skip it."
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub struct DataVersionFilter {
293    /// `Path [0]`.
294    pub path: ClusterPath,
295    /// `DataVersion [1]`.
296    pub data_version: DataVersion,
297}
298
299impl DataVersionFilter {
300    /// Writes the block as an anonymous `Structure`.
301    pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
302        w.start_structure(Tag::Anonymous)?;
303        self.path.encode(w, Tag::Context(0))?;
304        w.unsigned(Tag::Context(1), u64::from(self.data_version))?;
305        w.end_container()
306    }
307
308    /// Reads a block whose opening `Structure` element the caller has just taken.
309    pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
310        let mut path = None;
311        let mut data_version = None;
312        loop {
313            let Some(element) = reader.next_element()? else {
314                bail!(TlvTruncated)
315            };
316            if element.value == Value::EndOfContainer {
317                break;
318            }
319            match element.tag.context() {
320                Some(0) => {
321                    if element.value.container() != Some(ContainerKind::List) {
322                        bail!(TlvWrongType)
323                    }
324                    set_once(&mut path, ClusterPath::decode(reader)?)?;
325                }
326                Some(1) => set_once(&mut data_version, narrow32(element.unsigned()?)?)?,
327                _ => reader.skip_value(&element)?,
328            }
329        }
330        Ok(Self {
331            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
332            data_version: data_version.ok_or(Error::new(ErrorCode::TlvNotFound))?,
333        })
334    }
335}
336
337/// `EventFilterIB` (§10.6.6) — "I already have events up to number N."
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub struct EventFilter {
340    /// `Node [0]`.
341    pub node: Option<crate::msg::NodeId>,
342    /// `EventMin [1]` — the lowest event number the client still wants.
343    pub event_min: u64,
344}
345
346impl EventFilter {
347    /// Writes the block as an anonymous `Structure`.
348    pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
349        w.start_structure(Tag::Anonymous)?;
350        if let Some(node) = self.node {
351            w.unsigned(Tag::Context(0), node.0)?;
352        }
353        w.unsigned(Tag::Context(1), self.event_min)?;
354        w.end_container()
355    }
356
357    /// Reads a block whose opening `Structure` element the caller has just taken.
358    pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
359        let mut node = None;
360        let mut event_min = None;
361        loop {
362            let Some(element) = reader.next_element()? else {
363                bail!(TlvTruncated)
364            };
365            if element.value == Value::EndOfContainer {
366                break;
367            }
368            match element.tag.context() {
369                Some(0) => set_once(&mut node, crate::msg::NodeId(element.unsigned()?))?,
370                Some(1) => set_once(&mut event_min, element.unsigned()?)?,
371                _ => reader.skip_value(&element)?,
372            }
373        }
374        Ok(Self {
375            node,
376            event_min: event_min.ok_or(Error::new(ErrorCode::TlvNotFound))?,
377        })
378    }
379}
380
381/// `CommandDataIB` (§10.6.12) — a command invocation, or a command response's payload.
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub struct CommandData<'a> {
384    /// `CommandPath [0]`.
385    pub path: CommandPath,
386    /// `CommandFields [1]` — the encoded TLV element, or `None` for a command with no
387    /// fields.
388    pub fields: Option<&'a [u8]>,
389    /// `CommandRef [2]` — which request this response answers, when an `InvokeRequest`
390    /// carried more than one command (interaction model revision 12 and later).
391    pub command_ref: Option<u16>,
392}
393
394impl<'a> CommandData<'a> {
395    /// An invocation of a command that takes no fields.
396    #[must_use]
397    pub const fn new(path: CommandPath) -> Self {
398        Self {
399            path,
400            fields: None,
401            command_ref: None,
402        }
403    }
404
405    /// Writes the block as an anonymous `Structure`.
406    pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
407        w.start_structure(Tag::Anonymous)?;
408        self.path.encode(w, Tag::Context(0))?;
409        if let Some(fields) = self.fields {
410            w.raw_element(fields)?;
411        }
412        if let Some(command_ref) = self.command_ref {
413            w.unsigned(Tag::Context(2), u64::from(command_ref))?;
414        }
415        w.end_container()
416    }
417
418    /// Reads a block whose opening `Structure` element the caller has just taken.
419    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
420        let mut path = None;
421        let mut fields = None;
422        let mut command_ref = None;
423        loop {
424            let start = reader.position();
425            let Some(element) = reader.next_element()? else {
426                bail!(TlvTruncated)
427            };
428            if element.value == Value::EndOfContainer {
429                break;
430            }
431            match element.tag.context() {
432                Some(0) => {
433                    if element.value.container() != Some(ContainerKind::List) {
434                        bail!(TlvWrongType)
435                    }
436                    set_once(&mut path, CommandPath::decode(reader)?)?;
437                }
438                Some(1) => {
439                    reader.skip_value(&element)?;
440                    set_once(&mut fields, reader.slice_from(start)?)?;
441                }
442                Some(2) => set_once(&mut command_ref, narrow16(element.unsigned()?)?)?,
443                _ => reader.skip_value(&element)?,
444            }
445        }
446        Ok(Self {
447            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
448            fields,
449            command_ref,
450        })
451    }
452}
453
454/// `CommandStatusIB` (§10.6.14) — a command that produced a status rather than a response.
455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456pub struct CommandStatus {
457    /// `CommandPath [0]`.
458    pub path: CommandPath,
459    /// `Status [1]`.
460    pub status: StatusIb,
461    /// `CommandRef [2]`.
462    pub command_ref: Option<u16>,
463}
464
465impl CommandStatus {
466    /// Writes the block as a `Structure` under `tag`.
467    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
468        w.start_structure(tag)?;
469        self.path.encode(w, Tag::Context(0))?;
470        self.status.encode(w, Tag::Context(1))?;
471        if let Some(command_ref) = self.command_ref {
472            w.unsigned(Tag::Context(2), u64::from(command_ref))?;
473        }
474        w.end_container()
475    }
476
477    /// Reads a block whose opening `Structure` element the caller has just taken.
478    pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
479        let mut path = None;
480        let mut status = None;
481        let mut command_ref = None;
482        loop {
483            let Some(element) = reader.next_element()? else {
484                bail!(TlvTruncated)
485            };
486            if element.value == Value::EndOfContainer {
487                break;
488            }
489            match element.tag.context() {
490                Some(0) => {
491                    if element.value.container() != Some(ContainerKind::List) {
492                        bail!(TlvWrongType)
493                    }
494                    set_once(&mut path, CommandPath::decode(reader)?)?;
495                }
496                Some(1) => {
497                    expect_structure(&element)?;
498                    set_once(&mut status, StatusIb::decode(reader)?)?;
499                }
500                Some(2) => set_once(&mut command_ref, narrow16(element.unsigned()?)?)?,
501                _ => reader.skip_value(&element)?,
502            }
503        }
504        Ok(Self {
505            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
506            status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
507            command_ref,
508        })
509    }
510}
511
512/// `InvokeResponseIB` (§10.6.13) — one command's outcome.
513///
514/// As with [`AttributeReport`], the schema's two optional fields are a choice: a command
515/// either produced a response payload or a status.
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
517pub enum InvokeResponse<'a> {
518    /// `Command [0]` — a response command with its fields.
519    Command(CommandData<'a>),
520    /// `Status [1]`.
521    Status(CommandStatus),
522}
523
524impl<'a> InvokeResponse<'a> {
525    /// Writes the block as an anonymous `Structure`.
526    pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
527        w.start_structure(Tag::Anonymous)?;
528        match self {
529            Self::Command(command) => {
530                // A CommandDataIB is itself an anonymous structure in an array, but here it
531                // sits under context tag 0, so it is written out field by field rather than
532                // through `CommandData::encode`.
533                w.start_structure(Tag::Context(0))?;
534                command.path.encode(w, Tag::Context(0))?;
535                if let Some(fields) = command.fields {
536                    w.raw_element(fields)?;
537                }
538                if let Some(command_ref) = command.command_ref {
539                    w.unsigned(Tag::Context(2), u64::from(command_ref))?;
540                }
541                w.end_container()?;
542            }
543            Self::Status(status) => status.encode(w, Tag::Context(1))?,
544        }
545        w.end_container()
546    }
547
548    /// Reads a block whose opening `Structure` element the caller has just taken.
549    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
550        let mut out = None;
551        loop {
552            let Some(element) = reader.next_element()? else {
553                bail!(TlvTruncated)
554            };
555            if element.value == Value::EndOfContainer {
556                break;
557            }
558            match element.tag.context() {
559                Some(0) => {
560                    expect_structure(&element)?;
561                    set_once(&mut out, Self::Command(CommandData::decode(reader)?))?;
562                }
563                Some(1) => {
564                    expect_structure(&element)?;
565                    set_once(&mut out, Self::Status(CommandStatus::decode(reader)?))?;
566                }
567                _ => reader.skip_value(&element)?,
568            }
569        }
570        out.ok_or(Error::new(ErrorCode::TlvNotFound))
571    }
572}
573
574/// `EventStatusIB` (§10.6.15).
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
576pub struct EventStatus {
577    /// `Path [0]`.
578    pub path: EventPath,
579    /// `Status [1]`.
580    pub status: StatusIb,
581}
582
583impl EventStatus {
584    /// Writes the block as a `Structure` under `tag`.
585    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
586        w.start_structure(tag)?;
587        self.path.encode(w, Tag::Context(0))?;
588        self.status.encode(w, Tag::Context(1))?;
589        w.end_container()
590    }
591
592    /// Reads a block whose opening `Structure` element the caller has just taken.
593    pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
594        let mut path = None;
595        let mut status = None;
596        loop {
597            let Some(element) = reader.next_element()? else {
598                bail!(TlvTruncated)
599            };
600            if element.value == Value::EndOfContainer {
601                break;
602            }
603            match element.tag.context() {
604                Some(0) => {
605                    if element.value.container() != Some(ContainerKind::List) {
606                        bail!(TlvWrongType)
607                    }
608                    set_once(&mut path, EventPath::decode(reader)?)?;
609                }
610                Some(1) => {
611                    expect_structure(&element)?;
612                    set_once(&mut status, StatusIb::decode(reader)?)?;
613                }
614                _ => reader.skip_value(&element)?,
615            }
616        }
617        Ok(Self {
618            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
619            status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
620        })
621    }
622}
623
624fn expect_structure(element: &Element<'_>) -> Result<()> {
625    if element.value.container() == Some(ContainerKind::Structure) {
626        Ok(())
627    } else {
628        Err(Error::new(ErrorCode::TlvWrongType))
629    }
630}
631
632fn narrow8(value: u64) -> Result<u8> {
633    u8::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
634}
635
636fn narrow16(value: u64) -> Result<u16> {
637    u16::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
638}
639
640fn narrow32(value: u64) -> Result<u32> {
641    u32::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
642}
643
644/// `EventDataIB` (§10.6.9).
645///
646/// # The timestamp is a *choice* of four, and exactly one is present
647///
648/// §10.6.9's schema wraps tags 3 to 6 in a `one-of`, and the two delta forms say so twice
649/// over: "When this tag is present, all other timestamp tags SHALL be omitted." A record
650/// therefore carries an absolute epoch time, an absolute system time, or a delta against the
651/// previous record in the same report — never two of them, and never none.
652///
653/// The delta forms exist because a burst of events reported together differ by milliseconds:
654/// §7.14.1.2 requires a timestamp on every record "at the time it was created (and not when
655/// it is reported to a client)", and encoding forty of them as full 64-bit values is forty
656/// times eight octets where a delta is usually one or two.
657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
658pub struct EventData<'a> {
659    /// `Path [0]`.
660    pub path: EventPath,
661    /// `EventNumber [1]` — §7.14.1.1's node-scoped number, "monotonically increasing for the
662    /// life of the node", preserved across restarts.
663    pub number: u64,
664    /// `Priority [2]`.
665    pub priority: u8,
666    /// The timestamp, in one of §10.6.9's four forms.
667    pub timestamp: EventTimestamp,
668    /// `Data [7]` — the encoded TLV element, tag included, exactly as the cluster wrote it.
669    ///
670    /// §10.6.9.3: "If the cluster does not define any payload for the given event instance,
671    /// this Data field SHALL be encoded as a struct with no member elements" — an *empty
672    /// structure*, not an absent field.
673    pub data: &'a [u8],
674}
675
676/// §10.6.9's timestamp choice.
677#[derive(Debug, Clone, Copy, PartialEq, Eq)]
678pub enum EventTimestamp {
679    /// `EpochTimestamp [3]` — POSIX milliseconds. A node that knows the wall-clock time.
680    Epoch(u64),
681    /// `SystemTimestamp [4]` — milliseconds since boot. A node that does not.
682    System(u64),
683    /// `DeltaEpochTimestamp [5]` — milliseconds since the previous record's epoch time.
684    DeltaEpoch(u64),
685    /// `DeltaSystemTimestamp [6]` — milliseconds since the previous record's system time.
686    DeltaSystem(u64),
687}
688
689impl EventTimestamp {
690    /// The context tag this form occupies.
691    #[must_use]
692    pub const fn tag(self) -> u8 {
693        match self {
694            Self::Epoch(_) => 3,
695            Self::System(_) => 4,
696            Self::DeltaEpoch(_) => 5,
697            Self::DeltaSystem(_) => 6,
698        }
699    }
700
701    /// The value, whichever form it is.
702    #[must_use]
703    pub const fn value(self) -> u64 {
704        match self {
705            Self::Epoch(value)
706            | Self::System(value)
707            | Self::DeltaEpoch(value)
708            | Self::DeltaSystem(value) => value,
709        }
710    }
711
712    /// Whether this is one of the two delta forms.
713    #[must_use]
714    pub const fn is_delta(self) -> bool {
715        matches!(self, Self::DeltaEpoch(_) | Self::DeltaSystem(_))
716    }
717}
718
719impl<'a> EventData<'a> {
720    /// Writes the block as a `Structure` under `tag`.
721    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
722        w.start_structure(tag)?;
723        self.path.encode(w, Tag::Context(0))?;
724        w.unsigned(Tag::Context(1), self.number)?;
725        w.unsigned(Tag::Context(2), u64::from(self.priority))?;
726        // Exactly one timestamp tag: the `one-of` is a choice, not a set.
727        w.unsigned(Tag::Context(self.timestamp.tag()), self.timestamp.value())?;
728        // The data already carries its context-7 tag; `raw_element` checks that it is one
729        // well-formed element and that the tag is legal here before copying it.
730        w.raw_element(self.data)?;
731        w.end_container()
732    }
733
734    /// Reads a block whose opening `Structure` element the caller has just taken.
735    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
736        let mut path = None;
737        let mut number = None;
738        let mut priority = None;
739        let mut timestamp: Option<EventTimestamp> = None;
740        let mut data = None;
741        loop {
742            let start = reader.position();
743            let Some(element) = reader.next_element()? else {
744                bail!(TlvTruncated)
745            };
746            if element.value == Value::EndOfContainer {
747                break;
748            }
749            match element.tag.context() {
750                Some(0) => {
751                    let decoded = EventPath::decode(reader)?;
752                    set_once(&mut path, decoded)?;
753                }
754                Some(1) => set_once(&mut number, element.unsigned()?)?,
755                Some(2) => set_once(&mut priority, narrow8(element.unsigned()?)?)?,
756                // All four timestamp tags land in one slot, so a second one — of any form —
757                // is a duplicate. That is what makes "all other timestamp tags SHALL be
758                // omitted" enforceable rather than merely stated.
759                Some(3) => set_once(&mut timestamp, EventTimestamp::Epoch(element.unsigned()?))?,
760                Some(4) => set_once(&mut timestamp, EventTimestamp::System(element.unsigned()?))?,
761                Some(5) => {
762                    set_once(
763                        &mut timestamp,
764                        EventTimestamp::DeltaEpoch(element.unsigned()?),
765                    )?;
766                }
767                Some(6) => {
768                    set_once(
769                        &mut timestamp,
770                        EventTimestamp::DeltaSystem(element.unsigned()?),
771                    )?;
772                }
773                Some(7) => {
774                    reader.skip_value(&element)?;
775                    set_once(&mut data, reader.slice_from(start)?)?;
776                }
777                _ => reader.skip_value(&element)?,
778            }
779        }
780        Ok(Self {
781            path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
782            number: number.ok_or(Error::new(ErrorCode::TlvNotFound))?,
783            priority: priority.ok_or(Error::new(ErrorCode::TlvNotFound))?,
784            timestamp: timestamp.ok_or(Error::new(ErrorCode::TlvNotFound))?,
785            data: data.ok_or(Error::new(ErrorCode::TlvNotFound))?,
786        })
787    }
788}
789
790/// `EventReportIB` (§10.6.10).
791///
792/// As with [`AttributeReport`], the schema's two fields are a *choice*: a report carries the
793/// event, or a status saying why it could not.
794#[derive(Debug, Clone, Copy, PartialEq, Eq)]
795pub enum EventReport<'a> {
796    /// `EventStatus [0]`.
797    Status(EventStatus),
798    /// `EventData [1]`.
799    Data(EventData<'a>),
800}
801
802impl<'a> EventReport<'a> {
803    /// Writes the block as an anonymous `Structure`, for an array member.
804    pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
805        w.start_structure(Tag::Anonymous)?;
806        match self {
807            Self::Status(status) => status.encode(w, Tag::Context(0))?,
808            Self::Data(data) => data.encode(w, Tag::Context(1))?,
809        }
810        w.end_container()
811    }
812
813    /// Reads a block whose opening `Structure` element the caller has just taken.
814    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
815        let mut report = None;
816        loop {
817            let Some(element) = reader.next_element()? else {
818                bail!(TlvTruncated)
819            };
820            if element.value == Value::EndOfContainer {
821                break;
822            }
823            match element.tag.context() {
824                Some(0) => set_once(&mut report, Self::Status(EventStatus::decode(reader)?))?,
825                Some(1) => set_once(&mut report, Self::Data(EventData::decode(reader)?))?,
826                _ => reader.skip_value(&element)?,
827            }
828        }
829        report.ok_or(Error::new(ErrorCode::TlvNotFound))
830    }
831}