flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! CLS.EEDI (KEO, FNN control box) power limits as limits and back, behind the `cls` feature.
//!
//! A grid backend sends a CLS.EEDI `control` to the local device behind a smart meter gateway:
//! a consumption or production limit in whole watts, active or not, lasting `duration` seconds
//! from receipt or until the next control, and failsafe values the device falls back to. This
//! is the § 14a EnWG path in Germany: apply the limits to an [`Envelope`](crate::Envelope) that
//! carries the § 14a [`Guarantee`](crate::Guarantee), and a cap below the minimum is refused.
//!
//! - A **consumption** limit of p W is a consumption cap of p; a **production** limit of p W is
//!   a feed-in cap of p. Both are magnitudes on the wire.
//! - The duration starts when the control arrives; this crate has no clock, so the caller passes
//!   the instant, and the horizon a limit without a duration lasts until.
//! - An inactive limit sets nothing. An active limit of 0 W or a zero duration is what CLS.EEDI
//!   itself refuses, and is refused here too.
//!
//! ```
//! use flexibility::cls::{self, wire};
//! use flexibility::{Provenance, kw};
//! # use flexibility::jiff::Timestamp;
//! let received: Timestamp = "2026-12-01T16:00:00Z".parse()?;
//! let horizon: Timestamp = "2026-12-02T00:00:00Z".parse()?;
//! let control: wire::wire::Control = serde_json::from_str(
//!     r#"{"limits": {"power": {"active": {"consumption": {"value": 4200, "active": true, "duration": 7200}}}}}"#,
//! )?;
//! let dso = Provenance::new("dso.example", "cls-17", received);
//! let caps = cls::limits(&control, received, horizon, &dso)?;
//! assert_eq!(caps[0].bounds().max(), Some(kw!(4.2)));
//! assert_eq!(caps[0].window().until(), "2026-12-01T18:00:00Z".parse()?);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use jiff::{SignedDuration, Timestamp};

use crate::{Error, Limit, Power, Provenance, Window};

/// The `cls-eedi` crate this feature maps to.
pub use ::cls_eedi as wire;

use wire::wire::{Control, Limit as WireLimit, Power as Directions};

const PROTOCOL: &str = "CLS.EEDI";

fn refuse(field: &'static str, value: &impl ToString, reason: &'static str) -> Error {
    Error::Unrepresentable {
        protocol: PROTOCOL,
        field,
        value: value.to_string(),
        reason,
    }
}

fn magnitude(field: &'static str, watts: i64) -> Result<Power, Error> {
    if watts < 0 {
        return Err(refuse(
            field,
            &watts,
            "is negative; a CLS.EEDI limit is a magnitude",
        ));
    }
    Ok(Power::from_watts(watts))
}

fn cap(
    field: &'static str,
    window: Window,
    p: Power,
    provenance: &Provenance,
) -> Result<Limit, Error> {
    if field.starts_with("consumption") {
        Ok(Limit::consumption_cap(window, p, provenance.clone()))
    } else {
        Limit::feed_in_cap(window, p, provenance.clone())
    }
}

/// The limits a control sets, received at `received`: each active one from then until its
/// duration runs out, or until `horizon` without one. Inactive limits set nothing.
///
/// # Errors
/// [`Error::Unrepresentable`] for a negative value, an active limit of 0 W or a zero duration;
/// [`Error::EmptyWindow`] for a horizon not after `received`.
pub fn limits(
    control: &Control,
    received: Timestamp,
    horizon: Timestamp,
    provenance: &Provenance,
) -> Result<Vec<Limit>, Error> {
    let Some(limits) = &control.limits else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for (field, limit) in [
        ("consumption limit", limits.consumption.as_ref()),
        ("production limit", limits.production.as_ref()),
    ] {
        let Some(limit) = limit else { continue };
        if !limit.active {
            continue;
        }
        let p = magnitude(field, limit.value)?;
        if p == Power::ZERO {
            return Err(refuse(
                field,
                &p,
                "is active at 0 W, which CLS.EEDI refuses; deactivate it instead",
            ));
        }
        let until = match limit.duration {
            Some(0) => return Err(refuse("duration", &0, "is zero, which CLS.EEDI refuses")),
            Some(s) => received
                .checked_add(SignedDuration::from_secs(i64::from(s)))
                .map_err(|_| refuse("duration", &s, "ends outside the representable time range"))?,
            None => horizon,
        };
        out.push(cap(field, Window::new(received, until)?, p, provenance)?);
    }
    Ok(out)
}

/// The failsafe caps a control sets, over `window`: the time the caller expects the device to
/// fall back to them (after the gateway connection is lost).
///
/// # Errors
/// [`Error::Unrepresentable`] for a negative value.
pub fn failsafe(
    control: &Control,
    window: Window,
    provenance: &Provenance,
) -> Result<Vec<Limit>, Error> {
    let Some(f) = &control.failsafes else {
        return Ok(Vec::new());
    };
    [
        ("consumption failsafe", f.consumption),
        ("production failsafe", f.production),
    ]
    .into_iter()
    .filter_map(|(field, w)| w.map(|w| (field, w)))
    .map(|(field, w)| cap(field, window, magnitude(field, w)?, provenance))
    .collect()
}

/// The control that carries `limit` at instant `at`: an active consumption or production limit
/// in whole watts, with the seconds left until the limit's window ends. Reading it back at `at`
/// gives the limit from `at` on.
///
/// # Errors
/// [`Error::Unrepresentable`] for a band (both bounds), a consumption cap below zero or a
/// feed-in cap above zero, a cap of 0 W (CLS.EEDI has no active 0 W limit), a window not in
/// force at `at`, or one whose time left at `at` is not whole seconds.
pub fn control(limit: &Limit, at: Timestamp) -> Result<Control, Error> {
    let w = limit.window();
    if !(w.from() <= at && at < w.until()) {
        return Err(refuse(
            "duration",
            &w,
            "is not in force at the instant given",
        ));
    }
    let left = at.duration_until(w.until());
    if left.subsec_nanos() != 0 {
        return Err(refuse(
            "duration",
            &w,
            "is not a whole number of seconds from the instant given; CLS.EEDI counts whole seconds",
        ));
    }
    let seconds = u32::try_from(left.as_secs())
        .map_err(|_| refuse("duration", &w, "is longer than CLS.EEDI's duration holds"))?;
    let b = limit.bounds();
    let limits = match (b.min(), b.max()) {
        (None, Some(max)) if max > Power::ZERO => {
            Directions::consumption(WireLimit::active(max.watts()).lasting(seconds))
        }
        (Some(min), None) if min < Power::ZERO => {
            Directions::production(WireLimit::active(min.checked_neg()?.watts()).lasting(seconds))
        }
        _ => {
            return Err(refuse(
                "limits",
                &b,
                "is not one consumption or feed-in cap above 0 W, which is all CLS.EEDI carries",
            ));
        }
    };
    Ok(Control::limits(limits))
}