1use alloc::vec::Vec;
13
14use bon::Builder;
15use serde::{Deserialize, Serialize};
16
17use super::common::CommodityQuantity;
18use super::{Duration, Id, NumberRange, Timestamp};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
23pub enum PowerEnvelopeLimitType {
24 UpperLimit,
26 LowerLimit,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
33pub enum PowerEnvelopeConsequenceType {
34 Vanish,
37 Defer,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
48#[serde(deny_unknown_fields)]
49pub struct AllowedLimitRange {
50 pub commodity_quantity: CommodityQuantity,
52 pub limit_type: PowerEnvelopeLimitType,
54 pub range_boundary: NumberRange,
56 pub abnormal_condition_only: bool,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct PowerEnvelopeElement {
64 pub duration: Duration,
66 pub upper_limit: f64,
68 pub lower_limit: f64,
70}
71
72impl PowerEnvelopeElement {
73 #[must_use]
75 pub const fn new(duration: Duration, lower_limit: f64, upper_limit: f64) -> Self {
76 Self {
77 duration,
78 upper_limit,
79 lower_limit,
80 }
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
86#[serde(deny_unknown_fields)]
87pub struct PowerEnvelope {
88 pub id: Id,
90 pub commodity_quantity: CommodityQuantity,
92 pub power_envelope_elements: Vec<PowerEnvelopeElement>,
94}
95
96impl PowerEnvelope {
97 #[must_use]
99 pub fn total_duration(&self) -> Duration {
100 self.power_envelope_elements
101 .iter()
102 .fold(Duration::ZERO, |acc, e| {
103 acc.checked_add(e.duration).unwrap_or(acc)
104 })
105 }
106
107 #[must_use]
112 pub fn element_at(&self, offset: Duration) -> Option<&PowerEnvelopeElement> {
113 let mut elapsed = 0u64;
114 let target = offset.as_millis();
115 for element in &self.power_envelope_elements {
116 let end = elapsed.saturating_add(element.duration.as_millis());
117 if target < end {
118 return Some(element);
119 }
120 elapsed = end;
121 }
122 None
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
128#[serde(deny_unknown_fields)]
129pub struct PowerConstraints {
130 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
132 pub message_id: Id,
133 pub id: Id,
135 pub valid_from: Timestamp,
137 #[serde(skip_serializing_if = "Option::is_none")]
139 pub valid_until: Option<Timestamp>,
140 pub consequence_type: PowerEnvelopeConsequenceType,
142 pub allowed_limit_ranges: Vec<AllowedLimitRange>,
144}
145
146impl PowerConstraints {
147 #[must_use]
149 pub fn is_valid_at(&self, now: Timestamp) -> bool {
150 now >= self.valid_from && self.valid_until.is_none_or(|until| now < until)
151 }
152
153 pub fn ranges_for(
155 &self,
156 quantity: CommodityQuantity,
157 limit_type: PowerEnvelopeLimitType,
158 ) -> impl Iterator<Item = &AllowedLimitRange> {
159 self.allowed_limit_ranges
160 .iter()
161 .filter(move |r| r.commodity_quantity == quantity && r.limit_type == limit_type)
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
167#[serde(deny_unknown_fields)]
168pub struct EnergyConstraint {
169 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
171 pub message_id: Id,
172 pub id: Id,
174 pub valid_from: Timestamp,
176 pub valid_until: Timestamp,
178 pub upper_average_power: f64,
180 pub lower_average_power: f64,
186 pub commodity_quantity: CommodityQuantity,
188}
189
190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
192#[serde(deny_unknown_fields)]
193pub struct Instruction {
194 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
196 pub message_id: Id,
197 pub id: Id,
199 pub execution_time: Timestamp,
201 pub abnormal_condition: bool,
203 pub power_constraints_id: Id,
205 pub power_envelopes: Vec<PowerEnvelope>,
207}
208
209impl Instruction {
210 #[must_use]
212 pub fn envelope_for(&self, quantity: CommodityQuantity) -> Option<&PowerEnvelope> {
213 self.power_envelopes
214 .iter()
215 .find(|e| e.commodity_quantity == quantity)
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 #[test]
224 fn the_pv_example_from_the_docs_parses() {
225 let json = r#"{
227 "message_id": "aaaaaaaa-0000-0000-0000-000000000001",
228 "id": "powerConstraint1",
229 "valid_from": "2024-08-24T14:15:22Z",
230 "valid_until": "2024-08-25T14:15:22Z",
231 "consequence_type": "VANISH",
232 "allowed_limit_ranges": [
233 {
234 "commodity_quantity": "ELECTRIC.POWER.L1",
235 "limit_type": "LOWER_LIMIT",
236 "range_boundary": { "start_of_range": -4000, "end_of_range": 0 },
237 "abnormal_condition_only": false
238 },
239 {
240 "commodity_quantity": "ELECTRIC.POWER.L1",
241 "limit_type": "UPPER_LIMIT",
242 "range_boundary": { "start_of_range": 0, "end_of_range": 0 },
243 "abnormal_condition_only": false
244 }
245 ]
246 }"#;
247 let c: PowerConstraints = serde_json::from_str(json).unwrap();
248 assert_eq!(c.id, "powerConstraint1");
249 assert_eq!(c.consequence_type, PowerEnvelopeConsequenceType::Vanish);
250 let lower: Vec<_> = c
251 .ranges_for(
252 CommodityQuantity::ElectricPowerL1,
253 PowerEnvelopeLimitType::LowerLimit,
254 )
255 .collect();
256 assert_eq!(lower.len(), 1);
257 assert!(lower[0].range_boundary.contains(-2000.0));
259 assert!(!lower[0].range_boundary.contains(-5000.0));
260 }
261
262 #[test]
263 fn validity_window_is_half_open_and_tolerates_an_open_end() {
264 let from: Timestamp = "2024-08-24T14:00:00Z".parse().unwrap();
265 let until: Timestamp = "2024-08-24T15:00:00Z".parse().unwrap();
266 let c = PowerConstraints {
267 message_id: Id::new_const("m1"),
268 id: Id::new_const("pc1"),
269 valid_from: from,
270 valid_until: Some(until),
271 consequence_type: PowerEnvelopeConsequenceType::Vanish,
272 allowed_limit_ranges: Vec::new(),
273 };
274 assert!(!c.is_valid_at("2024-08-24T13:59:59Z".parse().unwrap()));
275 assert!(c.is_valid_at(from));
276 assert!(c.is_valid_at("2024-08-24T14:59:59Z".parse().unwrap()));
277 assert!(!c.is_valid_at(until));
278
279 let open = PowerConstraints {
280 valid_until: None,
281 ..c
282 };
283 assert!(open.is_valid_at("2099-01-01T00:00:00Z".parse().unwrap()));
284 }
285
286 #[test]
287 fn an_envelope_runs_out_rather_than_clamping() {
288 let e = PowerEnvelope {
289 id: Id::new_const("pe1"),
290 commodity_quantity: CommodityQuantity::ElectricPowerL1,
291 power_envelope_elements: alloc::vec![
292 PowerEnvelopeElement::new(Duration::from_secs(60), -2000.0, 0.0),
293 PowerEnvelopeElement::new(Duration::from_secs(60), -1000.0, 0.0),
294 ],
295 };
296 assert_eq!(e.total_duration(), Duration::from_secs(120));
297 assert_eq!(e.element_at(Duration::ZERO).unwrap().lower_limit, -2000.0);
298 assert_eq!(
299 e.element_at(Duration::from_secs(59)).unwrap().lower_limit,
300 -2000.0
301 );
302 assert_eq!(
303 e.element_at(Duration::from_secs(60)).unwrap().lower_limit,
304 -1000.0
305 );
306 assert!(e.element_at(Duration::from_secs(120)).is_none());
309 }
310}