emob_session/session.rs
1//! The session itself, and the states it may legally be in.
2//!
3//! A session is not a row that gets updated. It is a sequence of events with an
4//! order the protocol guarantees — authorised, plugged, charging, suspended,
5//! ended — and a state machine that refuses the transitions the protocol
6//! forbids. Modelling it as mutable fields is how a session ends twice, or
7//! delivers energy after it stopped, and both of those reach an invoice.
8
9use emob_core::{Activity, Direction, Energy, EvseId, SessionId};
10
11use crate::auth::Authorization;
12use crate::meter::MeterSeries;
13use crate::split::{SessionSplit, SplitError, into_periods};
14
15/// Where a session is in its life.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
19pub enum SessionState {
20 /// Authorised, but no energy has moved. A reservation, or a cable not yet
21 /// plugged in.
22 Pending,
23 /// Energy is moving.
24 Charging,
25 /// Plugged in and authorised, and **the vehicle** has stopped asking for
26 /// power — the battery is full, or the car paused its own charge.
27 ///
28 /// This is the occupancy `[AFIR Art. 5(4)]` lets a fast charger price per
29 /// minute, and the only state that is.
30 SuspendedByVehicle,
31 /// Plugged in and authorised, and **the operator** has stopped offering
32 /// power while the vehicle is still asking for it — a charging profile
33 /// holding the point at zero, a `[EnWG §14a]` dimming, a grid limit, a
34 /// fault.
35 ///
36 /// Kept apart from [`Self::SuspendedByVehicle`] because the two are priced
37 /// differently and one boolean cannot say which. OCPP has said which since
38 /// 2.0.1 — `SuspendedEV` against `SuspendedEVSE` — and
39 /// `[OCPI 2.3.0 §mod_cdrs_chargingperiod_class]` corrected its own
40 /// definition of `PARKING_TIME` to the vehicle's demand precisely so that a
41 /// driver is not billed a loitering fee for the operator's own curtailment.
42 /// Collapsing them here is what puts that fee on the invoice.
43 SuspendedByOperator,
44 /// Over. Nothing further may be added.
45 Ended,
46}
47
48impl SessionState {
49 /// Whether the session has finished.
50 #[must_use]
51 pub const fn is_final(self) -> bool {
52 matches!(self, Self::Ended)
53 }
54
55 /// Whether a transition to `next` is one the protocol allows.
56 ///
57 /// Written as one arm per rule rather than as the shortest expression that
58 /// computes the same booleans. The table *is* the specification of a
59 /// session's life, and a reader checking it against OCPP needs to find each
60 /// rule where it lives.
61 #[must_use]
62 #[allow(
63 clippy::match_same_arms,
64 reason = "one arm per protocol rule; collapsing them by return value \
65 would make the transition table unreadable"
66 )]
67 pub const fn can_transition_to(self, next: Self) -> bool {
68 match (self, next) {
69 // Nothing follows the end.
70 (Self::Ended, _) => false,
71 // A session may start charging, be held at zero, or be abandoned.
72 (
73 Self::Pending,
74 Self::Charging | Self::SuspendedByVehicle | Self::SuspendedByOperator | Self::Ended,
75 ) => true,
76 // Charging may pause — for either reason — or finish; it may not go
77 // back to pending, because energy has already moved.
78 (
79 Self::Charging,
80 Self::SuspendedByVehicle | Self::SuspendedByOperator | Self::Ended,
81 ) => true,
82 // A suspended session may resume, finish, or change *why* it is
83 // suspended: a car that fills while the point is curtailed has
84 // moved from one to the other, and both intervals are priced.
85 (
86 Self::SuspendedByVehicle | Self::SuspendedByOperator,
87 Self::Charging | Self::SuspendedByVehicle | Self::SuspendedByOperator | Self::Ended,
88 ) => true,
89 _ => false,
90 }
91 }
92}
93
94/// Why a session ended.
95///
96/// Worth recording separately from the state because a dispute usually turns on
97/// it: a session the operator cut off is a different conversation from one the
98/// driver ended.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
102#[non_exhaustive]
103pub enum EndReason {
104 /// The driver stopped it at the point.
105 Local,
106 /// The backend stopped it.
107 Remote,
108 /// The cable was unplugged.
109 EvDisconnected,
110 /// The vehicle reported itself full.
111 EvFull,
112 /// Authorisation was withdrawn.
113 DeAuthorized,
114 /// A fault.
115 Fault,
116 /// Power was lost.
117 PowerLoss,
118 /// Something else the station named.
119 Other,
120}
121
122/// One state the session was in, and when it entered it.
123///
124/// The history exists because "suspended" is not a status light, it is an
125/// interval that gets priced: `[AFIR Art. 5(4)]` lets a fast charger add an
126/// occupancy fee per minute for the time the vehicle is connected and not
127/// charging. A state field with no timestamp can say the session *is*
128/// suspended and never say for how long, which is precisely the number the
129/// article turns on.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
132pub struct StateChange {
133 /// The state entered.
134 pub state: SessionState,
135 /// When.
136 #[cfg_attr(feature = "serde", serde(with = "time::serde::rfc3339"))]
137 pub at: time::OffsetDateTime,
138}
139
140/// A charging session.
141#[derive(Debug, Clone, PartialEq, Eq)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
143pub struct Session {
144 /// Which session.
145 pub id: SessionId,
146 /// Where it happened.
147 pub evse_id: EvseId,
148 /// How it was authorised, and for whom.
149 pub authorization: Authorization,
150 /// When it began.
151 #[cfg_attr(feature = "serde", serde(with = "time::serde::rfc3339"))]
152 pub started_at: time::OffsetDateTime,
153 /// When it ended, once it has.
154 #[cfg_attr(feature = "serde", serde(with = "time::serde::rfc3339::option"))]
155 pub ended_at: Option<time::OffsetDateTime>,
156 /// Why it ended.
157 pub end_reason: Option<EndReason>,
158 /// Every state the session has been in, in order, starting with
159 /// [`SessionState::Pending`] at [`Self::started_at`].
160 history: Vec<StateChange>,
161 /// The energy it moved, by direction.
162 ///
163 /// A vector rather than one series because a bidirectional session has two
164 /// registers counting two quantities, and they never net.
165 pub series: Vec<MeterSeries>,
166 /// The vehicle-communication generation this session actually negotiated.
167 ///
168 /// # A different fact from the one the compliance calendar reads
169 ///
170 /// `emob_core::V2gCommunication` says what a **charger implements**, which
171 /// is what every `[DA-656 Anh. 2.1.x]` duty is judged on. This says what
172 /// two parties agreed on the wire, once, at an instant. A point that
173 /// implements -2 and -20 and negotiates -2 with a 2018 car is compliant and
174 /// had a -2 session, and until there was a Plug & Charge crate there was
175 /// nothing to put the second fact on.
176 ///
177 /// `None` for a session that negotiated nothing high-level — an RFID card
178 /// on a PWM point — which is not the same as *"nobody recorded it"* and is
179 /// why [`Self::contradicts_its_own_protocol`] asks about the pair rather
180 /// than about this field alone.
181 pub negotiated: Option<emob_core::V2gProtocol>,
182}
183
184impl Session {
185 /// Open a session in [`SessionState::Pending`].
186 #[must_use]
187 pub fn open(
188 id: SessionId,
189 evse_id: EvseId,
190 authorization: Authorization,
191 started_at: time::OffsetDateTime,
192 ) -> Self {
193 Self {
194 id,
195 evse_id,
196 authorization,
197 started_at,
198 ended_at: None,
199 end_reason: None,
200 history: vec![StateChange {
201 state: SessionState::Pending,
202 at: started_at,
203 }],
204 series: Vec::new(),
205 negotiated: None,
206 }
207 }
208
209 /// Record which vehicle-communication generation this session negotiated.
210 #[must_use]
211 pub fn negotiated(mut self, protocol: emob_core::V2gProtocol) -> Self {
212 self.negotiated = Some(protocol);
213 self
214 }
215
216 /// Whether the session's authorisation and its negotiated protocol are two
217 /// stories about one event.
218 ///
219 /// Plug & Charge is ISO 15118's. DIN SPEC 70121 is external identification
220 /// only — a card or an app — so a session recorded as `din70121` and
221 /// authorised by a contract certificate is a claim no charger can have
222 /// made, and the pair is the only place it becomes checkable: each half on
223 /// its own is a perfectly ordinary value.
224 ///
225 /// The same shape as the cross-check between an authorisation path and a
226 /// signed record's identification level, one field along — and it answers
227 /// `false` where the protocol was not recorded, because a fact nobody
228 /// stated contradicts nothing.
229 #[must_use]
230 pub fn contradicts_its_own_protocol(&self) -> bool {
231 self.authorization.path == crate::AuthPath::PlugAndCharge
232 && self
233 .negotiated
234 .is_some_and(|protocol| !protocol.carries_plug_and_charge())
235 }
236
237 /// Where the session is now.
238 #[must_use]
239 pub fn state(&self) -> SessionState {
240 // `open` seeds the history and nothing empties it.
241 self.history[self.history.len() - 1].state
242 }
243
244 /// Every state it has been in, in order.
245 #[must_use]
246 pub fn history(&self) -> &[StateChange] {
247 &self.history
248 }
249
250 /// The state the session was in at an instant.
251 ///
252 /// `None` before it started.
253 #[must_use]
254 pub fn state_at(&self, at: time::OffsetDateTime) -> Option<SessionState> {
255 self.history
256 .iter()
257 .rev()
258 .find(|change| change.at <= at)
259 .map(|change| change.state)
260 }
261
262 /// What the session says it was doing across the whole of `[from, to)`.
263 ///
264 /// `None` for an interval the record does not answer with one word: one
265 /// that spans a transition, one before the session started, one after it
266 /// ended, an empty one — and one in [`SessionState::Pending`], which is
267 /// authorised with no vehicle demand yet and no operator refusal either.
268 ///
269 /// This is the question `emob-cdr` asks of every period it prices, and it
270 /// is deliberately **one** question rather than two booleans. Asking
271 /// "was it charging" and "was it suspended" separately leaves the third
272 /// answer — the operator withholding power from a vehicle that is asking —
273 /// indistinguishable from the second, which is exactly the conflation
274 /// `[OCPI 2.3.0 §mod_cdrs_chargingperiod_class]` corrected its own
275 /// definition of `PARKING_TIME` to remove. See [`Activity`].
276 #[must_use]
277 pub fn activity_throughout(
278 &self,
279 from: time::OffsetDateTime,
280 to: time::OffsetDateTime,
281 ) -> Option<Activity> {
282 if to <= from {
283 return None;
284 }
285 // No transition may land strictly inside the interval.
286 if self
287 .history
288 .iter()
289 .any(|change| change.at > from && change.at < to)
290 {
291 return None;
292 }
293 match self.state_at(from)? {
294 SessionState::Charging => Some(Activity::Charging),
295 SessionState::SuspendedByVehicle => Some(Activity::Parked),
296 SessionState::SuspendedByOperator => Some(Activity::Withheld),
297 SessionState::Pending | SessionState::Ended => None,
298 }
299 }
300
301 /// Whether the session was suspended for the whole of `[from, to)`, for
302 /// either reason.
303 ///
304 /// The protocol's question. **Which** reason is the one money turns on, and
305 /// that is [`Self::activity_throughout`].
306 #[must_use]
307 pub fn suspended_throughout(
308 &self,
309 from: time::OffsetDateTime,
310 to: time::OffsetDateTime,
311 ) -> bool {
312 matches!(
313 self.activity_throughout(from, to),
314 Some(Activity::Parked | Activity::Withheld)
315 )
316 }
317
318 /// Whether the session was charging for the whole of `[from, to)`.
319 ///
320 /// # Not the negation of [`Self::suspended_throughout`]
321 ///
322 /// There are four states and two of them are neither: a [`Pending`] session
323 /// is authorised with no energy moving, and an [`Ended`] one is over. Both
324 /// are "connected and not charging" — which is what `[AFIR Art. 5(4)]`'s
325 /// occupancy fee prices — and neither is suspended.
326 ///
327 /// This is the question `emob-cdr` asks of every period it prices, metered
328 /// or not: a period is charging when the operator's own record says it was,
329 /// and occupancy otherwise. Asking `!suspended_throughout` instead reads
330 /// "the session never said suspended" as "the vehicle was charging", which
331 /// is an absence standing in for a claim — and bills the minute a car sat
332 /// `EVConnected` before its charge began as charging time.
333 ///
334 /// [`Pending`]: SessionState::Pending
335 /// [`Ended`]: SessionState::Ended
336 #[must_use]
337 pub fn charging_throughout(
338 &self,
339 from: time::OffsetDateTime,
340 to: time::OffsetDateTime,
341 ) -> bool {
342 self.activity_throughout(from, to) == Some(Activity::Charging)
343 }
344
345 /// Move to a new state at an instant.
346 ///
347 /// # Errors
348 ///
349 /// [`SessionError::IllegalTransition`] when the protocol forbids it —
350 /// above all, anything at all after the session ended.
351 /// [`SessionError::TimeWentBackwards`] when the instant precedes the last
352 /// transition, because a history that is not ordered cannot be read as
353 /// intervals.
354 pub fn transition_to(
355 &mut self,
356 next: SessionState,
357 at: time::OffsetDateTime,
358 ) -> Result<(), SessionError> {
359 let current = self.state();
360 if !current.can_transition_to(next) {
361 return Err(SessionError::IllegalTransition {
362 from: current,
363 to: next,
364 });
365 }
366 let last = self.history[self.history.len() - 1].at;
367 if at < last {
368 return Err(SessionError::TimeWentBackwards { previous: last, at });
369 }
370 self.history.push(StateChange { state: next, at });
371 Ok(())
372 }
373
374 /// End the session.
375 ///
376 /// # Errors
377 ///
378 /// [`SessionError::IllegalTransition`] when it has already ended,
379 /// [`SessionError::EndsBeforeItStarts`] when the end precedes the start, or
380 /// [`SessionError::TimeWentBackwards`] when it precedes the last
381 /// transition.
382 pub fn end(&mut self, at: time::OffsetDateTime, reason: EndReason) -> Result<(), SessionError> {
383 if at < self.started_at {
384 return Err(SessionError::EndsBeforeItStarts {
385 started_at: self.started_at,
386 ended_at: at,
387 });
388 }
389 self.transition_to(SessionState::Ended, at)?;
390 self.ended_at = Some(at);
391 self.end_reason = Some(reason);
392 Ok(())
393 }
394
395 /// Attach a meter series.
396 ///
397 /// # Errors
398 ///
399 /// [`SessionError::AlreadyEnded`] once the session is final — a series
400 /// arriving after the end is either a late duplicate or a different
401 /// session, and guessing which is how energy gets double-billed.
402 /// [`SessionError::DuplicateDirection`] when a direction already has one.
403 pub fn attach_series(&mut self, series: MeterSeries) -> Result<(), SessionError> {
404 if self.state().is_final() {
405 return Err(SessionError::AlreadyEnded);
406 }
407 if self
408 .series
409 .iter()
410 .any(|s| s.direction() == series.direction())
411 {
412 return Err(SessionError::DuplicateDirection {
413 direction: series.direction(),
414 });
415 }
416 self.series.push(series);
417 Ok(())
418 }
419
420 /// The series for a direction.
421 #[must_use]
422 pub fn series_for(&self, direction: Direction) -> Option<&MeterSeries> {
423 self.series.iter().find(|s| s.direction() == direction)
424 }
425
426 /// Total energy in a direction.
427 ///
428 /// `None` when the session recorded nothing in that direction — which is
429 /// not the same as zero, and a caller that treats it as zero will invoice a
430 /// session it has no readings for.
431 #[must_use]
432 pub fn total(&self, direction: Direction) -> Option<Energy> {
433 self.series_for(direction).and_then(|s| s.total().ok())
434 }
435
436 /// How long the session lasted, once it has ended.
437 #[must_use]
438 pub fn duration(&self) -> Option<time::Duration> {
439 self.ended_at.map(|end| end - self.started_at)
440 }
441
442 /// The intervals in which this session says no energy flowed — every
443 /// stretch of its history in a state other than [`SessionState::Charging`],
444 /// as `[from, to)` pairs in time order.
445 ///
446 /// A `Pending` session is authorised with nothing flowing, a `Suspended`
447 /// one is held at zero, and an `Ended` one is over; none of them moves the
448 /// register. The last interval — the time after the end, or the current
449 /// state of a session still running — is open-ended.
450 ///
451 /// This is what [`Self::split`] hands the interpolation, so a gap between
452 /// two readings spreads its energy over the seconds the session was
453 /// charging rather than in a straight line across a suspension. A meter
454 /// cannot tell a taper from a pause; the state machine can, and it is the
455 /// operator's own record of which was which.
456 #[must_use]
457 pub fn idle_intervals(&self) -> Vec<(time::OffsetDateTime, time::OffsetDateTime)> {
458 let mut idle = Vec::new();
459 for (index, change) in self.history.iter().enumerate() {
460 if change.state == SessionState::Charging {
461 continue;
462 }
463 // The last entry — `Ended`, or whatever state a running session
464 // is in now — has no successor and is open-ended.
465 let to = self.history.get(index + 1).map_or(
466 time::OffsetDateTime::new_utc(time::Date::MAX, time::Time::MIDNIGHT),
467 |next| next.at,
468 );
469 if to > change.at {
470 idle.push((change.at, to));
471 }
472 }
473 idle
474 }
475
476 /// Split a direction's energy across the quarter hours it touched, cut also
477 /// wherever the session changed state, with the energy of every gap between
478 /// two readings spread over the time the session was **charging** in it.
479 ///
480 /// The input `mako-emob` needs to assign each quarter hour to the balance
481 /// group of the supplier the driver chose `[A6 §IV.1]` —
482 /// [`SessionSplit::market_series`] sums the slices of a quarter hour back
483 /// together for exactly that.
484 ///
485 /// # Why the state changes cut it
486 ///
487 /// A quarter hour is where the energy settles. It is not where the price
488 /// changes: `[AFIR Art. 5(4)]` prices time connected and **not** charging
489 /// separately from the energy, and a vehicle stops charging when it stops
490 /// charging rather than at `:15:00`. Split on the grid alone, the quarter
491 /// hour a charge finishes in carries one `charging` flag for fifteen
492 /// minutes that were not all the same — so up to a quarter hour of
493 /// occupancy is billed as charging, or the reverse, at every transition.
494 /// The session's own history says where the line falls, so it is drawn
495 /// there.
496 ///
497 /// # …and why the state changes shape the interpolation too
498 ///
499 /// The same history says where the register *could* have moved. A
500 /// transaction that opens `EVConnected`, starts charging thirty seconds
501 /// later and sends its next meter value at the quarter hour — the ordinary
502 /// OCPP 2.0.1 shape — has a register that did not move for those thirty
503 /// seconds, and a straight line from the opening reading attributes energy
504 /// to an interval the operator's own record calls suspended. So the split
505 /// is handed [`Self::idle_intervals`] and holds the register flat across
506 /// them; see [`crate::split::into_periods`].
507 ///
508 /// # Errors
509 ///
510 /// [`SessionError::NoSeries`] when the direction has no readings, or
511 /// [`SessionError::Split`] when the readings cannot be split.
512 pub fn split(&self, direction: Direction) -> Result<SessionSplit, SessionError> {
513 let series = self
514 .series_for(direction)
515 .ok_or(SessionError::NoSeries { direction })?;
516 let cuts: Vec<time::OffsetDateTime> = self.history.iter().map(|change| change.at).collect();
517 into_periods(series, &cuts, &self.idle_intervals()).map_err(SessionError::Split)
518 }
519}
520
521/// What can be wrong with a session.
522#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
523#[non_exhaustive]
524pub enum SessionError {
525 /// The protocol does not allow this transition.
526 #[error("a session cannot go from {from:?} to {to:?}")]
527 IllegalTransition {
528 /// Where it was.
529 from: SessionState,
530 /// Where it was asked to go.
531 to: SessionState,
532 },
533
534 /// Something was added after the session ended.
535 #[error("the session has ended; nothing further may be added to it")]
536 AlreadyEnded,
537
538 /// The end precedes the start.
539 #[error("the session ends at {ended_at} but starts at {started_at}")]
540 EndsBeforeItStarts {
541 /// When it started.
542 started_at: time::OffsetDateTime,
543 /// When it supposedly ended.
544 ended_at: time::OffsetDateTime,
545 },
546
547 /// A transition is dated before the one it follows.
548 #[error("a transition at {at} follows one at {previous}: the history must be ordered")]
549 TimeWentBackwards {
550 /// The last transition's instant.
551 previous: time::OffsetDateTime,
552 /// The instant offered.
553 at: time::OffsetDateTime,
554 },
555
556 /// A second series for a direction that already has one.
557 #[error("the session already has a {direction} series")]
558 DuplicateDirection {
559 /// Which direction.
560 direction: Direction,
561 },
562
563 /// The direction has no readings.
564 #[error("the session has no {direction} readings")]
565 NoSeries {
566 /// Which direction.
567 direction: Direction,
568 },
569
570 /// The readings could not be split across quarter hours.
571 #[error(transparent)]
572 Split(#[from] SplitError),
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578 use crate::auth::Authorization;
579 use crate::meter::{MeterReading, ReadingContext};
580 use rust_decimal::Decimal;
581 use std::str::FromStr;
582 use time::macros::datetime;
583
584 fn kwh(s: &str) -> Energy {
585 Energy::from_kwh(Decimal::from_str(s).unwrap()).unwrap()
586 }
587
588 fn at(minute: i64) -> time::OffsetDateTime {
589 datetime!(2026-01-02 10:00 +1) + time::Duration::minutes(minute)
590 }
591
592 fn session() -> Session {
593 Session::open(
594 "s-1".parse().unwrap(),
595 "DE*AB7*E840*6487".parse().unwrap(),
596 Authorization::ad_hoc(),
597 at(0),
598 )
599 }
600
601 fn import_series() -> MeterSeries {
602 MeterSeries::new(
603 Direction::Import,
604 vec![
605 MeterReading::new(
606 at(0),
607 kwh("100.000"),
608 Direction::Import,
609 ReadingContext::TransactionBegin,
610 ),
611 MeterReading::new(
612 at(30),
613 kwh("118.000"),
614 Direction::Import,
615 ReadingContext::TransactionEnd,
616 ),
617 ],
618 )
619 .unwrap()
620 }
621
622 #[test]
623 fn a_session_runs_its_normal_course() {
624 let mut s = session();
625 assert_eq!(s.state(), SessionState::Pending);
626 s.transition_to(SessionState::Charging, at(1)).unwrap();
627 s.transition_to(SessionState::SuspendedByVehicle, at(20))
628 .unwrap();
629 s.transition_to(SessionState::Charging, at(25)).unwrap();
630 s.attach_series(import_series()).unwrap();
631 s.end(at(30), EndReason::Local).unwrap();
632
633 assert_eq!(s.state(), SessionState::Ended);
634 assert_eq!(s.end_reason, Some(EndReason::Local));
635 assert_eq!(s.duration(), Some(time::Duration::minutes(30)));
636 assert_eq!(
637 s.total(Direction::Import).unwrap().to_string(),
638 "18.000 kWh"
639 );
640 assert_eq!(
641 s.history().len(),
642 5,
643 "pending, charging, suspended, charging, ended"
644 );
645 }
646
647 #[test]
648 fn the_history_answers_when_rather_than_only_what() {
649 // "Suspended" with no timestamp cannot say for how long, and the
650 // occupancy fee of AFIR Art. 5(4) is a price per minute of exactly
651 // that interval.
652 let mut s = session();
653 s.transition_to(SessionState::Charging, at(0)).unwrap();
654 s.transition_to(SessionState::SuspendedByVehicle, at(40))
655 .unwrap();
656 s.end(at(70), EndReason::Local).unwrap();
657
658 assert_eq!(s.state_at(at(10)), Some(SessionState::Charging));
659 assert_eq!(s.state_at(at(50)), Some(SessionState::SuspendedByVehicle));
660 assert_eq!(s.state_at(at(-1)), None, "before it started");
661
662 assert!(
663 s.suspended_throughout(at(45), at(60)),
664 "half an hour of occupancy, and the tariff may price it"
665 );
666 assert!(
667 !s.suspended_throughout(at(30), at(50)),
668 "charging for part of it"
669 );
670 assert!(
671 !s.suspended_throughout(at(60), at(80)),
672 "the session ended at 70"
673 );
674 }
675
676 #[test]
677 fn charging_throughout_is_not_the_negation_of_suspended_throughout() {
678 // Four states, two of which are neither — and the gap between the two
679 // questions is where an occupancy fee gets charged for time nobody
680 // measured. `emob-cdr` fills the unmetered part of a session's window
681 // from this, and it has to ask "did the record say charging" rather
682 // than "did it fail to say suspended".
683 let mut s = session();
684 s.transition_to(SessionState::Charging, at(20)).unwrap();
685 s.transition_to(SessionState::SuspendedByVehicle, at(40))
686 .unwrap();
687 s.end(at(70), EndReason::Local).unwrap();
688
689 // Pending: neither. Connected, authorised, no energy moving — which is
690 // exactly what the fee is for.
691 assert!(!s.charging_throughout(at(0), at(20)));
692 assert!(!s.suspended_throughout(at(0), at(20)));
693
694 assert!(s.charging_throughout(at(20), at(40)));
695 assert!(!s.suspended_throughout(at(20), at(40)));
696
697 assert!(!s.charging_throughout(at(45), at(60)));
698 assert!(s.suspended_throughout(at(45), at(60)));
699
700 // Ended: neither, again, and the car may still be in the bay.
701 assert!(!s.charging_throughout(at(75), at(90)));
702 assert!(!s.suspended_throughout(at(75), at(90)));
703
704 // A transition strictly inside disqualifies either answer: the interval
705 // held two states, so neither is true *throughout* it.
706 assert!(!s.charging_throughout(at(30), at(50)));
707 assert!(!s.suspended_throughout(at(30), at(50)));
708
709 // …and an empty or reversed interval is nothing at all.
710 assert!(!s.charging_throughout(at(30), at(30)));
711 assert!(!s.charging_throughout(at(30), at(20)));
712 }
713
714 #[test]
715 fn a_history_that_runs_backwards_is_refused() {
716 let mut s = session();
717 s.transition_to(SessionState::Charging, at(20)).unwrap();
718 assert!(matches!(
719 s.transition_to(SessionState::SuspendedByVehicle, at(10)),
720 Err(SessionError::TimeWentBackwards { .. })
721 ));
722 assert_eq!(s.state(), SessionState::Charging, "and nothing moved");
723 }
724
725 #[test]
726 fn nothing_follows_the_end() {
727 let mut s = session();
728 s.transition_to(SessionState::Charging, at(0)).unwrap();
729 s.end(at(30), EndReason::Local).unwrap();
730
731 // Not a second end…
732 assert!(matches!(
733 s.end(at(40), EndReason::Remote),
734 Err(SessionError::IllegalTransition { .. })
735 ));
736 // …not a resumption…
737 assert!(matches!(
738 s.transition_to(SessionState::Charging, at(40)),
739 Err(SessionError::IllegalTransition { .. })
740 ));
741 // …and not a late series, which is a duplicate or a different session.
742 assert!(matches!(
743 s.attach_series(import_series()),
744 Err(SessionError::AlreadyEnded)
745 ));
746 }
747
748 #[test]
749 fn a_session_cannot_go_back_to_pending() {
750 let mut s = session();
751 s.transition_to(SessionState::Charging, at(0)).unwrap();
752 assert!(matches!(
753 s.transition_to(SessionState::Pending, at(5)),
754 Err(SessionError::IllegalTransition { .. })
755 ));
756 }
757
758 #[test]
759 fn a_session_cannot_end_before_it_starts() {
760 let mut s = session();
761 assert!(matches!(
762 s.end(at(-5), EndReason::Local),
763 Err(SessionError::EndsBeforeItStarts { .. })
764 ));
765 assert_eq!(
766 s.state(),
767 SessionState::Pending,
768 "and the state is untouched"
769 );
770 }
771
772 #[test]
773 fn a_direction_gets_one_series() {
774 let mut s = session();
775 s.attach_series(import_series()).unwrap();
776 assert!(matches!(
777 s.attach_series(import_series()),
778 Err(SessionError::DuplicateDirection { .. })
779 ));
780 }
781
782 #[test]
783 fn a_bidirectional_session_keeps_its_two_registers_apart() {
784 let mut s = session();
785 s.attach_series(import_series()).unwrap();
786 s.attach_series(
787 MeterSeries::new(
788 Direction::Export,
789 vec![
790 MeterReading::new(
791 at(0),
792 kwh("0"),
793 Direction::Export,
794 ReadingContext::TransactionBegin,
795 ),
796 MeterReading::new(
797 at(30),
798 kwh("5"),
799 Direction::Export,
800 ReadingContext::TransactionEnd,
801 ),
802 ],
803 )
804 .unwrap(),
805 )
806 .unwrap();
807
808 assert_eq!(s.total(Direction::Import).unwrap(), kwh("18.000"));
809 assert_eq!(s.total(Direction::Export).unwrap(), kwh("5"));
810 // 18 and 5, never 13.
811 }
812
813 #[test]
814 fn no_readings_is_not_zero() {
815 let s = session();
816 assert_eq!(
817 s.total(Direction::Import),
818 None,
819 "a caller treating this as zero would invoice a session it has no readings for"
820 );
821 }
822
823 #[test]
824 fn the_idle_intervals_are_every_stretch_the_session_was_not_charging() {
825 let mut s = session();
826 s.transition_to(SessionState::Charging, at(1)).unwrap();
827 s.transition_to(SessionState::SuspendedByVehicle, at(20))
828 .unwrap();
829 s.transition_to(SessionState::Charging, at(25)).unwrap();
830 assert_eq!(
831 s.idle_intervals(),
832 vec![(at(0), at(1)), (at(20), at(25))],
833 "pending at the start, then the pause"
834 );
835 s.end(at(30), EndReason::Local).unwrap();
836 assert_eq!(
837 s.idle_intervals().last().map(|(from, _)| *from),
838 Some(at(30)),
839 "…and the time after the end, which no reading can fall in"
840 );
841
842 // A session that ends without ever charging is idle from start to end.
843 let mut never = session();
844 never.end(at(10), EndReason::Local).unwrap();
845 assert_eq!(never.idle_intervals()[0], (at(0), at(10)));
846 }
847
848 #[test]
849 fn the_split_holds_the_register_flat_while_the_session_says_nothing_flowed() {
850 // The ordinary OCPP 2.0.1 shape: `EVConnected` at the opening reading,
851 // charging thirty seconds later, the next meter value at the quarter
852 // hour. The thirty seconds carry no energy, whatever a straight line
853 // between the readings would have said.
854 let mut s = session();
855 s.transition_to(SessionState::SuspendedByVehicle, at(0))
856 .unwrap();
857 let charging_from = at(0) + time::Duration::seconds(30);
858 s.transition_to(SessionState::Charging, charging_from)
859 .unwrap();
860 s.attach_series(
861 MeterSeries::new(
862 Direction::Import,
863 vec![
864 MeterReading::new(
865 at(0),
866 kwh("100.000"),
867 Direction::Import,
868 ReadingContext::TransactionBegin,
869 ),
870 MeterReading::new(
871 at(15),
872 kwh("105.000"),
873 Direction::Import,
874 ReadingContext::SampleClock,
875 ),
876 ],
877 )
878 .unwrap(),
879 )
880 .unwrap();
881 let split = s.split(Direction::Import).unwrap();
882 assert_eq!(split.slots[0].to, charging_from);
883 assert!(split.slots[0].energy.is_zero());
884 assert_eq!(split.slots[1].energy, kwh("5.000"));
885 assert!(split.conserves());
886 }
887
888 #[test]
889 fn a_session_splits_into_quarter_hours() {
890 let mut s = session();
891 s.attach_series(import_series()).unwrap();
892 let split = s.split(Direction::Import).unwrap();
893 assert_eq!(split.slots.len(), 2);
894 assert!(split.conserves());
895
896 assert!(matches!(
897 s.split(Direction::Export),
898 Err(SessionError::NoSeries { .. })
899 ));
900 }
901
902 #[test]
903 fn the_transition_table_is_exhaustive_and_final_is_final() {
904 use SessionState::{Charging, Ended, Pending, SuspendedByOperator, SuspendedByVehicle};
905 for next in [
906 Pending,
907 Charging,
908 SuspendedByVehicle,
909 SuspendedByOperator,
910 Ended,
911 ] {
912 assert!(!Ended.can_transition_to(next), "nothing follows Ended");
913 }
914 assert!(Pending.can_transition_to(Charging));
915 assert!(Pending.can_transition_to(Ended));
916 assert!(!Charging.can_transition_to(Pending));
917 assert!(SuspendedByVehicle.can_transition_to(Charging));
918 assert!(SuspendedByOperator.can_transition_to(Charging));
919 // A car that fills while the point is curtailed moves from one
920 // suspension to the other, and both intervals are priced differently.
921 assert!(SuspendedByOperator.can_transition_to(SuspendedByVehicle));
922 assert!(SuspendedByVehicle.can_transition_to(SuspendedByOperator));
923 assert!(!SuspendedByVehicle.can_transition_to(Pending));
924 }
925
926 #[test]
927 fn the_two_suspensions_are_two_activities() {
928 use emob_core::Activity;
929 let mut s = session();
930 s.transition_to(SessionState::Charging, at(10)).unwrap();
931 s.transition_to(SessionState::SuspendedByOperator, at(20))
932 .unwrap();
933 s.transition_to(SessionState::SuspendedByVehicle, at(30))
934 .unwrap();
935 s.end(at(40), EndReason::Local).unwrap();
936
937 assert_eq!(
938 s.activity_throughout(at(10), at(20)),
939 Some(Activity::Charging)
940 );
941 assert_eq!(
942 s.activity_throughout(at(20), at(30)),
943 Some(Activity::Withheld),
944 "the operator withheld: no occupancy fee is owed for it"
945 );
946 assert_eq!(
947 s.activity_throughout(at(30), at(40)),
948 Some(Activity::Parked),
949 "the vehicle stopped asking: this is what [AFIR Art. 5(4)] prices"
950 );
951 // Both are "suspended" to the protocol and only one of them is an
952 // occupancy fee.
953 assert!(s.suspended_throughout(at(20), at(30)));
954 assert!(s.suspended_throughout(at(30), at(40)));
955 // An interval spanning a transition has no single answer.
956 assert_eq!(s.activity_throughout(at(15), at(35)), None);
957 }
958}