Skip to main content

ocpp_kit/smart_charging/
wire.rs

1//! `Profile` across the wire. See [`ConversionError`].
2
3use 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/// Why a profile could not cross the wire.
14///
15/// The domain [`Profile`] across the wire, in both directions, for every version.
16///
17/// A CSMS sends a `Profile` as a `SetChargingProfileRequest`; a station — or a Local Controller
18/// that wants to know what the CSMS asked for — turns a received `ChargingProfile` back into a
19/// `Profile` for the [composite calculation](super::ProfileStore::composite). Each direction refuses, with a
20/// [`ConversionError`], every field the other side cannot carry *with its meaning*: a default
21/// here would be a profile the station applies differently from the one that was sent.
22///
23/// What is refused, and why:
24///
25/// * 1.6 numbers transactions; a domain transaction id that is not an integer cannot be a 1.6
26///   `TxProfile` (it would bind to another transaction, or to none).
27/// * Purposes a version lacks — 1.6 has no `ChargingStationExternalConstraints`, neither 1.6
28///   nor 2.0.1 has `PriorityCharging` or `LocalGeneration`.
29/// * 2.1 `Dynamic` profiles, periods without a `limit`, and everything that is not a plain
30///   ceiling: `limit_L2`/`limit_L3` (which turn `limit` into a per-phase value), discharge
31///   limits, setpoints, V2X curves and baselines, an `operationMode` other than
32///   `ChargingOnly`, `limitAtSoC`, `useLocalTime`, `randomizedDelay`. Those are V2X control
33///   (block Q), not a limit schedule — build those with [`v2x`](super::v2x), which produces
34///   the wire profile directly.
35/// * 1.6 `phaseToUse`, which 1.6 cannot say.
36///
37/// Carried by neither direction, on purpose, because none of them changes the limit: the
38/// ISO 15118 tariff and price schedules and their signatures, `customData`, 2.1
39/// `powerTolerance`, `evseSleep`, `preconditioningRequest`, and the 2.1 offline fields
40/// (`maxOfflineDuration`, `invalidAfterOfflineDuration`) — the composite here is the one that
41/// applies while online.
42///
43/// ```
44/// use ocpp_kit::smart_charging::{Period, Profile, ProfileKind, Purpose, RateUnit, Schedule};
45/// use ocpp_kit::types::Decimal;
46///
47/// let profile = Profile::new(
48///     1,
49///     0,
50///     Purpose::TxProfile,
51///     ProfileKind::Relative,
52///     Schedule::new(1, RateUnit::A, vec![Period::new(0, Decimal::from(16))]),
53/// )
54/// .on_evse(1)
55/// .for_transaction("42");
56///
57/// let request = profile.set_request_v1_6()?;          // 1.6 numbers its transactions
58/// assert_eq!(request.cs_charging_profiles.transaction_id, Some(42));
59/// let back = Profile::from_v1_6(&request.cs_charging_profiles, 1)?;
60/// assert_eq!(back, profile);
61///
62/// let not_a_number = profile.clone().for_transaction("abc");
63/// assert!(not_a_number.to_v1_6().is_err());
64/// # Ok::<(), ocpp_kit::smart_charging::ConversionError>(())
65/// ```
66
67#[derive(Clone, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum ConversionError {
70    /// A 1.6 `TxProfile` needs an integer transaction id.
71    TransactionIdNotInteger(alloc::string::String),
72    /// The version has no such purpose.
73    PurposeNotInVersion {
74        /// The purpose.
75        purpose: Purpose,
76        /// The version.
77        version: Version,
78    },
79    /// A profile kind the domain does not model (2.1 `Dynamic`).
80    UnmodelledKind(&'static str),
81    /// An enumeration value the station sent that no version defines, kept by lenient decoding.
82    UnknownValue {
83        /// The field.
84        field: &'static str,
85        /// What arrived.
86        value: alloc::string::String,
87    },
88    /// A profile without a schedule.
89    NoSchedule,
90    /// 1.6 carries exactly one schedule per profile.
91    SchedulesNotInVersion(usize),
92    /// A 2.1 period without a `limit` — a setpoint operation mode, not a ceiling.
93    PeriodWithoutLimit {
94        /// The period's index.
95        period: usize,
96    },
97    /// A field that would change what the profile means, which the target cannot carry.
98    UnmodelledField {
99        /// The wire name of the field.
100        field: &'static str,
101        /// The period's index, for a period field.
102        period: Option<usize>,
103    },
104    /// A number that does not fit the target's integer type.
105    OutOfRange {
106        /// The field.
107        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            // `{:?}` quotes and escapes: these strings came from a peer or a caller.
115            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/// Generates the purpose, kind, recurrency and unit mappings for one version's enums.
161#[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/// The one kind name a newer version adds, as a `'static` for the error.
244#[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        /// This profile as an OCPP 1.6 `ChargingProfile`.
269        ///
270        /// # Errors
271        ///
272        /// [`ConversionError`] for a transaction id that is not an integer, a purpose 1.6 lacks,
273        /// anything but exactly one schedule, a `phaseToUse`, or a number out of range.
274        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        /// This profile as an OCPP 1.6 `SetChargingProfile.req`, for connector
326        /// [`evse_id`](Self::evse_id).
327        ///
328        /// # Errors
329        ///
330        /// As [`to_v1_6`](Self::to_v1_6), and for a connector id out of range.
331        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        /// A profile received in an OCPP 1.6 `SetChargingProfile.req` for `connector_id`.
343        ///
344        /// 1.6 schedules carry no id; the domain schedule takes the profile's.
345        ///
346        /// # Errors
347        ///
348        /// [`ConversionError`] for an enumeration value 1.6 does not define.
349        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            // 1.6 schedules have no id of their own; the profile's stands in, which is what a
365            // plan converted by `ChargingPlan::to_profile` uses for both.
366            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/// The 2.x conversions, which share their shape and differ in their periods.
395#[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            ///
415            /// # Errors
416            ///
417            /// [`ConversionError`] for a purpose the version lacks, no schedule, or a number out
418            /// of range.
419            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            ///
453            /// # Errors
454            ///
455            #[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            ///
464            /// # Errors
465            ///
466            /// [`ConversionError`] for anything that is not a plain ceiling — see its
467            /// documentation for the list.
468            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}