use crate::power::div_round;
use crate::{Error, Limit, Power, Provenance, Rounding, Window};
pub use ::iec60870 as wire;
use wire::types::{
Normalized, SetpointFloat, SetpointNormalized, SetpointQualifier, SetpointScaled,
};
const PROTOCOL: &str = "IEC 104";
const FULL: i128 = 32_768;
fn refuse(field: &'static str, value: &impl ToString, reason: &'static str) -> Error {
Error::Unrepresentable {
protocol: PROTOCOL,
field,
value: value.to_string(),
reason,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
Consumption,
FeedIn,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Scale {
Normalized {
full_scale: Power,
},
Scaled {
step: Power,
},
Float {
unit: Power,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
pub direction: Direction,
pub scale: Scale,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Setpoint {
Normalized(SetpointNormalized),
Scaled(SetpointScaled),
Float(SetpointFloat),
}
impl From<SetpointNormalized> for Setpoint {
fn from(s: SetpointNormalized) -> Setpoint {
Setpoint::Normalized(s)
}
}
impl From<SetpointScaled> for Setpoint {
fn from(s: SetpointScaled) -> Setpoint {
Setpoint::Scaled(s)
}
}
impl From<SetpointFloat> for Setpoint {
fn from(s: SetpointFloat) -> Setpoint {
Setpoint::Float(s)
}
}
impl Setpoint {
fn qualifier(self) -> SetpointQualifier {
match self {
Setpoint::Normalized(s) => s.qualifier,
Setpoint::Scaled(s) => s.qualifier,
Setpoint::Float(s) => s.qualifier,
}
}
}
fn positive(field: &'static str, p: Power) -> Result<i128, Error> {
if p <= Power::ZERO {
return Err(refuse(field, &p, "must be positive in the point list"));
}
Ok(i128::from(p.watts()))
}
fn decimal_places(unit: Power) -> Result<u32, Error> {
let w = positive("unit", unit)?;
(0..=18)
.find(|&k| 10_i128.pow(k) == w)
.ok_or_else(|| refuse("unit", &unit, "is not a power of ten watts (W, kW, MW)"))
}
#[allow(clippy::disallowed_types)]
fn float_decimal(value: f32) -> Result<(i128, u32), Error> {
if !value.is_finite() {
return Err(refuse("value", &value, "is not a finite number"));
}
let text = format!("{value}");
let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
if whole.trim_start_matches('-').len() > 16 {
return Err(refuse(
"value",
&format!("{value:e}"),
"is outside the range of watts",
));
}
let mantissa: i128 = format!("{whole}{fraction}")
.parse()
.map_err(|_| refuse("value", &format!("{value:e}"), "is not a decimal number"))?;
let scale = u32::try_from(fraction.len()).unwrap_or(u32::MAX);
Ok((mantissa, scale))
}
#[allow(clippy::disallowed_types)]
fn float_of(text: &str) -> Option<(f32, (i128, u32))> {
let f: f32 = text.parse().ok()?;
float_decimal(f).ok().map(|d| (f, d))
}
fn negative(raw: i128, shown: &dyn Fn() -> String) -> Result<(), Error> {
if raw < 0 {
return Err(refuse(
"value",
&shown(),
"is negative; an active-power cap is a magnitude",
));
}
Ok(())
}
fn to_watts(
n: i128,
d: i128,
rounding: Rounding,
shown: &dyn Fn() -> String,
) -> Result<Power, Error> {
let w = match rounding {
Rounding::Exact if n % d != 0 => {
return Err(refuse("value", &shown(), "is not a whole number of watts"));
}
_ => div_round(n, d, rounding)?,
};
i64::try_from(w)
.map(Power::from_watts)
.map_err(|_| refuse("value", &shown(), "is outside the range of watts"))
}
pub fn limit(
setpoint: impl Into<Setpoint>,
point: Point,
window: Window,
rounding: Rounding,
provenance: Provenance,
) -> Result<Limit, Error> {
let setpoint = setpoint.into();
if setpoint.qualifier().is_select() {
return Err(refuse(
"qualifier",
&"select",
"is the select of select-before-operate; only the execute sets a value",
));
}
let power = match (setpoint, point.scale) {
(Setpoint::Normalized(s), Scale::Normalized { full_scale }) => {
let raw = i128::from(s.value.0);
negative(raw, &|| s.value.to_string())?;
to_watts(
raw * positive("full_scale", full_scale)?,
FULL,
rounding,
&|| format!("{} of {full_scale}", s.value),
)?
}
(Setpoint::Scaled(s), Scale::Scaled { step }) => {
let raw = i128::from(s.value);
negative(raw, &|| s.value.to_string())?;
to_watts(raw * positive("step", step)?, 1, rounding, &|| {
format!("{} × {step}", s.value)
})?
}
(Setpoint::Float(s), Scale::Float { unit }) => {
let k = decimal_places(unit)?;
let (mantissa, scale) = float_decimal(s.value)?;
let shown = || format!("{mantissa}e-{scale} × {unit}");
negative(mantissa, &shown)?;
if scale <= k {
let factor = 10_i128
.checked_pow(k - scale)
.ok_or_else(|| refuse("value", &shown(), "is outside the range of watts"))?;
to_watts(
mantissa.checked_mul(factor).ok_or_else(|| {
refuse("value", &shown(), "is outside the range of watts")
})?,
1,
rounding,
&shown,
)?
} else {
match 10_i128.checked_pow(scale - k) {
Some(divisor) => to_watts(mantissa, divisor, rounding, &shown)?,
None if rounding == Rounding::Exact && mantissa != 0 => {
return Err(refuse("value", &shown(), "is not a whole number of watts"));
}
None => Power::ZERO,
}
}
}
(s, scale) => {
return Err(refuse(
"type",
&format!("{s:?}"),
match scale {
Scale::Normalized { .. } => {
"arrived where the point list expects type 48 (normalized)"
}
Scale::Scaled { .. } => "arrived where the point list expects type 49 (scaled)",
Scale::Float { .. } => {
"arrived where the point list expects type 50 (short float)"
}
},
));
}
};
if power < Power::ZERO {
return Err(refuse(
"value",
&power,
"is negative; an active-power cap is a magnitude",
));
}
match point.direction {
Direction::Consumption => Ok(Limit::consumption_cap(window, power, provenance)),
Direction::FeedIn => Limit::feed_in_cap(window, power, provenance),
}
}
pub fn setpoint(cap: Power, point: Point, rounding: Rounding) -> Result<Setpoint, Error> {
if cap < Power::ZERO {
return Err(refuse(
"value",
&cap,
"is negative; an active-power cap is a magnitude",
));
}
let w = i128::from(cap.watts());
let fit = |raw: i128| {
i16::try_from(raw).map_err(|_| refuse("value", &cap, "is beyond the set point's range"))
};
match point.scale {
Scale::Normalized { full_scale } => {
let full = positive("full_scale", full_scale)?;
let mut raw = div_round(w * FULL, full, rounding)?;
if raw == FULL && rounding == Rounding::TowardZero {
raw = FULL - 1;
}
Ok(Setpoint::Normalized(SetpointNormalized::new(Normalized(
fit(raw)?,
))))
}
Scale::Scaled { step } => {
let raw = div_round(w, positive("step", step)?, rounding)?;
Ok(Setpoint::Scaled(SetpointScaled::new(fit(raw)?)))
}
Scale::Float { unit } => {
let k = decimal_places(unit)?;
let places = k as usize;
let digits = format!("{:0>width$}", w, width = places + 1);
let (whole, fraction) = digits.split_at(digits.len() - places);
let text = if k == 0 {
whole.to_owned()
} else {
format!("{whole}.{fraction}")
};
let (value, (mantissa, scale)) =
float_of(&text).ok_or_else(|| refuse("value", &cap, "is not a short float"))?;
let back = (scale <= k).then(|| mantissa * 10_i128.pow(k - scale));
if back != Some(w) {
return Err(refuse(
"value",
&cap,
"needs more digits than a short float holds",
));
}
Ok(Setpoint::Float(SetpointFloat::new(value)))
}
}
}