flexibility 0.3.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, CSIP-AUS, IEC 104, CLS.EEDI converters.
Documentation
//! EEBUS LPC and LPP limits as [`Limit`]s and back, behind the `eebus` feature.
//!
//! Both use cases take a non-negative magnitude in watts; LPP's is negated on the wire
//! [LPC-001, LPP-001] (the `eebus` crate's sign table). So an LPC limit is a consumption
//! maximum and an LPP limit a feed-in minimum, in this crate's one sign: consumption positive.
//! An EEBUS duration starts when the write arrives [LPC/LPP-004]; this crate has no clock, so
//! the caller passes the instant.
//!
//! ```
//! use flexibility::eebus::{self, Direction, LimitWrite};
//! use flexibility::{Provenance, kw};
//! use std::time::Duration;
//! # use flexibility::jiff::Timestamp;
//! let received: Timestamp = "2026-12-01T16:00:00Z".parse()?;
//! let horizon: Timestamp = "2026-12-02T00:00:00Z".parse()?;
//! let box_ = Provenance::new("dso.example", "lpc", received);
//!
//! let write = LimitWrite::active_for(4_200, Duration::from_secs(7_200));
//! let cap = eebus::limit(Direction::Consumption, &write, received, horizon, box_)?.expect("active");
//! assert_eq!(cap.bounds().max(), Some(kw!(4.2)));
//! assert_eq!(cap.window().until(), "2026-12-01T18:00:00Z".parse()?);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::time::Duration;

use jiff::{SignedDuration, Timestamp};

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

/// The `eebus` crate this feature maps to.
pub use ::eebus as wire;
pub use ::eebus::model::{IntoScaled, ScaledNumber};
pub use ::eebus::usecases::limitation::{Direction, LimitWrite};

const PROTOCOL: &str = "EEBUS";

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

/// The value as whole, non-negative watts, or refused: rounding a cap either way changes what
/// the operator set.
fn watts(value: ScaledNumber) -> Result<Power, Error> {
    match value.to_i64() {
        Some(w) if w >= 0 => Ok(Power::from_watts(w)),
        Some(_) => Err(refuse(
            "limit",
            &value,
            "is negative; a limit is a magnitude",
        )),
        None => Err(refuse("limit", &value, "is not a whole number of watts")),
    }
}

fn cap(
    direction: Direction,
    value: ScaledNumber,
    window: Window,
    provenance: Provenance,
) -> Result<Limit, Error> {
    let p = watts(value)?;
    match direction {
        Direction::Consumption => Ok(Limit::consumption_cap(window, p, provenance)),
        Direction::Production => Limit::feed_in_cap(window, p, provenance),
    }
}

/// The limit an LPC (`Consumption`) or LPP (`Production`) write sets, received at `received`:
/// from then until its duration runs out, or until `horizon` if it has none. `None` for a
/// deactivated write.
///
/// # Errors
/// [`Error::Unrepresentable`] for a value that is not a whole, non-negative number of watts or
/// a duration that ends outside the time range; [`Error::EmptyWindow`] for a zero duration or a
/// horizon not after `received`.
pub fn limit(
    direction: Direction,
    write: &LimitWrite,
    received: Timestamp,
    horizon: Timestamp,
    provenance: Provenance,
) -> Result<Option<Limit>, Error> {
    if !write.is_active {
        return Ok(None);
    }
    let until = match write.duration {
        Some(d) => SignedDuration::try_from(d)
            .ok()
            .and_then(|d| received.checked_add(d).ok())
            .ok_or_else(|| {
                refuse(
                    "duration",
                    &format!("{d:?}"),
                    "ends outside the representable time range",
                )
            })?,
        None => horizon,
    };
    cap(
        direction,
        write.value,
        Window::new(received, until)?,
        provenance,
    )
    .map(Some)
}

/// The failsafe limit (LPC's or LPP's failsafe active power limit) as a limit over `window`:
/// the time the caller expects the device to fall back to it, such as the failsafe duration
/// after the heartbeat stops.
///
/// # Errors
/// [`Error::Unrepresentable`] for a value that is not a whole, non-negative number of watts.
/// The value is anything `eebus` reads as one ([`IntoScaled`]): whole watts, a
/// [`ScaledNumber`] as written, or an `f64` kept to three decimals.
pub fn failsafe(
    direction: Direction,
    value: impl IntoScaled,
    window: Window,
    provenance: Provenance,
) -> Result<Limit, Error> {
    cap(direction, value.into_scaled(), window, provenance)
}

/// The LPC or LPP write that carries `limit` at instant `at`: active, its magnitude in watts,
/// and the duration left until the limit's window ends. Reading the write back at `at` gives
/// the limit from `at` on.
///
/// # Errors
/// [`Error::Unrepresentable`] for what EEBUS cannot carry: both bounds, a consumption maximum
/// below zero or a feed-in minimum above zero, or a window not in force at `at` (a duration
/// starts when the write arrives).
pub fn write(limit: &Limit, at: Timestamp) -> Result<(Direction, LimitWrite), Error> {
    let window = limit.window();
    if at < window.from() || at >= window.until() {
        return Err(refuse(
            "duration",
            &format!("{} to {}", window.from(), window.until()),
            "is not in force at the instant given; an EEBUS duration starts when it is written",
        ));
    }
    let bounds = limit.bounds();
    let (direction, magnitude) = match (bounds.min(), bounds.max()) {
        (None, Some(max)) if max >= Power::ZERO => (Direction::Consumption, max.watts()),
        (Some(min), None) if min <= Power::ZERO => (
            Direction::Production,
            min.watts()
                .checked_neg()
                .ok_or_else(|| refuse("limit", &min, "is outside the range of a magnitude"))?,
        ),
        _ => {
            return Err(refuse(
                "limit",
                &bounds,
                "EEBUS carries one cap: a consumption maximum of at least 0 W (LPC) or a \
                 feed-in minimum of at most 0 W (LPP)",
            ));
        }
    };
    let left = Duration::try_from(window.until().duration_since(at)).map_err(|_| {
        refuse(
            "duration",
            &window.until(),
            "is not after the instant given",
        )
    })?;
    Ok((direction, LimitWrite::active_for(magnitude, left)))
}