1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
98pub struct MacCounters {
99 pub tx_total: Option<u32>,
101 pub tx_unicast: Option<u32>,
103 pub tx_broadcast: Option<u32>,
105 pub tx_ack_requested: Option<u32>,
107 pub tx_acked: Option<u32>,
109 pub tx_no_ack_requested: Option<u32>,
111 pub tx_data: Option<u32>,
113 pub tx_data_poll: Option<u32>,
115 pub tx_beacon: Option<u32>,
117 pub tx_beacon_request: Option<u32>,
119 pub tx_other: Option<u32>,
121 pub tx_retry: Option<u32>,
123 pub tx_direct_max_retry_expiry: Option<u32>,
125 pub tx_indirect_max_retry_expiry: Option<u32>,
127 pub tx_err_cca: Option<u32>,
129 pub tx_err_abort: Option<u32>,
131 pub tx_err_busy_channel: Option<u32>,
133 pub rx_total: Option<u32>,
135 pub rx_unicast: Option<u32>,
137 pub rx_broadcast: Option<u32>,
139 pub rx_data: Option<u32>,
141 pub rx_data_poll: Option<u32>,
143 pub rx_beacon: Option<u32>,
145 pub rx_beacon_request: Option<u32>,
147 pub rx_other: Option<u32>,
149 pub rx_address_filtered: Option<u32>,
151 pub rx_dest_addr_filtered: Option<u32>,
153 pub rx_duplicated: Option<u32>,
155 pub rx_err_no_frame: Option<u32>,
157 pub rx_err_unknown_neighbor: Option<u32>,
159 pub rx_err_invalid_src_addr: Option<u32>,
161 pub rx_err_sec: Option<u32>,
163 pub rx_err_fcs: Option<u32>,
165 pub rx_err_other: Option<u32>,
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
174pub struct MleCounters {
175 pub detached_role: Option<u16>,
177 pub child_role: Option<u16>,
179 pub router_role: Option<u16>,
181 pub leader_role: Option<u16>,
183 pub attach_attempt: Option<u16>,
185 pub partition_id_change: Option<u16>,
187 pub better_partition_attach_attempt: Option<u16>,
189 pub parent_change: Option<u16>,
191}
192
193pub trait ThreadDriver {
199 fn channel(&self) -> Option<u16> {
201 None
202 }
203
204 fn routing_role(&self) -> Option<RoutingRoleEnum> {
209 None
210 }
211
212 fn network_name(&self) -> Option<&str> {
214 None
215 }
216
217 fn pan_id(&self) -> Option<u16> {
219 None
220 }
221
222 fn extended_pan_id(&self) -> Option<u64> {
224 None
225 }
226
227 fn mesh_local_prefix(&self) -> Option<&[u8]> {
229 None
230 }
231
232 fn overrun_count(&self) -> u64 {
237 0
238 }
239
240 fn neighbors(&self) -> &[NeighborTableStruct] {
242 &[]
243 }
244
245 fn routes(&self) -> &[RouteTableStruct] {
247 &[]
248 }
249
250 fn partition_id(&self) -> Option<u32> {
252 None
253 }
254
255 fn weighting(&self) -> Option<u16> {
257 None
258 }
259
260 fn data_version(&self) -> Option<u16> {
262 None
263 }
264
265 fn stable_data_version(&self) -> Option<u16> {
267 None
268 }
269
270 fn leader_router_id(&self) -> Option<u8> {
272 None
273 }
274
275 fn mle_counters(&self) -> MleCounters {
277 MleCounters::EMPTY
278 }
279
280 fn mac_counters(&self) -> MacCounters {
285 MacCounters::EMPTY
286 }
287
288 fn active_timestamp(&self) -> Option<u64> {
290 None
291 }
292
293 fn pending_timestamp(&self) -> Option<u64> {
295 None
296 }
297
298 fn delay(&self) -> Option<u32> {
300 None
301 }
302
303 fn security_policy(&self) -> Option<SecurityPolicy> {
305 None
306 }
307
308 fn channel_page0_mask(&self) -> Option<&[u8]> {
310 None
311 }
312
313 fn operational_dataset_components(&self) -> Option<OperationalDatasetComponents> {
315 None
316 }
317
318 fn active_network_faults(&self) -> &[NetworkFaultEnum] {
320 &[]
321 }
322
323 fn ext_address(&self) -> Option<u64> {
325 None
326 }
327
328 fn rloc16(&self) -> Option<u16> {
330 None
331 }
332
333 fn reset_counts(&self) {}
338}
339
340impl MacCounters {
341 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 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#[derive(Debug, Clone, Copy, Default)]
396pub struct Unknown;
397
398impl ThreadDriver for Unknown {}
399
400#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum Event {
406 ConnectionStatus(ConnectionStatusEnum),
408 NetworkFaultChange {
410 current: heapless::Vec<NetworkFaultEnum, 4>,
412 previous: heapless::Vec<NetworkFaultEnum, 4>,
414 },
415}
416
417impl Event {
418 #[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 #[must_use]
429 pub const fn priority(&self) -> EventPriority {
430 EventPriority::Info
431 }
432
433 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
453fn 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
463pub 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
481pub 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#[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#[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#[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#[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 #[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 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 #[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
610fn 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
624fn 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
642fn 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 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 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
1050impl<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 struct Detached;
1119
1120 impl ThreadDriver for Detached {}
1121
1122 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 #[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 #[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 #[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 #[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 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 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 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 #[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 [
1358 0x35, 0x07, 0x36, 0x00, 0x04, 0x01, 0x18, 0x36, 0x01, 0x18, 0x18
1359 ]
1360 );
1361 assert!(stack.take_events().is_empty());
1362 }
1363
1364 #[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 #[test]
1383 fn an_undefined_feature_is_refused() {
1384 assert!(conforming(1 << 4, &Optional::NONE).is_err());
1385 }
1386}