Skip to main content

ocpp_kit/smart_charging/
der.rs

1//! DER control (OCPP 2.1 block R): what a station reports, which control is in effect, and its
2//! alarm.
3//!
4//! A bidirectional station is a distributed energy resource, and a network operator's grid code
5//! reaches it as DER controls — volt-watt and frequency-watt curves, a frequency droop, trip
6//! curves, a cap on discharge (block R §2.7). The station executes them; this module does not.
7//! What a planner needs is to **read** them: a discharge that a DER control can lower or stop
8//! is a discharge it must not count on. Three things make that easy to get wrong from the
9//! generated types alone, and each is handled here:
10//!
11//! * **Which control is in effect is a rule, not a field** (§2.9, R04.FR.09–11). Per control
12//!   type, a scheduled control between its `startTime` and `startTime + duration` overrides the
13//!   default; among several, the lowest `priority` value wins; a superseded control is never
14//!   executed. A report lists all of them. [`DerControls::effective_at`] applies the rule.
15//! * **A report arrives in parts** (R04.FR.31/32): one `ReportDERControlRequest` per part, each
16//!   with the request's `requestId`, `tbc` on all but the last. [`DerReport`] collects exactly
17//!   one report and refuses a stray part, a part after the last, and a report that keeps
18//!   growing.
19//! * **An alarm has one level** (R05.FR.03/04): when control B takes over from A the station
20//!   reports B and never reports A's end. [`DerAlarmState`] holds one alarm, not a set.
21//!
22//! [`Effect`] classifies every control type by what it can do to active power, and
23//! [`DerControls::limiting_at`] answers the planner's question. A control type the crate does
24//! not know counts as limiting: assuming it harmless is the one guess that can cost a planned
25//! discharge.
26//!
27//! [`check`] refuses a `SetDERControlRequest` the station must reject (R04.FR.13, 15, 17 and
28//! 50–56), before it is sent. The settings themselves stay the generated types — they *are* the
29//! setting, field for field, with exact decimals.
30//!
31//! # What is not here
32//!
33//! Executing curves, trips and ramps: that needs grid measurements this crate never sees, and it
34//! is the inverter's job. And no watt figure from `LimitMaxDischarge.pctMaxDischargePower`: the
35//! specification gives the field two readings — §2.64 makes it the threshold above which the
36//! power-monitoring trip curve applies, use cases R01/R02 use it as the discharge cap itself — so
37//! any number computed from it is a guess about which reading the station took.
38//!
39//! ```
40//! use ocpp_kit::smart_charging::der::{DerReport, Effect};
41//! use ocpp_kit::types::DateTime;
42//! use ocpp_kit::v2_1::{DERControl, ReportDERControlRequest};
43//!
44//! // `GetDERControl { requestId: 7 }` was answered in two parts.
45//! let first: ReportDERControlRequest = serde_json::from_str(r#"{
46//!     "requestId": 7, "tbc": true,
47//!     "curve": [
48//!         {"id": "vw-default", "curveType": "VoltWatt", "isDefault": true, "isSuperseded": false,
49//!          "curve": {"priority": 1, "yUnit": "PctMaxW",
50//!                    "curveData": [{"x": 106, "y": 100}, {"x": 110, "y": 0}]}},
51//!         {"id": "vw-event", "curveType": "VoltWatt", "isDefault": false, "isSuperseded": false,
52//!          "curve": {"priority": 0, "yUnit": "PctMaxW", "startTime": "2026-11-20T17:00:00Z",
53//!                    "duration": 3600, "curveData": [{"x": 104, "y": 100}, {"x": 108, "y": 0}]}}
54//!     ]}"#)?;
55//! let last: ReportDERControlRequest = serde_json::from_str(r#"{
56//!     "requestId": 7,
57//!     "fixedPFInject": [
58//!         {"id": "pf", "isDefault": true, "isSuperseded": false,
59//!          "fixedPF": {"priority": 0, "displacement": 0.95, "excitation": false}}
60//!     ]}"#)?;
61//!
62//! let mut report = DerReport::new(7);
63//! report.add(&first)?;
64//! report.add(&last)?;
65//! let controls = report.finish()?;
66//!
67//! let evening: DateTime = "2026-11-20T17:30:00Z".parse()?;
68//! let volt_watt = controls.effective(&DERControl::VoltWatt, evening).unwrap();
69//! assert_eq!(volt_watt.id, "vw-event"); // scheduled beats default while it runs
70//! assert_eq!(volt_watt.effect(), Effect::Lowers);
71//!
72//! // The power factor is in effect too, but it only takes reactive headroom.
73//! let limiting: Vec<_> = controls.limiting_at(evening).iter().map(|c| c.id.as_str()).collect();
74//! assert_eq!(limiting, ["vw-event"]);
75//! # Ok::<(), Box<dyn std::error::Error>>(())
76//! ```
77
78use alloc::boxed::Box;
79use alloc::string::String;
80use alloc::vec::Vec;
81use core::fmt;
82
83use crate::types::{DateTime, Decimal};
84use crate::v2_1::{self, DERControl, DERUnit};
85
86/// What a control type can do to the active power a station charges or discharges with.
87#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
88pub enum Effect {
89    /// Lowers active power: `FreqDroop`, `FreqWatt` (P(f)), `VoltWatt` (P(U)),
90    /// `LimitMaxDischarge` (Table 161: "Limit Active Power").
91    Lowers,
92    /// Stops it: every trip and momentary-cessation curve, and `PowerMonitoringMustTrip`. A trip
93    /// curve says "after how many seconds a DER must disconnect" (§2.7).
94    Stops,
95    /// Slows changes to it: `Gradients` (ramp rates) and `EnterService` (delay and ramp after a
96    /// trip).
97    Slows,
98    /// Only reactive power: `VoltVar`, `WattVar`, `WattPF`, `FixedPFAbsorb`, `FixedPFInject`,
99    /// `FixedVar`. Whether reactive power costs active headroom depends on the inverter's
100    /// apparent-power rating, which OCPP does not carry, so these are not counted as limiting.
101    Reactive,
102    /// A control type this crate does not know, kept by lenient decoding.
103    Unknown,
104}
105
106impl Effect {
107    /// Whether a control with this effect can lower or stop active power — the controls a planner
108    /// must not plan around. `Unknown` counts: assuming it harmless is the costly guess.
109    #[must_use]
110    pub const fn limits_active_power(self) -> bool {
111        matches!(self, Self::Lowers | Self::Stops | Self::Unknown)
112    }
113}
114
115/// What a control type can do to active power.
116#[must_use]
117pub fn effect(kind: &DERControl) -> Effect {
118    match kind {
119        DERControl::FreqDroop
120        | DERControl::FreqWatt
121        | DERControl::VoltWatt
122        | DERControl::LimitMaxDischarge => Effect::Lowers,
123        DERControl::HFMustTrip
124        | DERControl::HFMayTrip
125        | DERControl::HVMustTrip
126        | DERControl::HVMomCess
127        | DERControl::HVMayTrip
128        | DERControl::LFMustTrip
129        | DERControl::LVMustTrip
130        | DERControl::LVMomCess
131        | DERControl::LVMayTrip
132        | DERControl::PowerMonitoringMustTrip => Effect::Stops,
133        DERControl::Gradients | DERControl::EnterService => Effect::Slows,
134        DERControl::VoltVar
135        | DERControl::WattVar
136        | DERControl::WattPF
137        | DERControl::FixedPFAbsorb
138        | DERControl::FixedPFInject
139        | DERControl::FixedVar => Effect::Reactive,
140        DERControl::UnknownValue(_) => Effect::Unknown,
141    }
142}
143
144/// The types that carry their own field in a `SetDERControlRequest` and their own array in a
145/// report; every other type is a `curve` (R04.FR.16).
146fn has_own_field(kind: &DERControl) -> bool {
147    matches!(
148        kind,
149        DERControl::EnterService
150            | DERControl::FreqDroop
151            | DERControl::FixedPFAbsorb
152            | DERControl::FixedPFInject
153            | DERControl::FixedVar
154            | DERControl::Gradients
155            | DERControl::LimitMaxDischarge
156    )
157}
158
159/// A control's setting, exactly as the station reported it.
160#[derive(Clone, Debug, PartialEq)]
161pub enum Setting {
162    /// Every curve type: `VoltWatt`, `FreqWatt`, the trip curves, …
163    Curve(v2_1::DERCurve),
164    /// `EnterService`.
165    EnterService(v2_1::EnterService),
166    /// `FixedPFAbsorb`.
167    FixedPfAbsorb(v2_1::FixedPF),
168    /// `FixedPFInject`.
169    FixedPfInject(v2_1::FixedPF),
170    /// `FixedVar`.
171    FixedVar(v2_1::FixedVar),
172    /// `FreqDroop`.
173    FreqDroop(v2_1::FreqDroop),
174    /// `Gradients`.
175    Gradient(v2_1::Gradient),
176    /// `LimitMaxDischarge`.
177    ///
178    /// No cap is derived from `pctMaxDischargePower`: §2.64 defines it as the threshold above
179    /// which the `powerMonitoringMustTrip` curve applies, while use cases R01/R02 use it as the
180    /// discharge cap itself. Read the field, and the station's documentation for which reading
181    /// it implements.
182    LimitMaxDischarge(v2_1::LimitMaxDischarge),
183}
184
185impl Setting {
186    /// The setting's `priority`; 0 is the highest.
187    #[must_use]
188    pub fn priority(&self) -> i32 {
189        match self {
190            Self::Curve(s) => s.priority,
191            Self::EnterService(s) => s.priority,
192            Self::FixedPfAbsorb(s) | Self::FixedPfInject(s) => s.priority,
193            Self::FixedVar(s) => s.priority,
194            Self::FreqDroop(s) => s.priority,
195            Self::Gradient(s) => s.priority,
196            Self::LimitMaxDischarge(s) => s.priority,
197        }
198    }
199
200    /// When a scheduled setting starts. `EnterService` and `Gradients` have none.
201    #[must_use]
202    pub fn start(&self) -> Option<DateTime> {
203        match self {
204            Self::Curve(s) => s.start_time,
205            Self::FixedPfAbsorb(s) | Self::FixedPfInject(s) => s.start_time,
206            Self::FixedVar(s) => s.start_time,
207            Self::FreqDroop(s) => s.start_time,
208            Self::LimitMaxDischarge(s) => s.start_time,
209            Self::EnterService(_) | Self::Gradient(_) => None,
210        }
211    }
212
213    /// How long a scheduled setting lasts, in seconds.
214    #[must_use]
215    pub fn duration(&self) -> Option<Decimal> {
216        match self {
217            Self::Curve(s) => s.duration,
218            Self::FixedPfAbsorb(s) | Self::FixedPfInject(s) => s.duration,
219            Self::FixedVar(s) => s.duration,
220            Self::FreqDroop(s) => s.duration,
221            Self::LimitMaxDischarge(s) => s.duration,
222            Self::EnterService(_) | Self::Gradient(_) => None,
223        }
224    }
225}
226
227/// One DER control as a station reported it.
228#[derive(Clone, Debug, PartialEq)]
229#[non_exhaustive]
230pub struct DerControl {
231    /// The control's id (`controlId` of the `SetDERControlRequest` that installed it).
232    pub id: String,
233    /// The control type.
234    pub kind: DERControl,
235    /// A default control, rather than a scheduled one. `EnterService` and `Gradients` exist only
236    /// as defaults (R04.FR.14).
237    pub default: bool,
238    /// Superseded by a control of higher priority: never executed (R04.FR.09).
239    pub superseded: bool,
240    /// The setting.
241    pub setting: Setting,
242    /// The scheduled window in epoch milliseconds: `None` start = from always, `None` end =
243    /// open-ended.
244    window: (Option<i64>, Option<i64>),
245}
246
247impl DerControl {
248    fn new(
249        id: &str,
250        kind: DERControl,
251        default: bool,
252        superseded: bool,
253        setting: Setting,
254    ) -> Result<Self, DerError> {
255        let start = setting.start().map(|at| at.timestamp().as_millisecond());
256        let end = match setting.duration() {
257            None => None,
258            Some(duration) => {
259                let millis = duration
260                    .checked_mul(Decimal::from(1000))
261                    .and_then(|ms| ms.round_to(0))
262                    .filter(|ms| ms.signum() >= 0)
263                    .map(Decimal::mantissa)
264                    .ok_or_else(|| DerError::BadDuration(id.into()))?;
265                match start {
266                    Some(start) => Some(
267                        start
268                            .checked_add(millis)
269                            .ok_or_else(|| DerError::BadDuration(id.into()))?,
270                    ),
271                    // A duration without a start: in effect from receipt, which the report does
272                    // not say. Open-ended is the reading that never drops a control.
273                    None => None,
274                }
275            }
276        };
277        Ok(Self {
278            id: id.into(),
279            kind,
280            default,
281            superseded,
282            setting,
283            window: (start, end),
284        })
285    }
286
287    /// The setting's `priority`; 0 is the highest.
288    #[must_use]
289    pub fn priority(&self) -> i32 {
290        self.setting.priority()
291    }
292
293    /// What this control can do to active power.
294    #[must_use]
295    pub fn effect(&self) -> Effect {
296        effect(&self.kind)
297    }
298
299    /// Whether `at` lies inside the control's window — always for a default, from `startTime`
300    /// until `startTime + duration` for a scheduled one. Says nothing about superseding or
301    /// priority; see [`DerControls::effective_at`].
302    #[must_use]
303    pub fn is_active_at(&self, at: DateTime) -> bool {
304        if self.default {
305            return true;
306        }
307        let at = at.timestamp().as_millisecond();
308        self.window.0.is_none_or(|start| start <= at) && self.window.1.is_none_or(|end| at < end)
309    }
310}
311
312/// The parts of one `GetDERControl` answer, collected (R04.FR.31/32).
313///
314/// Bound to one `requestId`; complete when a part arrives without `tbc = true`. A part is taken
315/// whole or not at all.
316#[derive(Clone, Debug)]
317pub struct DerReport {
318    request_id: i32,
319    limit: usize,
320    complete: bool,
321    controls: Vec<DerControl>,
322}
323
324impl DerReport {
325    /// How many controls a report may hold unless [`with_limit`](Self::with_limit) says
326    /// otherwise — two orders of magnitude above 22 control types with a handful of priorities.
327    pub const DEFAULT_LIMIT: usize = 1024;
328
329    /// A collector for the report answering `GetDERControlRequest { requestId }`.
330    #[must_use]
331    pub fn new(request_id: i32) -> Self {
332        Self {
333            request_id,
334            limit: Self::DEFAULT_LIMIT,
335            complete: false,
336            controls: Vec::new(),
337        }
338    }
339
340    /// The most controls the report may hold.
341    #[must_use]
342    pub fn with_limit(mut self, limit: usize) -> Self {
343        self.limit = limit;
344        self
345    }
346
347    /// Whether the last part has arrived.
348    #[must_use]
349    pub fn is_complete(&self) -> bool {
350        self.complete
351    }
352
353    /// Adds one part. Returns whether the report is now complete.
354    ///
355    /// # Errors
356    ///
357    /// [`DerError`] for a part with another `requestId`, a part after the last, a curve whose
358    /// type has its own array, a control id seen twice, a bad duration, or more controls than
359    /// the limit. The collector is unchanged.
360    pub fn add(&mut self, part: &v2_1::ReportDERControlRequest) -> Result<bool, DerError> {
361        if self.complete {
362            return Err(DerError::Complete);
363        }
364        if part.request_id != self.request_id {
365            return Err(DerError::RequestId {
366                expected: self.request_id,
367                got: part.request_id,
368            });
369        }
370        let added = controls_in(part)?;
371        if self.controls.len() + added.len() > self.limit {
372            return Err(DerError::TooManyControls { limit: self.limit });
373        }
374        for (index, control) in added.iter().enumerate() {
375            let seen = |other: &DerControl| other.id == control.id;
376            if self.controls.iter().any(seen) || added[..index].iter().any(seen) {
377                return Err(DerError::DuplicateId(control.id.clone()));
378            }
379        }
380        self.controls.extend(added);
381        self.complete = part.tbc != Some(true);
382        Ok(self.complete)
383    }
384
385    /// The collected controls.
386    ///
387    /// # Errors
388    ///
389    /// [`DerError::Incomplete`] when the last part has not arrived: a partial report is not the
390    /// station's state.
391    pub fn finish(self) -> Result<DerControls, DerError> {
392        if !self.complete {
393            return Err(DerError::Incomplete);
394        }
395        Ok(DerControls {
396            controls: self.controls,
397        })
398    }
399}
400
401/// Every control one report part carries, checked one by one (R04.FR.16, durations).
402fn controls_in(part: &v2_1::ReportDERControlRequest) -> Result<Vec<DerControl>, DerError> {
403    let mut added = Vec::new();
404    for c in part.curve.iter().flatten() {
405        if has_own_field(&c.curve_type) {
406            return Err(DerError::WrongArray {
407                id: c.id.clone(),
408                kind: c.curve_type.clone(),
409            });
410        }
411        added.push(DerControl::new(
412            &c.id,
413            c.curve_type.clone(),
414            c.is_default,
415            c.is_superseded,
416            Setting::Curve(c.curve.clone()),
417        )?);
418    }
419    // EnterService and Gradients exist only as defaults (R04.FR.14) and their report types
420    // carry neither flag.
421    for c in part.enter_service.iter().flatten() {
422        let setting = Setting::EnterService(c.enter_service.clone());
423        added.push(DerControl::new(
424            &c.id,
425            DERControl::EnterService,
426            true,
427            false,
428            setting,
429        )?);
430    }
431    for c in part.gradient.iter().flatten() {
432        let setting = Setting::Gradient(c.gradient.clone());
433        added.push(DerControl::new(
434            &c.id,
435            DERControl::Gradients,
436            true,
437            false,
438            setting,
439        )?);
440    }
441    for (list, kind, wrap) in [
442        (
443            &part.fixed_pf_absorb,
444            DERControl::FixedPFAbsorb,
445            Setting::FixedPfAbsorb as fn(v2_1::FixedPF) -> Setting,
446        ),
447        (
448            &part.fixed_pf_inject,
449            DERControl::FixedPFInject,
450            Setting::FixedPfInject,
451        ),
452    ] {
453        for c in list.iter().flatten() {
454            let setting = wrap(c.fixed_pf.clone());
455            added.push(DerControl::new(
456                &c.id,
457                kind.clone(),
458                c.is_default,
459                c.is_superseded,
460                setting,
461            )?);
462        }
463    }
464    for c in part.fixed_var.iter().flatten() {
465        let setting = Setting::FixedVar(c.fixed_var.clone());
466        added.push(DerControl::new(
467            &c.id,
468            DERControl::FixedVar,
469            c.is_default,
470            c.is_superseded,
471            setting,
472        )?);
473    }
474    for c in part.freq_droop.iter().flatten() {
475        let setting = Setting::FreqDroop(c.freq_droop.clone());
476        added.push(DerControl::new(
477            &c.id,
478            DERControl::FreqDroop,
479            c.is_default,
480            c.is_superseded,
481            setting,
482        )?);
483    }
484    for c in part.limit_max_discharge.iter().flatten() {
485        let setting = Setting::LimitMaxDischarge(c.limit_max_discharge.clone());
486        added.push(DerControl::new(
487            &c.id,
488            DERControl::LimitMaxDischarge,
489            c.is_default,
490            c.is_superseded,
491            setting,
492        )?);
493    }
494    Ok(added)
495}
496
497/// A station's DER controls, from a complete report and the start/stop notifications since.
498#[derive(Clone, Debug, Default, PartialEq)]
499pub struct DerControls {
500    controls: Vec<DerControl>,
501}
502
503impl DerControls {
504    /// Every control, in report order.
505    pub fn iter(&self) -> impl Iterator<Item = &DerControl> {
506        self.controls.iter()
507    }
508
509    /// How many controls there are.
510    #[must_use]
511    pub fn len(&self) -> usize {
512        self.controls.len()
513    }
514
515    /// Whether there are none.
516    #[must_use]
517    pub fn is_empty(&self) -> bool {
518        self.controls.is_empty()
519    }
520
521    /// The control with this id.
522    #[must_use]
523    pub fn get(&self, id: &str) -> Option<&DerControl> {
524        self.controls.iter().find(|control| control.id == id)
525    }
526
527    /// The control of type `kind` in effect at `at` (§2.9, R04.FR.09–11): the non-superseded
528    /// scheduled control whose window holds `at` with the lowest `priority` value, else the
529    /// non-superseded default with the lowest `priority` value. On a tie, the first reported.
530    #[must_use]
531    pub fn effective(&self, kind: &DERControl, at: DateTime) -> Option<&DerControl> {
532        let best = |default: bool| {
533            self.controls
534                .iter()
535                .filter(|c| c.kind == *kind && c.default == default && !c.superseded)
536                .filter(|c| c.is_active_at(at))
537                .fold(None, |best: Option<&DerControl>, c| match best {
538                    Some(b) if b.priority() <= c.priority() => Some(b),
539                    _ => Some(c),
540                })
541        };
542        best(false).or_else(|| best(true))
543    }
544
545    /// One control per type, the one in effect at `at`; types with none in effect are absent.
546    #[must_use]
547    pub fn effective_at(&self, at: DateTime) -> Vec<&DerControl> {
548        let mut kinds: Vec<&DERControl> = Vec::new();
549        for control in &self.controls {
550            if !kinds.contains(&&control.kind) {
551                kinds.push(&control.kind);
552            }
553        }
554        kinds
555            .into_iter()
556            .filter_map(|kind| self.effective(kind, at))
557            .collect()
558    }
559
560    /// The controls in effect at `at` that can lower or stop active power — what a planner must
561    /// not count on. Includes control types the crate does not know.
562    #[must_use]
563    pub fn limiting_at(&self, at: DateTime) -> Vec<&DerControl> {
564        self.effective_at(at)
565            .into_iter()
566            .filter(|control| control.effect().limits_active_power())
567            .collect()
568    }
569
570    /// Applies a `NotifyDERStartStopRequest` (R04.FR.20–22): a start marks the controls it
571    /// supersedes, an end removes the control (R04.FR.10).
572    pub fn apply(&mut self, notice: &v2_1::NotifyDERStartStopRequest) -> StartStop {
573        if notice.started {
574            let mut superseded = Vec::new();
575            for id in notice.superseded_ids.iter().flatten() {
576                if let Some(control) = self.controls.iter_mut().find(|c| c.id == *id) {
577                    control.superseded = true;
578                    superseded.push(id.clone());
579                }
580            }
581            if self.get(&notice.control_id).is_none() {
582                return StartStop::UnknownControl(notice.control_id.clone());
583            }
584            StartStop::Started { superseded }
585        } else {
586            match self.controls.iter().position(|c| c.id == notice.control_id) {
587                Some(index) => StartStop::Ended(Box::new(self.controls.remove(index))),
588                None => StartStop::UnknownControl(notice.control_id.clone()),
589            }
590        }
591    }
592}
593
594impl<'a> IntoIterator for &'a DerControls {
595    type Item = &'a DerControl;
596    type IntoIter = core::slice::Iter<'a, DerControl>;
597
598    fn into_iter(self) -> Self::IntoIter {
599        self.controls.iter()
600    }
601}
602
603/// What a `NotifyDERStartStopRequest` did.
604#[derive(Clone, Debug, PartialEq)]
605#[must_use = "an unknown control means the inventory is stale: ask the station again"]
606pub enum StartStop {
607    /// The control started; these known controls are now superseded.
608    Started {
609        /// The ids marked superseded.
610        superseded: Vec<String>,
611    },
612    /// The control ended and was removed.
613    Ended(Box<DerControl>),
614    /// The station named a control this inventory does not have. Superseded ids it named were
615    /// still applied; send `GetDERControl` to resynchronize.
616    UnknownControl(String),
617}
618
619/// The alarm a station has raised (R05).
620#[derive(Clone, Debug, PartialEq, Eq)]
621#[non_exhaustive]
622pub struct DerAlarm {
623    /// The control that is taking over.
624    pub kind: DERControl,
625    /// What caused it, when the station said.
626    pub fault: Option<v2_1::GridEventFault>,
627    /// When the station raised it.
628    pub since: DateTime,
629    /// Free text from the station.
630    pub extra_info: Option<String>,
631}
632
633/// A station's one DER alarm.
634///
635/// "There are no multiple levels of alarm" (R05.FR.04): when another control takes over, the
636/// station reports the new one and never ends the first, so this holds one alarm, not a set.
637#[derive(Clone, Debug, Default, PartialEq, Eq)]
638pub struct DerAlarmState {
639    current: Option<DerAlarm>,
640}
641
642impl DerAlarmState {
643    /// No alarm.
644    #[must_use]
645    pub fn new() -> Self {
646        Self::default()
647    }
648
649    /// The alarm currently raised.
650    #[must_use]
651    pub fn current(&self) -> Option<&DerAlarm> {
652        self.current.as_ref()
653    }
654
655    /// Applies a `NotifyDERAlarmRequest`.
656    pub fn apply(&mut self, notice: &v2_1::NotifyDERAlarmRequest) -> AlarmChange {
657        if notice.alarm_ended == Some(true) {
658            return match &self.current {
659                Some(alarm) if alarm.kind == notice.control_type => self
660                    .current
661                    .take()
662                    .map_or(AlarmChange::Unmatched, AlarmChange::Cleared),
663                _ => AlarmChange::Unmatched,
664            };
665        }
666        let alarm = DerAlarm {
667            kind: notice.control_type.clone(),
668            fault: notice.grid_event_fault.clone(),
669            since: notice.timestamp,
670            extra_info: notice.extra_info.clone(),
671        };
672        match self.current.take() {
673            None => {
674                self.current = Some(alarm);
675                AlarmChange::Raised
676            }
677            // A station retries a message it got no answer to: the same alarm again is not a
678            // new occurrence, and keeps its original start.
679            Some(previous) if previous.kind == alarm.kind && previous.fault == alarm.fault => {
680                self.current = Some(previous);
681                AlarmChange::Repeated
682            }
683            Some(previous) => {
684                self.current = Some(alarm);
685                AlarmChange::Replaced(previous)
686            }
687        }
688    }
689}
690
691/// What a `NotifyDERAlarmRequest` did.
692#[derive(Clone, Debug, PartialEq, Eq)]
693#[must_use = "an unmatched end means the alarm state and the station disagree"]
694pub enum AlarmChange {
695    /// An alarm was raised.
696    Raised,
697    /// The raised alarm was reported again, unchanged.
698    Repeated,
699    /// Another control took over (R05.FR.03); this was the alarm before.
700    Replaced(DerAlarm),
701    /// The alarm ended (R05.FR.02).
702    Cleared(DerAlarm),
703    /// An end for a control that is not the one raised, or with no alarm raised. Nothing changed.
704    Unmatched,
705}
706
707/// A rule a `SetDERControlRequest` breaks.
708#[derive(Clone, Debug, PartialEq, Eq)]
709#[non_exhaustive]
710pub enum DerRule {
711    /// A default control with a `startTime` or `duration` (R04.FR.13).
712    DefaultWithTime,
713    /// A scheduled `EnterService` or `Gradients`, which exist only as defaults (R04.FR.15).
714    DefaultOnly,
715    /// Not exactly one control field, or not the one the type maps to (R04.FR.17).
716    FieldMismatch,
717    /// A curve with a `yUnit` its type does not allow (R04.FR.50–56).
718    WrongYUnit {
719        /// The control type whose curve it is.
720        kind: DERControl,
721        /// The unit it had.
722        unit: DERUnit,
723    },
724}
725
726impl DerRule {
727    /// The requirement the request breaks, e.g. `"R04.FR.13"`.
728    #[must_use]
729    pub fn requirement(&self) -> &'static str {
730        match self {
731            Self::DefaultWithTime => "R04.FR.13",
732            Self::DefaultOnly => "R04.FR.15",
733            Self::FieldMismatch => "R04.FR.17",
734            Self::WrongYUnit { kind, .. } => {
735                y_unit_rule(kind).map_or("R04.FR.50", |(rule, _)| rule)
736            }
737        }
738    }
739}
740
741impl fmt::Display for DerRule {
742    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743        let rule = self.requirement();
744        match self {
745            Self::DefaultWithTime => {
746                write!(
747                    f,
748                    "a default DER control has no startTime or duration ({rule})"
749                )
750            }
751            Self::DefaultOnly => {
752                write!(
753                    f,
754                    "EnterService and Gradients exist only as defaults ({rule})"
755                )
756            }
757            Self::FieldMismatch => write!(
758                f,
759                "the request must carry exactly the one field its controlType maps to ({rule})"
760            ),
761            Self::WrongYUnit { kind, unit } => {
762                write!(f, "a {kind} curve cannot use yUnit {unit} ({rule})")
763            }
764        }
765    }
766}
767
768#[cfg(feature = "std")]
769impl std::error::Error for DerRule {}
770
771/// The `yUnit`s a curve of `kind` may use, and the requirement that says so (R04.FR.50–56).
772fn y_unit_rule(kind: &DERControl) -> Option<(&'static str, &'static [DERUnit])> {
773    const POWER: &[DERUnit] = &[DERUnit::PctMaxW, DERUnit::PctWAvail];
774    const VAR: &[DERUnit] = &[DERUnit::PctMaxVar, DERUnit::PctVarAvail];
775    const NONE: &[DERUnit] = &[DERUnit::NotApplicable];
776    Some(match kind {
777        DERControl::FreqWatt => ("R04.FR.50", POWER),
778        DERControl::HFMustTrip
779        | DERControl::HFMayTrip
780        | DERControl::HVMustTrip
781        | DERControl::HVMomCess
782        | DERControl::HVMayTrip
783        | DERControl::LFMustTrip
784        | DERControl::LVMustTrip
785        | DERControl::LVMomCess
786        | DERControl::LVMayTrip => ("R04.FR.51", NONE),
787        DERControl::VoltVar => ("R04.FR.52", VAR),
788        DERControl::VoltWatt => ("R04.FR.53", POWER),
789        DERControl::WattPF => ("R04.FR.54", NONE),
790        DERControl::WattVar => ("R04.FR.55", VAR),
791        DERControl::LimitMaxDischarge => ("R04.FR.56", NONE),
792        _ => return None,
793    })
794}
795
796/// Refuses a `SetDERControlRequest` that the station must reject: a default with a schedule
797/// (R04.FR.13), a scheduled `EnterService`/`Gradients` (R04.FR.15), a field that does not match
798/// `controlType` (R04.FR.17), a curve unit the type does not allow (R04.FR.50–56).
799///
800/// # Errors
801///
802/// The first [`DerRule`] the request breaks.
803pub fn check(request: &v2_1::SetDERControlRequest) -> Result<(), DerRule> {
804    let kind = &request.control_type;
805    let present = [
806        ("curve", request.curve.is_some()),
807        ("enterService", request.enter_service.is_some()),
808        ("fixedPFAbsorb", request.fixed_pf_absorb.is_some()),
809        ("fixedPFInject", request.fixed_pf_inject.is_some()),
810        ("fixedVar", request.fixed_var.is_some()),
811        ("freqDroop", request.freq_droop.is_some()),
812        ("gradient", request.gradient.is_some()),
813        ("limitMaxDischarge", request.limit_max_discharge.is_some()),
814    ];
815    let expected = match kind {
816        DERControl::EnterService => "enterService",
817        DERControl::FixedPFAbsorb => "fixedPFAbsorb",
818        DERControl::FixedPFInject => "fixedPFInject",
819        DERControl::FixedVar => "fixedVar",
820        DERControl::FreqDroop => "freqDroop",
821        DERControl::Gradients => "gradient",
822        DERControl::LimitMaxDischarge => "limitMaxDischarge",
823        _ => "curve",
824    };
825    let mut set = present.iter().filter(|(_, set)| *set);
826    if set.next().map(|(name, _)| *name) != Some(expected) || set.next().is_some() {
827        return Err(DerRule::FieldMismatch);
828    }
829    if !request.is_default && matches!(kind, DERControl::EnterService | DERControl::Gradients) {
830        return Err(DerRule::DefaultOnly);
831    }
832    let setting = request
833        .curve
834        .clone()
835        .map(Setting::Curve)
836        .or_else(|| request.fixed_pf_absorb.clone().map(Setting::FixedPfAbsorb))
837        .or_else(|| request.fixed_pf_inject.clone().map(Setting::FixedPfInject))
838        .or_else(|| request.fixed_var.clone().map(Setting::FixedVar))
839        .or_else(|| request.freq_droop.clone().map(Setting::FreqDroop))
840        .or_else(|| {
841            request
842                .limit_max_discharge
843                .clone()
844                .map(Setting::LimitMaxDischarge)
845        });
846    if request.is_default
847        && setting
848            .as_ref()
849            .is_some_and(|s| s.start().is_some() || s.duration().is_some())
850    {
851        return Err(DerRule::DefaultWithTime);
852    }
853    let curve = match (&request.curve, &request.limit_max_discharge) {
854        (Some(curve), _) => Some(curve),
855        (None, Some(limit)) => limit.power_monitoring_must_trip.as_ref(),
856        (None, None) => None,
857    };
858    if let (Some(curve), Some((_, allowed))) = (curve, y_unit_rule(kind)) {
859        if !allowed.contains(&curve.y_unit) {
860            return Err(DerRule::WrongYUnit {
861                kind: kind.clone(),
862                unit: curve.y_unit.clone(),
863            });
864        }
865    }
866    Ok(())
867}
868
869/// Why a DER report could not be collected.
870#[derive(Clone, Debug, PartialEq, Eq)]
871#[non_exhaustive]
872pub enum DerError {
873    /// A part answering another `GetDERControl` (R04.FR.31).
874    RequestId {
875        /// The collector's `requestId`.
876        expected: i32,
877        /// The part's.
878        got: i32,
879    },
880    /// A part after the last one (R04.FR.32).
881    Complete,
882    /// The last part has not arrived.
883    Incomplete,
884    /// A curve whose type has its own array (R04.FR.16).
885    WrongArray {
886        /// The control's id.
887        id: String,
888        /// Its type.
889        kind: DERControl,
890    },
891    /// Two controls with one id.
892    DuplicateId(String),
893    /// More controls than the collector's limit.
894    TooManyControls {
895        /// The limit.
896        limit: usize,
897    },
898    /// A negative duration, or a start plus duration that cannot be represented.
899    BadDuration(String),
900}
901
902impl fmt::Display for DerError {
903    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904        // `{:?}` quotes and escapes: ids came from a station.
905        match self {
906            Self::RequestId { expected, got } => write!(
907                f,
908                "report part for requestId {got}, expected {expected} (R04.FR.31)"
909            ),
910            Self::Complete => f.write_str("report part after the last one (R04.FR.32)"),
911            Self::Incomplete => f.write_str("the report's last part has not arrived"),
912            Self::WrongArray { id, kind } => write!(
913                f,
914                "control {id:?} of type {kind} arrived as a curve; it has its own field (R04.FR.16)"
915            ),
916            Self::DuplicateId(id) => write!(f, "control id {id:?} reported twice"),
917            Self::TooManyControls { limit } => {
918                write!(f, "report holds more than {limit} controls")
919            }
920            Self::BadDuration(id) => write!(
921                f,
922                "control {id:?} has a negative or unrepresentable duration"
923            ),
924        }
925    }
926}
927
928#[cfg(feature = "std")]
929impl std::error::Error for DerError {}
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934
935    fn at(text: &str) -> DateTime {
936        text.parse().unwrap()
937    }
938
939    fn part(json: &str) -> v2_1::ReportDERControlRequest {
940        serde_json::from_str(json).unwrap()
941    }
942
943    fn curve(id: &str, kind: &str, default: bool, superseded: bool, extra: &str) -> String {
944        let unit = match kind {
945            "VoltVar" | "WattVar" => "PctMaxVar",
946            "VoltWatt" | "FreqWatt" => "PctMaxW",
947            _ => "Not_Applicable",
948        };
949        format!(
950            r#"{{"id":"{id}","curveType":"{kind}","isDefault":{default},"isSuperseded":{superseded},
951               "curve":{{"yUnit":"{unit}","curveData":[{{"x":1,"y":2}}]{extra}}}}}"#
952        )
953    }
954
955    fn controls(curves: &[String]) -> DerControls {
956        let mut report = DerReport::new(1);
957        let json = format!(r#"{{"requestId":1,"curve":[{}]}}"#, curves.join(","));
958        assert!(report.add(&part(&json)).unwrap());
959        report.finish().unwrap()
960    }
961
962    #[test]
963    fn a_running_scheduled_control_beats_the_default_and_the_default_returns_after_it() {
964        let set = controls(&[
965            curve("default", "VoltWatt", true, false, r#","priority":1"#),
966            curve(
967                "event",
968                "VoltWatt",
969                false,
970                false,
971                r#","priority":0,"startTime":"2026-11-20T14:00:00Z","duration":3600"#,
972            ),
973        ]);
974        let kind = DERControl::VoltWatt;
975        assert_eq!(
976            set.effective(&kind, at("2026-11-20T14:30:00Z")).unwrap().id,
977            "event"
978        );
979        assert_eq!(
980            set.effective(&kind, at("2026-11-20T16:00:00Z")).unwrap().id,
981            "default"
982        );
983        // The window is half-open: the end instant belongs to the default again.
984        assert_eq!(
985            set.effective(&kind, at("2026-11-20T15:00:00Z")).unwrap().id,
986            "default"
987        );
988        assert_eq!(
989            set.effective(&kind, at("2026-11-20T13:59:59Z")).unwrap().id,
990            "default"
991        );
992    }
993
994    #[test]
995    fn the_lowest_priority_value_wins_and_a_superseded_control_is_never_in_effect() {
996        let set = controls(&[
997            curve("low", "FreqWatt", true, true, r#","priority":2"#),
998            curve("high", "FreqWatt", true, false, r#","priority":1"#),
999            curve("tie", "FreqWatt", true, false, r#","priority":1"#),
1000        ]);
1001        let effective = set.effective(&DERControl::FreqWatt, at("2026-11-20T00:00:00Z"));
1002        assert_eq!(effective.unwrap().id, "high");
1003
1004        // A superseded scheduled control inside its window falls back to the default.
1005        let set = controls(&[
1006            curve("default", "VoltWatt", true, false, r#","priority":3"#),
1007            curve(
1008                "gone",
1009                "VoltWatt",
1010                false,
1011                true,
1012                r#","priority":0,"startTime":"2026-11-20T00:00:00Z","duration":60"#,
1013            ),
1014        ]);
1015        let effective = set.effective(&DERControl::VoltWatt, at("2026-11-20T00:00:30Z"));
1016        assert_eq!(effective.unwrap().id, "default");
1017    }
1018
1019    #[test]
1020    fn only_controls_that_lower_or_stop_active_power_are_limiting() {
1021        let mut report = DerReport::new(4);
1022        report
1023            .add(&part(&format!(
1024                r#"{{"requestId":4,"tbc":true,"curve":[{},{}]}}"#,
1025                curve("vv", "VoltVar", true, false, r#","priority":0"#),
1026                curve("trip", "HVMustTrip", true, false, r#","priority":0"#),
1027            )))
1028            .unwrap();
1029        report
1030            .add(&part(
1031                r#"{"requestId":4,"freqDroop":[{"id":"droop","isDefault":true,"isSuperseded":false,
1032                    "freqDroop":{"priority":0,"overFreq":50.2,"underFreq":49.8,"overDroop":5,
1033                    "underDroop":5,"responseTime":1}}]}"#,
1034            ))
1035            .unwrap();
1036        let set = report.finish().unwrap();
1037        let ids: Vec<_> = set
1038            .limiting_at(at("2026-11-20T00:00:00Z"))
1039            .into_iter()
1040            .map(|c| c.id.as_str())
1041            .collect();
1042        assert_eq!(ids, ["trip", "droop"]);
1043        assert_eq!(set.effective_at(at("2026-11-20T00:00:00Z")).len(), 3);
1044    }
1045
1046    #[test]
1047    fn an_unknown_control_type_counts_as_limiting() {
1048        assert_eq!(
1049            effect(&DERControl::from_wire("VendorCurve")),
1050            Effect::Unknown
1051        );
1052        assert!(Effect::Unknown.limits_active_power());
1053        assert!(!Effect::Reactive.limits_active_power());
1054        assert!(!Effect::Slows.limits_active_power());
1055        let set = controls(&[curve("v", "VendorCurve", true, false, r#","priority":0"#)]);
1056        assert_eq!(set.limiting_at(at("2026-11-20T00:00:00Z")).len(), 1);
1057    }
1058
1059    #[test]
1060    fn a_stray_late_or_malformed_part_is_refused_and_changes_nothing() {
1061        let mut report = DerReport::new(7);
1062        let other = part(r#"{"requestId":8}"#);
1063        assert_eq!(
1064            report.add(&other),
1065            Err(DerError::RequestId {
1066                expected: 7,
1067                got: 8
1068            })
1069        );
1070        let wrong_array = part(&format!(
1071            r#"{{"requestId":7,"tbc":true,"curve":[{}]}}"#,
1072            curve("x", "FreqDroop", true, false, r#","priority":0"#)
1073        ));
1074        assert!(matches!(
1075            report.add(&wrong_array),
1076            Err(DerError::WrongArray { .. })
1077        ));
1078        let negative = part(&format!(
1079            r#"{{"requestId":7,"tbc":true,"curve":[{},{}]}}"#,
1080            curve("fine", "VoltVar", true, false, r#","priority":0"#),
1081            curve(
1082                "neg",
1083                "VoltVar",
1084                false,
1085                false,
1086                r#","priority":0,"startTime":"2026-11-20T00:00:00Z","duration":-5"#
1087            ),
1088        ));
1089        assert_eq!(
1090            report.add(&negative),
1091            Err(DerError::BadDuration("neg".into()))
1092        );
1093        let twice = part(&format!(
1094            r#"{{"requestId":7,"tbc":true,"curve":[{0},{0}]}}"#,
1095            curve("dup", "VoltVar", true, false, r#","priority":0"#)
1096        ));
1097        assert_eq!(report.add(&twice), Err(DerError::DuplicateId("dup".into())));
1098        assert!(!report.is_complete());
1099        assert_eq!(report.clone().finish(), Err(DerError::Incomplete));
1100
1101        // Nothing above was taken: an empty last part completes an empty report.
1102        assert_eq!(report.add(&part(r#"{"requestId":7}"#)), Ok(true));
1103        assert_eq!(
1104            report.add(&part(r#"{"requestId":7}"#)),
1105            Err(DerError::Complete)
1106        );
1107        assert!(report.finish().unwrap().is_empty());
1108    }
1109
1110    #[test]
1111    fn the_collector_is_bounded() {
1112        let mut report = DerReport::new(1).with_limit(2);
1113        let three = part(&format!(
1114            r#"{{"requestId":1,"curve":[{},{},{}]}}"#,
1115            curve("a", "VoltVar", true, false, r#","priority":0"#),
1116            curve("b", "VoltWatt", true, false, r#","priority":0"#),
1117            curve("c", "WattVar", true, false, r#","priority":0"#),
1118        ));
1119        assert_eq!(
1120            report.add(&three),
1121            Err(DerError::TooManyControls { limit: 2 })
1122        );
1123        assert!(!report.is_complete());
1124    }
1125
1126    #[test]
1127    fn a_limit_max_discharge_control_is_carried_as_reported() {
1128        let mut report = DerReport::new(1);
1129        report
1130            .add(&part(
1131                r#"{"requestId":1,"limitMaxDischarge":[{"id":"cap","isDefault":true,
1132                    "isSuperseded":false,"limitMaxDischarge":{"priority":0,"pctMaxDischargePower":50.0}}]}"#,
1133            ))
1134            .unwrap();
1135        let set = report.finish().unwrap();
1136        let control = set.get("cap").unwrap();
1137        assert_eq!(control.effect(), Effect::Lowers);
1138        let Setting::LimitMaxDischarge(setting) = &control.setting else {
1139            panic!("not a LimitMaxDischarge setting");
1140        };
1141        // The station's own number at its own scale; nothing derived from it.
1142        assert_eq!(setting.pct_max_discharge_power.unwrap().to_string(), "50.0");
1143    }
1144
1145    #[test]
1146    fn start_stop_notices_keep_the_inventory_current() {
1147        let mut set = controls(&[
1148            curve(
1149                "a",
1150                "VoltWatt",
1151                false,
1152                false,
1153                r#","priority":1,"startTime":"2026-11-20T00:00:00Z","duration":7200"#,
1154            ),
1155            curve(
1156                "b",
1157                "VoltWatt",
1158                false,
1159                false,
1160                r#","priority":0,"startTime":"2026-11-20T01:00:00Z","duration":600"#,
1161            ),
1162        ]);
1163        let started = v2_1::NotifyDERStartStopRequest::new("b", true, at("2026-11-20T01:00:00Z"))
1164            .with_superseded_ids(["a", "missing"]);
1165        assert_eq!(
1166            set.apply(&started),
1167            StartStop::Started {
1168                superseded: vec!["a".into()]
1169            }
1170        );
1171        assert!(set.get("a").unwrap().superseded);
1172        let ended = v2_1::NotifyDERStartStopRequest::new("b", false, at("2026-11-20T01:10:00Z"));
1173        assert!(matches!(set.apply(&ended), StartStop::Ended(control) if control.id == "b"));
1174        assert!(set.get("b").is_none());
1175        assert_eq!(set.apply(&ended), StartStop::UnknownControl("b".into()));
1176    }
1177
1178    fn alarm(
1179        kind: DERControl,
1180        fault: Option<v2_1::GridEventFault>,
1181        ended: bool,
1182    ) -> v2_1::NotifyDERAlarmRequest {
1183        let mut notice = v2_1::NotifyDERAlarmRequest::new(kind, at("2026-11-20T12:00:00Z"));
1184        notice.grid_event_fault = fault;
1185        notice.alarm_ended = ended.then_some(true);
1186        notice
1187    }
1188
1189    #[test]
1190    fn an_alarm_has_one_level() {
1191        use v2_1::GridEventFault::{OverFrequency, OverVoltage};
1192        let mut state = DerAlarmState::new();
1193        assert_eq!(
1194            state.apply(&alarm(DERControl::VoltWatt, Some(OverVoltage), false)),
1195            AlarmChange::Raised
1196        );
1197        assert_eq!(state.current().unwrap().kind, DERControl::VoltWatt);
1198        assert_eq!(
1199            state.apply(&alarm(DERControl::VoltWatt, Some(OverVoltage), false)),
1200            AlarmChange::Repeated
1201        );
1202        let replaced = state.apply(&alarm(DERControl::FreqDroop, Some(OverFrequency), false));
1203        assert!(
1204            matches!(replaced, AlarmChange::Replaced(previous) if previous.kind == DERControl::VoltWatt)
1205        );
1206        // R05.FR.04: the end of the first is never reported; one for it changes nothing.
1207        assert_eq!(
1208            state.apply(&alarm(DERControl::VoltWatt, None, true)),
1209            AlarmChange::Unmatched
1210        );
1211        assert_eq!(state.current().unwrap().kind, DERControl::FreqDroop);
1212        assert!(matches!(
1213            state.apply(&alarm(DERControl::FreqDroop, Some(OverFrequency), true)),
1214            AlarmChange::Cleared(_)
1215        ));
1216        assert!(state.current().is_none());
1217        assert_eq!(
1218            state.apply(&alarm(DERControl::FreqDroop, None, true)),
1219            AlarmChange::Unmatched
1220        );
1221    }
1222
1223    fn set_request(json: &str) -> v2_1::SetDERControlRequest {
1224        serde_json::from_str(json).unwrap()
1225    }
1226
1227    #[test]
1228    fn check_refuses_what_r04_forbids_and_names_the_rule() {
1229        let default_with_time = set_request(
1230            r#"{"isDefault":true,"controlId":"a","controlType":"FreqDroop","freqDroop":{"priority":0,
1231                "overFreq":50.2,"underFreq":49.8,"overDroop":5,"underDroop":5,"responseTime":1,
1232                "startTime":"2026-11-20T00:00:00Z"}}"#,
1233        );
1234        assert_eq!(
1235            check(&default_with_time).unwrap_err().requirement(),
1236            "R04.FR.13"
1237        );
1238        let scheduled_enter_service = set_request(
1239            r#"{"isDefault":false,"controlId":"a","controlType":"EnterService","enterService":{
1240                "priority":0,"highVoltage":253,"lowVoltage":207,"highFreq":50.1,"lowFreq":47.5}}"#,
1241        );
1242        assert_eq!(check(&scheduled_enter_service), Err(DerRule::DefaultOnly));
1243        let droop_as_curve = set_request(
1244            r#"{"isDefault":true,"controlId":"a","controlType":"FreqDroop","curve":{"priority":0,
1245                "yUnit":"PctMaxW","curveData":[{"x":1,"y":2}]}}"#,
1246        );
1247        assert_eq!(check(&droop_as_curve), Err(DerRule::FieldMismatch));
1248        let two_fields = set_request(
1249            r#"{"isDefault":true,"controlId":"a","controlType":"Gradients",
1250                "gradient":{"priority":0,"gradient":10,"softGradient":0},
1251                "curve":{"priority":0,"yUnit":"PctMaxW","curveData":[{"x":1,"y":2}]}}"#,
1252        );
1253        assert_eq!(check(&two_fields).unwrap_err().requirement(), "R04.FR.17");
1254        let none = set_request(r#"{"isDefault":true,"controlId":"a","controlType":"VoltVar"}"#);
1255        assert_eq!(check(&none), Err(DerRule::FieldMismatch));
1256        let wrong_unit = set_request(
1257            r#"{"isDefault":true,"controlId":"a","controlType":"VoltWatt","curve":{"priority":0,
1258                "yUnit":"PctMaxVar","curveData":[{"x":1,"y":2}]}}"#,
1259        );
1260        let error = check(&wrong_unit).unwrap_err();
1261        assert_eq!(error.requirement(), "R04.FR.53");
1262        assert!(error.to_string().contains("VoltWatt"));
1263        let monitoring = set_request(
1264            r#"{"isDefault":true,"controlId":"a","controlType":"LimitMaxDischarge",
1265                "limitMaxDischarge":{"priority":0,"pctMaxDischargePower":50,
1266                "powerMonitoringMustTrip":{"priority":0,"yUnit":"PctMaxW","curveData":[{"x":1,"y":2}]}}}"#,
1267        );
1268        assert_eq!(check(&monitoring).unwrap_err().requirement(), "R04.FR.56");
1269    }
1270
1271    #[test]
1272    fn check_accepts_the_specifications_own_examples() {
1273        // R04 scenario #1: a default frequency droop without startTime or duration.
1274        let droop = set_request(
1275            r#"{"isDefault":true,"controlId":"droop","controlType":"FreqDroop","freqDroop":{
1276                "priority":0,"overFreq":50.2,"underFreq":49.8,"overDroop":5,"underDroop":5,
1277                "responseTime":1}}"#,
1278        );
1279        assert_eq!(check(&droop), Ok(()));
1280        // R01: a default VoltWatt curve and a discharge limit of 50 %.
1281        let volt_watt = set_request(
1282            r#"{"isDefault":true,"controlId":"vw","controlType":"VoltWatt","curve":{"priority":0,
1283                "yUnit":"PctMaxW","curveData":[{"x":106,"y":100},{"x":110,"y":0}]}}"#,
1284        );
1285        assert_eq!(check(&volt_watt), Ok(()));
1286        let limit = set_request(
1287            r#"{"isDefault":true,"controlId":"lmd","controlType":"LimitMaxDischarge",
1288                "limitMaxDischarge":{"priority":0,"pctMaxDischargePower":50.0}}"#,
1289        );
1290        assert_eq!(check(&limit), Ok(()));
1291        // A scheduled trip curve with its window.
1292        let trip = set_request(
1293            r#"{"isDefault":false,"controlId":"hv","controlType":"HVMustTrip","curve":{"priority":0,
1294                "yUnit":"Not_Applicable","startTime":"2026-11-20T00:00:00Z","duration":3600,
1295                "curveData":[{"x":0.16,"y":120}]}}"#,
1296        );
1297        assert_eq!(check(&trip), Ok(()));
1298    }
1299}