1use 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
72pub trait WiFiDriver {
79 fn bssid(&self) -> Option<[u8; 6]> {
81 None
82 }
83
84 fn security_type(&self) -> Option<SecurityTypeEnum> {
86 None
87 }
88
89 fn wi_fi_version(&self) -> Option<WiFiVersionEnum> {
91 None
92 }
93
94 fn channel_number(&self) -> Option<u16> {
96 None
97 }
98
99 fn rssi(&self) -> Option<i8> {
105 None
106 }
107
108 fn beacon_lost_count(&self) -> Option<u32> {
110 None
111 }
112
113 fn beacon_rx_count(&self) -> Option<u32> {
115 None
116 }
117
118 fn packet_multicast_rx_count(&self) -> Option<u32> {
120 None
121 }
122
123 fn packet_multicast_tx_count(&self) -> Option<u32> {
125 None
126 }
127
128 fn packet_unicast_rx_count(&self) -> Option<u32> {
130 None
131 }
132
133 fn packet_unicast_tx_count(&self) -> Option<u32> {
135 None
136 }
137
138 fn current_max_rate(&self) -> Reading<u64> {
141 Reading::Unsupported
142 }
143
144 fn overrun_count(&self) -> Option<u64> {
146 None
147 }
148
149 fn reset_counts(&self) {}
154}
155
156#[derive(Debug, Clone, Copy, Default)]
158pub struct Unknown;
159
160impl WiFiDriver for Unknown {}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub enum Event {
168 Disconnection {
170 reason_code: u16,
172 },
173 AssociationFailure {
175 cause: AssociationFailureCauseEnum,
177 status: u16,
179 },
180 ConnectionStatus(ConnectionStatusEnum),
182}
183
184impl Event {
185 #[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 #[must_use]
197 pub const fn priority(&self) -> EventPriority {
198 EventPriority::Info
199 }
200
201 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
224pub 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
239pub const ALL_OPTIONAL: Optional<'static> = Optional {
241 attributes: &[CURRENT_MAX_RATE],
242 commands: &[],
243 events: &[DISCONNECTION, ASSOCIATION_FAILURE, CONNECTION_STATUS],
244};
245
246#[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 #[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 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 #[must_use]
283 pub fn take_events(&self) -> heapless::Vec<Event, E> {
284 core::mem::take(&mut self.events.borrow_mut())
285 }
286
287 const fn counts_packets(&self) -> bool {
289 self.features & feature::PACKET_COUNTS != 0
290 }
291
292 const fn counts_errors(&self) -> bool {
294 self.features & feature::ERROR_COUNTS != 0
295 }
296
297 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
319fn 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 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
428impl<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 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 #[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 #[test]
536 fn an_unassociated_radio_answers_null_rather_than_refusing() {
537 let detached = WiFiNetworkDiagnostics::<_, 4>::new(&Detached, feature::PACKET_COUNTS);
538 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 #[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 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 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 #[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 #[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 [0x35, 0x07, 0x24, 0x00, 0x02, 0x24, 0x01, 0x0F, 0x18]
698 );
699 }
700
701 #[test]
703 fn an_undefined_feature_is_refused() {
704 assert!(conforming(1 << 4, &Optional::NONE).is_err());
705 }
706}