Skip to main content

ocpp_kit/smart_charging/
mod.rs

1//! Charging profiles and the composite schedule (functional block K).
2//!
3//! Smart charging is the one part of OCPP where the protocol hands you a *calculation*
4//! rather than a state machine: several profiles apply at once, they stack by purpose and by
5//! stack level, they can recur daily or weekly, and `GetCompositeSchedule` asks for the
6//! single schedule that results. That calculation is what this module does.
7//!
8//! The rules it implements are Part 2 §3.5 "Stacking charging profiles" and §3.6 "Combining
9//! Charging Profile Purposes", which say different things and are easy to conflate:
10//!
11//! * **Within one purpose**, the *leading* schedule is the one that "has a schedule period
12//!   defined for that time and … belongs to a charging profile with the highest stack level
13//!   that is valid at that time". Both qualifications matter: a stack level 3 profile that
14//!   is outside its validity window, or whose schedule has nothing to say about this
15//!   instant, does not shadow stack level 2 — it is simply not leading here.
16//! * **Across purposes**, the composite is "the lowest charging limit … among the leading
17//!   profiles of the different purposes". `ChargingStationMaxProfile` and
18//!   `ChargingStationExternalConstraints` are two of those purposes, not post-hoc ceilings.
19//! * `TxProfile` **replaces** `TxDefaultProfile` for the transaction it names, and
20//!   `PriorityCharging` overrules both — the three occupy one purpose slot between them.
21//! * `LocalGeneration` is **added on top** of the result, not minimised with it. It is
22//!   capacity the site produces; treating it as a limit would turn a solar array into a cap.
23//! * A profile outside its `validFrom` / `validTo`, or past its schedule's `duration`,
24//!   contributes nothing.
25//!
26//! One thing it deliberately does not do: §3.6's note that "the limit value of
27//! `ChargingStationMaxProfile` for EVSE 0 is the limit for all EVSEs **combined**". That is an
28//! allocation problem across simultaneously charging EVSEs, not a property of one EVSE's
29//! schedule, and it belongs to whatever in the station arbitrates between them.
30
31use alloc::collections::BTreeSet;
32use alloc::string::String;
33use alloc::vec::Vec;
34use core::fmt;
35
36use crate::types::{DateTime, Decimal};
37
38#[cfg(feature = "v2_1")]
39pub mod der;
40#[cfg(any(feature = "v2_0_1", feature = "v2_1"))]
41mod needs;
42mod plan;
43#[cfg(feature = "v2_1")]
44pub mod v2x;
45mod wire;
46
47#[cfg(any(feature = "v2_0_1", feature = "v2_1"))]
48pub use needs::EvNeeds;
49pub use plan::{Ceiling, ChargingPlan, PlanError, Planned, RateUnits, StationLimits, Target};
50pub use wire::ConversionError;
51
52/// The scale a limit converted between amperes and watts is rounded to.
53///
54/// Amperes and watts convert by multiplying or dividing by `voltage × phases`, and division
55/// is the one operation with no exact answer in base ten — 1000 W over 230 V and three phases
56/// is 1.449275… A. Three decimals is a milliampere, which is four orders of magnitude finer
57/// than any charging station resolves, and rounding there is what keeps the calculation
58/// exact everywhere else.
59pub const CONVERSION_SCALE: u8 = 3;
60
61/// The unit a limit is expressed in.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum RateUnit {
64    /// Watts.
65    W,
66    /// Amperes, per phase.
67    A,
68}
69
70impl fmt::Display for RateUnit {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(match self {
73            RateUnit::W => "W",
74            RateUnit::A => "A",
75        })
76    }
77}
78
79/// What a profile is for, in the order that decides precedence.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
81#[non_exhaustive]
82pub enum Purpose {
83    /// The station's own ceiling, installed on EVSE 0. Never exceeded.
84    ChargingStationMaxProfile,
85    /// The default for any transaction at this EVSE.
86    TxDefaultProfile,
87    /// A profile for one specific transaction; replaces the default while it applies.
88    TxProfile,
89    /// A limit imposed from outside the CSMS — a DSO, or a local controller.
90    ChargingStationExternalConstraints,
91    /// Priority charging for one transaction (2.1).
92    PriorityCharging,
93    /// Local generation (2.1).
94    LocalGeneration,
95}
96
97impl Purpose {
98    /// Whether a CSMS may install a profile of this purpose with `SetChargingProfile`.
99    ///
100    /// No for `ChargingStationExternalConstraints` (K01.FR.62, 2.0.1 edition 4 and 2.1
101    /// edition 2 errata) and `LocalGeneration` (K01.FR.64, 2.1): both are set locally — by an
102    /// energy manager or the station's own metering — and a `SetChargingProfileRequest`
103    /// carrying one is answered `Rejected` with `reasonCode` `UnsupportedPurpose`.
104    /// [`ProfileStore::install`] accepts every purpose, because the local sources need it to;
105    /// a `SetChargingProfile` handler checks this first.
106    #[must_use]
107    pub const fn settable_by_csms(self) -> bool {
108        !matches!(
109            self,
110            Purpose::ChargingStationExternalConstraints | Purpose::LocalGeneration
111        )
112    }
113}
114
115/// How a profile's schedule is anchored in time.
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum ProfileKind {
119    /// `startSchedule` is an absolute instant.
120    Absolute,
121    /// `startSchedule` is the first occurrence; it repeats.
122    Recurring,
123    /// The schedule starts when the transaction starts.
124    Relative,
125}
126
127/// How often a recurring profile repeats.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum Recurrency {
130    /// Every 24 hours.
131    Daily,
132    /// Every 7 days.
133    Weekly,
134}
135
136impl Recurrency {
137    const fn seconds(self) -> i64 {
138        match self {
139            Recurrency::Daily => 86_400,
140            Recurrency::Weekly => 604_800,
141        }
142    }
143}
144
145/// One step of a schedule.
146#[derive(Clone, Copy, Debug, PartialEq)]
147pub struct Period {
148    /// Seconds after the schedule's start at which this step begins.
149    pub start_period: i64,
150    /// The limit, in the schedule's `RateUnit`.
151    pub limit: Decimal,
152    /// How many phases may be used.
153    pub number_phases: Option<i32>,
154    /// Which phase to use when only one is allowed.
155    pub phase_to_use: Option<i32>,
156}
157
158impl Period {
159    /// A step with no phase constraints.
160    #[must_use]
161    pub const fn new(start_period: i64, limit: Decimal) -> Self {
162        Self {
163            start_period,
164            limit,
165            number_phases: None,
166            phase_to_use: None,
167        }
168    }
169
170    /// Sets the phase count.
171    #[must_use]
172    pub const fn phases(mut self, phases: i32) -> Self {
173        self.number_phases = Some(phases);
174        self
175    }
176}
177
178/// A profile's schedule.
179#[derive(Clone, Debug, PartialEq)]
180pub struct Schedule {
181    /// The schedule id.
182    pub id: i32,
183    /// When the schedule starts. Required for `Absolute` and `Recurring`.
184    pub start: Option<DateTime>,
185    /// How long the schedule lasts, in seconds. `None` means "until the profile stops being
186    /// valid".
187    pub duration: Option<i64>,
188    /// The unit the limits are in.
189    pub rate_unit: RateUnit,
190    /// The steps, which must be ordered by `start_period`.
191    pub periods: Vec<Period>,
192    /// The lowest rate the EV can usefully take.
193    pub min_charging_rate: Option<Decimal>,
194}
195
196impl Schedule {
197    /// A schedule with the given steps.
198    #[must_use]
199    pub fn new(id: i32, rate_unit: RateUnit, mut periods: Vec<Period>) -> Self {
200        periods.sort_by_key(|period| period.start_period);
201        Self {
202            id,
203            start: None,
204            duration: None,
205            rate_unit,
206            periods,
207            min_charging_rate: None,
208        }
209    }
210
211    /// Sets the absolute start.
212    #[must_use]
213    pub fn starting(mut self, start: DateTime) -> Self {
214        self.start = Some(start);
215        self
216    }
217
218    /// Sets the duration in seconds.
219    #[must_use]
220    pub fn lasting(mut self, seconds: i64) -> Self {
221        self.duration = Some(seconds);
222        self
223    }
224
225    /// The step in effect `offset` seconds after the schedule started.
226    #[must_use]
227    pub fn period_at(&self, offset: i64) -> Option<&Period> {
228        if offset < 0 || self.duration.is_some_and(|duration| offset >= duration) {
229            return None;
230        }
231        self.periods
232            .iter()
233            .rev()
234            .find(|period| period.start_period <= offset)
235    }
236}
237
238/// A charging profile as installed by `SetChargingProfile`.
239#[derive(Clone, Debug, PartialEq)]
240pub struct Profile {
241    /// `chargingProfileId`.
242    pub id: i32,
243    /// Higher wins within a purpose.
244    pub stack_level: i32,
245    /// What the profile is for.
246    pub purpose: Purpose,
247    /// How its schedule is anchored.
248    pub kind: ProfileKind,
249    /// How often it repeats, for `Recurring`.
250    pub recurrency: Option<Recurrency>,
251    /// Not in effect before this instant.
252    pub valid_from: Option<DateTime>,
253    /// Not in effect after this instant.
254    pub valid_to: Option<DateTime>,
255    /// The transaction a `TxProfile` belongs to.
256    pub transaction_id: Option<String>,
257    /// The EVSE it was installed on; `0` means the whole Charging Station.
258    pub evse_id: u32,
259    /// Its schedules. Only the first is used by the composite calculation, as 1.6 and the
260    /// common 2.x case have exactly one.
261    pub schedules: Vec<Schedule>,
262}
263
264impl Profile {
265    /// A profile with one schedule.
266    #[must_use]
267    pub fn new(
268        id: i32,
269        stack_level: i32,
270        purpose: Purpose,
271        kind: ProfileKind,
272        schedule: Schedule,
273    ) -> Self {
274        Self {
275            id,
276            stack_level,
277            purpose,
278            kind,
279            recurrency: None,
280            valid_from: None,
281            valid_to: None,
282            transaction_id: None,
283            evse_id: 0,
284            schedules: alloc::vec![schedule],
285        }
286    }
287
288    /// Installs the profile on one EVSE.
289    #[must_use]
290    pub fn on_evse(mut self, evse_id: u32) -> Self {
291        self.evse_id = evse_id;
292        self
293    }
294
295    /// Binds the profile to one transaction.
296    #[must_use]
297    pub fn for_transaction(mut self, transaction_id: impl Into<String>) -> Self {
298        self.transaction_id = Some(transaction_id.into());
299        self
300    }
301
302    /// Sets the validity window.
303    #[must_use]
304    pub fn valid(mut self, from: Option<DateTime>, to: Option<DateTime>) -> Self {
305        self.valid_from = from;
306        self.valid_to = to;
307        self
308    }
309
310    /// Makes the profile repeat.
311    #[must_use]
312    pub fn recurring(mut self, recurrency: Recurrency) -> Self {
313        self.kind = ProfileKind::Recurring;
314        self.recurrency = Some(recurrency);
315        self
316    }
317
318    fn valid_at(&self, at: i64) -> bool {
319        self.valid_from.is_none_or(|from| epoch(from) <= at)
320            && self.valid_to.is_none_or(|to| at < epoch(to))
321    }
322
323    /// The offset into the schedule at `at`, honouring recurrence — or `None` when the
324    /// profile says nothing about that instant.
325    fn offset_at(&self, at: i64, transaction_start: Option<i64>) -> Option<i64> {
326        let schedule = self.schedules.first()?;
327        match self.kind {
328            ProfileKind::Absolute => {
329                let start = schedule.start.map(epoch)?;
330                (at >= start).then_some(at - start)
331            }
332            ProfileKind::Relative => {
333                let start = transaction_start?;
334                (at >= start).then_some(at - start)
335            }
336            ProfileKind::Recurring => {
337                let start = schedule.start.map(epoch)?;
338                let period = self.recurrency?.seconds();
339                if at < start {
340                    return None;
341                }
342                Some((at - start) % period)
343            }
344        }
345    }
346
347    /// The limit this profile imposes at `at`, in its own unit.
348    fn limit_at(
349        &self,
350        at: i64,
351        transaction_start: Option<i64>,
352    ) -> Option<(Decimal, RateUnit, Option<i32>)> {
353        if !self.valid_at(at) {
354            return None;
355        }
356        let schedule = self.schedules.first()?;
357        let offset = self.offset_at(at, transaction_start)?;
358        let period = schedule.period_at(offset)?;
359        Some((period.limit, schedule.rate_unit, period.number_phases))
360    }
361}
362
363/// The phase count assumed for a period without `numberPhases`.
364///
365/// K01.FR.49: "The Charging Station SHALL assume numberPhases = 3 as a default value", with
366/// the edition 4 note that "regions with a single phase network should always provide
367/// numberPhases = 1, otherwise 3 phases will be assumed". It is the CSMS's to say, not the
368/// station's to configure.
369pub const DEFAULT_PHASES: i32 = 3;
370
371/// The supply parameters needed to convert between amperes and watts.
372#[derive(Clone, Copy, Debug, PartialEq, Eq)]
373#[non_exhaustive]
374pub struct Supply {
375    /// Nominal line voltage, in volts: "not the measured voltage, but the set voltage for the
376    /// area (for example, 230 or 110 V)" (K01.FR.50).
377    pub voltage: Decimal,
378}
379
380impl Default for Supply {
381    /// 230 V — the European default.
382    fn default() -> Self {
383        Self::new(Decimal::from(230))
384    }
385}
386
387impl Supply {
388    /// A supply at the given nominal voltage.
389    #[must_use]
390    pub const fn new(voltage: Decimal) -> Self {
391        Self { voltage }
392    }
393
394    /// Converts a limit into `to`.
395    ///
396    /// Amperes to watts is exact. Watts to amperes is a division, so it is rounded to
397    /// [`CONVERSION_SCALE`] — a milliampere — half to even.
398    ///
399    /// `None` means the conversion has no representable answer: a zero voltage or phase
400    /// count, or a limit so large that `limit × voltage × phases` needs more than 19 digits.
401    /// Neither happens for a real supply, and a caller that hits one is better off seeing it
402    /// than being handed a number that is wrong.
403    #[must_use]
404    pub fn convert(
405        self,
406        limit: Decimal,
407        from: RateUnit,
408        to: RateUnit,
409        phases: Option<i32>,
410    ) -> Option<Decimal> {
411        if from == to {
412            return Some(limit);
413        }
414        // K01.FR.50: "Current per phase = limit / (Line Voltage * numberPhases)", with
415        // numberPhases from the period, or 3 when it has none (K01.FR.49).
416        let phases = Decimal::from(phases.unwrap_or(DEFAULT_PHASES).max(1));
417        let factor = self.voltage.checked_mul(phases)?;
418        match (from, to) {
419            (RateUnit::A, RateUnit::W) => limit.checked_mul(factor),
420            (RateUnit::W, RateUnit::A) => limit.checked_div(factor, CONVERSION_SCALE),
421            _ => Some(limit),
422        }
423    }
424}
425
426/// One step of a computed composite schedule.
427#[derive(Clone, Copy, Debug, PartialEq)]
428pub struct CompositePeriod {
429    /// Seconds after the requested start.
430    pub start_period: i64,
431    /// The effective limit, or `None` when no profile constrains this stretch at all.
432    ///
433    /// The gap is a real state and has to be representable. Carrying the previous step's
434    /// limit through it — the obvious shortcut — reports a constraint that no installed
435    /// profile imposes, and it does so for exactly the stretch where the EVSE is free to
436    /// draw its rated maximum. `ChargingSchedulePeriodType.limit` is mandatory in the
437    /// schemas, so a caller answering `GetCompositeSchedule` substitutes the EVSE's rated
438    /// maximum here; see [`CompositeSchedule::fill_gaps`].
439    pub limit: Option<Decimal>,
440    /// The lowest phase count any applicable period asked for (K01.FR.140); `None` when none
441    /// said, which means [`DEFAULT_PHASES`].
442    pub number_phases: Option<i32>,
443}
444
445/// The answer to `GetCompositeSchedule`.
446#[derive(Clone, Debug, PartialEq)]
447pub struct CompositeSchedule {
448    /// The EVSE it was computed for.
449    pub evse_id: u32,
450    /// When the schedule starts.
451    pub start: DateTime,
452    /// How long it covers, in seconds.
453    pub duration: i64,
454    /// The unit the limits are in.
455    pub rate_unit: RateUnit,
456    /// The steps, merged so that no two consecutive steps carry the same limit.
457    pub periods: Vec<CompositePeriod>,
458}
459
460impl CompositeSchedule {
461    /// Replaces every unconstrained stretch with `rated_maximum`, in this schedule's
462    /// [`rate_unit`](Self::rate_unit).
463    ///
464    /// `ChargingSchedulePeriodType.limit` is mandatory, so a `GetCompositeScheduleResponse`
465    /// has to name a number for a stretch that no profile constrains. The only honest number
466    /// is what the EVSE can actually deliver, which the protocol never tells the station —
467    /// hence a parameter rather than a guess.
468    #[must_use]
469    pub fn fill_gaps(mut self, rated_maximum: impl Into<Decimal>) -> Self {
470        let rated_maximum = rated_maximum.into();
471        for period in &mut self.periods {
472            if period.limit.is_none() {
473                period.limit = Some(rated_maximum);
474            }
475        }
476        self.periods
477            .dedup_by(|next, previous| same_step(*previous, *next));
478        self
479    }
480
481    /// Whether any stretch of this schedule is left unconstrained.
482    #[must_use]
483    pub fn has_gaps(&self) -> bool {
484        self.periods.iter().any(|period| period.limit.is_none())
485    }
486}
487
488/// The installed profiles, and the composite calculation over them.
489#[derive(Clone, Debug, Default)]
490pub struct ProfileStore {
491    profiles: Vec<Profile>,
492    /// The supply parameters used when a unit conversion is needed.
493    pub supply: Supply,
494}
495
496impl ProfileStore {
497    /// An empty store.
498    #[must_use]
499    pub fn new() -> Self {
500        Self::default()
501    }
502
503    /// Installs a profile, replacing any profile with the same id.
504    ///
505    /// K01: a `SetChargingProfile` with an id that already exists replaces it. Every purpose
506    /// is accepted; for one that came from the CSMS, check [`Purpose::settable_by_csms`]
507    /// first (K01.FR.62/64).
508    pub fn install(&mut self, profile: Profile) {
509        self.profiles.retain(|existing| existing.id != profile.id);
510        self.profiles.push(profile);
511    }
512
513    /// Every installed profile.
514    #[must_use]
515    pub fn profiles(&self) -> &[Profile] {
516        &self.profiles
517    }
518
519    /// Removes profiles matching the `ClearChargingProfile` criteria. Returns how many went.
520    ///
521    /// Passing no criteria at all clears everything, as the message defines.
522    pub fn clear(
523        &mut self,
524        id: Option<i32>,
525        evse_id: Option<u32>,
526        purpose: Option<Purpose>,
527        stack_level: Option<i32>,
528    ) -> usize {
529        let before = self.profiles.len();
530        self.profiles.retain(|profile| {
531            let matches = id.is_none_or(|id| profile.id == id)
532                && evse_id.is_none_or(|evse| profile.evse_id == evse)
533                && purpose.is_none_or(|purpose| profile.purpose == purpose)
534                && stack_level.is_none_or(|level| profile.stack_level == level);
535            !matches
536        });
537        before - self.profiles.len()
538    }
539
540    /// Removes every profile bound to a transaction that has ended (K08).
541    pub fn clear_transaction(&mut self, transaction_id: &str) -> usize {
542        let before = self.profiles.len();
543        self.profiles
544            .retain(|profile| profile.transaction_id.as_deref() != Some(transaction_id));
545        before - self.profiles.len()
546    }
547
548    /// Computes the composite schedule for `evse_id`.
549    ///
550    /// `transaction` names the transaction running at the EVSE, which decides which
551    /// `TxProfile` applies and where a `Relative` schedule starts.
552    #[must_use]
553    pub fn composite(
554        &self,
555        evse_id: u32,
556        from: DateTime,
557        duration: i64,
558        rate_unit: RateUnit,
559        transaction: Option<(&str, DateTime)>,
560    ) -> CompositeSchedule {
561        let start = epoch(from);
562        let end = start + duration.max(0);
563        let transaction_start = transaction.map(|(_, at)| epoch(at));
564
565        // Profiles on EVSE 0 apply to every EVSE; the ceiling always lives there.
566        let applicable: Vec<&Profile> = self
567            .profiles
568            .iter()
569            .filter(|profile| profile.evse_id == 0 || profile.evse_id == evse_id)
570            .filter(|profile| match profile.purpose {
571                // A TxProfile only applies to the transaction it names.
572                Purpose::TxProfile | Purpose::PriorityCharging => {
573                    match (&profile.transaction_id, transaction) {
574                        (Some(id), Some((running, _))) => id == running,
575                        (None, Some(_)) => true,
576                        _ => false,
577                    }
578                }
579                _ => true,
580            })
581            .collect();
582
583        let boundaries = Self::boundaries(&applicable, start, end, transaction_start);
584
585        let mut periods: Vec<CompositePeriod> = Vec::new();
586        for at in boundaries {
587            // `None` here means no installed profile says anything about this instant. It
588            // opens a step of its own: skipping it would silently extend the previous
589            // limit across a stretch nothing constrains.
590            let effective = self.limit_at(&applicable, at, rate_unit, transaction_start);
591            let step = CompositePeriod {
592                start_period: at - start,
593                limit: effective.map(|(limit, _)| limit),
594                number_phases: effective.and_then(|(_, phases)| phases),
595            };
596            match periods.last() {
597                Some(previous) if same_step(*previous, step) => {}
598                // A leading gap is not a step: the schedule simply starts where the first
599                // constraint does.
600                None if step.limit.is_none() => {}
601                _ => periods.push(step),
602            }
603        }
604
605        CompositeSchedule {
606            evse_id,
607            start: from,
608            duration,
609            rate_unit,
610            periods,
611        }
612    }
613
614    /// Every instant in `[start, end)` at which the effective limit could change.
615    fn boundaries(
616        profiles: &[&Profile],
617        start: i64,
618        end: i64,
619        transaction_start: Option<i64>,
620    ) -> Vec<i64> {
621        let mut points: BTreeSet<i64> = BTreeSet::new();
622        points.insert(start);
623        for profile in profiles {
624            for at in [profile.valid_from.map(epoch), profile.valid_to.map(epoch)]
625                .into_iter()
626                .flatten()
627            {
628                if (start..end).contains(&at) {
629                    points.insert(at);
630                }
631            }
632            let Some(schedule) = profile.schedules.first() else {
633                continue;
634            };
635            let anchors: Vec<i64> = match profile.kind {
636                ProfileKind::Absolute => schedule.start.map(epoch).into_iter().collect(),
637                ProfileKind::Relative => transaction_start.into_iter().collect(),
638                ProfileKind::Recurring => {
639                    let Some(first) = schedule.start.map(epoch) else {
640                        continue;
641                    };
642                    let Some(period) = profile.recurrency.map(Recurrency::seconds) else {
643                        continue;
644                    };
645                    // Walk the repetitions that overlap the window, bounded so a tiny period
646                    // cannot make this loop forever.
647                    let mut anchors = Vec::new();
648                    let skipped = (start - first).div_euclid(period);
649                    let mut at = first + skipped * period;
650                    while at < end && anchors.len() < 4096 {
651                        anchors.push(at);
652                        at += period;
653                    }
654                    anchors
655                }
656            };
657            for anchor in anchors {
658                for step in &schedule.periods {
659                    let at = anchor + step.start_period;
660                    if (start..end).contains(&at) {
661                        points.insert(at);
662                    }
663                }
664                if let Some(duration) = schedule.duration {
665                    let at = anchor + duration;
666                    if (start..end).contains(&at) {
667                        points.insert(at);
668                    }
669                }
670            }
671        }
672        points.into_iter().collect()
673    }
674
675    /// The effective limit at one instant, applying the stacking rules.
676    /// The effective limit at one instant, per Part 2 §3.6 "Combining Charging Profile
677    /// Purposes".
678    fn limit_at(
679        &self,
680        profiles: &[&Profile],
681        at: i64,
682        rate_unit: RateUnit,
683        transaction_start: Option<i64>,
684    ) -> Option<(Decimal, Option<i32>)> {
685        // §3.6: "the leading charging schedule for that purpose is the charging schedule that
686        // **has a schedule period defined for that time** and that belongs to a charging
687        // profile with the highest stack level **that is valid at that time**". Both
688        // qualifications are part of the selection, so a higher stack level that says nothing
689        // about this instant does not shadow a lower one that does — it simply is not
690        // leading here.
691        let leading = |purpose: Purpose| -> Option<(Decimal, Option<i32>)> {
692            profiles
693                .iter()
694                .filter(|profile| profile.purpose == purpose)
695                .filter_map(|profile| {
696                    profile
697                        .limit_at(at, transaction_start)
698                        .map(|limit| (profile.stack_level, limit))
699                })
700                .max_by_key(|(stack_level, _)| *stack_level)
701                .and_then(|(_, (limit, unit, phases))| {
702                    // A limit with no representable value in the requested unit constrains
703                    // nothing it can be trusted to constrain; see `Supply::convert`.
704                    Some((self.supply.convert(limit, unit, rate_unit, phases)?, phases))
705                })
706        };
707
708        // §3.6: a PriorityCharging profile "will overrule the TxDefaultProfile or TxProfile",
709        // and a TxProfile in turn overrules the TxDefaultProfile (figure 122). These three
710        // are one purpose slot, not three.
711        let session = leading(Purpose::PriorityCharging)
712            .or_else(|| leading(Purpose::TxProfile))
713            .or_else(|| leading(Purpose::TxDefaultProfile));
714
715        // §3.6: "the lowest charging limit … among the leading profiles of the different
716        // purposes". The station maximum and external constraints are the other two.
717        let mut effective = session;
718        for purpose in [
719            Purpose::ChargingStationMaxProfile,
720            Purpose::ChargingStationExternalConstraints,
721        ] {
722            if let Some((limit, phases)) = leading(purpose) {
723                effective = Some(match effective {
724                    Some((current, current_phases)) if current <= limit => {
725                        (current, current_phases)
726                    }
727                    // Either nothing constrained this instant yet, or this purpose is lower.
728                    _ => (limit, phases),
729                });
730            }
731        }
732
733        // §3.6: "If a charging profile of chargingProfilePurpose = LocalGeneration is active
734        // for the EVSE, then this capacity is **added on top** of the calculated composite
735        // schedule." It is generation, not a constraint — taking the minimum with it would
736        // turn a solar array into a limit.
737        let generation = leading(Purpose::LocalGeneration);
738        // K01.FR.140 (2.1 edition 2): "at each point in time use the lowest value of
739        // numberPhases for that point in time in all applicable chargingSchedulePeriods" — a
740        // station maximum of one phase and a TxProfile of three is one phase. 2.0.1 does not
741        // say; the lowest is the reading that never exceeds a profile.
742        let lowest_phases = [
743            Purpose::ChargingStationMaxProfile,
744            Purpose::ChargingStationExternalConstraints,
745        ]
746        .into_iter()
747        .filter_map(|purpose| leading(purpose).and_then(|(_, phases)| phases))
748        .chain(session.and_then(|(_, phases)| phases))
749        .chain(generation.and_then(|(_, phases)| phases))
750        .min();
751        if let Some((generation, phases)) = generation {
752            effective = match effective {
753                // The sum overflows only past 19 digits, at which point the honest answer is
754                // the constraint that was already there rather than a wrapped one.
755                Some((current, current_phases)) => Some((
756                    current.checked_add(generation).unwrap_or(current),
757                    current_phases,
758                )),
759                None => Some((generation, phases)),
760            };
761        }
762
763        effective.map(|(limit, _)| (limit, lowest_phases))
764    }
765}
766
767/// Whether two consecutive steps say the same thing, and so merge into one.
768///
769/// The limits are exact decimals, so this is an exact comparison — not the epsilon that a
770/// float would need, and that is wrong at both ends of the range it has to cover.
771fn same_step(previous: CompositePeriod, next: CompositePeriod) -> bool {
772    previous.limit == next.limit && previous.number_phases == next.number_phases
773}
774
775/// Seconds since the Unix epoch.
776fn epoch(at: DateTime) -> i64 {
777    at.timestamp().as_second()
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783    use crate::decimal;
784
785    fn at(text: &str) -> DateTime {
786        DateTime::parse(text).unwrap()
787    }
788
789    fn schedule(rate_unit: RateUnit, steps: &[(i64, Decimal)]) -> Schedule {
790        Schedule::new(
791            1,
792            rate_unit,
793            steps
794                .iter()
795                .map(|(start, limit)| Period::new(*start, *limit))
796                .collect(),
797        )
798    }
799
800    /// K01.FR.62/64: two purposes are the station's own to set.
801    #[test]
802    fn external_constraints_and_local_generation_are_not_the_csmss_to_set() {
803        assert!(!Purpose::ChargingStationExternalConstraints.settable_by_csms());
804        assert!(!Purpose::LocalGeneration.settable_by_csms());
805        for purpose in [
806            Purpose::ChargingStationMaxProfile,
807            Purpose::TxDefaultProfile,
808            Purpose::TxProfile,
809            Purpose::PriorityCharging,
810        ] {
811            assert!(purpose.settable_by_csms(), "{purpose:?}");
812        }
813    }
814
815    /// K01.FR.140: the composite's phase count is the lowest any applicable period asks for,
816    /// not the winning limit's — a one-phase station maximum keeps a three-phase `TxProfile`
817    /// on one phase even where the `TxProfile` limit is the lower.
818    #[test]
819    fn the_composite_uses_the_lowest_phase_count_k01_fr_140() {
820        let start = at("2024-01-01T00:00:00Z");
821        let mut store = ProfileStore::new();
822        store.install(Profile::new(
823            1,
824            0,
825            Purpose::ChargingStationMaxProfile,
826            ProfileKind::Absolute,
827            Schedule::new(
828                1,
829                RateUnit::A,
830                alloc::vec![Period::new(0, decimal!(32.0)).phases(1)],
831            )
832            .starting(start),
833        ));
834        store.install(Profile::new(
835            2,
836            0,
837            Purpose::TxDefaultProfile,
838            ProfileKind::Absolute,
839            Schedule::new(
840                1,
841                RateUnit::A,
842                alloc::vec![Period::new(0, decimal!(16.0)).phases(3)],
843            )
844            .starting(start),
845        ));
846        let composite = store.composite(1, start, 60, RateUnit::A, None);
847        assert_eq!(
848            composite.periods,
849            alloc::vec![CompositePeriod {
850                start_period: 0,
851                limit: Some(decimal!(16.0)),
852                number_phases: Some(1)
853            }]
854        );
855    }
856
857    /// K01.FR.49: a period without `numberPhases` converts with three phases.
858    #[test]
859    fn an_absent_phase_count_converts_as_three_k01_fr_49() {
860        let supply = Supply::default();
861        assert_eq!(
862            supply.convert(decimal!(6900), RateUnit::W, RateUnit::A, None),
863            Some(decimal!(10.000))
864        );
865        assert_eq!(
866            supply.convert(decimal!(2300), RateUnit::W, RateUnit::A, Some(1)),
867            Some(decimal!(10.000))
868        );
869    }
870
871    #[test]
872    fn a_single_absolute_profile_becomes_its_own_composite() {
873        let mut store = ProfileStore::new();
874        store.install(Profile::new(
875            1,
876            0,
877            Purpose::TxDefaultProfile,
878            ProfileKind::Absolute,
879            schedule(RateUnit::A, &[(0, decimal!(16.0)), (3600, decimal!(10.0))])
880                .starting(at("2024-01-01T00:00:00Z")),
881        ));
882
883        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 7200, RateUnit::A, None);
884        assert_eq!(
885            composite.periods,
886            alloc::vec![
887                CompositePeriod {
888                    start_period: 0,
889                    limit: Some(decimal!(16.0)),
890                    number_phases: None
891                },
892                CompositePeriod {
893                    start_period: 3600,
894                    limit: Some(decimal!(10.0)),
895                    number_phases: None
896                },
897            ]
898        );
899    }
900
901    #[test]
902    fn the_highest_stack_level_wins_within_a_purpose() {
903        let mut store = ProfileStore::new();
904        store.install(Profile::new(
905            1,
906            0,
907            Purpose::TxDefaultProfile,
908            ProfileKind::Absolute,
909            schedule(RateUnit::A, &[(0, decimal!(32.0))]).starting(at("2024-01-01T00:00:00Z")),
910        ));
911        store.install(Profile::new(
912            2,
913            5,
914            Purpose::TxDefaultProfile,
915            ProfileKind::Absolute,
916            schedule(RateUnit::A, &[(0, decimal!(6.0))]).starting(at("2024-01-01T00:00:00Z")),
917        ));
918
919        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 60, RateUnit::A, None);
920        assert_eq!(composite.periods[0].limit, Some(decimal!(6.0)));
921    }
922
923    #[test]
924    fn the_station_maximum_is_a_ceiling_over_the_session_profile() {
925        let mut store = ProfileStore::new();
926        store.install(Profile::new(
927            1,
928            0,
929            Purpose::TxDefaultProfile,
930            ProfileKind::Absolute,
931            schedule(RateUnit::A, &[(0, decimal!(32.0))]).starting(at("2024-01-01T00:00:00Z")),
932        ));
933        store.install(Profile::new(
934            2,
935            0,
936            Purpose::ChargingStationMaxProfile,
937            ProfileKind::Absolute,
938            schedule(RateUnit::A, &[(0, decimal!(20.0)), (1800, decimal!(40.0))])
939                .starting(at("2024-01-01T00:00:00Z")),
940        ));
941
942        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 3600, RateUnit::A, None);
943        // First the ceiling binds, then the session profile does.
944        assert_eq!(composite.periods[0].limit, Some(decimal!(20.0)));
945        assert_eq!(composite.periods[1].start_period, 1800);
946        assert_eq!(composite.periods[1].limit, Some(decimal!(32.0)));
947    }
948
949    /// §3.6: the leading schedule is the highest stack level "**that is valid at that
950    /// time**" and "**has a schedule period defined for that time**". A higher stack level
951    /// that says nothing about this instant is not leading, and must not shadow one that
952    /// does — otherwise a holiday exception profile would blank out the weekly default it
953    /// was layered on top of, and the EVSE would be left unconstrained.
954    #[test]
955    fn a_higher_stack_level_outside_its_window_does_not_shadow_a_lower_one() {
956        let mut store = ProfileStore::new();
957        // The weekly default: always applicable.
958        store.install(Profile::new(
959            1,
960            0,
961            Purpose::TxDefaultProfile,
962            ProfileKind::Absolute,
963            schedule(RateUnit::A, &[(0, decimal!(32.0))]).starting(at("2024-01-01T00:00:00Z")),
964        ));
965        // The exception: higher stack level, but only in effect for one hour.
966        store.install(
967            Profile::new(
968                2,
969                5,
970                Purpose::TxDefaultProfile,
971                ProfileKind::Absolute,
972                schedule(RateUnit::A, &[(0, decimal!(6.0))]).starting(at("2024-01-01T00:00:00Z")),
973            )
974            .valid(None, Some(at("2024-01-01T01:00:00Z"))),
975        );
976
977        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 7200, RateUnit::A, None);
978        assert_eq!(
979            composite.periods[0].limit,
980            Some(decimal!(6.0)),
981            "inside the exception's window it leads"
982        );
983        assert_eq!(
984            composite.periods.last().and_then(|period| period.limit),
985            Some(decimal!(32.0)),
986            "outside it, the weekly default leads again: {:?}",
987            composite.periods
988        );
989    }
990
991    /// §3.6: "If a charging profile of `chargingProfilePurpose` = `LocalGeneration` is active
992    /// the EVSE, then this capacity is **added on top** of the calculated composite
993    /// schedule." Minimising with it instead would let a solar array *reduce* what the EVSE
994    /// may draw.
995    #[test]
996    fn local_generation_is_added_on_top_rather_than_minimised() {
997        let mut store = ProfileStore::new();
998        store.install(Profile::new(
999            1,
1000            0,
1001            Purpose::TxDefaultProfile,
1002            ProfileKind::Absolute,
1003            schedule(RateUnit::W, &[(0, decimal!(11_000.0))]).starting(at("2024-01-01T00:00:00Z")),
1004        ));
1005        store.install(Profile::new(
1006            2,
1007            0,
1008            Purpose::LocalGeneration,
1009            ProfileKind::Absolute,
1010            schedule(RateUnit::W, &[(0, decimal!(4_000.0))]).starting(at("2024-01-01T00:00:00Z")),
1011        ));
1012
1013        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 60, RateUnit::W, None);
1014        assert_eq!(composite.periods[0].limit, Some(decimal!(15_000.0)));
1015    }
1016
1017    #[test]
1018    fn a_tx_profile_replaces_the_default_rather_than_combining_with_it() {
1019        let mut store = ProfileStore::new();
1020        store.install(Profile::new(
1021            1,
1022            9,
1023            Purpose::TxDefaultProfile,
1024            ProfileKind::Absolute,
1025            schedule(RateUnit::A, &[(0, decimal!(6.0))]).starting(at("2024-01-01T00:00:00Z")),
1026        ));
1027        store.install(
1028            Profile::new(
1029                2,
1030                0,
1031                Purpose::TxProfile,
1032                ProfileKind::Absolute,
1033                schedule(RateUnit::A, &[(0, decimal!(32.0))]).starting(at("2024-01-01T00:00:00Z")),
1034            )
1035            .for_transaction("tx-1"),
1036        );
1037
1038        // Without the transaction, the TxProfile does not apply at all.
1039        let without = store.composite(1, at("2024-01-01T00:00:00Z"), 60, RateUnit::A, None);
1040        assert_eq!(without.periods[0].limit, Some(decimal!(6.0)));
1041
1042        // With it, it replaces the default even though its stack level is lower.
1043        let with = store.composite(
1044            1,
1045            at("2024-01-01T00:00:00Z"),
1046            60,
1047            RateUnit::A,
1048            Some(("tx-1", at("2024-01-01T00:00:00Z"))),
1049        );
1050        assert_eq!(with.periods[0].limit, Some(decimal!(32.0)));
1051    }
1052
1053    #[test]
1054    fn a_recurring_profile_repeats_within_the_window() {
1055        let mut store = ProfileStore::new();
1056        store.install(
1057            Profile::new(
1058                1,
1059                0,
1060                Purpose::TxDefaultProfile,
1061                ProfileKind::Recurring,
1062                schedule(RateUnit::A, &[(0, decimal!(6.0)), (43_200, decimal!(32.0))])
1063                    .starting(at("2024-01-01T00:00:00Z")),
1064            )
1065            .recurring(Recurrency::Daily),
1066        );
1067
1068        let composite = store.composite(1, at("2024-01-03T00:00:00Z"), 172_800, RateUnit::A, None);
1069        let limits: Vec<Option<Decimal>> = composite.periods.iter().map(|p| p.limit).collect();
1070        // Cheap overnight, expensive by day, twice over two days.
1071        assert_eq!(
1072            limits,
1073            alloc::vec![
1074                Some(decimal!(6.0)),
1075                Some(decimal!(32.0)),
1076                Some(decimal!(6.0)),
1077                Some(decimal!(32.0))
1078            ]
1079        );
1080        assert_eq!(composite.periods[1].start_period, 43_200);
1081        assert_eq!(composite.periods[2].start_period, 86_400);
1082    }
1083
1084    #[test]
1085    fn a_validity_window_bounds_a_profile() {
1086        let mut store = ProfileStore::new();
1087        store.install(
1088            Profile::new(
1089                1,
1090                0,
1091                Purpose::TxDefaultProfile,
1092                ProfileKind::Absolute,
1093                schedule(RateUnit::A, &[(0, decimal!(16.0))]).starting(at("2024-01-01T00:00:00Z")),
1094            )
1095            .valid(None, Some(at("2024-01-01T01:00:00Z"))),
1096        );
1097        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 7200, RateUnit::A, None);
1098        // One step while the profile is valid, then an explicit gap. The second step is the
1099        // point: after `validTo` nothing constrains the EVSE, and carrying 16 A through the
1100        // rest of the window would report a limit that no installed profile imposes.
1101        assert_eq!(composite.periods.len(), 2, "{:?}", composite.periods);
1102        assert_eq!(composite.periods[0].limit, Some(decimal!(16.0)));
1103        assert_eq!(composite.periods[1].start_period, 3600);
1104        assert_eq!(composite.periods[1].limit, None);
1105        assert!(composite.has_gaps());
1106
1107        // `GetCompositeSchedule` has to name a number, so the caller supplies the EVSE's
1108        // rated maximum for the stretch nothing constrains.
1109        let filled = composite.fill_gaps(decimal!(32.0));
1110        assert_eq!(filled.periods[1].limit, Some(decimal!(32.0)));
1111        assert!(!filled.has_gaps());
1112    }
1113
1114    #[test]
1115    fn limits_convert_between_amperes_and_watts() {
1116        let mut store = ProfileStore::new();
1117        store.supply = Supply::new(decimal!(230.0));
1118        store.install(Profile::new(
1119            1,
1120            0,
1121            Purpose::TxDefaultProfile,
1122            ProfileKind::Absolute,
1123            schedule(RateUnit::A, &[(0, decimal!(16.0))]).starting(at("2024-01-01T00:00:00Z")),
1124        ));
1125        let composite = store.composite(1, at("2024-01-01T00:00:00Z"), 60, RateUnit::W, None);
1126        // Exactly 11040 W, not 11039.999999999998: the conversion is a decimal
1127        // multiplication, so there is nothing to compare with a tolerance.
1128        assert_eq!(composite.periods[0].limit, Some(decimal!(11040)));
1129    }
1130
1131    #[test]
1132    fn clearing_by_criteria_removes_only_what_matches() {
1133        let mut store = ProfileStore::new();
1134        for id in 1..=3 {
1135            store.install(
1136                Profile::new(
1137                    id,
1138                    id,
1139                    Purpose::TxDefaultProfile,
1140                    ProfileKind::Absolute,
1141                    schedule(RateUnit::A, &[(0, decimal!(16.0))])
1142                        .starting(at("2024-01-01T00:00:00Z")),
1143                )
1144                .on_evse(u32::try_from(id).unwrap()),
1145            );
1146        }
1147        assert_eq!(store.clear(None, Some(2), None, None), 1);
1148        assert_eq!(store.profiles().len(), 2);
1149        assert_eq!(
1150            store.clear(None, None, None, None),
1151            2,
1152            "no criteria clears everything"
1153        );
1154    }
1155
1156    #[test]
1157    fn an_ended_transaction_takes_its_profile_with_it() {
1158        let mut store = ProfileStore::new();
1159        store.install(
1160            Profile::new(
1161                1,
1162                0,
1163                Purpose::TxProfile,
1164                ProfileKind::Absolute,
1165                schedule(RateUnit::A, &[(0, decimal!(32.0))]).starting(at("2024-01-01T00:00:00Z")),
1166            )
1167            .for_transaction("tx-1"),
1168        );
1169        assert_eq!(store.clear_transaction("tx-2"), 0);
1170        assert_eq!(store.clear_transaction("tx-1"), 1);
1171        assert!(store.profiles().is_empty(), "{:?}", store.profiles());
1172    }
1173}