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