1use alloc::format;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12
13use super::{
14 Limits, all_limits_at, blocking_timers, resolve_ddbc, resolve_frbc, resolve_ombc, resolve_ppbc,
15 timer_label, transition_duration,
16};
17use crate::message::{Message, MessageKind};
18use crate::types::common::{CommodityQuantity, PowerValue};
19use crate::types::{Duration, Id, Timestamp};
20use crate::validate::Context;
21
22#[derive(Debug, Clone, PartialEq)]
24#[non_exhaustive]
25pub struct Explanation {
26 pub instruction_id: Id,
28 pub kind: MessageKind,
30 pub execution_time: Timestamp,
32 pub abnormal_condition: bool,
34 pub actuator: Option<Id>,
36 pub operation_mode: Option<(Id, Option<String>)>,
38 pub factor: Option<f64>,
40 pub power: Vec<PowerValue>,
42 pub fill_rate: Option<f64>,
44 pub supply_rate: Option<f64>,
46 pub limits: Vec<(CommodityQuantity, Limits)>,
48 pub sequence: Option<(Id, Id, Id, Duration)>,
50 pub transition_duration: Duration,
52 pub blocked_by: Vec<(Id, Option<String>)>,
54 pub abnormal_only_misuse: bool,
56 pub notes: Vec<String>,
58}
59
60impl Explanation {
61 #[must_use]
64 pub fn is_actionable(&self) -> bool {
65 self.blocked_by.is_empty() && !self.abnormal_only_misuse
66 }
67
68 #[must_use]
70 pub fn electric_power(&self) -> Option<f64> {
71 self.power
72 .iter()
73 .find(|v| {
74 v.commodity_quantity.commodity() == crate::types::common::Commodity::Electricity
75 })
76 .map(|v| v.value)
77 }
78}
79
80impl core::fmt::Display for Explanation {
81 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
82 write!(f, "{} {}", self.kind, self.instruction_id)?;
83 if let Some(actuator) = &self.actuator {
84 write!(f, " on {actuator}")?;
85 }
86 if let Some((mode, label)) = &self.operation_mode {
87 match label {
88 Some(label) => write!(f, " → {label} ({mode})")?,
89 None => write!(f, " → {mode}")?,
90 }
91 }
92 if let Some(factor) = self.factor {
93 write!(f, " at factor {factor}")?;
94 }
95 for value in &self.power {
96 write!(f, ", {:?} {} W", value.commodity_quantity, value.value)?;
97 }
98 if let Some(rate) = self.fill_rate {
99 write!(f, ", filling at {rate}/s")?;
100 }
101 if let Some(rate) = self.supply_rate {
102 write!(f, ", supplying {rate}")?;
103 }
104 for (quantity, limits) in &self.limits {
105 write!(
106 f,
107 ", {:?} bounded to {}..{}",
108 quantity, limits.lower, limits.upper
109 )?;
110 }
111 if let Some((_, _, sequence, duration)) = &self.sequence {
112 write!(f, ", running {sequence} for {duration}")?;
113 }
114 if !self.transition_duration.is_zero() {
115 write!(f, ", taking effect after {}", self.transition_duration)?;
116 }
117 for (timer, label) in &self.blocked_by {
118 match label {
119 Some(label) => write!(f, "; blocked by {label} ({timer})")?,
120 None => write!(f, "; blocked by {timer}")?,
121 }
122 }
123 if self.abnormal_only_misuse {
124 write!(
125 f,
126 "; uses an abnormal-condition-only option without saying so"
127 )?;
128 }
129 for note in &self.notes {
130 write!(f, "; {note}")?;
131 }
132 Ok(())
133 }
134}
135
136#[must_use]
140#[allow(clippy::too_many_lines)] pub fn explain(message: &Message, ctx: &Context<'_>) -> Option<Explanation> {
142 let instruction_id = message.instruction_id()?;
143 let mut e = Explanation {
144 instruction_id,
145 kind: message.kind(),
146 execution_time: Timestamp::UNIX_EPOCH,
147 abnormal_condition: false,
148 actuator: None,
149 operation_mode: None,
150 factor: None,
151 power: Vec::new(),
152 fill_rate: None,
153 supply_rate: None,
154 limits: Vec::new(),
155 sequence: None,
156 transition_duration: Duration::ZERO,
157 blocked_by: Vec::new(),
158 abnormal_only_misuse: false,
159 notes: Vec::new(),
160 };
161
162 match message {
163 Message::FrbcInstruction(i) => {
164 e.execution_time = i.execution_time;
165 e.abnormal_condition = i.abnormal_condition;
166 e.actuator = Some(i.actuator_id);
167 e.factor = Some(i.operation_mode_factor);
168 let Some(system) = ctx.frbc else {
169 e.notes
170 .push("no FRBC.SystemDescription has been seen".into());
171 return Some(e);
172 };
173 match resolve_frbc(system, i, ctx.fill_level) {
174 Ok(r) => {
175 e.operation_mode = Some((r.mode.id, r.mode.diagnostic_label.clone()));
176 e.power = r.power;
177 e.fill_rate = r.fill_rate;
178 e.abnormal_only_misuse = r.abnormal_only && !i.abnormal_condition;
179 if !system
180 .storage
181 .fill_level_range
182 .contains(ctx.fill_level.unwrap_or(f64::NAN))
183 && ctx.fill_level.is_some()
184 {
185 e.notes.push(
186 "the fill level is outside the storage's range, so the Resource \
187 Manager may ignore this"
188 .into(),
189 );
190 }
191 note_transition(
192 &mut e,
193 ctx,
194 &i.actuator_id,
195 &i.operation_mode,
196 &r.actuator.transitions,
197 &r.actuator.timers,
198 );
199 }
200 Err(err) => e.notes.push(err.to_string()),
201 }
202 }
203 Message::OmbcInstruction(i) => {
204 e.execution_time = i.execution_time;
205 e.abnormal_condition = i.abnormal_condition;
206 e.factor = Some(i.operation_mode_factor);
207 let Some(system) = ctx.ombc else {
208 e.notes
209 .push("no OMBC.SystemDescription has been seen".into());
210 return Some(e);
211 };
212 match resolve_ombc(system, i) {
213 Ok(r) => {
214 e.operation_mode = Some((r.mode.id, r.mode.diagnostic_label.clone()));
215 e.power = r.power;
216 e.abnormal_only_misuse = r.abnormal_only && !i.abnormal_condition;
217 note_transition(
218 &mut e,
219 ctx,
220 &Id::NIL,
221 &i.operation_mode_id,
222 &system.transitions,
223 &system.timers,
224 );
225 }
226 Err(err) => e.notes.push(err.to_string()),
227 }
228 }
229 Message::DdbcInstruction(i) => {
230 e.execution_time = i.execution_time;
231 e.abnormal_condition = i.abnormal_condition;
232 e.actuator = Some(i.actuator_id);
233 e.factor = Some(i.operation_mode_factor);
234 let Some(system) = ctx.ddbc else {
235 e.notes
236 .push("no DDBC.SystemDescription has been seen".into());
237 return Some(e);
238 };
239 match resolve_ddbc(system, i) {
240 Ok(r) => {
241 e.operation_mode = Some((r.mode.id, r.mode.diagnostic_label.clone()));
242 e.power = r.power;
243 e.supply_rate = Some(r.supply_rate);
244 e.abnormal_only_misuse = r.abnormal_only && !i.abnormal_condition;
245 note_transition(
246 &mut e,
247 ctx,
248 &i.actuator_id,
249 &i.operation_mode_id,
250 &r.actuator.transitions,
251 &r.actuator.timers,
252 );
253 }
254 Err(err) => e.notes.push(err.to_string()),
255 }
256 }
257 Message::PebcInstruction(i) => {
258 e.execution_time = i.execution_time;
259 e.abnormal_condition = i.abnormal_condition;
260 e.limits = all_limits_at(i, i.execution_time);
261 if e.limits.is_empty() {
262 e.notes
263 .push("the envelope bounds nothing at its own execution time".into());
264 }
265 if !ctx
266 .pebc_constraints
267 .iter()
268 .any(|c| c.id == i.power_constraints_id)
269 && !ctx.pebc_constraints.is_empty()
270 {
271 e.notes.push(format!(
272 "{} names no published PEBC.PowerConstraints",
273 i.power_constraints_id
274 ));
275 }
276 }
277 Message::PpbcScheduleInstruction(i) => {
278 e.execution_time = i.execution_time;
279 e.abnormal_condition = i.abnormal_condition;
280 note_sequence(
281 &mut e,
282 ctx,
283 i.power_profile_id,
284 i.sequence_container_id,
285 i.power_sequence_id,
286 );
287 }
288 Message::PpbcStartInterruptionInstruction(i) => {
289 e.execution_time = i.execution_time;
290 e.abnormal_condition = i.abnormal_condition;
291 note_sequence(
292 &mut e,
293 ctx,
294 i.power_profile_id,
295 i.sequence_container_id,
296 i.power_sequence_id,
297 );
298 e.notes.push("pauses the sequence".into());
299 }
300 Message::PpbcEndInterruptionInstruction(i) => {
301 e.execution_time = i.execution_time;
302 e.abnormal_condition = i.abnormal_condition;
303 note_sequence(
304 &mut e,
305 ctx,
306 i.power_profile_id,
307 i.sequence_container_id,
308 i.power_sequence_id,
309 );
310 e.notes.push("resumes the sequence".into());
311 }
312 _ => return None,
313 }
314
315 if let Some(now) = ctx.now
316 && e.execution_time <= now
317 {
318 e.notes
319 .push("execution time has passed, so this means as soon as possible".into());
320 }
321 Some(e)
322}
323
324fn note_transition(
325 e: &mut Explanation,
326 ctx: &Context<'_>,
327 actuator: &Id,
328 to: &Id,
329 transitions: &[crate::types::common::Transition],
330 timers: &[crate::types::common::Timer],
331) {
332 let Some(active) = ctx
333 .active_modes
334 .iter()
335 .find(|(a, _)| a == actuator)
336 .map(|(_, m)| *m)
337 else {
338 return;
339 };
340 if active == *to {
341 e.notes
342 .push("already in this operation mode; only the factor changes".into());
343 return;
344 }
345 e.transition_duration = transition_duration(transitions, &active, to);
346 if let Some(now) = ctx.now {
347 e.blocked_by = blocking_timers(transitions, &active, to, actuator, ctx.timers, now)
348 .into_iter()
349 .map(|id| (id, timer_label(timers, &id).map(ToString::to_string)))
350 .collect();
351 }
352 if transitions
353 .iter()
354 .all(|t| !(t.from == active && t.to == *to))
355 {
356 e.notes
357 .push(format!("no transition is described from {active}"));
358 }
359}
360
361fn note_sequence(e: &mut Explanation, ctx: &Context<'_>, profile: Id, container: Id, sequence: Id) {
362 match resolve_ppbc(ctx.ppbc_profiles, &profile, &container, &sequence) {
363 Ok(r) => e.sequence = Some((profile, container, sequence, r.duration)),
364 Err(err) => {
365 e.sequence = Some((profile, container, sequence, Duration::ZERO));
366 if !ctx.ppbc_profiles.is_empty() {
367 e.notes.push(err.to_string());
368 }
369 }
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use crate::types::common::{Commodity, NumberRange, PowerRange, Transition};
377 use crate::types::frbc;
378 use alloc::vec;
379
380 fn system() -> frbc::SystemDescription {
381 frbc::SystemDescription {
382 message_id: Id::new_const("m1"),
383 valid_from: Timestamp::UNIX_EPOCH,
384 actuators: vec![frbc::ActuatorDescription {
385 id: Id::new_const("actuator1"),
386 diagnostic_label: Some("EV charger".into()),
387 supported_commodities: vec![Commodity::Electricity],
388 operation_modes: vec![
389 frbc::OperationMode {
390 id: Id::new_const("om1"),
391 diagnostic_label: Some("Off".into()),
392 elements: vec![frbc::OperationModeElement {
393 fill_level_range: NumberRange::new(0.0, 100.0),
394 fill_rate: NumberRange::exactly(0.0),
395 power_ranges: vec![PowerRange::exactly(
396 0.0,
397 CommodityQuantity::ElectricPower3PhaseSymmetric,
398 )],
399 running_costs: None,
400 }],
401 abnormal_condition_only: false,
402 },
403 frbc::OperationMode {
404 id: Id::new_const("om2"),
405 diagnostic_label: Some("Charging".into()),
406 elements: vec![frbc::OperationModeElement {
407 fill_level_range: NumberRange::new(0.0, 100.0),
408 fill_rate: NumberRange::new(0.000_65, 0.0051),
409 power_ranges: vec![PowerRange::new(
410 1400.0,
411 11_000.0,
412 CommodityQuantity::ElectricPower3PhaseSymmetric,
413 )],
414 running_costs: None,
415 }],
416 abnormal_condition_only: false,
417 },
418 ],
419 transitions: vec![Transition {
420 id: Id::new_const("transition1"),
421 from: Id::new_const("om1"),
422 to: Id::new_const("om2"),
423 start_timers: vec![],
424 blocking_timers: vec![Id::new_const("timer0")],
425 transition_costs: None,
426 transition_duration: Some(Duration::from_secs(3)),
427 abnormal_condition_only: false,
428 }],
429 timers: vec![crate::types::common::Timer {
430 id: Id::new_const("timer0"),
431 diagnostic_label: Some("Minimum off time".into()),
432 duration: Duration::from_secs(3600),
433 }],
434 }],
435 storage: frbc::StorageDescription {
436 diagnostic_label: None,
437 fill_level_label: None,
438 provides_leakage_behaviour: false,
439 provides_fill_level_target_profile: false,
440 provides_usage_forecast: false,
441 fill_level_range: NumberRange::new(0.0, 100.0),
442 },
443 }
444 }
445
446 fn instruction() -> Message {
447 Message::from(frbc::Instruction {
448 message_id: Id::new_const("m2"),
449 id: Id::new_const("instr0"),
450 actuator_id: Id::new_const("actuator1"),
451 operation_mode: Id::new_const("om2"),
452 operation_mode_factor: 0.5,
453 execution_time: "2024-01-01T12:00:00Z".parse().unwrap(),
454 abnormal_condition: false,
455 })
456 }
457
458 #[test]
459 fn an_explanation_names_the_power_and_the_mode_a_human_would_recognise() {
460 let system = system();
461 let ctx = Context {
462 frbc: Some(&system),
463 fill_level: Some(50.0),
464 ..Context::empty()
465 };
466 let e = explain(&instruction(), &ctx).unwrap();
467 assert_eq!(e.operation_mode.clone().unwrap().1.unwrap(), "Charging");
468 assert!((e.power[0].value - 6200.0).abs() < 1e-9);
469 assert!(e.is_actionable());
470 let rendered = e.to_string();
471 assert!(rendered.contains("Charging"), "{rendered}");
472 assert!(rendered.contains("6200"), "{rendered}");
473 }
474
475 #[test]
476 fn an_explanation_says_when_a_timer_is_in_the_way() {
477 let system = system();
478 let now: Timestamp = "2024-01-01T12:00:00Z".parse().unwrap();
479 let active = [(Id::new_const("actuator1"), Id::new_const("om1"))];
480 let timers = [crate::validate::TimerState {
481 actuator: Id::new_const("actuator1"),
482 timer: Id::new_const("timer0"),
483 finished_at: "2024-01-01T12:30:00Z".parse().unwrap(),
484 }];
485 let ctx = Context {
486 frbc: Some(&system),
487 fill_level: Some(50.0),
488 active_modes: &active,
489 timers: &timers,
490 now: Some(now),
491 ..Context::empty()
492 };
493 let e = explain(&instruction(), &ctx).unwrap();
494 assert!(!e.is_actionable());
495 assert_eq!(e.blocked_by.len(), 1);
496 assert_eq!(e.blocked_by[0].1.as_deref(), Some("Minimum off time"));
497 assert_eq!(e.transition_duration, Duration::from_secs(3));
498 assert!(e.to_string().contains("Minimum off time"));
499 }
500
501 #[test]
502 fn an_explanation_without_a_description_says_so_rather_than_guessing() {
503 let e = explain(&instruction(), &Context::empty()).unwrap();
504 assert!(e.power.is_empty());
505 assert_eq!(e.notes, vec!["no FRBC.SystemDescription has been seen"]);
506 }
507
508 #[test]
509 fn nothing_to_explain_about_a_measurement() {
510 let m = Message::from(frbc::StorageStatus {
511 message_id: Id::new_const("m1"),
512 present_fill_level: 50.0,
513 });
514 assert!(explain(&m, &Context::empty()).is_none());
515 }
516}