Skip to main content

ocpp_kit/smart_charging/
plan.rs

1//! Plans of per-slot ceilings, and their conversion to a profile. See [`ChargingPlan`].
2
3use 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
14/// A cost larger than any real one, for a merge whose arithmetic overflowed.
15const UNBOUNDED: Decimal = Decimal::new(i64::MAX, 0);
16
17/// One slot's ceiling: the most the EV may draw during it.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct Ceiling {
20    /// The limit: in W the sum of all phases, in A per phase (2.1 §2.18).
21    pub limit: Decimal,
22    /// The unit of [`limit`](Self::limit).
23    pub unit: RateUnit,
24    /// How many phases may be used, 1–3; `None` lets the station assume 3 (K01.FR.49).
25    pub phases: Option<u8>,
26}
27
28impl Ceiling {
29    /// A ceiling in watts, summed over all phases.
30    #[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    /// A ceiling in amperes per phase.
40    #[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    /// Limits the number of phases (1–3).
50    #[must_use]
51    pub const fn phases(mut self, phases: u8) -> Self {
52        self.phases = Some(phases);
53        self
54    }
55}
56
57/// Which `chargingRateUnit`s a station accepts (K01.FR.26).
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct RateUnits {
60    /// `A` is allowed.
61    pub amperes: bool,
62    /// `W` is allowed.
63    pub watts: bool,
64}
65
66impl RateUnits {
67    /// Both units.
68    pub const BOTH: Self = Self {
69        amperes: true,
70        watts: true,
71    };
72
73    /// Reads 1.6 `ChargingScheduleAllowedChargingRateUnit` — `Current`, `Power`, or both,
74    /// comma-separated.
75    #[must_use]
76    pub fn parse_v16(value: &str) -> Self {
77        Self::parse(value, "Current", "Power")
78    }
79
80    /// Reads 2.x `SmartChargingCtrlr.RateUnit` — `A`, `W`, or both, comma-separated.
81    #[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/// What the station allows in a profile, from its own configuration.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct StationLimits {
109    /// `SmartChargingCtrlr.PeriodsPerSchedule` (1.6 `ChargingScheduleMaxPeriods`).
110    pub max_periods: usize,
111    /// `SmartChargingCtrlr.ProfileStackLevel` (1.6 `ChargeProfileMaxStackLevel`).
112    pub max_stack_level: i32,
113    /// `SmartChargingCtrlr.RateUnit` (1.6 `ChargingScheduleAllowedChargingRateUnit`).
114    pub units: RateUnits,
115}
116
117impl StationLimits {
118    /// The limits a station reported.
119    #[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/// What the profile is for.
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub enum Target {
132    /// A `TxProfile` for one running transaction (K01.FR.03).
133    Transaction {
134        /// The EVSE; must be > 0 (K01.FR.16).
135        evse_id: u32,
136        /// The transaction id.
137        transaction_id: String,
138    },
139    /// A `TxDefaultProfile` for every transaction on one EVSE (0: every EVSE).
140    EvseDefault {
141        /// The EVSE.
142        evse_id: u32,
143    },
144}
145
146impl Target {
147    /// A `TxProfile` for `transaction_id` on `evse_id`.
148    #[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/// A converted plan.
158#[derive(Clone, Debug, PartialEq)]
159#[must_use]
160pub struct Planned {
161    /// The profile, ready for [`Profile::set_request_v2_1`] and its siblings.
162    pub profile: Profile,
163    /// Whether the plan had more distinct slots than the station allows, so neighbours were
164    /// merged into their lower limit. The profile is then below the plan in places, never above.
165    pub coarsened: bool,
166}
167
168/// Why a plan could not become a profile.
169#[derive(Clone, Debug, PartialEq, Eq)]
170#[non_exhaustive]
171pub enum PlanError {
172    /// A plan needs at least one slot.
173    Empty,
174    /// More than [`ChargingPlan::MAX_SLOTS`] slots.
175    TooManySlots(usize),
176    /// A slot must last at least a second, and the plan at most `i32::MAX` seconds — what a
177    /// schedule's `duration` can say.
178    BadDuration,
179    /// A ceiling below zero.
180    NegativeLimit {
181        /// The slot.
182        slot: usize,
183    },
184    /// A phase count outside 1–3.
185    BadPhases {
186        /// The slot.
187        slot: usize,
188    },
189    /// The stack level is above what the station allows.
190    StackLevel {
191        /// What was asked for.
192        requested: i32,
193        /// The station's `ProfileStackLevel`.
194        max: i32,
195    },
196    /// A `TxProfile` on EVSE 0 (K01.FR.16).
197    TxProfileOnEvseZero,
198    /// The station allows no periods, or neither unit.
199    StationAllowsNothing,
200    /// A unit conversion has no representable answer (a zero voltage, or digits to spare).
201    Unconvertible {
202        /// The slot.
203        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/// Ceilings for consecutive, equally long slots from a start instant.
242///
243/// From a plan of per-slot ceilings to a `TxProfile` the station will accept.
244///
245/// Every consumer that drives a charging station from a plan — a home energy manager, a site
246/// load manager, a CSMS doing smart charging — writes this function, and writes it differently:
247/// a quarter-hour planner emits ceilings, and somewhere they have to become one valid
248/// `ChargingProfile` within the station's own limits. The rules that make it valid are spread
249/// over block K, and two of them are easy to get backwards:
250///
251/// * **A ceiling must stay a ceiling.** Converting watts to amperes divides by `voltage ×
252///   phases`, which has no exact decimal answer; rounding half-to-even rounds *up* half the time,
253///   and a profile 1 mA above the plan is a profile above the plan. Here W → A rounds down.
254/// * **Too many slots for the station** (`SmartChargingCtrlr.PeriodsPerSchedule`, 1.6
255///   `ChargingScheduleMaxPeriods`) are merged, never truncated: after a profile's last period
256///   the station falls back to whatever applied before, which may be higher than the plan. Two
257///   neighbours merge into the *lower* limit and the *fewer* phases, choosing each time the pair
258///   whose merge gives up the least energy — so the result is below the plan everywhere, and as
259///   close to it as the station allows.
260///
261/// The result is one profile for the whole plan. 2.1 K01.FR.56 lets a station refuse frequent
262/// `SetChargingProfile` with `RateLimitExceeded`, because profiles wear out its persistent
263/// memory; send a profile when the plan changes, not once per slot.
264///
265/// A plan holds ceilings only. OCPP 1.6 and 2.0.1 cannot command a *floor*: `minChargingRate`
266/// tells the station something about the EV (K01.FR.21), and the setpoints that can require a
267/// minimum are 2.1 V2X operation modes (block Q). A plan that needs one cannot be expressed here,
268/// and pretending otherwise would be a silent loss.
269///
270/// ```
271/// use core::time::Duration;
272/// use ocpp_kit::smart_charging::{
273///     Ceiling, ChargingPlan, RateUnits, StationLimits, Supply, Target,
274/// };
275/// use ocpp_kit::types::{DateTime, Decimal};
276///
277/// let start: DateTime = "2026-11-20T00:00:00Z".parse()?;
278/// // Four quarter hours: 11 kW, 11 kW, then 7.4 kW twice, on three phases.
279/// let plan = ChargingPlan::new(
280///     start,
281///     Duration::from_secs(900),
282///     [11_000, 11_000, 7_400, 7_400].map(|w| Ceiling::watts(Decimal::from(w)).phases(3)),
283/// )?;
284/// // What the station said in its configuration (1.6 keys here; `RateUnits::parse_v2` reads
285/// // `SmartChargingCtrlr.RateUnit`).
286/// let limits = StationLimits::new(24, 3, RateUnits::parse_v16("Current"));
287/// let planned = plan.to_profile(
288///     1,
289///     1,
290///     Target::transaction(1, "4711"),
291///     &limits,
292///     Supply::default(),
293/// )?;
294/// let schedule = &planned.profile.schedules[0];
295/// assert_eq!(schedule.periods.len(), 2);
296/// // 7400 W / (230 V × 3) = 10.72463… A: rounded *down*, never to 10.725.
297/// assert_eq!(schedule.periods[1].limit, Decimal::from_literal("10.724"));
298/// assert!(!planned.coarsened);
299/// # Ok::<(), Box<dyn std::error::Error>>(())
300/// ```
301
302#[derive(Clone, Debug, PartialEq)]
303pub struct ChargingPlan {
304    start: DateTime,
305    slot: i64,
306    ceilings: Vec<Ceiling>,
307}
308
309impl ChargingPlan {
310    /// The most slots a plan may hold: 31 days of quarter hours.
311    ///
312    /// Merging slots for a station with few periods is quadratic in the number of slots, and a
313    /// controller's one-second loop should not find that out from a planner bug.
314    pub const MAX_SLOTS: usize = 2976;
315
316    /// A plan of `ceilings`, one per `slot`, from `start`.
317    ///
318    /// # Errors
319    ///
320    /// [`PlanError`] for an empty or oversized plan, a slot shorter than a second, a plan
321    /// longer than `i32::MAX` seconds, a negative ceiling or a phase count outside 1–3.
322    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    /// When the plan starts.
360    #[must_use]
361    pub const fn start(&self) -> DateTime {
362        self.start
363    }
364
365    /// The plan's ceilings, in order.
366    #[must_use]
367    pub fn ceilings(&self) -> &[Ceiling] {
368        &self.ceilings
369    }
370
371    /// The ceiling `offset` seconds after the start, if the plan covers it.
372    #[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    /// How long the plan lasts, in seconds.
381    #[must_use]
382    pub fn duration(&self) -> i64 {
383        // `new` checked that this fits an `i32`.
384        self.slot_start(self.ceilings.len())
385    }
386
387    /// Seconds from the plan's start to the start of slot `index`.
388    fn slot_start(&self, index: usize) -> i64 {
389        self.slot
390            .saturating_mul(i64::try_from(index).unwrap_or(i64::MAX))
391    }
392
393    /// Turns the plan into one `Absolute` profile the station will accept.
394    ///
395    /// The profile is a `TxProfile` for [`Target::Transaction`] and a `TxDefaultProfile` for
396    /// [`Target::EvseDefault`]; it starts at the plan's start, lasts as long as the plan, has
397    /// its first period at 0 (K01.FR.31) and the rest ascending (K01.FR.35), never sets
398    /// `phaseToUse` (K01.FR.19/20), uses a unit the station allows (K01.FR.26) and has at most
399    /// the station's number of periods — merged conservatively when the plan has more.
400    ///
401    /// # Errors
402    ///
403    /// [`PlanError`] for a stack level above the station's, a `TxProfile` on EVSE 0, a station
404    /// that allows no periods or no unit, or a conversion with no answer.
405    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        // One unit for the whole schedule: if slots came in both, settle on the station's
444        // preference order — the plan's first unit when allowed, else the other.
445        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/// One slot on its way to becoming a period.
484#[derive(Clone, Copy)]
485struct Step {
486    start: i64,
487    limit: Decimal,
488    unit: RateUnit,
489    phases: Option<i32>,
490}
491
492/// Converts a ceiling so that the result is never above it: W → A rounds down to a milliampere.
493fn 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    // `convert` rounds half to even; step down one milliampere if that rounded up.
505    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
513/// One period per run of equal (limit, phases) slots.
514fn 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
532/// Merges the adjacent pair whose merge gives up the least energy, into the lower limit and the
533/// fewer phases.
534fn 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    // Merging may have made it equal to a neighbour; fold those too.
567    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(), &amperes_only, Supply::default())
624            .unwrap();
625        let period = planned.profile.schedules[0].periods[0];
626        // 7400 / 690 = 10.724637…: half to even gives 10.725, which is above the plan.
627        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(), &nothing, 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}