1use alloc::format;
23use alloc::string::{String, ToString};
24use alloc::vec::Vec;
25
26use crate::message::{Message, MessageKind};
27use crate::session::{
28 Analyzer, CemConfig, CemEvent, CemSession, Instructed, RmConfig, RmEvent, RmSession,
29};
30use crate::types::common::{
31 Commodity, CommodityQuantity, ControlType, NumberRange, PowerRange, ReceptionStatusValues,
32 ResourceManagerDetails, Role, RoleType, Timer, Transition,
33};
34use crate::types::{Duration, Id, Timestamp, frbc, pebc};
35use crate::validate::Severity;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Direction {
40 CemToRm,
42 RmToCem,
44}
45
46impl Direction {
47 #[must_use]
49 pub const fn as_str(self) -> &'static str {
50 match self {
51 Direction::CemToRm => "cem>rm",
52 Direction::RmToCem => "rm>cem",
53 }
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct TranscriptEntry {
60 pub at: Timestamp,
62 pub direction: Direction,
64 pub kind: MessageKind,
66 pub text: String,
68}
69
70impl Direction {
71 #[must_use]
73 pub const fn sender(self) -> crate::types::common::EnergyManagementRole {
74 match self {
75 Direction::CemToRm => crate::types::common::EnergyManagementRole::Cem,
76 Direction::RmToCem => crate::types::common::EnergyManagementRole::Rm,
77 }
78 }
79
80 #[must_use]
82 pub fn parse(s: &str) -> Option<Self> {
83 match s {
84 "cem>rm" => Some(Direction::CemToRm),
85 "rm>cem" => Some(Direction::RmToCem),
86 _ => None,
87 }
88 }
89}
90
91impl TranscriptEntry {
92 #[must_use]
94 pub fn to_jsonl(&self) -> String {
95 format!(
96 r#"{{"t":"{}","dir":"{}","msg":{}}}"#,
97 self.at,
98 self.direction.as_str(),
99 self.text
100 )
101 }
102
103 #[must_use]
108 pub fn from_jsonl(line: &str) -> Option<Self> {
109 let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
110 let at = value.get("t")?.as_str()?.parse().ok()?;
111 let direction = Direction::parse(value.get("dir")?.as_str()?)?;
112 let text = value.get("msg")?.to_string();
113 let kind = crate::codec::peek(&text).ok().and_then(|p| p.kind)?;
117 Some(Self {
118 at,
119 direction,
120 kind,
121 text,
122 })
123 }
124}
125
126#[must_use]
128pub fn read_s2log(text: &str) -> Vec<TranscriptEntry> {
129 text.lines()
130 .filter_map(TranscriptEntry::from_jsonl)
131 .collect()
132}
133
134pub struct Conversation {
136 pub rm: RmSession,
138 pub cem: CemSession,
140 pub now: Timestamp,
142 transcript: Vec<TranscriptEntry>,
143 rm_events: Vec<RmEvent>,
144 cem_events: Vec<CemEvent>,
145}
146
147impl Conversation {
148 #[must_use]
150 pub fn new(
151 rm_config: RmConfig,
152 details: ResourceManagerDetails,
153 cem_config: CemConfig,
154 ) -> Self {
155 Self {
156 rm: RmSession::new(rm_config, details),
157 cem: CemSession::new(cem_config),
158 now: "2024-01-01T12:00:00Z"
159 .parse()
160 .unwrap_or(Timestamp::UNIX_EPOCH),
161 transcript: Vec::new(),
162 rm_events: Vec::new(),
163 cem_events: Vec::new(),
164 }
165 }
166
167 #[must_use]
169 pub fn battery() -> Self {
170 Self::new(RmConfig::default(), battery_details(), CemConfig::default())
171 }
172
173 #[must_use]
175 pub fn pv() -> Self {
176 Self::new(RmConfig::default(), pv_details(), CemConfig::default())
177 }
178
179 pub fn open(&mut self) {
181 self.rm.open(self.now);
182 self.cem.open(self.now);
183 self.pump();
184 }
185
186 #[allow(clippy::panic)] pub fn pump(&mut self) {
196 for _ in 0..1000 {
197 let mut moved = false;
198 while let Some(out) = self.rm.poll_transmit() {
199 self.record(Direction::RmToCem, out.kind, &out.text);
200 self.cem.handle_text(&out.text, self.now);
201 moved = true;
202 }
203 while let Some(out) = self.cem.poll_transmit() {
204 self.record(Direction::CemToRm, out.kind, &out.text);
205 self.rm.handle_text(&out.text, self.now);
206 moved = true;
207 }
208 self.drain_events();
209 if !moved {
210 return;
211 }
212 }
213 panic!("the conversation did not settle: a session is answering its own answers");
214 }
215
216 fn record(&mut self, direction: Direction, kind: MessageKind, text: &str) {
217 self.transcript.push(TranscriptEntry {
218 at: self.now,
219 direction,
220 kind,
221 text: text.to_string(),
222 });
223 }
224
225 fn drain_events(&mut self) {
226 while let Some(event) = self.rm.poll_event() {
227 self.rm_events.push(event);
228 }
229 while let Some(event) = self.cem.poll_event() {
230 self.cem_events.push(event);
231 }
232 }
233
234 pub fn advance(&mut self, by: Duration) {
236 self.now = self.now.checked_add(by).unwrap_or(self.now);
237 self.rm.handle_timeout(self.now);
238 self.cem.handle_timeout(self.now);
239 self.pump();
240 }
241
242 pub fn advance_silently(&mut self, by: Duration) {
245 self.now = self.now.checked_add(by).unwrap_or(self.now);
246 self.rm.handle_timeout(self.now);
247 self.cem.handle_timeout(self.now);
248 self.drain_events();
249 }
250
251 pub fn drop_rm_traffic(&mut self) {
254 while self.rm.poll_transmit().is_some() {}
255 self.drain_events();
256 }
257
258 pub fn drop_cem_traffic(&mut self) {
260 while self.cem.poll_transmit().is_some() {}
261 self.drain_events();
262 }
263
264 #[must_use]
266 pub fn transcript(&self) -> &[TranscriptEntry] {
267 &self.transcript
268 }
269
270 #[must_use]
272 pub fn to_s2log(&self) -> String {
273 let mut out = String::new();
274 for entry in &self.transcript {
275 out.push_str(&entry.to_jsonl());
276 out.push('\n');
277 }
278 out
279 }
280
281 #[must_use]
283 pub fn flow(&self) -> Vec<(Direction, MessageKind)> {
284 self.transcript
285 .iter()
286 .map(|e| (e.direction, e.kind))
287 .collect()
288 }
289
290 #[must_use]
292 pub fn flow_without_acks(&self) -> Vec<(Direction, MessageKind)> {
293 self.flow()
294 .into_iter()
295 .filter(|(_, kind)| *kind != MessageKind::ReceptionStatus)
296 .collect()
297 }
298
299 pub fn take_rm_events(&mut self) -> Vec<RmEvent> {
301 self.drain_events();
302 core::mem::take(&mut self.rm_events)
303 }
304
305 pub fn take_cem_events(&mut self) -> Vec<CemEvent> {
307 self.drain_events();
308 core::mem::take(&mut self.cem_events)
309 }
310
311 pub fn first_instruction(&mut self) -> Option<Instructed> {
313 self.drain_events();
314 self.rm_events.iter().find_map(|e| match e {
315 RmEvent::Instruction(i) => Some((**i).clone()),
316 _ => None,
317 })
318 }
319
320 #[must_use]
322 pub fn refusals(&self) -> Vec<String> {
323 let mut out = Vec::new();
324 for event in &self.rm_events {
325 if let RmEvent::Refused { report, .. } = event {
326 out.push(format!("RM refused: {report}"));
327 }
328 }
329 for event in &self.cem_events {
330 if let CemEvent::Refused { report, .. } = event {
331 out.push(format!("CEM refused: {report}"));
332 }
333 }
334 out
335 }
336
337 pub fn assert_no_refusals(&self) {
343 let refusals = self.refusals();
344 assert!(refusals.is_empty(), "{refusals:#?}");
345 }
346}
347
348#[must_use]
354pub fn battery_details() -> ResourceManagerDetails {
355 ResourceManagerDetails {
356 message_id: Id::new_const("rmd-battery"),
357 resource_id: Id::new_const("acme_battery_1"),
358 name: Some("Home battery".into()),
359 roles: alloc::vec![Role::new(RoleType::EnergyStorage, Commodity::Electricity)],
360 manufacturer: Some("ACME".into()),
361 model: Some("Powerwall-ish".into()),
362 serial_number: Some("123".into()),
363 firmware_version: Some("v1.0".into()),
364 instruction_processing_delay: Duration::from_millis(500),
365 available_control_types: alloc::vec![ControlType::FillRateBasedControl],
366 currency: None,
367 provides_forecast: false,
368 provides_power_measurement_types: alloc::vec![
369 CommodityQuantity::ElectricPower3PhaseSymmetric
370 ],
371 }
372}
373
374#[must_use]
376pub fn battery_system(valid_from: Timestamp) -> frbc::SystemDescription {
377 let mode =
378 |id: &'static str, label: &str, rate: NumberRange, power: PowerRange| frbc::OperationMode {
379 id: Id::new_const(id),
380 diagnostic_label: Some(label.to_string()),
381 elements: alloc::vec![frbc::OperationModeElement {
382 fill_level_range: NumberRange::new(0.0, 100.0),
383 fill_rate: rate,
384 power_ranges: alloc::vec![power],
385 running_costs: None,
386 }],
387 abnormal_condition_only: false,
388 };
389 let q = CommodityQuantity::ElectricPower3PhaseSymmetric;
390 frbc::SystemDescription {
391 message_id: Id::new_const("frbc-system-1"),
392 valid_from,
393 actuators: alloc::vec![frbc::ActuatorDescription {
394 id: Id::new_const("actuator1"),
395 diagnostic_label: Some("Battery inverter".into()),
396 supported_commodities: alloc::vec![Commodity::Electricity],
397 operation_modes: alloc::vec![
398 mode(
399 "idle",
400 "Idle",
401 NumberRange::exactly(0.0),
402 PowerRange::exactly(0.0, q)
403 ),
404 mode(
405 "charge",
406 "Charging",
407 NumberRange::new(0.0, 0.0025),
408 PowerRange::new(0.0, 5000.0, q),
409 ),
410 mode(
411 "discharge",
412 "Discharging",
413 NumberRange::new(0.0, -0.0025),
414 PowerRange::new(0.0, -5000.0, q),
415 ),
416 ],
417 transitions: alloc::vec![
418 Transition::simple(
419 Id::new_const("t1"),
420 Id::new_const("idle"),
421 Id::new_const("charge")
422 ),
423 Transition::simple(
424 Id::new_const("t2"),
425 Id::new_const("charge"),
426 Id::new_const("idle")
427 ),
428 Transition::simple(
429 Id::new_const("t3"),
430 Id::new_const("idle"),
431 Id::new_const("discharge")
432 ),
433 Transition {
434 id: Id::new_const("t4"),
435 from: Id::new_const("discharge"),
436 to: Id::new_const("idle"),
437 start_timers: alloc::vec![],
438 blocking_timers: alloc::vec![Id::new_const("cooldown")],
439 transition_costs: None,
440 transition_duration: None,
441 abnormal_condition_only: false,
442 },
443 ],
444 timers: alloc::vec![Timer {
445 id: Id::new_const("cooldown"),
446 diagnostic_label: Some("Minimum discharge time".into()),
447 duration: Duration::from_secs(600),
448 }],
449 }],
450 storage: frbc::StorageDescription {
451 diagnostic_label: Some("Battery".into()),
452 fill_level_label: Some("percentage state of charge".into()),
453 provides_leakage_behaviour: false,
454 provides_fill_level_target_profile: false,
455 provides_usage_forecast: false,
456 fill_level_range: NumberRange::new(0.0, 100.0),
457 },
458 }
459}
460
461#[must_use]
463pub fn pv_details() -> ResourceManagerDetails {
464 ResourceManagerDetails {
465 message_id: Id::new_const("rmd-pv"),
466 resource_id: Id::new_const("acme_pv_installation"),
467 name: Some("Solar panels on roof".into()),
468 roles: alloc::vec![Role::new(RoleType::EnergyProducer, Commodity::Electricity)],
469 manufacturer: Some("ACME".into()),
470 model: Some("InverterType2024".into()),
471 serial_number: Some("123".into()),
472 firmware_version: Some("v1.0".into()),
473 instruction_processing_delay: Duration::from_millis(5000),
474 available_control_types: alloc::vec![ControlType::PowerEnvelopeBasedControl],
475 currency: None,
476 provides_forecast: true,
477 provides_power_measurement_types: alloc::vec![CommodityQuantity::ElectricPowerL1],
478 }
479}
480
481#[must_use]
483pub fn pv_constraints(valid_from: Timestamp) -> pebc::PowerConstraints {
484 pebc::PowerConstraints {
485 message_id: Id::new_const("pebc-constraints-1"),
486 id: Id::new_const("powerConstraint1"),
487 valid_from,
488 valid_until: None,
489 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
490 allowed_limit_ranges: alloc::vec![
491 pebc::AllowedLimitRange {
492 commodity_quantity: CommodityQuantity::ElectricPowerL1,
493 limit_type: pebc::PowerEnvelopeLimitType::LowerLimit,
494 range_boundary: NumberRange::new(-4000.0, 0.0),
495 abnormal_condition_only: false,
496 },
497 pebc::AllowedLimitRange {
498 commodity_quantity: CommodityQuantity::ElectricPowerL1,
499 limit_type: pebc::PowerEnvelopeLimitType::UpperLimit,
500 range_boundary: NumberRange::new(0.0, 0.0),
501 abnormal_condition_only: false,
502 },
503 ],
504 }
505}
506
507#[must_use]
509pub fn charge(id: &'static str, factor: f64, at: Timestamp) -> frbc::Instruction {
510 frbc::Instruction {
511 message_id: Id::new_const("frbc-instr-msg"),
512 id: Id::new_const(id),
513 actuator_id: Id::new_const("actuator1"),
514 operation_mode: Id::new_const("charge"),
515 operation_mode_factor: factor,
516 execution_time: at,
517 abnormal_condition: false,
518 }
519}
520
521#[derive(Debug, Clone, PartialEq)]
527#[non_exhaustive]
528pub enum Finding {
529 Violation {
531 line: usize,
533 direction: Direction,
535 kind: MessageKind,
537 violation: crate::validate::Violation,
539 },
540 StatusDiffers {
545 line: usize,
547 direction: Direction,
549 kind: MessageKind,
551 recorded: ReceptionStatusValues,
553 expected: ReceptionStatusValues,
555 because: Option<String>,
558 },
559 Unanswered {
565 line: usize,
567 direction: Direction,
569 kind: MessageKind,
571 message_id: Id,
573 },
574 UnmatchedAnswer {
578 line: usize,
580 direction: Direction,
582 subject: Id,
584 },
585}
586
587impl Finding {
588 #[must_use]
590 pub const fn line(&self) -> usize {
591 match self {
592 Finding::Violation { line, .. }
593 | Finding::StatusDiffers { line, .. }
594 | Finding::Unanswered { line, .. }
595 | Finding::UnmatchedAnswer { line, .. } => *line,
596 }
597 }
598
599 #[must_use]
604 pub fn is_error(&self) -> bool {
605 match self {
606 Finding::Violation { violation, .. } => violation.severity == Severity::Error,
607 _ => true,
608 }
609 }
610}
611
612impl core::fmt::Display for Finding {
613 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
614 match self {
615 Finding::Violation {
616 line,
617 direction,
618 kind,
619 violation,
620 } => write!(f, "{line:>4} {} {kind}: {violation}", direction.as_str()),
621 Finding::StatusDiffers {
622 line,
623 direction,
624 kind,
625 recorded,
626 expected,
627 because,
628 } => {
629 write!(
630 f,
631 "{line:>4} {} {kind}: answered {recorded:?}, s2-kit would answer {expected:?}",
632 direction.as_str()
633 )?;
634 match because {
635 Some(why) => write!(f, " ({why})"),
636 None => Ok(()),
637 }
638 }
639 Finding::Unanswered {
640 line,
641 direction,
642 kind,
643 message_id,
644 } => write!(
645 f,
646 "{line:>4} {} {kind}: never answered; no ReceptionStatus names {message_id}",
647 direction.as_str()
648 ),
649 Finding::UnmatchedAnswer {
650 line,
651 direction,
652 subject,
653 } => write!(
654 f,
655 "{line:>4} {} ReceptionStatus: answers {subject}, which no line sent",
656 direction.as_str()
657 ),
658 }
659 }
660}
661
662#[derive(Debug, Clone, Default)]
664pub struct ReplayReport {
665 pub findings: Vec<Finding>,
667 pub lines: usize,
669 pub answered: usize,
671}
672
673impl ReplayReport {
674 #[must_use]
676 pub fn is_conforming(&self) -> bool {
677 !self.findings.iter().any(Finding::is_error)
678 }
679}
680
681impl core::fmt::Display for ReplayReport {
682 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
683 for finding in &self.findings {
684 writeln!(f, "{finding}")?;
685 }
686 write!(
687 f,
688 "{} line(s), {} answered: {}",
689 self.lines,
690 self.answered,
691 if self.is_conforming() { "ok" } else { "FAILED" }
692 )
693 }
694}
695
696#[must_use]
720pub fn replay(entries: &[TranscriptEntry]) -> ReplayReport {
721 replay_with(entries, Analyzer::new())
722}
723
724#[must_use]
727pub fn replay_with(entries: &[TranscriptEntry], mut analyzer: Analyzer) -> ReplayReport {
728 let mut report = ReplayReport {
729 lines: entries.len(),
730 ..ReplayReport::default()
731 };
732
733 let mut answers: Vec<(Direction, Id, ReceptionStatusValues)> = Vec::new();
736 for entry in entries {
737 if entry.kind == MessageKind::ReceptionStatus
738 && let Ok(Message::ReceptionStatus(status)) = crate::codec::decode(&entry.text)
739 {
740 answers.push((entry.direction, status.subject_message_id, status.status));
741 }
742 }
743
744 for (index, entry) in entries.iter().enumerate() {
745 let line = index + 1;
746 let observed = analyzer.observe(entry.direction.sender(), &entry.text, entry.at);
747
748 for violation in observed.report.violations() {
749 report.findings.push(Finding::Violation {
750 line,
751 direction: entry.direction,
752 kind: entry.kind,
753 violation: violation.clone(),
754 });
755 }
756
757 let Some(message) = &observed.message else {
758 continue;
759 };
760
761 if let Message::ReceptionStatus(status) = message {
762 let sent = entries.iter().any(|other| {
767 other.direction != entry.direction
768 && crate::codec::peek(&other.text)
769 .ok()
770 .and_then(|p| p.message_id)
771 == Some(status.subject_message_id)
772 });
773 if !sent && status.subject_message_id != Id::NIL {
774 report.findings.push(Finding::UnmatchedAnswer {
775 line,
776 direction: entry.direction,
777 subject: status.subject_message_id,
778 });
779 }
780 continue;
781 }
782
783 let Some(message_id) = message.id() else {
784 continue;
785 };
786 let recorded = answers
788 .iter()
789 .find(|(direction, subject, _)| *direction != entry.direction && *subject == message_id)
790 .map(|(_, _, status)| *status);
791
792 match recorded {
793 None => report.findings.push(Finding::Unanswered {
794 line,
795 direction: entry.direction,
796 kind: entry.kind,
797 message_id,
798 }),
799 Some(recorded) => {
800 report.answered += 1;
801 let receiver_specific = matches!(
805 recorded,
806 ReceptionStatusValues::TemporaryError | ReceptionStatusValues::PermanentError
807 );
808 if recorded != observed.status && !receiver_specific {
809 report.findings.push(Finding::StatusDiffers {
810 line,
811 direction: entry.direction,
812 kind: entry.kind,
813 recorded,
814 expected: observed.status,
815 because: observed.diagnostic_label(),
816 });
817 }
818 }
819 }
820 }
821
822 report.findings.sort_by_key(Finding::line);
823 report
824}