use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use crate::types::DateTime;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum TxPoint {
ParkingBayOccupancy,
EVConnected,
Authorized,
DataSigned,
PowerPathClosed,
EnergyTransfer,
}
impl TxPoint {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
TxPoint::ParkingBayOccupancy => "ParkingBayOccupancy",
TxPoint::EVConnected => "EVConnected",
TxPoint::Authorized => "Authorized",
TxPoint::DataSigned => "DataSigned",
TxPoint::PowerPathClosed => "PowerPathClosed",
TxPoint::EnergyTransfer => "EnergyTransfer",
}
}
#[must_use]
pub fn from_wire(value: &str) -> Option<Self> {
Some(match value {
"ParkingBayOccupancy" => TxPoint::ParkingBayOccupancy,
"EVConnected" => TxPoint::EVConnected,
"Authorized" => TxPoint::Authorized,
"DataSigned" => TxPoint::DataSigned,
"PowerPathClosed" => TxPoint::PowerPathClosed,
"EnergyTransfer" => TxPoint::EnergyTransfer,
_ => return None,
})
}
#[must_use]
pub fn parse_list(value: &str) -> BTreeSet<TxPoint> {
value
.split(',')
.filter_map(|item| TxPoint::from_wire(item.trim()))
.collect()
}
}
impl fmt::Display for TxPoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[allow(clippy::struct_excessive_bools)]
pub struct Conditions {
pub parking_bay_occupied: bool,
pub ev_connected: bool,
pub authorized: bool,
pub data_signed: bool,
pub energy_transfer: bool,
}
impl Conditions {
#[must_use]
pub const fn holds(&self, point: TxPoint) -> bool {
match point {
TxPoint::ParkingBayOccupancy => self.parking_bay_occupied,
TxPoint::EVConnected => self.ev_connected,
TxPoint::Authorized => self.authorized,
TxPoint::DataSigned => self.data_signed,
TxPoint::PowerPathClosed => self.authorized && self.ev_connected,
TxPoint::EnergyTransfer => self.energy_transfer,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TxEvent {
Started {
transaction_id: String,
seq_no: i32,
trigger: &'static str,
timestamp: DateTime,
},
Updated {
transaction_id: String,
seq_no: i32,
trigger: &'static str,
timestamp: DateTime,
},
Ended {
transaction_id: String,
seq_no: i32,
trigger: &'static str,
stopped_reason: &'static str,
timestamp: DateTime,
},
}
impl TxEvent {
#[must_use]
pub const fn seq_no(&self) -> i32 {
match self {
TxEvent::Started { seq_no, .. }
| TxEvent::Updated { seq_no, .. }
| TxEvent::Ended { seq_no, .. } => *seq_no,
}
}
#[must_use]
pub fn transaction_id(&self) -> &str {
match self {
TxEvent::Started { transaction_id, .. }
| TxEvent::Updated { transaction_id, .. }
| TxEvent::Ended { transaction_id, .. } => transaction_id,
}
}
}
pub trait TransactionIds: Send {
fn next(&mut self) -> String;
}
#[cfg(feature = "getrandom")]
#[derive(Clone, Copy, Debug, Default)]
pub struct RandomTransactionIds {
fallback: u64,
}
#[cfg(feature = "getrandom")]
impl RandomTransactionIds {
#[must_use]
pub fn new() -> Self {
Self { fallback: 0 }
}
}
#[cfg(feature = "getrandom")]
impl TransactionIds for RandomTransactionIds {
fn next(&mut self) -> String {
if let Some(id) = crate::types::uuid_v4() {
return id;
}
self.fallback += 1;
alloc::format!("degraded-{}", self.fallback)
}
}
#[derive(Clone, Debug)]
pub struct CounterTransactionIds {
prefix: String,
next: u64,
}
impl CounterTransactionIds {
#[must_use]
pub fn new(prefix: impl Into<String>) -> Self {
Self {
prefix: prefix.into(),
next: 1,
}
}
}
impl TransactionIds for CounterTransactionIds {
fn next(&mut self) -> String {
let id = alloc::format!("{}{}", self.prefix, self.next);
self.next += 1;
id
}
}
pub struct TransactionMachine {
start_points: BTreeSet<TxPoint>,
stop_points: BTreeSet<TxPoint>,
ids: alloc::boxed::Box<dyn TransactionIds>,
conditions: Conditions,
active: Option<Active>,
}
struct Active {
id: String,
next_seq: i32,
}
impl fmt::Debug for TransactionMachine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TransactionMachine")
.field("start_points", &self.start_points)
.field("stop_points", &self.stop_points)
.field("conditions", &self.conditions)
.field(
"transaction",
&self.active.as_ref().map(|active| &active.id),
)
.finish_non_exhaustive()
}
}
impl TransactionMachine {
#[must_use]
pub fn new(
start_points: BTreeSet<TxPoint>,
stop_points: BTreeSet<TxPoint>,
ids: alloc::boxed::Box<dyn TransactionIds>,
) -> Self {
Self {
start_points,
stop_points,
ids,
conditions: Conditions::default(),
active: None,
}
}
#[must_use]
pub fn with_defaults(ids: alloc::boxed::Box<dyn TransactionIds>) -> Self {
Self::new(
BTreeSet::from([TxPoint::PowerPathClosed]),
BTreeSet::from([TxPoint::EVConnected, TxPoint::Authorized]),
ids,
)
}
#[must_use]
pub fn transaction_id(&self) -> Option<&str> {
self.active.as_ref().map(|active| active.id.as_str())
}
#[must_use]
pub const fn conditions(&self) -> Conditions {
self.conditions
}
pub fn observe(&mut self, conditions: Conditions, now: DateTime) -> Vec<TxEvent> {
let previous = self.conditions;
self.conditions = conditions;
let mut events = Vec::new();
match &mut self.active {
None => {
let started = self
.start_points
.iter()
.copied()
.find(|point| !previous.holds(*point) && conditions.holds(*point));
if started.is_some() {
let id = self.ids.next();
events.push(TxEvent::Started {
transaction_id: id.clone(),
seq_no: 0,
trigger: trigger_for(previous, conditions),
timestamp: now,
});
self.active = Some(Active { id, next_seq: 1 });
}
}
Some(active) => {
let stopped = self
.stop_points
.iter()
.copied()
.filter(|point| *point != TxPoint::DataSigned)
.find(|point| previous.holds(*point) && !conditions.holds(*point));
if let Some(point) = stopped {
let seq_no = active.next_seq;
let id = active.id.clone();
self.active = None;
events.push(TxEvent::Ended {
transaction_id: id,
seq_no,
trigger: trigger_for(previous, conditions),
stopped_reason: stopped_reason(point, previous, conditions),
timestamp: now,
});
} else if previous != conditions {
let seq_no = active.next_seq;
active.next_seq += 1;
events.push(TxEvent::Updated {
transaction_id: active.id.clone(),
seq_no,
trigger: trigger_for(previous, conditions),
timestamp: now,
});
}
}
}
events
}
pub fn update(&mut self, trigger: &'static str, now: DateTime) -> Option<TxEvent> {
let active = self.active.as_mut()?;
let seq_no = active.next_seq;
active.next_seq += 1;
Some(TxEvent::Updated {
transaction_id: active.id.clone(),
seq_no,
trigger,
timestamp: now,
})
}
pub fn stop_locally(&mut self, now: DateTime) -> Option<TxEvent> {
let active = self.active.take()?;
Some(TxEvent::Ended {
transaction_id: active.id,
seq_no: active.next_seq,
trigger: "StopAuthorized",
stopped_reason: "Local",
timestamp: now,
})
}
pub fn abort(&mut self, stopped_reason: &'static str, now: DateTime) -> Option<TxEvent> {
let active = self.active.take()?;
Some(TxEvent::Ended {
transaction_id: active.id,
seq_no: active.next_seq,
trigger: "AbnormalCondition",
stopped_reason,
timestamp: now,
})
}
pub fn resume(
&mut self,
transaction_id: impl Into<String>,
next_seq: i32,
conditions: Conditions,
) {
self.conditions = conditions;
self.active = Some(Active {
id: transaction_id.into(),
next_seq,
});
}
}
fn trigger_for(before: Conditions, after: Conditions) -> &'static str {
if before.authorized != after.authorized {
if after.authorized {
"Authorized"
} else {
"Deauthorized"
}
} else if before.ev_connected != after.ev_connected {
if after.ev_connected {
"CablePluggedIn"
} else {
"EVCommunicationLost"
}
} else if before.parking_bay_occupied != after.parking_bay_occupied {
if after.parking_bay_occupied {
"EVDetected"
} else {
"EVDeparted"
}
} else if before.data_signed != after.data_signed && after.data_signed {
"SignedDataReceived"
} else if before.energy_transfer != after.energy_transfer {
"ChargingStateChanged"
} else {
"Trigger"
}
}
fn stopped_reason(point: TxPoint, before: Conditions, after: Conditions) -> &'static str {
match point {
TxPoint::EVConnected | TxPoint::ParkingBayOccupancy => "EVDisconnected",
TxPoint::Authorized => "DeAuthorized",
TxPoint::PowerPathClosed => {
if before.ev_connected && !after.ev_connected {
"EVDisconnected"
} else {
"DeAuthorized"
}
}
TxPoint::EnergyTransfer => "StoppedByEV",
TxPoint::DataSigned => "Other",
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::boxed::Box;
fn now() -> DateTime {
DateTime::parse("2024-01-01T00:00:00Z").unwrap()
}
fn machine() -> TransactionMachine {
TransactionMachine::with_defaults(Box::new(CounterTransactionIds::new("tx-")))
}
fn points(list: &[TxPoint]) -> BTreeSet<TxPoint> {
list.iter().copied().collect()
}
#[test]
fn the_first_start_point_to_arrive_starts_the_transaction_e01_fr_02() {
let mut machine = TransactionMachine::new(
points(&[TxPoint::EVConnected, TxPoint::Authorized]),
points(&[TxPoint::EVConnected]),
Box::new(CounterTransactionIds::new("tx-")),
);
let plugged = Conditions {
ev_connected: true,
..Conditions::default()
};
let events = machine.observe(plugged, now());
assert!(
matches!(
&events[0],
TxEvent::Started {
seq_no: 0,
trigger: "CablePluggedIn",
..
}
),
"{events:?}"
);
let authorized = Conditions {
authorized: true,
..plugged
};
let events = machine.observe(authorized, now());
assert!(
matches!(
&events[0],
TxEvent::Updated {
seq_no: 1,
trigger: "Authorized",
..
}
),
"{events:?}"
);
}
#[test]
fn a_drivers_stop_at_the_station_is_local_e07_fr_05() {
let mut machine = machine();
let charging = Conditions {
ev_connected: true,
authorized: true,
..Conditions::default()
};
let _ = machine.observe(charging, now());
assert!(matches!(
machine.stop_locally(now()),
Some(TxEvent::Ended {
trigger: "StopAuthorized",
stopped_reason: "Local",
..
})
));
assert!(
machine.stop_locally(now()).is_none(),
"nothing left to stop"
);
}
#[test]
fn data_signed_is_not_a_stop_point() {
let mut machine = TransactionMachine::new(
points(&[TxPoint::DataSigned]),
points(&[TxPoint::DataSigned, TxPoint::EVConnected]),
Box::new(CounterTransactionIds::new("tx-")),
);
let signed = Conditions {
ev_connected: true,
data_signed: true,
..Conditions::default()
};
assert!(matches!(
machine.observe(signed, now())[0],
TxEvent::Started { .. }
));
let unsigned = Conditions {
data_signed: false,
..signed
};
assert!(matches!(
machine.observe(unsigned, now())[0],
TxEvent::Updated { .. }
));
let unplugged = Conditions::default();
assert!(matches!(
machine.observe(unplugged, now())[0],
TxEvent::Ended {
stopped_reason: "EVDisconnected",
..
}
));
}
#[test]
fn power_path_closed_is_derived_from_authorization_and_connection_e01_fr_05() {
let mut machine = machine();
let plugged = Conditions {
ev_connected: true,
..Conditions::default()
};
assert!(
machine.observe(plugged, now()).is_empty(),
"a cable alone does not close the power path"
);
let authorized = Conditions {
authorized: true,
..plugged
};
let events = machine.observe(authorized, now());
assert!(
matches!(&events[0], TxEvent::Started { seq_no: 0, .. }),
"{events:?}"
);
let deauthorized = Conditions {
authorized: false,
..authorized
};
let events = machine.observe(deauthorized, now());
assert!(
matches!(
&events[0],
TxEvent::Ended {
stopped_reason: "DeAuthorized",
trigger: "Deauthorized",
..
}
),
"{events:?}"
);
}
#[test]
fn a_stop_point_that_never_held_cannot_end_the_transaction_e06_fr_02() {
let mut machine = TransactionMachine::new(
points(&[TxPoint::ParkingBayOccupancy]),
points(&[TxPoint::EVConnected]),
Box::new(CounterTransactionIds::new("tx-")),
);
let occupied = Conditions {
parking_bay_occupied: true,
..Conditions::default()
};
assert!(matches!(
machine.observe(occupied, now())[0],
TxEvent::Started { .. }
));
let empty = Conditions::default();
let events = machine.observe(empty, now());
assert!(
!events
.iter()
.any(|event| matches!(event, TxEvent::Ended { .. })),
"the transaction must remain open: {events:?}"
);
assert!(machine.transaction_id().is_some());
}
#[test]
fn a_finished_transaction_does_not_restart_from_a_condition_that_never_changed() {
let mut machine = TransactionMachine::new(
points(&[TxPoint::EVConnected]),
points(&[TxPoint::Authorized]),
Box::new(CounterTransactionIds::new("tx-")),
);
let plugged = Conditions {
ev_connected: true,
..Conditions::default()
};
assert!(matches!(
machine.observe(plugged, now())[0],
TxEvent::Started { .. }
));
let authorized = Conditions {
authorized: true,
..plugged
};
machine.observe(authorized, now());
let events = machine.observe(plugged, now());
assert!(matches!(&events[0], TxEvent::Ended { .. }), "{events:?}");
assert!(machine.transaction_id().is_none());
let actions = machine.observe(plugged, now());
assert!(actions.is_empty(), "{actions:?}");
machine.observe(Conditions::default(), now());
assert!(matches!(
machine.observe(plugged, now())[0],
TxEvent::Started { .. }
));
}
#[test]
fn sequence_numbers_are_strictly_increasing_within_a_transaction() {
let mut machine = machine();
let start = Conditions {
ev_connected: true,
authorized: true,
..Conditions::default()
};
let events = machine.observe(start, now());
assert_eq!(events[0].seq_no(), 0);
assert_eq!(
machine
.update("MeterValuePeriodic", now())
.unwrap()
.seq_no(),
1
);
assert_eq!(
machine
.update("MeterValuePeriodic", now())
.unwrap()
.seq_no(),
2
);
let unplugged = Conditions {
ev_connected: false,
..start
};
let events = machine.observe(unplugged, now());
assert!(
matches!(
&events[0],
TxEvent::Ended {
seq_no: 3,
stopped_reason: "EVDisconnected",
..
}
),
"{events:?}"
);
assert_eq!(machine.transaction_id(), None);
assert!(machine.update("MeterValuePeriodic", now()).is_none());
}
#[test]
fn a_reboot_resumes_the_sequence_and_the_conditions_it_left_behind() {
let mut machine = machine();
let live = Conditions {
ev_connected: true,
authorized: true,
..Conditions::default()
};
machine.resume("tx-7", 12, live);
assert_eq!(machine.transaction_id(), Some("tx-7"));
let event = machine.update("MeterValuePeriodic", now()).unwrap();
assert_eq!(event.seq_no(), 12);
assert_eq!(event.transaction_id(), "tx-7");
let events = machine.observe(
Conditions {
ev_connected: false,
..live
},
now(),
);
assert!(matches!(&events[0], TxEvent::Ended { .. }), "{events:?}");
}
#[test]
fn an_abort_ends_the_transaction_with_its_own_reason() {
let mut machine = machine();
machine.observe(
Conditions {
ev_connected: true,
authorized: true,
..Conditions::default()
},
now(),
);
let event = machine.abort("Remote", now()).unwrap();
assert!(
matches!(
event,
TxEvent::Ended {
stopped_reason: "Remote",
trigger: "AbnormalCondition",
..
}
),
"{event:?}"
);
assert!(machine.abort("Remote", now()).is_none());
}
#[test]
fn tx_points_parse_from_the_device_model_member_list() {
let points = TxPoint::parse_list("Authorized, PowerPathClosed");
assert_eq!(
points,
BTreeSet::from([TxPoint::Authorized, TxPoint::PowerPathClosed])
);
}
#[cfg(feature = "v2_1")]
#[test]
fn every_trigger_and_reason_is_a_defined_enumeration_value() {
use crate::v2_1::{Reason, TriggerReason};
let all = [
Conditions::default(),
Conditions {
parking_bay_occupied: true,
..Conditions::default()
},
Conditions {
ev_connected: true,
..Conditions::default()
},
Conditions {
ev_connected: true,
authorized: true,
..Conditions::default()
},
Conditions {
data_signed: true,
..Conditions::default()
},
Conditions {
energy_transfer: true,
..Conditions::default()
},
];
for before in all {
for after in all {
let trigger = trigger_for(before, after);
assert!(
!matches!(
serde_json::from_str::<TriggerReason>(&alloc::format!("\"{trigger}\"")),
Ok(TriggerReason::UnknownValue(_)) | Err(_)
),
"{trigger:?} is not a TriggerReasonEnumType value"
);
for point in [
TxPoint::ParkingBayOccupancy,
TxPoint::EVConnected,
TxPoint::Authorized,
TxPoint::DataSigned,
TxPoint::PowerPathClosed,
TxPoint::EnergyTransfer,
] {
let reason = stopped_reason(point, before, after);
assert!(
!matches!(
serde_json::from_str::<Reason>(&alloc::format!("\"{reason}\"")),
Ok(Reason::UnknownValue(_)) | Err(_)
),
"{reason:?} is not a ReasonEnumType value"
);
}
}
}
assert!(!matches!(
serde_json::from_str::<TriggerReason>("\"AbnormalCondition\""),
Ok(TriggerReason::UnknownValue(_)) | Err(_)
));
}
}