use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::time::Duration;
use super::{
CONVERSION_SCALE, DEFAULT_PHASES, Period, Profile, ProfileKind, Purpose, RateUnit, Schedule,
Supply,
};
use crate::types::{DateTime, Decimal};
const UNBOUNDED: Decimal = Decimal::new(i64::MAX, 0);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ceiling {
pub limit: Decimal,
pub unit: RateUnit,
pub phases: Option<u8>,
}
impl Ceiling {
#[must_use]
pub const fn watts(limit: Decimal) -> Self {
Self {
limit,
unit: RateUnit::W,
phases: None,
}
}
#[must_use]
pub const fn amperes(limit: Decimal) -> Self {
Self {
limit,
unit: RateUnit::A,
phases: None,
}
}
#[must_use]
pub const fn phases(mut self, phases: u8) -> Self {
self.phases = Some(phases);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RateUnits {
pub amperes: bool,
pub watts: bool,
}
impl RateUnits {
pub const BOTH: Self = Self {
amperes: true,
watts: true,
};
#[must_use]
pub fn parse_v16(value: &str) -> Self {
Self::parse(value, "Current", "Power")
}
#[must_use]
pub fn parse_v2(value: &str) -> Self {
Self::parse(value, "A", "W")
}
fn parse(value: &str, amperes: &str, watts: &str) -> Self {
let mut units = Self {
amperes: false,
watts: false,
};
for item in value.split(',').map(str::trim) {
units.amperes |= item.eq_ignore_ascii_case(amperes);
units.watts |= item.eq_ignore_ascii_case(watts);
}
units
}
const fn allows(self, unit: RateUnit) -> bool {
match unit {
RateUnit::A => self.amperes,
RateUnit::W => self.watts,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StationLimits {
pub max_periods: usize,
pub max_stack_level: i32,
pub units: RateUnits,
}
impl StationLimits {
#[must_use]
pub const fn new(max_periods: usize, max_stack_level: i32, units: RateUnits) -> Self {
Self {
max_periods,
max_stack_level,
units,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
Transaction {
evse_id: u32,
transaction_id: String,
},
EvseDefault {
evse_id: u32,
},
}
impl Target {
#[must_use]
pub fn transaction(evse_id: u32, transaction_id: impl Into<String>) -> Self {
Self::Transaction {
evse_id,
transaction_id: transaction_id.into(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub struct Planned {
pub profile: Profile,
pub coarsened: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlanError {
Empty,
TooManySlots(usize),
BadDuration,
NegativeLimit {
slot: usize,
},
BadPhases {
slot: usize,
},
StackLevel {
requested: i32,
max: i32,
},
TxProfileOnEvseZero,
StationAllowsNothing,
Unconvertible {
slot: usize,
},
}
impl fmt::Display for PlanError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => f.write_str("a charging plan needs at least one slot"),
Self::TooManySlots(n) => write!(
f,
"{n} slots is more than a plan may hold ({})",
ChargingPlan::MAX_SLOTS
),
Self::BadDuration => {
f.write_str("slots must last at least 1 s and the plan at most i32::MAX s")
}
Self::NegativeLimit { slot } => write!(f, "slot {slot} has a negative ceiling"),
Self::BadPhases { slot } => write!(f, "slot {slot} has a phase count outside 1โ3"),
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 (K01.FR.16)")
}
Self::StationAllowsNothing => {
f.write_str("the station allows no periods or no rate unit")
}
Self::Unconvertible { slot } => {
write!(f, "slot {slot} cannot be converted to the station's unit")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for PlanError {}
#[derive(Clone, Debug, PartialEq)]
pub struct ChargingPlan {
start: DateTime,
slot: i64,
ceilings: Vec<Ceiling>,
}
impl ChargingPlan {
pub const MAX_SLOTS: usize = 2976;
pub fn new(
start: DateTime,
slot: Duration,
ceilings: impl IntoIterator<Item = Ceiling>,
) -> Result<Self, PlanError> {
let ceilings: Vec<Ceiling> = ceilings.into_iter().collect();
if ceilings.is_empty() {
return Err(PlanError::Empty);
}
if ceilings.len() > Self::MAX_SLOTS {
return Err(PlanError::TooManySlots(ceilings.len()));
}
let slot = i64::try_from(slot.as_secs()).map_err(|_| PlanError::BadDuration)?;
let total = slot
.checked_mul(i64::try_from(ceilings.len()).map_err(|_| PlanError::BadDuration)?)
.ok_or(PlanError::BadDuration)?;
if slot < 1 || total > i64::from(i32::MAX) {
return Err(PlanError::BadDuration);
}
for (index, ceiling) in ceilings.iter().enumerate() {
if ceiling.limit.signum() < 0 {
return Err(PlanError::NegativeLimit { slot: index });
}
if ceiling
.phases
.is_some_and(|phases| !(1..=3).contains(&phases))
{
return Err(PlanError::BadPhases { slot: index });
}
}
Ok(Self {
start,
slot,
ceilings,
})
}
#[must_use]
pub const fn start(&self) -> DateTime {
self.start
}
#[must_use]
pub fn ceilings(&self) -> &[Ceiling] {
&self.ceilings
}
#[must_use]
pub fn ceiling_at(&self, offset: i64) -> Option<&Ceiling> {
if offset < 0 {
return None;
}
self.ceilings.get(usize::try_from(offset / self.slot).ok()?)
}
#[must_use]
pub fn duration(&self) -> i64 {
self.slot_start(self.ceilings.len())
}
fn slot_start(&self, index: usize) -> i64 {
self.slot
.saturating_mul(i64::try_from(index).unwrap_or(i64::MAX))
}
pub fn to_profile(
&self,
id: i32,
stack_level: i32,
target: Target,
limits: &StationLimits,
supply: Supply,
) -> Result<Planned, PlanError> {
if stack_level > limits.max_stack_level {
return Err(PlanError::StackLevel {
requested: stack_level,
max: limits.max_stack_level,
});
}
if limits.max_periods == 0 || !(limits.units.amperes || limits.units.watts) {
return Err(PlanError::StationAllowsNothing);
}
let mut steps = Vec::with_capacity(self.ceilings.len());
for (index, ceiling) in self.ceilings.iter().enumerate() {
let unit = if limits.units.allows(ceiling.unit) {
ceiling.unit
} else if ceiling.unit == RateUnit::W {
RateUnit::A
} else {
RateUnit::W
};
let phases = ceiling.phases.map(i32::from);
let limit = convert_down(supply, ceiling.limit, ceiling.unit, unit, phases)
.ok_or(PlanError::Unconvertible { slot: index })?;
steps.push(Step {
start: self.slot_start(index),
limit,
unit,
phases,
});
}
let unit = steps[0].unit;
for (index, step) in steps.iter_mut().enumerate() {
if step.unit != unit {
step.limit = convert_down(supply, step.limit, step.unit, unit, step.phases)
.ok_or(PlanError::Unconvertible { slot: index })?;
step.unit = unit;
}
}
let mut periods = merge_equal(&steps);
let mut coarsened = false;
while periods.len() > limits.max_periods {
coarsen_once(&mut periods, self.duration());
coarsened = true;
}
let schedule = Schedule::new(id, unit, periods)
.starting(self.start)
.lasting(self.duration());
let (purpose, evse_id, transaction) = match target {
Target::Transaction {
evse_id,
transaction_id,
} => {
if evse_id == 0 {
return Err(PlanError::TxProfileOnEvseZero);
}
(Purpose::TxProfile, evse_id, Some(transaction_id))
}
Target::EvseDefault { evse_id } => (Purpose::TxDefaultProfile, evse_id, None),
};
let mut profile = Profile::new(id, stack_level, purpose, ProfileKind::Absolute, schedule)
.on_evse(evse_id);
profile.transaction_id = transaction;
Ok(Planned { profile, coarsened })
}
}
#[derive(Clone, Copy)]
struct Step {
start: i64,
limit: Decimal,
unit: RateUnit,
phases: Option<i32>,
}
fn convert_down(
supply: Supply,
limit: Decimal,
from: RateUnit,
to: RateUnit,
phases: Option<i32>,
) -> Option<Decimal> {
let converted = supply.convert(limit, from, to, phases)?;
if from != RateUnit::W || to != RateUnit::A {
return Some(converted);
}
let back = supply.convert(converted, RateUnit::A, RateUnit::W, phases)?;
if back > limit {
converted.checked_sub(Decimal::new(1, CONVERSION_SCALE))
} else {
Some(converted)
}
}
fn merge_equal(steps: &[Step]) -> Vec<Period> {
let mut periods: Vec<Period> = Vec::new();
for step in steps {
if let Some(last) = periods.last() {
if last.limit == step.limit && last.number_phases == step.phases {
continue;
}
}
periods.push(Period {
start_period: step.start,
limit: step.limit,
number_phases: step.phases,
phase_to_use: None,
});
}
periods
}
fn coarsen_once(periods: &mut Vec<Period>, total: i64) {
let end = |index: usize, periods: &[Period]| {
periods
.get(index + 1)
.map_or(total, |next| next.start_period)
};
let mut best: Option<(usize, Decimal)> = None;
for index in 0..periods.len() - 1 {
let (a, b) = (&periods[index], &periods[index + 1]);
let low = a.limit.min(b.limit);
let lost = |period: &Period, from: i64, to: i64| {
period
.limit
.checked_sub(low)
.and_then(|excess| excess.checked_mul(Decimal::from(to - from)))
.unwrap_or(UNBOUNDED)
};
let cost = lost(a, a.start_period, b.start_period)
.checked_add(lost(b, b.start_period, end(index + 1, periods)))
.unwrap_or(UNBOUNDED);
if best.is_none_or(|(_, seen)| cost < seen) {
best = Some((index, cost));
}
}
let Some((index, _)) = best else { return };
let next = periods.remove(index + 1);
let merged = &mut periods[index];
merged.limit = merged.limit.min(next.limit);
merged.number_phases = match (merged.number_phases, next.number_phases) {
(None, None) => None,
(a, b) => Some(a.unwrap_or(DEFAULT_PHASES).min(b.unwrap_or(DEFAULT_PHASES))),
};
let folded = periods.windows(2).position(|pair| {
pair[0].limit == pair[1].limit && pair[0].number_phases == pair[1].number_phases
});
if let Some(at) = folded {
periods.remove(at + 1);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn start() -> DateTime {
"2026-11-20T00:00:00Z".parse().unwrap()
}
fn w(value: i64) -> Ceiling {
Ceiling::watts(Decimal::from(value))
}
fn quarter_hours(ceilings: impl IntoIterator<Item = Ceiling>) -> ChargingPlan {
ChargingPlan::new(start(), Duration::from_secs(900), ceilings).unwrap()
}
const BOTH: StationLimits = StationLimits::new(48, 3, RateUnits::BOTH);
fn target() -> Target {
Target::transaction(1, "tx")
}
#[test]
fn equal_neighbours_become_one_period() {
let planned = quarter_hours([w(11_000), w(11_000), w(7_000), w(7_000)])
.to_profile(1, 1, target(), &BOTH, Supply::default())
.unwrap();
let schedule = &planned.profile.schedules[0];
let periods: Vec<(i64, Decimal)> = schedule
.periods
.iter()
.map(|p| (p.start_period, p.limit))
.collect();
assert_eq!(
periods,
[(0, Decimal::from(11_000)), (1800, Decimal::from(7_000))]
);
assert_eq!(schedule.rate_unit, RateUnit::W);
assert_eq!(schedule.start, Some(start()));
assert_eq!(schedule.duration, Some(3600));
assert_eq!(planned.profile.kind, ProfileKind::Absolute);
assert!(!planned.coarsened);
}
#[test]
fn watts_to_amperes_rounds_down_never_half_to_even() {
let amperes_only = StationLimits::new(48, 3, RateUnits::parse_v16("Current"));
let planned = quarter_hours([w(7_400).phases(3)])
.to_profile(1, 1, target(), &eres_only, Supply::default())
.unwrap();
let period = planned.profile.schedules[0].periods[0];
assert_eq!(period.limit, Decimal::from_literal("10.724"));
assert_eq!(planned.profile.schedules[0].rate_unit, RateUnit::A);
assert_eq!(period.number_phases, Some(3));
}
#[test]
fn too_many_periods_are_merged_below_the_plan() {
let plan = quarter_hours([w(5_000), w(11_000), w(4_000), w(9_000), w(3_000)]);
let limits = StationLimits::new(2, 3, RateUnits::BOTH);
let planned = plan
.to_profile(1, 1, target(), &limits, Supply::default())
.unwrap();
assert!(planned.coarsened);
let schedule = &planned.profile.schedules[0];
assert!(schedule.periods.len() <= 2);
for second in 0..plan.duration() {
let planned_limit = plan.ceiling_at(second).unwrap().limit;
let profile_limit = schedule.period_at(second).unwrap().limit;
assert!(profile_limit <= planned_limit, "at {second}s");
}
}
#[test]
fn one_period_allowed_means_the_plan_minimum() {
let limits = StationLimits::new(1, 3, RateUnits::BOTH);
let planned = quarter_hours([w(5_000), w(11_000), w(4_000)])
.to_profile(1, 1, target(), &limits, Supply::default())
.unwrap();
let periods = &planned.profile.schedules[0].periods;
assert_eq!(periods.len(), 1);
assert_eq!(periods[0].limit, Decimal::from(4_000));
}
#[test]
fn a_tx_profile_is_shaped_by_block_k() {
let planned = quarter_hours([w(5_000).phases(1), w(11_000)])
.to_profile(
7,
2,
Target::transaction(2, "tx-9"),
&BOTH,
Supply::default(),
)
.unwrap();
let profile = planned.profile;
assert_eq!(profile.purpose, Purpose::TxProfile);
assert_eq!(profile.evse_id, 2);
assert_eq!(profile.transaction_id.as_deref(), Some("tx-9"));
assert_eq!(profile.stack_level, 2);
assert_eq!(profile.schedules[0].periods[0].start_period, 0);
assert!(
profile.schedules[0]
.periods
.iter()
.all(|p| p.phase_to_use.is_none())
);
let default = quarter_hours([w(5_000)])
.to_profile(
8,
0,
Target::EvseDefault { evse_id: 0 },
&BOTH,
Supply::default(),
)
.unwrap();
assert_eq!(default.profile.purpose, Purpose::TxDefaultProfile);
assert_eq!(default.profile.transaction_id, None);
}
#[test]
fn the_station_limits_are_refused_not_ignored() {
let plan = quarter_hours([w(5_000)]);
assert_eq!(
plan.to_profile(1, 4, target(), &BOTH, Supply::default()),
Err(PlanError::StackLevel {
requested: 4,
max: 3
})
);
assert_eq!(
plan.to_profile(1, 1, Target::transaction(0, "tx"), &BOTH, Supply::default()),
Err(PlanError::TxProfileOnEvseZero)
);
let nothing = StationLimits::new(10, 3, RateUnits::parse_v2(""));
assert_eq!(
plan.to_profile(1, 1, target(), ¬hing, Supply::default()),
Err(PlanError::StationAllowsNothing)
);
}
#[test]
fn bad_plans_are_refused() {
let empty: [Ceiling; 0] = [];
assert_eq!(
ChargingPlan::new(start(), Duration::from_secs(900), empty),
Err(PlanError::Empty)
);
assert_eq!(
ChargingPlan::new(
start(),
Duration::from_secs(900),
core::iter::repeat_n(w(1), ChargingPlan::MAX_SLOTS + 1)
),
Err(PlanError::TooManySlots(ChargingPlan::MAX_SLOTS + 1))
);
assert_eq!(
ChargingPlan::new(start(), Duration::from_millis(500), [w(1)]),
Err(PlanError::BadDuration)
);
assert_eq!(
ChargingPlan::new(start(), Duration::from_secs(u64::from(u32::MAX)), [w(1)]),
Err(PlanError::BadDuration)
);
assert_eq!(
ChargingPlan::new(start(), Duration::from_secs(900), [w(-1)]),
Err(PlanError::NegativeLimit { slot: 0 })
);
assert_eq!(
ChargingPlan::new(start(), Duration::from_secs(900), [w(1).phases(4)]),
Err(PlanError::BadPhases { slot: 0 })
);
}
#[test]
fn rate_units_read_both_spellings() {
assert_eq!(RateUnits::parse_v16("Current,Power"), RateUnits::BOTH);
assert_eq!(
RateUnits::parse_v16("Power"),
RateUnits {
amperes: false,
watts: true
}
);
assert_eq!(RateUnits::parse_v2("A, W"), RateUnits::BOTH);
assert_eq!(
RateUnits::parse_v2("A"),
RateUnits {
amperes: true,
watts: false
}
);
}
}