1use 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
64pub trait EthernetDriver {
70 fn phy_rate(&self) -> Reading<PHYRateEnum> {
73 Reading::Unsupported
74 }
75
76 fn full_duplex(&self) -> Reading<bool> {
79 Reading::Unsupported
80 }
81
82 fn packet_rx_count(&self) -> u64 {
87 0
88 }
89
90 fn packet_tx_count(&self) -> u64 {
92 0
93 }
94
95 fn tx_err_count(&self) -> u64 {
97 0
98 }
99
100 fn collision_count(&self) -> u64 {
102 0
103 }
104
105 fn overrun_count(&self) -> u64 {
108 0
109 }
110
111 fn carrier_detect(&self) -> Reading<bool> {
113 Reading::Unsupported
114 }
115
116 fn time_since_reset(&self) -> Option<u64> {
121 None
122 }
123
124 fn reset_counts(&self) {}
130}
131
132#[derive(Debug, Clone, Copy, Default)]
134pub struct Unknown;
135
136impl EthernetDriver for Unknown {}
137
138pub 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
154pub const ALL_OPTIONAL: Optional<'static> = Optional {
156 attributes: &[PHY_RATE, FULL_DUPLEX, CARRIER_DETECT, TIME_SINCE_RESET],
157 commands: &[],
158 events: &[],
159};
160
161#[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 #[must_use]
171 pub const fn new(driver: &'a D, features: u32) -> Self {
172 Self { driver, features }
173 }
174
175 #[must_use]
177 const fn counts_packets(&self) -> bool {
178 self.features & feature::PACKET_COUNTS != 0
179 }
180
181 #[must_use]
183 const fn counts_errors(&self) -> bool {
184 self.features & feature::ERROR_COUNTS != 0
185 }
186}
187
188fn 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 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 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 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
284impl<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 Ok(heapless::Vec::from_slice(w.finish().expect("finish")).expect("fits"))
349 }
350
351 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 #[test]
367 fn an_unclaimed_counter_is_not_advertised_and_not_answered() {
368 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 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 #[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 #[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 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 #[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 #[test]
503 fn an_undefined_feature_is_refused() {
504 assert!(conforming(1 << 5, &Optional::NONE).is_err());
505 }
506}