use alloc::string::String;
use alloc::vec::Vec;
use rust_decimal::Decimal;
use crate::payload::{MeterState, TransactionMarker};
use crate::record::Record;
use crate::time::TimeStatus;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "finding"))]
#[non_exhaustive]
pub enum Finding {
Empty,
PaginationBroken {
from: u64,
to: u64,
index: usize,
},
PaginationUnreadable {
index: usize,
},
PaginationContextChanged {
index: usize,
},
NoBegin,
NoEnd,
MultipleBegins,
MultipleEnds,
MarkerOutOfPlace {
index: usize,
},
SourceChanged {
index: usize,
expected: String,
found: String,
},
MeterNotOk {
index: usize,
state: MeterState,
},
ErrorFlagged {
index: usize,
flags: String,
},
TransactionFaulted {
index: usize,
marker: TransactionMarker,
},
IdentificationError {
index: usize,
level: String,
},
MeterWentBackwards {
obis: String,
},
RegisterEndWithoutBegin {
obis: String,
},
TimeWentBackwards,
ClockNotSynchronised {
status: Option<TimeStatus>,
},
DuplicateRecord {
index: usize,
},
}
impl core::fmt::Display for Finding {
#[allow(clippy::too_many_lines)]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Empty => f.write_str("no records"),
Self::PaginationBroken { from, to, index } => write!(
f,
"pagination went {from} → {to} at record {index}: a record was removed, duplicated or reordered"
),
Self::PaginationUnreadable { index } => {
write!(f, "record {index} has no readable `PG` counter")
}
Self::PaginationContextChanged { index } => {
write!(
f,
"record {index} belongs to a different pagination context"
)
}
Self::NoBegin => f.write_str("no reading marks the begin of the transaction"),
Self::NoEnd => f.write_str("no reading marks the end of the transaction"),
Self::MultipleBegins => f.write_str("more than one reading marks the begin"),
Self::MultipleEnds => f.write_str("more than one reading marks the end"),
Self::MarkerOutOfPlace { index } => write!(
f,
"record {index} carries a begin or end marker out of its place in the sequence"
),
Self::SourceChanged {
index,
expected,
found,
} => write!(
f,
"record {index} comes from {found}, the sequence started with {expected}"
),
Self::MeterNotOk { index, state } => write!(
f,
"record {index} reports meter state {state} ({})",
state.identifier()
),
Self::ErrorFlagged { index, flags } => {
write!(f, "record {index} flags {flags} as unusable for billing")
}
Self::TransactionFaulted { index, marker } => {
write!(f, "record {index} marks the transaction {marker}")
}
Self::IdentificationError { index, level } => {
write!(f, "record {index} reports user assignment error {level}")
}
Self::MeterWentBackwards { obis } => {
write!(f, "register {obis} ends below where it began")
}
Self::RegisterEndWithoutBegin { obis } => {
write!(f, "register {obis} has an end reading and no begin")
}
Self::TimeWentBackwards => f.write_str("the end is stamped before the begin"),
Self::ClockNotSynchronised { status } => match status {
Some(s) => write!(
f,
"the weakest clock in the sequence is `{}`, which cannot support a duration",
s.letter()
),
None => f.write_str("no reading carries a clock status"),
},
Self::DuplicateRecord { index } => {
write!(
f,
"record {index} repeats a payload already in the sequence"
)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum SequenceKind {
#[default]
Transaction,
Fiscal,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct RegisterTotal {
pub obis: String,
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal_as_text"))]
pub begin: Decimal,
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal_as_text"))]
pub end: Decimal,
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal_as_text"))]
pub delta: Decimal,
pub unit: String,
}
#[cfg(feature = "serde")]
fn decimal_as_text<S: serde::Serializer>(d: &Decimal, s: S) -> Result<S::Ok, S::Error> {
use alloc::string::ToString as _;
s.serialize_str(&d.to_string())
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SessionReport {
kind: SequenceKind,
findings: Vec<Finding>,
totals: Vec<RegisterTotal>,
worst_clock: Option<TimeStatus>,
best_clock: Option<TimeStatus>,
}
impl SessionReport {
#[must_use]
pub fn findings(&self) -> &[Finding] {
&self.findings
}
#[must_use]
pub const fn kind(&self) -> SequenceKind {
self.kind
}
#[must_use]
pub fn is_clean(&self) -> bool {
self.findings.is_empty()
}
#[must_use]
pub fn totals(&self) -> &[RegisterTotal] {
&self.totals
}
#[must_use]
pub const fn clock(&self) -> Option<TimeStatus> {
self.worst_clock
}
#[must_use]
pub const fn best_clock(&self) -> Option<TimeStatus> {
self.best_clock
}
}
#[cfg(feature = "verify")]
#[cfg_attr(docsrs, doc(cfg(feature = "verify")))]
#[must_use]
pub fn validate_verified(verified: &[crate::Verified<'_, '_>]) -> SessionReport {
let records: Vec<&Record<'_>> = verified.iter().map(crate::Verified::record).collect();
validate_refs(&records)
}
#[must_use]
pub fn validate(records: &[Record<'_>]) -> SessionReport {
let refs: Vec<&Record<'_>> = records.iter().collect();
validate_refs(&refs)
}
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn validate_refs(records: &[&Record<'_>]) -> SessionReport {
let mut report = SessionReport::default();
let Some(first) = records.first() else {
report.findings.push(Finding::Empty);
return report;
};
report.kind = if records.iter().any(|r| r.payload().is_transaction()) {
SequenceKind::Transaction
} else {
SequenceKind::Fiscal
};
for (i, r) in records.iter().enumerate() {
if r.payload().pagination().is_none() {
report
.findings
.push(Finding::PaginationUnreadable { index: i });
}
}
for (i, pair) in records.windows(2).enumerate() {
let (Some(a), Some(b)) = (
pair[0].payload().pagination(),
pair[1].payload().pagination(),
) else {
continue;
};
if a.context() != b.context() {
report
.findings
.push(Finding::PaginationContextChanged { index: i + 1 });
} else if !a.is_followed_by(&b) {
report.findings.push(Finding::PaginationBroken {
from: a.number(),
to: b.number(),
index: i + 1,
});
}
}
let source = |r: &&Record<'_>| -> String {
let p = r.payload();
match (p.meter_serial(), p.gateway_serial()) {
(Some(m), Some(g)) => alloc::format!("{g}/{m}"),
(Some(m), None) => String::from(m),
(None, Some(g)) => String::from(g),
(None, None) => String::new(),
}
};
let expected = source(first);
for (i, r) in records.iter().enumerate().skip(1) {
let found = source(r);
if found != expected {
report.findings.push(Finding::SourceChanged {
index: i,
expected: expected.clone(),
found,
});
}
}
#[cfg(feature = "digest")]
{
let mut seen: Vec<[u8; 32]> = Vec::with_capacity(records.len());
for (i, r) in records.iter().enumerate() {
let d = r.payload_digest();
if seen.contains(&d) {
report.findings.push(Finding::DuplicateRecord { index: i });
}
seen.push(d);
}
}
let mut begins = Vec::new();
let mut ends = Vec::new();
for (i, r) in records.iter().enumerate() {
let p = r.payload();
if let Some(level) = p.identification_level()
&& level.is_error()
{
report.findings.push(Finding::IdentificationError {
index: i,
level: String::from(level.as_str()),
});
}
for reading in p.readings() {
match reading.state() {
Some(st) if !st.is_ok() => {
report.findings.push(Finding::MeterNotOk {
index: i,
state: st,
});
}
_ => {}
}
if reading.error_flags().any() {
report.findings.push(Finding::ErrorFlagged {
index: i,
flags: String::from(reading.error_flags().as_str()),
});
}
if let Some(tx) = reading.transaction() {
if tx.is_fault() {
report.findings.push(Finding::TransactionFaulted {
index: i,
marker: tx,
});
}
if tx.is_begin() {
begins.push(i);
}
if tx.is_end() {
ends.push(i);
}
}
if let Some(t) = reading.time() {
let status = t.status.unwrap_or(TimeStatus::Unknown);
report.worst_clock = Some(report.worst_clock.map_or(status, |w| w.min(status)));
report.best_clock = Some(report.best_clock.map_or(status, |b| {
if status.rank() > b.rank() { status } else { b }
}));
}
}
}
begins.dedup();
ends.dedup();
if report.kind == SequenceKind::Transaction {
check_markers(&begins, &ends, records.len(), &mut report.findings);
}
if report.worst_clock.is_none_or(|s| !s.duration_is_billable()) {
report.findings.push(Finding::ClockNotSynchronised {
status: report.worst_clock,
});
}
let mut totals: Vec<RegisterTotal> = Vec::new();
let mut unpaired: Vec<String> = Vec::new();
let mut begin_time = None;
let mut end_time = None;
let fiscal = report.kind == SequenceKind::Fiscal;
for r in records {
for series in r.payload().by_register() {
let (opens, closes) = if fiscal {
(
series.readings.first().copied(),
series.readings.last().copied(),
)
} else {
(series.begin(), series.end())
};
if let Some(b) = opens
&& let (Some(v), Some(u)) = (b.value(), b.unit())
&& !totals.iter().any(|t| t.obis == series.obis)
{
totals.push(RegisterTotal {
obis: series.obis.clone(),
begin: v.value(),
end: v.value(),
delta: Decimal::ZERO,
unit: String::from(u.as_str()),
});
begin_time = begin_time.or_else(|| b.time().map(|t| t.unix_millis()));
}
if let Some(e) = closes
&& let Some(v) = e.value()
{
match totals.iter_mut().find(|t| t.obis == series.obis) {
Some(t) => {
t.end = v.value();
t.delta = t.end - t.begin;
if let Some(stamp) = e.time() {
end_time = Some(stamp.unix_millis());
}
}
None => unpaired.push(series.obis.clone()),
}
}
}
}
for t in &totals {
if t.delta < Decimal::ZERO {
report.findings.push(Finding::MeterWentBackwards {
obis: t.obis.clone(),
});
}
}
unpaired.dedup();
for obis in unpaired {
report
.findings
.push(Finding::RegisterEndWithoutBegin { obis });
}
if let (Some(b), Some(e)) = (begin_time, end_time)
&& e < b
{
report.findings.push(Finding::TimeWentBackwards);
}
report.totals = totals;
report
}
fn check_markers(begins: &[usize], ends: &[usize], count: usize, out: &mut Vec<Finding>) {
match begins {
[] => out.push(Finding::NoBegin),
[only] if *only != 0 => out.push(Finding::MarkerOutOfPlace { index: *only }),
[_] => {}
_ => out.push(Finding::MultipleBegins),
}
match ends {
[] => out.push(Finding::NoEnd),
[only] if *only != count - 1 => out.push(Finding::MarkerOutOfPlace { index: *only }),
[_] => {}
_ => out.push(Finding::MultipleEnds),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::Record;
use alloc::string::ToString;
use alloc::vec;
fn record(pg: u32, tx: &str, rv: &str, extra: &str) -> String {
alloc::format!(
r#"OCMF|{{"FV":"1.4","GS":"GW-1","PG":"T{pg}","MS":"METER-1","IS":true,"IL":"VERIFIED","IF":[],"IT":"ISO14443","ID":"AA","RD":[{{"TM":"2018-07-24T13:{:02}:04,000+0200 S","TX":"{tx}","RV":{rv},"RI":"1-b:1.8.0","RU":"kWh","EF":"","ST":"G"{extra}}}]}}|{{"SD":"00"}}"#,
20 + pg
)
}
fn parse_all(texts: &[String]) -> Vec<Record<'_>> {
texts.iter().map(|t| Record::parse(t).unwrap()).collect()
}
#[test]
fn a_clean_two_record_session_reports_nothing() {
let texts = vec![record(1, "B", "10.000", ""), record(2, "E", "12.500", "")];
let report = validate(&parse_all(&texts));
assert!(report.is_clean(), "{:?}", report.findings());
assert_eq!(report.totals()[0].delta.to_string(), "2.500");
assert_eq!(report.clock(), Some(TimeStatus::Synchronized));
}
#[test]
fn a_removed_record_is_caught_by_the_pagination() {
let texts = vec![record(1, "B", "10.000", ""), record(3, "E", "12.500", "")];
let report = validate(&parse_all(&texts));
assert!(report.findings().contains(&Finding::PaginationBroken {
from: 1,
to: 3,
index: 1
}));
}
#[test]
fn a_session_that_never_ends_is_not_a_session() {
let texts = vec![record(1, "B", "10.000", "")];
let report = validate(&parse_all(&texts));
assert!(report.findings().contains(&Finding::NoEnd));
}
#[test]
fn records_from_another_meter_do_not_belong_to_this_session() {
let texts = vec![
record(1, "B", "10.000", ""),
record(2, "E", "12.500", "").replace("METER-1", "METER-2"),
];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::SourceChanged { .. }))
);
}
#[test]
fn a_meter_fault_and_an_error_flag_are_both_findings() {
let texts = vec![
record(1, "B", "10.000", ""),
record(2, "E", "12.500", "").replace(r#""ST":"G""#, r#""ST":"F""#),
];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::MeterNotOk { .. }))
);
let texts = vec![
record(1, "B", "10.000", ""),
record(2, "E", "12.500", "").replace(r#""EF":"""#, r#""EF":"E""#),
];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::ErrorFlagged { .. }))
);
}
#[test]
fn a_meter_that_runs_backwards_is_a_finding() {
let texts = vec![record(1, "B", "12.500", ""), record(2, "E", "10.000", "")];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::MeterWentBackwards { .. }))
);
}
#[test]
fn an_unsynchronised_clock_blocks_a_time_tariff() {
let texts = vec![
record(1, "B", "10.000", "").replace("+0200 S", "+0200 U"),
record(2, "E", "12.500", "").replace("+0200 S", "+0200 U"),
];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::ClockNotSynchronised { .. }))
);
}
#[test]
fn one_synchronised_reading_does_not_vouch_for_an_unsynchronised_session() {
let texts = vec![
record(1, "B", "10.000", ""),
record(2, "E", "12.500", "").replace("+0200 S", "+0200 U"),
];
let report = validate(&parse_all(&texts));
assert_eq!(report.clock(), Some(TimeStatus::Unknown), "the weakest");
assert_eq!(
report.best_clock(),
Some(TimeStatus::Synchronized),
"reported, and not what anything is decided on"
);
assert!(report.findings().contains(&Finding::ClockNotSynchronised {
status: Some(TimeStatus::Unknown)
}));
}
#[test]
fn a_relative_clock_is_good_enough_for_a_duration() {
let texts = vec![
record(1, "B", "10.000", "").replace("+0200 S", "+0200 R"),
record(2, "E", "12.500", "").replace("+0200 S", "+0200 R"),
];
let report = validate(&parse_all(&texts));
assert!(
!report
.findings()
.iter()
.any(|f| matches!(f, Finding::ClockNotSynchronised { .. }))
);
}
#[test]
fn a_failed_user_assignment_is_a_finding() {
let texts = vec![
record(1, "B", "10.000", "").replace("VERIFIED", "MISMATCH"),
record(2, "E", "12.500", ""),
];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::IdentificationError { .. }))
);
}
#[test]
#[cfg(feature = "digest")]
fn the_same_record_twice_is_caught_even_with_a_valid_pagination() {
let one = record(1, "B", "10.000", "");
let texts = vec![one.clone(), one];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.iter()
.any(|f| matches!(f, Finding::DuplicateRecord { .. }))
);
}
#[test]
fn a_register_that_ends_without_beginning_has_no_delta_and_says_so() {
let texts = vec![
record(1, "B", "10.000", ""),
record(2, "E", "12.500", "").replace(r#""RI":"1-b:1.8.0""#, r#""RI":"1-b:2.8.0""#),
];
let report = validate(&parse_all(&texts));
assert!(
report
.findings()
.contains(&Finding::RegisterEndWithoutBegin {
obis: String::from("01-0B:02.08.00")
}),
"{:?}",
report.findings()
);
assert!(report.totals().iter().all(|t| t.delta == Decimal::ZERO));
}
fn fiscal(pg: u32, rv: &str) -> String {
alloc::format!(
r#"OCMF|{{"FV":"1.3","PG":"F{pg}","MS":"METER-1","RD":[{{"TM":"2024-03-01T0{pg}:00:00,000+0100 S","RV":{rv},"RI":"01-00:B1.08.00*FF","RU":"kWh","EF":"","ST":"G"}}]}}|{{"SD":"00"}}"#
)
}
#[test]
fn a_fiscal_sequence_is_not_asked_for_markers_it_cannot_carry() {
let texts = vec![fiscal(1, "100.000"), fiscal(2, "129.500")];
let report = validate(&parse_all(&texts));
assert_eq!(report.kind(), SequenceKind::Fiscal);
assert!(report.is_clean(), "{:?}", report.findings());
assert_eq!(report.totals().len(), 1);
assert_eq!(report.totals()[0].delta.to_string(), "29.500");
}
#[test]
fn a_fiscal_sequence_is_still_held_to_every_other_rule() {
let texts = vec![fiscal(1, "100.000"), fiscal(3, "129.500")];
let report = validate(&parse_all(&texts));
assert!(report.findings().contains(&Finding::PaginationBroken {
from: 1,
to: 3,
index: 1
}));
let texts = vec![fiscal(1, "129.500"), fiscal(2, "100.000")];
assert!(
validate(&parse_all(&texts))
.findings()
.iter()
.any(|f| matches!(f, Finding::MeterWentBackwards { .. }))
);
}
#[test]
fn a_transaction_sequence_is_still_judged_as_one() {
let texts = vec![record(1, "B", "10.000", ""), record(2, "E", "12.500", "")];
assert_eq!(
validate(&parse_all(&texts)).kind(),
SequenceKind::Transaction
);
}
#[test]
#[cfg(feature = "serde")]
fn a_report_serialises_and_the_quantities_stay_exact() {
let texts = vec![record(1, "B", "10.000", ""), record(2, "E", "12.500", "")];
let json = serde_json::to_string(&validate(&parse_all(&texts))).unwrap();
assert!(json.contains(r#""delta":"2.500""#), "{json}");
assert!(json.contains(r#""kind":"Transaction""#), "{json}");
assert!(json.contains(r#""worst_clock":"S""#), "{json}");
let texts = vec![record(1, "B", "10.000", ""), record(3, "E", "12.500", "")];
let json = serde_json::to_string(&validate(&parse_all(&texts))).unwrap();
assert!(json.contains(r#""finding":"PaginationBroken""#), "{json}");
}
#[test]
fn an_empty_sequence_says_so() {
assert_eq!(validate(&[]).findings(), &[Finding::Empty]);
}
#[test]
#[cfg(feature = "curve-p256")]
fn the_verified_entry_point_runs_the_same_rules() {
use crate as ocmf_self;
use ocmf_self::sign::{ReadingSpec, RecordBuilder, Secp256r1Signer, Signer};
let signer = Secp256r1Signer::from_bytes(&[3u8; 32]).unwrap();
let key = signer.public_key().unwrap();
let at =
|s: &str| crate::OcmfTime::parse(s, &crate::Location::at(0), &mut Vec::new()).unwrap();
let one = |page: u64, marker: TransactionMarker, value: &str| {
RecordBuilder::new()
.gateway("ocmf", "GW-1", "0.1.0")
.pagination(crate::Pagination::transaction(page))
.meter_serial("METER-1")
.identification(
true,
crate::IdentificationLevel::Verified,
Vec::new(),
crate::IdentificationType::None,
"",
)
.reading(
ReadingSpec::new(
at("2024-03-01T08:00:00,000+0100 S"),
Decimal::from_str_exact(value).unwrap(),
"01-00:B1.08.00*FF",
crate::Unit::KWh,
)
.transaction(marker),
)
.sign(&signer)
.unwrap()
};
let bufs = [
one(1, TransactionMarker::Begin, "10.000"),
one(2, TransactionMarker::End, "12.500"),
];
let records: Vec<_> = bufs.iter().map(|b| b.record().unwrap()).collect();
let verified: Vec<_> = records
.iter()
.map(|r| crate::verify(r, &key).expect("this crate signed it"))
.collect();
let report = validate_verified(&verified);
assert!(report.is_clean(), "{:?}", report.findings());
assert_eq!(report.totals()[0].delta.to_string(), "2.500");
assert_eq!(
report.findings(),
validate(&records).findings(),
"the same rules, whatever the caller holds"
);
}
}