Skip to main content

matter_kit/clusters/
thread_network_diagnostics.rs

1//! Thread Network Diagnostics, cluster `0x0035` (Core §11.14).
2//!
3//! The largest of the three network diagnostics clusters — sixty-five attributes — and the same
4//! shape as the other two: every number belongs to a radio and a Thread stack this crate does
5//! not own, so the cluster is a [`ThreadDriver`] the integrator implements. It needs no radio to
6//! compile or to test; the `openthread` crate is one source for the numbers, and nothing here
7//! depends on it.
8//!
9//! # Three kinds of attribute, and three shapes in the trait
10//!
11//! * **The network's state** — `Channel`, `RoutingRole`, `NetworkName`, the timestamps — is
12//!   mandatory and nullable. A driver returns [`Option`], where `None` is the specification's
13//!   `null`: the Thread interface is not configured or operational. There is no third answer,
14//!   because a Thread device reports these or is not a Thread device.
15//! * **The tables** — `NeighborTable`, `RouteTable`, `ActiveNetworkFaultsList` — are mandatory
16//!   lists, and empty is a perfectly good answer. A driver returns a slice, which is also the
17//!   only list shape a `no_std` crate can hand over without allocating.
18//! * **The counters** are conditional on §11.14.4's features *and* optional within them. They
19//!   arrive as [`MacCounters`] and [`MleCounters`], one struct each, because that is how a
20//!   Thread stack hands them over and because forty-two separate trait methods would be
21//!   forty-two chances to wire one to the wrong attribute. A field left `None` is a counter the
22//!   device does not keep, and it belongs out of the [`Optional`] list too.
23//!
24//!   `OverrunCount` is the exception: §11.14.6 makes it mandatory within `ERRCNT` and does not
25//!   make it nullable, so it is a plain `u64` a device claiming `ERRCNT` has promised to count.
26//!
27//! ```
28//! use matter_kit::clusters::thread_network_diagnostics::{
29//!     RoutingRoleEnum, ThreadDriver, ThreadNetworkDiagnostics,
30//! };
31//!
32//! struct Stack;
33//! impl ThreadDriver for Stack {
34//!     fn channel(&self) -> Option<u16> { Some(15) }
35//!     fn routing_role(&self) -> Option<RoutingRoleEnum> { Some(RoutingRoleEnum::Router) }
36//!     fn network_name(&self) -> Option<&str> { Some("matter-kit") }
37//!     fn pan_id(&self) -> Option<u16> { Some(0x1234) }
38//!     fn extended_pan_id(&self) -> Option<u64> { Some(0xDEAD_BEEF_0000_0001) }
39//! }
40//!
41//! // No feature bits: this driver reports the network and counts nothing.
42//! let cluster = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, 0);
43//! # let _ = cluster;
44//! ```
45
46use core::cell::RefCell;
47
48use crate::dm::spec::{Conforming, Optional};
49use crate::dm::{EventPriority, Resolved, ResolvedCommand};
50use crate::im::{
51    AttributeId, ClusterHandler, ClusterId, CommandId, EventId, InteractionContext, Status,
52    StatusIb,
53};
54use crate::tlv::{Tag, TlvWriter, ToTlv};
55
56use super::Cluster;
57use crate::clusters::generated::thread_network_diagnostics as spec_thread;
58
59pub use spec_thread::{
60    ConnectionStatusEnum, ID, NeighborTableStruct, NetworkFaultEnum, OperationalDatasetComponents,
61    PICS, REVISION, RouteTableStruct, RoutingRoleEnum, SecurityPolicy, feature,
62};
63
64use spec_thread::attribute::{
65    ACTIVE_NETWORK_FAULTS_LIST, ACTIVE_TIMESTAMP, CHANNEL, CHANNEL_PAGE0_MASK, DATA_VERSION, DELAY,
66    EXT_ADDRESS, EXTENDED_PAN_ID, LEADER_ROUTER_ID, MESH_LOCAL_PREFIX, NEIGHBOR_TABLE,
67    NETWORK_NAME, OPERATIONAL_DATASET_COMPONENTS, OVERRUN_COUNT, PAN_ID, PARTITION_ID,
68    PENDING_TIMESTAMP, RLOC16, ROUTE_TABLE, ROUTING_ROLE, SECURITY_POLICY, STABLE_DATA_VERSION,
69    WEIGHTING,
70};
71use spec_thread::attribute::{
72    ATTACH_ATTEMPT_COUNT, BETTER_PARTITION_ATTACH_ATTEMPT_COUNT, CHILD_ROLE_COUNT,
73    DETACHED_ROLE_COUNT, LEADER_ROLE_COUNT, PARENT_CHANGE_COUNT, PARTITION_ID_CHANGE_COUNT,
74    ROUTER_ROLE_COUNT,
75};
76use spec_thread::attribute::{
77    RX_ADDRESS_FILTERED_COUNT, RX_BEACON_COUNT, RX_BEACON_REQUEST_COUNT, RX_BROADCAST_COUNT,
78    RX_DATA_COUNT, RX_DATA_POLL_COUNT, RX_DEST_ADDR_FILTERED_COUNT, RX_DUPLICATED_COUNT,
79    RX_ERR_FCS_COUNT, RX_ERR_INVALID_SRC_ADDR_COUNT, RX_ERR_NO_FRAME_COUNT, RX_ERR_OTHER_COUNT,
80    RX_ERR_SEC_COUNT, RX_ERR_UNKNOWN_NEIGHBOR_COUNT, RX_OTHER_COUNT, RX_TOTAL_COUNT,
81    RX_UNICAST_COUNT, TX_ACK_REQUESTED_COUNT, TX_ACKED_COUNT, TX_BEACON_COUNT,
82    TX_BEACON_REQUEST_COUNT, TX_BROADCAST_COUNT, TX_DATA_COUNT, TX_DATA_POLL_COUNT,
83    TX_DIRECT_MAX_RETRY_EXPIRY_COUNT, TX_ERR_ABORT_COUNT, TX_ERR_BUSY_CHANNEL_COUNT,
84    TX_ERR_CCA_COUNT, TX_INDIRECT_MAX_RETRY_EXPIRY_COUNT, TX_NO_ACK_REQUESTED_COUNT,
85    TX_OTHER_COUNT, TX_RETRY_COUNT, TX_TOTAL_COUNT, TX_UNICAST_COUNT,
86};
87use spec_thread::command::RESET_COUNTS;
88pub use spec_thread::event::{CONNECTION_STATUS, NETWORK_FAULT_CHANGE};
89
90/// The `MACCNT` counters of §11.14.6, as a Thread stack hands them over.
91///
92/// Every field is optional: §11.14.4's `MACCNT` says the device *may* report these, not that it
93/// reports all of them. `None` is "this device does not keep that counter", and the same
94/// counter must then be left out of the [`Optional`] list the descriptor is built from — a
95/// value answered for an attribute that is not in `AttributeList` is a number no client asked
96/// for and no client can find.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
98pub struct MacCounters {
99    /// `TxTotalCount` (§11.14.6.23).
100    pub tx_total: Option<u32>,
101    /// `TxUnicastCount` (§11.14.6.24).
102    pub tx_unicast: Option<u32>,
103    /// `TxBroadcastCount` (§11.14.6.25).
104    pub tx_broadcast: Option<u32>,
105    /// `TxAckRequestedCount` (§11.14.6.26).
106    pub tx_ack_requested: Option<u32>,
107    /// `TxAckedCount` (§11.14.6.27).
108    pub tx_acked: Option<u32>,
109    /// `TxNoAckRequestedCount` (§11.14.6.28).
110    pub tx_no_ack_requested: Option<u32>,
111    /// `TxDataCount` (§11.14.6.29).
112    pub tx_data: Option<u32>,
113    /// `TxDataPollCount` (§11.14.6.30).
114    pub tx_data_poll: Option<u32>,
115    /// `TxBeaconCount` (§11.14.6.31).
116    pub tx_beacon: Option<u32>,
117    /// `TxBeaconRequestCount` (§11.14.6.32).
118    pub tx_beacon_request: Option<u32>,
119    /// `TxOtherCount` (§11.14.6.33).
120    pub tx_other: Option<u32>,
121    /// `TxRetryCount` (§11.14.6.34).
122    pub tx_retry: Option<u32>,
123    /// `TxDirectMaxRetryExpiryCount` (§11.14.6.35).
124    pub tx_direct_max_retry_expiry: Option<u32>,
125    /// `TxIndirectMaxRetryExpiryCount` (§11.14.6.36).
126    pub tx_indirect_max_retry_expiry: Option<u32>,
127    /// `TxErrCcaCount` (§11.14.6.37).
128    pub tx_err_cca: Option<u32>,
129    /// `TxErrAbortCount` (§11.14.6.38).
130    pub tx_err_abort: Option<u32>,
131    /// `TxErrBusyChannelCount` (§11.14.6.39).
132    pub tx_err_busy_channel: Option<u32>,
133    /// `RxTotalCount` (§11.14.6.40).
134    pub rx_total: Option<u32>,
135    /// `RxUnicastCount` (§11.14.6.41).
136    pub rx_unicast: Option<u32>,
137    /// `RxBroadcastCount` (§11.14.6.42).
138    pub rx_broadcast: Option<u32>,
139    /// `RxDataCount` (§11.14.6.43).
140    pub rx_data: Option<u32>,
141    /// `RxDataPollCount` (§11.14.6.44).
142    pub rx_data_poll: Option<u32>,
143    /// `RxBeaconCount` (§11.14.6.45).
144    pub rx_beacon: Option<u32>,
145    /// `RxBeaconRequestCount` (§11.14.6.46).
146    pub rx_beacon_request: Option<u32>,
147    /// `RxOtherCount` (§11.14.6.47).
148    pub rx_other: Option<u32>,
149    /// `RxAddressFilteredCount` (§11.14.6.48).
150    pub rx_address_filtered: Option<u32>,
151    /// `RxDestAddrFilteredCount` (§11.14.6.49).
152    pub rx_dest_addr_filtered: Option<u32>,
153    /// `RxDuplicatedCount` (§11.14.6.50).
154    pub rx_duplicated: Option<u32>,
155    /// `RxErrNoFrameCount` (§11.14.6.51).
156    pub rx_err_no_frame: Option<u32>,
157    /// `RxErrUnknownNeighborCount` (§11.14.6.52).
158    pub rx_err_unknown_neighbor: Option<u32>,
159    /// `RxErrInvalidSrcAddrCount` (§11.14.6.53).
160    pub rx_err_invalid_src_addr: Option<u32>,
161    /// `RxErrSecCount` (§11.14.6.54).
162    pub rx_err_sec: Option<u32>,
163    /// `RxErrFcsCount` (§11.14.6.55).
164    pub rx_err_fcs: Option<u32>,
165    /// `RxErrOtherCount` (§11.14.6.56).
166    pub rx_err_other: Option<u32>,
167}
168
169/// The `MLECNT` counters of §11.14.6 — how often this node changed role, re-attached, or
170/// followed a better partition.
171///
172/// Optional in the same way [`MacCounters`] is, and for the same reason.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
174pub struct MleCounters {
175    /// `DetachedRoleCount` (§11.14.6.15).
176    pub detached_role: Option<u16>,
177    /// `ChildRoleCount` (§11.14.6.16).
178    pub child_role: Option<u16>,
179    /// `RouterRoleCount` (§11.14.6.17).
180    pub router_role: Option<u16>,
181    /// `LeaderRoleCount` (§11.14.6.18).
182    pub leader_role: Option<u16>,
183    /// `AttachAttemptCount` (§11.14.6.19).
184    pub attach_attempt: Option<u16>,
185    /// `PartitionIdChangeCount` (§11.14.6.20).
186    pub partition_id_change: Option<u16>,
187    /// `BetterPartitionAttachAttemptCount` (§11.14.6.21).
188    pub better_partition_attach_attempt: Option<u16>,
189    /// `ParentChangeCount` (§11.14.6.22).
190    pub parent_change: Option<u16>,
191}
192
193/// What a device's Thread stack can report (§11.14.6).
194///
195/// Every method has a default, so an integrator implements only what the stack exposes. The
196/// defaults are the conservative ones: `null` for the network state, empty for the tables, and
197/// no counters at all.
198pub trait ThreadDriver {
199    /// `Channel` (§11.14.6.1) — the 802.15.4 channel in use.
200    fn channel(&self) -> Option<u16> {
201        None
202    }
203
204    /// `RoutingRole` (§11.14.6.2).
205    ///
206    /// [`RoutingRoleEnum::Unassigned`] and `null` are not the same answer: the first is a
207    /// configured interface with no role yet, the second is no configured interface.
208    fn routing_role(&self) -> Option<RoutingRoleEnum> {
209        None
210    }
211
212    /// `NetworkName` (§11.14.6.3), at most sixteen octets.
213    fn network_name(&self) -> Option<&str> {
214        None
215    }
216
217    /// `PanId` (§11.14.6.4).
218    fn pan_id(&self) -> Option<u16> {
219        None
220    }
221
222    /// `ExtendedPanId` (§11.14.6.5).
223    fn extended_pan_id(&self) -> Option<u64> {
224        None
225    }
226
227    /// `MeshLocalPrefix` (§11.14.6.6) — an `ipv6pre`: one length octet, then the prefix.
228    fn mesh_local_prefix(&self) -> Option<&[u8]> {
229        None
230    }
231
232    /// `OverrunCount` (§11.14.6.7) — packets dropped for want of buffer memory. `ERRCNT`.
233    ///
234    /// The one counter here that is mandatory within its feature and not nullable, so it is a
235    /// plain number: a device claiming `ERRCNT` has promised to count it.
236    fn overrun_count(&self) -> u64 {
237        0
238    }
239
240    /// `NeighborTable` (§11.14.6.8). Empty is a legitimate answer and `null` is not one.
241    fn neighbors(&self) -> &[NeighborTableStruct] {
242        &[]
243    }
244
245    /// `RouteTable` (§11.14.6.9).
246    fn routes(&self) -> &[RouteTableStruct] {
247        &[]
248    }
249
250    /// `PartitionId` (§11.14.6.10).
251    fn partition_id(&self) -> Option<u32> {
252        None
253    }
254
255    /// `Weighting` (§11.14.6.11) — the leader weight this node's partition is running at.
256    fn weighting(&self) -> Option<u16> {
257        None
258    }
259
260    /// `DataVersion` (§11.14.6.12).
261    fn data_version(&self) -> Option<u16> {
262        None
263    }
264
265    /// `StableDataVersion` (§11.14.6.13).
266    fn stable_data_version(&self) -> Option<u16> {
267        None
268    }
269
270    /// `LeaderRouterId` (§11.14.6.14).
271    fn leader_router_id(&self) -> Option<u8> {
272        None
273    }
274
275    /// The `MLECNT` counters (§11.14.6).
276    fn mle_counters(&self) -> MleCounters {
277        MleCounters::EMPTY
278    }
279
280    /// The `MACCNT` counters (§11.14.6).
281    ///
282    /// Called once per counter read, so a driver that has to ask the radio should cache: a
283    /// wildcard read of this cluster asks for thirty-four of them in a row.
284    fn mac_counters(&self) -> MacCounters {
285        MacCounters::EMPTY
286    }
287
288    /// `ActiveTimestamp` (§11.14.6.57) of the Active Operational Dataset.
289    fn active_timestamp(&self) -> Option<u64> {
290        None
291    }
292
293    /// `PendingTimestamp` (§11.14.6.58) of the Pending Operational Dataset.
294    fn pending_timestamp(&self) -> Option<u64> {
295        None
296    }
297
298    /// `Delay` (§11.14.6.59) before a pending dataset is adopted, in milliseconds.
299    fn delay(&self) -> Option<u32> {
300        None
301    }
302
303    /// `SecurityPolicy` (§11.14.6.60).
304    fn security_policy(&self) -> Option<SecurityPolicy> {
305        None
306    }
307
308    /// `ChannelPage0Mask` (§11.14.6.61) — the channel mask as an octet string.
309    fn channel_page0_mask(&self) -> Option<&[u8]> {
310        None
311    }
312
313    /// `OperationalDatasetComponents` (§11.14.6.62) — which parts of the dataset are present.
314    fn operational_dataset_components(&self) -> Option<OperationalDatasetComponents> {
315        None
316    }
317
318    /// `ActiveNetworkFaultsList` (§11.14.6.63) — the faults currently detected, if any.
319    fn active_network_faults(&self) -> &[NetworkFaultEnum] {
320        &[]
321    }
322
323    /// `ExtAddress` (§11.14.6.64) — the node's IEEE 802.15.4 extended address.
324    fn ext_address(&self) -> Option<u64> {
325        None
326    }
327
328    /// `Rloc16` (§11.14.6.65) — the node's routing locator.
329    fn rloc16(&self) -> Option<u16> {
330        None
331    }
332
333    /// `ResetCounts` (§11.14.7.1): zero every counter this cluster reports.
334    ///
335    /// The default does nothing, which is correct for a driver that reports no counters. One
336    /// that does must implement this, or a client's reset silently fails.
337    fn reset_counts(&self) {}
338}
339
340impl MacCounters {
341    /// A device that keeps none of them.
342    pub const EMPTY: Self = Self {
343        tx_total: None,
344        tx_unicast: None,
345        tx_broadcast: None,
346        tx_ack_requested: None,
347        tx_acked: None,
348        tx_no_ack_requested: None,
349        tx_data: None,
350        tx_data_poll: None,
351        tx_beacon: None,
352        tx_beacon_request: None,
353        tx_other: None,
354        tx_retry: None,
355        tx_direct_max_retry_expiry: None,
356        tx_indirect_max_retry_expiry: None,
357        tx_err_cca: None,
358        tx_err_abort: None,
359        tx_err_busy_channel: None,
360        rx_total: None,
361        rx_unicast: None,
362        rx_broadcast: None,
363        rx_data: None,
364        rx_data_poll: None,
365        rx_beacon: None,
366        rx_beacon_request: None,
367        rx_other: None,
368        rx_address_filtered: None,
369        rx_dest_addr_filtered: None,
370        rx_duplicated: None,
371        rx_err_no_frame: None,
372        rx_err_unknown_neighbor: None,
373        rx_err_invalid_src_addr: None,
374        rx_err_sec: None,
375        rx_err_fcs: None,
376        rx_err_other: None,
377    };
378}
379
380impl MleCounters {
381    /// A device that keeps none of them.
382    pub const EMPTY: Self = Self {
383        detached_role: None,
384        child_role: None,
385        router_role: None,
386        leader_role: None,
387        attach_attempt: None,
388        partition_id_change: None,
389        better_partition_attach_attempt: None,
390        parent_change: None,
391    };
392}
393
394/// The driver for a device with no Thread metrics to report.
395#[derive(Debug, Clone, Copy, Default)]
396pub struct Unknown;
397
398impl ThreadDriver for Unknown {}
399
400/// One of §11.14.8's events, as the Thread stack noticed it.
401///
402/// The cluster collects these and the device drains them into its own event store, because
403/// the store belongs to the node and not to any one cluster.
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum Event {
406    /// §11.14.8.1 `ConnectionStatus`, on every transition between connected and not.
407    ConnectionStatus(ConnectionStatusEnum),
408    /// §11.14.8.2 `NetworkFaultChange`, carrying both sides of the change.
409    NetworkFaultChange {
410        /// `Current` — the faults detected now.
411        current: heapless::Vec<NetworkFaultEnum, 4>,
412        /// `Previous` — the faults detected before this change.
413        previous: heapless::Vec<NetworkFaultEnum, 4>,
414    },
415}
416
417impl Event {
418    /// The event id this record is reported under.
419    #[must_use]
420    pub const fn id(&self) -> EventId {
421        match self {
422            Self::ConnectionStatus(_) => CONNECTION_STATUS,
423            Self::NetworkFaultChange { .. } => NETWORK_FAULT_CHANGE,
424        }
425    }
426
427    /// Both events in §11.14.8 are `INFO` priority.
428    #[must_use]
429    pub const fn priority(&self) -> EventPriority {
430        EventPriority::Info
431    }
432
433    /// Writes the event's fields as an `EventDataIB`'s `Data` (§10.6.13).
434    ///
435    /// # Errors
436    ///
437    /// Whatever the writer returns when the buffer is too small.
438    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> crate::error::Result<()> {
439        w.start_structure(tag)?;
440        match self {
441            Self::ConnectionStatus(status) => {
442                w.unsigned(Tag::Context(0), u64::from(status.value()))?;
443            }
444            Self::NetworkFaultChange { current, previous } => {
445                faults(w, Tag::Context(0), current)?;
446                faults(w, Tag::Context(1), previous)?;
447            }
448        }
449        w.end_container()
450    }
451}
452
453/// A `list[NetworkFaultEnum]`, which both `ActiveNetworkFaultsList` and `NetworkFaultChange`
454/// are made of.
455fn faults(w: &mut TlvWriter<'_>, tag: Tag, list: &[NetworkFaultEnum]) -> crate::error::Result<()> {
456    w.start_array(tag)?;
457    for fault in list {
458        w.unsigned(Tag::Anonymous, u64::from(fault.value()))?;
459    }
460    w.end_container()
461}
462
463/// Builds a descriptor for a feature map and the optional elements a product implements.
464///
465/// The `Optional` list is doing real work here: forty-two of the sixty-five attributes are
466/// optional within their feature, so this is where a product says which counters it actually
467/// keeps. [`ALL_OPTIONAL`] is the everything-reported end of that range and a poor default for
468/// a real device.
469///
470/// # Errors
471///
472/// [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does not define,
473/// or [`NoSpace`](crate::ErrorCode::NoSpace) if the selection does not fit.
474pub fn conforming(
475    features: u32,
476    optional: &Optional<'_>,
477) -> crate::error::Result<Conforming<70, 1, 0, 2>> {
478    Conforming::new(&spec_thread::CLUSTER, features, optional)
479}
480
481/// Every counter §11.14.4's `MLECNT` and `MACCNT` features bring, each of which §11.14.6 leaves
482/// optional within its feature.
483///
484/// A real product names the ones it actually keeps; this is the everything-reported end of the
485/// range and a poor default for a device.
486pub const COUNTERS: &[AttributeId] = &[
487    DETACHED_ROLE_COUNT,
488    CHILD_ROLE_COUNT,
489    ROUTER_ROLE_COUNT,
490    LEADER_ROLE_COUNT,
491    ATTACH_ATTEMPT_COUNT,
492    PARTITION_ID_CHANGE_COUNT,
493    BETTER_PARTITION_ATTACH_ATTEMPT_COUNT,
494    PARENT_CHANGE_COUNT,
495    TX_TOTAL_COUNT,
496    TX_UNICAST_COUNT,
497    TX_BROADCAST_COUNT,
498    TX_ACK_REQUESTED_COUNT,
499    TX_ACKED_COUNT,
500    TX_NO_ACK_REQUESTED_COUNT,
501    TX_DATA_COUNT,
502    TX_DATA_POLL_COUNT,
503    TX_BEACON_COUNT,
504    TX_BEACON_REQUEST_COUNT,
505    TX_OTHER_COUNT,
506    TX_RETRY_COUNT,
507    TX_DIRECT_MAX_RETRY_EXPIRY_COUNT,
508    TX_INDIRECT_MAX_RETRY_EXPIRY_COUNT,
509    TX_ERR_CCA_COUNT,
510    TX_ERR_ABORT_COUNT,
511    TX_ERR_BUSY_CHANNEL_COUNT,
512    RX_TOTAL_COUNT,
513    RX_UNICAST_COUNT,
514    RX_BROADCAST_COUNT,
515    RX_DATA_COUNT,
516    RX_DATA_POLL_COUNT,
517    RX_BEACON_COUNT,
518    RX_BEACON_REQUEST_COUNT,
519    RX_OTHER_COUNT,
520    RX_ADDRESS_FILTERED_COUNT,
521    RX_DEST_ADDR_FILTERED_COUNT,
522    RX_DUPLICATED_COUNT,
523    RX_ERR_NO_FRAME_COUNT,
524    RX_ERR_UNKNOWN_NEIGHBOR_COUNT,
525    RX_ERR_INVALID_SRC_ADDR_COUNT,
526    RX_ERR_SEC_COUNT,
527    RX_ERR_FCS_COUNT,
528    RX_ERR_OTHER_COUNT,
529];
530
531/// Every attribute, command and event §11.14 leaves to the product.
532///
533/// `ExtAddress` and `Rloc16` are absent, because 1.6 marks them provisional (Core §2.13) and the
534/// default build here is the certifiable one. Under the `provisional` feature they are included.
535#[cfg(not(feature = "provisional"))]
536pub const ALL_OPTIONAL: Optional<'static> = Optional {
537    attributes: COUNTERS,
538    commands: &[],
539    events: &[CONNECTION_STATUS, NETWORK_FAULT_CHANGE],
540};
541
542/// Every attribute, command and event §11.14 leaves to the product, including §2.13's two
543/// provisional attributes.
544#[cfg(feature = "provisional")]
545pub const ALL_OPTIONAL: Optional<'static> = Optional {
546    attributes: &WITH_PROVISIONAL,
547    commands: &[],
548    events: &[CONNECTION_STATUS, NETWORK_FAULT_CHANGE],
549};
550
551/// [`COUNTERS`] followed by the two provisional attributes, as one contiguous table.
552#[cfg(feature = "provisional")]
553#[allow(clippy::indexing_slicing)]
554const WITH_PROVISIONAL: [AttributeId; 44] = {
555    let mut all = [0; 44];
556    let mut i = 0;
557    while i < COUNTERS.len() {
558        all[i] = COUNTERS[i];
559        i += 1;
560    }
561    all[42] = EXT_ADDRESS;
562    all[43] = RLOC16;
563    all
564};
565
566/// The Thread Network Diagnostics cluster (§11.14).
567///
568/// `E` is how many events the cluster holds before the oldest is dropped. A stack that flaps
569/// must not be able to grow this, and the device drains it every time round its own loop.
570#[derive(Debug)]
571pub struct ThreadNetworkDiagnostics<'a, D: ThreadDriver, const E: usize = 4> {
572    driver: &'a D,
573    features: u32,
574    events: RefCell<heapless::Vec<Event, E>>,
575}
576
577impl<'a, D: ThreadDriver, const E: usize> ThreadNetworkDiagnostics<'a, D, E> {
578    /// A cluster over a device's own Thread stack.
579    #[must_use]
580    pub fn new(driver: &'a D, features: u32) -> Self {
581        Self {
582            driver,
583            features,
584            events: RefCell::new(heapless::Vec::new()),
585        }
586    }
587
588    /// Records one of §11.14.8's events for the device to drain.
589    ///
590    /// Public because both of them are the *stack's* to notice.
591    pub fn record(&self, event: Event) {
592        let mut events = self.events.borrow_mut();
593        if events.is_full() {
594            events.remove(0);
595        }
596        let _ = events.push(event);
597    }
598
599    /// Takes the events recorded since the last call.
600    #[must_use]
601    pub fn take_events(&self) -> heapless::Vec<Event, E> {
602        core::mem::take(&mut self.events.borrow_mut())
603    }
604
605    const fn has(&self, bit: u32) -> bool {
606        self.features & bit != 0
607    }
608}
609
610/// Writes a mandatory nullable attribute: the value, or §11.14.6's `null`.
611fn nullable<T>(
612    value: Option<T>,
613    w: &mut TlvWriter<'_>,
614    tag: Tag,
615    encode: impl FnOnce(&mut TlvWriter<'_>, Tag, T) -> crate::error::Result<()>,
616) -> Result<(), Status> {
617    match value {
618        Some(v) => encode(w, tag, v),
619        None => w.null(tag),
620    }
621    .map_err(|_| Status::ResourceExhausted)
622}
623
624/// A counter §11.14.4 makes conditional on a feature and §11.14.6 leaves optional within it.
625///
626/// Two different refusals, one status: the feature is not claimed, or it is claimed and this
627/// device does not keep that particular counter. Both mean the attribute is not on this device,
628/// which is what the descriptor says too — answering zero would be the stack asserting a
629/// measurement it never made.
630fn counter(
631    claimed: bool,
632    value: Option<u64>,
633    w: &mut TlvWriter<'_>,
634    tag: Tag,
635) -> Result<(), Status> {
636    match (claimed, value) {
637        (true, Some(v)) => w.unsigned(tag, v).map_err(|_| Status::ResourceExhausted),
638        _ => Err(Status::UnsupportedAttribute),
639    }
640}
641
642/// A `list[Struct]` attribute, written as the array it is.
643fn list<T: ToTlv>(items: &[T], w: &mut TlvWriter<'_>, tag: Tag) -> Result<(), Status> {
644    (|| {
645        w.start_array(tag)?;
646        for item in items {
647            item.to_tlv(w, Tag::Anonymous)?;
648        }
649        w.end_container()
650    })()
651    .map_err(|_: crate::Error| Status::ResourceExhausted)
652}
653
654impl<D: ThreadDriver, const E: usize> ClusterHandler for ThreadNetworkDiagnostics<'_, D, E> {
655    fn read(
656        &self,
657        resolved: &Resolved<'_>,
658        _ctx: &InteractionContext<'_>,
659        w: &mut TlvWriter<'_>,
660        tag: Tag,
661    ) -> Result<(), Status> {
662        let mac = self.has(feature::MAC_COUNTS);
663        let mle = self.has(feature::MLE_COUNTS);
664        match resolved.attribute {
665            CHANNEL => nullable(self.driver.channel(), w, tag, |w, tag, v| {
666                w.unsigned(tag, u64::from(v))
667            }),
668            ROUTING_ROLE => nullable(self.driver.routing_role(), w, tag, |w, tag, v| {
669                w.unsigned(tag, u64::from(v.value()))
670            }),
671            NETWORK_NAME => nullable(self.driver.network_name(), w, tag, |w, tag, v| {
672                w.utf8(tag, v)
673            }),
674            PAN_ID => nullable(self.driver.pan_id(), w, tag, |w, tag, v| {
675                w.unsigned(tag, u64::from(v))
676            }),
677            EXTENDED_PAN_ID => nullable(self.driver.extended_pan_id(), w, tag, |w, tag, v| {
678                w.unsigned(tag, v)
679            }),
680            MESH_LOCAL_PREFIX => nullable(self.driver.mesh_local_prefix(), w, tag, |w, tag, v| {
681                w.octets(tag, v)
682            }),
683            // Mandatory within `ERRCNT` and not nullable, unlike every other counter here.
684            OVERRUN_COUNT => {
685                if !self.has(feature::ERROR_COUNTS) {
686                    return Err(Status::UnsupportedAttribute);
687                }
688                w.unsigned(tag, self.driver.overrun_count())
689                    .map_err(|_| Status::ResourceExhausted)
690            }
691            NEIGHBOR_TABLE => list(self.driver.neighbors(), w, tag),
692            ROUTE_TABLE => list(self.driver.routes(), w, tag),
693            PARTITION_ID => nullable(self.driver.partition_id(), w, tag, |w, tag, v| {
694                w.unsigned(tag, u64::from(v))
695            }),
696            WEIGHTING => nullable(self.driver.weighting(), w, tag, |w, tag, v| {
697                w.unsigned(tag, u64::from(v))
698            }),
699            DATA_VERSION => nullable(self.driver.data_version(), w, tag, |w, tag, v| {
700                w.unsigned(tag, u64::from(v))
701            }),
702            STABLE_DATA_VERSION => {
703                nullable(self.driver.stable_data_version(), w, tag, |w, tag, v| {
704                    w.unsigned(tag, u64::from(v))
705                })
706            }
707            LEADER_ROUTER_ID => nullable(self.driver.leader_router_id(), w, tag, |w, tag, v| {
708                w.unsigned(tag, u64::from(v))
709            }),
710            DETACHED_ROLE_COUNT => counter(
711                mle,
712                self.driver.mle_counters().detached_role.map(u64::from),
713                w,
714                tag,
715            ),
716            CHILD_ROLE_COUNT => counter(
717                mle,
718                self.driver.mle_counters().child_role.map(u64::from),
719                w,
720                tag,
721            ),
722            ROUTER_ROLE_COUNT => counter(
723                mle,
724                self.driver.mle_counters().router_role.map(u64::from),
725                w,
726                tag,
727            ),
728            LEADER_ROLE_COUNT => counter(
729                mle,
730                self.driver.mle_counters().leader_role.map(u64::from),
731                w,
732                tag,
733            ),
734            ATTACH_ATTEMPT_COUNT => counter(
735                mle,
736                self.driver.mle_counters().attach_attempt.map(u64::from),
737                w,
738                tag,
739            ),
740            PARTITION_ID_CHANGE_COUNT => counter(
741                mle,
742                self.driver
743                    .mle_counters()
744                    .partition_id_change
745                    .map(u64::from),
746                w,
747                tag,
748            ),
749            BETTER_PARTITION_ATTACH_ATTEMPT_COUNT => counter(
750                mle,
751                self.driver
752                    .mle_counters()
753                    .better_partition_attach_attempt
754                    .map(u64::from),
755                w,
756                tag,
757            ),
758            PARENT_CHANGE_COUNT => counter(
759                mle,
760                self.driver.mle_counters().parent_change.map(u64::from),
761                w,
762                tag,
763            ),
764            TX_TOTAL_COUNT => counter(
765                mac,
766                self.driver.mac_counters().tx_total.map(u64::from),
767                w,
768                tag,
769            ),
770            TX_UNICAST_COUNT => counter(
771                mac,
772                self.driver.mac_counters().tx_unicast.map(u64::from),
773                w,
774                tag,
775            ),
776            TX_BROADCAST_COUNT => counter(
777                mac,
778                self.driver.mac_counters().tx_broadcast.map(u64::from),
779                w,
780                tag,
781            ),
782            TX_ACK_REQUESTED_COUNT => counter(
783                mac,
784                self.driver.mac_counters().tx_ack_requested.map(u64::from),
785                w,
786                tag,
787            ),
788            TX_ACKED_COUNT => counter(
789                mac,
790                self.driver.mac_counters().tx_acked.map(u64::from),
791                w,
792                tag,
793            ),
794            TX_NO_ACK_REQUESTED_COUNT => counter(
795                mac,
796                self.driver
797                    .mac_counters()
798                    .tx_no_ack_requested
799                    .map(u64::from),
800                w,
801                tag,
802            ),
803            TX_DATA_COUNT => counter(
804                mac,
805                self.driver.mac_counters().tx_data.map(u64::from),
806                w,
807                tag,
808            ),
809            TX_DATA_POLL_COUNT => counter(
810                mac,
811                self.driver.mac_counters().tx_data_poll.map(u64::from),
812                w,
813                tag,
814            ),
815            TX_BEACON_COUNT => counter(
816                mac,
817                self.driver.mac_counters().tx_beacon.map(u64::from),
818                w,
819                tag,
820            ),
821            TX_BEACON_REQUEST_COUNT => counter(
822                mac,
823                self.driver.mac_counters().tx_beacon_request.map(u64::from),
824                w,
825                tag,
826            ),
827            TX_OTHER_COUNT => counter(
828                mac,
829                self.driver.mac_counters().tx_other.map(u64::from),
830                w,
831                tag,
832            ),
833            TX_RETRY_COUNT => counter(
834                mac,
835                self.driver.mac_counters().tx_retry.map(u64::from),
836                w,
837                tag,
838            ),
839            TX_DIRECT_MAX_RETRY_EXPIRY_COUNT => counter(
840                mac,
841                self.driver
842                    .mac_counters()
843                    .tx_direct_max_retry_expiry
844                    .map(u64::from),
845                w,
846                tag,
847            ),
848            TX_INDIRECT_MAX_RETRY_EXPIRY_COUNT => counter(
849                mac,
850                self.driver
851                    .mac_counters()
852                    .tx_indirect_max_retry_expiry
853                    .map(u64::from),
854                w,
855                tag,
856            ),
857            TX_ERR_CCA_COUNT => counter(
858                mac,
859                self.driver.mac_counters().tx_err_cca.map(u64::from),
860                w,
861                tag,
862            ),
863            TX_ERR_ABORT_COUNT => counter(
864                mac,
865                self.driver.mac_counters().tx_err_abort.map(u64::from),
866                w,
867                tag,
868            ),
869            TX_ERR_BUSY_CHANNEL_COUNT => counter(
870                mac,
871                self.driver
872                    .mac_counters()
873                    .tx_err_busy_channel
874                    .map(u64::from),
875                w,
876                tag,
877            ),
878            RX_TOTAL_COUNT => counter(
879                mac,
880                self.driver.mac_counters().rx_total.map(u64::from),
881                w,
882                tag,
883            ),
884            RX_UNICAST_COUNT => counter(
885                mac,
886                self.driver.mac_counters().rx_unicast.map(u64::from),
887                w,
888                tag,
889            ),
890            RX_BROADCAST_COUNT => counter(
891                mac,
892                self.driver.mac_counters().rx_broadcast.map(u64::from),
893                w,
894                tag,
895            ),
896            RX_DATA_COUNT => counter(
897                mac,
898                self.driver.mac_counters().rx_data.map(u64::from),
899                w,
900                tag,
901            ),
902            RX_DATA_POLL_COUNT => counter(
903                mac,
904                self.driver.mac_counters().rx_data_poll.map(u64::from),
905                w,
906                tag,
907            ),
908            RX_BEACON_COUNT => counter(
909                mac,
910                self.driver.mac_counters().rx_beacon.map(u64::from),
911                w,
912                tag,
913            ),
914            RX_BEACON_REQUEST_COUNT => counter(
915                mac,
916                self.driver.mac_counters().rx_beacon_request.map(u64::from),
917                w,
918                tag,
919            ),
920            RX_OTHER_COUNT => counter(
921                mac,
922                self.driver.mac_counters().rx_other.map(u64::from),
923                w,
924                tag,
925            ),
926            RX_ADDRESS_FILTERED_COUNT => counter(
927                mac,
928                self.driver
929                    .mac_counters()
930                    .rx_address_filtered
931                    .map(u64::from),
932                w,
933                tag,
934            ),
935            RX_DEST_ADDR_FILTERED_COUNT => counter(
936                mac,
937                self.driver
938                    .mac_counters()
939                    .rx_dest_addr_filtered
940                    .map(u64::from),
941                w,
942                tag,
943            ),
944            RX_DUPLICATED_COUNT => counter(
945                mac,
946                self.driver.mac_counters().rx_duplicated.map(u64::from),
947                w,
948                tag,
949            ),
950            RX_ERR_NO_FRAME_COUNT => counter(
951                mac,
952                self.driver.mac_counters().rx_err_no_frame.map(u64::from),
953                w,
954                tag,
955            ),
956            RX_ERR_UNKNOWN_NEIGHBOR_COUNT => counter(
957                mac,
958                self.driver
959                    .mac_counters()
960                    .rx_err_unknown_neighbor
961                    .map(u64::from),
962                w,
963                tag,
964            ),
965            RX_ERR_INVALID_SRC_ADDR_COUNT => counter(
966                mac,
967                self.driver
968                    .mac_counters()
969                    .rx_err_invalid_src_addr
970                    .map(u64::from),
971                w,
972                tag,
973            ),
974            RX_ERR_SEC_COUNT => counter(
975                mac,
976                self.driver.mac_counters().rx_err_sec.map(u64::from),
977                w,
978                tag,
979            ),
980            RX_ERR_FCS_COUNT => counter(
981                mac,
982                self.driver.mac_counters().rx_err_fcs.map(u64::from),
983                w,
984                tag,
985            ),
986            RX_ERR_OTHER_COUNT => counter(
987                mac,
988                self.driver.mac_counters().rx_err_other.map(u64::from),
989                w,
990                tag,
991            ),
992            ACTIVE_TIMESTAMP => nullable(self.driver.active_timestamp(), w, tag, |w, tag, v| {
993                w.unsigned(tag, v)
994            }),
995            PENDING_TIMESTAMP => nullable(self.driver.pending_timestamp(), w, tag, |w, tag, v| {
996                w.unsigned(tag, v)
997            }),
998            DELAY => nullable(self.driver.delay(), w, tag, |w, tag, v| {
999                w.unsigned(tag, u64::from(v))
1000            }),
1001            SECURITY_POLICY => nullable(self.driver.security_policy(), w, tag, |w, tag, v| {
1002                v.to_tlv(w, tag)
1003            }),
1004            CHANNEL_PAGE0_MASK => {
1005                nullable(self.driver.channel_page0_mask(), w, tag, |w, tag, v| {
1006                    w.octets(tag, v)
1007                })
1008            }
1009            OPERATIONAL_DATASET_COMPONENTS => nullable(
1010                self.driver.operational_dataset_components(),
1011                w,
1012                tag,
1013                |w, tag, v| v.to_tlv(w, tag),
1014            ),
1015            ACTIVE_NETWORK_FAULTS_LIST => faults(w, tag, self.driver.active_network_faults())
1016                .map_err(|_| Status::ResourceExhausted),
1017            EXT_ADDRESS => nullable(self.driver.ext_address(), w, tag, |w, tag, v| {
1018                w.unsigned(tag, v)
1019            }),
1020            RLOC16 => nullable(self.driver.rloc16(), w, tag, |w, tag, v| {
1021                w.unsigned(tag, u64::from(v))
1022            }),
1023            _ => Err(Status::UnsupportedAttribute),
1024        }
1025    }
1026
1027    fn invoke(
1028        &self,
1029        resolved: &ResolvedCommand<'_>,
1030        _fields: Option<&[u8]>,
1031        _ctx: &InteractionContext<'_>,
1032        _w: &mut TlvWriter<'_>,
1033        _tag: Tag,
1034    ) -> Result<Option<CommandId>, StatusIb> {
1035        match resolved.command.id {
1036            // §11.14.7's conformance is `ERRCNT`, like Wi-Fi's and unlike Ethernet's
1037            // `PKTCNT | ERRCNT`.
1038            RESET_COUNTS => {
1039                if !self.has(feature::ERROR_COUNTS) {
1040                    return Err(StatusIb::new(Status::UnsupportedCommand));
1041                }
1042                self.driver.reset_counts();
1043                Ok(None)
1044            }
1045            _ => Err(StatusIb::new(Status::UnsupportedCommand)),
1046        }
1047    }
1048}
1049
1050/// So a tuple of clusters can dispatch to it by id.
1051impl<D: ThreadDriver, const E: usize> Cluster for ThreadNetworkDiagnostics<'_, D, E> {
1052    const ID: ClusterId = ID;
1053}
1054
1055#[cfg(test)]
1056#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
1057mod tests {
1058    use super::*;
1059    use crate::im::AttributeId;
1060
1061    const NEIGHBORS: &[NeighborTableStruct] = &[NeighborTableStruct {
1062        ext_address: 0x0011_2233_4455_6677,
1063        age: 12,
1064        rloc16: 0x4000,
1065        link_frame_counter: 7,
1066        mle_frame_counter: 9,
1067        lqi: 3,
1068        average_rssi: crate::tlv::Nullable::some(-70),
1069        last_rssi: crate::tlv::Nullable::null(),
1070        frame_error_rate: 0,
1071        message_error_rate: 0,
1072        rx_on_when_idle: true,
1073        full_thread_device: true,
1074        full_network_data: true,
1075        is_child: false,
1076    }];
1077
1078    struct Stack;
1079
1080    impl ThreadDriver for Stack {
1081        fn channel(&self) -> Option<u16> {
1082            Some(15)
1083        }
1084        fn routing_role(&self) -> Option<RoutingRoleEnum> {
1085            Some(RoutingRoleEnum::Router)
1086        }
1087        fn network_name(&self) -> Option<&str> {
1088            Some("matter-kit")
1089        }
1090        fn pan_id(&self) -> Option<u16> {
1091            Some(0x1234)
1092        }
1093        fn overrun_count(&self) -> u64 {
1094            5
1095        }
1096        fn neighbors(&self) -> &[NeighborTableStruct] {
1097            NEIGHBORS
1098        }
1099        fn active_network_faults(&self) -> &[NetworkFaultEnum] {
1100            &[NetworkFaultEnum::LinkDown]
1101        }
1102        fn mle_counters(&self) -> MleCounters {
1103            MleCounters {
1104                parent_change: Some(2),
1105                ..MleCounters::EMPTY
1106            }
1107        }
1108        fn mac_counters(&self) -> MacCounters {
1109            MacCounters {
1110                tx_total: Some(100),
1111                rx_total: Some(90),
1112                ..MacCounters::EMPTY
1113            }
1114        }
1115    }
1116
1117    /// A Thread interface that is powered and not attached.
1118    struct Detached;
1119
1120    impl ThreadDriver for Detached {}
1121
1122    /// The optional set a product that keeps only `ParentChangeCount`, `TxTotalCount` and
1123    /// `RxTotalCount` would declare — which is what `Stack` above actually measures.
1124    const MEASURED: Optional<'static> = Optional {
1125        attributes: &[PARENT_CHANGE_COUNT, TX_TOTAL_COUNT, RX_TOTAL_COUNT],
1126        commands: &[],
1127        events: &[],
1128    };
1129
1130    fn read<D: ThreadDriver>(
1131        cluster: &ThreadNetworkDiagnostics<'_, D>,
1132        attribute: AttributeId,
1133    ) -> Result<heapless::Vec<u8, 96>, Status> {
1134        let descriptor = conforming(cluster.features, &MEASURED).expect("descriptor");
1135        let cl = descriptor.descriptor();
1136        let resolved = Resolved {
1137            endpoint: 0,
1138            cluster: &cl,
1139            attribute,
1140        };
1141        let mut buf = [0u8; 96];
1142        let mut w = TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
1143        cluster.read(
1144            &resolved,
1145            &InteractionContext::new(),
1146            &mut w,
1147            Tag::Context(0),
1148        )?;
1149        Ok(heapless::Vec::from_slice(w.finish().expect("finish")).expect("fits"))
1150    }
1151
1152    fn advertises(features: u32, optional: &Optional<'_>, attribute: AttributeId) -> bool {
1153        conforming(features, optional)
1154            .expect("descriptor")
1155            .descriptor()
1156            .attributes
1157            .iter()
1158            .any(|a| a.id == attribute)
1159    }
1160
1161    /// The whole specification table fits, which is the assertion that `conforming`'s bounds
1162    /// are not one short — the failure mode is `NoSpace` at construction and nowhere else.
1163    #[test]
1164    fn every_element_the_revision_defines_fits_at_once() {
1165        let all = conforming(
1166            feature::PACKET_COUNTS
1167                | feature::ERROR_COUNTS
1168                | feature::MLE_COUNTS
1169                | feature::MAC_COUNTS,
1170            &ALL_OPTIONAL,
1171        )
1172        .expect("the whole cluster fits");
1173        assert!(advertises(
1174            feature::MAC_COUNTS,
1175            &ALL_OPTIONAL,
1176            RX_ERR_OTHER_COUNT
1177        ));
1178        assert_eq!(all.descriptor().events.len(), 2);
1179    }
1180
1181    /// §11.14.4's counters are conditional on a feature *and* optional within it, so there are
1182    /// two ways for one not to be on a device — and a product that claims `MACCNT` without
1183    /// keeping every counter is the normal case, not an edge one.
1184    #[test]
1185    fn a_counter_needs_both_its_feature_and_the_products_declaration() {
1186        assert!(!advertises(0, &MEASURED, TX_TOTAL_COUNT), "no MACCNT");
1187        assert!(advertises(feature::MAC_COUNTS, &MEASURED, TX_TOTAL_COUNT));
1188        assert!(
1189            !advertises(feature::MAC_COUNTS, &MEASURED, TX_RETRY_COUNT),
1190            "claimed the feature, does not keep this one"
1191        );
1192
1193        let counting = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, feature::MAC_COUNTS);
1194        assert_eq!(
1195            read(&counting, TX_TOTAL_COUNT).expect("tx"),
1196            [0x24, 0x00, 100]
1197        );
1198        assert_eq!(
1199            read(&counting, TX_RETRY_COUNT),
1200            Err(Status::UnsupportedAttribute),
1201            "a counter the driver left None is not answered as zero"
1202        );
1203
1204        let silent = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, 0);
1205        assert_eq!(
1206            read(&silent, TX_TOTAL_COUNT),
1207            Err(Status::UnsupportedAttribute)
1208        );
1209    }
1210
1211    /// `OverrunCount` is the only counter §11.14.6 makes mandatory within its feature, so it is
1212    /// the only one that is a plain number rather than an `Option`.
1213    #[test]
1214    fn overrun_count_is_mandatory_within_its_feature() {
1215        let errors = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, feature::ERROR_COUNTS);
1216        assert_eq!(
1217            read(&errors, OVERRUN_COUNT).expect("overrun"),
1218            [0x24, 0x00, 5]
1219        );
1220        assert!(advertises(
1221            feature::ERROR_COUNTS,
1222            &Optional::NONE,
1223            OVERRUN_COUNT
1224        ));
1225
1226        let none = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, 0);
1227        assert_eq!(
1228            read(&none, OVERRUN_COUNT),
1229            Err(Status::UnsupportedAttribute)
1230        );
1231        assert!(!advertises(0, &Optional::NONE, OVERRUN_COUNT));
1232    }
1233
1234    /// A detached interface answers `null`, and the tables answer empty — which is a different
1235    /// thing, and the reason the tables are slices rather than `Option`s.
1236    #[test]
1237    fn a_detached_interface_is_null_and_its_tables_are_empty() {
1238        let detached = ThreadNetworkDiagnostics::<_, 4>::new(&Detached, 0);
1239        assert_eq!(read(&detached, CHANNEL).expect("channel"), [0x34, 0x00]);
1240        assert_eq!(read(&detached, ROUTING_ROLE).expect("role"), [0x34, 0x00]);
1241        assert_eq!(read(&detached, NETWORK_NAME).expect("name"), [0x34, 0x00]);
1242        // An empty array, not null: the node has a neighbor table and nothing is in it.
1243        assert_eq!(
1244            read(&detached, NEIGHBOR_TABLE).expect("neighbors"),
1245            [0x36, 0x00, 0x18]
1246        );
1247        assert_eq!(
1248            read(&detached, ACTIVE_NETWORK_FAULTS_LIST).expect("faults"),
1249            [0x36, 0x00, 0x18]
1250        );
1251    }
1252
1253    #[test]
1254    fn values_round_trip_through_the_reader() {
1255        let stack = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, feature::MLE_COUNTS);
1256        assert_eq!(read(&stack, CHANNEL).expect("channel"), [0x24, 0x00, 15]);
1257        // `RoutingRoleEnum::Router` is 5.
1258        assert_eq!(read(&stack, ROUTING_ROLE).expect("role"), [0x24, 0x00, 5]);
1259        assert_eq!(
1260            read(&stack, NETWORK_NAME).expect("name"),
1261            [
1262                0x2C, 0x00, 0x0A, b'm', b'a', b't', b't', b'e', b'r', b'-', b'k', b'i', b't'
1263            ]
1264        );
1265        assert_eq!(read(&stack, PAN_ID).expect("pan"), [0x25, 0x00, 0x34, 0x12]);
1266        assert_eq!(
1267            read(&stack, PARENT_CHANGE_COUNT).expect("parent changes"),
1268            [0x24, 0x00, 2]
1269        );
1270        // One fault, as a one-element array.
1271        assert_eq!(
1272            read(&stack, ACTIVE_NETWORK_FAULTS_LIST).expect("faults"),
1273            [0x36, 0x00, 0x04, 0x01, 0x18]
1274        );
1275        assert!(read(&stack, NEIGHBOR_TABLE).expect("neighbors").len() > 3);
1276    }
1277
1278    /// §11.14.7's `ResetCounts` is `ERRCNT`, like Wi-Fi's and unlike Ethernet's.
1279    #[test]
1280    fn reset_counts_belongs_to_the_error_counts_feature() {
1281        assert!(
1282            conforming(feature::MAC_COUNTS, &Optional::NONE)
1283                .expect("descriptor")
1284                .descriptor()
1285                .accepted_commands
1286                .is_empty(),
1287            "counting MAC frames does not bring ResetCounts"
1288        );
1289
1290        let descriptor = conforming(feature::ERROR_COUNTS, &Optional::NONE).expect("descriptor");
1291        let cl = descriptor.descriptor();
1292        let command = *cl
1293            .accepted_commands
1294            .iter()
1295            .find(|c| c.id == RESET_COUNTS)
1296            .expect("ERRCNT brings ResetCounts");
1297        let resolved = ResolvedCommand {
1298            endpoint: 0,
1299            cluster: &cl,
1300            command,
1301        };
1302        let mut buf = [0u8; 32];
1303        let mut w = TlvWriter::new(&mut buf);
1304
1305        let mac = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, feature::MAC_COUNTS);
1306        assert_eq!(
1307            mac.invoke(
1308                &resolved,
1309                None,
1310                &InteractionContext::new(),
1311                &mut w,
1312                Tag::Anonymous
1313            )
1314            .unwrap_err()
1315            .status,
1316            Status::UnsupportedCommand
1317        );
1318
1319        let errors = ThreadNetworkDiagnostics::<_, 4>::new(&Stack, feature::ERROR_COUNTS);
1320        assert!(
1321            errors
1322                .invoke(
1323                    &resolved,
1324                    None,
1325                    &InteractionContext::new(),
1326                    &mut w,
1327                    Tag::Anonymous
1328                )
1329                .is_ok()
1330        );
1331    }
1332
1333    #[test]
1334    fn a_fault_change_event_carries_both_sides() {
1335        let stack = ThreadNetworkDiagnostics::<_, 2>::new(&Stack, 0);
1336        stack.record(Event::ConnectionStatus(ConnectionStatusEnum::NotConnected));
1337        stack.record(Event::NetworkFaultChange {
1338            current: heapless::Vec::from_slice(&[NetworkFaultEnum::LinkDown]).expect("fits"),
1339            previous: heapless::Vec::new(),
1340        });
1341        let drained = stack.take_events();
1342        assert_eq!(drained.len(), 2);
1343        assert_eq!(drained[1].id(), NETWORK_FAULT_CHANGE);
1344        assert_eq!(
1345            drained[1].priority(),
1346            EventPriority::Info,
1347            "§11.14.8 gives both events INFO priority, which is what decides which of the event \
1348             store's three rings the record lands in"
1349        );
1350
1351        let mut buf = [0u8; 64];
1352        let mut w = TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
1353        drained[1].encode(&mut w, Tag::Context(7)).expect("encode");
1354        assert_eq!(
1355            w.finish().expect("finish"),
1356            // struct ctx-7 { ctx-0 = [LinkDown], ctx-1 = [] }
1357            [
1358                0x35, 0x07, 0x36, 0x00, 0x04, 0x01, 0x18, 0x36, 0x01, 0x18, 0x18
1359            ]
1360        );
1361        assert!(stack.take_events().is_empty());
1362    }
1363
1364    /// Core §2.13's provisional elements are off in the default build: a device that advertised
1365    /// `ExtAddress` today could be non-conformant after a 1.6.x revision moved it, and the
1366    /// certifiable build is the one you get without asking.
1367    #[test]
1368    fn the_two_provisional_attributes_are_behind_the_provisional_feature() {
1369        let advertised = advertises(0, &ALL_OPTIONAL, EXT_ADDRESS);
1370        assert_eq!(advertised, cfg!(feature = "provisional"));
1371        assert_eq!(
1372            advertises(0, &ALL_OPTIONAL, RLOC16),
1373            cfg!(feature = "provisional")
1374        );
1375        assert!(
1376            !COUNTERS.contains(&EXT_ADDRESS),
1377            "the counters table is counters, and nothing else"
1378        );
1379    }
1380
1381    /// §11.14.4's features must not invent elements the revision does not define.
1382    #[test]
1383    fn an_undefined_feature_is_refused() {
1384        assert!(conforming(1 << 4, &Optional::NONE).is_err());
1385    }
1386}