use std::sync::Arc;
use std::time::Duration;
use zenkey::origin::LocalOrigin;
use zenoh::Session;
use crate::plane::SduPlane;
use modem_contract::registry::modem::Subject;
pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(5_000);
struct Snapshot {
sdu: Option<SduCounters>,
device: modem_device::Report,
netdev: Option<modem_device::NetdevStats>,
counters: std::collections::BTreeMap<(String, String), u64>,
}
fn counters_of(
counters: Vec<modem_device::Counter>,
) -> std::collections::BTreeMap<(String, String), u64> {
counters
.into_iter()
.map(|c| ((c.scope, c.name), c.value))
.collect()
}
struct SduCounters {
medium: modem_device::Metrics,
sched_dropped: u64,
sched_stale: u64,
sched_peerless: u64,
tx_failed: u64,
unroutable: u64,
rx_oversize: u64,
tx_oversize: u64,
queue_depth: u64,
lane_backlog: Option<u64>,
}
impl Snapshot {
fn of(plane: &dyn SduPlane) -> Self {
let s = plane.scheduler();
let lane_backlog = plane
.lanes()
.iter()
.filter_map(|l| l.backlog_bytes)
.reduce(|a, b| a + b);
Self {
sdu: Some(SduCounters {
medium: plane.medium_metrics(),
sched_dropped: s.dropped,
sched_stale: s.stale,
sched_peerless: s.peerless,
tx_failed: s.tx_failed,
unroutable: s.unroutable,
rx_oversize: s.rx_oversize,
tx_oversize: s.tx_oversize,
queue_depth: s.queue_depth(),
lane_backlog,
}),
device: plane.report(),
netdev: None,
counters: counters_of(plane.counters()),
}
}
fn of_device(dev: &dyn modem_device::Device) -> Self {
Self {
sdu: None,
device: dev.report(),
netdev: None,
counters: counters_of(dev.counters()),
}
}
fn of_netdev(dev: &dyn modem_device::Netdev) -> Self {
Self {
sdu: None,
device: dev.report(),
netdev: Some(dev.statistics()),
counters: counters_of(dev.counters()),
}
}
#[allow(dead_code)]
fn counter(&self, scope: &str, name: &str) -> Option<u64> {
self.counters
.get(&(scope.to_string(), name.to_string()))
.copied()
}
fn sdu(&self) -> Option<&SduCounters> {
self.sdu.as_ref()
}
}
pub enum Source {
Sdu(Arc<dyn SduPlane>),
Device(Arc<dyn modem_device::Device>),
Netdev(Arc<dyn modem_device::Netdev>),
}
impl Source {
pub(crate) fn of(node: &crate::host::Node) -> Self {
match node.plane() {
crate::host::Plane::Sdu(plane) => Self::Sdu(plane.clone()),
crate::host::Plane::Netdev(dev) => Self::Netdev(dev.clone()),
}
}
fn snapshot(&self) -> Snapshot {
match self {
Source::Sdu(p) => Snapshot::of(p.as_ref()),
Source::Device(d) => Snapshot::of_device(d.as_ref()),
Source::Netdev(n) => Snapshot::of_netdev(n.as_ref()),
}
}
fn has_configuration(&self) -> bool {
match self {
Source::Sdu(p) => p.configuration().is_some(),
Source::Device(d) => d.configuration().is_some(),
Source::Netdev(n) => n.configuration().is_some(),
}
}
fn has_actions(&self) -> bool {
match self {
Source::Sdu(p) => p.actions().is_some(),
Source::Device(d) => d.actions().is_some(),
Source::Netdev(n) => n.actions().is_some(),
}
}
fn has_netdev(&self) -> bool {
matches!(self, Source::Netdev(_))
}
fn has_destinations(&self) -> bool {
matches!(self, Source::Netdev(n) if n.destinations().is_some())
}
}
pub(crate) fn capabilities_of(device: &str, source: &Source) -> std::collections::BTreeSet<String> {
let snapshot = source.snapshot();
let mut holds = std::collections::BTreeSet::new();
if matches!(source, Source::Sdu(_)) {
holds.insert("sdu".to_string());
}
if source.has_configuration() {
holds.insert("config".to_string());
}
if source.has_actions() {
holds.insert("actions".to_string());
}
if source.has_netdev() {
holds.insert("netdev".to_string());
}
if source.has_destinations() {
holds.insert("destinations".to_string());
}
if snapshot.device.registration.is_some() {
holds.insert("registration".to_string());
}
for (subject, value) in READINGS {
if value(&snapshot).is_none() {
continue;
}
for (kind, name) in subject(device).when() {
if matches!(kind, zenkey::slice::PredicateKind::Capability) {
holds.insert((*name).to_string());
}
}
}
holds
}
pub const STALE_AFTER: Duration = Duration::from_secs(600);
impl Snapshot {
fn stale(&self) -> bool {
self.device
.age_ms
.is_some_and(|age| age > STALE_AFTER.as_millis() as u64)
}
fn fresh_duty(&self) -> Option<modem_device::DutyCycle> {
if self.stale() {
None
} else {
self.device.duty_cycle
}
}
fn fresh<T: Copy>(&self, v: Option<T>) -> Option<T> {
if self.stale() { None } else { v }
}
fn fresh_signal(&self) -> Option<u8> {
if self.stale() {
None
} else {
self.device.signal_bars
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Value {
Int(u64),
Real(f64),
}
impl Value {
fn milli(m: i32) -> Self {
Self::Real(f64::from(m) / 1000.0)
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Int(v) => write!(f, "{v}"),
Self::Real(v) => write!(f, "{v}"),
}
}
}
type Reading = (fn(&str) -> Subject, fn(&Snapshot) -> Option<Value>);
const READINGS: &[Reading] = &[
(
|d| Subject::device_sdu_tx_sdus_total(d),
|s| (s.sdu().map(|c| c.medium.tx_sdus)).map(Value::Int),
),
(
|d| Subject::device_sdu_tx_bytes_total(d),
|s| (s.sdu().map(|c| c.medium.tx_bytes)).map(Value::Int),
),
(
|d| Subject::device_sdu_rx_sdus_total(d),
|s| (s.sdu().map(|c| c.medium.rx_sdus)).map(Value::Int),
),
(
|d| Subject::device_sdu_rx_bytes_total(d),
|s| (s.sdu().map(|c| c.medium.rx_bytes)).map(Value::Int),
),
(
|d| Subject::device_sdu_dropped_total(d),
|s| (s.sdu().map(|c| c.medium.dropped)).map(Value::Int),
),
(
|d| Subject::device_sched_dropped_total(d),
|s| (s.sdu().map(|c| c.sched_dropped)).map(Value::Int),
),
(
|d| Subject::device_sched_stale_total(d),
|s| (s.sdu().map(|c| c.sched_stale)).map(Value::Int),
),
(
|d| Subject::device_sched_peerless_total(d),
|s| (s.sdu().map(|c| c.sched_peerless)).map(Value::Int),
),
(
|d| Subject::device_sdu_tx_failed_total(d),
|s| (s.sdu().map(|c| c.tx_failed)).map(Value::Int),
),
(
|d| Subject::device_sdu_rx_unroutable_total(d),
|s| (s.sdu().map(|c| c.unroutable)).map(Value::Int),
),
(
|d| Subject::device_sdu_rx_oversize_total(d),
|s| (s.sdu().map(|c| c.rx_oversize)).map(Value::Int),
),
(
|d| Subject::device_sdu_tx_oversize_total(d),
|s| (s.sdu().map(|c| c.tx_oversize)).map(Value::Int),
),
(
|d| Subject::device_air_airtime_ms_total(d),
|s| (s.device.time_on_air_ms).map(Value::Int),
),
(
|d| Subject::device_air_retransmits_total(d),
|s| (s.device.retransmits).map(Value::Int),
),
(
|d| Subject::device_air_bytes_wasted_total(d),
|s| (s.device.bytes_wasted).map(Value::Int),
),
(
|d| Subject::device_air_rx_errors_total(d),
|s| (s.device.rx_errors).map(Value::Int),
),
(
|d| Subject::device_air_duty_cycle_available(d),
|s| (s.fresh_duty().map(|c| u64::from(c.available))).map(Value::Int),
),
(
|d| Subject::device_air_duty_cycle_wait_ms(d),
|s| (s.fresh_duty().map(|c| c.next_available_in_ms)).map(Value::Int),
),
(
|d| Subject::device_radio_signal_bars(d),
|s| (s.fresh_signal().map(u64::from)).map(Value::Int),
),
(
|d| Subject::device_sched_queue_depth(d),
|s| (s.sdu().map(|c| c.queue_depth)).map(Value::Int),
),
(
|d| Subject::device_sched_lane_backlog_bytes(d),
|s| s.sdu().and_then(|c| c.lane_backlog).map(Value::Int),
),
(
|d| Subject::device_radio_rssi(d),
|s| s.fresh(s.device.rssi).map(Value::milli),
),
(
|d| Subject::device_radio_rsrp(d),
|s| s.fresh(s.device.rsrp).map(Value::milli),
),
(
|d| Subject::device_radio_rsrq(d),
|s| s.fresh(s.device.rsrq).map(Value::milli),
),
(
|d| Subject::device_radio_snr(d),
|s| s.fresh(s.device.snr).map(Value::milli),
),
(
|d| Subject::device_radio_error_rate(d),
|s| s.fresh(s.device.error_rate).map(Value::milli),
),
(
|d| Subject::device_link_rx_rate(d),
|s| s.fresh(s.device.rx_rate).map(Value::Int),
),
(
|d| Subject::device_link_tx_rate(d),
|s| s.fresh(s.device.tx_rate).map(Value::Int),
),
(
|d| Subject::device_link_rx_max_rate(d),
|s| s.fresh(s.device.rx_max_rate).map(Value::Int),
),
(
|d| Subject::device_link_tx_max_rate(d),
|s| s.fresh(s.device.tx_max_rate).map(Value::Int),
),
(
|d| Subject::device_link_latency(d),
|s| s.fresh(s.device.latency).map(Value::Int),
),
(
|d| Subject::device_link_resources(d),
|s| s.fresh(s.device.resources).map(Value::milli),
),
(
|d| Subject::device_link_rx_quality(d),
|s| s.fresh(s.device.rx_quality).map(Value::milli),
),
(
|d| Subject::device_link_tx_quality(d),
|s| s.fresh(s.device.tx_quality).map(Value::milli),
),
(
|d| Subject::device_if_in_octets(d),
|s| s.netdev.and_then(|n| n.in_octets).map(Value::Int),
),
(
|d| Subject::device_if_out_octets(d),
|s| s.netdev.and_then(|n| n.out_octets).map(Value::Int),
),
(
|d| Subject::device_if_in_errors(d),
|s| s.netdev.and_then(|n| n.in_errors).map(Value::Int),
),
(
|d| Subject::device_if_out_errors(d),
|s| s.netdev.and_then(|n| n.out_errors).map(Value::Int),
),
(
|d| Subject::device_if_in_discards(d),
|s| s.netdev.and_then(|n| n.in_discards).map(Value::Int),
),
(
|d| Subject::device_if_out_discards(d),
|s| s.netdev.and_then(|n| n.out_discards).map(Value::Int),
),
(
|d| Subject::device_if_in_multicast_pkts(d),
|s| s.netdev.and_then(|n| n.in_multicast_pkts).map(Value::Int),
),
(
|d| Subject::device_if_in_pkts(d),
|s| s.netdev.and_then(|n| n.in_pkts).map(Value::Int),
),
(
|d| Subject::device_if_out_pkts(d),
|s| s.netdev.and_then(|n| n.out_pkts).map(Value::Int),
),
(
|d| Subject::device_if_qdisc_backlog_bytes(d),
|s| s.netdev.and_then(|n| n.qdisc_backlog_bytes).map(Value::Int),
),
(
|d| Subject::device_if_qdisc_backlog_pkts(d),
|s| s.netdev.and_then(|n| n.qdisc_backlog_pkts).map(Value::Int),
),
];
pub fn subjects(device: &str) -> Vec<Subject> {
READINGS.iter().map(|(name, _)| name(device)).collect()
}
pub fn values(plane: &dyn SduPlane) -> Vec<Option<Value>> {
values_of(&Snapshot::of(plane))
}
pub fn netdev_values(dev: &dyn modem_device::Netdev) -> Vec<Option<Value>> {
values_of(&Snapshot::of_netdev(dev))
}
fn values_of(snap: &Snapshot) -> Vec<Option<Value>> {
READINGS.iter().map(|(_, read)| read(snap)).collect()
}
pub async fn publish_loop(
session: Session,
origin: LocalOrigin,
device: String,
source: Source,
interval: Duration,
) {
let mut publishers = Vec::new();
for subject in subjects(&device) {
let qos = subject.qos();
let key = modem_contract::registry::modem::key(&origin, &subject);
match session
.declare_publisher(key.as_keyexpr().to_owned())
.congestion_control(qos.congestion_control())
.priority(qos.priority())
.express(qos.express())
.reliability(qos.reliability())
.await
{
Ok(p) => publishers.push(p),
Err(e) => {
tracing::error!(key = %key, error = %e, "could not declare a telemetry publisher");
return;
}
}
}
loop {
for (publisher, value) in publishers.iter().zip(values_of(&source.snapshot())) {
let Some(value) = value else {
continue;
};
if let Err(e) = publisher
.put(value.to_string())
.encoding(zenoh::bytes::Encoding::APPLICATION_JSON)
.await
{
tracing::debug!(
key = %publisher.key_expr(),
error = %e,
"telemetry publication failed"
);
}
}
tokio::time::sleep(interval).await;
}
}