Skip to main content

matter_kit/dm/
spec.rs

1//! What the specification says a cluster is (Core §7.3, and the Application Cluster library).
2//!
3//! [`meta`](crate::dm::meta) describes what *this device serves*: the attributes its handler
4//! answers, the commands it accepts. This module describes what the **specification defines**:
5//! every element the cluster has, its conformance, its access, its qualities — the whole
6//! table, whether or not any device implements all of it.
7//!
8//! The two are different things and the gap between them is where certification failures
9//! live. A device whose `ClusterDescriptor` omits a mandatory attribute, or serves one its
10//! feature map disallows, is conformant-looking and wrong; nothing in its own test suite
11//! finds it, because its own tests only exercise what it does implement.
12//! [`Cluster::validate`] is that check, and it is the reason these tables are generated from
13//! the CSA XML rather than transcribed.
14//!
15//! Everything here is `&'static` const data. A device that names one cluster links one
16//! cluster's table; the rest are dropped by the linker exactly as any other unreferenced
17//! const is.
18
19use crate::dm::conformance::{Conform, Conformance, Supports};
20use crate::dm::meta::{
21    AttributeDescriptor, ClusterDescriptor, CommandDescriptor, EventDescriptor, EventPriority,
22    Reporting,
23};
24use crate::dm::{Access, AttributeQualities};
25use crate::im::{AttributeId, ClusterId, CommandId, EventId};
26
27/// One bit of a cluster's `FeatureMap` (§7.13.2).
28#[derive(Debug, Clone, Copy)]
29pub struct Feature {
30    /// Which bit.
31    pub bit: u8,
32    /// The short code the conformance expressions name it by — "LT", "OFFONLY".
33    pub code: &'static str,
34    /// The readable name — "Lighting".
35    pub name: &'static str,
36    /// When the feature itself may be claimed. Features have conformance too: On/Off's
37    /// `Lighting` is optional *only when* `OffOnly` is absent.
38    pub conform: Conform,
39}
40
41/// One attribute, as the specification defines it.
42#[derive(Debug, Clone, Copy)]
43pub struct Attribute {
44    /// Its id.
45    pub id: AttributeId,
46    /// Its name in the specification — "StartUpOnOff".
47    pub name: &'static str,
48    /// The specification's type name, verbatim — "uint16", "StartUpOnOffEnum",
49    /// `list[TargetStruct]`. Kept as text because what a Rust program does with it is the
50    /// handler's business; the generated Rust type lives in the cluster's own module.
51    ///
52    /// **Empty** for the handful of attributes the specification lists with no type at all —
53    /// General Diagnostics' `DoNotUse`, Door Lock's `SecurityLevel`. Every one of them is
54    /// deprecated or disallowed: there is nothing to say what they were, and the conformance
55    /// already says they must not be there.
56    pub kind: &'static str,
57    /// §7.6's access column.
58    pub access: Access,
59    /// §7.12's qualities, minus the reporting policy.
60    pub qualities: AttributeQualities,
61    /// Whether and how changes are reported.
62    pub reporting: Reporting,
63    /// When the attribute may or must be present.
64    pub conform: Conform,
65}
66
67/// One command.
68#[derive(Debug, Clone, Copy)]
69pub struct Command {
70    /// Its id.
71    pub id: CommandId,
72    /// Its name in the specification — "OffWithEffect".
73    pub name: &'static str,
74    /// Whether the client sends it to the server, or the reverse. A response command is
75    /// `to_client`, and a server's *accepted* command list must not contain one.
76    pub to_server: bool,
77    /// The command that answers it, if the answer is not a bare status.
78    pub response: Option<CommandId>,
79    /// The privilege an invoke needs, and whether it must be Timed.
80    pub access: Access,
81    /// When the command may or must be present.
82    pub conform: Conform,
83}
84
85/// One event.
86#[derive(Debug, Clone, Copy)]
87pub struct Event {
88    /// Its id.
89    pub id: EventId,
90    /// Its name in the specification — "StateChanged".
91    pub name: &'static str,
92    /// Which ring of the event store it goes in (§7.14.2).
93    pub priority: EventPriority,
94    /// The privilege a read needs.
95    pub access: Access,
96    /// When the event may or must be present.
97    pub conform: Conform,
98}
99
100/// A whole cluster, as the specification defines it.
101#[derive(Debug, Clone, Copy)]
102pub struct Cluster {
103    /// Its id.
104    pub id: ClusterId,
105    /// The readable name — "On/Off".
106    pub name: &'static str,
107    /// The highest revision in the cluster's revision history, which is what
108    /// `ClusterRevision` must report (§7.13.1).
109    pub revision: u16,
110    /// The PICS code, for the certification declaration a test harness reads.
111    pub pics: &'static str,
112    /// Whether this cluster is a base or is derived from another — the Mode Base family and
113    /// the Resource Monitoring clusters are one element set behind many ids.
114    pub derived_from: Option<&'static str>,
115    /// Its `FeatureMap` bits.
116    pub features: &'static [Feature],
117    /// Every attribute it defines, sorted by id.
118    pub attributes: &'static [Attribute],
119    /// Every command, accepted and generated, sorted by id.
120    pub commands: &'static [Command],
121    /// Every event, sorted by id.
122    pub events: &'static [Event],
123}
124
125/// Something a device's configuration got wrong.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum Defect {
128    /// A mandatory element the device does not serve.
129    Missing(Element),
130    /// An element the device serves that its feature map disallows.
131    Disallowed(Element),
132    /// A feature bit the device claims that this cluster revision does not define.
133    UnknownFeature(u8),
134    /// The descriptor's `ClusterRevision` is not the one the specification defines.
135    WrongRevision {
136        /// What the device reports.
137        found: u16,
138        /// What the specification says.
139        expected: u16,
140    },
141    /// A response command in the accepted list, which is a command the server sends.
142    ResponseAccepted(CommandId),
143}
144
145/// Which element a [`Defect`] is about.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Element {
148    /// An attribute.
149    Attribute(AttributeId),
150    /// A command.
151    Command(CommandId),
152    /// An event.
153    Event(EventId),
154}
155
156/// A device's cluster instance, seen as a set of supported things.
157///
158/// This is the bridge between [`meta::ClusterDescriptor`](crate::dm::ClusterDescriptor) — what
159/// a device serves — and [`Conform`] — what the specification allows.
160struct Instance<'a> {
161    descriptor: &'a ClusterDescriptor<'a>,
162}
163
164impl Supports for Instance<'_> {
165    fn feature_map(&self) -> u32 {
166        self.descriptor.feature_map
167    }
168
169    fn has_attribute(&self, id: AttributeId) -> bool {
170        self.descriptor.attributes.iter().any(|a| a.id == id)
171    }
172
173    fn has_command(&self, id: CommandId) -> bool {
174        self.descriptor.accepted_commands.iter().any(|c| c.id == id) || self.generates(id)
175    }
176
177    fn has_event(&self, id: EventId) -> bool {
178        self.descriptor.events.iter().any(|e| e.id == id)
179    }
180
181    fn has_cluster(&self, _id: ClusterId) -> bool {
182        // A cluster's own conformance never refers to another cluster; a device type's does,
183        // and that check has the endpoint to answer it with.
184        false
185    }
186}
187
188impl Instance<'_> {
189    /// Whether the server sends this command.
190    ///
191    /// §7.13.5's `GeneratedCommandList` is *synthesised*: "For each client request command in
192    /// this list that mandates a response from the server, the response command SHALL be
193    /// indicated in the GeneratedCommandList", so most responses are declared once, on the
194    /// request, through [`CommandDescriptor::response`](crate::dm::CommandDescriptor). Asking
195    /// only about the explicit list would find none of them and call every response command
196    /// missing.
197    fn generates(&self, id: CommandId) -> bool {
198        self.descriptor.generated_command_ids().any(|c| c == id)
199    }
200}
201
202impl Cluster {
203    /// The feature bits this revision defines, as a mask.
204    #[must_use]
205    pub fn feature_mask(&self) -> u32 {
206        let mut mask = 0u32;
207        for feature in self.features {
208            if feature.bit < 32 {
209                mask |= 1u32 << feature.bit;
210            }
211        }
212        mask
213    }
214
215    /// The feature whose code is `code`, if this cluster has one.
216    #[must_use]
217    pub fn feature(&self, code: &str) -> Option<&Feature> {
218        self.features.iter().find(|f| f.code == code)
219    }
220
221    /// Checks a device's descriptor against the specification, reporting each defect to
222    /// `found`.
223    ///
224    /// Four kinds of mistake, and the first two are the ones a device makes by accident:
225    ///
226    /// * a **mandatory element missing** — the feature map claims `Lighting` and the
227    ///   descriptor has no `StartUpOnOff`;
228    /// * a **disallowed element present** — `StartUpOnOff` served without `Lighting`, which a
229    ///   commissioner reads as a device that does not know what it is;
230    /// * a feature bit this revision does not define;
231    /// * a `ClusterRevision` that is not the specification's.
232    ///
233    /// Elements whose conformance is [prose](Conformance::Described) are skipped in both
234    /// directions. The specification could not express the rule mechanically, so neither can
235    /// this — and guessing would produce exactly the confident-and-wrong answer that makes a
236    /// validator worth ignoring.
237    pub fn validate(&self, descriptor: &ClusterDescriptor<'_>, mut found: impl FnMut(Defect)) {
238        if descriptor.revision != self.revision {
239            found(Defect::WrongRevision {
240                found: descriptor.revision,
241                expected: self.revision,
242            });
243        }
244        let undefined = descriptor.feature_map & !self.feature_mask();
245        for bit in 0..32u8 {
246            if undefined & (1u32 << bit) != 0 {
247                found(Defect::UnknownFeature(bit));
248            }
249        }
250
251        let instance = Instance { descriptor };
252
253        for attribute in self.attributes {
254            let verdict = attribute.conform.verdict(&instance);
255            let present = instance.has_attribute(attribute.id);
256            check(
257                verdict,
258                present,
259                Element::Attribute(attribute.id),
260                &mut found,
261            );
262        }
263        for command in self.commands {
264            let verdict = command.conform.verdict(&instance);
265            if command.to_server {
266                let present = descriptor
267                    .accepted_commands
268                    .iter()
269                    .any(|c| c.id == command.id);
270                check(verdict, present, Element::Command(command.id), &mut found);
271            } else {
272                // A response command belongs in the *generated* list. Accepting one would
273                // advertise that a client may invoke this server's own reply.
274                //
275                // Only when the id is unambiguous. Matter scopes command ids **by
276                // direction**, and four clusters in the 1.6 library reuse one across both —
277                // Groups' `AddGroup` and `AddGroupResponse` are each `0x00`. Finding that id
278                // in the accepted list there means the *request* is accepted, which is exactly
279                // right, and reporting it would make every conformant Groups server look
280                // broken.
281                let shared = self
282                    .commands
283                    .iter()
284                    .any(|other| other.to_server && other.id == command.id);
285                if !shared
286                    && descriptor
287                        .accepted_commands
288                        .iter()
289                        .any(|c| c.id == command.id)
290                {
291                    found(Defect::ResponseAccepted(command.id));
292                }
293                let present = instance.generates(command.id);
294                check(verdict, present, Element::Command(command.id), &mut found);
295            }
296        }
297        for event in self.events {
298            let verdict = event.conform.verdict(&instance);
299            let present = instance.has_event(event.id);
300            check(verdict, present, Element::Event(event.id), &mut found);
301        }
302    }
303
304    /// Whether a descriptor has no defects at all.
305    #[must_use]
306    pub fn is_valid(&self, descriptor: &ClusterDescriptor<'_>) -> bool {
307        let mut ok = true;
308        self.validate(descriptor, |_| ok = false);
309        ok
310    }
311}
312
313fn check(verdict: Conformance, present: bool, element: Element, found: &mut impl FnMut(Defect)) {
314    match verdict {
315        Conformance::Mandatory if !present => found(Defect::Missing(element)),
316        Conformance::Disallowed if present => found(Defect::Disallowed(element)),
317        _ => {}
318    }
319}
320
321// --- Building a descriptor from the specification ------------------------------------------
322
323/// The optional elements a device chooses to serve.
324///
325/// Conformance says what a device *may* have, and "may" is not derivable — an optional
326/// attribute is present because the product decided to implement it. So a device supplies its
327/// feature map, which settles the mandatory and disallowed elements, and this, which settles
328/// the rest.
329#[derive(Debug, Clone, Copy, Default)]
330pub struct Optional<'a> {
331    /// Optional attributes the device serves.
332    pub attributes: &'a [AttributeId],
333    /// Optional commands it accepts or generates.
334    pub commands: &'a [CommandId],
335    /// Optional events it may emit.
336    pub events: &'a [EventId],
337}
338
339impl Optional<'_> {
340    /// A device that implements nothing optional.
341    pub const NONE: Self = Self {
342        attributes: &[],
343        commands: &[],
344        events: &[],
345    };
346}
347
348/// A [`ClusterDescriptor`] derived from the specification's own tables.
349///
350/// The tables say which elements a feature map makes mandatory and which it forbids, so a
351/// device that states its features and its optional choices does not need to write the lists
352/// out — and cannot get them wrong. That is the failure this exists for: a hand-written
353/// descriptor whose element list does not move when its feature map does still *advertises*
354/// the elements, and a client reading `AttributeList` believes it.
355///
356/// `A`, `C`, `G` and `E` bound what the *device holds* — the attributes, accepted commands,
357/// generated commands and events conformance selected, not the size of the specification's
358/// table. Sizing one too small is [`NoSpace`](crate::ErrorCode::NoSpace), at construction,
359/// once.
360///
361/// ```
362/// use matter_kit::clusters::generated::on_off;
363/// use matter_kit::dm::spec::{Conforming, Optional};
364///
365/// // A plain On/Off server: no Lighting, so none of its four attributes.
366/// let plain = Conforming::<8, 8, 4, 4>::new(&on_off::CLUSTER, 0, &Optional::NONE)?;
367/// assert_eq!(plain.descriptor().attributes.len(), 1);
368///
369/// // The same cluster with Lighting: `StartUpOnOff` and its three companions appear, and so
370/// // do three more commands, without a line of it being written down anywhere.
371/// let lighting =
372///     Conforming::<8, 8, 4, 4>::new(&on_off::CLUSTER, on_off::feature::LIGHTING, &Optional::NONE)?;
373/// assert_eq!(lighting.descriptor().attributes.len(), 5);
374/// assert_eq!(lighting.descriptor().accepted_commands.len(), 6);
375/// # Ok::<(), matter_kit::Error>(())
376/// ```
377#[derive(Debug)]
378pub struct Conforming<const A: usize, const C: usize, const G: usize, const E: usize> {
379    id: ClusterId,
380    revision: u16,
381    feature_map: u32,
382    attributes: heapless::Vec<AttributeDescriptor, A>,
383    accepted: heapless::Vec<CommandDescriptor, C>,
384    generated: heapless::Vec<CommandId, G>,
385    events: heapless::Vec<EventDescriptor, E>,
386}
387
388/// Which entries of a specification table have been chosen, by position.
389///
390/// A bitset rather than a list of ids, because an id does not identify an entry: Matter scopes
391/// command ids by direction, and Groups, Scenes, Door Lock and Commodity Tariff each define a
392/// request and a response that share one.
393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394struct Chosen<const N: usize> {
395    bits: [bool; N],
396}
397
398impl<const N: usize> Chosen<N> {
399    const fn new() -> Self {
400        Self { bits: [false; N] }
401    }
402
403    /// Marks an entry chosen, or fails when the table is longer than the caller sized for.
404    fn set(&mut self, index: usize) -> crate::error::Result<()> {
405        match self.bits.get_mut(index) {
406            Some(slot) => {
407                *slot = true;
408                Ok(())
409            }
410            None => Err(crate::Error::new(crate::ErrorCode::NoSpace)),
411        }
412    }
413
414    fn has(&self, index: usize) -> bool {
415        self.bits.get(index).copied().unwrap_or(false)
416    }
417}
418
419/// What a candidate element set looks like to a conformance expression.
420struct Candidate<'a> {
421    feature_map: u32,
422    spec: &'a Cluster,
423    attributes: &'a Chosen<MAX_ELEMENTS>,
424    commands: &'a Chosen<MAX_ELEMENTS>,
425    events: &'a Chosen<MAX_ELEMENTS>,
426}
427
428impl Supports for Candidate<'_> {
429    fn feature_map(&self) -> u32 {
430        self.feature_map
431    }
432    fn has_attribute(&self, id: AttributeId) -> bool {
433        self.spec
434            .attributes
435            .iter()
436            .enumerate()
437            .any(|(index, a)| a.id == id && self.attributes.has(index))
438    }
439    /// A condition names a command by id alone, which is direction-agnostic, so this answers
440    /// "some chosen command has this id". No cluster that reuses an id across directions
441    /// conditions on a command, so the two readings never differ in the 1.6 library.
442    fn has_command(&self, id: CommandId) -> bool {
443        self.spec
444            .commands
445            .iter()
446            .enumerate()
447            .any(|(index, c)| c.id == id && self.commands.has(index))
448    }
449    fn has_event(&self, id: EventId) -> bool {
450        self.spec
451            .events
452            .iter()
453            .enumerate()
454            .any(|(index, e)| e.id == id && self.events.has(index))
455    }
456    fn has_cluster(&self, _id: ClusterId) -> bool {
457        false
458    }
459}
460
461/// How many times the element set may be recomputed before giving up.
462///
463/// An element's conformance may name another element, so the answer depends on the set being
464/// computed — `Attribute(x)` is true or false according to whether `x` ended up present. The
465/// dependencies in the 1.6 library are one deep, so this settles on the second pass; the
466/// margin is for a future revision, and the cap is because the specification does not promise
467/// such a system has a unique solution at all.
468const ROUNDS: usize = 8;
469
470/// How many elements of one kind a cluster may define.
471///
472/// The working set during the fixed-point search, which is sized by the *specification's*
473/// table rather than by what the caller chose to serve — so `A`, `C`, `G` and `E` keep meaning
474/// "how much the device holds" rather than "how big the cluster is". The largest tables in the
475/// 1.6 library are 65 attributes, 28 commands and 17 events; this leaves room for a revision
476/// that grows them.
477const MAX_ELEMENTS: usize = 128;
478
479impl<const A: usize, const C: usize, const G: usize, const E: usize> Conforming<A, C, G, E> {
480    /// Derives the descriptor for an instance of `spec` with this feature map.
481    ///
482    /// Returns [`InvalidArgument`](crate::ErrorCode::InvalidArgument) for a feature bit the cluster does not define —
483    /// a device claiming one is describing a cluster that does not exist — and
484    /// [`NoSpace`](crate::ErrorCode::NoSpace) when a const parameter is too small for what conformance
485    /// selected.
486    pub fn new(
487        spec: &'static Cluster,
488        feature_map: u32,
489        optional: &Optional<'_>,
490    ) -> crate::error::Result<Self> {
491        if feature_map & !spec.feature_mask() != 0 {
492            crate::error::bail!(InvalidArgument)
493        }
494
495        // Iterate to a fixed point. Each round decides every element against the previous
496        // round's set, which is what lets an attribute whose conformance names another
497        // attribute settle.
498        // Selection is by *position* in the specification's tables, never by id. Matter
499        // scopes command ids by direction, and Groups, Scenes, Door Lock and Commodity Tariff
500        // each define a request and a response sharing one — so a set of ids would silently
501        // merge them and serve whichever the filter happened to match first.
502        let mut attributes = Chosen::<MAX_ELEMENTS>::new();
503        let mut commands = Chosen::<MAX_ELEMENTS>::new();
504        let mut events = Chosen::<MAX_ELEMENTS>::new();
505        for round in 0..ROUNDS {
506            let candidate = Candidate {
507                feature_map,
508                spec,
509                attributes: &attributes,
510                commands: &commands,
511                events: &events,
512            };
513            let mut next_attributes = Chosen::<MAX_ELEMENTS>::new();
514            let mut next_commands = Chosen::<MAX_ELEMENTS>::new();
515            let mut next_events = Chosen::<MAX_ELEMENTS>::new();
516
517            for (index, attribute) in spec.attributes.iter().enumerate() {
518                if selected(
519                    attribute.conform.verdict(&candidate),
520                    optional.attributes.contains(&attribute.id),
521                ) {
522                    next_attributes.set(index)?;
523                }
524            }
525            for (index, command) in spec.commands.iter().enumerate() {
526                if selected(
527                    command.conform.verdict(&candidate),
528                    optional.commands.contains(&command.id),
529                ) {
530                    next_commands.set(index)?;
531                }
532            }
533            for (index, event) in spec.events.iter().enumerate() {
534                if selected(
535                    event.conform.verdict(&candidate),
536                    optional.events.contains(&event.id),
537                ) {
538                    next_events.set(index)?;
539                }
540            }
541
542            let settled =
543                next_attributes == attributes && next_commands == commands && next_events == events;
544            attributes = next_attributes;
545            commands = next_commands;
546            events = next_events;
547            if settled {
548                break;
549            }
550            if round == ROUNDS - 1 {
551                // The conformance did not settle. Better to refuse than to ship whichever
552                // half of an oscillation the loop happened to stop on.
553                crate::error::bail!(InvalidState)
554            }
555        }
556
557        let mut this = Self {
558            id: spec.id,
559            revision: spec.revision,
560            feature_map,
561            attributes: heapless::Vec::new(),
562            accepted: heapless::Vec::new(),
563            generated: heapless::Vec::new(),
564            events: heapless::Vec::new(),
565        };
566        for (_, attribute) in spec
567            .attributes
568            .iter()
569            .enumerate()
570            .filter(|(index, _)| attributes.has(*index))
571        {
572            this.attributes
573                .push(AttributeDescriptor {
574                    id: attribute.id,
575                    access: attribute.access,
576                    reporting: attribute.reporting,
577                    qualities: attribute.qualities,
578                })
579                .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
580        }
581        for (_, command) in spec
582            .commands
583            .iter()
584            .enumerate()
585            .filter(|(index, _)| commands.has(*index))
586        {
587            if command.to_server {
588                this.accepted
589                    .push(CommandDescriptor {
590                        id: command.id,
591                        access: command.access,
592                        // Left `None`: §7.13.5's list is synthesised from it, and the
593                        // responses are already selected in their own right below. Declaring
594                        // them here as well would list each one twice.
595                        response: None,
596                    })
597                    .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
598            } else {
599                this.generated
600                    .push(command.id)
601                    .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
602            }
603        }
604        for (_, event) in spec
605            .events
606            .iter()
607            .enumerate()
608            .filter(|(index, _)| events.has(*index))
609        {
610            this.events
611                .push(EventDescriptor {
612                    id: event.id,
613                    access: event.access,
614                    priority: event.priority,
615                })
616                .map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
617        }
618        Ok(this)
619    }
620
621    /// The descriptor, borrowed from this storage.
622    #[must_use]
623    pub fn descriptor(&self) -> ClusterDescriptor<'_> {
624        ClusterDescriptor {
625            id: self.id,
626            revision: self.revision,
627            feature_map: self.feature_map,
628            attributes: &self.attributes,
629            accepted_commands: &self.accepted,
630            generated_commands: &self.generated,
631            events: &self.events,
632        }
633    }
634}
635
636/// Whether an element with this verdict is served.
637///
638/// `Provisional` and `Deprecated` are treated as optional: neither is forbidden, and both are
639/// a decision the product makes rather than one the conformance makes for it. `Described` is
640/// *not* selected — the specification could not express the rule, so a device that needs the
641/// element names it in [`Optional`] and takes responsibility for reading the prose.
642const fn selected(verdict: Conformance, chosen: bool) -> bool {
643    match verdict {
644        Conformance::Mandatory => true,
645        Conformance::Optional
646        | Conformance::Provisional
647        | Conformance::Deprecated
648        | Conformance::Described => chosen,
649        Conformance::Disallowed => false,
650    }
651}