modem-mgmt 0.3.0

The management plane of zenoh-modem as a library: serve every device on a host over Zenoh, for any driver that links the contract
Documentation
//! The producer's registration document, `state/modem/sensor` (#122).
//!
//! zenkey RFC 04 §5: who this producer is — versions — and, since v1.41,
//! **which `when` predicates hold here, per device**. The registry says which
//! surfaces are conditional and on what; this document says which of those
//! conditions hold on *this* host, which is what lets a consumer read a gated
//! subject's silence as honest and a conformance suite judge it (#131). The
//! map is derived from the same readings table the telemetry loop publishes
//! from, so it cannot claim a capability whose reading is silent.
//!
//! Refreshed on the state cadence like any other document. `config_hash` is
//! empty until #125 gives a device an effective configuration to hash.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use modem_contract::registry::modem::{Subject, key};
use zenkey::origin::LocalOrigin;
use zenoh::Session;

use crate::host::Host;
use crate::telemetry;

/// `git describe` of the tree this plane was built from, when the build had
/// one (`build.rs`); absent otherwise, which the document says by omission.
const BUILD: Option<&str> = option_env!("ZENOH_MODEM_GIT_DESCRIBE");

/// The document, now.
pub(crate) fn document(host: &Host) -> super::Sensor {
    let mut capabilities: BTreeMap<String, Vec<String>> = host
        .nodes()
        .iter()
        .map(|node| {
            let holds = telemetry::capabilities_of(node.name(), &telemetry::Source::of(node));
            (node.name().to_string(), holds.into_iter().collect())
        })
        .collect();
    // The producer's own, device-less capabilities: none declared yet, and
    // the key is present so a reader sees that it was asked.
    capabilities.insert("*".to_string(), Vec::new());
    super::Sensor {
        version: host.version().to_string(),
        build: BUILD.map(str::to_string),
        zenkey: modem_contract::ZENKEY_VERSION.to_string(),
        capabilities,
        config_hash: BTreeMap::new(),
    }
}

pub(super) async fn publish_loop(
    session: Session,
    origin: LocalOrigin,
    host: Arc<Host>,
    ttl_s: u64,
) {
    let subject = Subject::Sensor;
    let doc_key = key(&origin, &subject);
    let qos = subject.qos();
    let refresh = Duration::from_secs((ttl_s / 2).max(1));
    loop {
        crate::state::put(&session, &doc_key, &document(&host), qos).await;
        tokio::time::sleep(refresh).await;
    }
}