1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
88pub enum Effect {
89 Lowers,
92 Stops,
95 Slows,
98 Reactive,
102 Unknown,
104}
105
106impl Effect {
107 #[must_use]
110 pub const fn limits_active_power(self) -> bool {
111 matches!(self, Self::Lowers | Self::Stops | Self::Unknown)
112 }
113}
114
115#[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
144fn 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#[derive(Clone, Debug, PartialEq)]
161pub enum Setting {
162 Curve(v2_1::DERCurve),
164 EnterService(v2_1::EnterService),
166 FixedPfAbsorb(v2_1::FixedPF),
168 FixedPfInject(v2_1::FixedPF),
170 FixedVar(v2_1::FixedVar),
172 FreqDroop(v2_1::FreqDroop),
174 Gradient(v2_1::Gradient),
176 LimitMaxDischarge(v2_1::LimitMaxDischarge),
183}
184
185impl Setting {
186 #[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 #[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 #[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#[derive(Clone, Debug, PartialEq)]
229#[non_exhaustive]
230pub struct DerControl {
231 pub id: String,
233 pub kind: DERControl,
235 pub default: bool,
238 pub superseded: bool,
240 pub setting: Setting,
242 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 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 #[must_use]
289 pub fn priority(&self) -> i32 {
290 self.setting.priority()
291 }
292
293 #[must_use]
295 pub fn effect(&self) -> Effect {
296 effect(&self.kind)
297 }
298
299 #[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#[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 pub const DEFAULT_LIMIT: usize = 1024;
328
329 #[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 #[must_use]
342 pub fn with_limit(mut self, limit: usize) -> Self {
343 self.limit = limit;
344 self
345 }
346
347 #[must_use]
349 pub fn is_complete(&self) -> bool {
350 self.complete
351 }
352
353 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 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
401fn 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 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#[derive(Clone, Debug, Default, PartialEq)]
499pub struct DerControls {
500 controls: Vec<DerControl>,
501}
502
503impl DerControls {
504 pub fn iter(&self) -> impl Iterator<Item = &DerControl> {
506 self.controls.iter()
507 }
508
509 #[must_use]
511 pub fn len(&self) -> usize {
512 self.controls.len()
513 }
514
515 #[must_use]
517 pub fn is_empty(&self) -> bool {
518 self.controls.is_empty()
519 }
520
521 #[must_use]
523 pub fn get(&self, id: &str) -> Option<&DerControl> {
524 self.controls.iter().find(|control| control.id == id)
525 }
526
527 #[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 #[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 #[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 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(¬ice.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#[derive(Clone, Debug, PartialEq)]
605#[must_use = "an unknown control means the inventory is stale: ask the station again"]
606pub enum StartStop {
607 Started {
609 superseded: Vec<String>,
611 },
612 Ended(Box<DerControl>),
614 UnknownControl(String),
617}
618
619#[derive(Clone, Debug, PartialEq, Eq)]
621#[non_exhaustive]
622pub struct DerAlarm {
623 pub kind: DERControl,
625 pub fault: Option<v2_1::GridEventFault>,
627 pub since: DateTime,
629 pub extra_info: Option<String>,
631}
632
633#[derive(Clone, Debug, Default, PartialEq, Eq)]
638pub struct DerAlarmState {
639 current: Option<DerAlarm>,
640}
641
642impl DerAlarmState {
643 #[must_use]
645 pub fn new() -> Self {
646 Self::default()
647 }
648
649 #[must_use]
651 pub fn current(&self) -> Option<&DerAlarm> {
652 self.current.as_ref()
653 }
654
655 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 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#[derive(Clone, Debug, PartialEq, Eq)]
693#[must_use = "an unmatched end means the alarm state and the station disagree"]
694pub enum AlarmChange {
695 Raised,
697 Repeated,
699 Replaced(DerAlarm),
701 Cleared(DerAlarm),
703 Unmatched,
705}
706
707#[derive(Clone, Debug, PartialEq, Eq)]
709#[non_exhaustive]
710pub enum DerRule {
711 DefaultWithTime,
713 DefaultOnly,
715 FieldMismatch,
717 WrongYUnit {
719 kind: DERControl,
721 unit: DERUnit,
723 },
724}
725
726impl DerRule {
727 #[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
771fn 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
796pub 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#[derive(Clone, Debug, PartialEq, Eq)]
871#[non_exhaustive]
872pub enum DerError {
873 RequestId {
875 expected: i32,
877 got: i32,
879 },
880 Complete,
882 Incomplete,
884 WrongArray {
886 id: String,
888 kind: DERControl,
890 },
891 DuplicateId(String),
893 TooManyControls {
895 limit: usize,
897 },
898 BadDuration(String),
900}
901
902impl fmt::Display for DerError {
903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904 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 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 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 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 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 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 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 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 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}