use crate::dm::spec::{Conforming, Optional};
use crate::dm::{Resolved, ResolvedCommand};
use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
use crate::tlv::{Tag, TlvWriter};
use super::Cluster;
pub use super::Reading;
use crate::clusters::generated::ethernet_network_diagnostics as spec_eth;
pub use spec_eth::{ID, PHYRateEnum, PICS, REVISION, feature};
use spec_eth::attribute::{
CARRIER_DETECT, COLLISION_COUNT, FULL_DUPLEX, OVERRUN_COUNT, PACKET_RX_COUNT, PACKET_TX_COUNT,
PHY_RATE, TIME_SINCE_RESET, TX_ERR_COUNT,
};
use spec_eth::command::RESET_COUNTS;
pub trait EthernetDriver {
fn phy_rate(&self) -> Reading<PHYRateEnum> {
Reading::Unsupported
}
fn full_duplex(&self) -> Reading<bool> {
Reading::Unsupported
}
fn packet_rx_count(&self) -> u64 {
0
}
fn packet_tx_count(&self) -> u64 {
0
}
fn tx_err_count(&self) -> u64 {
0
}
fn collision_count(&self) -> u64 {
0
}
fn overrun_count(&self) -> u64 {
0
}
fn carrier_detect(&self) -> Reading<bool> {
Reading::Unsupported
}
fn time_since_reset(&self) -> Option<u64> {
None
}
fn reset_counts(&self) {}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Unknown;
impl EthernetDriver for Unknown {}
pub fn conforming(
features: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Conforming<14, 1, 0, 0>> {
Conforming::new(&spec_eth::CLUSTER, features, optional)
}
pub const ALL_OPTIONAL: Optional<'static> = Optional {
attributes: &[PHY_RATE, FULL_DUPLEX, CARRIER_DETECT, TIME_SINCE_RESET],
commands: &[],
events: &[],
};
#[derive(Debug)]
pub struct EthernetNetworkDiagnostics<'a, D: EthernetDriver> {
driver: &'a D,
features: u32,
}
impl<'a, D: EthernetDriver> EthernetNetworkDiagnostics<'a, D> {
#[must_use]
pub const fn new(driver: &'a D, features: u32) -> Self {
Self { driver, features }
}
#[must_use]
const fn counts_packets(&self) -> bool {
self.features & feature::PACKET_COUNTS != 0
}
#[must_use]
const fn counts_errors(&self) -> bool {
self.features & feature::ERROR_COUNTS != 0
}
}
fn reading<T>(
value: Reading<T>,
w: &mut TlvWriter<'_>,
tag: Tag,
encode: impl FnOnce(&mut TlvWriter<'_>, Tag, T) -> crate::error::Result<()>,
) -> Result<(), Status> {
match value {
Reading::Value(v) => encode(w, tag, v).map_err(|_| Status::ResourceExhausted),
Reading::NotOperational => w.null(tag).map_err(|_| Status::ResourceExhausted),
Reading::Unsupported => Err(Status::UnsupportedAttribute),
}
}
impl<D: EthernetDriver> ClusterHandler for EthernetNetworkDiagnostics<'_, D> {
fn read(
&self,
resolved: &Resolved<'_>,
_ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
let counter = |claimed: bool, value: u64| -> Result<u64, Status> {
if claimed {
Ok(value)
} else {
Err(Status::UnsupportedAttribute)
}
};
match resolved.attribute {
PHY_RATE => reading(self.driver.phy_rate(), w, tag, |w, tag, rate| {
w.unsigned(tag, u64::from(rate.value()))
}),
FULL_DUPLEX => reading(self.driver.full_duplex(), w, tag, |w, tag, v| {
w.bool(tag, v)
}),
CARRIER_DETECT => reading(self.driver.carrier_detect(), w, tag, |w, tag, v| {
w.bool(tag, v)
}),
PACKET_RX_COUNT => full(w.unsigned(
tag,
counter(self.counts_packets(), self.driver.packet_rx_count())?,
)),
PACKET_TX_COUNT => full(w.unsigned(
tag,
counter(self.counts_packets(), self.driver.packet_tx_count())?,
)),
TX_ERR_COUNT => full(w.unsigned(
tag,
counter(self.counts_errors(), self.driver.tx_err_count())?,
)),
COLLISION_COUNT => full(w.unsigned(
tag,
counter(self.counts_errors(), self.driver.collision_count())?,
)),
OVERRUN_COUNT => full(w.unsigned(
tag,
counter(self.counts_errors(), self.driver.overrun_count())?,
)),
TIME_SINCE_RESET => match self.driver.time_since_reset() {
Some(minutes) => full(w.unsigned(tag, minutes)),
None => Err(Status::UnsupportedAttribute),
},
_ => Err(Status::UnsupportedAttribute),
}
}
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
_fields: Option<&[u8]>,
_ctx: &InteractionContext<'_>,
_w: &mut TlvWriter<'_>,
_tag: Tag,
) -> Result<Option<CommandId>, StatusIb> {
match resolved.command.id {
RESET_COUNTS => {
if !self.counts_packets() && !self.counts_errors() {
return Err(StatusIb::new(Status::UnsupportedCommand));
}
self.driver.reset_counts();
Ok(None)
}
_ => Err(StatusIb::new(Status::UnsupportedCommand)),
}
}
}
impl<D: EthernetDriver> Cluster for EthernetNetworkDiagnostics<'_, D> {
const ID: ClusterId = ID;
}
#[cfg(test)]
#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
mod tests {
use super::*;
use crate::im::AttributeId;
struct Nic;
impl EthernetDriver for Nic {
fn phy_rate(&self) -> Reading<PHYRateEnum> {
Reading::Value(PHYRateEnum::Rate1G)
}
fn full_duplex(&self) -> Reading<bool> {
Reading::Value(true)
}
fn carrier_detect(&self) -> Reading<bool> {
Reading::NotOperational
}
fn packet_rx_count(&self) -> u64 {
11
}
fn packet_tx_count(&self) -> u64 {
22
}
fn tx_err_count(&self) -> u64 {
33
}
fn collision_count(&self) -> u64 {
44
}
fn overrun_count(&self) -> u64 {
55
}
fn time_since_reset(&self) -> Option<u64> {
Some(7)
}
}
fn read<D: EthernetDriver>(
cluster: &EthernetNetworkDiagnostics<'_, D>,
attribute: AttributeId,
) -> Result<heapless::Vec<u8, 64>, Status> {
let descriptor = conforming(cluster.features, &ALL_OPTIONAL).expect("descriptor");
let cl = descriptor.descriptor();
let resolved = Resolved {
endpoint: 0,
cluster: &cl,
attribute,
};
let mut buf = [0u8; 64];
let mut w = TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
cluster.read(
&resolved,
&InteractionContext::new(),
&mut w,
Tag::Context(0),
)?;
Ok(heapless::Vec::from_slice(w.finish().expect("finish")).expect("fits"))
}
fn advertises(features: u32, attribute: AttributeId) -> bool {
conforming(features, &ALL_OPTIONAL)
.expect("descriptor")
.descriptor()
.attributes
.iter()
.any(|a| a.id == attribute)
}
#[test]
fn an_unclaimed_counter_is_not_advertised_and_not_answered() {
assert!(!advertises(0, PACKET_RX_COUNT));
assert!(!advertises(0, TX_ERR_COUNT));
assert!(advertises(feature::PACKET_COUNTS, PACKET_RX_COUNT));
assert!(
!advertises(feature::PACKET_COUNTS, TX_ERR_COUNT),
"PKTCNT does not imply ERRCNT"
);
assert!(advertises(feature::ERROR_COUNTS, COLLISION_COUNT));
assert!(
!advertises(feature::ERROR_COUNTS, PACKET_TX_COUNT),
"and ERRCNT does not imply PKTCNT"
);
let none = EthernetNetworkDiagnostics::new(&Nic, 0);
assert_eq!(
read(&none, PACKET_RX_COUNT),
Err(Status::UnsupportedAttribute)
);
assert_eq!(read(&none, TX_ERR_COUNT), Err(Status::UnsupportedAttribute));
let packets = EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS);
assert!(read(&packets, PACKET_RX_COUNT).is_ok());
assert_eq!(
read(&packets, TX_ERR_COUNT),
Err(Status::UnsupportedAttribute)
);
}
#[test]
fn a_driver_can_be_asked_which_attributes_it_reports() {
assert!(Reading::Value(PHYRateEnum::Rate1G).is_supported());
assert!(
Reading::<bool>::NotOperational.is_supported(),
"null is a value the device reports, not a missing attribute"
);
assert!(!Reading::<bool>::Unsupported.is_supported());
assert_eq!(
Reading::<bool>::default(),
Reading::Unsupported,
"the default is the one a device that has not said otherwise should have"
);
}
#[test]
fn null_and_unsupported_are_different_answers() {
let nic = EthernetNetworkDiagnostics::new(&Nic, 0);
let carrier = read(&nic, CARRIER_DETECT).expect("carrier detect is reported");
assert_eq!(carrier, [0x34, 0x00], "null, not absent");
let blank = EthernetNetworkDiagnostics::new(&Unknown, 0);
assert_eq!(
read(&blank, CARRIER_DETECT),
Err(Status::UnsupportedAttribute),
"a device that cannot measure it says so"
);
}
#[test]
fn values_round_trip_through_the_reader() {
let nic =
EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS | feature::ERROR_COUNTS);
assert_eq!(read(&nic, PHY_RATE).expect("phy"), [0x24, 0x00, 0x02]);
assert_eq!(read(&nic, FULL_DUPLEX).expect("duplex"), [0x29, 0x00]);
assert_eq!(read(&nic, PACKET_RX_COUNT).expect("rx"), [0x24, 0x00, 11]);
assert_eq!(
read(&nic, OVERRUN_COUNT).expect("overrun"),
[0x24, 0x00, 55]
);
assert_eq!(
read(&nic, TIME_SINCE_RESET).expect("since"),
[0x24, 0x00, 7]
);
}
#[test]
fn reset_counts_needs_a_counter_to_reset() {
let descriptor = conforming(feature::PACKET_COUNTS, &Optional::NONE).expect("descriptor");
let cl = descriptor.descriptor();
let command = *cl
.accepted_commands
.iter()
.find(|c| c.id == RESET_COUNTS)
.expect("ResetCounts is present when PKTCNT is claimed");
let resolved = ResolvedCommand {
endpoint: 0,
cluster: &cl,
command,
};
let mut buf = [0u8; 32];
let mut w = TlvWriter::new(&mut buf);
let none = EthernetNetworkDiagnostics::new(&Nic, 0);
assert_eq!(
none.invoke(
&resolved,
None,
&InteractionContext::new(),
&mut w,
Tag::Anonymous
)
.unwrap_err()
.status,
Status::UnsupportedCommand,
"a device with no counters has no ResetCounts"
);
let packets = EthernetNetworkDiagnostics::new(&Nic, feature::PACKET_COUNTS);
assert!(
packets
.invoke(
&resolved,
None,
&InteractionContext::new(),
&mut w,
Tag::Anonymous
)
.is_ok()
);
}
#[test]
fn an_undefined_feature_is_refused() {
assert!(conforming(1 << 5, &Optional::NONE).is_err());
}
}