use std::time::Duration;
use jiff::{SignedDuration, Timestamp};
use crate::power::{DecimalFault, decimal_watts};
use crate::{Error, Limit, Power, Provenance, Rounding, Window};
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,
}
}
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),
}
}
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)
}
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)
}
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)))
}
pub fn write_open(limit: &Limit, at: Timestamp) -> Result<(Direction, LimitWrite), Error> {
let (direction, magnitude) = carried(limit, at)?;
Ok((direction, LimitWrite::active(magnitude)))
}
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)",
)),
}
}