1use 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
46pub const CONVERSION_SCALE: u8 = 3;
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum RateUnit {
58 W,
60 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
75#[non_exhaustive]
76pub enum Purpose {
77 ChargingStationMaxProfile,
79 TxDefaultProfile,
81 TxProfile,
83 ChargingStationExternalConstraints,
85 PriorityCharging,
87 LocalGeneration,
89}
90
91impl Purpose {
92 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111#[non_exhaustive]
112pub enum ProfileKind {
113 Absolute,
115 Recurring,
117 Relative,
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum Recurrency {
124 Daily,
126 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#[derive(Clone, Copy, Debug, PartialEq)]
141pub struct Period {
142 pub start_period: i64,
144 pub limit: Decimal,
146 pub number_phases: Option<i32>,
148 pub phase_to_use: Option<i32>,
150}
151
152impl Period {
153 #[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 #[must_use]
166 pub const fn phases(mut self, phases: i32) -> Self {
167 self.number_phases = Some(phases);
168 self
169 }
170}
171
172#[derive(Clone, Debug, PartialEq)]
174pub struct Schedule {
175 pub id: i32,
177 pub start: Option<DateTime>,
179 pub duration: Option<i64>,
182 pub rate_unit: RateUnit,
184 pub periods: Vec<Period>,
186 pub min_charging_rate: Option<Decimal>,
188}
189
190impl Schedule {
191 #[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 #[must_use]
207 pub fn starting(mut self, start: DateTime) -> Self {
208 self.start = Some(start);
209 self
210 }
211
212 #[must_use]
214 pub fn lasting(mut self, seconds: i64) -> Self {
215 self.duration = Some(seconds);
216 self
217 }
218
219 #[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#[derive(Clone, Debug, PartialEq)]
234pub struct Profile {
235 pub id: i32,
237 pub stack_level: i32,
239 pub purpose: Purpose,
241 pub kind: ProfileKind,
243 pub recurrency: Option<Recurrency>,
245 pub valid_from: Option<DateTime>,
247 pub valid_to: Option<DateTime>,
249 pub transaction_id: Option<String>,
251 pub evse_id: u32,
253 pub schedules: Vec<Schedule>,
256}
257
258impl Profile {
259 #[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 #[must_use]
284 pub fn on_evse(mut self, evse_id: u32) -> Self {
285 self.evse_id = evse_id;
286 self
287 }
288
289 #[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 #[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 #[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 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 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
357pub const DEFAULT_PHASES: i32 = 3;
364
365#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367#[non_exhaustive]
368pub struct Supply {
369 pub voltage: Decimal,
372}
373
374impl Default for Supply {
375 fn default() -> Self {
377 Self::new(Decimal::from(230))
378 }
379}
380
381impl Supply {
382 #[must_use]
384 pub const fn new(voltage: Decimal) -> Self {
385 Self { voltage }
386 }
387
388 #[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 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#[derive(Clone, Copy, Debug, PartialEq)]
422pub struct CompositePeriod {
423 pub start_period: i64,
425 pub limit: Option<Decimal>,
434 pub number_phases: Option<i32>,
437}
438
439#[derive(Clone, Debug, PartialEq)]
441pub struct CompositeSchedule {
442 pub evse_id: u32,
444 pub start: DateTime,
446 pub duration: i64,
448 pub rate_unit: RateUnit,
450 pub periods: Vec<CompositePeriod>,
452}
453
454impl CompositeSchedule {
455 #[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 #[must_use]
477 pub fn has_gaps(&self) -> bool {
478 self.periods.iter().any(|period| period.limit.is_none())
479 }
480}
481
482#[derive(Clone, Debug, Default)]
484pub struct ProfileStore {
485 profiles: Vec<Profile>,
486 pub supply: Supply,
488}
489
490impl ProfileStore {
491 #[must_use]
493 pub fn new() -> Self {
494 Self::default()
495 }
496
497 pub fn install(&mut self, profile: Profile) {
503 self.profiles.retain(|existing| existing.id != profile.id);
504 self.profiles.push(profile);
505 }
506
507 #[must_use]
509 pub fn profiles(&self) -> &[Profile] {
510 &self.profiles
511 }
512
513 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 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 #[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 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 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 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 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 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 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 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 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 Some((self.supply.convert(limit, unit, rate_unit, phases)?, phases))
699 })
700 };
701
702 let session = leading(Purpose::PriorityCharging)
706 .or_else(|| leading(Purpose::TxProfile))
707 .or_else(|| leading(Purpose::TxDefaultProfile));
708
709 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 _ => (limit, phases),
723 });
724 }
725 }
726
727 let generation = leading(Purpose::LocalGeneration);
732 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 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
761fn same_step(previous: CompositePeriod, next: CompositePeriod) -> bool {
766 previous.limit == next.limit && previous.number_phases == next.number_phases
767}
768
769fn 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 #[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 #[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 #[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 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 #[test]
949 fn a_higher_stack_level_outside_its_window_does_not_shadow_a_lower_one() {
950 let mut store = ProfileStore::new();
951 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 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 #[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 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 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 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 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 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 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}