1use alloc::string::String;
15use alloc::vec::Vec;
16
17use bon::Builder;
18use serde::{Deserialize, Serialize};
19
20use super::common::{PowerRange, Timer, Transition};
21use super::{Duration, Id, NumberRange, Timestamp};
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
29#[serde(deny_unknown_fields)]
30#[builder(on(String, into))]
31pub struct StorageDescription {
32 #[serde(skip_serializing_if = "Option::is_none")]
34 pub diagnostic_label: Option<String>,
35 #[serde(skip_serializing_if = "Option::is_none")]
38 pub fill_level_label: Option<String>,
39 pub provides_leakage_behaviour: bool,
41 pub provides_fill_level_target_profile: bool,
43 pub provides_usage_forecast: bool,
45 pub fill_level_range: NumberRange,
50}
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
58#[serde(deny_unknown_fields)]
59pub struct OperationModeElement {
60 pub fill_level_range: NumberRange,
62 pub fill_rate: NumberRange,
65 pub power_ranges: Vec<PowerRange>,
67 #[serde(skip_serializing_if = "Option::is_none")]
70 pub running_costs: Option<NumberRange>,
71}
72
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
75#[serde(deny_unknown_fields)]
76#[builder(on(String, into))]
77pub struct OperationMode {
78 pub id: Id,
80 #[serde(skip_serializing_if = "Option::is_none")]
82 pub diagnostic_label: Option<String>,
83 pub elements: Vec<OperationModeElement>,
85 pub abnormal_condition_only: bool,
87}
88
89impl OperationMode {
90 #[must_use]
92 pub fn element_at(&self, fill_level: f64) -> Option<&OperationModeElement> {
93 self.elements
94 .iter()
95 .find(|e| e.fill_level_range.contains(fill_level))
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
101#[serde(deny_unknown_fields)]
102#[builder(on(String, into))]
103pub struct ActuatorDescription {
104 pub id: Id,
106 #[serde(skip_serializing_if = "Option::is_none")]
108 pub diagnostic_label: Option<String>,
109 pub supported_commodities: Vec<super::common::Commodity>,
111 pub operation_modes: Vec<OperationMode>,
113 pub transitions: Vec<Transition>,
115 pub timers: Vec<Timer>,
117}
118
119impl ActuatorDescription {
120 #[must_use]
122 pub fn operation_mode(&self, id: &Id) -> Option<&OperationMode> {
123 self.operation_modes.iter().find(|m| m.id == *id)
124 }
125
126 #[must_use]
128 pub fn timer(&self, id: &Id) -> Option<&Timer> {
129 self.timers.iter().find(|t| t.id == *id)
130 }
131
132 #[must_use]
134 pub fn transition(&self, from: &Id, to: &Id) -> Option<&Transition> {
135 self.transitions
136 .iter()
137 .find(|t| t.from == *from && t.to == *to)
138 }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
143#[serde(deny_unknown_fields)]
144pub struct FillLevelTargetProfileElement {
145 pub duration: Duration,
147 pub fill_level_range: NumberRange,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
154#[serde(deny_unknown_fields)]
155pub struct LeakageBehaviourElement {
156 pub fill_level_range: NumberRange,
158 pub leakage_rate: f64,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
166#[serde(deny_unknown_fields)]
167pub struct UsageForecastElement {
168 pub duration: Duration,
170 #[serde(skip_serializing_if = "Option::is_none")]
172 pub usage_rate_upper_limit: Option<f64>,
173 #[serde(
175 rename = "usage_rate_upper_95PPR",
176 skip_serializing_if = "Option::is_none"
177 )]
178 pub usage_rate_upper_95ppr: Option<f64>,
179 #[serde(
181 rename = "usage_rate_upper_68PPR",
182 skip_serializing_if = "Option::is_none"
183 )]
184 pub usage_rate_upper_68ppr: Option<f64>,
185 pub usage_rate_expected: f64,
187 #[serde(
189 rename = "usage_rate_lower_68PPR",
190 skip_serializing_if = "Option::is_none"
191 )]
192 pub usage_rate_lower_68ppr: Option<f64>,
193 #[serde(
195 rename = "usage_rate_lower_95PPR",
196 skip_serializing_if = "Option::is_none"
197 )]
198 pub usage_rate_lower_95ppr: Option<f64>,
199 #[serde(skip_serializing_if = "Option::is_none")]
201 pub usage_rate_lower_limit: Option<f64>,
202}
203
204impl UsageForecastElement {
205 #[must_use]
207 pub fn bands_ascending(&self) -> [(&'static str, Option<f64>); 7] {
208 [
209 ("usage_rate_lower_limit", self.usage_rate_lower_limit),
210 ("usage_rate_lower_95PPR", self.usage_rate_lower_95ppr),
211 ("usage_rate_lower_68PPR", self.usage_rate_lower_68ppr),
212 ("usage_rate_expected", Some(self.usage_rate_expected)),
213 ("usage_rate_upper_68PPR", self.usage_rate_upper_68ppr),
214 ("usage_rate_upper_95PPR", self.usage_rate_upper_95ppr),
215 ("usage_rate_upper_limit", self.usage_rate_upper_limit),
216 ]
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
226#[serde(deny_unknown_fields)]
227pub struct SystemDescription {
228 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
230 pub message_id: Id,
231 pub valid_from: Timestamp,
233 pub actuators: Vec<ActuatorDescription>,
235 pub storage: StorageDescription,
237}
238
239impl SystemDescription {
240 #[must_use]
242 pub fn actuator(&self, id: &Id) -> Option<&ActuatorDescription> {
243 self.actuators.iter().find(|a| a.id == *id)
244 }
245}
246
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
249#[serde(deny_unknown_fields)]
250pub struct StorageStatus {
251 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
253 pub message_id: Id,
254 pub present_fill_level: f64,
256}
257
258impl StorageStatus {
259 #[cfg(feature = "uuid")]
261 #[must_use]
262 pub fn new(present_fill_level: f64) -> Self {
263 Self {
264 message_id: Id::generate(),
265 present_fill_level,
266 }
267 }
268}
269
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
272#[serde(deny_unknown_fields)]
273pub struct ActuatorStatus {
274 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
276 pub message_id: Id,
277 pub actuator_id: Id,
279 pub active_operation_mode_id: Id,
281 pub operation_mode_factor: f64,
283 #[serde(skip_serializing_if = "Option::is_none")]
286 pub previous_operation_mode_id: Option<Id>,
287 #[serde(skip_serializing_if = "Option::is_none")]
289 pub transition_timestamp: Option<Timestamp>,
290}
291
292#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
294#[serde(deny_unknown_fields)]
295pub struct TimerStatus {
296 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
298 pub message_id: Id,
299 pub timer_id: Id,
301 pub actuator_id: Id,
303 pub finished_at: Timestamp,
306}
307
308#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
310#[serde(deny_unknown_fields)]
311pub struct LeakageBehaviour {
312 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
314 pub message_id: Id,
315 pub valid_from: Timestamp,
317 pub elements: Vec<LeakageBehaviourElement>,
319}
320
321#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
323#[serde(deny_unknown_fields)]
324pub struct UsageForecast {
325 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
327 pub message_id: Id,
328 pub start_time: Timestamp,
330 pub elements: Vec<UsageForecastElement>,
332}
333
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
336#[serde(deny_unknown_fields)]
337pub struct FillLevelTargetProfile {
338 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
340 pub message_id: Id,
341 pub start_time: Timestamp,
343 pub elements: Vec<FillLevelTargetProfileElement>,
345}
346
347#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
349#[serde(deny_unknown_fields)]
350pub struct Instruction {
351 #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
353 pub message_id: Id,
354 pub id: Id,
358 pub actuator_id: Id,
360 pub operation_mode: Id,
365 pub operation_mode_factor: f64,
367 pub execution_time: Timestamp,
369 pub abnormal_condition: bool,
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use crate::types::common::CommodityQuantity;
377
378 #[test]
379 fn the_ev_example_from_the_docs_round_trips() {
380 let json = r#"{
382 "id": "om2",
383 "diagnostic_label": "Charging",
384 "elements": [
385 {
386 "fill_level_range": { "start_of_range": 0, "end_of_range": 100 },
387 "fill_rate": { "start_of_range": 0.00065, "end_of_range": 0.0051 },
388 "power_ranges": [
389 {
390 "start_of_range": 1400,
391 "end_of_range": 11000,
392 "commodity_quantity": "ELECTRIC.POWER.3_PHASE_SYMMETRIC"
393 }
394 ]
395 }
396 ],
397 "abnormal_condition_only": false
398 }"#;
399 let mode: OperationMode = serde_json::from_str(json).unwrap();
400 assert_eq!(mode.id, "om2");
401 let element = mode.element_at(50.0).unwrap();
402 assert_eq!(element.power_ranges.len(), 1);
403 assert!((element.fill_rate.at_factor(0.0) - 0.000_65).abs() < 1e-12);
406 assert!((element.power_ranges.first().unwrap().at_factor(0.0) - 1400.0).abs() < 1e-9);
407 assert!(mode.element_at(101.0).is_none());
409 }
410
411 #[test]
412 fn a_small_fill_rate_survives_the_json_round_trip() {
413 let original = 0.001_319_444_444_444_444_3_f64;
416 let element = LeakageBehaviourElement {
417 fill_level_range: NumberRange::new(0.0, 100.0),
418 leakage_rate: original,
419 };
420 let json = serde_json::to_string(&element).unwrap();
421 let back: LeakageBehaviourElement = serde_json::from_str(&json).unwrap();
422 assert_eq!(
423 back.leakage_rate.to_bits(),
424 original.to_bits(),
425 "fill rates must round-trip bit for bit"
426 );
427 }
428
429 #[test]
430 fn instruction_keeps_the_operation_mode_field_name() {
431 let instruction = Instruction {
432 message_id: Id::new_const("m1"),
433 id: Id::new_const("instr0"),
434 actuator_id: Id::new_const("actuator1"),
435 operation_mode: Id::new_const("om1"),
436 operation_mode_factor: 1.0,
437 execution_time: Timestamp::UNIX_EPOCH,
438 abnormal_condition: false,
439 };
440 let json = serde_json::to_string(&instruction).unwrap();
441 assert!(json.contains(r#""operation_mode":"om1""#));
442 assert!(!json.contains("operation_mode_id"));
443 }
444
445 #[test]
446 fn usage_and_leakage_rates_are_positive_when_the_level_falls() {
447 let e = UsageForecastElement::builder()
450 .duration(Duration::from_secs(900))
451 .usage_rate_expected(0.5)
452 .build();
453 assert!(
454 e.usage_rate_expected > 0.0,
455 "positive means the store drains"
456 );
457 let bands: Vec<_> = e.bands_ascending().iter().filter_map(|(_, v)| *v).collect();
458 assert_eq!(bands, alloc::vec![0.5]);
459 }
460
461 #[test]
462 fn power_range_interpolates_between_its_ends() {
463 let r = PowerRange::new(500.0, 2000.0, CommodityQuantity::ElectricPowerL1);
464 assert!((r.at_factor(1.0) - 2000.0).abs() < 1e-9);
465 assert_eq!(r.range(), NumberRange::new(500.0, 2000.0));
466 }
467}