1use 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
52pub const CONVERSION_SCALE: u8 = 3;
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum RateUnit {
64 W,
66 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
81#[non_exhaustive]
82pub enum Purpose {
83 ChargingStationMaxProfile,
85 TxDefaultProfile,
87 TxProfile,
89 ChargingStationExternalConstraints,
91 PriorityCharging,
93 LocalGeneration,
95}
96
97impl Purpose {
98 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum ProfileKind {
119 Absolute,
121 Recurring,
123 Relative,
125}
126
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum Recurrency {
130 Daily,
132 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#[derive(Clone, Copy, Debug, PartialEq)]
147pub struct Period {
148 pub start_period: i64,
150 pub limit: Decimal,
152 pub number_phases: Option<i32>,
154 pub phase_to_use: Option<i32>,
156}
157
158impl Period {
159 #[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 #[must_use]
172 pub const fn phases(mut self, phases: i32) -> Self {
173 self.number_phases = Some(phases);
174 self
175 }
176}
177
178#[derive(Clone, Debug, PartialEq)]
180pub struct Schedule {
181 pub id: i32,
183 pub start: Option<DateTime>,
185 pub duration: Option<i64>,
188 pub rate_unit: RateUnit,
190 pub periods: Vec<Period>,
192 pub min_charging_rate: Option<Decimal>,
194}
195
196impl Schedule {
197 #[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 #[must_use]
213 pub fn starting(mut self, start: DateTime) -> Self {
214 self.start = Some(start);
215 self
216 }
217
218 #[must_use]
220 pub fn lasting(mut self, seconds: i64) -> Self {
221 self.duration = Some(seconds);
222 self
223 }
224
225 #[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#[derive(Clone, Debug, PartialEq)]
240pub struct Profile {
241 pub id: i32,
243 pub stack_level: i32,
245 pub purpose: Purpose,
247 pub kind: ProfileKind,
249 pub recurrency: Option<Recurrency>,
251 pub valid_from: Option<DateTime>,
253 pub valid_to: Option<DateTime>,
255 pub transaction_id: Option<String>,
257 pub evse_id: u32,
259 pub schedules: Vec<Schedule>,
262}
263
264impl Profile {
265 #[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 #[must_use]
290 pub fn on_evse(mut self, evse_id: u32) -> Self {
291 self.evse_id = evse_id;
292 self
293 }
294
295 #[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 #[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 #[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 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 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
363pub const DEFAULT_PHASES: i32 = 3;
370
371#[derive(Clone, Copy, Debug, PartialEq, Eq)]
373#[non_exhaustive]
374pub struct Supply {
375 pub voltage: Decimal,
378}
379
380impl Default for Supply {
381 fn default() -> Self {
383 Self::new(Decimal::from(230))
384 }
385}
386
387impl Supply {
388 #[must_use]
390 pub const fn new(voltage: Decimal) -> Self {
391 Self { voltage }
392 }
393
394 #[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 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#[derive(Clone, Copy, Debug, PartialEq)]
428pub struct CompositePeriod {
429 pub start_period: i64,
431 pub limit: Option<Decimal>,
440 pub number_phases: Option<i32>,
443}
444
445#[derive(Clone, Debug, PartialEq)]
447pub struct CompositeSchedule {
448 pub evse_id: u32,
450 pub start: DateTime,
452 pub duration: i64,
454 pub rate_unit: RateUnit,
456 pub periods: Vec<CompositePeriod>,
458}
459
460impl CompositeSchedule {
461 #[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 #[must_use]
483 pub fn has_gaps(&self) -> bool {
484 self.periods.iter().any(|period| period.limit.is_none())
485 }
486}
487
488#[derive(Clone, Debug, Default)]
490pub struct ProfileStore {
491 profiles: Vec<Profile>,
492 pub supply: Supply,
494}
495
496impl ProfileStore {
497 #[must_use]
499 pub fn new() -> Self {
500 Self::default()
501 }
502
503 pub fn install(&mut self, profile: Profile) {
509 self.profiles.retain(|existing| existing.id != profile.id);
510 self.profiles.push(profile);
511 }
512
513 #[must_use]
515 pub fn profiles(&self) -> &[Profile] {
516 &self.profiles
517 }
518
519 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 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 #[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 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 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 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 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 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 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 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 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 Some((self.supply.convert(limit, unit, rate_unit, phases)?, phases))
705 })
706 };
707
708 let session = leading(Purpose::PriorityCharging)
712 .or_else(|| leading(Purpose::TxProfile))
713 .or_else(|| leading(Purpose::TxDefaultProfile));
714
715 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 _ => (limit, phases),
729 });
730 }
731 }
732
733 let generation = leading(Purpose::LocalGeneration);
738 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 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
767fn same_step(previous: CompositePeriod, next: CompositePeriod) -> bool {
772 previous.limit == next.limit && previous.number_phases == next.number_phases
773}
774
775fn 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 #[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 #[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 #[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 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 #[test]
955 fn a_higher_stack_level_outside_its_window_does_not_shadow_a_lower_one() {
956 let mut store = ProfileStore::new();
957 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 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 #[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 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 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 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 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 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 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}