openadr 0.11.0

OpenADR 3.1 in Rust: VTN server, VEN runtime, typed client and an open conformance suite
Documentation
//! The domain core: deterministic, I/O-free, and shared by the VTN, the VEN and the tests.
//!
//! Four things live here, and they are the parts of OpenADR that carry real semantics rather than
//! transport: [`IntervalExpander`] resolves an event's declared timing into absolute windows,
//! [`Timeline`] merges concurrent events by priority, [`Access`] decides object privacy, and
//! [`ReportSchedule`] says when a VEN owes a report.
//!
//! Everything takes its time from an injected [`Clock`], so a scenario that fails in production can
//! be replayed exactly in a test and nothing here needs to sleep. That, and having no I/O, is what
//! makes the layer `no_std`-capable.
//!
//! # Converting events and reports
//!
//! Capacity limits with their unit, and usage as an absolute series, exact throughout. The
//! specification names no default unit; a payload's unit is in the event's descriptor, else in its
//! programme's `[UG ยง7.6]`:
//!
//! ```
//! use openadr::core::IntervalExpander;
//! use openadr::model::{Event, Program, Report, Unit};
//!
//! # let program: Program = serde_json::from_str(r#"{"id": "p1", "programName": "caps",
//! #   "createdDateTime": "2026-03-01T00:00:00Z", "modificationDateTime": "2026-03-01T00:00:00Z",
//! #   "payloadDescriptors": [{"objectType": "EVENT_PAYLOAD_DESCRIPTOR",
//! #                           "payloadType": "IMPORT_CAPACITY_LIMIT", "units": "KW"}]}"#)?;
//! # let event: Event = serde_json::from_str(r#"{"id": "e1", "programID": "p1",
//! #   "createdDateTime": "2026-03-13T12:00:00Z", "modificationDateTime": "2026-03-13T12:00:00Z",
//! #   "intervalPeriod": {"start": "2026-03-14T00:00:00Z", "duration": "PT1H"},
//! #   "intervals": [{"id": 0, "payloads": [{"type": "IMPORT_CAPACITY_LIMIT", "values": [7.56]}]},
//! #                 {"id": 1, "payloads": [{"type": "IMPORT_CAPACITY_LIMIT", "values": [5]}]}]}"#)?;
//! # let report: Report = serde_json::from_str(r#"{"id": "r1", "eventID": "e1", "clientName": "ven-1",
//! #   "createdDateTime": "2026-03-14T02:00:00Z", "modificationDateTime": "2026-03-14T02:00:00Z",
//! #   "resources": [{"resourceName": "meter-1", "intervals": [
//! #     {"id": 1, "payloads": [{"type": "USAGE", "values": [4.2]}]}]}]}"#)?;
//! let expander = IntervalExpander::at("2026-03-14T03:00:00Z".parse()?);
//!
//! // Limits: one window per interval. This event has no descriptor; its programme's applies.
//! let unit = event.payload_descriptor_in(&program, "IMPORT_CAPACITY_LIMIT").and_then(|d| d.units.as_ref());
//! assert_eq!(unit, Some(&Unit::Kw));
//! for window in expander.expand(&event.content)? {
//!     if let Some(limit) = window.payload("IMPORT_CAPACITY_LIMIT").and_then(|p| p.values[0].as_decimal()) {
//!         println!("{}..{:?}: {limit} kW", window.start, window.end);
//!     }
//! }
//!
//! // Usage is energy (kWh); `DEMAND` is power. These intervals carry only the event's ids, so pass
//! // the event to place them.
//! for resource in &report.content.resources {
//!     for window in expander.expand_report(resource, Some(&event.content))? {
//!         let kwh = window.payload("USAGE").and_then(|p| p.values[0].as_decimal());
//!         assert_eq!(window.start.to_string(), "2026-03-14T01:00:00Z");
//!         assert_eq!(kwh, Some("4.2".parse()?));
//!     }
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! Guide: <https://hupe1980.github.io/openadr/docs/domain-core/>.

use crate::model::Timestamp;

pub mod interval;
pub mod privacy;
pub mod report;
pub mod timeline;

pub use interval::{
    ExpandError, ExpandedInterval, IntervalExpander, IntervalSequence, active_window,
};
pub use privacy::{Access, Grant, GrantIndex, OwnerFilter, Role, TargetFilter};
pub use report::{AggregateError, ReportDue, ReportSchedule, ScheduleOptions, aggregate};
pub use timeline::{Segment, Timeline};

/// A source of the current time.
///
/// Everything time-dependent in this crate goes through this trait. Tests use [`FixedClock`]; the
/// VTN uses [`SystemClock`].
pub trait Clock: core::fmt::Debug + Send + Sync {
    /// The current instant.
    fn now(&self) -> Timestamp;
}

/// Reads the host clock.
#[cfg(feature = "std")]
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;

#[cfg(feature = "std")]
impl Clock for SystemClock {
    fn now(&self) -> Timestamp {
        Timestamp::now()
    }
}

/// A clock frozen at one instant.
#[derive(Debug, Clone, Copy)]
pub struct FixedClock(pub Timestamp);

impl FixedClock {
    /// Freeze at an instant.
    pub fn new(at: Timestamp) -> Self {
        Self(at)
    }
}

impl Clock for FixedClock {
    fn now(&self) -> Timestamp {
        self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_fixed_clock_does_not_move() {
        let at: Timestamp = "2026-01-01T12:00:00Z".parse().unwrap();
        let clock = FixedClock::new(at);
        assert_eq!(clock.now(), at);
        assert_eq!(clock.now(), at);
    }
}