use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::ops::Deref;
use crate::types::{DateTime, Decimal};
pub mod measurand {
pub const ENERGY_ACTIVE_IMPORT_REGISTER: &str = "Energy.Active.Import.Register";
pub const POWER_ACTIVE_IMPORT: &str = "Power.Active.Import";
pub const POWER_ACTIVE_EXPORT: &str = "Power.Active.Export";
pub const POWER_OFFERED: &str = "Power.Offered";
pub const CURRENT_IMPORT: &str = "Current.Import";
pub const CURRENT_EXPORT: &str = "Current.Export";
pub const CURRENT_OFFERED: &str = "Current.Offered";
pub const VOLTAGE: &str = "Voltage";
pub const FREQUENCY: &str = "Frequency";
pub const SOC: &str = "SoC";
pub const POWER_ACTIVE_SETPOINT: &str = "Power.Active.Setpoint";
pub const POWER_ACTIVE_RESIDUAL: &str = "Power.Active.Residual";
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Phase {
L1,
L2,
L3,
N,
L1N,
L2N,
L3N,
L1L2,
L2L3,
L3L1,
Other(String),
}
impl Phase {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"L1" => Self::L1,
"L2" => Self::L2,
"L3" => Self::L3,
"N" => Self::N,
"L1-N" => Self::L1N,
"L2-N" => Self::L2N,
"L3-N" => Self::L3N,
"L1-L2" => Self::L1L2,
"L2-L3" => Self::L2L3,
"L3-L1" => Self::L3L1,
other => Self::Other(other.into()),
}
}
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::L1 => "L1",
Self::L2 => "L2",
Self::L3 => "L3",
Self::N => "N",
Self::L1N => "L1-N",
Self::L2N => "L2-N",
Self::L3N => "L3-N",
Self::L1L2 => "L1-L2",
Self::L2L3 => "L2-L3",
Self::L3L1 => "L3-L1",
Self::Other(other) => other,
}
}
#[must_use]
pub const fn line(&self) -> Option<u8> {
match self {
Self::L1 | Self::L1N => Some(1),
Self::L2 | Self::L2N => Some(2),
Self::L3 | Self::L3N => Some(3),
_ => None,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Location {
#[default]
Outlet,
Inlet,
Cable,
Ev,
Body,
Upstream,
Other(String),
}
impl Location {
#[must_use]
pub fn parse(value: Option<&str>) -> Self {
match value {
None | Some("Outlet") => Self::Outlet,
Some("Inlet") => Self::Inlet,
Some("Cable") => Self::Cable,
Some("EV") => Self::Ev,
Some("Body") => Self::Body,
Some("Upstream") => Self::Upstream,
Some(other) => Self::Other(other.into()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Unit {
Wh,
W,
Varh,
Var,
VAh,
VA,
A,
V,
Hz,
Percent,
Celsius,
Fahrenheit,
Kelvin,
Unspecified,
Other(String),
}
impl fmt::Display for Unit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Wh => "Wh",
Self::W => "W",
Self::Varh => "varh",
Self::Var => "var",
Self::VAh => "VAh",
Self::VA => "VA",
Self::A => "A",
Self::V => "V",
Self::Hz => "Hz",
Self::Percent => "%",
Self::Celsius => "°C",
Self::Fahrenheit => "°F",
Self::Kelvin => "K",
Self::Unspecified => "",
Self::Other(other) => other,
})
}
}
#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
fn natural_unit(measurand: &str) -> Unit {
let starts = |prefix| measurand.starts_with(prefix);
if starts("Energy.Active") {
Unit::Wh
} else if starts("Energy.Reactive") {
Unit::Varh
} else if starts("Energy.Apparent") {
Unit::VAh
} else if starts("Power.Active") || starts("Power.Offered") {
Unit::W
} else if starts("Power.Reactive") {
Unit::Var
} else if starts("Power.Apparent") {
Unit::VA
} else if starts("Current") {
Unit::A
} else if starts("Voltage") {
Unit::V
} else if starts("Frequency") {
Unit::Hz
} else if starts("SoC") {
Unit::Percent
} else if starts("Temperature") {
Unit::Celsius
} else {
Unit::Unspecified
}
}
#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
fn parse_unit(unit: &str) -> Option<(Unit, i32)> {
let same = |a: &str| unit.eq_ignore_ascii_case(a);
Some(if same("Wh") {
(Unit::Wh, 0)
} else if same("kWh") {
(Unit::Wh, 3)
} else if same("MWh") {
(Unit::Wh, 6)
} else if same("W") {
(Unit::W, 0)
} else if same("kW") {
(Unit::W, 3)
} else if same("MW") {
(Unit::W, 6)
} else if same("varh") {
(Unit::Varh, 0)
} else if same("kvarh") {
(Unit::Varh, 3)
} else if same("var") {
(Unit::Var, 0)
} else if same("kvar") {
(Unit::Var, 3)
} else if same("VAh") {
(Unit::VAh, 0)
} else if same("kVAh") {
(Unit::VAh, 3)
} else if same("VA") {
(Unit::VA, 0)
} else if same("kVA") {
(Unit::VA, 3)
} else if same("A") {
(Unit::A, 0)
} else if same("V") {
(Unit::V, 0)
} else if same("Hz") {
(Unit::Hz, 0)
} else if same("Percent") || same("%") {
(Unit::Percent, 0)
} else if same("Celsius") {
(Unit::Celsius, 0)
} else if same("Fahrenheit") {
(Unit::Fahrenheit, 0)
} else if same("K") {
(Unit::Kelvin, 0)
} else {
return None;
})
}
#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
pub(crate) enum NormalizeProblem {
UnknownUnit,
Unrepresentable,
}
#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
pub(crate) fn normalize(
value: Decimal,
unit: Option<&str>,
multiplier: Option<i32>,
measurand: &str,
) -> Result<(Decimal, Unit, Option<NormalizeProblem>), NormalizeProblem> {
let (unit, exponent, problem) = match unit {
None => (natural_unit(measurand), 0, None),
Some(text) => match parse_unit(text) {
Some((unit, exponent)) => (unit, exponent, None),
None => (
Unit::Other(text.into()),
0,
Some(NormalizeProblem::UnknownUnit),
),
},
};
let value = value
.checked_pow10(multiplier.unwrap_or(0))
.and_then(|scaled| scaled.checked_pow10(exponent))
.ok_or(NormalizeProblem::Unrepresentable)?;
Ok((value, unit, problem))
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Measurement {
pub measurand: String,
pub phase: Option<Phase>,
pub location: Location,
pub context: String,
pub value: Decimal,
pub unit: Unit,
pub timestamp: Option<DateTime>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Total {
Reported(Decimal),
Summed(Decimal),
}
impl Total {
#[must_use]
pub const fn value(self) -> Decimal {
match self {
Self::Reported(value) | Self::Summed(value) => value,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PerPhase {
pub lines: [Option<Decimal>; 3],
pub neutral: Option<Decimal>,
pub total: Option<Total>,
pub unit: Option<Unit>,
}
impl PerPhase {
#[must_use]
pub fn phases_in_use(&self, minimum: Decimal) -> Option<u8> {
if self.lines.iter().all(Option::is_none) {
return None;
}
let in_use = self
.lines
.iter()
.flatten()
.filter(|value| **value >= minimum)
.count();
u8::try_from(in_use).ok()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Measurements(pub(crate) Vec<Measurement>);
impl Deref for Measurements {
type Target = [Measurement];
fn deref(&self) -> &[Measurement] {
&self.0
}
}
impl<'a> IntoIterator for &'a Measurements {
type Item = &'a Measurement;
type IntoIter = core::slice::Iter<'a, Measurement>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl From<Vec<Measurement>> for Measurements {
fn from(measurements: Vec<Measurement>) -> Self {
Self(measurements)
}
}
impl Measurements {
#[must_use]
pub fn per_phase(&self, measurand: &str) -> PerPhase {
self.per_phase_at(measurand, &Location::Outlet)
}
#[must_use]
pub fn per_phase_at(&self, measurand: &str, location: &Location) -> PerPhase {
let mut view = PerPhase::default();
let mut seen: [Option<Option<DateTime>>; 5] = [None; 5];
for measurement in &self.0 {
if measurement.measurand != measurand || measurement.location != *location {
continue;
}
let slot = match &measurement.phase {
None => 4,
Some(Phase::N) => 3,
Some(phase) => match phase.line() {
Some(line) => usize::from(line - 1),
None => continue,
},
};
if seen[slot].is_some_and(|at| at > measurement.timestamp) {
continue;
}
seen[slot] = Some(measurement.timestamp);
view.unit = Some(measurement.unit.clone());
match slot {
0..=2 => view.lines[slot] = Some(measurement.value),
3 => view.neutral = Some(measurement.value),
_ => view.total = Some(Total::Reported(measurement.value)),
}
}
if view.total.is_none() && is_additive(measurand) {
if let [Some(a), Some(b), Some(c)] = view.lines {
view.total = a
.checked_add(b)
.and_then(|ab| ab.checked_add(c))
.map(Total::Summed);
}
}
view
}
#[must_use]
pub fn latest(&self, measurand: &str, phase: Option<&Phase>) -> Option<&Measurement> {
self.0
.iter()
.filter(|m| {
m.measurand == measurand
&& m.phase.as_ref() == phase
&& m.location == Location::Outlet
})
.fold(None, |best: Option<&Measurement>, m| match best {
Some(seen) if seen.timestamp > m.timestamp => Some(seen),
_ => Some(m),
})
}
}
fn is_additive(measurand: &str) -> bool {
measurand.starts_with("Power.Active")
|| measurand.starts_with("Power.Reactive")
|| measurand.starts_with("Energy.")
}
#[cfg(test)]
mod tests {
use super::*;
fn at(value: &str, phase: Option<Phase>) -> Measurement {
Measurement {
measurand: measurand::POWER_ACTIVE_IMPORT.into(),
phase,
location: Location::Outlet,
context: "Sample.Periodic".into(),
value: Decimal::from_literal(value),
unit: Unit::W,
timestamp: None,
}
}
#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
#[test]
fn units_are_normalized_exactly_and_unknown_ones_kept() {
let ok = |v: &str, unit: Option<&str>, mult: Option<i32>, m: &str| {
let (value, unit, problem) = normalize(Decimal::from_literal(v), unit, mult, m)
.ok()
.unwrap();
assert!(problem.is_none());
(value, unit)
};
assert_eq!(
ok("7.4", Some("kW"), None, "Power.Active.Import"),
(Decimal::from(7400), Unit::W)
);
assert_eq!(
ok("74", None, Some(2), "Power.Active.Import"),
(Decimal::from(7400), Unit::W)
);
assert_eq!(
ok("16", None, None, "Current.Import"),
(Decimal::from(16), Unit::A)
);
assert_eq!(
ok("230", None, None, "Voltage"),
(Decimal::from(230), Unit::V)
);
assert_eq!(
ok("1.5", Some("KWH"), None, "Energy.Active.Import.Register"),
(Decimal::from(1500), Unit::Wh)
);
assert_eq!(
ok("0.98", None, None, "Power.Factor"),
(Decimal::from_literal("0.98"), Unit::Unspecified)
);
let (value, unit, problem) = normalize(
Decimal::from(3),
Some("furlongs"),
Some(1),
"Power.Active.Import",
)
.ok()
.unwrap();
assert_eq!(
(value, unit),
(Decimal::from(30), Unit::Other("furlongs".into()))
);
assert!(matches!(problem, Some(NormalizeProblem::UnknownUnit)));
assert!(matches!(
normalize(
Decimal::from(1),
Some("kW"),
Some(30),
"Power.Active.Import"
),
Err(NormalizeProblem::Unrepresentable)
));
}
#[test]
fn line_to_neutral_is_the_line_and_line_to_line_is_no_line() {
assert_eq!(Phase::parse("L2-N").line(), Some(2));
assert_eq!(Phase::parse("L2").line(), Some(2));
assert_eq!(Phase::parse("L1-L2").line(), None);
assert_eq!(Phase::parse("N").line(), None);
assert_eq!(Phase::parse("L4"), Phase::Other("L4".into()));
}
#[test]
fn power_sums_currents_and_voltages_do_not() {
let power = Measurements(vec![
at("3000", Some(Phase::L1N)),
at("3000", Some(Phase::L2N)),
at("1000", Some(Phase::L3N)),
]);
assert_eq!(
power.per_phase(measurand::POWER_ACTIVE_IMPORT).total,
Some(Total::Summed(Decimal::from(7000)))
);
let partial = Measurements(vec![
at("3000", Some(Phase::L1)),
at("3000", Some(Phase::L2)),
]);
assert_eq!(
partial.per_phase(measurand::POWER_ACTIVE_IMPORT).total,
None,
"a partial sum understates"
);
let mut current = Measurements(vec![
at("16", Some(Phase::L1)),
at("16", Some(Phase::L2)),
at("16", Some(Phase::L3)),
]);
for m in &mut current.0 {
m.measurand = measurand::CURRENT_IMPORT.into();
}
assert_eq!(current.per_phase(measurand::CURRENT_IMPORT).total, None);
assert_eq!(
current
.per_phase(measurand::CURRENT_IMPORT)
.phases_in_use(Decimal::from(1)),
Some(3)
);
}
#[test]
fn a_reported_total_wins_and_the_latest_sample_wins() {
let early: DateTime = "2026-11-20T12:00:00Z".parse().unwrap();
let late: DateTime = "2026-11-20T12:00:10Z".parse().unwrap();
let mut a = at("100", None);
a.timestamp = Some(late);
let mut b = at("50", None);
b.timestamp = Some(early);
let view = Measurements(vec![
a,
b,
at("1", Some(Phase::L1)),
at("1", Some(Phase::L2)),
at("1", Some(Phase::L3)),
])
.per_phase(measurand::POWER_ACTIVE_IMPORT);
assert_eq!(view.total, Some(Total::Reported(Decimal::from(100))));
}
#[test]
fn the_outlet_is_the_default_location() {
let mut inlet = at("9000", None);
inlet.location = Location::Inlet;
let view = Measurements(vec![inlet, at("7000", None)]);
assert_eq!(
view.per_phase(measurand::POWER_ACTIVE_IMPORT)
.total
.map(Total::value),
Some(Decimal::from(7000))
);
assert_eq!(
view.per_phase_at(measurand::POWER_ACTIVE_IMPORT, &Location::Inlet)
.total
.map(Total::value),
Some(Decimal::from(9000))
);
}
}