Skip to main content

matter_kit/clusters/
wi_fi_network_diagnostics.rs

1//! Wi-Fi Network Diagnostics, cluster `0x0036` (Core §11.15).
2//!
3//! The counterpart to [`ethernet_network_diagnostics`](super::ethernet_network_diagnostics) for
4//! a node reached over Wi-Fi, and the same shape: every number belongs to a radio this crate
5//! does not own, so the cluster is a [`WiFiDriver`] the integrator implements.
6//!
7//! # What is different from Ethernet, and why it shows in the types
8//!
9//! §11.15.6 makes **every** attribute here nullable, and all but `CurrentMaxRate` mandatory or
10//! conditional on a feature. So there is no "this device does not report `RSSI`" — a Wi-Fi
11//! device reports it, and reports `null` while it is not associated. That is what
12//! [`Option`] means on this trait: `None` is the specification's `null`, not a missing
13//! implementation. Only `CurrentMaxRate` has all three answers, and only it takes a
14//! [`Reading`].
15//!
16//! # Two features, and what claiming one promises
17//!
18//! §11.15.4 splits the counters: `PKTCNT` claims the four packet counts and `BeaconRxCount`,
19//! `ERRCNT` claims `BeaconLostCount` and `OverrunCount`. Claiming a feature is a promise that
20//! the driver can count the thing, which is why the defaults on [`WiFiDriver`] are the ones a
21//! device that cannot measure should keep, and the feature map is what the integrator opts
22//! into.
23//!
24//! `ResetCounts` is `ERRCNT` alone here — not `PKTCNT | ERRCNT` as it is on Ethernet. A device
25//! that counts packets and no errors has no `ResetCounts`, which is a difference between two
26//! adjacent clusters that reads like a mistake and is not one.
27//!
28//! ```
29//! use matter_kit::clusters::wi_fi_network_diagnostics::{
30//!     SecurityTypeEnum, WiFiDriver, WiFiNetworkDiagnostics, WiFiVersionEnum, feature,
31//! };
32//!
33//! struct Radio;
34//! impl WiFiDriver for Radio {
35//!     fn bssid(&self) -> Option<[u8; 6]> { Some([0x02, 0x00, 0x5E, 0x10, 0x00, 0x01]) }
36//!     fn security_type(&self) -> Option<SecurityTypeEnum> { Some(SecurityTypeEnum::WPA3) }
37//!     fn wi_fi_version(&self) -> Option<WiFiVersionEnum> { Some(WiFiVersionEnum::N) }
38//!     fn channel_number(&self) -> Option<u16> { Some(11) }
39//!     fn rssi(&self) -> Option<i8> { Some(-58) }
40//! }
41//!
42//! // No feature bits: this driver reports the association and counts nothing.
43//! let cluster = WiFiNetworkDiagnostics::<_, 4>::new(&Radio, 0);
44//! # let _ = (cluster, feature::PACKET_COUNTS);
45//! ```
46
47use core::cell::RefCell;
48
49use crate::dm::spec::{Conforming, Optional};
50use crate::dm::{EventPriority, Resolved, ResolvedCommand};
51use crate::im::{
52    ClusterHandler, ClusterId, CommandId, EventId, InteractionContext, Status, StatusIb,
53};
54use crate::tlv::{Tag, TlvWriter};
55
56use super::{Cluster, Reading};
57use crate::clusters::generated::wi_fi_network_diagnostics as spec_wifi;
58
59pub use spec_wifi::{
60    AssociationFailureCauseEnum, ConnectionStatusEnum, ID, PICS, REVISION, SecurityTypeEnum,
61    WiFiVersionEnum, feature,
62};
63
64use spec_wifi::attribute::{
65    BEACON_LOST_COUNT, BEACON_RX_COUNT, BSSID, CHANNEL_NUMBER, CURRENT_MAX_RATE, OVERRUN_COUNT,
66    PACKET_MULTICAST_RX_COUNT, PACKET_MULTICAST_TX_COUNT, PACKET_UNICAST_RX_COUNT,
67    PACKET_UNICAST_TX_COUNT, RSSI, SECURITY_TYPE, WI_FI_VERSION,
68};
69use spec_wifi::command::RESET_COUNTS;
70pub use spec_wifi::event::{ASSOCIATION_FAILURE, CONNECTION_STATUS, DISCONNECTION};
71
72/// What a device's Wi-Fi interface can report (§11.15.6).
73///
74/// Every method has a default, so an integrator implements only what the radio can measure.
75/// The defaults are the conservative ones: `null` for the association, and `null` for the
76/// counters §11.15.4 makes conditional on a feature — a driver that claims the feature is the
77/// one that has to answer.
78pub trait WiFiDriver {
79    /// `BSSID` (§11.15.6.1) — the access point's MAC address, or `null` when not associated.
80    fn bssid(&self) -> Option<[u8; 6]> {
81        None
82    }
83
84    /// `SecurityType` (§11.15.6.2) — the security in use on the current association.
85    fn security_type(&self) -> Option<SecurityTypeEnum> {
86        None
87    }
88
89    /// `WiFiVersion` (§11.15.6.3) — the 802.11 generation the association is running at.
90    fn wi_fi_version(&self) -> Option<WiFiVersionEnum> {
91        None
92    }
93
94    /// `ChannelNumber` (§11.15.6.4) — the channel the association is on.
95    fn channel_number(&self) -> Option<u16> {
96        None
97    }
98
99    /// `RSSI` (§11.15.6.5), in dBm.
100    ///
101    /// Signed, and negative for every association a real radio will ever report. A driver that
102    /// hands back an unsigned "signal strength" here is the unit mismatch this attribute
103    /// invites.
104    fn rssi(&self) -> Option<i8> {
105        None
106    }
107
108    /// `BeaconLostCount` (§11.15.6.6). `ERRCNT`.
109    fn beacon_lost_count(&self) -> Option<u32> {
110        None
111    }
112
113    /// `BeaconRxCount` (§11.15.6.7). `PKTCNT`.
114    fn beacon_rx_count(&self) -> Option<u32> {
115        None
116    }
117
118    /// `PacketMulticastRxCount` (§11.15.6.8). `PKTCNT`.
119    fn packet_multicast_rx_count(&self) -> Option<u32> {
120        None
121    }
122
123    /// `PacketMulticastTxCount` (§11.15.6.9). `PKTCNT`.
124    fn packet_multicast_tx_count(&self) -> Option<u32> {
125        None
126    }
127
128    /// `PacketUnicastRxCount` (§11.15.6.10). `PKTCNT`.
129    fn packet_unicast_rx_count(&self) -> Option<u32> {
130        None
131    }
132
133    /// `PacketUnicastTxCount` (§11.15.6.11). `PKTCNT`.
134    fn packet_unicast_tx_count(&self) -> Option<u32> {
135        None
136    }
137
138    /// `CurrentMaxRate` (§11.15.6.12), in bits per second — the only optional attribute here,
139    /// and so the only one a device may leave out of `AttributeList` altogether.
140    fn current_max_rate(&self) -> Reading<u64> {
141        Reading::Unsupported
142    }
143
144    /// `OverrunCount` (§11.15.6.13) — packets dropped for want of buffer memory. `ERRCNT`.
145    fn overrun_count(&self) -> Option<u64> {
146        None
147    }
148
149    /// `ResetCounts` (§11.15.7.1): zero every counter this cluster reports.
150    ///
151    /// The default does nothing, which is correct for a driver that reports no counters. One
152    /// that does must implement this, or a client's reset silently fails.
153    fn reset_counts(&self) {}
154}
155
156/// The driver for a device with no Wi-Fi metrics to report.
157#[derive(Debug, Clone, Copy, Default)]
158pub struct Unknown;
159
160impl WiFiDriver for Unknown {}
161
162/// One of §11.15.8's events, as the radio noticed it.
163///
164/// The cluster collects these and the device drains them into its own event store, because
165/// the store belongs to the node and not to any one cluster.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub enum Event {
168    /// §11.15.8.1 `Disconnection`, carrying the 802.11 reason code the AP gave.
169    Disconnection {
170        /// `ReasonCode`, from IEEE 802.11-2020 table 9-49.
171        reason_code: u16,
172    },
173    /// §11.15.8.2 `AssociationFailure`.
174    AssociationFailure {
175        /// `AssociationFailureCause`.
176        cause: AssociationFailureCauseEnum,
177        /// `Status`, the 802.11 status code.
178        status: u16,
179    },
180    /// §11.15.8.3 `ConnectionStatus`, on every transition between connected and not.
181    ConnectionStatus(ConnectionStatusEnum),
182}
183
184impl Event {
185    /// The event id this record is reported under.
186    #[must_use]
187    pub const fn id(&self) -> EventId {
188        match self {
189            Self::Disconnection { .. } => DISCONNECTION,
190            Self::AssociationFailure { .. } => ASSOCIATION_FAILURE,
191            Self::ConnectionStatus(_) => CONNECTION_STATUS,
192        }
193    }
194
195    /// Every event in §11.15.8 is `INFO` priority.
196    #[must_use]
197    pub const fn priority(&self) -> EventPriority {
198        EventPriority::Info
199    }
200
201    /// Writes the event's fields as an `EventDataIB`'s `Data` (§10.6.13).
202    ///
203    /// # Errors
204    ///
205    /// Whatever the writer returns when the buffer is too small.
206    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> crate::error::Result<()> {
207        w.start_structure(tag)?;
208        match *self {
209            Self::Disconnection { reason_code } => {
210                w.unsigned(Tag::Context(0), u64::from(reason_code))?;
211            }
212            Self::AssociationFailure { cause, status } => {
213                w.unsigned(Tag::Context(0), u64::from(cause.value()))?;
214                w.unsigned(Tag::Context(1), u64::from(status))?;
215            }
216            Self::ConnectionStatus(status) => {
217                w.unsigned(Tag::Context(0), u64::from(status.value()))?;
218            }
219        }
220        w.end_container()
221    }
222}
223
224/// Builds a descriptor for a feature map and the optional elements a product implements.
225///
226/// `CurrentMaxRate` is the only optional attribute; §11.15.8's three events are optional too,
227/// and a device that never records one must not advertise it.
228///
229/// # Errors
230///
231/// [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does not define.
232pub fn conforming(
233    features: u32,
234    optional: &Optional<'_>,
235) -> crate::error::Result<Conforming<18, 1, 0, 3>> {
236    Conforming::new(&spec_wifi::CLUSTER, features, optional)
237}
238
239/// Everything §11.15 makes optional, for a device that reports all of it.
240pub const ALL_OPTIONAL: Optional<'static> = Optional {
241    attributes: &[CURRENT_MAX_RATE],
242    commands: &[],
243    events: &[DISCONNECTION, ASSOCIATION_FAILURE, CONNECTION_STATUS],
244};
245
246/// The Wi-Fi Network Diagnostics cluster (§11.15).
247///
248/// `E` is how many events the cluster holds before the oldest is dropped. A radio that
249/// disconnects in a loop must not be able to grow this, and the device drains it every time
250/// round its own loop.
251#[derive(Debug)]
252pub struct WiFiNetworkDiagnostics<'a, D: WiFiDriver, const E: usize = 4> {
253    driver: &'a D,
254    features: u32,
255    events: RefCell<heapless::Vec<Event, E>>,
256}
257
258impl<'a, D: WiFiDriver, const E: usize> WiFiNetworkDiagnostics<'a, D, E> {
259    /// A cluster over a device's own Wi-Fi driver.
260    #[must_use]
261    pub fn new(driver: &'a D, features: u32) -> Self {
262        Self {
263            driver,
264            features,
265            events: RefCell::new(heapless::Vec::new()),
266        }
267    }
268
269    /// Records one of §11.15.8's events for the device to drain.
270    ///
271    /// Public because every one of them is the *radio's* to notice: this cluster is told that
272    /// an association failed, it cannot find out.
273    pub fn record(&self, event: Event) {
274        let mut events = self.events.borrow_mut();
275        if events.is_full() {
276            events.remove(0);
277        }
278        let _ = events.push(event);
279    }
280
281    /// Takes the events recorded since the last call.
282    #[must_use]
283    pub fn take_events(&self) -> heapless::Vec<Event, E> {
284        core::mem::take(&mut self.events.borrow_mut())
285    }
286
287    /// Whether `PKTCNT` is claimed.
288    const fn counts_packets(&self) -> bool {
289        self.features & feature::PACKET_COUNTS != 0
290    }
291
292    /// Whether `ERRCNT` is claimed.
293    const fn counts_errors(&self) -> bool {
294        self.features & feature::ERROR_COUNTS != 0
295    }
296
297    /// A counter §11.15.4 makes conditional on a feature.
298    ///
299    /// Two different refusals hide behind one `?`: an unclaimed feature means the attribute is
300    /// not on this device at all, and `None` means the device has it and its value is `null`.
301    /// Answering zero for the first would be the radio asserting a measurement it never made.
302    fn counter(
303        claimed: bool,
304        value: Option<u64>,
305        w: &mut TlvWriter<'_>,
306        tag: Tag,
307    ) -> Result<(), Status> {
308        if !claimed {
309            return Err(Status::UnsupportedAttribute);
310        }
311        match value {
312            Some(v) => w.unsigned(tag, v),
313            None => w.null(tag),
314        }
315        .map_err(|_| Status::ResourceExhausted)
316    }
317}
318
319/// Writes a mandatory nullable attribute: the value, or §11.15.6's `null`.
320fn nullable<T>(
321    value: Option<T>,
322    w: &mut TlvWriter<'_>,
323    tag: Tag,
324    encode: impl FnOnce(&mut TlvWriter<'_>, Tag, T) -> crate::error::Result<()>,
325) -> Result<(), Status> {
326    match value {
327        Some(v) => encode(w, tag, v),
328        None => w.null(tag),
329    }
330    .map_err(|_| Status::ResourceExhausted)
331}
332
333impl<D: WiFiDriver, const E: usize> ClusterHandler for WiFiNetworkDiagnostics<'_, D, E> {
334    fn read(
335        &self,
336        resolved: &Resolved<'_>,
337        _ctx: &InteractionContext<'_>,
338        w: &mut TlvWriter<'_>,
339        tag: Tag,
340    ) -> Result<(), Status> {
341        let packets = self.counts_packets();
342        let errors = self.counts_errors();
343        match resolved.attribute {
344            BSSID => nullable(self.driver.bssid(), w, tag, |w, tag, v| w.octets(tag, &v)),
345            SECURITY_TYPE => nullable(self.driver.security_type(), w, tag, |w, tag, v| {
346                w.unsigned(tag, u64::from(v.value()))
347            }),
348            WI_FI_VERSION => nullable(self.driver.wi_fi_version(), w, tag, |w, tag, v| {
349                w.unsigned(tag, u64::from(v.value()))
350            }),
351            CHANNEL_NUMBER => nullable(self.driver.channel_number(), w, tag, |w, tag, v| {
352                w.unsigned(tag, u64::from(v))
353            }),
354            RSSI => nullable(self.driver.rssi(), w, tag, |w, tag, v| {
355                w.signed(tag, i64::from(v))
356            }),
357            BEACON_LOST_COUNT => Self::counter(
358                errors,
359                self.driver.beacon_lost_count().map(u64::from),
360                w,
361                tag,
362            ),
363            BEACON_RX_COUNT => Self::counter(
364                packets,
365                self.driver.beacon_rx_count().map(u64::from),
366                w,
367                tag,
368            ),
369            PACKET_MULTICAST_RX_COUNT => Self::counter(
370                packets,
371                self.driver.packet_multicast_rx_count().map(u64::from),
372                w,
373                tag,
374            ),
375            PACKET_MULTICAST_TX_COUNT => Self::counter(
376                packets,
377                self.driver.packet_multicast_tx_count().map(u64::from),
378                w,
379                tag,
380            ),
381            PACKET_UNICAST_RX_COUNT => Self::counter(
382                packets,
383                self.driver.packet_unicast_rx_count().map(u64::from),
384                w,
385                tag,
386            ),
387            PACKET_UNICAST_TX_COUNT => Self::counter(
388                packets,
389                self.driver.packet_unicast_tx_count().map(u64::from),
390                w,
391                tag,
392            ),
393            OVERRUN_COUNT => Self::counter(errors, self.driver.overrun_count(), w, tag),
394            CURRENT_MAX_RATE => match self.driver.current_max_rate() {
395                Reading::Value(rate) => {
396                    w.unsigned(tag, rate).map_err(|_| Status::ResourceExhausted)
397                }
398                Reading::NotOperational => w.null(tag).map_err(|_| Status::ResourceExhausted),
399                Reading::Unsupported => Err(Status::UnsupportedAttribute),
400            },
401            _ => Err(Status::UnsupportedAttribute),
402        }
403    }
404
405    fn invoke(
406        &self,
407        resolved: &ResolvedCommand<'_>,
408        _fields: Option<&[u8]>,
409        _ctx: &InteractionContext<'_>,
410        _w: &mut TlvWriter<'_>,
411        _tag: Tag,
412    ) -> Result<Option<CommandId>, StatusIb> {
413        match resolved.command.id {
414            // §11.15.7's conformance is `ERRCNT` alone, which is narrower than the Ethernet
415            // cluster's `PKTCNT | ERRCNT` — a device that only counts packets has no reset.
416            RESET_COUNTS => {
417                if !self.counts_errors() {
418                    return Err(StatusIb::new(Status::UnsupportedCommand));
419                }
420                self.driver.reset_counts();
421                Ok(None)
422            }
423            _ => Err(StatusIb::new(Status::UnsupportedCommand)),
424        }
425    }
426}
427
428/// So a tuple of clusters can dispatch to it by id.
429impl<D: WiFiDriver, const E: usize> Cluster for WiFiNetworkDiagnostics<'_, D, E> {
430    const ID: ClusterId = ID;
431}
432
433#[cfg(test)]
434#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
435mod tests {
436    use super::*;
437    use crate::im::AttributeId;
438
439    struct Radio;
440
441    impl WiFiDriver for Radio {
442        fn bssid(&self) -> Option<[u8; 6]> {
443            Some([0x02, 0x00, 0x5E, 0x10, 0x00, 0x01])
444        }
445        fn security_type(&self) -> Option<SecurityTypeEnum> {
446            Some(SecurityTypeEnum::WPA3)
447        }
448        fn wi_fi_version(&self) -> Option<WiFiVersionEnum> {
449            Some(WiFiVersionEnum::Ax)
450        }
451        fn channel_number(&self) -> Option<u16> {
452            Some(36)
453        }
454        fn rssi(&self) -> Option<i8> {
455            Some(-58)
456        }
457        fn beacon_lost_count(&self) -> Option<u32> {
458            Some(3)
459        }
460        fn beacon_rx_count(&self) -> Option<u32> {
461            Some(900)
462        }
463        fn overrun_count(&self) -> Option<u64> {
464            Some(7)
465        }
466        fn current_max_rate(&self) -> Reading<u64> {
467            Reading::Value(144_400_000)
468        }
469    }
470
471    /// A radio that is powered but not associated: every mandatory attribute is `null`.
472    struct Detached;
473
474    impl WiFiDriver for Detached {}
475
476    fn read<D: WiFiDriver>(
477        cluster: &WiFiNetworkDiagnostics<'_, D>,
478        attribute: AttributeId,
479    ) -> Result<heapless::Vec<u8, 64>, Status> {
480        let descriptor = conforming(cluster.features, &ALL_OPTIONAL).expect("descriptor");
481        let cl = descriptor.descriptor();
482        let resolved = Resolved {
483            endpoint: 0,
484            cluster: &cl,
485            attribute,
486        };
487        let mut buf = [0u8; 64];
488        let mut w = TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
489        cluster.read(
490            &resolved,
491            &InteractionContext::new(),
492            &mut w,
493            Tag::Context(0),
494        )?;
495        Ok(heapless::Vec::from_slice(w.finish().expect("finish")).expect("fits"))
496    }
497
498    fn advertises(features: u32, attribute: AttributeId) -> bool {
499        conforming(features, &ALL_OPTIONAL)
500            .expect("descriptor")
501            .descriptor()
502            .attributes
503            .iter()
504            .any(|a| a.id == attribute)
505    }
506
507    /// §11.15.4's two features are independent, and each claims a different set of counters.
508    #[test]
509    fn an_unclaimed_counter_is_not_advertised_and_not_answered() {
510        assert!(!advertises(0, BEACON_RX_COUNT));
511        assert!(!advertises(0, BEACON_LOST_COUNT));
512        assert!(advertises(feature::PACKET_COUNTS, BEACON_RX_COUNT));
513        assert!(
514            !advertises(feature::PACKET_COUNTS, BEACON_LOST_COUNT),
515            "BeaconLostCount is ERRCNT's, not PKTCNT's — the two beacon counters are split \
516             across the features"
517        );
518        assert!(advertises(feature::ERROR_COUNTS, OVERRUN_COUNT));
519        assert!(!advertises(feature::ERROR_COUNTS, PACKET_UNICAST_TX_COUNT));
520
521        let none = WiFiNetworkDiagnostics::<_, 4>::new(&Radio, 0);
522        assert_eq!(
523            read(&none, BEACON_RX_COUNT),
524            Err(Status::UnsupportedAttribute)
525        );
526        assert_eq!(
527            read(&none, OVERRUN_COUNT),
528            Err(Status::UnsupportedAttribute)
529        );
530    }
531
532    /// Every attribute in §11.15.6 is nullable, and an unassociated radio is what `null` is
533    /// for. A device that answered `UNSUPPORTED_ATTRIBUTE` while its Wi-Fi was down would be
534    /// changing its own `AttributeList` from one read to the next.
535    #[test]
536    fn an_unassociated_radio_answers_null_rather_than_refusing() {
537        let detached = WiFiNetworkDiagnostics::<_, 4>::new(&Detached, feature::PACKET_COUNTS);
538        // 0x34 is a context-tagged null.
539        assert_eq!(read(&detached, BSSID).expect("bssid"), [0x34, 0x00]);
540        assert_eq!(read(&detached, RSSI).expect("rssi"), [0x34, 0x00]);
541        assert_eq!(
542            read(&detached, SECURITY_TYPE).expect("security"),
543            [0x34, 0x00]
544        );
545        assert_eq!(
546            read(&detached, BEACON_RX_COUNT).expect("claimed, so present and null"),
547            [0x34, 0x00]
548        );
549    }
550
551    /// `CurrentMaxRate` is the one optional attribute, so it is the one with three answers.
552    #[test]
553    fn the_only_optional_attribute_is_the_only_one_that_can_be_unsupported() {
554        assert!(
555            advertises(0, CURRENT_MAX_RATE),
556            "optional, so it is advertised only because ALL_OPTIONAL asks for it"
557        );
558        let reporting = WiFiNetworkDiagnostics::<_, 4>::new(&Radio, 0);
559        assert_eq!(
560            read(&reporting, CURRENT_MAX_RATE).expect("rate"),
561            [0x26, 0x00, 0x80, 0x5E, 0x9B, 0x08]
562        );
563
564        let silent = WiFiNetworkDiagnostics::<_, 4>::new(&Detached, 0);
565        assert_eq!(
566            read(&silent, CURRENT_MAX_RATE),
567            Err(Status::UnsupportedAttribute)
568        );
569    }
570
571    #[test]
572    fn values_round_trip_through_the_reader() {
573        let radio = WiFiNetworkDiagnostics::<_, 4>::new(
574            &Radio,
575            feature::PACKET_COUNTS | feature::ERROR_COUNTS,
576        );
577        assert_eq!(
578            read(&radio, BSSID).expect("bssid"),
579            [0x30, 0x00, 0x06, 0x02, 0x00, 0x5E, 0x10, 0x00, 0x01]
580        );
581        // `SecurityTypeEnum::WPA3` is 5, `WiFiVersionEnum::Ax` is 5.
582        assert_eq!(read(&radio, SECURITY_TYPE).expect("sec"), [0x24, 0x00, 5]);
583        assert_eq!(read(&radio, WI_FI_VERSION).expect("ver"), [0x24, 0x00, 5]);
584        assert_eq!(
585            read(&radio, CHANNEL_NUMBER).expect("chan"),
586            [0x24, 0x00, 36]
587        );
588        // -58 as a one-byte signed integer, which is the type `RSSI` actually has.
589        assert_eq!(read(&radio, RSSI).expect("rssi"), [0x20, 0x00, 0xC6]);
590        assert_eq!(
591            read(&radio, BEACON_LOST_COUNT).expect("lost"),
592            [0x24, 0x00, 3]
593        );
594        assert_eq!(
595            read(&radio, OVERRUN_COUNT).expect("overrun"),
596            [0x24, 0x00, 7]
597        );
598    }
599
600    /// §11.15.7's `ResetCounts` is `ERRCNT` alone, which differs from §11.16.7's
601    /// `PKTCNT | ERRCNT` — the kind of near-miss between two adjacent clusters that a shared
602    /// helper would have flattened.
603    #[test]
604    fn reset_counts_belongs_to_the_error_counts_feature_alone() {
605        assert!(
606            conforming(feature::PACKET_COUNTS, &Optional::NONE)
607                .expect("descriptor")
608                .descriptor()
609                .accepted_commands
610                .is_empty(),
611            "PKTCNT alone does not bring ResetCounts"
612        );
613
614        let descriptor = conforming(feature::ERROR_COUNTS, &Optional::NONE).expect("descriptor");
615        let cl = descriptor.descriptor();
616        let command = *cl
617            .accepted_commands
618            .iter()
619            .find(|c| c.id == RESET_COUNTS)
620            .expect("ERRCNT brings ResetCounts");
621        let resolved = ResolvedCommand {
622            endpoint: 0,
623            cluster: &cl,
624            command,
625        };
626        let mut buf = [0u8; 32];
627        let mut w = TlvWriter::new(&mut buf);
628
629        let packets = WiFiNetworkDiagnostics::<_, 4>::new(&Radio, feature::PACKET_COUNTS);
630        assert_eq!(
631            packets
632                .invoke(
633                    &resolved,
634                    None,
635                    &InteractionContext::new(),
636                    &mut w,
637                    Tag::Anonymous
638                )
639                .unwrap_err()
640                .status,
641            Status::UnsupportedCommand
642        );
643
644        let errors = WiFiNetworkDiagnostics::<_, 4>::new(&Radio, feature::ERROR_COUNTS);
645        assert!(
646            errors
647                .invoke(
648                    &resolved,
649                    None,
650                    &InteractionContext::new(),
651                    &mut w,
652                    Tag::Anonymous
653                )
654                .is_ok()
655        );
656    }
657
658    /// The queue drops its oldest rather than refusing: a radio that disconnects in a loop
659    /// must not be able to make the cluster fail, and the newest disconnection is the one a
660    /// support engineer wants.
661    #[test]
662    fn the_event_queue_is_bounded_and_keeps_the_newest() {
663        let radio = WiFiNetworkDiagnostics::<_, 2>::new(&Radio, 0);
664        radio.record(Event::Disconnection { reason_code: 1 });
665        radio.record(Event::Disconnection { reason_code: 2 });
666        radio.record(Event::ConnectionStatus(ConnectionStatusEnum::Connected));
667        let drained = radio.take_events();
668        assert_eq!(
669            drained.as_slice(),
670            [
671                Event::Disconnection { reason_code: 2 },
672                Event::ConnectionStatus(ConnectionStatusEnum::Connected)
673            ]
674        );
675        assert!(radio.take_events().is_empty(), "draining empties it");
676    }
677
678    #[test]
679    fn an_event_encodes_its_fields_under_the_data_tag() {
680        let mut buf = [0u8; 64];
681        let mut w = TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
682        let event = Event::AssociationFailure {
683            cause: AssociationFailureCauseEnum::AuthenticationFailed,
684            status: 0x000F,
685        };
686        event.encode(&mut w, Tag::Context(7)).expect("encode");
687        assert_eq!(event.id(), ASSOCIATION_FAILURE);
688        assert_eq!(
689            event.priority(),
690            EventPriority::Info,
691            "§11.15.8 gives all three events INFO priority, which is what decides which of the \
692             event store's three rings the record lands in"
693        );
694        assert_eq!(
695            w.finish().expect("finish"),
696            // struct ctx-7 { ctx-0 = 2, ctx-1 = 15 }
697            [0x35, 0x07, 0x24, 0x00, 0x02, 0x24, 0x01, 0x0F, 0x18]
698        );
699    }
700
701    /// §11.15.4's features must not invent elements the revision does not define.
702    #[test]
703    fn an_undefined_feature_is_refused() {
704        assert!(conforming(1 << 4, &Optional::NONE).is_err());
705    }
706}