Skip to main content

ocpp_kit/smart_charging/
v2x.rs

1//! Bidirectional charging (OCPP 2.1 block Q): operation modes and setpoints.
2//!
3//! What the EV can do comes from [`EvNeeds`], whose
4//! [`clamp_watts`](super::EvNeeds::clamp_watts) fits a setpoint into it.
5//!
6//! [`ChargingPlan`] tells a station what it may *draw*. A V2H or V2B
7//! controller also tells it what the EV should *do* — charge at 3.7 kW, discharge 5 kW into the
8//! house, sit idle — and 2.1 says that with an `operationMode` and a `setpoint` in the same
9//! schedule period. Three things in block Q are easy to get wrong, and each is a type here:
10//!
11//! * **Each mode allows different fields** (Q §2.2, "Limits and setpoints per operation mode").
12//!   `ChargingOnly` needs a `limit`; `CentralSetpoint` needs a `setpoint`; `Idle` forbids all of
13//!   them (Q10.FR.01); a setpoint outside `[dischargeLimit, limit]` is rejected (V2X.05). An
14//!   [`Operation`] can only be built in a shape the station will accept.
15//! * **Signs disagree across messages.** A profile's `setpoint` is signed and its
16//!   `dischargeLimit` negative, while the EV's `maxDischargePower` is a positive magnitude. Here
17//!   nothing takes a signed discharge: [`Setpoint::discharge`] and
18//!   [`Operation::discharge_at_most`] take magnitudes, and the wire gets the sign block Q wants.
19//! * **A dynamic setpoint needs a dead-man switch.** When a `Dynamic` profile is not updated
20//!   within its `duration`, the station falls back to the next valid profile (K28.FR.13). A
21//!   [`DynamicSetpoint`] cannot be built without that duration: a controller that crashes while
22//!   the EV discharges at 11 kW must not leave it discharging.
23//!
24//! The modes are those a home or building controller uses; the frequency modes are not modelled.
25//!
26//! ```
27//! use core::time::Duration;
28//! use ocpp_kit::smart_charging::v2x::{
29//!     DynamicSetpoint, Operation, OperationModes, Setpoint, V2xPlan, V2xStation,
30//! };
31//! use ocpp_kit::smart_charging::{RateUnit, RateUnits, StationLimits, Target};
32//! use ocpp_kit::types::{DateTime, Decimal};
33//!
34//! let station = V2xStation::new(
35//!     StationLimits::new(24, 3, RateUnits::parse_v2("A,W")),
36//!     OperationModes::parse("ChargingOnly,CentralSetpoint,Idle"),
37//! );
38//! let w = |watts: i64| Decimal::from(watts);
39//!
40//! // A day in four slots: charge cheaply at night, idle, cover the evening peak, charge.
41//! let plan = V2xPlan::new(
42//!     "2026-11-20T00:00:00Z".parse::<DateTime>()?,
43//!     Duration::from_secs(6 * 3600),
44//!     [
45//!         Operation::central_setpoint(Setpoint::charge(w(3700))?),
46//!         Operation::idle(),
47//!         Operation::central_setpoint(Setpoint::discharge(w(5000))?).discharge_at_most(w(6000))?,
48//!         Operation::charging_only(w(11000))?,
49//!     ],
50//! )?;
51//! let request = plan.to_request(1, 1, Target::transaction(1, "tx-1"), RateUnit::W, &station)?;
52//! let evening = &request.charging_profile.charging_schedule[0].charging_schedule_period[2];
53//! assert_eq!(evening.setpoint, Some(w(-5000)));
54//! assert_eq!(evening.discharge_limit, Some(w(-6000)));
55//!
56//! // The one-second arbiter: a Dynamic profile that falls back after 30 s without an update.
57//! let mut follow = DynamicSetpoint::new(
58//!     2,
59//!     Target::transaction(1, "tx-1"),
60//!     RateUnit::W,
61//!     Operation::central_setpoint(Setpoint::ZERO).discharge_at_most(w(7000))?,
62//!     Duration::from_secs(30),
63//! )?;
64//! let install = follow.to_request(&station)?;
65//! let update = follow.update_setpoint(Setpoint::discharge(w(2400))?)?;
66//! assert_eq!(update.charging_profile_id, install.charging_profile.id);
67//! assert_eq!(update.schedule_update.setpoint, Some(w(-2400)));
68//! # Ok::<(), Box<dyn std::error::Error>>(())
69//! ```
70
71use 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/// A V2X operation mode this module models (block Q §2.2).
80#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
81#[non_exhaustive]
82pub enum Mode {
83    /// Charging only — the default, and the mode before V2X is authorized (Q02).
84    ChargingOnly,
85    /// The CSMS sets the setpoint (Q03, Q04).
86    CentralSetpoint,
87    /// An external system (an EMS) sets the setpoint, within limits the CSMS may set (Q05).
88    ExternalSetpoint,
89    /// An external system sets the limits (Q06).
90    ExternalLimits,
91    /// The station balances against its grid meter's thresholds (Q09).
92    LocalLoadBalancing,
93    /// The EV is idle (Q10).
94    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    /// The wire spelling.
108    #[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/// The operation modes a station supports — `V2XChargingCtrlr.SupportedOperationModes`
143/// (Q01.FR.30).
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct OperationModes(u8);
146
147impl OperationModes {
148    /// What every V2X station supports (Q01.FR.31), as far as this module models it:
149    /// `ChargingOnly` and `CentralSetpoint`. Use it when the station reports nothing.
150    pub const MANDATORY: Self = Self(Mode::ChargingOnly.bit() | Mode::CentralSetpoint.bit());
151
152    /// Reads the variable's `MemberList`, e.g. `"ChargingOnly,CentralSetpoint,LocalLoadBalancing"`.
153    /// Modes this module does not model (the frequency modes) are ignored.
154    #[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    /// Whether `mode` is supported.
166    #[must_use]
167    pub const fn contains(self, mode: Mode) -> bool {
168        self.0 & mode.bit() != 0
169    }
170}
171
172/// What a V2X station allows: its smart-charging limits and its operation modes.
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174pub struct V2xStation {
175    /// `PeriodsPerSchedule`, `ProfileStackLevel`, `RateUnit`.
176    pub limits: StationLimits,
177    /// `V2XChargingCtrlr.SupportedOperationModes`.
178    pub modes: OperationModes,
179}
180
181impl V2xStation {
182    /// A station with these limits and modes.
183    #[must_use]
184    pub const fn new(limits: StationLimits, modes: OperationModes) -> Self {
185        Self { limits, modes }
186    }
187}
188
189/// A target rate the EV should follow as closely as it can (V2X.02).
190///
191/// Built from a magnitude and a direction, so a discharge can never be sent with the wrong sign.
192#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
193pub struct Setpoint(Decimal);
194
195impl Setpoint {
196    /// Neither charging nor discharging.
197    pub const ZERO: Self = Self(Decimal::ZERO);
198
199    /// Charge at `rate` (in the schedule's unit).
200    ///
201    /// # Errors
202    ///
203    /// [`V2xError::NegativeMagnitude`] for a negative `rate`.
204    pub fn charge(rate: Decimal) -> Result<Self, V2xError> {
205        magnitude(rate).map(Self)
206    }
207
208    /// Discharge at `rate` — a magnitude; the wire gets it negative.
209    ///
210    /// # Errors
211    ///
212    /// [`V2xError::NegativeMagnitude`] for a negative `rate`.
213    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    /// The signed value block Q uses: positive charges, negative discharges.
220    #[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/// One schedule period's V2X content: a mode, and exactly the fields that mode allows.
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub struct Operation {
237    mode: Mode,
238    setpoint: Option<Setpoint>,
239    limit: Option<Decimal>,
240    /// Signed, ≤ 0, as on the wire.
241    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    /// Charging only, up to `limit` — the only mode in which `limit` is required.
259    ///
260    /// # Errors
261    ///
262    /// [`V2xError::NegativeMagnitude`] for a negative `limit`.
263    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    /// The CSMS sets the setpoint (Q03.FR.02). Bound it with
271    /// [`charge_at_most`](Self::charge_at_most) and [`discharge_at_most`](Self::discharge_at_most).
272    #[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    /// An external system sets the setpoint; the CSMS may bound it.
281    #[must_use]
282    pub const fn external_setpoint() -> Self {
283        Self::bare(Mode::ExternalSetpoint)
284    }
285
286    /// An external system sets the limits; the CSMS sets nothing.
287    #[must_use]
288    pub const fn external_limits() -> Self {
289        Self::bare(Mode::ExternalLimits)
290    }
291
292    /// The station balances against its grid meter (Q09); the CSMS may bound the result
293    /// (Q09.FR.05). Its thresholds are device-model variables (`V2XLocalLoadBalancing`), set
294    /// separately — the station rejects this mode without them (Q09.FR.02).
295    #[must_use]
296    pub const fn local_load_balancing() -> Self {
297        Self::bare(Mode::LocalLoadBalancing)
298    }
299
300    /// The EV is idle; no limit or setpoint may be set (Q10.FR.01).
301    #[must_use]
302    pub const fn idle() -> Self {
303        Self::bare(Mode::Idle)
304    }
305
306    /// Caps charging at `rate` (V2X.03).
307    ///
308    /// # Errors
309    ///
310    /// [`V2xError::NotInMode`] for `ChargingOnly` (its limit is already set), `ExternalLimits`
311    /// and `Idle`; [`V2xError::SetpointOutsideLimits`] when the setpoint would exceed it (V2X.05);
312    /// [`V2xError::NegativeMagnitude`].
313    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    /// Caps discharging at `rate`, a magnitude; the wire gets `dischargeLimit = -rate`
327    /// (V2X.04).
328    ///
329    /// # Errors
330    ///
331    /// As [`charge_at_most`](Self::charge_at_most).
332    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    /// Lets the EVSE switch its electronics off while idle (Q10.FR.03).
350    ///
351    /// # Errors
352    ///
353    /// [`V2xError::NotInMode`] unless the mode is `Idle`.
354    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    /// Asks the EV to stay on standby rather than sleep, ready to react quickly (Q §2.2 Idle).
361    ///
362    /// # Errors
363    ///
364    /// [`V2xError::NotInMode`] unless the mode is `Idle`.
365    pub fn precondition(mut self) -> Result<Self, V2xError> {
366        self.allow("preconditioningRequest", &[Mode::Idle])?;
367        self.preconditioning = true;
368        Ok(self)
369    }
370
371    /// The same operation with another setpoint, checked against its limits.
372    ///
373    /// # Errors
374    ///
375    /// [`V2xError::NotInMode`] unless the mode is `CentralSetpoint`;
376    /// [`V2xError::SetpointOutsideLimits`].
377    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    /// The mode.
384    #[must_use]
385    pub const fn mode(&self) -> Mode {
386        self.mode
387    }
388
389    /// The setpoint, signed as on the wire.
390    #[must_use]
391    pub fn setpoint(&self) -> Option<Decimal> {
392        self.setpoint.map(Setpoint::signed)
393    }
394
395    /// The charge limit.
396    #[must_use]
397    pub const fn limit(&self) -> Option<Decimal> {
398        self.limit
399    }
400
401    /// The discharge limit, signed (≤ 0) as on the wire.
402    #[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    /// V2X.05: the setpoint lies between `dischargeLimit` and `limit`.
419    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/// Why a V2X operation, plan or update was refused.
451#[derive(Clone, Debug, PartialEq, Eq)]
452#[non_exhaustive]
453pub enum V2xError {
454    /// A rate is a magnitude; the direction is in the method's name.
455    NegativeMagnitude,
456    /// The setpoint lies outside `[dischargeLimit, limit]` (V2X.05).
457    SetpointOutsideLimits,
458    /// The field is not one this mode allows (block Q §2.2; Q10.FR.01 for `Idle`).
459    NotInMode {
460        /// The wire name of the field.
461        field: &'static str,
462        /// The mode.
463        mode: Mode,
464    },
465    /// The station does not list this mode in `SupportedOperationModes` (Q09.FR.01).
466    UnsupportedMode(Mode),
467    /// More distinct periods than `PeriodsPerSchedule`. Setpoints are not merged.
468    TooManyPeriods {
469        /// How many the plan needs.
470        periods: usize,
471        /// How many the station allows.
472        max: usize,
473    },
474    /// The stack level is above `ProfileStackLevel`.
475    StackLevel {
476        /// Requested.
477        requested: i32,
478        /// Allowed.
479        max: i32,
480    },
481    /// A `TxProfile` on EVSE 0 (K01.FR.16).
482    TxProfileOnEvseZero,
483    /// The station does not accept this `chargingRateUnit` (K01.FR.26).
484    UnitNotAllowed(RateUnit),
485    /// A plan needs at least one slot.
486    Empty,
487    /// More than [`ChargingPlan::MAX_SLOTS`] slots.
488    TooManySlots(usize),
489    /// A slot or fallback shorter than a second, or a schedule longer than `i32::MAX` seconds.
490    BadDuration,
491    /// A dynamic update must keep the profile's mode: an update carries no `operationMode`.
492    ModeChanged {
493        /// The profile's mode.
494        from: Mode,
495        /// The update's.
496        to: Mode,
497    },
498    /// A number that does not fit the wire's integer.
499    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
547/// The checks every V2X profile shares: unit, stack level, target.
548fn 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/// A V2X plan: one [`Operation`] per equally long slot from a start instant.
608#[derive(Clone, Debug, PartialEq)]
609pub struct V2xPlan {
610    start: DateTime,
611    slot: i32,
612    operations: Vec<Operation>,
613}
614
615impl V2xPlan {
616    /// A plan of `operations`, one per `slot`, from `start`.
617    ///
618    /// # Errors
619    ///
620    /// [`V2xError::Empty`], [`V2xError::TooManySlots`] (above [`ChargingPlan::MAX_SLOTS`]),
621    /// [`V2xError::BadDuration`].
622    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    /// The operations, in order.
645    #[must_use]
646    pub fn operations(&self) -> &[Operation] {
647        &self.operations
648    }
649
650    /// The `SetChargingProfileRequest` for this plan: one `Absolute` profile in `unit`, equal
651    /// neighbours merged, checked against everything the station said about itself.
652    ///
653    /// # Errors
654    ///
655    /// [`V2xError::UnsupportedMode`], [`V2xError::TooManyPeriods`],
656    /// [`V2xError::StackLevel`], [`V2xError::UnitNotAllowed`], [`V2xError::TxProfileOnEvseZero`].
657    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            // `new` checked that slot × len fits an i32.
680            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/// A `Dynamic` profile whose one period a controller moves with updates (Q04, K28).
705///
706/// Built with a fallback: when no update arrives within it, the station drops the profile and
707/// falls back to the next valid one (K28.FR.13). There is no way to build one without.
708#[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    /// A dynamic profile `id` for `target`, starting with `operation`, falling back when not
721    /// updated for `fallback_after`. Stack level 0; see [`stack_level`](Self::stack_level).
722    ///
723    /// # Errors
724    ///
725    /// [`V2xError::BadDuration`] for a fallback under a second or above `i32::MAX` seconds.
726    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    /// Sets the stack level — above a plan's, so the dynamic profile leads while it lives.
745    #[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    /// Lets the station pull updates (`PullDynamicScheduleUpdateRequest`) every `interval`
752    /// (`dynUpdateInterval`, K28.FR.10); answer with [`pull_response`](Self::pull_response).
753    ///
754    /// # Errors
755    ///
756    /// [`V2xError::BadDuration`].
757    pub fn pull_every(mut self, interval: Duration) -> Result<Self, V2xError> {
758        self.pull_every = Some(seconds(interval)?);
759        Ok(self)
760    }
761
762    /// The operation currently in force.
763    #[must_use]
764    pub const fn operation(&self) -> &Operation {
765        &self.operation
766    }
767
768    /// The profile id updates are addressed to.
769    #[must_use]
770    pub const fn id(&self) -> i32 {
771        self.id
772    }
773
774    /// The `SetChargingProfileRequest` installing it: `Dynamic`, one schedule, one period at 0
775    /// (K28.FR.01/02), `duration` = the fallback.
776    ///
777    /// # Errors
778    ///
779    /// As [`V2xPlan::to_request`].
780    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    /// Replaces the operation, keeping its mode, and returns the update to send (K28.FR.06).
806    ///
807    /// # Errors
808    ///
809    /// [`V2xError::ModeChanged`]: an update carries no `operationMode`, so changing the mode
810    /// needs a new profile.
811    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    /// Moves the setpoint within the current limits and returns the update to send.
829    ///
830    /// # Errors
831    ///
832    /// [`V2xError::SetpointOutsideLimits`], or [`V2xError::NotInMode`] unless `CentralSetpoint`.
833    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    /// The answer to the station's `PullDynamicScheduleUpdateRequest` (K28.FR.07): the operation
842    /// currently in force.
843    #[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    /// `setpoint` (in W) clamped to what the EV can do: no faster than
854    /// [`max_charge`](EvNeeds::max_charge), no faster than
855    /// [`max_discharge`](EvNeeds::max_discharge), and no discharge at all unless the transfer is
856    /// bidirectional.
857    #[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}