use jiff::{SignedDuration, Timestamp};
use crate::{Error, Limit, Power, Provenance, Window};
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())
}
}
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)
}
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()
}
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))
}