Skip to main content

emob_session/
meter.rs

1//! The meter readings a session leaves behind, and where each one came from.
2//!
3//! A charging station reports its energy register several times during a
4//! session: once at the start, once at the end, periodically in between, and —
5//! when configured for it — on every quarter-hour boundary of the clock. OCPP
6//! calls that last kind `Sample.Clock`, and it is the one that matters most
7//! here, because it is the only kind that can settle a quarter hour without
8//! anybody having to guess.
9
10use emob_core::{Direction, Energy};
11
12/// Why a reading was taken.
13///
14/// The OCPP `ReadingContext` values, kept because the distinction decides how
15/// much a reading is worth for settlement. `Sample.Clock` is a measurement of a
16/// quarter-hour boundary; `Sample.Periodic` is a measurement of whenever the
17/// station felt like it.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[non_exhaustive]
21pub enum ReadingContext {
22    /// `Transaction.Begin` — the opening register value.
23    TransactionBegin,
24    /// `Transaction.End` — the closing register value.
25    TransactionEnd,
26    /// `Sample.Clock` — aligned to the clock, at `AlignedDataInterval`.
27    SampleClock,
28    /// `Sample.Periodic` — at `SampledDataTxUpdatedInterval`, from an arbitrary
29    /// phase.
30    SamplePeriodic,
31    /// `Interruption.Begin` — charging stopped.
32    InterruptionBegin,
33    /// `Interruption.End` — charging resumed.
34    InterruptionEnd,
35    /// `Trigger` — the backend asked for it.
36    Trigger,
37    /// `Other`.
38    Other,
39}
40
41impl ReadingContext {
42    /// Whether this reading lands on a clock boundary by construction.
43    ///
44    /// Only `Sample.Clock` does. A periodic sample that happens to fall on
45    /// `:15:00` is a coincidence, and settling a quarter hour on a coincidence
46    /// is how two suppliers end up disagreeing by the same kilowatt-hour in
47    /// opposite directions.
48    #[must_use]
49    pub const fn is_clock_aligned(self) -> bool {
50        matches!(self, Self::SampleClock)
51    }
52
53    /// Whether this reading bounds the transaction.
54    #[must_use]
55    pub const fn is_transaction_boundary(self) -> bool {
56        matches!(self, Self::TransactionBegin | Self::TransactionEnd)
57    }
58
59    /// The OCPP spelling, identical in 1.6, 2.0.1 and 2.1.
60    ///
61    /// Beside the variants rather than in the OCPP crate, because these *are*
62    /// the OCPP names — the variant documentation gives them one line up — and a
63    /// spelling kept somewhere else is a spelling that drifts from the enum it
64    /// spells.
65    #[must_use]
66    pub const fn as_str(self) -> &'static str {
67        match self {
68            Self::TransactionBegin => "Transaction.Begin",
69            Self::TransactionEnd => "Transaction.End",
70            Self::SampleClock => "Sample.Clock",
71            Self::SamplePeriodic => "Sample.Periodic",
72            Self::InterruptionBegin => "Interruption.Begin",
73            Self::InterruptionEnd => "Interruption.End",
74            Self::Trigger => "Trigger",
75            Self::Other => "Other",
76        }
77    }
78}
79
80impl core::fmt::Display for ReadingContext {
81    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
82        f.write_str(self.as_str())
83    }
84}
85
86/// One reading of a cumulative energy register.
87///
88/// Cumulative, not incremental: this is the register's own running total, the
89/// quantity OCMF signs and the quantity a difference between two readings is
90/// taken of. An incremental value cannot be checked against anything.
91#[derive(Debug, Clone, PartialEq, Eq)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
93pub struct MeterReading {
94    /// When the register held this value.
95    #[cfg_attr(feature = "serde", serde(with = "time::serde::rfc3339"))]
96    pub at: time::OffsetDateTime,
97    /// The register's value.
98    pub register: Energy,
99    /// Which way the energy this register counts was flowing.
100    pub direction: Direction,
101    /// Why this reading was taken.
102    pub context: ReadingContext,
103    /// Whether a signed record backs this reading.
104    ///
105    /// Set by the layer that has the evidence. A reading nobody signed may
106    /// still be perfectly good telemetry; it may not be the basis of an
107    /// invoice `[MessEG §33]`.
108    pub signed: bool,
109}
110
111impl MeterReading {
112    /// A reading, unsigned.
113    #[must_use]
114    pub const fn new(
115        at: time::OffsetDateTime,
116        register: Energy,
117        direction: Direction,
118        context: ReadingContext,
119    ) -> Self {
120        Self {
121            at,
122            register,
123            direction,
124            context,
125            signed: false,
126        }
127    }
128
129    /// The same reading, marked as backed by a signed record.
130    #[must_use]
131    pub const fn signed(mut self) -> Self {
132        self.signed = true;
133        self
134    }
135}
136
137/// A session's readings for one direction, in time order.
138///
139/// One direction, because import and export are separate registers counting
140/// separate quantities. Interleaving them into one series and taking
141/// differences would net a V2G discharge against a draw, and both would leave
142/// their supplier's balance group unaccounted for — the same rule
143/// `mako-emob` enforces on the market side `[A6 §IV.1]`.
144#[derive(Debug, Clone, PartialEq, Eq)]
145#[cfg_attr(feature = "serde", derive(serde::Serialize))]
146pub struct MeterSeries {
147    direction: Direction,
148    readings: Vec<MeterReading>,
149}
150
151/// Read back through [`MeterSeries::new`], because the ordering, the single
152/// direction and the register that never runs backwards are what the type
153/// **is**.
154///
155/// A derived `Deserialize` restored the fields and asked none of it, so a series
156/// read from a store could interleave two directions, contradict itself about
157/// one instant, or run its register backwards — and every consumer downstream
158/// takes differences of exactly those numbers (D264).
159#[cfg(feature = "serde")]
160impl<'de> serde::Deserialize<'de> for MeterSeries {
161    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
162        use serde::de::Error as _;
163
164        #[derive(serde::Deserialize)]
165        struct AsSent {
166            direction: Direction,
167            readings: Vec<MeterReading>,
168        }
169
170        let sent = AsSent::deserialize(deserializer)?;
171        Self::new(sent.direction, sent.readings).map_err(D::Error::custom)
172    }
173}
174
175impl MeterSeries {
176    /// Build a series from readings, sorting them and checking their coherence.
177    ///
178    /// # Errors
179    ///
180    /// [`MeterError`] when the readings are empty, mix directions, contradict
181    /// each other about one instant, or contain a register that runs
182    /// backwards — the last being a fault to escalate, never a negative
183    /// quantity to bill.
184    pub fn new(direction: Direction, mut readings: Vec<MeterReading>) -> Result<Self, MeterError> {
185        if readings.is_empty() {
186            return Err(MeterError::Empty);
187        }
188        if let Some(wrong) = readings.iter().find(|r| r.direction != direction) {
189            return Err(MeterError::MixedDirections {
190                expected: direction,
191                found: wrong.direction,
192            });
193        }
194
195        readings.sort_by_key(|r| r.at);
196
197        for pair in readings.windows(2) {
198            // Two readings of one register at one instant that disagree about
199            // its value. A meter had one value at that moment, so one of the
200            // two is wrong — and which one decides the energy either side of
201            // the boundary.
202            //
203            // Asked **before** the monotonicity question, because otherwise the
204            // sort decides which fault is reported: the same contradiction is
205            // `RegisterRanBackwards` when the larger value happens to be sorted
206            // first, and silently accepted when the smaller is. A stable sort
207            // preserves the caller's order at equal keys, so that is the
208            // arrival order of two messages — which is not evidence about a
209            // meter.
210            if pair[0].at == pair[1].at && pair[0].register != pair[1].register {
211                return Err(MeterError::ContradictoryReading {
212                    at: pair[0].at,
213                    one: pair[0].register,
214                    other: pair[1].register,
215                });
216            }
217            if pair[1].register < pair[0].register {
218                return Err(MeterError::RegisterRanBackwards {
219                    at: pair[1].at,
220                    from: pair[0].register,
221                    to: pair[1].register,
222                });
223            }
224        }
225
226        Ok(Self {
227            direction,
228            readings,
229        })
230    }
231
232    /// Which direction these readings count.
233    #[must_use]
234    pub const fn direction(&self) -> Direction {
235        self.direction
236    }
237
238    /// The readings, in time order.
239    #[must_use]
240    pub fn readings(&self) -> &[MeterReading] {
241        &self.readings
242    }
243
244    /// The first reading.
245    #[must_use]
246    pub fn first(&self) -> &MeterReading {
247        // `new` refuses an empty series.
248        &self.readings[0]
249    }
250
251    /// The last reading.
252    #[must_use]
253    pub fn last(&self) -> &MeterReading {
254        &self.readings[self.readings.len() - 1]
255    }
256
257    /// The total energy across the whole series.
258    ///
259    /// # Errors
260    ///
261    /// [`MeterError::RegisterRanBackwards`] cannot occur — `new` already
262    /// rejected it — but the subtraction is fallible in the type system, so the
263    /// error is surfaced rather than unwrapped.
264    pub fn total(&self) -> Result<Energy, MeterError> {
265        self.last()
266            .register
267            .difference_from(self.first().register)
268            .map_err(|_| MeterError::RegisterRanBackwards {
269                at: self.last().at,
270                from: self.first().register,
271                to: self.last().register,
272            })
273    }
274
275    /// How many readings land on a clock boundary.
276    ///
277    /// The number that decides whether a quarter-hour settlement is measured or
278    /// interpolated, so it is worth being able to ask for directly — an
279    /// operator's answer to "why is this session's allocation marked
280    /// interpolated?" usually starts here.
281    #[must_use]
282    pub fn clock_aligned_count(&self) -> usize {
283        self.readings
284            .iter()
285            .filter(|r| r.context.is_clock_aligned())
286            .count()
287    }
288
289    /// Whether every reading is backed by a signed record.
290    #[must_use]
291    pub fn fully_signed(&self) -> bool {
292        self.readings.iter().all(|r| r.signed)
293    }
294}
295
296/// What can be wrong with a series of readings.
297#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
298#[non_exhaustive]
299pub enum MeterError {
300    /// No readings at all.
301    #[error("a meter series needs at least one reading")]
302    Empty,
303
304    /// A reading counts the other direction.
305    #[error("a {expected} series must not contain a {found} reading: the two never net")]
306    MixedDirections {
307        /// The series' direction.
308        expected: Direction,
309        /// The reading's direction.
310        found: Direction,
311    },
312
313    /// The register decreased between two readings.
314    #[error("the register ran backwards at {at}: {from} then {to}")]
315    RegisterRanBackwards {
316        /// When.
317        at: time::OffsetDateTime,
318        /// The earlier value.
319        from: Energy,
320        /// The later, smaller value.
321        to: Energy,
322    },
323
324    /// Two readings state different values for one register at one instant.
325    ///
326    /// A meter had one value at that moment, so one of the two is wrong — and
327    /// which one decides the energy on both sides of the boundary. Kept apart
328    /// from [`Self::RegisterRanBackwards`] because it is a different fault with
329    /// a different fix: a register that decreased over time is a metrology
330    /// incident, while two values at one instant is a station or a transport
331    /// sending the same reading twice with different content.
332    #[error(
333        "two readings state different values for one register at {at}: {one} and {other}. A meter had one value at that instant"
334    )]
335    ContradictoryReading {
336        /// When.
337        at: time::OffsetDateTime,
338        /// One of the two values.
339        one: Energy,
340        /// The other.
341        other: Energy,
342    },
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use rust_decimal::Decimal;
349    use std::str::FromStr;
350    use time::macros::datetime;
351
352    fn kwh(s: &str) -> Energy {
353        Energy::from_kwh(Decimal::from_str(s).unwrap()).unwrap()
354    }
355
356    fn reading(minute: u8, value: &str, context: ReadingContext) -> MeterReading {
357        MeterReading::new(
358            datetime!(2026-01-02 10:00 +1) + time::Duration::minutes(i64::from(minute)),
359            kwh(value),
360            Direction::Import,
361            context,
362        )
363    }
364
365    #[cfg(feature = "serde")]
366    #[test]
367    fn a_series_arrives_through_the_constructor_that_orders_it() {
368        // The ordering, the single direction and the register that never runs
369        // backwards are what the type is. A derived `Deserialize` restored the
370        // fields and asked none of it, and every consumer downstream takes
371        // differences of exactly those numbers (D264).
372        let backwards = r#"{"direction":"import","readings":[
373            {"at":"2026-01-02T10:00:00+01:00","register":"110.000","direction":"import","context":"TransactionBegin","signed":false},
374            {"at":"2026-01-02T10:15:00+01:00","register":"100.000","direction":"import","context":"TransactionEnd","signed":false}]}"#;
375        assert!(serde_json::from_str::<MeterSeries>(backwards).is_err());
376
377        let mixed = r#"{"direction":"import","readings":[
378            {"at":"2026-01-02T10:00:00+01:00","register":"100.000","direction":"export","context":"TransactionBegin","signed":false}]}"#;
379        assert!(serde_json::from_str::<MeterSeries>(mixed).is_err());
380
381        let ordinary = r#"{"direction":"import","readings":[
382            {"at":"2026-01-02T10:00:00+01:00","register":"100.000","direction":"import","context":"TransactionBegin","signed":false},
383            {"at":"2026-01-02T10:15:00+01:00","register":"110.000","direction":"import","context":"TransactionEnd","signed":false}]}"#;
384        let series: MeterSeries = serde_json::from_str(ordinary).unwrap();
385        assert_eq!(series.total().unwrap().to_string(), "10.000 kWh");
386    }
387
388    #[test]
389    fn two_values_for_one_instant_are_a_contradiction_rather_than_an_order() {
390        // A meter had one value at that moment. Which of the two is believed
391        // decides the energy on both sides of the boundary, and the sort cannot
392        // decide it: a stable sort preserves the caller's order at equal keys,
393        // so the same contradiction read as `RegisterRanBackwards` when the
394        // larger value arrived first and was silently accepted when the smaller
395        // did.
396        let descending = MeterSeries::new(
397            Direction::Import,
398            vec![
399                reading(0, "10.000", ReadingContext::TransactionBegin),
400                reading(30, "30.000", ReadingContext::SamplePeriodic),
401                reading(30, "28.000", ReadingContext::TransactionEnd),
402            ],
403        );
404        let ascending = MeterSeries::new(
405            Direction::Import,
406            vec![
407                reading(0, "10.000", ReadingContext::TransactionBegin),
408                reading(30, "28.000", ReadingContext::SamplePeriodic),
409                reading(30, "30.000", ReadingContext::TransactionEnd),
410            ],
411        );
412        for series in [descending, ascending] {
413            assert!(
414                matches!(series, Err(MeterError::ContradictoryReading { .. })),
415                "the arrival order of two messages is not evidence about a meter: {series:?}"
416            );
417        }
418
419        // …and a retransmission that says the same thing is not a
420        // contradiction, because it does not contradict anything.
421        assert!(
422            MeterSeries::new(
423                Direction::Import,
424                vec![
425                    reading(0, "10.000", ReadingContext::TransactionBegin),
426                    reading(30, "30.000", ReadingContext::TransactionEnd),
427                    reading(30, "30.000", ReadingContext::TransactionEnd),
428                ],
429            )
430            .is_ok()
431        );
432    }
433
434    #[test]
435    fn readings_are_sorted_and_totalled() {
436        let series = MeterSeries::new(
437            Direction::Import,
438            vec![
439                reading(30, "30.000", ReadingContext::TransactionEnd),
440                reading(0, "10.000", ReadingContext::TransactionBegin),
441                reading(15, "20.000", ReadingContext::SampleClock),
442            ],
443        )
444        .unwrap();
445
446        assert_eq!(series.readings().len(), 3);
447        assert_eq!(series.first().register, kwh("10.000"));
448        assert_eq!(series.last().register, kwh("30.000"));
449        assert_eq!(series.total().unwrap().to_string(), "20.000 kWh");
450    }
451
452    #[test]
453    fn a_series_refuses_the_other_direction() {
454        let mut export = reading(0, "1", ReadingContext::TransactionBegin);
455        export.direction = Direction::Export;
456        let err = MeterSeries::new(
457            Direction::Import,
458            vec![reading(0, "1", ReadingContext::TransactionBegin), export],
459        )
460        .unwrap_err();
461        assert!(matches!(err, MeterError::MixedDirections { .. }));
462        assert!(err.to_string().contains("never net"));
463    }
464
465    #[test]
466    fn a_backwards_register_is_a_fault() {
467        let err = MeterSeries::new(
468            Direction::Import,
469            vec![
470                reading(0, "30.000", ReadingContext::TransactionBegin),
471                reading(15, "10.000", ReadingContext::TransactionEnd),
472            ],
473        )
474        .unwrap_err();
475        assert!(matches!(err, MeterError::RegisterRanBackwards { .. }));
476    }
477
478    #[test]
479    fn an_empty_series_is_refused() {
480        assert!(matches!(
481            MeterSeries::new(Direction::Import, vec![]),
482            Err(MeterError::Empty)
483        ));
484    }
485
486    #[test]
487    fn only_sample_clock_counts_as_aligned() {
488        let series = MeterSeries::new(
489            Direction::Import,
490            vec![
491                reading(0, "10", ReadingContext::TransactionBegin),
492                reading(15, "20", ReadingContext::SampleClock),
493                // Falls on a boundary by coincidence, which is not the same
494                // thing as being aligned to one.
495                reading(30, "25", ReadingContext::SamplePeriodic),
496                reading(45, "30", ReadingContext::TransactionEnd),
497            ],
498        )
499        .unwrap();
500        assert_eq!(series.clock_aligned_count(), 1);
501    }
502
503    #[test]
504    fn signing_is_tracked_per_reading() {
505        let series = MeterSeries::new(
506            Direction::Import,
507            vec![
508                reading(0, "10", ReadingContext::TransactionBegin).signed(),
509                reading(15, "20", ReadingContext::TransactionEnd),
510            ],
511        )
512        .unwrap();
513        assert!(!series.fully_signed());
514    }
515}