1use alloc::string::String;
4use alloc::vec::Vec;
5use core::fmt;
6use core::time::Duration;
7
8use super::{
9 CONVERSION_SCALE, DEFAULT_PHASES, Period, Profile, ProfileKind, Purpose, RateUnit, Schedule,
10 Supply,
11};
12use crate::types::{DateTime, Decimal};
13
14const UNBOUNDED: Decimal = Decimal::new(i64::MAX, 0);
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct Ceiling {
20 pub limit: Decimal,
22 pub unit: RateUnit,
24 pub phases: Option<u8>,
26}
27
28impl Ceiling {
29 #[must_use]
31 pub const fn watts(limit: Decimal) -> Self {
32 Self {
33 limit,
34 unit: RateUnit::W,
35 phases: None,
36 }
37 }
38
39 #[must_use]
41 pub const fn amperes(limit: Decimal) -> Self {
42 Self {
43 limit,
44 unit: RateUnit::A,
45 phases: None,
46 }
47 }
48
49 #[must_use]
51 pub const fn phases(mut self, phases: u8) -> Self {
52 self.phases = Some(phases);
53 self
54 }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct RateUnits {
60 pub amperes: bool,
62 pub watts: bool,
64}
65
66impl RateUnits {
67 pub const BOTH: Self = Self {
69 amperes: true,
70 watts: true,
71 };
72
73 #[must_use]
76 pub fn parse_v16(value: &str) -> Self {
77 Self::parse(value, "Current", "Power")
78 }
79
80 #[must_use]
82 pub fn parse_v2(value: &str) -> Self {
83 Self::parse(value, "A", "W")
84 }
85
86 fn parse(value: &str, amperes: &str, watts: &str) -> Self {
87 let mut units = Self {
88 amperes: false,
89 watts: false,
90 };
91 for item in value.split(',').map(str::trim) {
92 units.amperes |= item.eq_ignore_ascii_case(amperes);
93 units.watts |= item.eq_ignore_ascii_case(watts);
94 }
95 units
96 }
97
98 const fn allows(self, unit: RateUnit) -> bool {
99 match unit {
100 RateUnit::A => self.amperes,
101 RateUnit::W => self.watts,
102 }
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct StationLimits {
109 pub max_periods: usize,
111 pub max_stack_level: i32,
113 pub units: RateUnits,
115}
116
117impl StationLimits {
118 #[must_use]
120 pub const fn new(max_periods: usize, max_stack_level: i32, units: RateUnits) -> Self {
121 Self {
122 max_periods,
123 max_stack_level,
124 units,
125 }
126 }
127}
128
129#[derive(Clone, Debug, PartialEq, Eq)]
131pub enum Target {
132 Transaction {
134 evse_id: u32,
136 transaction_id: String,
138 },
139 EvseDefault {
141 evse_id: u32,
143 },
144}
145
146impl Target {
147 #[must_use]
149 pub fn transaction(evse_id: u32, transaction_id: impl Into<String>) -> Self {
150 Self::Transaction {
151 evse_id,
152 transaction_id: transaction_id.into(),
153 }
154 }
155}
156
157#[derive(Clone, Debug, PartialEq)]
159#[must_use]
160pub struct Planned {
161 pub profile: Profile,
163 pub coarsened: bool,
166}
167
168#[derive(Clone, Debug, PartialEq, Eq)]
170#[non_exhaustive]
171pub enum PlanError {
172 Empty,
174 TooManySlots(usize),
176 BadDuration,
179 NegativeLimit {
181 slot: usize,
183 },
184 BadPhases {
186 slot: usize,
188 },
189 StackLevel {
191 requested: i32,
193 max: i32,
195 },
196 TxProfileOnEvseZero,
198 StationAllowsNothing,
200 Unconvertible {
202 slot: usize,
204 },
205}
206
207impl fmt::Display for PlanError {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 match self {
210 Self::Empty => f.write_str("a charging plan needs at least one slot"),
211 Self::TooManySlots(n) => write!(
212 f,
213 "{n} slots is more than a plan may hold ({})",
214 ChargingPlan::MAX_SLOTS
215 ),
216 Self::BadDuration => {
217 f.write_str("slots must last at least 1 s and the plan at most i32::MAX s")
218 }
219 Self::NegativeLimit { slot } => write!(f, "slot {slot} has a negative ceiling"),
220 Self::BadPhases { slot } => write!(f, "slot {slot} has a phase count outside 1–3"),
221 Self::StackLevel { requested, max } => write!(
222 f,
223 "stack level {requested} is above the station's ProfileStackLevel {max}"
224 ),
225 Self::TxProfileOnEvseZero => {
226 f.write_str("a TxProfile needs an EVSE above 0 (K01.FR.16)")
227 }
228 Self::StationAllowsNothing => {
229 f.write_str("the station allows no periods or no rate unit")
230 }
231 Self::Unconvertible { slot } => {
232 write!(f, "slot {slot} cannot be converted to the station's unit")
233 }
234 }
235 }
236}
237
238#[cfg(feature = "std")]
239impl std::error::Error for PlanError {}
240
241#[derive(Clone, Debug, PartialEq)]
303pub struct ChargingPlan {
304 start: DateTime,
305 slot: i64,
306 ceilings: Vec<Ceiling>,
307}
308
309impl ChargingPlan {
310 pub const MAX_SLOTS: usize = 2976;
315
316 pub fn new(
323 start: DateTime,
324 slot: Duration,
325 ceilings: impl IntoIterator<Item = Ceiling>,
326 ) -> Result<Self, PlanError> {
327 let ceilings: Vec<Ceiling> = ceilings.into_iter().collect();
328 if ceilings.is_empty() {
329 return Err(PlanError::Empty);
330 }
331 if ceilings.len() > Self::MAX_SLOTS {
332 return Err(PlanError::TooManySlots(ceilings.len()));
333 }
334 let slot = i64::try_from(slot.as_secs()).map_err(|_| PlanError::BadDuration)?;
335 let total = slot
336 .checked_mul(i64::try_from(ceilings.len()).map_err(|_| PlanError::BadDuration)?)
337 .ok_or(PlanError::BadDuration)?;
338 if slot < 1 || total > i64::from(i32::MAX) {
339 return Err(PlanError::BadDuration);
340 }
341 for (index, ceiling) in ceilings.iter().enumerate() {
342 if ceiling.limit.signum() < 0 {
343 return Err(PlanError::NegativeLimit { slot: index });
344 }
345 if ceiling
346 .phases
347 .is_some_and(|phases| !(1..=3).contains(&phases))
348 {
349 return Err(PlanError::BadPhases { slot: index });
350 }
351 }
352 Ok(Self {
353 start,
354 slot,
355 ceilings,
356 })
357 }
358
359 #[must_use]
361 pub const fn start(&self) -> DateTime {
362 self.start
363 }
364
365 #[must_use]
367 pub fn ceilings(&self) -> &[Ceiling] {
368 &self.ceilings
369 }
370
371 #[must_use]
373 pub fn ceiling_at(&self, offset: i64) -> Option<&Ceiling> {
374 if offset < 0 {
375 return None;
376 }
377 self.ceilings.get(usize::try_from(offset / self.slot).ok()?)
378 }
379
380 #[must_use]
382 pub fn duration(&self) -> i64 {
383 self.slot_start(self.ceilings.len())
385 }
386
387 fn slot_start(&self, index: usize) -> i64 {
389 self.slot
390 .saturating_mul(i64::try_from(index).unwrap_or(i64::MAX))
391 }
392
393 pub fn to_profile(
406 &self,
407 id: i32,
408 stack_level: i32,
409 target: Target,
410 limits: &StationLimits,
411 supply: Supply,
412 ) -> Result<Planned, PlanError> {
413 if stack_level > limits.max_stack_level {
414 return Err(PlanError::StackLevel {
415 requested: stack_level,
416 max: limits.max_stack_level,
417 });
418 }
419 if limits.max_periods == 0 || !(limits.units.amperes || limits.units.watts) {
420 return Err(PlanError::StationAllowsNothing);
421 }
422
423 let mut steps = Vec::with_capacity(self.ceilings.len());
424 for (index, ceiling) in self.ceilings.iter().enumerate() {
425 let unit = if limits.units.allows(ceiling.unit) {
426 ceiling.unit
427 } else if ceiling.unit == RateUnit::W {
428 RateUnit::A
429 } else {
430 RateUnit::W
431 };
432 let phases = ceiling.phases.map(i32::from);
433 let limit = convert_down(supply, ceiling.limit, ceiling.unit, unit, phases)
434 .ok_or(PlanError::Unconvertible { slot: index })?;
435 steps.push(Step {
436 start: self.slot_start(index),
437 limit,
438 unit,
439 phases,
440 });
441 }
442
443 let unit = steps[0].unit;
446 for (index, step) in steps.iter_mut().enumerate() {
447 if step.unit != unit {
448 step.limit = convert_down(supply, step.limit, step.unit, unit, step.phases)
449 .ok_or(PlanError::Unconvertible { slot: index })?;
450 step.unit = unit;
451 }
452 }
453
454 let mut periods = merge_equal(&steps);
455 let mut coarsened = false;
456 while periods.len() > limits.max_periods {
457 coarsen_once(&mut periods, self.duration());
458 coarsened = true;
459 }
460
461 let schedule = Schedule::new(id, unit, periods)
462 .starting(self.start)
463 .lasting(self.duration());
464 let (purpose, evse_id, transaction) = match target {
465 Target::Transaction {
466 evse_id,
467 transaction_id,
468 } => {
469 if evse_id == 0 {
470 return Err(PlanError::TxProfileOnEvseZero);
471 }
472 (Purpose::TxProfile, evse_id, Some(transaction_id))
473 }
474 Target::EvseDefault { evse_id } => (Purpose::TxDefaultProfile, evse_id, None),
475 };
476 let mut profile = Profile::new(id, stack_level, purpose, ProfileKind::Absolute, schedule)
477 .on_evse(evse_id);
478 profile.transaction_id = transaction;
479 Ok(Planned { profile, coarsened })
480 }
481}
482
483#[derive(Clone, Copy)]
485struct Step {
486 start: i64,
487 limit: Decimal,
488 unit: RateUnit,
489 phases: Option<i32>,
490}
491
492fn convert_down(
494 supply: Supply,
495 limit: Decimal,
496 from: RateUnit,
497 to: RateUnit,
498 phases: Option<i32>,
499) -> Option<Decimal> {
500 let converted = supply.convert(limit, from, to, phases)?;
501 if from != RateUnit::W || to != RateUnit::A {
502 return Some(converted);
503 }
504 let back = supply.convert(converted, RateUnit::A, RateUnit::W, phases)?;
506 if back > limit {
507 converted.checked_sub(Decimal::new(1, CONVERSION_SCALE))
508 } else {
509 Some(converted)
510 }
511}
512
513fn merge_equal(steps: &[Step]) -> Vec<Period> {
515 let mut periods: Vec<Period> = Vec::new();
516 for step in steps {
517 if let Some(last) = periods.last() {
518 if last.limit == step.limit && last.number_phases == step.phases {
519 continue;
520 }
521 }
522 periods.push(Period {
523 start_period: step.start,
524 limit: step.limit,
525 number_phases: step.phases,
526 phase_to_use: None,
527 });
528 }
529 periods
530}
531
532fn coarsen_once(periods: &mut Vec<Period>, total: i64) {
535 let end = |index: usize, periods: &[Period]| {
536 periods
537 .get(index + 1)
538 .map_or(total, |next| next.start_period)
539 };
540 let mut best: Option<(usize, Decimal)> = None;
541 for index in 0..periods.len() - 1 {
542 let (a, b) = (&periods[index], &periods[index + 1]);
543 let low = a.limit.min(b.limit);
544 let lost = |period: &Period, from: i64, to: i64| {
545 period
546 .limit
547 .checked_sub(low)
548 .and_then(|excess| excess.checked_mul(Decimal::from(to - from)))
549 .unwrap_or(UNBOUNDED)
550 };
551 let cost = lost(a, a.start_period, b.start_period)
552 .checked_add(lost(b, b.start_period, end(index + 1, periods)))
553 .unwrap_or(UNBOUNDED);
554 if best.is_none_or(|(_, seen)| cost < seen) {
555 best = Some((index, cost));
556 }
557 }
558 let Some((index, _)) = best else { return };
559 let next = periods.remove(index + 1);
560 let merged = &mut periods[index];
561 merged.limit = merged.limit.min(next.limit);
562 merged.number_phases = match (merged.number_phases, next.number_phases) {
563 (None, None) => None,
564 (a, b) => Some(a.unwrap_or(DEFAULT_PHASES).min(b.unwrap_or(DEFAULT_PHASES))),
565 };
566 let folded = periods.windows(2).position(|pair| {
568 pair[0].limit == pair[1].limit && pair[0].number_phases == pair[1].number_phases
569 });
570 if let Some(at) = folded {
571 periods.remove(at + 1);
572 }
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578
579 fn start() -> DateTime {
580 "2026-11-20T00:00:00Z".parse().unwrap()
581 }
582
583 fn w(value: i64) -> Ceiling {
584 Ceiling::watts(Decimal::from(value))
585 }
586
587 fn quarter_hours(ceilings: impl IntoIterator<Item = Ceiling>) -> ChargingPlan {
588 ChargingPlan::new(start(), Duration::from_secs(900), ceilings).unwrap()
589 }
590
591 const BOTH: StationLimits = StationLimits::new(48, 3, RateUnits::BOTH);
592
593 fn target() -> Target {
594 Target::transaction(1, "tx")
595 }
596
597 #[test]
598 fn equal_neighbours_become_one_period() {
599 let planned = quarter_hours([w(11_000), w(11_000), w(7_000), w(7_000)])
600 .to_profile(1, 1, target(), &BOTH, Supply::default())
601 .unwrap();
602 let schedule = &planned.profile.schedules[0];
603 let periods: Vec<(i64, Decimal)> = schedule
604 .periods
605 .iter()
606 .map(|p| (p.start_period, p.limit))
607 .collect();
608 assert_eq!(
609 periods,
610 [(0, Decimal::from(11_000)), (1800, Decimal::from(7_000))]
611 );
612 assert_eq!(schedule.rate_unit, RateUnit::W);
613 assert_eq!(schedule.start, Some(start()));
614 assert_eq!(schedule.duration, Some(3600));
615 assert_eq!(planned.profile.kind, ProfileKind::Absolute);
616 assert!(!planned.coarsened);
617 }
618
619 #[test]
620 fn watts_to_amperes_rounds_down_never_half_to_even() {
621 let amperes_only = StationLimits::new(48, 3, RateUnits::parse_v16("Current"));
622 let planned = quarter_hours([w(7_400).phases(3)])
623 .to_profile(1, 1, target(), &eres_only, Supply::default())
624 .unwrap();
625 let period = planned.profile.schedules[0].periods[0];
626 assert_eq!(period.limit, Decimal::from_literal("10.724"));
628 assert_eq!(planned.profile.schedules[0].rate_unit, RateUnit::A);
629 assert_eq!(period.number_phases, Some(3));
630 }
631
632 #[test]
633 fn too_many_periods_are_merged_below_the_plan() {
634 let plan = quarter_hours([w(5_000), w(11_000), w(4_000), w(9_000), w(3_000)]);
635 let limits = StationLimits::new(2, 3, RateUnits::BOTH);
636 let planned = plan
637 .to_profile(1, 1, target(), &limits, Supply::default())
638 .unwrap();
639 assert!(planned.coarsened);
640 let schedule = &planned.profile.schedules[0];
641 assert!(schedule.periods.len() <= 2);
642 for second in 0..plan.duration() {
643 let planned_limit = plan.ceiling_at(second).unwrap().limit;
644 let profile_limit = schedule.period_at(second).unwrap().limit;
645 assert!(profile_limit <= planned_limit, "at {second}s");
646 }
647 }
648
649 #[test]
650 fn one_period_allowed_means_the_plan_minimum() {
651 let limits = StationLimits::new(1, 3, RateUnits::BOTH);
652 let planned = quarter_hours([w(5_000), w(11_000), w(4_000)])
653 .to_profile(1, 1, target(), &limits, Supply::default())
654 .unwrap();
655 let periods = &planned.profile.schedules[0].periods;
656 assert_eq!(periods.len(), 1);
657 assert_eq!(periods[0].limit, Decimal::from(4_000));
658 }
659
660 #[test]
661 fn a_tx_profile_is_shaped_by_block_k() {
662 let planned = quarter_hours([w(5_000).phases(1), w(11_000)])
663 .to_profile(
664 7,
665 2,
666 Target::transaction(2, "tx-9"),
667 &BOTH,
668 Supply::default(),
669 )
670 .unwrap();
671 let profile = planned.profile;
672 assert_eq!(profile.purpose, Purpose::TxProfile);
673 assert_eq!(profile.evse_id, 2);
674 assert_eq!(profile.transaction_id.as_deref(), Some("tx-9"));
675 assert_eq!(profile.stack_level, 2);
676 assert_eq!(profile.schedules[0].periods[0].start_period, 0);
677 assert!(
678 profile.schedules[0]
679 .periods
680 .iter()
681 .all(|p| p.phase_to_use.is_none())
682 );
683
684 let default = quarter_hours([w(5_000)])
685 .to_profile(
686 8,
687 0,
688 Target::EvseDefault { evse_id: 0 },
689 &BOTH,
690 Supply::default(),
691 )
692 .unwrap();
693 assert_eq!(default.profile.purpose, Purpose::TxDefaultProfile);
694 assert_eq!(default.profile.transaction_id, None);
695 }
696
697 #[test]
698 fn the_station_limits_are_refused_not_ignored() {
699 let plan = quarter_hours([w(5_000)]);
700 assert_eq!(
701 plan.to_profile(1, 4, target(), &BOTH, Supply::default()),
702 Err(PlanError::StackLevel {
703 requested: 4,
704 max: 3
705 })
706 );
707 assert_eq!(
708 plan.to_profile(1, 1, Target::transaction(0, "tx"), &BOTH, Supply::default()),
709 Err(PlanError::TxProfileOnEvseZero)
710 );
711 let nothing = StationLimits::new(10, 3, RateUnits::parse_v2(""));
712 assert_eq!(
713 plan.to_profile(1, 1, target(), ¬hing, Supply::default()),
714 Err(PlanError::StationAllowsNothing)
715 );
716 }
717
718 #[test]
719 fn bad_plans_are_refused() {
720 let empty: [Ceiling; 0] = [];
721 assert_eq!(
722 ChargingPlan::new(start(), Duration::from_secs(900), empty),
723 Err(PlanError::Empty)
724 );
725 assert_eq!(
726 ChargingPlan::new(
727 start(),
728 Duration::from_secs(900),
729 core::iter::repeat_n(w(1), ChargingPlan::MAX_SLOTS + 1)
730 ),
731 Err(PlanError::TooManySlots(ChargingPlan::MAX_SLOTS + 1))
732 );
733 assert_eq!(
734 ChargingPlan::new(start(), Duration::from_millis(500), [w(1)]),
735 Err(PlanError::BadDuration)
736 );
737 assert_eq!(
738 ChargingPlan::new(start(), Duration::from_secs(u64::from(u32::MAX)), [w(1)]),
739 Err(PlanError::BadDuration)
740 );
741 assert_eq!(
742 ChargingPlan::new(start(), Duration::from_secs(900), [w(-1)]),
743 Err(PlanError::NegativeLimit { slot: 0 })
744 );
745 assert_eq!(
746 ChargingPlan::new(start(), Duration::from_secs(900), [w(1).phases(4)]),
747 Err(PlanError::BadPhases { slot: 0 })
748 );
749 }
750
751 #[test]
752 fn rate_units_read_both_spellings() {
753 assert_eq!(RateUnits::parse_v16("Current,Power"), RateUnits::BOTH);
754 assert_eq!(
755 RateUnits::parse_v16("Power"),
756 RateUnits {
757 amperes: false,
758 watts: true
759 }
760 );
761 assert_eq!(RateUnits::parse_v2("A, W"), RateUnits::BOTH);
762 assert_eq!(
763 RateUnits::parse_v2("A"),
764 RateUnits {
765 amperes: true,
766 watts: false
767 }
768 );
769 }
770}