use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::time::Duration;
use super::{ChargingPlan, RateUnit, StationLimits, Target};
use crate::types::{DateTime, Decimal};
use crate::v2_1;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Mode {
ChargingOnly,
CentralSetpoint,
ExternalSetpoint,
ExternalLimits,
LocalLoadBalancing,
Idle,
}
impl Mode {
const ALL: [Self; 6] = [
Self::ChargingOnly,
Self::CentralSetpoint,
Self::ExternalSetpoint,
Self::ExternalLimits,
Self::LocalLoadBalancing,
Self::Idle,
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::ChargingOnly => "ChargingOnly",
Self::CentralSetpoint => "CentralSetpoint",
Self::ExternalSetpoint => "ExternalSetpoint",
Self::ExternalLimits => "ExternalLimits",
Self::LocalLoadBalancing => "LocalLoadBalancing",
Self::Idle => "Idle",
}
}
const fn bit(self) -> u8 {
1 << (self as u8)
}
const fn to_wire(self) -> v2_1::OperationMode {
match self {
Self::ChargingOnly => v2_1::OperationMode::ChargingOnly,
Self::CentralSetpoint => v2_1::OperationMode::CentralSetpoint,
Self::ExternalSetpoint => v2_1::OperationMode::ExternalSetpoint,
Self::ExternalLimits => v2_1::OperationMode::ExternalLimits,
Self::LocalLoadBalancing => v2_1::OperationMode::LocalLoadBalancing,
Self::Idle => v2_1::OperationMode::Idle,
}
}
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OperationModes(u8);
impl OperationModes {
pub const MANDATORY: Self = Self(Mode::ChargingOnly.bit() | Mode::CentralSetpoint.bit());
#[must_use]
pub fn parse(value: &str) -> Self {
let mut bits = 0;
for item in value.split(',').map(str::trim) {
if let Some(mode) = Mode::ALL.iter().find(|mode| mode.as_str() == item) {
bits |= mode.bit();
}
}
Self(bits)
}
#[must_use]
pub const fn contains(self, mode: Mode) -> bool {
self.0 & mode.bit() != 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct V2xStation {
pub limits: StationLimits,
pub modes: OperationModes,
}
impl V2xStation {
#[must_use]
pub const fn new(limits: StationLimits, modes: OperationModes) -> Self {
Self { limits, modes }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Setpoint(Decimal);
impl Setpoint {
pub const ZERO: Self = Self(Decimal::ZERO);
pub fn charge(rate: Decimal) -> Result<Self, V2xError> {
magnitude(rate).map(Self)
}
pub fn discharge(rate: Decimal) -> Result<Self, V2xError> {
magnitude(rate)
.and_then(|rate| rate.checked_neg().ok_or(V2xError::NegativeMagnitude))
.map(Self)
}
#[must_use]
pub const fn signed(self) -> Decimal {
self.0
}
}
fn magnitude(value: Decimal) -> Result<Decimal, V2xError> {
if value.signum() < 0 {
Err(V2xError::NegativeMagnitude)
} else {
Ok(value)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Operation {
mode: Mode,
setpoint: Option<Setpoint>,
limit: Option<Decimal>,
discharge_limit: Option<Decimal>,
evse_sleep: bool,
preconditioning: bool,
}
impl Operation {
const fn bare(mode: Mode) -> Self {
Self {
mode,
setpoint: None,
limit: None,
discharge_limit: None,
evse_sleep: false,
preconditioning: false,
}
}
pub fn charging_only(limit: Decimal) -> Result<Self, V2xError> {
Ok(Self {
limit: Some(magnitude(limit)?),
..Self::bare(Mode::ChargingOnly)
})
}
#[must_use]
pub const fn central_setpoint(setpoint: Setpoint) -> Self {
Self {
setpoint: Some(setpoint),
..Self::bare(Mode::CentralSetpoint)
}
}
#[must_use]
pub const fn external_setpoint() -> Self {
Self::bare(Mode::ExternalSetpoint)
}
#[must_use]
pub const fn external_limits() -> Self {
Self::bare(Mode::ExternalLimits)
}
#[must_use]
pub const fn local_load_balancing() -> Self {
Self::bare(Mode::LocalLoadBalancing)
}
#[must_use]
pub const fn idle() -> Self {
Self::bare(Mode::Idle)
}
pub fn charge_at_most(mut self, rate: Decimal) -> Result<Self, V2xError> {
self.allow(
"limit",
&[
Mode::CentralSetpoint,
Mode::ExternalSetpoint,
Mode::LocalLoadBalancing,
],
)?;
self.limit = Some(magnitude(rate)?);
self.check_range()
}
pub fn discharge_at_most(mut self, rate: Decimal) -> Result<Self, V2xError> {
self.allow(
"dischargeLimit",
&[
Mode::CentralSetpoint,
Mode::ExternalSetpoint,
Mode::LocalLoadBalancing,
],
)?;
self.discharge_limit = Some(
magnitude(rate)?
.checked_neg()
.ok_or(V2xError::NegativeMagnitude)?,
);
self.check_range()
}
pub fn sleep_evse(mut self) -> Result<Self, V2xError> {
self.allow("evseSleep", &[Mode::Idle])?;
self.evse_sleep = true;
Ok(self)
}
pub fn precondition(mut self) -> Result<Self, V2xError> {
self.allow("preconditioningRequest", &[Mode::Idle])?;
self.preconditioning = true;
Ok(self)
}
pub fn with_setpoint(mut self, setpoint: Setpoint) -> Result<Self, V2xError> {
self.allow("setpoint", &[Mode::CentralSetpoint])?;
self.setpoint = Some(setpoint);
self.check_range()
}
#[must_use]
pub const fn mode(&self) -> Mode {
self.mode
}
#[must_use]
pub fn setpoint(&self) -> Option<Decimal> {
self.setpoint.map(Setpoint::signed)
}
#[must_use]
pub const fn limit(&self) -> Option<Decimal> {
self.limit
}
#[must_use]
pub const fn discharge_limit(&self) -> Option<Decimal> {
self.discharge_limit
}
fn allow(&self, field: &'static str, modes: &[Mode]) -> Result<(), V2xError> {
if modes.contains(&self.mode) {
Ok(())
} else {
Err(V2xError::NotInMode {
field,
mode: self.mode,
})
}
}
fn check_range(self) -> Result<Self, V2xError> {
if let Some(setpoint) = self.setpoint() {
let above = self.limit.is_some_and(|limit| setpoint > limit);
let below = self.discharge_limit.is_some_and(|floor| setpoint < floor);
if above || below {
return Err(V2xError::SetpointOutsideLimits);
}
}
Ok(self)
}
fn to_period(self, start: i32) -> v2_1::ChargingSchedulePeriod {
let mut period = v2_1::ChargingSchedulePeriod::new(start);
period.operation_mode = Some(self.mode.to_wire());
period.setpoint = self.setpoint();
period.limit = self.limit;
period.discharge_limit = self.discharge_limit;
period.evse_sleep = self.evse_sleep.then_some(true);
period.preconditioning_request = self.preconditioning.then_some(true);
period
}
fn to_update(self) -> v2_1::ChargingScheduleUpdate {
let mut update = v2_1::ChargingScheduleUpdate::new();
update.setpoint = self.setpoint();
update.limit = self.limit;
update.discharge_limit = self.discharge_limit;
update
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum V2xError {
NegativeMagnitude,
SetpointOutsideLimits,
NotInMode {
field: &'static str,
mode: Mode,
},
UnsupportedMode(Mode),
TooManyPeriods {
periods: usize,
max: usize,
},
StackLevel {
requested: i32,
max: i32,
},
TxProfileOnEvseZero,
UnitNotAllowed(RateUnit),
Empty,
TooManySlots(usize),
BadDuration,
ModeChanged {
from: Mode,
to: Mode,
},
OutOfRange(&'static str),
}
impl fmt::Display for V2xError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NegativeMagnitude => {
f.write_str("a rate is a magnitude; say charge or discharge instead of a sign")
}
Self::SetpointOutsideLimits => {
f.write_str("the setpoint lies outside [dischargeLimit, limit] (V2X.05)")
}
Self::NotInMode { field, mode } => write!(f, "{mode} does not take {field}"),
Self::UnsupportedMode(mode) => {
write!(f, "the station does not support operation mode {mode}")
}
Self::TooManyPeriods { periods, max } => write!(
f,
"{periods} periods, the station allows {max}; setpoints are not merged"
),
Self::StackLevel { requested, max } => write!(
f,
"stack level {requested} is above the station's ProfileStackLevel {max}"
),
Self::TxProfileOnEvseZero => f.write_str("a TxProfile needs an EVSE above 0"),
Self::UnitNotAllowed(unit) => write!(f, "the station does not accept {unit}"),
Self::Empty => f.write_str("a V2X plan needs at least one slot"),
Self::TooManySlots(n) => write!(f, "{n} slots is more than a plan may hold"),
Self::BadDuration => f.write_str("a duration is outside 1 s ..= i32::MAX s"),
Self::ModeChanged { from, to } => write!(
f,
"an update cannot change {from} into {to}; send a new profile"
),
Self::OutOfRange(field) => write!(f, "{field} does not fit the wire's integer"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for V2xError {}
fn seconds(duration: Duration) -> Result<i32, V2xError> {
i32::try_from(duration.as_secs())
.ok()
.filter(|seconds| *seconds >= 1)
.ok_or(V2xError::BadDuration)
}
fn profile(
id: i32,
stack_level: i32,
target: Target,
kind: v2_1::ChargingProfileKind,
schedule: v2_1::ChargingSchedule,
station: &V2xStation,
) -> Result<v2_1::SetChargingProfileRequest, V2xError> {
if stack_level > station.limits.max_stack_level {
return Err(V2xError::StackLevel {
requested: stack_level,
max: station.limits.max_stack_level,
});
}
let unit = match schedule.charging_rate_unit {
v2_1::ChargingRateUnit::A => RateUnit::A,
_ => RateUnit::W,
};
let allowed = match unit {
RateUnit::A => station.limits.units.amperes,
RateUnit::W => station.limits.units.watts,
};
if !allowed {
return Err(V2xError::UnitNotAllowed(unit));
}
let (purpose, evse, transaction) = match target {
Target::Transaction {
evse_id,
transaction_id,
} => {
if evse_id == 0 {
return Err(V2xError::TxProfileOnEvseZero);
}
(
v2_1::ChargingProfilePurpose::TxProfile,
evse_id,
Some(transaction_id),
)
}
Target::EvseDefault { evse_id } => (
v2_1::ChargingProfilePurpose::TxDefaultProfile,
evse_id,
None,
),
};
let mut wire =
v2_1::ChargingProfile::new(id, stack_level, purpose, kind, alloc::vec![schedule]);
wire.transaction_id = transaction;
let evse = i32::try_from(evse).map_err(|_| V2xError::OutOfRange("evseId"))?;
Ok(v2_1::SetChargingProfileRequest::new(evse, wire))
}
const fn wire_unit(unit: RateUnit) -> v2_1::ChargingRateUnit {
match unit {
RateUnit::A => v2_1::ChargingRateUnit::A,
RateUnit::W => v2_1::ChargingRateUnit::W,
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct V2xPlan {
start: DateTime,
slot: i32,
operations: Vec<Operation>,
}
impl V2xPlan {
pub fn new(
start: DateTime,
slot: Duration,
operations: impl IntoIterator<Item = Operation>,
) -> Result<Self, V2xError> {
let operations: Vec<Operation> = operations.into_iter().collect();
if operations.is_empty() {
return Err(V2xError::Empty);
}
if operations.len() > ChargingPlan::MAX_SLOTS {
return Err(V2xError::TooManySlots(operations.len()));
}
let slot = seconds(slot)?;
let slots = i32::try_from(operations.len()).map_err(|_| V2xError::BadDuration)?;
slot.checked_mul(slots).ok_or(V2xError::BadDuration)?;
Ok(Self {
start,
slot,
operations,
})
}
#[must_use]
pub fn operations(&self) -> &[Operation] {
&self.operations
}
pub fn to_request(
&self,
id: i32,
stack_level: i32,
target: Target,
unit: RateUnit,
station: &V2xStation,
) -> Result<v2_1::SetChargingProfileRequest, V2xError> {
if let Some(op) = self
.operations
.iter()
.find(|op| !station.modes.contains(op.mode))
{
return Err(V2xError::UnsupportedMode(op.mode));
}
let mut periods: Vec<v2_1::ChargingSchedulePeriod> = Vec::new();
let mut previous: Option<&Operation> = None;
for (index, operation) in self.operations.iter().enumerate() {
if previous == Some(operation) {
continue;
}
previous = Some(operation);
let start = self.slot * i32::try_from(index).unwrap_or(i32::MAX);
periods.push(operation.to_period(start));
}
if periods.len() > station.limits.max_periods {
return Err(V2xError::TooManyPeriods {
periods: periods.len(),
max: station.limits.max_periods,
});
}
let mut schedule = v2_1::ChargingSchedule::new(id, wire_unit(unit), periods);
schedule.start_schedule = Some(self.start);
schedule.duration =
Some(self.slot * i32::try_from(self.operations.len()).unwrap_or(i32::MAX));
profile(
id,
stack_level,
target,
v2_1::ChargingProfileKind::Absolute,
schedule,
station,
)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct DynamicSetpoint {
id: i32,
stack_level: i32,
target: Target,
unit: RateUnit,
operation: Operation,
fallback: i32,
pull_every: Option<i32>,
}
impl DynamicSetpoint {
pub fn new(
id: i32,
target: Target,
unit: RateUnit,
operation: Operation,
fallback_after: Duration,
) -> Result<Self, V2xError> {
Ok(Self {
id,
stack_level: 0,
target,
unit,
operation,
fallback: seconds(fallback_after)?,
pull_every: None,
})
}
#[must_use]
pub const fn stack_level(mut self, stack_level: i32) -> Self {
self.stack_level = stack_level;
self
}
pub fn pull_every(mut self, interval: Duration) -> Result<Self, V2xError> {
self.pull_every = Some(seconds(interval)?);
Ok(self)
}
#[must_use]
pub const fn operation(&self) -> &Operation {
&self.operation
}
#[must_use]
pub const fn id(&self) -> i32 {
self.id
}
pub fn to_request(
&self,
station: &V2xStation,
) -> Result<v2_1::SetChargingProfileRequest, V2xError> {
if !station.modes.contains(self.operation.mode) {
return Err(V2xError::UnsupportedMode(self.operation.mode));
}
let mut schedule = v2_1::ChargingSchedule::new(
self.id,
wire_unit(self.unit),
alloc::vec![self.operation.to_period(0)],
);
schedule.duration = Some(self.fallback);
let mut request = profile(
self.id,
self.stack_level,
self.target.clone(),
v2_1::ChargingProfileKind::Dynamic,
schedule,
station,
)?;
request.charging_profile.dyn_update_interval = self.pull_every;
Ok(request)
}
pub fn update(
&mut self,
next: Operation,
) -> Result<v2_1::UpdateDynamicScheduleRequest, V2xError> {
if next.mode != self.operation.mode {
return Err(V2xError::ModeChanged {
from: self.operation.mode,
to: next.mode,
});
}
self.operation = next;
Ok(v2_1::UpdateDynamicScheduleRequest::new(
self.id,
next.to_update(),
))
}
pub fn update_setpoint(
&mut self,
setpoint: Setpoint,
) -> Result<v2_1::UpdateDynamicScheduleRequest, V2xError> {
let next = self.operation.with_setpoint(setpoint)?;
self.update(next)
}
#[must_use]
pub fn pull_response(&self) -> v2_1::PullDynamicScheduleUpdateResponse {
let mut response =
v2_1::PullDynamicScheduleUpdateResponse::new(v2_1::ChargingProfileStatus::Accepted);
response.schedule_update = Some(self.operation.to_update());
response
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct EvV2x {
pub requested: String,
pub bidirectional: bool,
pub max_charge: Option<Decimal>,
pub min_charge: Option<Decimal>,
pub max_discharge: Option<Decimal>,
pub min_discharge: Option<Decimal>,
pub target_energy: Option<Decimal>,
pub min_energy: Option<Decimal>,
pub max_energy: Option<Decimal>,
pub target_soc: Option<i32>,
pub departure: Option<DateTime>,
}
impl EvV2x {
#[must_use]
pub fn from_v2_1(needs: &v2_1::ChargingNeeds) -> Self {
let requested = needs.requested_energy_transfer.as_str();
let bidirectional = matches!(
requested,
"AC_BPT" | "AC_BPT_DER" | "DC_BPT" | "DC_ACDP_BPT"
);
let mut ev = Self {
requested: requested.into(),
bidirectional,
departure: needs.departure_time,
..Self::default()
};
if let Some(v2x) = &needs.v2x_charging_parameters {
ev.max_charge = total(
v2x.max_charge_power,
v2x.max_charge_power_l2,
v2x.max_charge_power_l3,
);
ev.min_charge = total(
v2x.min_charge_power,
v2x.min_charge_power_l2,
v2x.min_charge_power_l3,
);
ev.max_discharge = total(
v2x.max_discharge_power,
v2x.max_discharge_power_l2,
v2x.max_discharge_power_l3,
);
ev.min_discharge = total(
v2x.min_discharge_power,
v2x.min_discharge_power_l2,
v2x.min_discharge_power_l3,
);
ev.target_energy = v2x.ev_target_energy_request;
ev.min_energy = v2x.ev_min_energy_request;
ev.max_energy = v2x.ev_max_energy_request;
ev.target_soc = v2x.target_so_c;
}
ev
}
#[must_use]
pub fn clamp_watts(&self, setpoint: Setpoint) -> Setpoint {
let value = setpoint.signed();
if value.signum() >= 0 {
Setpoint(self.max_charge.map_or(value, |max| value.min(max)))
} else if !self.bidirectional {
Setpoint::ZERO
} else {
let floor = self.max_discharge.and_then(Decimal::checked_neg);
Setpoint(floor.map_or(value, |floor| value.max(floor)))
}
}
}
fn total(base: Option<Decimal>, l2: Option<Decimal>, l3: Option<Decimal>) -> Option<Decimal> {
if l2.is_none() && l3.is_none() {
return base;
}
[base, l2, l3]
.into_iter()
.flatten()
.try_fold(Decimal::ZERO, Decimal::checked_add)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::smart_charging::RateUnits;
fn w(value: i64) -> Decimal {
Decimal::from(value)
}
fn station(modes: &str) -> V2xStation {
V2xStation::new(
StationLimits::new(10, 3, RateUnits::BOTH),
OperationModes::parse(modes),
)
}
fn start() -> DateTime {
"2026-11-20T00:00:00Z".parse().unwrap()
}
const ALL: &str =
"ChargingOnly,CentralSetpoint,ExternalSetpoint,ExternalLimits,LocalLoadBalancing,Idle";
#[test]
fn signs_reach_the_wire_as_block_q_wants_them() {
let op = Operation::central_setpoint(Setpoint::discharge(w(5000)).unwrap())
.discharge_at_most(w(6000))
.unwrap()
.charge_at_most(w(11000))
.unwrap();
let period = op.to_period(0);
assert_eq!(period.setpoint, Some(w(-5000)));
assert_eq!(period.discharge_limit, Some(w(-6000)));
assert_eq!(period.limit, Some(w(11000)));
assert_eq!(
period.operation_mode,
Some(v2_1::OperationMode::CentralSetpoint)
);
assert_eq!(Setpoint::charge(w(3700)).unwrap().signed(), w(3700));
assert_eq!(Setpoint::discharge(w(-1)), Err(V2xError::NegativeMagnitude));
assert_eq!(
Operation::central_setpoint(Setpoint::ZERO).discharge_at_most(w(-5)),
Err(V2xError::NegativeMagnitude)
);
assert_eq!(Setpoint::charge(Decimal::ZERO).unwrap(), Setpoint::ZERO);
}
#[test]
fn a_setpoint_outside_its_limits_is_refused_v2x_05() {
let discharge = Operation::central_setpoint(Setpoint::discharge(w(7000)).unwrap());
assert_eq!(
discharge.discharge_at_most(w(6000)),
Err(V2xError::SetpointOutsideLimits)
);
let charge = Operation::central_setpoint(Setpoint::charge(w(1)).unwrap());
assert_eq!(
charge.charge_at_most(Decimal::ZERO),
Err(V2xError::SetpointOutsideLimits)
);
let bounded = Operation::central_setpoint(Setpoint::ZERO)
.charge_at_most(w(1000))
.unwrap();
assert_eq!(
bounded.with_setpoint(Setpoint::charge(w(2000)).unwrap()),
Err(V2xError::SetpointOutsideLimits)
);
}
#[test]
fn each_mode_takes_only_its_fields() {
let idle = Operation::idle()
.sleep_evse()
.unwrap()
.precondition()
.unwrap();
let period = idle.to_period(0);
assert_eq!(
(
period.limit,
period.discharge_limit,
period.setpoint,
period.setpoint_reactive
),
(None, None, None, None),
"Q10.FR.01"
);
assert_eq!(
(period.evse_sleep, period.preconditioning_request),
(Some(true), Some(true))
);
assert!(matches!(
Operation::idle().charge_at_most(w(1)),
Err(V2xError::NotInMode { field: "limit", .. })
));
assert!(matches!(
Operation::external_limits().discharge_at_most(w(1)),
Err(V2xError::NotInMode { .. })
));
assert!(matches!(
Operation::charging_only(w(1)).unwrap().sleep_evse(),
Err(V2xError::NotInMode {
field: "evseSleep",
..
})
));
assert!(matches!(
Operation::local_load_balancing().with_setpoint(Setpoint::ZERO),
Err(V2xError::NotInMode {
field: "setpoint",
..
})
));
assert!(
Operation::local_load_balancing()
.charge_at_most(w(9000))
.is_ok(),
"Q09.FR.05"
);
let charging = Operation::charging_only(w(11000)).unwrap().to_period(0);
assert_eq!((charging.limit, charging.setpoint), (Some(w(11000)), None));
}
#[test]
#[allow(clippy::too_many_lines)]
fn a_plan_merges_neighbours_and_honours_the_station() {
let charge = Operation::charging_only(w(11000)).unwrap();
let plan = V2xPlan::new(
start(),
Duration::from_secs(900),
[charge, charge, Operation::idle(), charge],
)
.unwrap();
let request = plan
.to_request(
1,
1,
Target::transaction(1, "tx"),
RateUnit::W,
&station(ALL),
)
.unwrap();
let profile = &request.charging_profile;
let starts: Vec<i32> = profile.charging_schedule[0]
.charging_schedule_period
.iter()
.map(|p| p.start_period)
.collect();
assert_eq!(starts, [0, 1800, 2700]);
assert_eq!(profile.charging_schedule[0].duration, Some(3600));
assert_eq!(
profile.charging_profile_kind,
v2_1::ChargingProfileKind::Absolute
);
assert_eq!(profile.transaction_id.as_deref(), Some("tx"));
assert_eq!(request.evse_id, 1);
let llb = V2xPlan::new(
start(),
Duration::from_secs(900),
[Operation::local_load_balancing()],
)
.unwrap();
assert_eq!(
llb.to_request(
1,
1,
Target::transaction(1, "tx"),
RateUnit::W,
&station("ChargingOnly,CentralSetpoint")
),
Err(V2xError::UnsupportedMode(Mode::LocalLoadBalancing))
);
let many = V2xPlan::new(
start(),
Duration::from_secs(60),
(0..11).map(|n| Operation::charging_only(w(1000 + n)).unwrap()),
)
.unwrap();
assert_eq!(
many.to_request(
1,
1,
Target::transaction(1, "tx"),
RateUnit::W,
&station(ALL)
),
Err(V2xError::TooManyPeriods {
periods: 11,
max: 10
})
);
let one = V2xPlan::new(start(), Duration::from_secs(60), [charge]).unwrap();
assert_eq!(
one.to_request(
1,
4,
Target::transaction(1, "tx"),
RateUnit::W,
&station(ALL)
),
Err(V2xError::StackLevel {
requested: 4,
max: 3
})
);
let watts_only = V2xStation::new(
StationLimits::new(10, 3, RateUnits::parse_v2("W")),
OperationModes::MANDATORY,
);
assert_eq!(
one.to_request(1, 1, Target::transaction(1, "tx"), RateUnit::A, &watts_only),
Err(V2xError::UnitNotAllowed(RateUnit::A))
);
assert_eq!(
one.to_request(
1,
1,
Target::transaction(0, "tx"),
RateUnit::W,
&station(ALL)
),
Err(V2xError::TxProfileOnEvseZero)
);
assert_eq!(
V2xPlan::new(start(), Duration::from_secs(60), []),
Err(V2xError::Empty)
);
}
#[test]
fn operation_modes_read_the_member_list() {
let modes = OperationModes::parse(
"ChargingOnly, CentralSetpoint,CentralFrequency,LocalLoadBalancing",
);
assert!(modes.contains(Mode::LocalLoadBalancing));
assert!(!modes.contains(Mode::Idle));
assert!(OperationModes::MANDATORY.contains(Mode::CentralSetpoint));
assert!(!OperationModes::MANDATORY.contains(Mode::Idle));
}
#[test]
fn a_dynamic_setpoint_has_a_fallback_and_one_period() {
let mut follow = DynamicSetpoint::new(
10,
Target::transaction(1, "tx"),
RateUnit::W,
Operation::central_setpoint(Setpoint::ZERO)
.charge_at_most(w(11000))
.unwrap(),
Duration::from_secs(30),
)
.unwrap()
.stack_level(2)
.pull_every(Duration::from_secs(60))
.unwrap();
let request = follow.to_request(&station(ALL)).unwrap();
let profile = &request.charging_profile;
assert_eq!(
profile.charging_profile_kind,
v2_1::ChargingProfileKind::Dynamic
);
assert_eq!(profile.charging_schedule.len(), 1, "K28.FR.01");
assert_eq!(
profile.charging_schedule[0].charging_schedule_period.len(),
1
);
assert_eq!(
profile.charging_schedule[0].charging_schedule_period[0].start_period, 0,
"K28.FR.02"
);
assert_eq!(profile.charging_schedule[0].duration, Some(30), "K28.FR.13");
assert_eq!(profile.dyn_update_interval, Some(60));
assert_eq!(profile.stack_level, 2);
let update = follow
.update_setpoint(Setpoint::charge(w(2000)).unwrap())
.unwrap();
assert_eq!(update.charging_profile_id, 10);
assert_eq!(update.schedule_update.setpoint, Some(w(2000)));
assert_eq!(update.schedule_update.limit, Some(w(11000)));
assert_eq!(
follow.update_setpoint(Setpoint::charge(w(12000)).unwrap()),
Err(V2xError::SetpointOutsideLimits)
);
assert_eq!(
follow.operation().setpoint(),
Some(w(2000)),
"a refused update changes nothing"
);
assert_eq!(
follow.update(Operation::idle()),
Err(V2xError::ModeChanged {
from: Mode::CentralSetpoint,
to: Mode::Idle
})
);
let pull = follow.pull_response();
assert_eq!(pull.status, v2_1::ChargingProfileStatus::Accepted);
assert_eq!(pull.schedule_update.unwrap().setpoint, Some(w(2000)));
assert_eq!(
DynamicSetpoint::new(
1,
Target::transaction(1, "tx"),
RateUnit::W,
Operation::idle(),
Duration::ZERO
),
Err(V2xError::BadDuration)
);
let plain = DynamicSetpoint::new(
1,
Target::transaction(1, "tx"),
RateUnit::W,
Operation::idle(),
Duration::from_secs(5),
)
.unwrap()
.to_request(&station(ALL))
.unwrap();
assert_eq!(
plain.charging_profile.dyn_update_interval, None,
"K28.FR.04 only when asked"
);
}
fn needs(json: &str) -> v2_1::ChargingNeeds {
serde_json::from_str(json).unwrap()
}
#[test]
fn the_ev_reads_in_magnitudes_and_sums_its_phases() {
let ev = EvV2x::from_v2_1(&needs(
r#"{"requestedEnergyTransfer":"AC_BPT","v2xChargingParameters":{
"maxChargePower":11000,"maxDischargePower":2000,"maxDischargePower_L2":2000,
"maxDischargePower_L3":2000,"evTargetEnergyRequest":20000,"targetSoC":80}}"#,
));
assert!(ev.bidirectional);
assert_eq!(ev.max_charge, Some(w(11000)));
assert_eq!(
ev.max_discharge,
Some(w(6000)),
"the plain field is L1 when L2/L3 are given"
);
assert_eq!(ev.target_energy, Some(w(20000)));
assert_eq!(ev.target_soc, Some(80));
assert_eq!(
ev.clamp_watts(Setpoint::charge(w(22000)).unwrap()),
Setpoint::charge(w(11000)).unwrap()
);
assert_eq!(
ev.clamp_watts(Setpoint::discharge(w(9000)).unwrap()),
Setpoint::discharge(w(6000)).unwrap()
);
let plain = EvV2x::from_v2_1(&needs(r#"{"requestedEnergyTransfer":"AC_three_phase"}"#));
assert!(!plain.bidirectional);
assert_eq!(
plain.clamp_watts(Setpoint::discharge(w(1000)).unwrap()),
Setpoint::ZERO
);
}
}