use std::time::Duration;
use jiff::{SignedDuration, Timestamp};
use crate::{Error, Limit, Power, Provenance, 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) -> 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),
}
}
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)
}
pub fn failsafe(
direction: Direction,
value: impl IntoScaled,
window: Window,
provenance: Provenance,
) -> Result<Limit, Error> {
cap(direction, value.into_scaled(), window, provenance)
}
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)))
}