1use core::fmt;
4
5#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
6use alloc::{string::ToString, vec::Vec};
7
8use super::Purpose;
9#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
10use super::{Period, Profile, ProfileKind, RateUnit, Recurrency, Schedule};
11use crate::version::Version;
12
13#[derive(Clone, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum ConversionError {
70 TransactionIdNotInteger(alloc::string::String),
72 PurposeNotInVersion {
74 purpose: Purpose,
76 version: Version,
78 },
79 UnmodelledKind(&'static str),
81 UnknownValue {
83 field: &'static str,
85 value: alloc::string::String,
87 },
88 NoSchedule,
90 SchedulesNotInVersion(usize),
92 PeriodWithoutLimit {
94 period: usize,
96 },
97 UnmodelledField {
99 field: &'static str,
101 period: Option<usize>,
103 },
104 OutOfRange {
106 field: &'static str,
108 },
109}
110
111impl fmt::Display for ConversionError {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 match self {
114 Self::TransactionIdNotInteger(id) => write!(
116 f,
117 "transaction id {id:?} is not an integer, which a 1.6 TxProfile needs"
118 ),
119 Self::PurposeNotInVersion { purpose, version } => {
120 write!(f, "OCPP {version} has no {purpose:?} purpose")
121 }
122 Self::UnmodelledKind(kind) => write!(f, "{kind} profiles are not modelled"),
123 Self::UnknownValue { field, value } => {
124 write!(f, "{field} {value:?} is not a value any version defines")
125 }
126 Self::NoSchedule => f.write_str("the profile has no schedule"),
127 Self::SchedulesNotInVersion(n) => {
128 write!(f, "OCPP 1.6 carries one schedule per profile, not {n}")
129 }
130 Self::PeriodWithoutLimit { period } => {
131 write!(
132 f,
133 "period {period} has no limit (a setpoint operation mode)"
134 )
135 }
136 Self::UnmodelledField {
137 field,
138 period: Some(period),
139 } => write!(
140 f,
141 "period {period} sets {field}, which is not a plain ceiling"
142 ),
143 Self::UnmodelledField {
144 field,
145 period: None,
146 } => write!(f, "{field} is set, which is not a plain ceiling"),
147 Self::OutOfRange { field } => write!(f, "{field} does not fit the wire's integer"),
148 }
149 }
150}
151
152#[cfg(feature = "std")]
153impl std::error::Error for ConversionError {}
154
155#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
156fn to_i32(value: i64, field: &'static str) -> Result<i32, ConversionError> {
157 i32::try_from(value).map_err(|_| ConversionError::OutOfRange { field })
158}
159
160#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
162macro_rules! enum_mappings {
163 ($module:ident, $version:expr, { $($domain:ident <=> $wire:ident),* $(,)? }) => {
164 fn purpose_to_wire(purpose: Purpose) -> Result<crate::$module::ChargingProfilePurpose, ConversionError> {
165 match purpose {
166 $(Purpose::$domain => Ok(crate::$module::ChargingProfilePurpose::$wire),)*
167 #[allow(unreachable_patterns)]
168 other => Err(ConversionError::PurposeNotInVersion { purpose: other, version: $version }),
169 }
170 }
171
172 fn purpose_from_wire(purpose: &crate::$module::ChargingProfilePurpose) -> Result<Purpose, ConversionError> {
173 match purpose {
174 $(crate::$module::ChargingProfilePurpose::$wire => Ok(Purpose::$domain),)*
175 other => Err(ConversionError::UnknownValue {
176 field: "chargingProfilePurpose",
177 value: other.as_str().to_string(),
178 }),
179 }
180 }
181
182 fn kind_to_wire(kind: ProfileKind) -> crate::$module::ChargingProfileKind {
183 match kind {
184 ProfileKind::Absolute => crate::$module::ChargingProfileKind::Absolute,
185 ProfileKind::Recurring => crate::$module::ChargingProfileKind::Recurring,
186 ProfileKind::Relative => crate::$module::ChargingProfileKind::Relative,
187 }
188 }
189
190 fn kind_from_wire(kind: &crate::$module::ChargingProfileKind) -> Result<ProfileKind, ConversionError> {
191 match kind {
192 crate::$module::ChargingProfileKind::Absolute => Ok(ProfileKind::Absolute),
193 crate::$module::ChargingProfileKind::Recurring => Ok(ProfileKind::Recurring),
194 crate::$module::ChargingProfileKind::Relative => Ok(ProfileKind::Relative),
195 #[allow(unreachable_patterns)]
196 crate::$module::ChargingProfileKind::UnknownValue(value) => Err(ConversionError::UnknownValue {
197 field: "chargingProfileKind",
198 value: value.clone(),
199 }),
200 #[allow(unreachable_patterns)]
201 other => Err(ConversionError::UnmodelledKind(kind_name(other.as_str()))),
202 }
203 }
204
205 fn recurrency_to_wire(recurrency: Recurrency) -> crate::$module::RecurrencyKind {
206 match recurrency {
207 Recurrency::Daily => crate::$module::RecurrencyKind::Daily,
208 Recurrency::Weekly => crate::$module::RecurrencyKind::Weekly,
209 }
210 }
211
212 fn recurrency_from_wire(recurrency: &crate::$module::RecurrencyKind) -> Result<Recurrency, ConversionError> {
213 match recurrency {
214 crate::$module::RecurrencyKind::Daily => Ok(Recurrency::Daily),
215 crate::$module::RecurrencyKind::Weekly => Ok(Recurrency::Weekly),
216 other => Err(ConversionError::UnknownValue {
217 field: "recurrencyKind",
218 value: other.as_str().to_string(),
219 }),
220 }
221 }
222
223 fn unit_to_wire(unit: RateUnit) -> crate::$module::ChargingRateUnit {
224 match unit {
225 RateUnit::A => crate::$module::ChargingRateUnit::A,
226 RateUnit::W => crate::$module::ChargingRateUnit::W,
227 }
228 }
229
230 fn unit_from_wire(unit: &crate::$module::ChargingRateUnit) -> Result<RateUnit, ConversionError> {
231 match unit {
232 crate::$module::ChargingRateUnit::A => Ok(RateUnit::A),
233 crate::$module::ChargingRateUnit::W => Ok(RateUnit::W),
234 other => Err(ConversionError::UnknownValue {
235 field: "chargingRateUnit",
236 value: other.as_str().to_string(),
237 }),
238 }
239 }
240 };
241}
242
243#[cfg(any(feature = "v1_6", feature = "v2_0_1", feature = "v2_1"))]
245fn kind_name(kind: &str) -> &'static str {
246 if kind == "Dynamic" {
247 "Dynamic"
248 } else {
249 "unknown"
250 }
251}
252
253#[cfg(feature = "v1_6")]
254mod v1_6_wire {
255 use super::{
256 ConversionError, Period, Profile, ProfileKind, Purpose, RateUnit, Recurrency, Schedule,
257 ToString, Vec, Version, kind_name, to_i32,
258 };
259 use crate::v1_6;
260
261 enum_mappings!(v1_6, Version::V1_6, {
262 ChargingStationMaxProfile <=> ChargePointMaxProfile,
263 TxDefaultProfile <=> TxDefaultProfile,
264 TxProfile <=> TxProfile,
265 });
266
267 impl Profile {
268 pub fn to_v1_6(&self) -> Result<v1_6::ChargingProfile, ConversionError> {
275 let schedule = match self.schedules.as_slice() {
276 [] => return Err(ConversionError::NoSchedule),
277 [one] => one,
278 many => return Err(ConversionError::SchedulesNotInVersion(many.len())),
279 };
280 let mut periods = Vec::with_capacity(schedule.periods.len());
281 for (index, period) in schedule.periods.iter().enumerate() {
282 if period.phase_to_use.is_some() {
283 return Err(ConversionError::UnmodelledField {
284 field: "phaseToUse",
285 period: Some(index),
286 });
287 }
288 let mut wire = v1_6::ChargingSchedulePeriod::new(
289 to_i32(period.start_period, "startPeriod")?,
290 period.limit,
291 );
292 wire.number_phases = period.number_phases;
293 periods.push(wire);
294 }
295 let mut wire_schedule =
296 v1_6::ChargingSchedule::new(unit_to_wire(schedule.rate_unit), periods);
297 wire_schedule.duration = schedule
298 .duration
299 .map(|d| to_i32(d, "duration"))
300 .transpose()?;
301 wire_schedule.start_schedule = schedule.start;
302 wire_schedule.min_charging_rate = schedule.min_charging_rate;
303
304 let mut profile = v1_6::ChargingProfile::new(
305 self.id,
306 self.stack_level,
307 purpose_to_wire(self.purpose)?,
308 kind_to_wire(self.kind),
309 wire_schedule,
310 );
311 profile.transaction_id = self
312 .transaction_id
313 .as_ref()
314 .map(|id| {
315 id.parse::<i32>()
316 .map_err(|_| ConversionError::TransactionIdNotInteger(id.clone()))
317 })
318 .transpose()?;
319 profile.recurrency_kind = self.recurrency.map(recurrency_to_wire);
320 profile.valid_from = self.valid_from;
321 profile.valid_to = self.valid_to;
322 Ok(profile)
323 }
324
325 pub fn set_request_v1_6(&self) -> Result<v1_6::SetChargingProfileRequest, ConversionError> {
332 let connector =
333 i32::try_from(self.evse_id).map_err(|_| ConversionError::OutOfRange {
334 field: "connectorId",
335 })?;
336 Ok(v1_6::SetChargingProfileRequest::new(
337 connector,
338 self.to_v1_6()?,
339 ))
340 }
341
342 pub fn from_v1_6(
350 wire: &v1_6::ChargingProfile,
351 connector_id: u32,
352 ) -> Result<Self, ConversionError> {
353 let schedule = &wire.charging_schedule;
354 let periods = schedule
355 .charging_schedule_period
356 .iter()
357 .map(|period| Period {
358 start_period: i64::from(period.start_period),
359 limit: period.limit,
360 number_phases: period.number_phases,
361 phase_to_use: None,
362 })
363 .collect();
364 let mut domain = Schedule::new(
367 wire.charging_profile_id,
368 unit_from_wire(&schedule.charging_rate_unit)?,
369 periods,
370 );
371 domain.start = schedule.start_schedule;
372 domain.duration = schedule.duration.map(i64::from);
373 domain.min_charging_rate = schedule.min_charging_rate;
374 Ok(Self {
375 id: wire.charging_profile_id,
376 stack_level: wire.stack_level,
377 purpose: purpose_from_wire(&wire.charging_profile_purpose)?,
378 kind: kind_from_wire(&wire.charging_profile_kind)?,
379 recurrency: wire
380 .recurrency_kind
381 .as_ref()
382 .map(recurrency_from_wire)
383 .transpose()?,
384 valid_from: wire.valid_from,
385 valid_to: wire.valid_to,
386 transaction_id: wire.transaction_id.map(|id| id.to_string()),
387 evse_id: connector_id,
388 schedules: alloc::vec![domain],
389 })
390 }
391 }
392}
393
394#[cfg(any(feature = "v2_0_1", feature = "v2_1"))]
396macro_rules! wire_2x {
397 (
398 $module:ident, $version:expr, $to:ident, $set:ident, $from:ident,
399 { $($domain:ident <=> $wire:ident),* $(,)? },
400 period_to_wire: $period_to:expr,
401 period_from_wire: $period_from:expr,
402 schedule_check: $schedule_check:expr $(,)?
403 ) => {
404 use super::{
405 ConversionError, Period, Profile, ProfileKind, Purpose, RateUnit, Recurrency, Schedule,
406 ToString, Vec, Version, kind_name, to_i32,
407 };
408 use crate::$module;
409
410 enum_mappings!($module, $version, { $($domain <=> $wire),* });
411
412 impl Profile {
413 #[doc = concat!("This profile as an OCPP ", stringify!($module), " `ChargingProfile`.")]
414 pub fn $to(&self) -> Result<$module::ChargingProfile, ConversionError> {
420 if self.schedules.is_empty() {
421 return Err(ConversionError::NoSchedule);
422 }
423 let mut schedules = Vec::with_capacity(self.schedules.len());
424 for schedule in &self.schedules {
425 let periods = schedule
426 .periods
427 .iter()
428 .map($period_to)
429 .collect::<Result<Vec<_>, _>>()?;
430 let mut wire =
431 $module::ChargingSchedule::new(schedule.id, unit_to_wire(schedule.rate_unit), periods);
432 wire.start_schedule = schedule.start;
433 wire.duration = schedule.duration.map(|d| to_i32(d, "duration")).transpose()?;
434 wire.min_charging_rate = schedule.min_charging_rate;
435 schedules.push(wire);
436 }
437 let mut profile = $module::ChargingProfile::new(
438 self.id,
439 self.stack_level,
440 purpose_to_wire(self.purpose)?,
441 kind_to_wire(self.kind),
442 schedules,
443 );
444 profile.transaction_id = self.transaction_id.clone();
445 profile.recurrency_kind = self.recurrency.map(recurrency_to_wire);
446 profile.valid_from = self.valid_from;
447 profile.valid_to = self.valid_to;
448 Ok(profile)
449 }
450
451 #[doc = concat!("This profile as an OCPP ", stringify!($module), " `SetChargingProfileRequest` for EVSE [`evse_id`](Self::evse_id).")]
452 #[doc = concat!("As [`", stringify!($to), "`](Self::", stringify!($to), "), and for an EVSE id out of range.")]
456 pub fn $set(&self) -> Result<$module::SetChargingProfileRequest, ConversionError> {
457 let evse = i32::try_from(self.evse_id)
458 .map_err(|_| ConversionError::OutOfRange { field: "evseId" })?;
459 Ok($module::SetChargingProfileRequest::new(evse, self.$to()?))
460 }
461
462 #[doc = concat!("A profile received in an OCPP ", stringify!($module), " `SetChargingProfileRequest` for `evse_id`.")]
463 pub fn $from(wire: &$module::ChargingProfile, evse_id: u32) -> Result<Self, ConversionError> {
469 let mut schedules = Vec::with_capacity(wire.charging_schedule.len());
470 for schedule in &wire.charging_schedule {
471 $schedule_check(schedule)?;
472 let periods = schedule
473 .charging_schedule_period
474 .iter()
475 .enumerate()
476 .map($period_from)
477 .collect::<Result<Vec<_>, _>>()?;
478 let mut domain =
479 Schedule::new(schedule.id, unit_from_wire(&schedule.charging_rate_unit)?, periods);
480 domain.start = schedule.start_schedule;
481 domain.duration = schedule.duration.map(i64::from);
482 domain.min_charging_rate = schedule.min_charging_rate;
483 schedules.push(domain);
484 }
485 if schedules.is_empty() {
486 return Err(ConversionError::NoSchedule);
487 }
488 Ok(Self {
489 id: wire.id,
490 stack_level: wire.stack_level,
491 purpose: purpose_from_wire(&wire.charging_profile_purpose)?,
492 kind: kind_from_wire(&wire.charging_profile_kind)?,
493 recurrency: wire.recurrency_kind.as_ref().map(recurrency_from_wire).transpose()?,
494 valid_from: wire.valid_from,
495 valid_to: wire.valid_to,
496 transaction_id: wire.transaction_id.clone(),
497 evse_id,
498 schedules,
499 })
500 }
501 }
502 };
503}
504
505#[cfg(feature = "v2_0_1")]
506mod v2_0_1_wire {
507 wire_2x!(
508 v2_0_1, Version::V2_0_1, to_v2_0_1, set_request_v2_0_1, from_v2_0_1,
509 {
510 ChargingStationMaxProfile <=> ChargingStationMaxProfile,
511 TxDefaultProfile <=> TxDefaultProfile,
512 TxProfile <=> TxProfile,
513 ChargingStationExternalConstraints <=> ChargingStationExternalConstraints,
514 },
515 period_to_wire: |period: &Period| -> Result<v2_0_1::ChargingSchedulePeriod, ConversionError> {
516 let mut wire = v2_0_1::ChargingSchedulePeriod::new(
517 to_i32(period.start_period, "startPeriod")?,
518 period.limit,
519 );
520 wire.number_phases = period.number_phases;
521 wire.phase_to_use = period.phase_to_use;
522 Ok(wire)
523 },
524 period_from_wire: |(_, period): (usize, &v2_0_1::ChargingSchedulePeriod)| -> Result<Period, ConversionError> {
525 Ok(Period {
526 start_period: i64::from(period.start_period),
527 limit: period.limit,
528 number_phases: period.number_phases,
529 phase_to_use: period.phase_to_use,
530 })
531 },
532 schedule_check: |_: &v2_0_1::ChargingSchedule| -> Result<(), ConversionError> { Ok(()) },
533 );
534}
535
536#[cfg(feature = "v2_1")]
537mod v2_1_wire {
538 wire_2x!(
539 v2_1, Version::V2_1, to_v2_1, set_request_v2_1, from_v2_1,
540 {
541 ChargingStationMaxProfile <=> ChargingStationMaxProfile,
542 TxDefaultProfile <=> TxDefaultProfile,
543 TxProfile <=> TxProfile,
544 ChargingStationExternalConstraints <=> ChargingStationExternalConstraints,
545 PriorityCharging <=> PriorityCharging,
546 LocalGeneration <=> LocalGeneration,
547 },
548 period_to_wire: |period: &Period| -> Result<v2_1::ChargingSchedulePeriod, ConversionError> {
549 let mut wire = v2_1::ChargingSchedulePeriod::new(to_i32(period.start_period, "startPeriod")?);
550 wire.limit = Some(period.limit);
551 wire.number_phases = period.number_phases;
552 wire.phase_to_use = period.phase_to_use;
553 Ok(wire)
554 },
555 period_from_wire: |(index, period): (usize, &v2_1::ChargingSchedulePeriod)| -> Result<Period, ConversionError> {
556 let refuse = |field| Err(ConversionError::UnmodelledField { field, period: Some(index) });
557 for (field, set) in [
558 ("limit_L2", period.limit_l2.is_some()),
559 ("limit_L3", period.limit_l3.is_some()),
560 ("dischargeLimit", period.discharge_limit.is_some()),
561 ("dischargeLimit_L2", period.discharge_limit_l2.is_some()),
562 ("dischargeLimit_L3", period.discharge_limit_l3.is_some()),
563 ("setpoint", period.setpoint.is_some()),
564 ("setpoint_L2", period.setpoint_l2.is_some()),
565 ("setpoint_L3", period.setpoint_l3.is_some()),
566 ("setpointReactive", period.setpoint_reactive.is_some()),
567 ("setpointReactive_L2", period.setpoint_reactive_l2.is_some()),
568 ("setpointReactive_L3", period.setpoint_reactive_l3.is_some()),
569 ("v2xBaseline", period.v2x_baseline.is_some()),
570 ("v2xFreqWattCurve", period.v2x_freq_watt_curve.is_some()),
571 ("v2xSignalWattCurve", period.v2x_signal_watt_curve.is_some()),
572 ] {
573 if set {
574 return refuse(field);
575 }
576 }
577 if period
578 .operation_mode
579 .as_ref()
580 .is_some_and(|mode| *mode != v2_1::OperationMode::ChargingOnly)
581 {
582 return refuse("operationMode");
583 }
584 let limit = period
585 .limit
586 .ok_or(ConversionError::PeriodWithoutLimit { period: index })?;
587 Ok(Period {
588 start_period: i64::from(period.start_period),
589 limit,
590 number_phases: period.number_phases,
591 phase_to_use: period.phase_to_use,
592 })
593 },
594 schedule_check: |schedule: &v2_1::ChargingSchedule| -> Result<(), ConversionError> {
595 let refuse = |field| Err(ConversionError::UnmodelledField { field, period: None });
596 if schedule.limit_at_so_c.is_some() {
597 return refuse("limitAtSoC");
598 }
599 if schedule.use_local_time == Some(true) {
600 return refuse("useLocalTime");
601 }
602 if schedule.randomized_delay.is_some_and(|delay| delay > 0) {
603 return refuse("randomizedDelay");
604 }
605 Ok(())
606 },
607 );
608}