Skip to main content

matter_kit/im/
message.rs

1//! The ten interaction model messages (Core §10.7).
2//!
3//! # Arrays are iterated, not collected
4//!
5//! Every one of these messages carries at least one array whose length the *peer* chooses: a
6//! `ReadRequest` can name any number of paths, a `ReportData` can carry any number of
7//! attributes. Decoding those into a fixed-capacity array would mean picking a number, and
8//! any number picked is either too small for a legitimate client or too large for the
9//! smallest node this crate targets.
10//!
11//! So a decoded message holds the array's **encoded bytes** and hands out an iterator. The
12//! cost of parsing is paid per element, by the caller, as it walks — which is also what lets
13//! a server stop early when it runs out of room and answer `PATHS_EXHAUSTED` (§8.10.1)
14//! rather than having already allocated for paths it cannot serve.
15//!
16//! # `InteractionModelRevision` is not optional
17//!
18//! §10.2.2.2 requires the interaction model's ten messages to "include these tagged fields",
19//! and the field is context tag `0xFF`. It is written on every message here. On the
20//! way in it is accepted as absent, because §8.1.1 has revisions going back to 10 and a peer
21//! that omits it is old rather than malformed.
22
23use crate::error::{Error, ErrorCode, Result, bail};
24use crate::im::ib::{
25    AttributeData, AttributeReport, CommandData, DataVersionFilter, EventFilter, InvokeResponse,
26};
27use crate::im::path::{AttributePath, EventPath};
28use crate::im::status::Status;
29use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value, set_once};
30
31/// `InteractionModelRevision`, context tag `0xFF` on every action (§10.2.2.2).
32pub const REVISION_TAG: u8 = 0xFF;
33
34/// The revision this crate implements — 13, "Added WildcardFilterConfigurationVersion"
35/// (§8.1.1).
36pub const INTERACTION_MODEL_REVISION: u16 = 13;
37
38/// The protocol opcodes of §10.2.1, under `PROTOCOL_ID_INTERACTION_MODEL`.
39pub mod opcode {
40    /// `StatusResponseMessage`.
41    pub const STATUS_RESPONSE: u8 = 0x01;
42    /// `ReadRequestMessage`.
43    pub const READ_REQUEST: u8 = 0x02;
44    /// `SubscribeRequestMessage`.
45    pub const SUBSCRIBE_REQUEST: u8 = 0x03;
46    /// `SubscribeResponseMessage`.
47    pub const SUBSCRIBE_RESPONSE: u8 = 0x04;
48    /// `ReportDataMessage`.
49    pub const REPORT_DATA: u8 = 0x05;
50    /// `WriteRequestMessage`.
51    pub const WRITE_REQUEST: u8 = 0x06;
52    /// `WriteResponseMessage`.
53    pub const WRITE_RESPONSE: u8 = 0x07;
54    /// `InvokeRequestMessage`.
55    pub const INVOKE_REQUEST: u8 = 0x08;
56    /// `InvokeResponseMessage`.
57    pub const INVOKE_RESPONSE: u8 = 0x09;
58    /// `TimedRequestMessage`.
59    pub const TIMED_REQUEST: u8 = 0x0A;
60}
61
62/// Opens the anonymous outer structure every action message is.
63fn open(buf: &[u8]) -> Result<TlvReader<'_>> {
64    let mut reader = TlvReader::new(buf);
65    let Some(head) = reader.next_element()? else {
66        bail!(TlvTruncated)
67    };
68    if head.value.container() != Some(ContainerKind::Structure) || !head.tag.is_anonymous() {
69        bail!(TlvWrongType)
70    }
71    Ok(reader)
72}
73
74/// Captures an array's encoded bytes, for later iteration.
75fn take_array<'a>(
76    reader: &mut TlvReader<'a>,
77    element: &Element<'a>,
78    start: usize,
79) -> Result<&'a [u8]> {
80    if element.value.container() != Some(ContainerKind::Array) {
81        bail!(TlvWrongType)
82    }
83    reader.skip_value(element)?;
84    reader.slice_from(start)
85}
86
87/// Walks the members of a captured array, decoding one at a time.
88///
89/// Each member is an anonymous container, and **which** container depends on the block: the
90/// path blocks of §10.6.2, §10.6.8 and §10.6.11 are `List`s, and everything else is a
91/// `Structure`. That is not a detail to paper over by accepting either — a list and a
92/// structure have different tag rules, and a decoder that accepted a structure where the
93/// schema says list would accept paths no conforming peer sends and reject none.
94#[derive(Debug, Clone)]
95pub struct ArrayIter<'a, T> {
96    reader: TlvReader<'a>,
97    done: bool,
98    member: ContainerKind,
99    decode: fn(&mut TlvReader<'a>) -> Result<T>,
100}
101
102impl<'a, T> ArrayIter<'a, T> {
103    /// Starts an iterator over an array's encoded bytes, whose members are `member`.
104    pub(crate) fn new(
105        bytes: &'a [u8],
106        member: ContainerKind,
107        decode: fn(&mut TlvReader<'a>) -> Result<T>,
108    ) -> Result<Self> {
109        // The captured slice is the array element itself, tag included. Which tag is legal
110        // depends on where it sat, and it sat inside a structure.
111        let mut reader = TlvReader::new_in(bytes, ContainerKind::Structure);
112        let Some(head) = reader.next_element()? else {
113            bail!(TlvTruncated)
114        };
115        if head.value.container() != Some(ContainerKind::Array) {
116            bail!(TlvWrongType)
117        }
118        Ok(Self {
119            reader,
120            done: false,
121            member,
122            decode,
123        })
124    }
125}
126
127impl<'a, T> Iterator for ArrayIter<'a, T> {
128    type Item = Result<T>;
129
130    fn next(&mut self) -> Option<Self::Item> {
131        if self.done {
132            return None;
133        }
134        let element = match self.reader.next_element() {
135            Ok(Some(element)) => element,
136            Ok(None) => {
137                self.done = true;
138                return None;
139            }
140            Err(e) => {
141                self.done = true;
142                return Some(Err(e));
143            }
144        };
145        if element.value == Value::EndOfContainer {
146            self.done = true;
147            return None;
148        }
149        // An information block in an array is anonymous, and is the container its own
150        // schema names (§10.6).
151        if element.value.container() != Some(self.member) || !element.tag.is_anonymous() {
152            self.done = true;
153            return Some(Err(Error::new(ErrorCode::TlvWrongType)));
154        }
155        let out = (self.decode)(&mut self.reader);
156        if out.is_err() {
157            self.done = true;
158        }
159        Some(out)
160    }
161}
162
163/// Writes the `InteractionModelRevision` every action carries.
164fn write_revision(w: &mut TlvWriter<'_>) -> Result<()> {
165    w.unsigned(
166        Tag::Context(REVISION_TAG),
167        u64::from(INTERACTION_MODEL_REVISION),
168    )
169}
170
171// --- StatusResponse (§10.7.1) ----------------------------------------------------------------
172
173/// `StatusResponseMessage` — the one-field message that answers an action outright.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct StatusResponse {
176    /// `Status [0]`.
177    pub status: Status,
178    /// `InteractionModelRevision [0xFF]`, absent from a peer older than revision 10.
179    pub revision: Option<u16>,
180}
181
182impl StatusResponse {
183    /// A response carrying `status`.
184    #[must_use]
185    pub const fn new(status: Status) -> Self {
186        Self {
187            status,
188            revision: Some(INTERACTION_MODEL_REVISION),
189        }
190    }
191
192    /// Encodes the message.
193    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
194        let mut w = TlvWriter::new(buf);
195        w.start_structure(Tag::Anonymous)?;
196        w.unsigned(Tag::Context(0), u64::from(self.status.value()))?;
197        write_revision(&mut w)?;
198        w.end_container()?;
199        w.finish()
200    }
201
202    /// Decodes the message.
203    pub fn decode(buf: &[u8]) -> Result<Self> {
204        let mut reader = open(buf)?;
205        let mut status = None;
206        let mut revision = None;
207        loop {
208            let Some(element) = reader.next_element()? else {
209                bail!(TlvTruncated)
210            };
211            if element.value == Value::EndOfContainer {
212                break;
213            }
214            match element.tag.context() {
215                Some(0) => set_once(
216                    &mut status,
217                    Status::from_value(
218                        u8::try_from(element.unsigned()?)
219                            .map_err(|_| Error::new(ErrorCode::TlvOutOfRange))?,
220                    ),
221                )?,
222                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
223                _ => reader.skip_value(&element)?,
224            }
225        }
226        reader.finish()?;
227        Ok(Self {
228            status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
229            revision,
230        })
231    }
232}
233
234// --- ReadRequest (§10.7.2) -------------------------------------------------------------------
235
236/// `ReadRequestMessage`.
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub struct ReadRequest<'a> {
239    attribute_requests: Option<&'a [u8]>,
240    event_requests: Option<&'a [u8]>,
241    event_filters: Option<&'a [u8]>,
242    data_version_filters: Option<&'a [u8]>,
243    /// `FabricFiltered [3]` — whether fabric-scoped data is limited to the accessing
244    /// fabric (§8.4.2).
245    pub fabric_filtered: bool,
246    /// `InteractionModelRevision [0xFF]`.
247    pub revision: Option<u16>,
248}
249
250impl<'a> ReadRequest<'a> {
251    /// The attribute paths, decoded one at a time.
252    pub fn attribute_paths(&self) -> Result<Option<ArrayIter<'a, AttributePath>>> {
253        self.attribute_requests
254            .map(|bytes| ArrayIter::new(bytes, ContainerKind::List, path_from_list))
255            .transpose()
256    }
257
258    /// The event paths.
259    pub fn event_paths(&self) -> Result<Option<ArrayIter<'a, EventPath>>> {
260        self.event_requests
261            .map(|bytes| ArrayIter::new(bytes, ContainerKind::List, event_path_from_list))
262            .transpose()
263    }
264
265    /// The event filters, still encoded — what
266    /// [`InteractionContext::event_filters`](crate::im::InteractionContext) carries.
267    #[must_use]
268    pub const fn event_filters_raw(&self) -> Option<&'a [u8]> {
269        self.event_filters
270    }
271
272    /// The event filters.
273    pub fn event_filters(&self) -> Result<Option<ArrayIter<'a, EventFilter>>> {
274        self.event_filters
275            .map(|bytes| ArrayIter::new(bytes, ContainerKind::Structure, EventFilter::decode))
276            .transpose()
277    }
278
279    /// The data version filters, still encoded — what
280    /// [`InteractionContext::data_version_filters`](crate::im::InteractionContext) carries.
281    #[must_use]
282    pub const fn data_version_filters_raw(&self) -> Option<&'a [u8]> {
283        self.data_version_filters
284    }
285
286    /// The data version filters.
287    pub fn data_version_filters(&self) -> Result<Option<ArrayIter<'a, DataVersionFilter>>> {
288        self.data_version_filters
289            .map(|bytes| ArrayIter::new(bytes, ContainerKind::Structure, DataVersionFilter::decode))
290            .transpose()
291    }
292
293    /// Decodes the message.
294    pub fn decode(buf: &'a [u8]) -> Result<Self> {
295        let mut reader = open(buf)?;
296        let mut attribute_requests = None;
297        let mut event_requests = None;
298        let mut event_filters = None;
299        let mut data_version_filters = None;
300        let mut fabric_filtered = None;
301        let mut revision = None;
302
303        loop {
304            let start = reader.position();
305            let Some(element) = reader.next_element()? else {
306                bail!(TlvTruncated)
307            };
308            if element.value == Value::EndOfContainer {
309                break;
310            }
311            match element.tag.context() {
312                Some(0) => set_once(
313                    &mut attribute_requests,
314                    take_array(&mut reader, &element, start)?,
315                )?,
316                Some(1) => set_once(
317                    &mut event_requests,
318                    take_array(&mut reader, &element, start)?,
319                )?,
320                Some(2) => {
321                    set_once(
322                        &mut event_filters,
323                        take_array(&mut reader, &element, start)?,
324                    )?;
325                }
326                Some(3) => set_once(&mut fabric_filtered, element.bool()?)?,
327                Some(4) => set_once(
328                    &mut data_version_filters,
329                    take_array(&mut reader, &element, start)?,
330                )?,
331                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
332                _ => reader.skip_value(&element)?,
333            }
334        }
335        reader.finish()?;
336
337        Ok(Self {
338            attribute_requests,
339            event_requests,
340            event_filters,
341            data_version_filters,
342            // `FabricFiltered` is not optional in the schema; §8.4.2 makes `true` the safe
343            // reading, since it narrows what is returned rather than widening it.
344            fabric_filtered: fabric_filtered.ok_or(Error::new(ErrorCode::TlvNotFound))?,
345            revision,
346        })
347    }
348}
349
350/// Writes a `ReadRequestMessage` from paths a caller supplies.
351///
352/// Taking iterators rather than slices keeps the builder usable from a generator: a
353/// controller reading every endpoint does not have to materialise the path list first.
354pub fn encode_read_request<A, E>(
355    buf: &mut [u8],
356    attribute_paths: A,
357    event_paths: E,
358    fabric_filtered: bool,
359) -> Result<&[u8]>
360where
361    A: IntoIterator<Item = AttributePath>,
362    E: IntoIterator<Item = EventPath>,
363{
364    let mut w = TlvWriter::new(buf);
365    w.start_structure(Tag::Anonymous)?;
366
367    let mut attributes = attribute_paths.into_iter().peekable();
368    if attributes.peek().is_some() {
369        w.start_array(Tag::Context(0))?;
370        for path in attributes {
371            path.encode(&mut w, Tag::Anonymous)?;
372        }
373        w.end_container()?;
374    }
375
376    let mut events = event_paths.into_iter().peekable();
377    if events.peek().is_some() {
378        w.start_array(Tag::Context(1))?;
379        for path in events {
380            path.encode(&mut w, Tag::Anonymous)?;
381        }
382        w.end_container()?;
383    }
384
385    w.bool(Tag::Context(3), fabric_filtered)?;
386    write_revision(&mut w)?;
387    w.end_container()?;
388    w.finish()
389}
390
391/// Writes a `SubscribeRequestMessage` (§10.7.5).
392///
393/// The client's half of §8.5. The two intervals are a *request*: §8.5.3.2 lets the server
394/// answer with a `MaxInterval` of its own inside the `SubscribeResponse`, and a client that
395/// assumed its ceiling had been honoured would call a live subscription dead.
396///
397/// `keep_subscriptions` is the one field with teeth. §8.5.2.3: "If KeepSubscriptions is FALSE,
398/// all existing or pending subscriptions on the publisher for this subscriber SHALL be
399/// terminated." — which is what a controller wants after a restart, and exactly what it does
400/// not want when adding a second subscription to a node it is already watching.
401pub fn encode_subscribe_request<A, E>(
402    buf: &mut [u8],
403    attribute_paths: A,
404    event_paths: E,
405    min_interval_floor_s: u16,
406    max_interval_ceiling_s: u16,
407    keep_subscriptions: bool,
408    fabric_filtered: bool,
409) -> Result<&[u8]>
410where
411    A: IntoIterator<Item = AttributePath>,
412    E: IntoIterator<Item = EventPath>,
413{
414    let mut w = TlvWriter::new(buf);
415    w.start_structure(Tag::Anonymous)?;
416    w.bool(Tag::Context(0), keep_subscriptions)?;
417    w.unsigned(Tag::Context(1), u64::from(min_interval_floor_s))?;
418    w.unsigned(Tag::Context(2), u64::from(max_interval_ceiling_s))?;
419
420    let mut attributes = attribute_paths.into_iter().peekable();
421    if attributes.peek().is_some() {
422        w.start_array(Tag::Context(3))?;
423        for path in attributes {
424            path.encode(&mut w, Tag::Anonymous)?;
425        }
426        w.end_container()?;
427    }
428
429    let mut events = event_paths.into_iter().peekable();
430    if events.peek().is_some() {
431        w.start_array(Tag::Context(4))?;
432        for path in events {
433            path.encode(&mut w, Tag::Anonymous)?;
434        }
435        w.end_container()?;
436    }
437
438    w.bool(Tag::Context(7), fabric_filtered)?;
439    write_revision(&mut w)?;
440    w.end_container()?;
441    w.finish()
442}
443
444// --- ReportData (§10.7.3) --------------------------------------------------------------------
445
446/// `ReportDataMessage`.
447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
448pub struct ReportData<'a> {
449    /// `SubscriptionID [0]`, present when this report belongs to a subscription.
450    pub subscription_id: Option<u32>,
451    attribute_reports: Option<&'a [u8]>,
452    event_reports: Option<&'a [u8]>,
453    /// `MoreChunkedMessages [3]` — another message of this same action follows (§10.2.3).
454    pub more_chunked_messages: bool,
455    /// `SuppressResponse [4]` — the receiver need not send a `StatusResponse`.
456    pub suppress_response: bool,
457    /// `InteractionModelRevision [0xFF]`.
458    pub revision: Option<u16>,
459}
460
461impl<'a> ReportData<'a> {
462    /// The attribute reports, decoded one at a time.
463    pub fn attribute_reports(&self) -> Result<Option<ArrayIter<'a, AttributeReport<'a>>>> {
464        self.attribute_reports
465            .map(|bytes| ArrayIter::new(bytes, ContainerKind::Structure, AttributeReport::decode))
466            .transpose()
467    }
468
469    /// The event reports, decoded one at a time.
470    pub fn event_reports(&self) -> Result<Option<ArrayIter<'a, crate::im::EventReport<'a>>>> {
471        self.event_reports
472            .map(|bytes| {
473                ArrayIter::new(
474                    bytes,
475                    ContainerKind::Structure,
476                    crate::im::EventReport::decode,
477                )
478            })
479            .transpose()
480    }
481
482    /// The raw bytes of the attribute reports array, for a caller that forwards or
483    /// accumulates them without looking — a bridge relaying a report, or
484    /// [`ReportAssembler`](crate::im::ReportAssembler) putting a chunked one back together.
485    ///
486    /// The slice is the whole array *element*, tag and end-of-container included, which is
487    /// why two chunks cannot simply be concatenated: that would make two arrays, not one.
488    #[must_use]
489    pub const fn attribute_reports_bytes(&self) -> Option<&'a [u8]> {
490        self.attribute_reports
491    }
492
493    /// The raw bytes of the event reports array, for a caller that forwards them without
494    /// looking — a bridge relaying a report for a cluster it has never heard of.
495    #[must_use]
496    pub const fn event_reports_bytes(&self) -> Option<&'a [u8]> {
497        self.event_reports
498    }
499
500    /// Decodes the message.
501    pub fn decode(buf: &'a [u8]) -> Result<Self> {
502        let mut reader = open(buf)?;
503        let mut subscription_id = None;
504        let mut attribute_reports = None;
505        let mut event_reports = None;
506        let mut more_chunked_messages = None;
507        let mut suppress_response = None;
508        let mut revision = None;
509
510        loop {
511            let start = reader.position();
512            let Some(element) = reader.next_element()? else {
513                bail!(TlvTruncated)
514            };
515            if element.value == Value::EndOfContainer {
516                break;
517            }
518            match element.tag.context() {
519                Some(0) => set_once(&mut subscription_id, narrow32(element.unsigned()?)?)?,
520                Some(1) => set_once(
521                    &mut attribute_reports,
522                    take_array(&mut reader, &element, start)?,
523                )?,
524                Some(2) => {
525                    set_once(
526                        &mut event_reports,
527                        take_array(&mut reader, &element, start)?,
528                    )?;
529                }
530                Some(3) => set_once(&mut more_chunked_messages, element.bool()?)?,
531                Some(4) => set_once(&mut suppress_response, element.bool()?)?,
532                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
533                _ => reader.skip_value(&element)?,
534            }
535        }
536        reader.finish()?;
537
538        Ok(Self {
539            subscription_id,
540            attribute_reports,
541            event_reports,
542            // Both booleans are "can be omitted" / "omit if false" in §10.7.3.
543            more_chunked_messages: more_chunked_messages.unwrap_or(false),
544            suppress_response: suppress_response.unwrap_or(false),
545            revision,
546        })
547    }
548}
549
550/// Writes a `ReportDataMessage`.
551pub fn encode_report_data<'b, R>(
552    buf: &'b mut [u8],
553    subscription_id: Option<u32>,
554    reports: R,
555    more_chunked_messages: bool,
556    suppress_response: bool,
557) -> Result<&'b [u8]>
558where
559    R: IntoIterator<Item = AttributeReport<'b>>,
560{
561    let mut w = TlvWriter::new(buf);
562    w.start_structure(Tag::Anonymous)?;
563    if let Some(id) = subscription_id {
564        w.unsigned(Tag::Context(0), u64::from(id))?;
565    }
566    let mut reports = reports.into_iter().peekable();
567    if reports.peek().is_some() {
568        w.start_array(Tag::Context(1))?;
569        for report in reports {
570            report.encode(&mut w)?;
571        }
572        w.end_container()?;
573    }
574    // "Can be omitted" / "Omit if 'false'" — writing the default would be legal but is
575    // wasted octets in a message whose size drives chunking.
576    if more_chunked_messages {
577        w.bool(Tag::Context(3), true)?;
578    }
579    if suppress_response {
580        w.bool(Tag::Context(4), true)?;
581    }
582    write_revision(&mut w)?;
583    w.end_container()?;
584    w.finish()
585}
586
587// --- WriteRequest (§10.7.6) and WriteResponse (§10.7.7) --------------------------------------
588
589/// `WriteRequestMessage`.
590#[derive(Debug, Clone, Copy, PartialEq, Eq)]
591pub struct WriteRequest<'a> {
592    /// `SuppressResponse [0]`.
593    pub suppress_response: bool,
594    /// `TimedRequest [1]` — this write is inside a Timed interaction (§8.7).
595    pub timed_request: bool,
596    write_requests: &'a [u8],
597    /// `MoreChunkedMessages [3]`.
598    pub more_chunked_messages: bool,
599    /// `InteractionModelRevision [0xFF]`.
600    pub revision: Option<u16>,
601}
602
603impl<'a> WriteRequest<'a> {
604    /// The attribute data to write, decoded one at a time.
605    pub fn writes(&self) -> Result<ArrayIter<'a, AttributeData<'a>>> {
606        ArrayIter::new(
607            self.write_requests,
608            ContainerKind::Structure,
609            AttributeData::decode,
610        )
611    }
612
613    /// Decodes the message.
614    pub fn decode(buf: &'a [u8]) -> Result<Self> {
615        let mut reader = open(buf)?;
616        let mut suppress_response = None;
617        let mut timed_request = None;
618        let mut write_requests = None;
619        let mut more_chunked_messages = None;
620        let mut revision = None;
621
622        loop {
623            let start = reader.position();
624            let Some(element) = reader.next_element()? else {
625                bail!(TlvTruncated)
626            };
627            if element.value == Value::EndOfContainer {
628                break;
629            }
630            match element.tag.context() {
631                Some(0) => set_once(&mut suppress_response, element.bool()?)?,
632                Some(1) => set_once(&mut timed_request, element.bool()?)?,
633                Some(2) => set_once(
634                    &mut write_requests,
635                    take_array(&mut reader, &element, start)?,
636                )?,
637                Some(3) => set_once(&mut more_chunked_messages, element.bool()?)?,
638                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
639                _ => reader.skip_value(&element)?,
640            }
641        }
642        reader.finish()?;
643
644        Ok(Self {
645            suppress_response: suppress_response.unwrap_or(false),
646            timed_request: timed_request.unwrap_or(false),
647            // `WriteRequests` is the only mandatory field: a write with nothing to write is
648            // not a write.
649            write_requests: write_requests.ok_or(Error::new(ErrorCode::TlvNotFound))?,
650            more_chunked_messages: more_chunked_messages.unwrap_or(false),
651            revision,
652        })
653    }
654}
655
656/// Writes a `WriteRequestMessage`.
657pub fn encode_write_request<'b, W>(
658    buf: &'b mut [u8],
659    writes: W,
660    timed_request: bool,
661    suppress_response: bool,
662) -> Result<&'b [u8]>
663where
664    W: IntoIterator<Item = AttributeData<'b>>,
665{
666    let mut w = TlvWriter::new(buf);
667    w.start_structure(Tag::Anonymous)?;
668    if suppress_response {
669        w.bool(Tag::Context(0), true)?;
670    }
671    w.bool(Tag::Context(1), timed_request)?;
672    w.start_array(Tag::Context(2))?;
673    for data in writes {
674        // An AttributeDataIB inside an array is an anonymous structure.
675        data.encode(&mut w, Tag::Anonymous)?;
676    }
677    w.end_container()?;
678    write_revision(&mut w)?;
679    w.end_container()?;
680    w.finish()
681}
682
683/// `WriteResponseMessage`.
684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685pub struct WriteResponse<'a> {
686    write_responses: &'a [u8],
687    /// `InteractionModelRevision [0xFF]`.
688    pub revision: Option<u16>,
689}
690
691impl<'a> WriteResponse<'a> {
692    /// The per-path outcomes, decoded one at a time.
693    pub fn statuses(&self) -> Result<ArrayIter<'a, crate::im::ib::AttributeStatus>> {
694        ArrayIter::new(
695            self.write_responses,
696            ContainerKind::Structure,
697            crate::im::ib::AttributeStatus::decode,
698        )
699    }
700
701    /// Decodes the message.
702    pub fn decode(buf: &'a [u8]) -> Result<Self> {
703        let mut reader = open(buf)?;
704        let mut write_responses = None;
705        let mut revision = None;
706        loop {
707            let start = reader.position();
708            let Some(element) = reader.next_element()? else {
709                bail!(TlvTruncated)
710            };
711            if element.value == Value::EndOfContainer {
712                break;
713            }
714            match element.tag.context() {
715                Some(0) => set_once(
716                    &mut write_responses,
717                    take_array(&mut reader, &element, start)?,
718                )?,
719                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
720                _ => reader.skip_value(&element)?,
721            }
722        }
723        reader.finish()?;
724        Ok(Self {
725            write_responses: write_responses.ok_or(Error::new(ErrorCode::TlvNotFound))?,
726            revision,
727        })
728    }
729}
730
731/// Writes a `WriteResponseMessage`.
732pub fn encode_write_response<S>(buf: &mut [u8], statuses: S) -> Result<&[u8]>
733where
734    S: IntoIterator<Item = crate::im::ib::AttributeStatus>,
735{
736    let mut w = TlvWriter::new(buf);
737    w.start_structure(Tag::Anonymous)?;
738    w.start_array(Tag::Context(0))?;
739    for status in statuses {
740        status.encode(&mut w, Tag::Anonymous)?;
741    }
742    w.end_container()?;
743    write_revision(&mut w)?;
744    w.end_container()?;
745    w.finish()
746}
747
748// --- InvokeRequest (§10.7.9) and InvokeResponse (§10.7.10) -----------------------------------
749
750/// `InvokeRequestMessage`.
751#[derive(Debug, Clone, Copy, PartialEq, Eq)]
752pub struct InvokeRequest<'a> {
753    /// `SuppressResponse [0]`.
754    pub suppress_response: bool,
755    /// `TimedRequest [1]`.
756    pub timed_request: bool,
757    invoke_requests: &'a [u8],
758    /// `InteractionModelRevision [0xFF]`.
759    pub revision: Option<u16>,
760}
761
762impl<'a> InvokeRequest<'a> {
763    /// The commands to invoke, decoded one at a time.
764    ///
765    /// More than one is permitted from interaction model revision 12 (§8.1.1: "added support
766    /// for multiple CommandDataIB in one Invoke Request"), and each then carries a
767    /// `CommandRef` so the responses can be matched up.
768    pub fn commands(&self) -> Result<ArrayIter<'a, CommandData<'a>>> {
769        ArrayIter::new(
770            self.invoke_requests,
771            ContainerKind::Structure,
772            CommandData::decode,
773        )
774    }
775
776    /// Decodes the message.
777    pub fn decode(buf: &'a [u8]) -> Result<Self> {
778        let mut reader = open(buf)?;
779        let mut suppress_response = None;
780        let mut timed_request = None;
781        let mut invoke_requests = None;
782        let mut revision = None;
783
784        loop {
785            let start = reader.position();
786            let Some(element) = reader.next_element()? else {
787                bail!(TlvTruncated)
788            };
789            if element.value == Value::EndOfContainer {
790                break;
791            }
792            match element.tag.context() {
793                Some(0) => set_once(&mut suppress_response, element.bool()?)?,
794                Some(1) => set_once(&mut timed_request, element.bool()?)?,
795                Some(2) => set_once(
796                    &mut invoke_requests,
797                    take_array(&mut reader, &element, start)?,
798                )?,
799                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
800                _ => reader.skip_value(&element)?,
801            }
802        }
803        reader.finish()?;
804
805        Ok(Self {
806            suppress_response: suppress_response.unwrap_or(false),
807            timed_request: timed_request.unwrap_or(false),
808            invoke_requests: invoke_requests.ok_or(Error::new(ErrorCode::TlvNotFound))?,
809            revision,
810        })
811    }
812}
813
814/// Writes an `InvokeRequestMessage`.
815pub fn encode_invoke_request<'b, C>(
816    buf: &'b mut [u8],
817    commands: C,
818    timed_request: bool,
819    suppress_response: bool,
820) -> Result<&'b [u8]>
821where
822    C: IntoIterator<Item = CommandData<'b>>,
823{
824    let mut w = TlvWriter::new(buf);
825    w.start_structure(Tag::Anonymous)?;
826    w.bool(Tag::Context(0), suppress_response)?;
827    w.bool(Tag::Context(1), timed_request)?;
828    w.start_array(Tag::Context(2))?;
829    for command in commands {
830        command.encode(&mut w)?;
831    }
832    w.end_container()?;
833    write_revision(&mut w)?;
834    w.end_container()?;
835    w.finish()
836}
837
838/// `InvokeResponseMessage`.
839#[derive(Debug, Clone, Copy, PartialEq, Eq)]
840pub struct InvokeResponseMessage<'a> {
841    /// `SuppressResponse [0]`.
842    pub suppress_response: bool,
843    invoke_responses: &'a [u8],
844    /// `MoreChunkedMessages [2]`.
845    pub more_chunked_messages: bool,
846    /// `InteractionModelRevision [0xFF]`.
847    pub revision: Option<u16>,
848}
849
850impl<'a> InvokeResponseMessage<'a> {
851    /// The per-command outcomes, decoded one at a time.
852    pub fn responses(&self) -> Result<ArrayIter<'a, InvokeResponse<'a>>> {
853        ArrayIter::new(
854            self.invoke_responses,
855            ContainerKind::Structure,
856            InvokeResponse::decode,
857        )
858    }
859
860    /// Decodes the message.
861    pub fn decode(buf: &'a [u8]) -> Result<Self> {
862        let mut reader = open(buf)?;
863        let mut suppress_response = None;
864        let mut invoke_responses = None;
865        let mut more_chunked_messages = None;
866        let mut revision = None;
867
868        loop {
869            let start = reader.position();
870            let Some(element) = reader.next_element()? else {
871                bail!(TlvTruncated)
872            };
873            if element.value == Value::EndOfContainer {
874                break;
875            }
876            match element.tag.context() {
877                Some(0) => set_once(&mut suppress_response, element.bool()?)?,
878                Some(1) => set_once(
879                    &mut invoke_responses,
880                    take_array(&mut reader, &element, start)?,
881                )?,
882                Some(2) => set_once(&mut more_chunked_messages, element.bool()?)?,
883                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
884                _ => reader.skip_value(&element)?,
885            }
886        }
887        reader.finish()?;
888
889        Ok(Self {
890            suppress_response: suppress_response.unwrap_or(false),
891            invoke_responses: invoke_responses.ok_or(Error::new(ErrorCode::TlvNotFound))?,
892            more_chunked_messages: more_chunked_messages.unwrap_or(false),
893            revision,
894        })
895    }
896}
897
898/// Writes an `InvokeResponseMessage`.
899pub fn encode_invoke_response<'b, R>(
900    buf: &'b mut [u8],
901    responses: R,
902    suppress_response: bool,
903) -> Result<&'b [u8]>
904where
905    R: IntoIterator<Item = InvokeResponse<'b>>,
906{
907    let mut w = TlvWriter::new(buf);
908    w.start_structure(Tag::Anonymous)?;
909    w.bool(Tag::Context(0), suppress_response)?;
910    w.start_array(Tag::Context(1))?;
911    for response in responses {
912        response.encode(&mut w)?;
913    }
914    w.end_container()?;
915    write_revision(&mut w)?;
916    w.end_container()?;
917    w.finish()
918}
919
920// --- TimedRequest (§10.7.8) ------------------------------------------------------------------
921
922/// `TimedRequestMessage` — opens a Timed interaction (§8.7).
923#[derive(Debug, Clone, Copy, PartialEq, Eq)]
924pub struct TimedRequest {
925    /// `Timeout [0]`, in milliseconds.
926    pub timeout_ms: u16,
927    /// `InteractionModelRevision [0xFF]`.
928    pub revision: Option<u16>,
929}
930
931impl TimedRequest {
932    /// A request with this timeout.
933    #[must_use]
934    pub const fn new(timeout_ms: u16) -> Self {
935        Self {
936            timeout_ms,
937            revision: Some(INTERACTION_MODEL_REVISION),
938        }
939    }
940
941    /// Encodes the message.
942    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
943        let mut w = TlvWriter::new(buf);
944        w.start_structure(Tag::Anonymous)?;
945        w.unsigned(Tag::Context(0), u64::from(self.timeout_ms))?;
946        write_revision(&mut w)?;
947        w.end_container()?;
948        w.finish()
949    }
950
951    /// Decodes the message.
952    pub fn decode(buf: &[u8]) -> Result<Self> {
953        let mut reader = open(buf)?;
954        let mut timeout_ms = None;
955        let mut revision = None;
956        loop {
957            let Some(element) = reader.next_element()? else {
958                bail!(TlvTruncated)
959            };
960            if element.value == Value::EndOfContainer {
961                break;
962            }
963            match element.tag.context() {
964                Some(0) => set_once(&mut timeout_ms, narrow16(element.unsigned()?)?)?,
965                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
966                _ => reader.skip_value(&element)?,
967            }
968        }
969        reader.finish()?;
970        Ok(Self {
971            timeout_ms: timeout_ms.ok_or(Error::new(ErrorCode::TlvNotFound))?,
972            revision,
973        })
974    }
975}
976
977// --- SubscribeRequest (§10.7.4) and SubscribeResponse (§10.7.5) ------------------------------
978
979/// `SubscribeRequestMessage`.
980#[derive(Debug, Clone, Copy, PartialEq, Eq)]
981pub struct SubscribeRequest<'a> {
982    /// `KeepSubscriptions [0]` — leave the client's existing subscriptions in place.
983    pub keep_subscriptions: bool,
984    /// `MinIntervalFloor [1]`, in seconds — the shortest gap between reports.
985    pub min_interval_floor_s: u16,
986    /// `MaxIntervalCeiling [2]`, in seconds — the longest the server may stay silent.
987    pub max_interval_ceiling_s: u16,
988    attribute_requests: Option<&'a [u8]>,
989    event_requests: Option<&'a [u8]>,
990    event_filters: Option<&'a [u8]>,
991    data_version_filters: Option<&'a [u8]>,
992    /// `FabricFiltered [7]`.
993    pub fabric_filtered: bool,
994    /// `InteractionModelRevision [0xFF]`.
995    pub revision: Option<u16>,
996}
997
998impl<'a> SubscribeRequest<'a> {
999    /// The attribute paths, decoded one at a time.
1000    pub fn attribute_paths(&self) -> Result<Option<ArrayIter<'a, AttributePath>>> {
1001        self.attribute_requests
1002            .map(|bytes| ArrayIter::new(bytes, ContainerKind::List, path_from_list))
1003            .transpose()
1004    }
1005
1006    /// The event paths.
1007    pub fn event_paths(&self) -> Result<Option<ArrayIter<'a, EventPath>>> {
1008        self.event_requests
1009            .map(|bytes| ArrayIter::new(bytes, ContainerKind::List, event_path_from_list))
1010            .transpose()
1011    }
1012
1013    /// The data version filters, still encoded — what
1014    /// [`InteractionContext::data_version_filters`](crate::im::InteractionContext) carries.
1015    #[must_use]
1016    pub const fn data_version_filters_raw(&self) -> Option<&'a [u8]> {
1017        self.data_version_filters
1018    }
1019
1020    /// The data version filters.
1021    pub fn data_version_filters(&self) -> Result<Option<ArrayIter<'a, DataVersionFilter>>> {
1022        self.data_version_filters
1023            .map(|bytes| ArrayIter::new(bytes, ContainerKind::Structure, DataVersionFilter::decode))
1024            .transpose()
1025    }
1026
1027    /// The event filters, still encoded — what
1028    /// [`InteractionContext::event_filters`](crate::im::InteractionContext) carries.
1029    #[must_use]
1030    pub const fn event_filters_raw(&self) -> Option<&'a [u8]> {
1031        self.event_filters
1032    }
1033
1034    /// The event filters.
1035    pub fn event_filters(&self) -> Result<Option<ArrayIter<'a, EventFilter>>> {
1036        self.event_filters
1037            .map(|bytes| ArrayIter::new(bytes, ContainerKind::Structure, EventFilter::decode))
1038            .transpose()
1039    }
1040
1041    /// Decodes the message.
1042    pub fn decode(buf: &'a [u8]) -> Result<Self> {
1043        let mut reader = open(buf)?;
1044        let mut keep_subscriptions = None;
1045        let mut min_interval_floor_s = None;
1046        let mut max_interval_ceiling_s = None;
1047        let mut attribute_requests = None;
1048        let mut event_requests = None;
1049        let mut event_filters = None;
1050        let mut data_version_filters = None;
1051        let mut fabric_filtered = None;
1052        let mut revision = None;
1053
1054        loop {
1055            let start = reader.position();
1056            let Some(element) = reader.next_element()? else {
1057                bail!(TlvTruncated)
1058            };
1059            if element.value == Value::EndOfContainer {
1060                break;
1061            }
1062            match element.tag.context() {
1063                Some(0) => set_once(&mut keep_subscriptions, element.bool()?)?,
1064                Some(1) => set_once(&mut min_interval_floor_s, narrow16(element.unsigned()?)?)?,
1065                Some(2) => set_once(&mut max_interval_ceiling_s, narrow16(element.unsigned()?)?)?,
1066                Some(3) => set_once(
1067                    &mut attribute_requests,
1068                    take_array(&mut reader, &element, start)?,
1069                )?,
1070                Some(4) => set_once(
1071                    &mut event_requests,
1072                    take_array(&mut reader, &element, start)?,
1073                )?,
1074                Some(5) => {
1075                    set_once(
1076                        &mut event_filters,
1077                        take_array(&mut reader, &element, start)?,
1078                    )?;
1079                }
1080                Some(7) => set_once(&mut fabric_filtered, element.bool()?)?,
1081                Some(8) => set_once(
1082                    &mut data_version_filters,
1083                    take_array(&mut reader, &element, start)?,
1084                )?,
1085                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
1086                _ => reader.skip_value(&element)?,
1087            }
1088        }
1089        reader.finish()?;
1090
1091        Ok(Self {
1092            keep_subscriptions: keep_subscriptions.unwrap_or(false),
1093            min_interval_floor_s: min_interval_floor_s.ok_or(Error::new(ErrorCode::TlvNotFound))?,
1094            max_interval_ceiling_s: max_interval_ceiling_s
1095                .ok_or(Error::new(ErrorCode::TlvNotFound))?,
1096            attribute_requests,
1097            event_requests,
1098            event_filters,
1099            data_version_filters,
1100            fabric_filtered: fabric_filtered.ok_or(Error::new(ErrorCode::TlvNotFound))?,
1101            revision,
1102        })
1103    }
1104}
1105
1106/// `SubscribeResponseMessage`.
1107///
1108/// Note the gap: the schema has `SubscriptionID [0]` and `MaxInterval [2]`, with no tag 1.
1109/// That is the specification's, not a transcription slip — tag 1 held a `MinInterval` that
1110/// was removed.
1111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1112pub struct SubscribeResponse {
1113    /// `SubscriptionID [0]`.
1114    pub subscription_id: u32,
1115    /// `MaxInterval [2]`, in seconds — what the server actually settled on.
1116    pub max_interval_s: u16,
1117    /// `InteractionModelRevision [0xFF]`.
1118    pub revision: Option<u16>,
1119}
1120
1121impl SubscribeResponse {
1122    /// A response granting a subscription.
1123    #[must_use]
1124    pub const fn new(subscription_id: u32, max_interval_s: u16) -> Self {
1125        Self {
1126            subscription_id,
1127            max_interval_s,
1128            revision: Some(INTERACTION_MODEL_REVISION),
1129        }
1130    }
1131
1132    /// Encodes the message.
1133    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
1134        let mut w = TlvWriter::new(buf);
1135        w.start_structure(Tag::Anonymous)?;
1136        w.unsigned(Tag::Context(0), u64::from(self.subscription_id))?;
1137        w.unsigned(Tag::Context(2), u64::from(self.max_interval_s))?;
1138        write_revision(&mut w)?;
1139        w.end_container()?;
1140        w.finish()
1141    }
1142
1143    /// Decodes the message.
1144    pub fn decode(buf: &[u8]) -> Result<Self> {
1145        let mut reader = open(buf)?;
1146        let mut subscription_id = None;
1147        let mut max_interval_s = None;
1148        let mut revision = None;
1149        loop {
1150            let Some(element) = reader.next_element()? else {
1151                bail!(TlvTruncated)
1152            };
1153            if element.value == Value::EndOfContainer {
1154                break;
1155            }
1156            match element.tag.context() {
1157                Some(0) => set_once(&mut subscription_id, narrow32(element.unsigned()?)?)?,
1158                Some(2) => set_once(&mut max_interval_s, narrow16(element.unsigned()?)?)?,
1159                Some(REVISION_TAG) => set_once(&mut revision, narrow16(element.unsigned()?)?)?,
1160                _ => reader.skip_value(&element)?,
1161            }
1162        }
1163        reader.finish()?;
1164        Ok(Self {
1165            subscription_id: subscription_id.ok_or(Error::new(ErrorCode::TlvNotFound))?,
1166            max_interval_s: max_interval_s.ok_or(Error::new(ErrorCode::TlvNotFound))?,
1167            revision,
1168        })
1169    }
1170}
1171
1172fn path_from_list(reader: &mut TlvReader<'_>) -> Result<AttributePath> {
1173    AttributePath::decode(reader)
1174}
1175
1176fn event_path_from_list(reader: &mut TlvReader<'_>) -> Result<EventPath> {
1177    EventPath::decode(reader)
1178}
1179
1180fn narrow16(value: u64) -> Result<u16> {
1181    u16::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
1182}
1183
1184fn narrow32(value: u64) -> Result<u32> {
1185    u32::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
1186}