Skip to main content

matter_kit/clusters/
general_diagnostics.rs

1//! General Diagnostics, cluster `0x0033` (Core §11.12).
2//!
3//! > The General Diagnostics Cluster attempts to centralize all metrics that are broadly
4//! > relevant to the majority of Nodes.
5//!
6//! Mandatory on the root node of every device, which makes it the cluster most likely to be
7//! read by a support engineer trying to work out why a light has stopped answering. What it
8//! holds is a mixture of things this crate cannot know — how many times the device has
9//! rebooted, what its interfaces are called, which of its radios is faulty — so almost all of
10//! it comes from a [`Diagnostics`] the device implements.
11//!
12//! # The `EnableKey` is not authentication
13//!
14//! `TestEventTrigger` (§11.12.7.1) makes a device do things the specification deliberately
15//! does not define: certification test plans do. It is gated on a 128-bit key the manufacturer
16//! configures, and §11.12.7.1 is specific about what that means:
17//!
18//! > Devices not targeted towards going to a certification test event SHALL NOT have a
19//! > non-zero EnableKey value configured, so that only devices in test environments are
20//! > responsive to this command.
21//!
22//! So the key is a *shipping* control, not a credential — the command already required
23//! Manage privilege to get this far. A device that ships with a key configured ships with an
24//! undocumented back door, which is why [`Diagnostics::enable_key`] defaults to none and an
25//! all-zero key is refused rather than matched: "The value of all zeroes is reserved to
26//! indicate that no EnableKey is set."
27
28use core::cell::RefCell;
29
30use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey, ct_eq};
31use crate::dm::spec::{Conforming, Optional};
32use crate::dm::{Resolved, ResolvedCommand};
33use crate::im::{
34    AttributeId, ClusterHandler, ClusterId, CommandId, EventId, InteractionContext, Status,
35    StatusIb,
36};
37use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
38
39use super::Cluster;
40
41/// `0x0033` (§11.12.3).
42pub const ID: ClusterId = 0x0033;
43
44/// The revision §11.12.1's table ends on.
45pub const REVISION: u16 = 3;
46
47/// `DMTEST` (§11.12.4) — the extended Data Model testing commands.
48///
49/// "This feature SHALL be supported if the MaxPathsPerInvoke attribute of the Basic
50/// Information Cluster has a value > 1."
51pub const FEATURE_DATA_MODEL_TEST: u32 = 1 << 0;
52
53/// `NetworkInterfaces` (§11.12.6.1) — `list[NetworkInterface]`, max 8, `RV`.
54pub const NETWORK_INTERFACES: AttributeId = 0x0000;
55/// `RebootCount` (§11.12.6.2) — `uint16`, `RV N`.
56pub const REBOOT_COUNT: AttributeId = 0x0001;
57/// `UpTime` (§11.12.6.3) — `uint64`, seconds, `RV C`.
58pub const UP_TIME: AttributeId = 0x0002;
59/// `TotalOperationalHours` (§11.12.6.4) — `uint32`, `RV CN`.
60pub const TOTAL_OPERATIONAL_HOURS: AttributeId = 0x0003;
61/// `BootReason` (§11.12.6.5) — `BootReasonEnum`, `RV`.
62pub const BOOT_REASON: AttributeId = 0x0004;
63/// `ActiveHardwareFaults` (§11.12.6.6) — `list[HardwareFaultEnum]`, max 11, `RV`.
64pub const ACTIVE_HARDWARE_FAULTS: AttributeId = 0x0005;
65/// `ActiveRadioFaults` (§11.12.6.7) — `list[RadioFaultEnum]`, max 7, `RV`.
66pub const ACTIVE_RADIO_FAULTS: AttributeId = 0x0006;
67/// `ActiveNetworkFaults` (§11.12.6.8) — `list[NetworkFaultEnum]`, max 4, `RV`.
68pub const ACTIVE_NETWORK_FAULTS: AttributeId = 0x0007;
69/// `TestEventTriggersEnabled` (§11.12.6) — `bool`, `RV`, mandatory.
70pub const TEST_EVENT_TRIGGERS_ENABLED: AttributeId = 0x0008;
71/// `DeviceLoadStatus` (§11.12.5.7) — `DeviceLoadStruct`, `RV C`, revision 3 and above.
72pub const DEVICE_LOAD_STATUS: AttributeId = 0x000A;
73
74/// `TestEventTrigger` (§11.12.7.1) — Manage, mandatory.
75pub const TEST_EVENT_TRIGGER: CommandId = 0x00;
76/// `TimeSnapshot` (§11.12.7.2) — Operate, mandatory.
77pub const TIME_SNAPSHOT: CommandId = 0x01;
78/// `TimeSnapshotResponse` (§11.12.7.3).
79pub const TIME_SNAPSHOT_RESPONSE: CommandId = 0x02;
80/// `PayloadTestRequest` (§11.12.7.4) — Manage, `DMTEST`.
81pub const PAYLOAD_TEST_REQUEST: CommandId = 0x03;
82/// `PayloadTestResponse` (§11.12.7.5).
83pub const PAYLOAD_TEST_RESPONSE: CommandId = 0x04;
84
85/// `HardwareFaultChange` (§11.12.8.1) — CRITICAL.
86pub const HARDWARE_FAULT_CHANGE: EventId = 0x00;
87/// `RadioFaultChange` (§11.12.8.2) — CRITICAL.
88pub const RADIO_FAULT_CHANGE: EventId = 0x01;
89/// `NetworkFaultChange` (§11.12.8.3) — CRITICAL.
90pub const NETWORK_FAULT_CHANGE: EventId = 0x02;
91/// `BootReason` (§11.12.8.4) — CRITICAL, mandatory.
92pub const BOOT_REASON_EVENT: EventId = 0x03;
93
94/// `PayloadTestRequest`'s `Count` constraint (§11.12.7.4).
95pub const PAYLOAD_TEST_MAX: u16 = 2048;
96
97/// §11.12.5.1's `HardwareFaultEnum`.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99#[repr(u8)]
100pub enum HardwareFault {
101    /// An unspecified fault.
102    Unspecified = 0,
103    /// At least one radio.
104    Radio = 1,
105    /// At least one sensor.
106    Sensor = 2,
107    /// An over-temperature fault that can be reset.
108    ResettableOverTemp = 3,
109    /// One that cannot.
110    NonResettableOverTemp = 4,
111    /// At least one power source.
112    PowerSource = 5,
113    /// A visual display.
114    VisualDisplayFault = 6,
115    /// An audio output.
116    AudioOutputFault = 7,
117    /// A user interface.
118    UserInterfaceFault = 8,
119    /// Non-volatile memory.
120    NonVolatileMemoryError = 9,
121    /// "The Node has encountered disallowed physical tampering."
122    TamperDetected = 10,
123}
124
125/// §11.12.5.2's `RadioFaultEnum`.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127#[repr(u8)]
128pub enum RadioFault {
129    /// An unspecified radio fault.
130    Unspecified = 0,
131    /// The Wi-Fi radio.
132    WiFiFault = 1,
133    /// The cellular radio.
134    CellularFault = 2,
135    /// The 802.15.4 radio.
136    ThreadFault = 3,
137    /// The NFC radio.
138    NfcFault = 4,
139    /// The BLE radio.
140    BleFault = 5,
141    /// The Ethernet controller.
142    EthernetFault = 6,
143}
144
145/// §11.12.5.3's `NetworkFaultEnum`.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147#[repr(u8)]
148pub enum NetworkFault {
149    /// An unspecified fault.
150    Unspecified = 0,
151    /// A hardware failure.
152    HardwareFailure = 1,
153    /// A jammed network.
154    NetworkJammed = 2,
155    /// A failure to establish a connection.
156    ConnectionFailed = 3,
157}
158
159/// §11.12.5.4's `InterfaceTypeEnum`.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
161#[repr(u8)]
162pub enum InterfaceType {
163    /// An interface of an unspecified type.
164    #[default]
165    Unspecified = 0,
166    /// Wi-Fi.
167    WiFi = 1,
168    /// Ethernet.
169    Ethernet = 2,
170    /// Cellular.
171    Cellular = 3,
172    /// Thread.
173    Thread = 4,
174}
175
176/// §11.12.5.5's `BootReasonEnum` — why the node started.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
178#[repr(u8)]
179pub enum BootReason {
180    /// "unable to identify the Power-On reason as one of the other provided enumeration
181    /// values".
182    #[default]
183    Unspecified = 0,
184    /// Physical interaction with the device.
185    PowerOnReboot = 1,
186    /// A brown-out of the power supply.
187    BrownOutReset = 2,
188    /// A software watchdog timer.
189    SoftwareWatchdogReset = 3,
190    /// A hardware watchdog timer.
191    HardwareWatchdogReset = 4,
192    /// A completed software update.
193    SoftwareUpdateCompleted = 5,
194    /// A software-initiated reboot.
195    SoftwareReset = 6,
196}
197
198/// One entry of `NetworkInterfaces` (§11.12.5.6).
199///
200/// The IP addresses are borrowed slices of wire-order octets — four each for IPv4, sixteen for
201/// IPv6 — because a device already holds them somewhere and this cluster is a *view*.
202#[derive(Debug, Clone, Copy)]
203pub struct NetworkInterface<'a> {
204    /// "a human-readable (displayable) name for the network interface, that is different
205    /// from all other interfaces", at most 32 octets.
206    pub name: &'a str,
207    /// Whether the node is advertising operationally on it and can receive on it.
208    pub is_operational: bool,
209    /// Whether off-premise services are reachable over IPv4; `None` writes TLV null, which
210    /// §11.12.5.6 requires when "the Node does not use such services or does not know".
211    pub off_premise_ipv4: Option<bool>,
212    /// The same for IPv6.
213    pub off_premise_ipv6: Option<bool>,
214    /// "the current link-layer address for a 802.3 or IEEE 802.11-2020 network interface …
215    /// the current extended MAC address for a 802.15.4 interface", in wire byte order.
216    pub hardware_address: &'a [u8],
217    /// Up to four IPv4 addresses, four octets each.
218    pub ipv4_addresses: &'a [[u8; 4]],
219    /// Up to eight unicast IPv6 addresses. "This list SHALL include the Node's link-local
220    /// address … SHALL NOT include any multicast group addresses."
221    pub ipv6_addresses: &'a [[u8; 16]],
222    /// What kind of interface it is.
223    pub interface_type: InterfaceType,
224}
225
226impl NetworkInterface<'_> {
227    fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
228        w.start_structure(Tag::Anonymous)?;
229        w.utf8(Tag::Context(0), self.name)?;
230        w.bool(Tag::Context(1), self.is_operational)?;
231        match self.off_premise_ipv4 {
232            Some(value) => w.bool(Tag::Context(2), value)?,
233            None => w.null(Tag::Context(2))?,
234        }
235        match self.off_premise_ipv6 {
236            Some(value) => w.bool(Tag::Context(3), value)?,
237            None => w.null(Tag::Context(3))?,
238        }
239        w.octets(Tag::Context(4), self.hardware_address)?;
240        w.start_array(Tag::Context(5))?;
241        for address in self.ipv4_addresses.iter().take(4) {
242            w.octets(Tag::Anonymous, address)?;
243        }
244        w.end_container()?;
245        w.start_array(Tag::Context(6))?;
246        for address in self.ipv6_addresses.iter().take(8) {
247            w.octets(Tag::Anonymous, address)?;
248        }
249        w.end_container()?;
250        w.unsigned(Tag::Context(7), self.interface_type as u64)?;
251        w.end_container()
252    }
253}
254
255/// §11.12.5.7's `DeviceLoadStruct` — how hard the node is working.
256///
257/// "For all the fields, the value SHALL remain at the maximum representable (clamp to max) if
258/// the maximum value is reached." Saturating rather than wrapping, because a counter that
259/// wraps reports a node under no load at the moment it is under the most.
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
261pub struct DeviceLoad {
262    /// Active subscriptions across every fabric.
263    pub current_subscriptions: u16,
264    /// Active subscriptions for the accessing fabric alone. "If no accessing fabric is
265    /// available, this field SHALL be set to zero."
266    pub current_subscriptions_for_fabric: u16,
267    /// Subscriptions successfully established since start-up, across every fabric.
268    pub total_subscriptions_established: u32,
269    /// Interaction Model messages sent since start-up, "excluding any retries".
270    pub total_im_messages_sent: u32,
271    /// Interaction Model messages received since start-up, excluding retries.
272    pub total_im_messages_received: u32,
273}
274
275impl DeviceLoad {
276    fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> crate::error::Result<()> {
277        w.start_structure(tag)?;
278        w.unsigned(Tag::Context(0), u64::from(self.current_subscriptions))?;
279        w.unsigned(
280            Tag::Context(1),
281            u64::from(self.current_subscriptions_for_fabric),
282        )?;
283        w.unsigned(
284            Tag::Context(2),
285            u64::from(self.total_subscriptions_established),
286        )?;
287        w.unsigned(Tag::Context(3), u64::from(self.total_im_messages_sent))?;
288        w.unsigned(Tag::Context(4), u64::from(self.total_im_messages_received))?;
289        w.end_container()
290    }
291}
292
293/// What the device knows about itself, and this crate cannot.
294///
295/// Every method has a default, because §11.12.6's conformance column makes all but three of
296/// these optional and a node that does not track them should say so rather than invent a
297/// number. The defaults are the "I do not know" answers: no interfaces, no faults, boot reason
298/// `Unspecified`.
299pub trait Diagnostics {
300    /// The node's network interfaces (§11.12.6.1). Each is passed to `emit` in turn, so a
301    /// device can build them from whatever it holds without allocating a list.
302    fn network_interfaces(&self, emit: &mut dyn FnMut(&NetworkInterface<'_>)) {
303        let _ = emit;
304    }
305
306    /// "a best-effort count of the number of times the Node has rebooted" (§11.12.6.2).
307    ///
308    /// "SHALL NOT be incremented when a Node wakes from a low-power or sleep state", and
309    /// "SHALL only be reset to 0 upon a factory reset" — so it is persisted, and a device
310    /// that recomputed it from RAM would report 0 forever.
311    fn reboot_count(&self) -> u16 {
312        0
313    }
314
315    /// Seconds since the node's last reboot (§11.12.6.3).
316    ///
317    /// "SHALL be based on the same System Time source as those used to fulfill any usage of
318    /// the systime-us and systime-ms data types" — the same clock the event log timestamps
319    /// with, so that a client correlating an event with an uptime gets a consistent answer.
320    fn up_time(&self) -> u64 {
321        0
322    }
323
324    /// Hours the node has been operational, across reboots (§11.12.6.4). `None` omits the
325    /// optional attribute.
326    fn total_operational_hours(&self) -> Option<u32> {
327        None
328    }
329
330    /// Why the node last started (§11.12.6.5).
331    fn boot_reason(&self) -> BootReason {
332        BootReason::Unspecified
333    }
334
335    /// The hardware faults currently raised (§11.12.6.6). "This list SHALL NOT contain more
336    /// than one instance of a specific HardwareFaultEnum value."
337    fn active_hardware_faults(&self, emit: &mut dyn FnMut(HardwareFault)) {
338        let _ = emit;
339    }
340
341    /// The radio faults currently raised (§11.12.6.7).
342    fn active_radio_faults(&self, emit: &mut dyn FnMut(RadioFault)) {
343        let _ = emit;
344    }
345
346    /// The network faults currently raised (§11.12.6.8).
347    fn active_network_faults(&self, emit: &mut dyn FnMut(NetworkFault)) {
348        let _ = emit;
349    }
350
351    /// The node's current load (§11.12.5.7), or `None` to omit the attribute.
352    fn device_load(&self, _ctx: &InteractionContext<'_>) -> Option<DeviceLoad> {
353        None
354    }
355
356    /// The 128-bit `EnableKey` this device was provisioned with, if any (§11.12.7.1).
357    ///
358    /// `None` on anything that ships to a customer. A device with a key configured answers
359    /// `TestEventTrigger`, and what that command does is defined by certification test
360    /// literature rather than by the specification — so on a shipped product it is an
361    /// undocumented mechanism with no documented effects.
362    fn enable_key(&self) -> Option<&SymmetricKey> {
363        None
364    }
365
366    /// Runs one test event trigger (§11.12.7.1), having already passed the key check.
367    ///
368    /// `false` is §11.12.7.1's "If the value of EventTrigger received is not supported by the
369    /// receiving Node, this command SHALL fail with a status code of INVALID_COMMAND" — which
370    /// is also the right answer for a device that supports none at all: "this command MAY
371    /// always fail with the INVALID_COMMAND status, equivalent to the situation of receiving
372    /// an unknown EventTrigger, for all possible EventTrigger values".
373    ///
374    /// Whatever it does "SHALL NOT cause any changes to the state of the device that persist
375    /// after the last fabric is removed".
376    fn test_event_trigger(&self, trigger: u64) -> bool {
377        let _ = trigger;
378        false
379    }
380
381    /// POSIX time in milliseconds, for `TimeSnapshotResponse` (§11.12.7.3).
382    ///
383    /// `None` is the correct answer unless the node implements Time Synchronization and its
384    /// `UTCTime` is not null — those are the only two cases the specification allows a
385    /// non-null value in, and the field is there so a client can align its own clock with the
386    /// System Time that stamps this node's events.
387    fn posix_time_ms(&self) -> Option<u64> {
388        None
389    }
390}
391
392/// A device that reports nothing it is not obliged to.
393///
394/// Every mandatory attribute still answers — `RebootCount` 0, `UpTime` 0, `BootReason`
395/// `Unspecified`, no interfaces and no faults — which is a conformant, if uninformative,
396/// General Diagnostics cluster. Useful for a node under test and as a starting point.
397#[derive(Debug, Clone, Copy, Default)]
398pub struct Unknown;
399
400impl Diagnostics for Unknown {}
401
402/// The descriptor for an instance with these features.
403///
404/// Derived from the specification's own tables rather than written out. §11.12 gates
405/// `PayloadTestRequest` and its response on `DMTEST`, and a fixed command list would advertise
406/// them on every device — including the shipped ones, where §11.12.7.4 says the command must
407/// not be answerable at all.
408///
409/// `Optional` names the elements §11.12.6 leaves to the product: `TotalOperationalHours`,
410/// `BootReason`, the three fault lists and `DeviceLoadStatus`.
411///
412/// Returns [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does
413/// not define.
414pub fn conforming(
415    features: u32,
416    optional: &Optional<'_>,
417) -> crate::error::Result<Conforming<12, 4, 4, 4>> {
418    Conforming::new(
419        &crate::clusters::generated::general_diagnostics::CLUSTER,
420        features,
421        optional,
422    )
423}
424
425/// Everything §11.12.6 makes optional, for a device that reports all of it.
426pub const ALL_OPTIONAL: Optional<'static> = Optional {
427    attributes: &[
428        TOTAL_OPERATIONAL_HOURS,
429        BOOT_REASON,
430        ACTIVE_HARDWARE_FAULTS,
431        ACTIVE_RADIO_FAULTS,
432        ACTIVE_NETWORK_FAULTS,
433        DEVICE_LOAD_STATUS,
434    ],
435    commands: &[],
436    events: &[
437        HARDWARE_FAULT_CHANGE,
438        RADIO_FAULT_CHANGE,
439        NETWORK_FAULT_CHANGE,
440    ],
441};
442
443/// The General Diagnostics cluster (§11.12).
444#[derive(Debug)]
445pub struct GeneralDiagnostics<'a, D: Diagnostics> {
446    device: &'a D,
447    features: u32,
448    /// `TestEventTriggersEnabled` (§11.12.6): whether this device is in a test environment.
449    ///
450    /// Mutable because a device may be told to leave test mode, and read by both
451    /// `TestEventTrigger` and `PayloadTestRequest`.
452    triggers_enabled: RefCell<bool>,
453}
454
455impl<'a, D: Diagnostics> GeneralDiagnostics<'a, D> {
456    /// A cluster over a device's own diagnostics.
457    ///
458    /// `TestEventTriggersEnabled` starts **false** and stays false unless the device was
459    /// provisioned with an `EnableKey`: §11.12.7.1's whole point is that a shipped product is
460    /// unresponsive to these commands.
461    #[must_use]
462    pub fn new(device: &'a D, features: u32) -> Self {
463        let enabled = device.enable_key().is_some();
464        Self {
465            device,
466            features,
467            triggers_enabled: RefCell::new(enabled),
468        }
469    }
470
471    /// Whether test event triggers are currently answered (§11.12.6).
472    #[must_use]
473    pub fn triggers_enabled(&self) -> bool {
474        *self.triggers_enabled.borrow()
475    }
476
477    /// Leaves or re-enters test mode.
478    ///
479    /// Enabling without a provisioned key is [`Status::ConstraintError`]: there would be
480    /// nothing for a caller's `EnableKey` to match, and §11.12.7.1 reserves all-zeroes to mean
481    /// "no EnableKey is set" rather than "the key is zero".
482    pub fn set_triggers_enabled(&self, enabled: bool) -> Result<(), Status> {
483        if enabled && self.device.enable_key().is_none() {
484            return Err(Status::ConstraintError);
485        }
486        *self.triggers_enabled.borrow_mut() = enabled;
487        Ok(())
488    }
489
490    /// §11.12.7.1's `EnableKey` check, shared by both gated commands.
491    ///
492    /// Three ways to fail, and all three are `CONSTRAINT_ERROR` rather than anything more
493    /// specific — which is the specification's choice and a good one: distinguishing "no key
494    /// configured" from "wrong key" would tell a caller whether the device is a test unit.
495    fn check_enable_key(&self, offered: &[u8]) -> Result<(), StatusIb> {
496        if !self.triggers_enabled() {
497            return Err(Status::ConstraintError.into());
498        }
499        if offered.len() != SYMMETRIC_KEY_LENGTH_BYTES {
500            return Err(Status::ConstraintError.into());
501        }
502        // "The value of all zeroes is reserved to indicate that no EnableKey is set.
503        // Therefore, if the EnableKey field is received with all zeroes, this command SHALL
504        // FAIL with a response status of CONSTRAINT_ERROR." Checked before the comparison, so
505        // a device that somehow held a zero key still cannot be unlocked by one.
506        if offered.iter().all(|&b| b == 0) {
507            return Err(Status::ConstraintError.into());
508        }
509        let Some(configured) = self.device.enable_key() else {
510            return Err(Status::ConstraintError.into());
511        };
512        // `ct_eq`: a comparison that returns at the first differing octet turns 2¹²⁸ into
513        // 16 × 256 guesses.
514        if !ct_eq(offered, configured.as_bytes()) {
515            return Err(Status::ConstraintError.into());
516        }
517        Ok(())
518    }
519}
520
521/// Reads the two fields of `TestEventTrigger` (§11.12.7.1).
522fn decode_trigger(fields: &[u8]) -> Result<(heapless::Vec<u8, 32>, u64), Status> {
523    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
524    let element = reader
525        .next_element()
526        .map_err(|_| Status::InvalidAction)?
527        .ok_or(Status::InvalidAction)?;
528    if element.value.container() != Some(ContainerKind::Structure) {
529        return Err(Status::InvalidAction);
530    }
531    let mut key: Option<heapless::Vec<u8, 32>> = None;
532    let mut trigger = None;
533    loop {
534        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
535            return Err(Status::InvalidAction);
536        };
537        if field.value == Value::EndOfContainer {
538            break;
539        }
540        match field.tag.context() {
541            Some(0) => {
542                let bytes = field.octets().map_err(|_| Status::ConstraintError)?;
543                key = Some(heapless::Vec::from_slice(bytes).map_err(|_| Status::ConstraintError)?);
544            }
545            Some(1) => trigger = Some(field.unsigned().map_err(|_| Status::ConstraintError)?),
546            _ => {
547                reader
548                    .skip_value(&field)
549                    .map_err(|_| Status::InvalidAction)?;
550            }
551        }
552    }
553    match (key, trigger) {
554        (Some(key), Some(trigger)) => Ok((key, trigger)),
555        _ => Err(Status::InvalidCommand),
556    }
557}
558
559/// Reads the three fields of `PayloadTestRequest` (§11.12.7.4).
560fn decode_payload_test(fields: &[u8]) -> Result<(heapless::Vec<u8, 32>, u8, u16), Status> {
561    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
562    let element = reader
563        .next_element()
564        .map_err(|_| Status::InvalidAction)?
565        .ok_or(Status::InvalidAction)?;
566    if element.value.container() != Some(ContainerKind::Structure) {
567        return Err(Status::InvalidAction);
568    }
569    let mut key: Option<heapless::Vec<u8, 32>> = None;
570    let mut value = None;
571    let mut count = None;
572    loop {
573        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
574            return Err(Status::InvalidAction);
575        };
576        if field.value == Value::EndOfContainer {
577            break;
578        }
579        match field.tag.context() {
580            Some(0) => {
581                let bytes = field.octets().map_err(|_| Status::ConstraintError)?;
582                key = Some(heapless::Vec::from_slice(bytes).map_err(|_| Status::ConstraintError)?);
583            }
584            Some(1) => {
585                value = Some(
586                    u8::try_from(field.unsigned().map_err(|_| Status::ConstraintError)?)
587                        .map_err(|_| Status::ConstraintError)?,
588                );
589            }
590            Some(2) => {
591                let raw = field.unsigned().map_err(|_| Status::ConstraintError)?;
592                let raw = u16::try_from(raw).map_err(|_| Status::ConstraintError)?;
593                if raw > PAYLOAD_TEST_MAX {
594                    return Err(Status::ConstraintError);
595                }
596                count = Some(raw);
597            }
598            _ => {
599                reader
600                    .skip_value(&field)
601                    .map_err(|_| Status::InvalidAction)?;
602            }
603        }
604    }
605    match (key, value, count) {
606        (Some(key), Some(value), Some(count)) => Ok((key, value, count)),
607        _ => Err(Status::InvalidCommand),
608    }
609}
610
611impl<D: Diagnostics> ClusterHandler for GeneralDiagnostics<'_, D> {
612    fn read(
613        &self,
614        resolved: &Resolved<'_>,
615        ctx: &InteractionContext<'_>,
616        w: &mut TlvWriter<'_>,
617        tag: Tag,
618    ) -> Result<(), Status> {
619        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
620        match resolved.attribute {
621            NETWORK_INTERFACES => {
622                full(w.start_array(tag))?;
623                // A write that fails part way cannot be reported from inside the closure, so
624                // the first failure is remembered and returned after it.
625                let mut failure = None;
626                self.device.network_interfaces(&mut |interface| {
627                    if failure.is_none()
628                        && let Err(error) = interface.encode(w)
629                    {
630                        failure = Some(error);
631                    }
632                });
633                if failure.is_some() {
634                    return Err(Status::ResourceExhausted);
635                }
636                full(w.end_container())
637            }
638            REBOOT_COUNT => full(w.unsigned(tag, u64::from(self.device.reboot_count()))),
639            UP_TIME => full(w.unsigned(tag, self.device.up_time())),
640            TOTAL_OPERATIONAL_HOURS => {
641                let Some(hours) = self.device.total_operational_hours() else {
642                    return Err(Status::UnsupportedAttribute);
643                };
644                full(w.unsigned(tag, u64::from(hours)))
645            }
646            BOOT_REASON => full(w.unsigned(tag, self.device.boot_reason() as u64)),
647            ACTIVE_HARDWARE_FAULTS => {
648                full(w.start_array(tag))?;
649                let mut failure = false;
650                self.device.active_hardware_faults(&mut |fault| {
651                    failure |= w.unsigned(Tag::Anonymous, fault as u64).is_err();
652                });
653                if failure {
654                    return Err(Status::ResourceExhausted);
655                }
656                full(w.end_container())
657            }
658            ACTIVE_RADIO_FAULTS => {
659                full(w.start_array(tag))?;
660                let mut failure = false;
661                self.device.active_radio_faults(&mut |fault| {
662                    failure |= w.unsigned(Tag::Anonymous, fault as u64).is_err();
663                });
664                if failure {
665                    return Err(Status::ResourceExhausted);
666                }
667                full(w.end_container())
668            }
669            ACTIVE_NETWORK_FAULTS => {
670                full(w.start_array(tag))?;
671                let mut failure = false;
672                self.device.active_network_faults(&mut |fault| {
673                    failure |= w.unsigned(Tag::Anonymous, fault as u64).is_err();
674                });
675                if failure {
676                    return Err(Status::ResourceExhausted);
677                }
678                full(w.end_container())
679            }
680            TEST_EVENT_TRIGGERS_ENABLED => full(w.bool(tag, self.triggers_enabled())),
681            DEVICE_LOAD_STATUS => {
682                let Some(load) = self.device.device_load(ctx) else {
683                    return Err(Status::UnsupportedAttribute);
684                };
685                full(load.encode(w, tag))
686            }
687            _ => Err(Status::UnsupportedAttribute),
688        }
689    }
690
691    fn invoke(
692        &self,
693        resolved: &ResolvedCommand<'_>,
694        fields: Option<&[u8]>,
695        ctx: &InteractionContext<'_>,
696        w: &mut TlvWriter<'_>,
697        tag: Tag,
698    ) -> Result<Option<CommandId>, StatusIb> {
699        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
700        match resolved.command.id {
701            TEST_EVENT_TRIGGER => {
702                let (key, trigger) =
703                    decode_trigger(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
704                self.check_enable_key(&key)?;
705                // "If the value of EventTrigger received is not supported by the receiving
706                // Node, this command SHALL fail with a status code of INVALID_COMMAND."
707                if !self.device.test_event_trigger(trigger) {
708                    return Err(Status::InvalidCommand.into());
709                }
710                Ok(None)
711            }
712            TIME_SNAPSHOT => {
713                // "all fields SHALL be gathered as close together in time as possible, so that
714                // the time jitter between the values is minimized" — which is why System Time
715                // comes from the context's single instant rather than a fresh clock read.
716                full(w.start_structure(tag))?;
717                full(w.unsigned(Tag::Context(0), ctx.now.as_millis()))?;
718                match self.device.posix_time_ms() {
719                    Some(posix) => full(w.unsigned(Tag::Context(1), posix))?,
720                    None => full(w.null(Tag::Context(1)))?,
721                }
722                full(w.end_container())?;
723                Ok(Some(TIME_SNAPSHOT_RESPONSE))
724            }
725            PAYLOAD_TEST_REQUEST => {
726                if self.features & FEATURE_DATA_MODEL_TEST == 0 {
727                    return Err(Status::UnsupportedCommand.into());
728                }
729                let (key, value, count) =
730                    decode_payload_test(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
731                self.check_enable_key(&key)?;
732
733                // "If the response is too large to send, the server SHALL fail the command and
734                // respond with a response status of RESOURCE_EXHAUSTED" — which is the whole
735                // point of the command: it exists so a certification test can find the size at
736                // which this device starts refusing.
737                full(w.start_structure(tag))?;
738                w.octets_fill(Tag::Context(0), usize::from(count), value)
739                    .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
740                full(w.end_container())?;
741                Ok(Some(PAYLOAD_TEST_RESPONSE))
742            }
743            _ => Err(Status::UnsupportedCommand.into()),
744        }
745    }
746}
747
748/// So a tuple of clusters can dispatch to it by id.
749impl<D: Diagnostics> Cluster for GeneralDiagnostics<'_, D> {
750    const ID: ClusterId = ID;
751}