Skip to main content

matter_kit/clusters/
ethernet_network_diagnostics.rs

1//! Ethernet Network Diagnostics, cluster `0x0037` (Core §11.16).
2//!
3//! > The Ethernet Network Diagnostics Cluster attempts to centralize all metrics that are
4//! > relevant to a potential Ethernet connection to a Node.
5//!
6//! Every number here belongs to a network interface this crate does not own, so the cluster is
7//! a [`EthernetDriver`] the integrator implements — the same shape
8//! [`general_diagnostics::Diagnostics`](super::general_diagnostics::Diagnostics) takes, and for
9//! the same reason: a driver is the only thing that can count a collision.
10//!
11//! # Two features, and what they promise
12//!
13//! §11.16.4 splits the counters in two. `PKTCNT` claims `PacketRxCount` and `PacketTxCount`;
14//! `ERRCNT` claims `TxErrCount`, `CollisionCount` and `OverrunCount`. Claiming a feature is a
15//! promise that the driver can actually count the thing — a device that advertises `ERRCNT` and
16//! reports zero collisions forever is worse than one that advertises neither, because the first
17//! tells a support engineer the link is clean and the second tells them to look elsewhere. So
18//! the defaults on [`EthernetDriver`] are the ones a device that cannot measure should keep, and
19//! the feature map is what the integrator opts into.
20//!
21//! # `null` is a state, not a missing value
22//!
23//! `PHYRate`, `FullDuplex` and `CarrierDetect` are all `X`-quality: §11.16.6.1's "A value of null
24//! SHALL indicate that the interface is not currently configured or operational". That is a
25//! different fact from "this device does not report PHY rate", which is what omitting the
26//! optional attribute means. `Option<Option<T>>` would say both, and say neither clearly, so the
27//! trait returns [`Reading<T>`] instead and names the three answers.
28//!
29//! ```
30//! use matter_kit::clusters::ethernet_network_diagnostics::{
31//!     EthernetDriver, EthernetNetworkDiagnostics, PHYRateEnum, Reading, feature,
32//! };
33//!
34//! struct Nic;
35//! impl EthernetDriver for Nic {
36//!     fn phy_rate(&self) -> Reading<PHYRateEnum> { Reading::Value(PHYRateEnum::Rate1G) }
37//!     fn full_duplex(&self) -> Reading<bool> { Reading::Value(true) }
38//!     fn packet_rx_count(&self) -> u64 { 1_234 }
39//!     fn packet_tx_count(&self) -> u64 { 5_678 }
40//! }
41//!
42//! // `PKTCNT` because this driver counts packets; no `ERRCNT`, because it does not count errors.
43//! let cluster = EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS);
44//! # let _ = cluster;
45//! ```
46
47use crate::dm::spec::{Conforming, Optional};
48use crate::dm::{Resolved, ResolvedCommand};
49use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
50use crate::tlv::{Tag, TlvWriter};
51
52use super::Cluster;
53pub use super::Reading;
54use crate::clusters::generated::ethernet_network_diagnostics as spec_eth;
55
56pub use spec_eth::{ID, PHYRateEnum, PICS, REVISION, feature};
57
58use spec_eth::attribute::{
59    CARRIER_DETECT, COLLISION_COUNT, FULL_DUPLEX, OVERRUN_COUNT, PACKET_RX_COUNT, PACKET_TX_COUNT,
60    PHY_RATE, TIME_SINCE_RESET, TX_ERR_COUNT,
61};
62use spec_eth::command::RESET_COUNTS;
63
64/// What a device's Ethernet interface can report (§11.16.6).
65///
66/// Every method has a default, so an integrator implements only what the hardware can measure.
67/// The defaults are the conservative ones: an unsupported optional attribute, and a zero counter
68/// for the features §11.16.4 makes the counters conditional on.
69pub trait EthernetDriver {
70    /// `PHYRate` (§11.16.6.1) — "the current nominal, usable speed at the top of the physical
71    /// layer".
72    fn phy_rate(&self) -> Reading<PHYRateEnum> {
73        Reading::Unsupported
74    }
75
76    /// `FullDuplex` (§11.16.6.2) — "if the Node is currently utilizing the full-duplex
77    /// operating mode".
78    fn full_duplex(&self) -> Reading<bool> {
79        Reading::Unsupported
80    }
81
82    /// `PacketRxCount` (§11.16.6.3). `PKTCNT`.
83    ///
84    /// "SHALL be reset to 0 upon a reboot of the Node" — so a driver that persisted it would be
85    /// reporting something the attribute does not mean.
86    fn packet_rx_count(&self) -> u64 {
87        0
88    }
89
90    /// `PacketTxCount` (§11.16.6.4). `PKTCNT`.
91    fn packet_tx_count(&self) -> u64 {
92        0
93    }
94
95    /// `TxErrCount` (§11.16.6.5). `ERRCNT`.
96    fn tx_err_count(&self) -> u64 {
97        0
98    }
99
100    /// `CollisionCount` (§11.16.6.6). `ERRCNT`.
101    fn collision_count(&self) -> u64 {
102        0
103    }
104
105    /// `OverrunCount` (§11.16.6.7) — "packets dropped either at ingress or egress, due to lack
106    /// of buffer memory". `ERRCNT`.
107    fn overrun_count(&self) -> u64 {
108        0
109    }
110
111    /// `CarrierDetect` (§11.16.6.8) — the carrier-detect control signal.
112    fn carrier_detect(&self) -> Reading<bool> {
113        Reading::Unsupported
114    }
115
116    /// `TimeSinceReset` (§11.16.6.9), **in minutes** since the interface last reset.
117    ///
118    /// Minutes, not the seconds every other duration in diagnostics uses, which is exactly the
119    /// kind of unit mismatch that produces a plausible wrong number rather than an error.
120    fn time_since_reset(&self) -> Option<u64> {
121        None
122    }
123
124    /// `ResetCounts` (§11.16.7.1): zero `PacketRxCount`, `PacketTxCount`, `TxErrCount`,
125    /// `CollisionCount` and `OverrunCount`.
126    ///
127    /// The default does nothing, which is correct for a driver that reports no counters. One
128    /// that does report them must implement this, or a client's reset silently fails.
129    fn reset_counts(&self) {}
130}
131
132/// The driver for a device with no Ethernet metrics to report.
133#[derive(Debug, Clone, Copy, Default)]
134pub struct Unknown;
135
136impl EthernetDriver for Unknown {}
137
138/// Builds a descriptor for a feature map and the optional elements a product implements.
139///
140/// `Optional` names what §11.16.6 leaves to the product: `PHYRate`, `FullDuplex`,
141/// `CarrierDetect` and `TimeSinceReset`. The counters are not optional — they are conditional on
142/// `PKTCNT` and `ERRCNT`, and the conformance engine derives them from the feature map.
143///
144/// # Errors
145///
146/// [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does not define.
147pub fn conforming(
148    features: u32,
149    optional: &Optional<'_>,
150) -> crate::error::Result<Conforming<14, 1, 0, 0>> {
151    Conforming::new(&spec_eth::CLUSTER, features, optional)
152}
153
154/// Everything §11.16.6 makes optional, for a driver that reports all of it.
155pub const ALL_OPTIONAL: Optional<'static> = Optional {
156    attributes: &[PHY_RATE, FULL_DUPLEX, CARRIER_DETECT, TIME_SINCE_RESET],
157    commands: &[],
158    events: &[],
159};
160
161/// The Ethernet Network Diagnostics cluster (§11.16).
162#[derive(Debug)]
163pub struct EthernetNetworkDiagnostics<'a, D: EthernetDriver> {
164    driver: &'a D,
165    features: u32,
166}
167
168impl<'a, D: EthernetDriver> EthernetNetworkDiagnostics<'a, D> {
169    /// A cluster over a device's own Ethernet driver.
170    #[must_use]
171    pub const fn new(driver: &'a D, features: u32) -> Self {
172        Self { driver, features }
173    }
174
175    /// Whether `PKTCNT` is claimed.
176    #[must_use]
177    const fn counts_packets(&self) -> bool {
178        self.features & feature::PACKET_COUNTS != 0
179    }
180
181    /// Whether `ERRCNT` is claimed.
182    #[must_use]
183    const fn counts_errors(&self) -> bool {
184        self.features & feature::ERROR_COUNTS != 0
185    }
186}
187
188/// Writes a `Reading`, mapping [`Reading::Unsupported`] to the status that says so.
189fn reading<T>(
190    value: Reading<T>,
191    w: &mut TlvWriter<'_>,
192    tag: Tag,
193    encode: impl FnOnce(&mut TlvWriter<'_>, Tag, T) -> crate::error::Result<()>,
194) -> Result<(), Status> {
195    match value {
196        Reading::Value(v) => encode(w, tag, v).map_err(|_| Status::ResourceExhausted),
197        // §11.16.6.1: "A value of null SHALL indicate that the interface is not currently
198        // configured or operational."
199        Reading::NotOperational => w.null(tag).map_err(|_| Status::ResourceExhausted),
200        Reading::Unsupported => Err(Status::UnsupportedAttribute),
201    }
202}
203
204impl<D: EthernetDriver> ClusterHandler for EthernetNetworkDiagnostics<'_, D> {
205    fn read(
206        &self,
207        resolved: &Resolved<'_>,
208        _ctx: &InteractionContext<'_>,
209        w: &mut TlvWriter<'_>,
210        tag: Tag,
211    ) -> Result<(), Status> {
212        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
213        // A counter whose feature is not claimed is not an attribute this cluster has. Answering
214        // zero instead would be the device asserting a measurement it never made — a link that
215        // has never dropped a packet, forever.
216        let counter = |claimed: bool, value: u64| -> Result<u64, Status> {
217            if claimed {
218                Ok(value)
219            } else {
220                Err(Status::UnsupportedAttribute)
221            }
222        };
223        match resolved.attribute {
224            PHY_RATE => reading(self.driver.phy_rate(), w, tag, |w, tag, rate| {
225                w.unsigned(tag, u64::from(rate.value()))
226            }),
227            FULL_DUPLEX => reading(self.driver.full_duplex(), w, tag, |w, tag, v| {
228                w.bool(tag, v)
229            }),
230            CARRIER_DETECT => reading(self.driver.carrier_detect(), w, tag, |w, tag, v| {
231                w.bool(tag, v)
232            }),
233            PACKET_RX_COUNT => full(w.unsigned(
234                tag,
235                counter(self.counts_packets(), self.driver.packet_rx_count())?,
236            )),
237            PACKET_TX_COUNT => full(w.unsigned(
238                tag,
239                counter(self.counts_packets(), self.driver.packet_tx_count())?,
240            )),
241            TX_ERR_COUNT => full(w.unsigned(
242                tag,
243                counter(self.counts_errors(), self.driver.tx_err_count())?,
244            )),
245            COLLISION_COUNT => full(w.unsigned(
246                tag,
247                counter(self.counts_errors(), self.driver.collision_count())?,
248            )),
249            OVERRUN_COUNT => full(w.unsigned(
250                tag,
251                counter(self.counts_errors(), self.driver.overrun_count())?,
252            )),
253            TIME_SINCE_RESET => match self.driver.time_since_reset() {
254                Some(minutes) => full(w.unsigned(tag, minutes)),
255                None => Err(Status::UnsupportedAttribute),
256            },
257            _ => Err(Status::UnsupportedAttribute),
258        }
259    }
260
261    fn invoke(
262        &self,
263        resolved: &ResolvedCommand<'_>,
264        _fields: Option<&[u8]>,
265        _ctx: &InteractionContext<'_>,
266        _w: &mut TlvWriter<'_>,
267        _tag: Tag,
268    ) -> Result<Option<CommandId>, StatusIb> {
269        match resolved.command.id {
270            RESET_COUNTS => {
271                // §11.16.7's conformance is `PKTCNT | ERRCNT`: a device claiming neither has no
272                // counters to reset and does not have the command.
273                if !self.counts_packets() && !self.counts_errors() {
274                    return Err(StatusIb::new(Status::UnsupportedCommand));
275                }
276                self.driver.reset_counts();
277                Ok(None)
278            }
279            _ => Err(StatusIb::new(Status::UnsupportedCommand)),
280        }
281    }
282}
283
284/// So a tuple of clusters can dispatch to it by id.
285impl<D: EthernetDriver> Cluster for EthernetNetworkDiagnostics<'_, D> {
286    const ID: ClusterId = ID;
287}
288
289#[cfg(test)]
290#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
291mod tests {
292    use super::*;
293    use crate::im::AttributeId;
294
295    struct Nic;
296
297    impl EthernetDriver for Nic {
298        fn phy_rate(&self) -> Reading<PHYRateEnum> {
299            Reading::Value(PHYRateEnum::Rate1G)
300        }
301        fn full_duplex(&self) -> Reading<bool> {
302            Reading::Value(true)
303        }
304        fn carrier_detect(&self) -> Reading<bool> {
305            Reading::NotOperational
306        }
307        fn packet_rx_count(&self) -> u64 {
308            11
309        }
310        fn packet_tx_count(&self) -> u64 {
311            22
312        }
313        fn tx_err_count(&self) -> u64 {
314            33
315        }
316        fn collision_count(&self) -> u64 {
317            44
318        }
319        fn overrun_count(&self) -> u64 {
320            55
321        }
322        fn time_since_reset(&self) -> Option<u64> {
323            Some(7)
324        }
325    }
326
327    fn read<D: EthernetDriver>(
328        cluster: &EthernetNetworkDiagnostics<'_, D>,
329        attribute: AttributeId,
330    ) -> Result<heapless::Vec<u8, 64>, Status> {
331        let descriptor = conforming(cluster.features, &ALL_OPTIONAL).expect("descriptor");
332        let cl = descriptor.descriptor();
333        let resolved = Resolved {
334            endpoint: 0,
335            cluster: &cl,
336            attribute,
337        };
338        let mut buf = [0u8; 64];
339        let mut w = TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
340        cluster.read(
341            &resolved,
342            &InteractionContext::new(),
343            &mut w,
344            Tag::Context(0),
345        )?;
346        // `heapless`, not `alloc`: these tests run under `--no-default-features`
347        // too, which is the build a device ships and the one with no allocator.
348        Ok(heapless::Vec::from_slice(w.finish().expect("finish")).expect("fits"))
349    }
350
351    /// Whether an attribute is in the descriptor at all, which is what a client reads from
352    /// `AttributeList` and what the server routes on.
353    fn advertises(features: u32, attribute: AttributeId) -> bool {
354        conforming(features, &ALL_OPTIONAL)
355            .expect("descriptor")
356            .descriptor()
357            .attributes
358            .iter()
359            .any(|a| a.id == attribute)
360    }
361
362    /// §11.16.4 makes the counters conditional on `PKTCNT` and `ERRCNT`, and the two are
363    /// independent. A device that claims neither does not *have* the counters — reporting zero
364    /// would be it asserting a measurement it never made, which reads to a support engineer as
365    /// a link that has never dropped a packet.
366    #[test]
367    fn an_unclaimed_counter_is_not_advertised_and_not_answered() {
368        // The conformance engine keeps it out of the descriptor...
369        assert!(!advertises(0, PACKET_RX_COUNT));
370        assert!(!advertises(0, TX_ERR_COUNT));
371        assert!(advertises(feature::PACKET_COUNTS, PACKET_RX_COUNT));
372        assert!(
373            !advertises(feature::PACKET_COUNTS, TX_ERR_COUNT),
374            "PKTCNT does not imply ERRCNT"
375        );
376        assert!(advertises(feature::ERROR_COUNTS, COLLISION_COUNT));
377        assert!(
378            !advertises(feature::ERROR_COUNTS, PACKET_TX_COUNT),
379            "and ERRCNT does not imply PKTCNT"
380        );
381
382        // ...and the handler refuses it even if something routed there anyway. The server never
383        // will, having read the same descriptor — this is the second of the two answers, kept
384        // because a cluster that returned 0 for an attribute it does not have would be wrong in
385        // a way no descriptor check downstream could catch.
386        let none = EthernetNetworkDiagnostics::new(&Nic, 0);
387        assert_eq!(
388            read(&none, PACKET_RX_COUNT),
389            Err(Status::UnsupportedAttribute)
390        );
391        assert_eq!(read(&none, TX_ERR_COUNT), Err(Status::UnsupportedAttribute));
392
393        let packets = EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS);
394        assert!(read(&packets, PACKET_RX_COUNT).is_ok());
395        assert_eq!(
396            read(&packets, TX_ERR_COUNT),
397            Err(Status::UnsupportedAttribute)
398        );
399    }
400
401    /// A device builds its `Optional` list from what its driver reports, and
402    /// [`Reading::is_supported`] is how it asks — the one question whose answer must match the
403    /// descriptor, because an attribute answered but not advertised is a number no client can
404    /// find, and one advertised but not answered is a read that fails.
405    #[test]
406    fn a_driver_can_be_asked_which_attributes_it_reports() {
407        assert!(Reading::Value(PHYRateEnum::Rate1G).is_supported());
408        assert!(
409            Reading::<bool>::NotOperational.is_supported(),
410            "null is a value the device reports, not a missing attribute"
411        );
412        assert!(!Reading::<bool>::Unsupported.is_supported());
413        assert_eq!(
414            Reading::<bool>::default(),
415            Reading::Unsupported,
416            "the default is the one a device that has not said otherwise should have"
417        );
418    }
419
420    /// §11.16.6.1's `null` is "not currently configured or operational", which is a different
421    /// fact from the device not reporting the attribute.
422    #[test]
423    fn null_and_unsupported_are_different_answers() {
424        let nic = EthernetNetworkDiagnostics::new(&Nic, 0);
425        let carrier = read(&nic, CARRIER_DETECT).expect("carrier detect is reported");
426        // 0x34 is a context-tagged null; the value being present at all is the point.
427        assert_eq!(carrier, [0x34, 0x00], "null, not absent");
428
429        let blank = EthernetNetworkDiagnostics::new(&Unknown, 0);
430        assert_eq!(
431            read(&blank, CARRIER_DETECT),
432            Err(Status::UnsupportedAttribute),
433            "a device that cannot measure it says so"
434        );
435    }
436
437    #[test]
438    fn values_round_trip_through_the_reader() {
439        let nic =
440            EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS | feature::ERROR_COUNTS);
441        assert_eq!(read(&nic, PHY_RATE).expect("phy"), [0x24, 0x00, 0x02]);
442        assert_eq!(read(&nic, FULL_DUPLEX).expect("duplex"), [0x29, 0x00]);
443        assert_eq!(read(&nic, PACKET_RX_COUNT).expect("rx"), [0x24, 0x00, 11]);
444        assert_eq!(
445            read(&nic, OVERRUN_COUNT).expect("overrun"),
446            [0x24, 0x00, 55]
447        );
448        assert_eq!(
449            read(&nic, TIME_SINCE_RESET).expect("since"),
450            [0x24, 0x00, 7]
451        );
452    }
453
454    /// §11.16.7's conformance is `PKTCNT | ERRCNT`.
455    #[test]
456    fn reset_counts_needs_a_counter_to_reset() {
457        let descriptor = conforming(feature::PACKET_COUNTS, &Optional::NONE).expect("descriptor");
458        let cl = descriptor.descriptor();
459        let command = *cl
460            .accepted_commands
461            .iter()
462            .find(|c| c.id == RESET_COUNTS)
463            .expect("ResetCounts is present when PKTCNT is claimed");
464        let resolved = ResolvedCommand {
465            endpoint: 0,
466            cluster: &cl,
467            command,
468        };
469        let mut buf = [0u8; 32];
470        let mut w = TlvWriter::new(&mut buf);
471
472        let none = EthernetNetworkDiagnostics::new(&Nic, 0);
473        assert_eq!(
474            none.invoke(
475                &resolved,
476                None,
477                &InteractionContext::new(),
478                &mut w,
479                Tag::Anonymous
480            )
481            .unwrap_err()
482            .status,
483            Status::UnsupportedCommand,
484            "a device with no counters has no ResetCounts"
485        );
486
487        let packets = EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS);
488        assert!(
489            packets
490                .invoke(
491                    &resolved,
492                    None,
493                    &InteractionContext::new(),
494                    &mut w,
495                    Tag::Anonymous
496                )
497                .is_ok()
498        );
499    }
500
501    /// §11.16.4's features must not invent elements the revision does not define.
502    #[test]
503    fn an_undefined_feature_is_refused() {
504        assert!(conforming(1 << 5, &Optional::NONE).is_err());
505    }
506}