Skip to main content

matter_kit/clusters/
bridged_device_basic_information.rs

1//! Bridged Device Basic Information, cluster `0x0039` (Core §9.13).
2//!
3//! > This cluster provides attributes and events for determining basic information about
4//! > Bridged Nodes.
5//!
6//! What a bridge says about a lamp it does not itself contain. It is Basic Information with
7//! the *node's* facts taken out — §9.13.5 marks `DataModelRevision`, `Location`,
8//! `LocalConfigDisabled`, `CapabilityMinima`, `SpecificationVersion` and `MaxPathsPerInvoke`
9//! disallowed, because those describe the Matter node doing the bridging, not the Zigbee bulb
10//! behind it.
11//!
12//! # Absent, not blank
13//!
14//! Almost everything here is optional, and §9.13 is unusually explicit about why:
15//!
16//! > For such cases where the information for a particular attribute is not available, the
17//! > Bridge SHOULD NOT include the attribute in the cluster for this Bridged Device.
18//!
19//! And again per attribute: "If the manufacturer of a Bridged Device is known to the Bridge,
20//! the Bridge SHALL provide this name (in attribute VendorName), otherwise it SHALL NOT
21//! include this attribute." So [`BridgedDevice`]'s fields are `Option`, an absent one is left
22//! out of `AttributeList` rather than reported as an empty string, and a client can tell "the
23//! bridge does not know" from "the vendor is called nothing".
24//!
25//! # Where it may appear
26//!
27//! > This cluster SHALL NOT be used on an endpoint that is not in the Descriptor cluster
28//! > PartsList of an endpoint with an Aggregator device type.
29//!
30//! A rule about the node's shape rather than about this cluster's data, so it is the
31//! endpoint's `PartsList` that enforces it — see `examples/bridge`.
32
33use core::cell::{Cell, RefCell};
34
35use crate::clusters::generated::bridged_device_basic_information as spec_bridged;
36use crate::dm::spec::{Conforming, Optional};
37use crate::dm::{Resolved, ResolvedCommand};
38use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
39use crate::msg::VendorId;
40use crate::platform::{Duration, Instant};
41use crate::tlv::{Tag, TlvWriter};
42
43use super::Cluster;
44
45pub use spec_bridged::attribute::{
46    CONFIGURATION_VERSION, HARDWARE_VERSION, HARDWARE_VERSION_STRING, MANUFACTURING_DATE,
47    NODE_LABEL, PART_NUMBER, PRODUCT_LABEL, PRODUCT_NAME, PRODUCT_URL, REACHABLE, SERIAL_NUMBER,
48    SOFTWARE_VERSION, SOFTWARE_VERSION_STRING, UNIQUE_ID, VENDOR_ID, VENDOR_NAME,
49};
50pub use spec_bridged::command::KEEP_ACTIVE;
51pub use spec_bridged::event::{ACTIVE_CHANGED, REACHABLE_CHANGED};
52pub use spec_bridged::{ID, PICS, REVISION, feature};
53
54/// What the bridge knows about one bridged device.
55///
56/// Every field is optional because the bridge may simply not know: a Zigbee bulb has no
57/// Matter product id, and §9.13.5.1 says "For bridged non-Matter devices, the ProductID
58/// attribute SHALL NOT be included."
59#[derive(Debug, Clone, Copy, Default)]
60pub struct BridgedDevice<'a> {
61    /// `VendorName` — the manufacturer, when the bridge knows it.
62    pub vendor_name: Option<&'a str>,
63    /// `VendorID` — the Alliance-assigned code, when the bridge knows it.
64    pub vendor_id: Option<VendorId>,
65    /// `ProductName`.
66    pub product_name: Option<&'a str>,
67    /// `ProductID` — only ever for a bridged *Matter* device.
68    pub product_id: Option<u16>,
69    /// `HardwareVersion` and its string form.
70    pub hardware_version: Option<u16>,
71    /// `HardwareVersionString`.
72    pub hardware_version_string: Option<&'a str>,
73    /// `SoftwareVersion`.
74    pub software_version: Option<u32>,
75    /// `SoftwareVersionString`.
76    pub software_version_string: Option<&'a str>,
77    /// `ManufacturingDate`, as §11.1.5.12's "YYYYMMDD" prefix.
78    pub manufacturing_date: Option<&'a str>,
79    /// `PartNumber`.
80    pub part_number: Option<&'a str>,
81    /// `ProductURL`.
82    pub product_url: Option<&'a str>,
83    /// `ProductLabel`.
84    pub product_label: Option<&'a str>,
85    /// `SerialNumber`.
86    pub serial_number: Option<&'a str>,
87    /// `UniqueID` (§9.13.5.3).
88    ///
89    /// > If the bridged device does not provide some unique id ... the bridge SHALL generate a
90    /// > unique id on behalf of the bridged device.
91    ///
92    /// So a bridge that has one should always pass one: this is what lets a controller
93    /// recognise the same bulb after the bridge renumbers its endpoints.
94    pub unique_id: Option<&'a str>,
95    /// `ConfigurationVersion` (§9.13.5.4) — bumped when the bridged device's configuration
96    /// changes, so a client can tell a renamed device from a replaced one.
97    pub configuration_version: Option<u32>,
98}
99
100/// What a `KeepActive` (§9.13.6.1) asks the bridge to do.
101///
102/// The bridge cannot do it synchronously: the device is asleep, by definition. So the
103/// cluster records the *request* — merged per §9.13.6.1's rules — and the bridge acts on it
104/// when the device next checks in.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct PendingActive {
107    /// How long to hold the device awake, in milliseconds.
108    pub stay_active_ms: u32,
109    /// When the request lapses if the device does not appear.
110    pub expires: Instant,
111}
112
113/// What a device labelled its `NodeLabel` (§11.1.5.6) — writable, max 32.
114pub const NODE_LABEL_MAX: usize = 32;
115
116/// Bridged Device Basic Information for one bridged device.
117#[derive(Debug)]
118pub struct BridgedDeviceBasicInformation<'a> {
119    device: BridgedDevice<'a>,
120    reachable: Cell<bool>,
121    node_label: RefCell<heapless::String<NODE_LABEL_MAX>>,
122    pending: Cell<Option<PendingActive>>,
123    /// Event records the device turns into §7.14 events, drained by [`Self::take_events`].
124    events: RefCell<heapless::Vec<Event, 8>>,
125}
126
127/// An event this cluster produced, for the device to record in its own store.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum Event {
130    /// §9.13.7.1 `ReachableChanged`, carrying the new `ReachableNewValue`.
131    ReachableChanged(bool),
132    /// §9.13.7.2 `ActiveChanged`, carrying `PromisedActiveDuration` in milliseconds.
133    ActiveChanged(u32),
134}
135
136impl<'a> BridgedDeviceBasicInformation<'a> {
137    /// A cluster describing `device`, reachable or not.
138    #[must_use]
139    pub fn new(device: BridgedDevice<'a>, reachable: bool) -> Self {
140        Self {
141            device,
142            reachable: Cell::new(reachable),
143            node_label: RefCell::new(heapless::String::new()),
144            pending: Cell::new(None),
145            events: RefCell::new(heapless::Vec::new()),
146        }
147    }
148
149    /// The descriptor for an instance, derived from the specification's tables.
150    ///
151    /// The optional set is the *bridge's* to declare, and it is not a style choice: §9.13
152    /// says an attribute the bridge cannot fill must be left out, so
153    /// [`Self::optional_for`] derives it from what [`BridgedDevice`] actually holds.
154    pub fn conforming(
155        feature_map: u32,
156        optional: &Optional<'_>,
157    ) -> crate::error::Result<Conforming<16, 1, 0, 2>> {
158        Conforming::new(&spec_bridged::CLUSTER, feature_map, optional)
159    }
160
161    /// Which optional attributes this bridge can actually fill.
162    ///
163    /// `NodeLabel` is always served — it is the *user's* name for the device, which the bridge
164    /// stores whether or not the device told it anything.
165    #[must_use]
166    pub fn optional_for(device: &BridgedDevice<'_>, buf: &'a mut [u32; 16]) -> Optional<'a> {
167        let mut n = 0usize;
168        let mut add = |id: u32, present: bool| {
169            if present && n < buf.len() {
170                if let Some(slot) = buf.get_mut(n) {
171                    *slot = id;
172                }
173                n = n.saturating_add(1);
174            }
175        };
176        add(VENDOR_NAME, device.vendor_name.is_some());
177        add(VENDOR_ID, device.vendor_id.is_some());
178        add(PRODUCT_NAME, device.product_name.is_some());
179        add(NODE_LABEL, true);
180        add(HARDWARE_VERSION, device.hardware_version.is_some());
181        add(
182            HARDWARE_VERSION_STRING,
183            device.hardware_version_string.is_some(),
184        );
185        add(SOFTWARE_VERSION, device.software_version.is_some());
186        add(
187            SOFTWARE_VERSION_STRING,
188            device.software_version_string.is_some(),
189        );
190        add(MANUFACTURING_DATE, device.manufacturing_date.is_some());
191        add(PART_NUMBER, device.part_number.is_some());
192        add(PRODUCT_URL, device.product_url.is_some());
193        add(PRODUCT_LABEL, device.product_label.is_some());
194        add(SERIAL_NUMBER, device.serial_number.is_some());
195        add(UNIQUE_ID, device.unique_id.is_some());
196        add(
197            CONFIGURATION_VERSION,
198            device.configuration_version.is_some(),
199        );
200        // `ProductID` is `desc` rather than `O`, so it is not an optional the caller may
201        // switch on — a bridged Matter device gets it and a non-Matter one must not.
202        Optional {
203            attributes: buf.get(..n).unwrap_or(&[]),
204            commands: &[],
205            events: &[],
206        }
207    }
208
209    /// Everything the `BridgedICDSupport` feature adds: `KeepActive`.
210    pub const WITH_KEEP_ACTIVE: Optional<'static> = Optional {
211        attributes: &[],
212        commands: &[KEEP_ACTIVE],
213        events: &[],
214    };
215
216    /// What the bridge knows about the device.
217    #[must_use]
218    pub const fn device(&self) -> &BridgedDevice<'a> {
219        &self.device
220    }
221
222    /// `Reachable` (§9.13.5.2).
223    #[must_use]
224    pub fn reachable(&self) -> bool {
225        self.reachable.get()
226    }
227
228    /// Reports that the bridged device became reachable, or stopped being.
229    ///
230    /// §9.13.7.1's `ReachableChanged` is "generated when the Reachable attribute changes" —
231    /// on the change, so a bridge that re-polls every thirty seconds does not emit an event
232    /// every thirty seconds. That matters more here than in most clusters: an event is a
233    /// buffered record on a device with a fixed ring, and a chatty one pushes out everything
234    /// else in the ring.
235    pub fn set_reachable(&self, reachable: bool) {
236        if self.reachable.replace(reachable) != reachable {
237            self.push(Event::ReachableChanged(reachable));
238        }
239    }
240
241    /// `NodeLabel` — the name a user gave the device through this bridge.
242    #[must_use]
243    pub fn node_label(&self) -> core::cell::Ref<'_, heapless::String<NODE_LABEL_MAX>> {
244        self.node_label.borrow()
245    }
246
247    /// The `KeepActive` request outstanding, if any.
248    #[must_use]
249    pub fn pending_active(&self) -> Option<PendingActive> {
250        self.pending.get()
251    }
252
253    /// Drops a `KeepActive` request whose `TimeoutMs` has run out (§9.13.6.1).
254    ///
255    /// > The server "pending active" state SHALL expire after the amount of time defined by
256    /// > the TimeoutMs field ... if no subsequent KeepActive command is received.
257    pub fn poll(&self, now: Instant) {
258        if let Some(pending) = self.pending.get()
259            && now >= pending.expires
260        {
261            self.pending.set(None);
262        }
263    }
264
265    /// The bridge saw the device wake, so the outstanding request is satisfied.
266    ///
267    /// §9.13.6.1: "The server SHALL only keep the bridged device active once for a request.
268    /// (The server SHALL only consider the operation performed if an associated ActiveChanged
269    /// event was generated.)" — so the request is cleared here and nowhere else.
270    pub fn became_active(&self) {
271        if let Some(pending) = self.pending.take() {
272            self.push(Event::ActiveChanged(pending.stay_active_ms));
273        }
274    }
275
276    /// Takes the event records the cluster has produced.
277    ///
278    /// Draining rather than reading means a record is reported once, and a device that never
279    /// drains cannot accumulate them forever — the buffer is fixed and its oldest records go,
280    /// the same way §7.14.2's event ring drops its oldest.
281    pub fn take_events(&self) -> heapless::Vec<Event, 8> {
282        core::mem::take(&mut self.events.borrow_mut())
283    }
284
285    fn push(&self, event: Event) {
286        let mut events = self.events.borrow_mut();
287        if events.is_full() {
288            events.remove(0);
289        }
290        let _ = events.push(event);
291    }
292
293    /// §9.13.6.1's merge: a second `KeepActive` never shortens the first.
294    ///
295    /// > the StayActiveDuration is updated to the greater of the new value and the previously
296    /// > stored value, and the TimeoutMs is updated to the greater of the new value and the
297    /// > remaining time until the prior "pending active" state expires.
298    ///
299    /// Two controllers each asking for the device to stay awake must not end with it awake
300    /// for the shorter of the two.
301    fn keep_active(&self, stay_active_ms: u32, timeout_ms: u32, now: Instant) {
302        let expires = now.saturating_add(Duration::from_millis(u64::from(timeout_ms)));
303        let merged = match self.pending.get() {
304            Some(prior) => PendingActive {
305                stay_active_ms: prior.stay_active_ms.max(stay_active_ms),
306                expires: if prior.expires > expires {
307                    prior.expires
308                } else {
309                    expires
310                },
311            },
312            None => PendingActive {
313                stay_active_ms,
314                expires,
315            },
316        };
317        self.pending.set(Some(merged));
318    }
319}
320
321impl ClusterHandler for BridgedDeviceBasicInformation<'_> {
322    fn read(
323        &self,
324        resolved: &Resolved<'_>,
325        _ctx: &InteractionContext<'_>,
326        w: &mut TlvWriter<'_>,
327        tag: Tag,
328    ) -> Result<(), Status> {
329        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
330        let device = &self.device;
331        // An attribute the bridge cannot fill is not served at all — §9.13's "SHOULD NOT
332        // include the attribute" — so the descriptor leaves it out and a path naming it
333        // resolves to UNSUPPORTED_ATTRIBUTE before ever reaching here. This arm is the second
334        // half of the same fact, for a handler used without that descriptor.
335        fn text(value: Option<&str>) -> Result<&str, Status> {
336            value.ok_or(Status::UnsupportedAttribute)
337        }
338        match resolved.attribute {
339            REACHABLE => full(w.bool(tag, self.reachable.get())),
340            NODE_LABEL => full(w.utf8(tag, self.node_label.borrow().as_str())),
341            VENDOR_NAME => full(w.utf8(tag, text(device.vendor_name)?)),
342            VENDOR_ID => full(w.unsigned(
343                tag,
344                u64::from(device.vendor_id.ok_or(Status::UnsupportedAttribute)?.0),
345            )),
346            PRODUCT_NAME => full(w.utf8(tag, text(device.product_name)?)),
347            spec_bridged::attribute::PRODUCT_ID => full(w.unsigned(
348                tag,
349                u64::from(device.product_id.ok_or(Status::UnsupportedAttribute)?),
350            )),
351            HARDWARE_VERSION => full(
352                w.unsigned(
353                    tag,
354                    u64::from(
355                        device
356                            .hardware_version
357                            .ok_or(Status::UnsupportedAttribute)?,
358                    ),
359                ),
360            ),
361            HARDWARE_VERSION_STRING => full(w.utf8(tag, text(device.hardware_version_string)?)),
362            SOFTWARE_VERSION => full(
363                w.unsigned(
364                    tag,
365                    u64::from(
366                        device
367                            .software_version
368                            .ok_or(Status::UnsupportedAttribute)?,
369                    ),
370                ),
371            ),
372            SOFTWARE_VERSION_STRING => full(w.utf8(tag, text(device.software_version_string)?)),
373            MANUFACTURING_DATE => full(w.utf8(tag, text(device.manufacturing_date)?)),
374            PART_NUMBER => full(w.utf8(tag, text(device.part_number)?)),
375            PRODUCT_URL => full(w.utf8(tag, text(device.product_url)?)),
376            PRODUCT_LABEL => full(w.utf8(tag, text(device.product_label)?)),
377            SERIAL_NUMBER => full(w.utf8(tag, text(device.serial_number)?)),
378            UNIQUE_ID => full(w.utf8(tag, text(device.unique_id)?)),
379            CONFIGURATION_VERSION => full(
380                w.unsigned(
381                    tag,
382                    u64::from(
383                        device
384                            .configuration_version
385                            .ok_or(Status::UnsupportedAttribute)?,
386                    ),
387                ),
388            ),
389            _ => Err(Status::UnsupportedAttribute),
390        }
391    }
392
393    fn write(
394        &self,
395        resolved: &Resolved<'_>,
396        data: &[u8],
397        _op: crate::im::WriteOp,
398        _ctx: &InteractionContext<'_>,
399    ) -> Result<(), Status> {
400        // §11.1.5.6's `NodeLabel` is the one writable attribute: the user's name for the
401        // device, which belongs to whoever is looking at it rather than to the bridge.
402        if resolved.attribute != NODE_LABEL {
403            return Err(Status::UnsupportedWrite);
404        }
405        let mut reader = crate::tlv::TlvReader::new_in(data, crate::tlv::ContainerKind::Structure);
406        let element = reader
407            .next_element()
408            .map_err(|_| Status::InvalidAction)?
409            .ok_or(Status::InvalidAction)?;
410        let crate::tlv::Value::Utf8(text) = element.value else {
411            return Err(Status::InvalidDataType);
412        };
413        let mut label = heapless::String::new();
414        label.push_str(text).map_err(|_| Status::ConstraintError)?;
415        *self.node_label.borrow_mut() = label;
416        Ok(())
417    }
418
419    fn invoke(
420        &self,
421        resolved: &ResolvedCommand<'_>,
422        fields: Option<&[u8]>,
423        ctx: &InteractionContext<'_>,
424        _w: &mut TlvWriter<'_>,
425        _tag: Tag,
426    ) -> Result<Option<CommandId>, StatusIb> {
427        if resolved.command.id != KEEP_ACTIVE {
428            return Err(Status::UnsupportedCommand.into());
429        }
430        let decoded: spec_bridged::KeepActiveFields =
431            super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
432        self.keep_active(decoded.stay_active_duration, decoded.timeout_ms, ctx.now);
433        // §9.13.6's table gives the command response "Y": a plain status. The work is
434        // best-effort and asynchronous by nature — the device is asleep — so success here
435        // means "recorded", and `ActiveChanged` is what says it actually happened.
436        Ok(None)
437    }
438}
439
440/// So a tuple of clusters can dispatch to it by id.
441impl Cluster for BridgedDeviceBasicInformation<'_> {
442    const ID: ClusterId = ID;
443}