1use alloc::vec::Vec;
72use core::fmt;
73use core::time::Duration;
74
75use super::{ChargingPlan, EvNeeds, RateUnit, StationLimits, Target};
76use crate::types::{DateTime, Decimal};
77use crate::v2_1;
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
81#[non_exhaustive]
82pub enum Mode {
83 ChargingOnly,
85 CentralSetpoint,
87 ExternalSetpoint,
89 ExternalLimits,
91 LocalLoadBalancing,
93 Idle,
95}
96
97impl Mode {
98 const ALL: [Self; 6] = [
99 Self::ChargingOnly,
100 Self::CentralSetpoint,
101 Self::ExternalSetpoint,
102 Self::ExternalLimits,
103 Self::LocalLoadBalancing,
104 Self::Idle,
105 ];
106
107 #[must_use]
109 pub const fn as_str(self) -> &'static str {
110 match self {
111 Self::ChargingOnly => "ChargingOnly",
112 Self::CentralSetpoint => "CentralSetpoint",
113 Self::ExternalSetpoint => "ExternalSetpoint",
114 Self::ExternalLimits => "ExternalLimits",
115 Self::LocalLoadBalancing => "LocalLoadBalancing",
116 Self::Idle => "Idle",
117 }
118 }
119
120 const fn bit(self) -> u8 {
121 1 << (self as u8)
122 }
123
124 const fn to_wire(self) -> v2_1::OperationMode {
125 match self {
126 Self::ChargingOnly => v2_1::OperationMode::ChargingOnly,
127 Self::CentralSetpoint => v2_1::OperationMode::CentralSetpoint,
128 Self::ExternalSetpoint => v2_1::OperationMode::ExternalSetpoint,
129 Self::ExternalLimits => v2_1::OperationMode::ExternalLimits,
130 Self::LocalLoadBalancing => v2_1::OperationMode::LocalLoadBalancing,
131 Self::Idle => v2_1::OperationMode::Idle,
132 }
133 }
134}
135
136impl fmt::Display for Mode {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 f.write_str(self.as_str())
139 }
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct OperationModes(u8);
146
147impl OperationModes {
148 pub const MANDATORY: Self = Self(Mode::ChargingOnly.bit() | Mode::CentralSetpoint.bit());
151
152 #[must_use]
155 pub fn parse(value: &str) -> Self {
156 let mut bits = 0;
157 for item in value.split(',').map(str::trim) {
158 if let Some(mode) = Mode::ALL.iter().find(|mode| mode.as_str() == item) {
159 bits |= mode.bit();
160 }
161 }
162 Self(bits)
163 }
164
165 #[must_use]
167 pub const fn contains(self, mode: Mode) -> bool {
168 self.0 & mode.bit() != 0
169 }
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174pub struct V2xStation {
175 pub limits: StationLimits,
177 pub modes: OperationModes,
179}
180
181impl V2xStation {
182 #[must_use]
184 pub const fn new(limits: StationLimits, modes: OperationModes) -> Self {
185 Self { limits, modes }
186 }
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
193pub struct Setpoint(Decimal);
194
195impl Setpoint {
196 pub const ZERO: Self = Self(Decimal::ZERO);
198
199 pub fn charge(rate: Decimal) -> Result<Self, V2xError> {
205 magnitude(rate).map(Self)
206 }
207
208 pub fn discharge(rate: Decimal) -> Result<Self, V2xError> {
214 magnitude(rate)
215 .and_then(|rate| rate.checked_neg().ok_or(V2xError::NegativeMagnitude))
216 .map(Self)
217 }
218
219 #[must_use]
221 pub const fn signed(self) -> Decimal {
222 self.0
223 }
224}
225
226fn magnitude(value: Decimal) -> Result<Decimal, V2xError> {
227 if value.signum() < 0 {
228 Err(V2xError::NegativeMagnitude)
229 } else {
230 Ok(value)
231 }
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub struct Operation {
237 mode: Mode,
238 setpoint: Option<Setpoint>,
239 limit: Option<Decimal>,
240 discharge_limit: Option<Decimal>,
242 evse_sleep: bool,
243 preconditioning: bool,
244}
245
246impl Operation {
247 const fn bare(mode: Mode) -> Self {
248 Self {
249 mode,
250 setpoint: None,
251 limit: None,
252 discharge_limit: None,
253 evse_sleep: false,
254 preconditioning: false,
255 }
256 }
257
258 pub fn charging_only(limit: Decimal) -> Result<Self, V2xError> {
264 Ok(Self {
265 limit: Some(magnitude(limit)?),
266 ..Self::bare(Mode::ChargingOnly)
267 })
268 }
269
270 #[must_use]
273 pub const fn central_setpoint(setpoint: Setpoint) -> Self {
274 Self {
275 setpoint: Some(setpoint),
276 ..Self::bare(Mode::CentralSetpoint)
277 }
278 }
279
280 #[must_use]
282 pub const fn external_setpoint() -> Self {
283 Self::bare(Mode::ExternalSetpoint)
284 }
285
286 #[must_use]
288 pub const fn external_limits() -> Self {
289 Self::bare(Mode::ExternalLimits)
290 }
291
292 #[must_use]
296 pub const fn local_load_balancing() -> Self {
297 Self::bare(Mode::LocalLoadBalancing)
298 }
299
300 #[must_use]
302 pub const fn idle() -> Self {
303 Self::bare(Mode::Idle)
304 }
305
306 pub fn charge_at_most(mut self, rate: Decimal) -> Result<Self, V2xError> {
314 self.allow(
315 "limit",
316 &[
317 Mode::CentralSetpoint,
318 Mode::ExternalSetpoint,
319 Mode::LocalLoadBalancing,
320 ],
321 )?;
322 self.limit = Some(magnitude(rate)?);
323 self.check_range()
324 }
325
326 pub fn discharge_at_most(mut self, rate: Decimal) -> Result<Self, V2xError> {
333 self.allow(
334 "dischargeLimit",
335 &[
336 Mode::CentralSetpoint,
337 Mode::ExternalSetpoint,
338 Mode::LocalLoadBalancing,
339 ],
340 )?;
341 self.discharge_limit = Some(
342 magnitude(rate)?
343 .checked_neg()
344 .ok_or(V2xError::NegativeMagnitude)?,
345 );
346 self.check_range()
347 }
348
349 pub fn sleep_evse(mut self) -> Result<Self, V2xError> {
355 self.allow("evseSleep", &[Mode::Idle])?;
356 self.evse_sleep = true;
357 Ok(self)
358 }
359
360 pub fn precondition(mut self) -> Result<Self, V2xError> {
366 self.allow("preconditioningRequest", &[Mode::Idle])?;
367 self.preconditioning = true;
368 Ok(self)
369 }
370
371 pub fn with_setpoint(mut self, setpoint: Setpoint) -> Result<Self, V2xError> {
378 self.allow("setpoint", &[Mode::CentralSetpoint])?;
379 self.setpoint = Some(setpoint);
380 self.check_range()
381 }
382
383 #[must_use]
385 pub const fn mode(&self) -> Mode {
386 self.mode
387 }
388
389 #[must_use]
391 pub fn setpoint(&self) -> Option<Decimal> {
392 self.setpoint.map(Setpoint::signed)
393 }
394
395 #[must_use]
397 pub const fn limit(&self) -> Option<Decimal> {
398 self.limit
399 }
400
401 #[must_use]
403 pub const fn discharge_limit(&self) -> Option<Decimal> {
404 self.discharge_limit
405 }
406
407 fn allow(&self, field: &'static str, modes: &[Mode]) -> Result<(), V2xError> {
408 if modes.contains(&self.mode) {
409 Ok(())
410 } else {
411 Err(V2xError::NotInMode {
412 field,
413 mode: self.mode,
414 })
415 }
416 }
417
418 fn check_range(self) -> Result<Self, V2xError> {
420 if let Some(setpoint) = self.setpoint() {
421 let above = self.limit.is_some_and(|limit| setpoint > limit);
422 let below = self.discharge_limit.is_some_and(|floor| setpoint < floor);
423 if above || below {
424 return Err(V2xError::SetpointOutsideLimits);
425 }
426 }
427 Ok(self)
428 }
429
430 fn to_period(self, start: i32) -> v2_1::ChargingSchedulePeriod {
431 let mut period = v2_1::ChargingSchedulePeriod::new(start);
432 period.operation_mode = Some(self.mode.to_wire());
433 period.setpoint = self.setpoint();
434 period.limit = self.limit;
435 period.discharge_limit = self.discharge_limit;
436 period.evse_sleep = self.evse_sleep.then_some(true);
437 period.preconditioning_request = self.preconditioning.then_some(true);
438 period
439 }
440
441 fn to_update(self) -> v2_1::ChargingScheduleUpdate {
442 let mut update = v2_1::ChargingScheduleUpdate::new();
443 update.setpoint = self.setpoint();
444 update.limit = self.limit;
445 update.discharge_limit = self.discharge_limit;
446 update
447 }
448}
449
450#[derive(Clone, Debug, PartialEq, Eq)]
452#[non_exhaustive]
453pub enum V2xError {
454 NegativeMagnitude,
456 SetpointOutsideLimits,
458 NotInMode {
460 field: &'static str,
462 mode: Mode,
464 },
465 UnsupportedMode(Mode),
467 TooManyPeriods {
469 periods: usize,
471 max: usize,
473 },
474 StackLevel {
476 requested: i32,
478 max: i32,
480 },
481 TxProfileOnEvseZero,
483 UnitNotAllowed(RateUnit),
485 Empty,
487 TooManySlots(usize),
489 BadDuration,
491 ModeChanged {
493 from: Mode,
495 to: Mode,
497 },
498 OutOfRange(&'static str),
500}
501
502impl fmt::Display for V2xError {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 match self {
505 Self::NegativeMagnitude => {
506 f.write_str("a rate is a magnitude; say charge or discharge instead of a sign")
507 }
508 Self::SetpointOutsideLimits => {
509 f.write_str("the setpoint lies outside [dischargeLimit, limit] (V2X.05)")
510 }
511 Self::NotInMode { field, mode } => write!(f, "{mode} does not take {field}"),
512 Self::UnsupportedMode(mode) => {
513 write!(f, "the station does not support operation mode {mode}")
514 }
515 Self::TooManyPeriods { periods, max } => write!(
516 f,
517 "{periods} periods, the station allows {max}; setpoints are not merged"
518 ),
519 Self::StackLevel { requested, max } => write!(
520 f,
521 "stack level {requested} is above the station's ProfileStackLevel {max}"
522 ),
523 Self::TxProfileOnEvseZero => f.write_str("a TxProfile needs an EVSE above 0"),
524 Self::UnitNotAllowed(unit) => write!(f, "the station does not accept {unit}"),
525 Self::Empty => f.write_str("a V2X plan needs at least one slot"),
526 Self::TooManySlots(n) => write!(f, "{n} slots is more than a plan may hold"),
527 Self::BadDuration => f.write_str("a duration is outside 1 s ..= i32::MAX s"),
528 Self::ModeChanged { from, to } => write!(
529 f,
530 "an update cannot change {from} into {to}; send a new profile"
531 ),
532 Self::OutOfRange(field) => write!(f, "{field} does not fit the wire's integer"),
533 }
534 }
535}
536
537#[cfg(feature = "std")]
538impl std::error::Error for V2xError {}
539
540fn seconds(duration: Duration) -> Result<i32, V2xError> {
541 i32::try_from(duration.as_secs())
542 .ok()
543 .filter(|seconds| *seconds >= 1)
544 .ok_or(V2xError::BadDuration)
545}
546
547fn profile(
549 id: i32,
550 stack_level: i32,
551 target: Target,
552 kind: v2_1::ChargingProfileKind,
553 schedule: v2_1::ChargingSchedule,
554 station: &V2xStation,
555) -> Result<v2_1::SetChargingProfileRequest, V2xError> {
556 if stack_level > station.limits.max_stack_level {
557 return Err(V2xError::StackLevel {
558 requested: stack_level,
559 max: station.limits.max_stack_level,
560 });
561 }
562 let unit = match schedule.charging_rate_unit {
563 v2_1::ChargingRateUnit::A => RateUnit::A,
564 _ => RateUnit::W,
565 };
566 let allowed = match unit {
567 RateUnit::A => station.limits.units.amperes,
568 RateUnit::W => station.limits.units.watts,
569 };
570 if !allowed {
571 return Err(V2xError::UnitNotAllowed(unit));
572 }
573 let (purpose, evse, transaction) = match target {
574 Target::Transaction {
575 evse_id,
576 transaction_id,
577 } => {
578 if evse_id == 0 {
579 return Err(V2xError::TxProfileOnEvseZero);
580 }
581 (
582 v2_1::ChargingProfilePurpose::TxProfile,
583 evse_id,
584 Some(transaction_id),
585 )
586 }
587 Target::EvseDefault { evse_id } => (
588 v2_1::ChargingProfilePurpose::TxDefaultProfile,
589 evse_id,
590 None,
591 ),
592 };
593 let mut wire =
594 v2_1::ChargingProfile::new(id, stack_level, purpose, kind, alloc::vec![schedule]);
595 wire.transaction_id = transaction;
596 let evse = i32::try_from(evse).map_err(|_| V2xError::OutOfRange("evseId"))?;
597 Ok(v2_1::SetChargingProfileRequest::new(evse, wire))
598}
599
600const fn wire_unit(unit: RateUnit) -> v2_1::ChargingRateUnit {
601 match unit {
602 RateUnit::A => v2_1::ChargingRateUnit::A,
603 RateUnit::W => v2_1::ChargingRateUnit::W,
604 }
605}
606
607#[derive(Clone, Debug, PartialEq)]
609pub struct V2xPlan {
610 start: DateTime,
611 slot: i32,
612 operations: Vec<Operation>,
613}
614
615impl V2xPlan {
616 pub fn new(
623 start: DateTime,
624 slot: Duration,
625 operations: impl IntoIterator<Item = Operation>,
626 ) -> Result<Self, V2xError> {
627 let operations: Vec<Operation> = operations.into_iter().collect();
628 if operations.is_empty() {
629 return Err(V2xError::Empty);
630 }
631 if operations.len() > ChargingPlan::MAX_SLOTS {
632 return Err(V2xError::TooManySlots(operations.len()));
633 }
634 let slot = seconds(slot)?;
635 let slots = i32::try_from(operations.len()).map_err(|_| V2xError::BadDuration)?;
636 slot.checked_mul(slots).ok_or(V2xError::BadDuration)?;
637 Ok(Self {
638 start,
639 slot,
640 operations,
641 })
642 }
643
644 #[must_use]
646 pub fn operations(&self) -> &[Operation] {
647 &self.operations
648 }
649
650 pub fn to_request(
658 &self,
659 id: i32,
660 stack_level: i32,
661 target: Target,
662 unit: RateUnit,
663 station: &V2xStation,
664 ) -> Result<v2_1::SetChargingProfileRequest, V2xError> {
665 if let Some(op) = self
666 .operations
667 .iter()
668 .find(|op| !station.modes.contains(op.mode))
669 {
670 return Err(V2xError::UnsupportedMode(op.mode));
671 }
672 let mut periods: Vec<v2_1::ChargingSchedulePeriod> = Vec::new();
673 let mut previous: Option<&Operation> = None;
674 for (index, operation) in self.operations.iter().enumerate() {
675 if previous == Some(operation) {
676 continue;
677 }
678 previous = Some(operation);
679 let start = self.slot * i32::try_from(index).unwrap_or(i32::MAX);
681 periods.push(operation.to_period(start));
682 }
683 if periods.len() > station.limits.max_periods {
684 return Err(V2xError::TooManyPeriods {
685 periods: periods.len(),
686 max: station.limits.max_periods,
687 });
688 }
689 let mut schedule = v2_1::ChargingSchedule::new(id, wire_unit(unit), periods);
690 schedule.start_schedule = Some(self.start);
691 schedule.duration =
692 Some(self.slot * i32::try_from(self.operations.len()).unwrap_or(i32::MAX));
693 profile(
694 id,
695 stack_level,
696 target,
697 v2_1::ChargingProfileKind::Absolute,
698 schedule,
699 station,
700 )
701 }
702}
703
704#[derive(Clone, Debug, PartialEq)]
709pub struct DynamicSetpoint {
710 id: i32,
711 stack_level: i32,
712 target: Target,
713 unit: RateUnit,
714 operation: Operation,
715 fallback: i32,
716 pull_every: Option<i32>,
717}
718
719impl DynamicSetpoint {
720 pub fn new(
727 id: i32,
728 target: Target,
729 unit: RateUnit,
730 operation: Operation,
731 fallback_after: Duration,
732 ) -> Result<Self, V2xError> {
733 Ok(Self {
734 id,
735 stack_level: 0,
736 target,
737 unit,
738 operation,
739 fallback: seconds(fallback_after)?,
740 pull_every: None,
741 })
742 }
743
744 #[must_use]
746 pub const fn stack_level(mut self, stack_level: i32) -> Self {
747 self.stack_level = stack_level;
748 self
749 }
750
751 pub fn pull_every(mut self, interval: Duration) -> Result<Self, V2xError> {
758 self.pull_every = Some(seconds(interval)?);
759 Ok(self)
760 }
761
762 #[must_use]
764 pub const fn operation(&self) -> &Operation {
765 &self.operation
766 }
767
768 #[must_use]
770 pub const fn id(&self) -> i32 {
771 self.id
772 }
773
774 pub fn to_request(
781 &self,
782 station: &V2xStation,
783 ) -> Result<v2_1::SetChargingProfileRequest, V2xError> {
784 if !station.modes.contains(self.operation.mode) {
785 return Err(V2xError::UnsupportedMode(self.operation.mode));
786 }
787 let mut schedule = v2_1::ChargingSchedule::new(
788 self.id,
789 wire_unit(self.unit),
790 alloc::vec![self.operation.to_period(0)],
791 );
792 schedule.duration = Some(self.fallback);
793 let mut request = profile(
794 self.id,
795 self.stack_level,
796 self.target.clone(),
797 v2_1::ChargingProfileKind::Dynamic,
798 schedule,
799 station,
800 )?;
801 request.charging_profile.dyn_update_interval = self.pull_every;
802 Ok(request)
803 }
804
805 pub fn update(
812 &mut self,
813 next: Operation,
814 ) -> Result<v2_1::UpdateDynamicScheduleRequest, V2xError> {
815 if next.mode != self.operation.mode {
816 return Err(V2xError::ModeChanged {
817 from: self.operation.mode,
818 to: next.mode,
819 });
820 }
821 self.operation = next;
822 Ok(v2_1::UpdateDynamicScheduleRequest::new(
823 self.id,
824 next.to_update(),
825 ))
826 }
827
828 pub fn update_setpoint(
834 &mut self,
835 setpoint: Setpoint,
836 ) -> Result<v2_1::UpdateDynamicScheduleRequest, V2xError> {
837 let next = self.operation.with_setpoint(setpoint)?;
838 self.update(next)
839 }
840
841 #[must_use]
844 pub fn pull_response(&self) -> v2_1::PullDynamicScheduleUpdateResponse {
845 let mut response =
846 v2_1::PullDynamicScheduleUpdateResponse::new(v2_1::ChargingProfileStatus::Accepted);
847 response.schedule_update = Some(self.operation.to_update());
848 response
849 }
850}
851
852impl EvNeeds {
853 #[must_use]
858 pub fn clamp_watts(&self, setpoint: Setpoint) -> Setpoint {
859 let value = setpoint.signed();
860 if value.signum() >= 0 {
861 Setpoint(self.max_charge.map_or(value, |max| value.min(max)))
862 } else if !self.bidirectional {
863 Setpoint::ZERO
864 } else {
865 let floor = self.max_discharge.and_then(Decimal::checked_neg);
866 Setpoint(floor.map_or(value, |floor| value.max(floor)))
867 }
868 }
869}
870
871#[cfg(test)]
872mod tests {
873 use super::*;
874 use crate::smart_charging::RateUnits;
875
876 fn w(value: i64) -> Decimal {
877 Decimal::from(value)
878 }
879
880 fn station(modes: &str) -> V2xStation {
881 V2xStation::new(
882 StationLimits::new(10, 3, RateUnits::BOTH),
883 OperationModes::parse(modes),
884 )
885 }
886
887 fn start() -> DateTime {
888 "2026-11-20T00:00:00Z".parse().unwrap()
889 }
890
891 const ALL: &str =
892 "ChargingOnly,CentralSetpoint,ExternalSetpoint,ExternalLimits,LocalLoadBalancing,Idle";
893
894 #[test]
895 fn signs_reach_the_wire_as_block_q_wants_them() {
896 let op = Operation::central_setpoint(Setpoint::discharge(w(5000)).unwrap())
897 .discharge_at_most(w(6000))
898 .unwrap()
899 .charge_at_most(w(11000))
900 .unwrap();
901 let period = op.to_period(0);
902 assert_eq!(period.setpoint, Some(w(-5000)));
903 assert_eq!(period.discharge_limit, Some(w(-6000)));
904 assert_eq!(period.limit, Some(w(11000)));
905 assert_eq!(
906 period.operation_mode,
907 Some(v2_1::OperationMode::CentralSetpoint)
908 );
909 assert_eq!(Setpoint::charge(w(3700)).unwrap().signed(), w(3700));
910 assert_eq!(Setpoint::discharge(w(-1)), Err(V2xError::NegativeMagnitude));
911 assert_eq!(
912 Operation::central_setpoint(Setpoint::ZERO).discharge_at_most(w(-5)),
913 Err(V2xError::NegativeMagnitude)
914 );
915 assert_eq!(Setpoint::charge(Decimal::ZERO).unwrap(), Setpoint::ZERO);
916 }
917
918 #[test]
919 fn a_setpoint_outside_its_limits_is_refused_v2x_05() {
920 let discharge = Operation::central_setpoint(Setpoint::discharge(w(7000)).unwrap());
921 assert_eq!(
922 discharge.discharge_at_most(w(6000)),
923 Err(V2xError::SetpointOutsideLimits)
924 );
925 let charge = Operation::central_setpoint(Setpoint::charge(w(1)).unwrap());
926 assert_eq!(
927 charge.charge_at_most(Decimal::ZERO),
928 Err(V2xError::SetpointOutsideLimits)
929 );
930 let bounded = Operation::central_setpoint(Setpoint::ZERO)
931 .charge_at_most(w(1000))
932 .unwrap();
933 assert_eq!(
934 bounded.with_setpoint(Setpoint::charge(w(2000)).unwrap()),
935 Err(V2xError::SetpointOutsideLimits)
936 );
937 }
938
939 #[test]
940 fn each_mode_takes_only_its_fields() {
941 let idle = Operation::idle()
942 .sleep_evse()
943 .unwrap()
944 .precondition()
945 .unwrap();
946 let period = idle.to_period(0);
947 assert_eq!(
948 (
949 period.limit,
950 period.discharge_limit,
951 period.setpoint,
952 period.setpoint_reactive
953 ),
954 (None, None, None, None),
955 "Q10.FR.01"
956 );
957 assert_eq!(
958 (period.evse_sleep, period.preconditioning_request),
959 (Some(true), Some(true))
960 );
961 assert!(matches!(
962 Operation::idle().charge_at_most(w(1)),
963 Err(V2xError::NotInMode { field: "limit", .. })
964 ));
965 assert!(matches!(
966 Operation::external_limits().discharge_at_most(w(1)),
967 Err(V2xError::NotInMode { .. })
968 ));
969 assert!(matches!(
970 Operation::charging_only(w(1)).unwrap().sleep_evse(),
971 Err(V2xError::NotInMode {
972 field: "evseSleep",
973 ..
974 })
975 ));
976 assert!(matches!(
977 Operation::local_load_balancing().with_setpoint(Setpoint::ZERO),
978 Err(V2xError::NotInMode {
979 field: "setpoint",
980 ..
981 })
982 ));
983 assert!(
984 Operation::local_load_balancing()
985 .charge_at_most(w(9000))
986 .is_ok(),
987 "Q09.FR.05"
988 );
989 let charging = Operation::charging_only(w(11000)).unwrap().to_period(0);
990 assert_eq!((charging.limit, charging.setpoint), (Some(w(11000)), None));
991 }
992
993 #[test]
994 #[allow(clippy::too_many_lines)]
995 fn a_plan_merges_neighbours_and_honours_the_station() {
996 let charge = Operation::charging_only(w(11000)).unwrap();
997 let plan = V2xPlan::new(
998 start(),
999 Duration::from_secs(900),
1000 [charge, charge, Operation::idle(), charge],
1001 )
1002 .unwrap();
1003 let request = plan
1004 .to_request(
1005 1,
1006 1,
1007 Target::transaction(1, "tx"),
1008 RateUnit::W,
1009 &station(ALL),
1010 )
1011 .unwrap();
1012 let profile = &request.charging_profile;
1013 let starts: Vec<i32> = profile.charging_schedule[0]
1014 .charging_schedule_period
1015 .iter()
1016 .map(|p| p.start_period)
1017 .collect();
1018 assert_eq!(starts, [0, 1800, 2700]);
1019 assert_eq!(profile.charging_schedule[0].duration, Some(3600));
1020 assert_eq!(
1021 profile.charging_profile_kind,
1022 v2_1::ChargingProfileKind::Absolute
1023 );
1024 assert_eq!(profile.transaction_id.as_deref(), Some("tx"));
1025 assert_eq!(request.evse_id, 1);
1026
1027 let llb = V2xPlan::new(
1028 start(),
1029 Duration::from_secs(900),
1030 [Operation::local_load_balancing()],
1031 )
1032 .unwrap();
1033 assert_eq!(
1034 llb.to_request(
1035 1,
1036 1,
1037 Target::transaction(1, "tx"),
1038 RateUnit::W,
1039 &station("ChargingOnly,CentralSetpoint")
1040 ),
1041 Err(V2xError::UnsupportedMode(Mode::LocalLoadBalancing))
1042 );
1043 let many = V2xPlan::new(
1044 start(),
1045 Duration::from_secs(60),
1046 (0..11).map(|n| Operation::charging_only(w(1000 + n)).unwrap()),
1047 )
1048 .unwrap();
1049 assert_eq!(
1050 many.to_request(
1051 1,
1052 1,
1053 Target::transaction(1, "tx"),
1054 RateUnit::W,
1055 &station(ALL)
1056 ),
1057 Err(V2xError::TooManyPeriods {
1058 periods: 11,
1059 max: 10
1060 })
1061 );
1062 let one = V2xPlan::new(start(), Duration::from_secs(60), [charge]).unwrap();
1063 assert_eq!(
1064 one.to_request(
1065 1,
1066 4,
1067 Target::transaction(1, "tx"),
1068 RateUnit::W,
1069 &station(ALL)
1070 ),
1071 Err(V2xError::StackLevel {
1072 requested: 4,
1073 max: 3
1074 })
1075 );
1076 let watts_only = V2xStation::new(
1077 StationLimits::new(10, 3, RateUnits::parse_v2("W")),
1078 OperationModes::MANDATORY,
1079 );
1080 assert_eq!(
1081 one.to_request(1, 1, Target::transaction(1, "tx"), RateUnit::A, &watts_only),
1082 Err(V2xError::UnitNotAllowed(RateUnit::A))
1083 );
1084 assert_eq!(
1085 one.to_request(
1086 1,
1087 1,
1088 Target::transaction(0, "tx"),
1089 RateUnit::W,
1090 &station(ALL)
1091 ),
1092 Err(V2xError::TxProfileOnEvseZero)
1093 );
1094 assert_eq!(
1095 V2xPlan::new(start(), Duration::from_secs(60), []),
1096 Err(V2xError::Empty)
1097 );
1098 }
1099
1100 #[test]
1101 fn operation_modes_read_the_member_list() {
1102 let modes = OperationModes::parse(
1103 "ChargingOnly, CentralSetpoint,CentralFrequency,LocalLoadBalancing",
1104 );
1105 assert!(modes.contains(Mode::LocalLoadBalancing));
1106 assert!(!modes.contains(Mode::Idle));
1107 assert!(OperationModes::MANDATORY.contains(Mode::CentralSetpoint));
1108 assert!(!OperationModes::MANDATORY.contains(Mode::Idle));
1109 }
1110
1111 #[test]
1112 fn a_dynamic_setpoint_has_a_fallback_and_one_period() {
1113 let mut follow = DynamicSetpoint::new(
1114 10,
1115 Target::transaction(1, "tx"),
1116 RateUnit::W,
1117 Operation::central_setpoint(Setpoint::ZERO)
1118 .charge_at_most(w(11000))
1119 .unwrap(),
1120 Duration::from_secs(30),
1121 )
1122 .unwrap()
1123 .stack_level(2)
1124 .pull_every(Duration::from_secs(60))
1125 .unwrap();
1126 let request = follow.to_request(&station(ALL)).unwrap();
1127 let profile = &request.charging_profile;
1128 assert_eq!(
1129 profile.charging_profile_kind,
1130 v2_1::ChargingProfileKind::Dynamic
1131 );
1132 assert_eq!(profile.charging_schedule.len(), 1, "K28.FR.01");
1133 assert_eq!(
1134 profile.charging_schedule[0].charging_schedule_period.len(),
1135 1
1136 );
1137 assert_eq!(
1138 profile.charging_schedule[0].charging_schedule_period[0].start_period, 0,
1139 "K28.FR.02"
1140 );
1141 assert_eq!(profile.charging_schedule[0].duration, Some(30), "K28.FR.13");
1142 assert_eq!(profile.dyn_update_interval, Some(60));
1143 assert_eq!(profile.stack_level, 2);
1144
1145 let update = follow
1146 .update_setpoint(Setpoint::charge(w(2000)).unwrap())
1147 .unwrap();
1148 assert_eq!(update.charging_profile_id, 10);
1149 assert_eq!(update.schedule_update.setpoint, Some(w(2000)));
1150 assert_eq!(update.schedule_update.limit, Some(w(11000)));
1151 assert_eq!(
1152 follow.update_setpoint(Setpoint::charge(w(12000)).unwrap()),
1153 Err(V2xError::SetpointOutsideLimits)
1154 );
1155 assert_eq!(
1156 follow.operation().setpoint(),
1157 Some(w(2000)),
1158 "a refused update changes nothing"
1159 );
1160 assert_eq!(
1161 follow.update(Operation::idle()),
1162 Err(V2xError::ModeChanged {
1163 from: Mode::CentralSetpoint,
1164 to: Mode::Idle
1165 })
1166 );
1167 let pull = follow.pull_response();
1168 assert_eq!(pull.status, v2_1::ChargingProfileStatus::Accepted);
1169 assert_eq!(pull.schedule_update.unwrap().setpoint, Some(w(2000)));
1170
1171 assert_eq!(
1172 DynamicSetpoint::new(
1173 1,
1174 Target::transaction(1, "tx"),
1175 RateUnit::W,
1176 Operation::idle(),
1177 Duration::ZERO
1178 ),
1179 Err(V2xError::BadDuration)
1180 );
1181 let plain = DynamicSetpoint::new(
1182 1,
1183 Target::transaction(1, "tx"),
1184 RateUnit::W,
1185 Operation::idle(),
1186 Duration::from_secs(5),
1187 )
1188 .unwrap()
1189 .to_request(&station(ALL))
1190 .unwrap();
1191 assert_eq!(
1192 plain.charging_profile.dyn_update_interval, None,
1193 "K28.FR.04 only when asked"
1194 );
1195 }
1196
1197 fn needs(json: &str) -> EvNeeds {
1198 EvNeeds::from_v2_1(&serde_json::from_str(json).unwrap())
1199 }
1200
1201 #[test]
1202 fn a_setpoint_is_clamped_to_what_the_ev_can_do() {
1203 let ev = needs(
1204 r#"{"requestedEnergyTransfer":"AC_BPT","v2xChargingParameters":{
1205 "maxChargePower":11000,"maxDischargePower":2000,"maxDischargePower_L2":2000,
1206 "maxDischargePower_L3":2000}}"#,
1207 );
1208 assert_eq!(
1209 ev.clamp_watts(Setpoint::charge(w(22000)).unwrap()),
1210 Setpoint::charge(w(11000)).unwrap()
1211 );
1212 assert_eq!(
1213 ev.clamp_watts(Setpoint::discharge(w(9000)).unwrap()),
1214 Setpoint::discharge(w(6000)).unwrap()
1215 );
1216
1217 let plain = needs(r#"{"requestedEnergyTransfer":"AC_three_phase"}"#);
1218 assert!(!plain.bidirectional);
1219 assert_eq!(
1220 plain.clamp_watts(Setpoint::discharge(w(1000)).unwrap()),
1221 Setpoint::ZERO
1222 );
1223 }
1224}