flexibility 0.4.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. A write without a duration stands until it is released or
//! replaced; [`write_open`] sends one, and [`limit`] reads it until the caller's horizon.
//!
//! A device may acknowledge a fraction of a watt (4 200.5 W). The readers take a [`Rounding`]:
//! [`Rounding::Exact`] refuses it, [`Rounding::TowardZero`] takes the whole watts below the
//! magnitude, which is the stricter cap for LPC and LPP alike.
//!
//! ```
//! use flexibility::eebus::{self, Direction, LimitWrite};
//! use flexibility::{Provenance, Rounding, 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, Rounding::Exact, box_.clone())?
//!     .expect("active");
//! assert_eq!(cap.bounds().max(), Some(kw!(4.2)));
//! assert_eq!(cap.window().until(), "2026-12-01T18:00:00Z".parse()?);
//!
//! // Acknowledged as 4 200.5 W: toward zero, the device is held to 4 200 W.
//! let ack = LimitWrite::active(eebus::ScaledNumber::new(42_005, -1));
//! let cap = eebus::limit(Direction::Consumption, &ack, received, horizon, Rounding::TowardZero, box_)?
//!     .expect("active");
//! assert_eq!(cap.bounds().max(), Some(kw!(4.2)));
//! assert_eq!(cap.window().until(), horizon);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::time::Duration;

use jiff::{SignedDuration, Timestamp};

use crate::power::{DecimalFault, decimal_watts};
use crate::{Error, Limit, Power, Provenance, Rounding, 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 magnitude in whole watts, rounded as named; a negative or absent value is refused.
fn watts(value: ScaledNumber, rounding: Rounding) -> Result<Power, Error> {
    let Some(number) = value.number.map(|n| i128::from(n.get())) else {
        return Err(refuse("limit", &value, "has no number"));
    };
    if number < 0 {
        return Err(refuse(
            "limit",
            &value,
            "is negative; a limit is a magnitude",
        ));
    }
    let scale = value.scale.map_or(0, |s| i32::from(s.get()));
    decimal_watts(number, scale, rounding).map_err(|fault| match fault {
        DecimalFault::Fraction => refuse("limit", &value, "is not a whole number of watts"),
        DecimalFault::Range => refuse("limit", &value, "is outside the range of watts"),
    })
}

fn cap(
    direction: Direction,
    value: ScaledNumber,
    window: Window,
    rounding: Rounding,
    provenance: Provenance,
) -> Result<Limit, Error> {
    let p = watts(value, rounding)?;
    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. The value is rounded as named; [`Rounding::TowardZero`] never loosens it.
///
/// # Errors
/// [`Error::Unrepresentable`] for a negative value, a fraction of a watt under
/// [`Rounding::Exact`], a value beyond the range 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,
    rounding: Rounding,
    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)?,
        rounding,
        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. The value is anything `eebus` reads as one ([`IntoScaled`]):
/// whole watts, a [`ScaledNumber`] as written, or an `f64` kept to three decimals; it is
/// rounded as for [`limit`].
///
/// # Errors
/// [`Error::Unrepresentable`] as for [`limit`].
pub fn failsafe(
    direction: Direction,
    value: impl IntoScaled,
    window: Window,
    rounding: Rounding,
    provenance: Provenance,
) -> Result<Limit, Error> {
    cap(direction, value.into_scaled(), window, rounding, 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 (direction, magnitude) = carried(limit, at)?;
    let until = limit.window().until();
    let left = Duration::try_from(until.duration_since(at))
        .map_err(|_| refuse("duration", &until, "is not after the instant given"))?;
    Ok((direction, LimitWrite::active_for(magnitude, left)))
}

/// As [`write`](fn@write), without a duration: the device holds the limit until it is released
/// (`LimitWrite::deactivated()`) or replaced [LPC/LPP-004]. The window's end is not sent;
/// reading the write back at `at` with a horizon gives the limit until that horizon.
///
/// # Errors
/// As [`write`](fn@write).
pub fn write_open(limit: &Limit, at: Timestamp) -> Result<(Direction, LimitWrite), Error> {
    let (direction, magnitude) = carried(limit, at)?;
    Ok((direction, LimitWrite::active(magnitude)))
}

/// The use case and magnitude that carry `limit` at `at`, or why EEBUS cannot.
fn carried(limit: &Limit, at: Timestamp) -> Result<(Direction, i64), 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();
    match (bounds.min(), bounds.max()) {
        (None, Some(max)) if max >= Power::ZERO => Ok((Direction::Consumption, max.watts())),
        (Some(min), None) if min <= Power::ZERO => min
            .watts()
            .checked_neg()
            .map(|m| (Direction::Production, m))
            .ok_or_else(|| refuse("limit", &min, "is outside the range of a magnitude")),
        _ => 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)",
        )),
    }
}