use crate::power::div_round;
use crate::{Error, Grid, Guarantee, Power, Provenance, Rounding, Series, Window};
pub use ::metering as wire;
use wire::Direction;
use wire::grid::para14a::Mindestleistung;
const PROTOCOL: &str = "metering";
fn refuse(field: &'static str, value: &impl ToString, reason: &'static str) -> Error {
Error::Unrepresentable {
protocol: PROTOCOL,
field,
value: value.to_string(),
reason,
}
}
pub fn guarantee(
minimum: Mindestleistung,
window: Window,
provenance: Provenance,
) -> Result<Guarantee, Error> {
let watts = minimum.watts().ok_or_else(|| {
refuse(
"Mindestleistung",
&minimum,
"exceeds the range of whole watts",
)
})?;
Guarantee::consumption(window, Power::consumption(watts)?, provenance)
}
fn overflow(left: i128) -> Error {
Error::Overflow {
quantity: "energy",
operation: "net",
left,
right: None,
}
}
pub fn power(
channels: &[&wire::Series],
grid: &Grid,
rounding: Rounding,
) -> Result<Series<Power>, Error> {
if grid.isp().minutes() != 15 {
return Err(Error::Mismatch {
field: "ISP-Duration",
ours: format!("{} min", grid.isp().minutes()),
theirs: "15 min (Lastgang quarters)".into(),
});
}
if channels.is_empty() {
return Err(Error::NoData {
what: "no metering channel",
});
}
let n = grid.count() as usize;
let mut sums: Vec<(i128, u32)> = vec![(0, 0); n];
for series in channels {
let channel = series.channel();
let sign = match series.lastgang_direction() {
Some(Direction::Import) => 1,
Some(Direction::Export) => -1,
_ => {
return Err(refuse(
"channel",
&channel.map_or_else(|| "none".to_owned(), |c| c.to_string()),
"is not an active-energy Lastgang in kWh (1-0:1.29.0 import, 1-0:2.29.0 export)",
));
}
};
let quarters = series
.billable_quarters((grid.start(), grid.end()))
.map_err(|e| refuse("interval", &e, "cannot be settled"))?;
for (sum, iv) in sums.iter_mut().zip(quarters) {
let v = iv.value();
let (num, scale) = (sign * v.mantissa(), v.scale());
let top = sum.1.max(scale);
let lift = |x: i128, from: u32| {
10_i128
.checked_pow(top - from)
.and_then(|f| x.checked_mul(f))
.ok_or_else(|| overflow(x))
};
let total = lift(sum.0, sum.1)?
.checked_add(lift(num, scale)?)
.ok_or_else(|| overflow(sum.0))?;
*sum = (total, top);
}
}
let values = sums
.into_iter()
.map(|(num, scale)| {
let n = num.checked_mul(4_000).ok_or_else(|| overflow(num))?;
let d = 10_i128.checked_pow(scale).ok_or_else(|| overflow(num))?;
let w = div_round(n, d, rounding)?;
i64::try_from(w)
.map(Power::from_watts)
.map_err(|_| overflow(w))
})
.collect::<Result<Vec<_>, Error>>()?;
Series::new(grid.clone(), values)
}