Skip to main content

matter_kit/clusters/
software_diagnostics.rs

1//! Software Diagnostics, cluster `0x0034` (Core §11.13).
2//!
3//! > The Software Diagnostics Cluster attempts to centralize all metrics that are relevant to
4//! > the software that may be running on a Node.
5//!
6//! Heap and stack, essentially — how much is free now and how little has ever been free. On
7//! the kind of device this crate is built for, the second number is the one that matters: a
8//! node with 32 KB of RAM does not run out of memory gradually, it runs out once, three weeks
9//! after shipping, in a code path nobody was watching. `CurrentHeapHighWatermark` and
10//! `StackFreeMinimum` are the record of how close it came.
11//!
12//! # A crate with no allocator still has something to report
13//!
14//! `matter-kit` is no-alloc, so nothing *here* has a heap. The metrics are the device's: a
15//! node that runs an RTOS with a heap for its application reports that heap, and one that has
16//! none reports nothing and declares neither attribute. Which is why every method of
17//! [`SoftwareMetrics`] returns an `Option` and the absent case is
18//! [`Status::UnsupportedAttribute`] rather than a zero — "0 bytes free" and "no heap" read the
19//! same to a client and mean opposite things.
20
21use crate::dm::spec::{Conforming, Optional};
22use crate::dm::{Resolved, ResolvedCommand};
23use crate::im::{
24    AttributeId, ClusterHandler, ClusterId, CommandId, EventId, InteractionContext, Status,
25    StatusIb,
26};
27use crate::tlv::{Tag, TlvWriter};
28
29use super::Cluster;
30
31/// `0x0034` (§11.13.3).
32pub const ID: ClusterId = 0x0034;
33
34/// The revision §11.13.1's table ends on.
35pub const REVISION: u16 = 1;
36
37/// `WTRMRK` (§11.13.4) — "Node makes available the metrics for high watermark related to
38/// memory consumption".
39pub const FEATURE_WATERMARKS: u32 = 1 << 0;
40
41/// `ThreadMetrics` (§11.13.6.1) — `list[ThreadMetricsStruct]`, max 64, `RV C`.
42pub const THREAD_METRICS: AttributeId = 0x0000;
43/// `CurrentHeapFree` (§11.13.6.2) — `uint64`, `RV C`.
44pub const CURRENT_HEAP_FREE: AttributeId = 0x0001;
45/// `CurrentHeapUsed` (§11.13.6.3) — `uint64`, `RV C`.
46pub const CURRENT_HEAP_USED: AttributeId = 0x0002;
47/// `CurrentHeapHighWatermark` (§11.13.6.4) — `uint64`, `RV C`, `WTRMRK`.
48pub const CURRENT_HEAP_HIGH_WATERMARK: AttributeId = 0x0003;
49
50/// `ResetWatermarks` (§11.13.7.1) — Manage, `WTRMRK`.
51pub const RESET_WATERMARKS: CommandId = 0x00;
52
53/// `SoftwareFault` (§11.13.8.1) — INFO.
54pub const SOFTWARE_FAULT: EventId = 0x00;
55
56/// One entry of `ThreadMetrics` (§11.13.5.1) — a *software* thread, not a Thread network.
57#[derive(Debug, Clone, Copy, Default)]
58pub struct ThreadMetrics<'a> {
59    /// "a server-assigned per-thread unique ID that is constant for the duration of the
60    /// thread. Efforts SHOULD be made to avoid reusing ID values when possible."
61    pub id: u64,
62    /// "a vendor defined name or prefix of the software thread", at most 8 octets.
63    pub name: &'a str,
64    /// Stack bytes not currently in use, or `None` to omit the optional field.
65    pub stack_free_current: Option<u32>,
66    /// The least that has been free "between the current time and this attribute being reset
67    /// or initialized" — the number that says how close the thread came to overflowing.
68    pub stack_free_minimum: Option<u32>,
69    /// Bytes allocated to the thread's stack.
70    pub stack_size: Option<u32>,
71}
72
73impl ThreadMetrics<'_> {
74    fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
75        w.start_structure(Tag::Anonymous)?;
76        w.unsigned(Tag::Context(0), self.id)?;
77        if !self.name.is_empty() {
78            w.utf8(Tag::Context(1), self.name)?;
79        }
80        if let Some(value) = self.stack_free_current {
81            w.unsigned(Tag::Context(2), u64::from(value))?;
82        }
83        if let Some(value) = self.stack_free_minimum {
84            w.unsigned(Tag::Context(3), u64::from(value))?;
85        }
86        if let Some(value) = self.stack_size {
87            w.unsigned(Tag::Context(4), u64::from(value))?;
88        }
89        w.end_container()
90    }
91}
92
93/// What the device's runtime knows about its own memory.
94///
95/// Every method returns `Option` and defaults to `None`, because §11.13.6 marks every
96/// attribute optional and a node without a heap has nothing to say about one. Reporting zero
97/// instead would be a device that looks permanently out of memory.
98pub trait SoftwareMetrics {
99    /// Each active software thread in turn (§11.13.6.1).
100    fn thread_metrics(&self, emit: &mut dyn FnMut(&ThreadMetrics<'_>)) {
101        let _ = emit;
102    }
103
104    /// Heap bytes free for allocation. "The effective amount MAY be smaller due to heap
105    /// fragmentation or other reasons" — so this is an upper bound, not a promise.
106    fn current_heap_free(&self) -> Option<u64> {
107        None
108    }
109
110    /// Heap bytes currently in use.
111    fn current_heap_used(&self) -> Option<u64> {
112        None
113    }
114
115    /// The most heap that has ever been in use (§11.13.6.4). "This value SHALL only be reset
116    /// upon a Node reboot or upon receiving of the ResetWatermarks command."
117    fn current_heap_high_watermark(&self) -> Option<u64> {
118        None
119    }
120
121    /// §11.13.7.1's `ResetWatermarks`.
122    ///
123    /// The specification is exact about what "reset" means, and it is not zero: "the server
124    /// SHALL set the value of the CurrentHeapHighWatermark attribute to the value of the
125    /// CurrentHeapUsed attribute", and each thread's `StackFreeMinimum` to its
126    /// `StackFreeCurrent`. A watermark reset to zero would claim the node had once used no
127    /// memory at all, and would then never rise again until usage exceeded the real peak.
128    fn reset_watermarks(&self) {}
129}
130
131/// A node that reports no software metrics at all.
132///
133/// Correct for a `no_std`, no-alloc device with no application heap, which is what this crate
134/// is built for — and a conformant Software Diagnostics cluster, since §11.13.6 makes every
135/// attribute optional.
136#[derive(Debug, Clone, Copy, Default)]
137pub struct NoMetrics;
138
139impl SoftwareMetrics for NoMetrics {}
140
141/// The descriptor for an instance with these features.
142///
143/// Derived from the specification's own tables. §11.13.6 marks every attribute optional and
144/// gates `CurrentHeapHighWatermark` and `ResetWatermarks` on `WTRMRK`, so what a device serves
145/// is almost entirely its own choice — and a fixed list would make that choice for it.
146///
147/// Returns [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does
148/// not define.
149pub fn conforming(
150    features: u32,
151    optional: &Optional<'_>,
152) -> crate::error::Result<Conforming<4, 1, 0, 1>> {
153    Conforming::new(
154        &crate::clusters::generated::software_diagnostics::CLUSTER,
155        features,
156        optional,
157    )
158}
159
160/// Everything §11.13.6 makes optional, for a runtime that reports all of it.
161pub const ALL_OPTIONAL: Optional<'static> = Optional {
162    attributes: &[
163        THREAD_METRICS,
164        CURRENT_HEAP_FREE,
165        CURRENT_HEAP_USED,
166        CURRENT_HEAP_HIGH_WATERMARK,
167    ],
168    commands: &[],
169    events: &[SOFTWARE_FAULT],
170};
171
172/// The Software Diagnostics cluster (§11.13).
173#[derive(Debug)]
174pub struct SoftwareDiagnostics<'a, M: SoftwareMetrics> {
175    metrics: &'a M,
176    features: u32,
177}
178
179impl<'a, M: SoftwareMetrics> SoftwareDiagnostics<'a, M> {
180    /// A cluster over a runtime's own metrics.
181    #[must_use]
182    pub const fn new(metrics: &'a M, features: u32) -> Self {
183        Self { metrics, features }
184    }
185
186    const fn watermarks(&self) -> bool {
187        self.features & FEATURE_WATERMARKS != 0
188    }
189}
190
191impl<M: SoftwareMetrics> ClusterHandler for SoftwareDiagnostics<'_, M> {
192    fn read(
193        &self,
194        resolved: &Resolved<'_>,
195        _ctx: &InteractionContext<'_>,
196        w: &mut TlvWriter<'_>,
197        tag: Tag,
198    ) -> Result<(), Status> {
199        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
200        match resolved.attribute {
201            THREAD_METRICS => {
202                full(w.start_array(tag))?;
203                let mut failure = false;
204                self.metrics.thread_metrics(&mut |thread| {
205                    failure |= thread.encode(w).is_err();
206                });
207                if failure {
208                    return Err(Status::ResourceExhausted);
209                }
210                full(w.end_container())
211            }
212            CURRENT_HEAP_FREE => {
213                let Some(value) = self.metrics.current_heap_free() else {
214                    return Err(Status::UnsupportedAttribute);
215                };
216                full(w.unsigned(tag, value))
217            }
218            CURRENT_HEAP_USED => {
219                let Some(value) = self.metrics.current_heap_used() else {
220                    return Err(Status::UnsupportedAttribute);
221                };
222                full(w.unsigned(tag, value))
223            }
224            CURRENT_HEAP_HIGH_WATERMARK => {
225                // §11.13.6's conformance column makes this one `WTRMRK` rather than `O`: the
226                // feature bit is the promise that it exists, so serving it without declaring
227                // the feature would contradict the `FeatureMap` a client read first.
228                if !self.watermarks() {
229                    return Err(Status::UnsupportedAttribute);
230                }
231                let Some(value) = self.metrics.current_heap_high_watermark() else {
232                    return Err(Status::UnsupportedAttribute);
233                };
234                full(w.unsigned(tag, value))
235            }
236            _ => Err(Status::UnsupportedAttribute),
237        }
238    }
239
240    fn invoke(
241        &self,
242        resolved: &ResolvedCommand<'_>,
243        _fields: Option<&[u8]>,
244        _ctx: &InteractionContext<'_>,
245        _w: &mut TlvWriter<'_>,
246        _tag: Tag,
247    ) -> Result<Option<CommandId>, StatusIb> {
248        if resolved.command.id != RESET_WATERMARKS {
249            return Err(Status::UnsupportedCommand.into());
250        }
251        if !self.watermarks() {
252            return Err(Status::UnsupportedCommand.into());
253        }
254        self.metrics.reset_watermarks();
255        Ok(None)
256    }
257}
258
259/// So a tuple of clusters can dispatch to it by id.
260impl<M: SoftwareMetrics> Cluster for SoftwareDiagnostics<'_, M> {
261    const ID: ClusterId = ID;
262}