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, Currency, EnergyManagementRole, Handshake,
32 HandshakeResponse, InstructionStatus, InstructionStatusUpdate, NumberRange, PowerForecast,
33 PowerForecastElement, PowerForecastValue, PowerMeasurement, PowerRange, PowerValue,
34 ReceptionStatus, ReceptionStatusValues, ResourceManagerDetails, RevokableObjects, RevokeObject,
35 Role, RoleType, SelectControlType, SessionRequest, SessionRequestType, Timer, Transition,
36};
37use crate::types::{Duration, Id, ProtocolVersion, Timestamp, ddbc, frbc, ombc, pebc, ppbc};
38use crate::validate::Severity;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
45pub enum Direction {
46 CemToRm,
48 RmToCem,
50}
51
52impl Direction {
53 #[must_use]
58 pub const fn other(self) -> Self {
59 match self {
60 Direction::CemToRm => Direction::RmToCem,
61 Direction::RmToCem => Direction::CemToRm,
62 }
63 }
64
65 #[must_use]
67 pub const fn as_str(self) -> &'static str {
68 match self {
69 Direction::CemToRm => "cem>rm",
70 Direction::RmToCem => "rm>cem",
71 }
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct TranscriptEntry {
78 pub at: Timestamp,
80 pub direction: Direction,
82 pub kind: MessageKind,
84 pub text: String,
86}
87
88impl Direction {
89 #[must_use]
91 pub const fn sender(self) -> crate::types::common::EnergyManagementRole {
92 match self {
93 Direction::CemToRm => crate::types::common::EnergyManagementRole::Cem,
94 Direction::RmToCem => crate::types::common::EnergyManagementRole::Rm,
95 }
96 }
97
98 #[must_use]
100 pub fn parse(s: &str) -> Option<Self> {
101 match s {
102 "cem>rm" => Some(Direction::CemToRm),
103 "rm>cem" => Some(Direction::RmToCem),
104 _ => None,
105 }
106 }
107}
108
109impl TranscriptEntry {
110 #[must_use]
112 pub fn to_jsonl(&self) -> String {
113 format!(
114 r#"{{"t":"{}","dir":"{}","msg":{}}}"#,
115 self.at,
116 self.direction.as_str(),
117 self.text
118 )
119 }
120
121 #[must_use]
126 pub fn from_jsonl(line: &str) -> Option<Self> {
127 let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
128 let at = value.get("t")?.as_str()?.parse().ok()?;
129 let direction = Direction::parse(value.get("dir")?.as_str()?)?;
130 let text = value.get("msg")?.to_string();
131 let kind = crate::codec::peek(&text).ok().and_then(|p| p.kind)?;
135 Some(Self {
136 at,
137 direction,
138 kind,
139 text,
140 })
141 }
142}
143
144#[must_use]
146pub fn read_s2log(text: &str) -> Vec<TranscriptEntry> {
147 text.lines()
148 .filter_map(TranscriptEntry::from_jsonl)
149 .collect()
150}
151
152pub struct Conversation {
154 pub rm: RmSession,
156 pub cem: CemSession,
158 pub now: Timestamp,
160 transcript: Vec<TranscriptEntry>,
161 rm_events: Vec<RmEvent>,
162 cem_events: Vec<CemEvent>,
163}
164
165impl Conversation {
166 #[must_use]
168 pub fn new(
169 rm_config: RmConfig,
170 details: ResourceManagerDetails,
171 cem_config: CemConfig,
172 ) -> Self {
173 Self {
174 rm: RmSession::new(rm_config, details),
175 cem: CemSession::new(cem_config),
176 now: "2024-01-01T12:00:00Z"
177 .parse()
178 .unwrap_or(Timestamp::UNIX_EPOCH),
179 transcript: Vec::new(),
180 rm_events: Vec::new(),
181 cem_events: Vec::new(),
182 }
183 }
184
185 #[must_use]
187 pub fn battery() -> Self {
188 Self::new(RmConfig::default(), battery_details(), CemConfig::default())
189 }
190
191 #[must_use]
193 pub fn pv() -> Self {
194 Self::new(RmConfig::default(), pv_details(), CemConfig::default())
195 }
196
197 pub fn open(&mut self) {
199 self.rm.open(self.now);
200 self.cem.open(self.now);
201 self.pump();
202 }
203
204 #[allow(clippy::panic)] pub fn pump(&mut self) {
214 for _ in 0..1000 {
215 let mut moved = false;
216 while let Some(out) = self.rm.poll_transmit() {
217 self.record(Direction::RmToCem, out.kind, &out.text);
218 self.cem.handle_text(&out.text, self.now);
219 moved = true;
220 }
221 while let Some(out) = self.cem.poll_transmit() {
222 self.record(Direction::CemToRm, out.kind, &out.text);
223 self.rm.handle_text(&out.text, self.now);
224 moved = true;
225 }
226 self.drain_events();
227 if !moved {
228 return;
229 }
230 }
231 panic!("the conversation did not settle: a session is answering its own answers");
232 }
233
234 fn record(&mut self, direction: Direction, kind: MessageKind, text: &str) {
235 self.transcript.push(TranscriptEntry {
236 at: self.now,
237 direction,
238 kind,
239 text: text.to_string(),
240 });
241 }
242
243 fn drain_events(&mut self) {
244 while let Some(event) = self.rm.poll_event() {
245 self.rm_events.push(event);
246 }
247 while let Some(event) = self.cem.poll_event() {
248 self.cem_events.push(event);
249 }
250 }
251
252 pub fn advance(&mut self, by: Duration) {
254 self.now = self.now.checked_add(by).unwrap_or(self.now);
255 self.rm.handle_timeout(self.now);
256 self.cem.handle_timeout(self.now);
257 self.pump();
258 }
259
260 pub fn advance_silently(&mut self, by: Duration) {
263 self.now = self.now.checked_add(by).unwrap_or(self.now);
264 self.rm.handle_timeout(self.now);
265 self.cem.handle_timeout(self.now);
266 self.drain_events();
267 }
268
269 pub fn drop_rm_traffic(&mut self) {
272 while self.rm.poll_transmit().is_some() {}
273 self.drain_events();
274 }
275
276 pub fn drop_cem_traffic(&mut self) {
278 while self.cem.poll_transmit().is_some() {}
279 self.drain_events();
280 }
281
282 #[must_use]
284 pub fn transcript(&self) -> &[TranscriptEntry] {
285 &self.transcript
286 }
287
288 #[must_use]
290 pub fn to_s2log(&self) -> String {
291 let mut out = String::new();
292 for entry in &self.transcript {
293 out.push_str(&entry.to_jsonl());
294 out.push('\n');
295 }
296 out
297 }
298
299 #[must_use]
301 pub fn flow(&self) -> Vec<(Direction, MessageKind)> {
302 self.transcript
303 .iter()
304 .map(|e| (e.direction, e.kind))
305 .collect()
306 }
307
308 #[must_use]
310 pub fn flow_without_acks(&self) -> Vec<(Direction, MessageKind)> {
311 self.flow()
312 .into_iter()
313 .filter(|(_, kind)| *kind != MessageKind::ReceptionStatus)
314 .collect()
315 }
316
317 pub fn take_rm_events(&mut self) -> Vec<RmEvent> {
319 self.drain_events();
320 core::mem::take(&mut self.rm_events)
321 }
322
323 pub fn take_cem_events(&mut self) -> Vec<CemEvent> {
325 self.drain_events();
326 core::mem::take(&mut self.cem_events)
327 }
328
329 pub fn first_instruction(&mut self) -> Option<Instructed> {
331 self.drain_events();
332 self.rm_events.iter().find_map(|e| match e {
333 RmEvent::Instruction(i) => Some((**i).clone()),
334 _ => None,
335 })
336 }
337
338 #[must_use]
340 pub fn refusals(&self) -> Vec<String> {
341 let mut out = Vec::new();
342 for event in &self.rm_events {
343 if let RmEvent::Refused { report, .. } = event {
344 out.push(format!("RM refused: {report}"));
345 }
346 }
347 for event in &self.cem_events {
348 if let CemEvent::Refused { report, .. } = event {
349 out.push(format!("CEM refused: {report}"));
350 }
351 }
352 out
353 }
354
355 pub fn assert_no_refusals(&self) {
361 let refusals = self.refusals();
362 assert!(refusals.is_empty(), "{refusals:#?}");
363 }
364}
365
366#[must_use]
372pub fn battery_details() -> ResourceManagerDetails {
373 ResourceManagerDetails {
374 message_id: Id::new_const("rmd-battery"),
375 resource_id: Id::new_const("acme_battery_1"),
376 name: Some("Home battery".into()),
377 roles: alloc::vec![Role::new(RoleType::EnergyStorage, Commodity::Electricity)],
378 manufacturer: Some("ACME".into()),
379 model: Some("Powerwall-ish".into()),
380 serial_number: Some("123".into()),
381 firmware_version: Some("v1.0".into()),
382 instruction_processing_delay: Duration::from_millis(500),
383 available_control_types: alloc::vec![ControlType::FillRateBasedControl],
384 currency: None,
385 provides_forecast: false,
386 provides_power_measurement_types: alloc::vec![
387 CommodityQuantity::ElectricPower3PhaseSymmetric
388 ],
389 }
390}
391
392#[must_use]
394pub fn battery_system(valid_from: Timestamp) -> frbc::SystemDescription {
395 let mode =
396 |id: &'static str, label: &str, rate: NumberRange, power: PowerRange| frbc::OperationMode {
397 id: Id::new_const(id),
398 diagnostic_label: Some(label.to_string()),
399 elements: alloc::vec![frbc::OperationModeElement {
400 fill_level_range: NumberRange::new(0.0, 100.0),
401 fill_rate: rate,
402 power_ranges: alloc::vec![power],
403 running_costs: None,
404 }],
405 abnormal_condition_only: false,
406 };
407 let q = CommodityQuantity::ElectricPower3PhaseSymmetric;
408 frbc::SystemDescription {
409 message_id: Id::new_const("frbc-system-1"),
410 valid_from,
411 actuators: alloc::vec![frbc::ActuatorDescription {
412 id: Id::new_const("actuator1"),
413 diagnostic_label: Some("Battery inverter".into()),
414 supported_commodities: alloc::vec![Commodity::Electricity],
415 operation_modes: alloc::vec![
416 mode(
417 "idle",
418 "Idle",
419 NumberRange::exactly(0.0),
420 PowerRange::exactly(0.0, q)
421 ),
422 mode(
423 "charge",
424 "Charging",
425 NumberRange::new(0.0, 0.0025),
426 PowerRange::new(0.0, 5000.0, q),
427 ),
428 mode(
429 "discharge",
430 "Discharging",
431 NumberRange::new(0.0, -0.0025),
432 PowerRange::new(0.0, -5000.0, q),
433 ),
434 ],
435 transitions: alloc::vec![
436 Transition::simple(
437 Id::new_const("t1"),
438 Id::new_const("idle"),
439 Id::new_const("charge")
440 ),
441 Transition::simple(
442 Id::new_const("t2"),
443 Id::new_const("charge"),
444 Id::new_const("idle")
445 ),
446 Transition::simple(
447 Id::new_const("t3"),
448 Id::new_const("idle"),
449 Id::new_const("discharge")
450 ),
451 Transition {
452 id: Id::new_const("t4"),
453 from: Id::new_const("discharge"),
454 to: Id::new_const("idle"),
455 start_timers: alloc::vec![],
456 blocking_timers: alloc::vec![Id::new_const("cooldown")],
457 transition_costs: None,
458 transition_duration: None,
459 abnormal_condition_only: false,
460 },
461 ],
462 timers: alloc::vec![Timer {
463 id: Id::new_const("cooldown"),
464 diagnostic_label: Some("Minimum discharge time".into()),
465 duration: Duration::from_secs(600),
466 }],
467 }],
468 storage: frbc::StorageDescription {
469 diagnostic_label: Some("Battery".into()),
470 fill_level_label: Some("percentage state of charge".into()),
471 provides_leakage_behaviour: false,
472 provides_fill_level_target_profile: false,
473 provides_usage_forecast: false,
474 fill_level_range: NumberRange::new(0.0, 100.0),
475 },
476 }
477}
478
479#[must_use]
481pub fn pv_details() -> ResourceManagerDetails {
482 ResourceManagerDetails {
483 message_id: Id::new_const("rmd-pv"),
484 resource_id: Id::new_const("acme_pv_installation"),
485 name: Some("Solar panels on roof".into()),
486 roles: alloc::vec![Role::new(RoleType::EnergyProducer, Commodity::Electricity)],
487 manufacturer: Some("ACME".into()),
488 model: Some("InverterType2024".into()),
489 serial_number: Some("123".into()),
490 firmware_version: Some("v1.0".into()),
491 instruction_processing_delay: Duration::from_millis(5000),
492 available_control_types: alloc::vec![ControlType::PowerEnvelopeBasedControl],
493 currency: None,
494 provides_forecast: true,
495 provides_power_measurement_types: alloc::vec![CommodityQuantity::ElectricPowerL1],
496 }
497}
498
499#[must_use]
501pub fn pv_constraints(valid_from: Timestamp) -> pebc::PowerConstraints {
502 pebc::PowerConstraints {
503 message_id: Id::new_const("pebc-constraints-1"),
504 id: Id::new_const("powerConstraint1"),
505 valid_from,
506 valid_until: None,
507 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
508 allowed_limit_ranges: alloc::vec![
509 pebc::AllowedLimitRange {
510 commodity_quantity: CommodityQuantity::ElectricPowerL1,
511 limit_type: pebc::PowerEnvelopeLimitType::LowerLimit,
512 range_boundary: NumberRange::new(-4000.0, 0.0),
513 abnormal_condition_only: false,
514 },
515 pebc::AllowedLimitRange {
516 commodity_quantity: CommodityQuantity::ElectricPowerL1,
517 limit_type: pebc::PowerEnvelopeLimitType::UpperLimit,
518 range_boundary: NumberRange::new(0.0, 0.0),
519 abnormal_condition_only: false,
520 },
521 ],
522 }
523}
524
525#[must_use]
527pub fn charge(id: &'static str, factor: f64, at: Timestamp) -> frbc::Instruction {
528 frbc::Instruction {
529 message_id: Id::new_const("frbc-instr-msg"),
530 id: Id::new_const(id),
531 actuator_id: Id::new_const("actuator1"),
532 operation_mode: Id::new_const("charge"),
533 operation_mode_factor: factor,
534 execution_time: at,
535 abnormal_condition: false,
536 }
537}
538
539#[derive(Debug, Clone, PartialEq)]
545#[non_exhaustive]
546pub enum Finding {
547 Violation {
549 line: usize,
551 direction: Direction,
553 kind: MessageKind,
555 violation: crate::validate::Violation,
557 },
558 StatusDiffers {
563 line: usize,
565 direction: Direction,
567 kind: MessageKind,
569 recorded: ReceptionStatusValues,
571 expected: ReceptionStatusValues,
573 because: Option<String>,
576 },
577 Unanswered {
583 line: usize,
585 direction: Direction,
587 kind: MessageKind,
589 message_id: Id,
591 },
592 UnmatchedAnswer {
596 line: usize,
598 direction: Direction,
600 subject: Id,
602 },
603}
604
605impl Finding {
606 #[must_use]
608 pub const fn line(&self) -> usize {
609 match self {
610 Finding::Violation { line, .. }
611 | Finding::StatusDiffers { line, .. }
612 | Finding::Unanswered { line, .. }
613 | Finding::UnmatchedAnswer { line, .. } => *line,
614 }
615 }
616
617 #[must_use]
622 pub fn is_error(&self) -> bool {
623 match self {
624 Finding::Violation { violation, .. } => violation.severity == Severity::Error,
625 _ => true,
626 }
627 }
628}
629
630impl core::fmt::Display for Finding {
631 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
632 match self {
633 Finding::Violation {
634 line,
635 direction,
636 kind,
637 violation,
638 } => write!(f, "{line:>4} {} {kind}: {violation}", direction.as_str()),
639 Finding::StatusDiffers {
640 line,
641 direction,
642 kind,
643 recorded,
644 expected,
645 because,
646 } => {
647 write!(
648 f,
649 "{line:>4} {} {kind}: answered {recorded:?}, s2-kit would answer {expected:?}",
650 direction.as_str()
651 )?;
652 match because {
653 Some(why) => write!(f, " ({why})"),
654 None => Ok(()),
655 }
656 }
657 Finding::Unanswered {
658 line,
659 direction,
660 kind,
661 message_id,
662 } => write!(
663 f,
664 "{line:>4} {} {kind}: never answered; no ReceptionStatus names {message_id}",
665 direction.as_str()
666 ),
667 Finding::UnmatchedAnswer {
668 line,
669 direction,
670 subject,
671 } => write!(
672 f,
673 "{line:>4} {} ReceptionStatus: answers {subject}, which no line sent",
674 direction.as_str()
675 ),
676 }
677 }
678}
679
680#[derive(Debug, Clone, Default)]
682pub struct ReplayReport {
683 pub findings: Vec<Finding>,
685 pub lines: usize,
687 pub answered: usize,
689}
690
691impl ReplayReport {
692 #[must_use]
694 pub fn is_conforming(&self) -> bool {
695 !self.findings.iter().any(Finding::is_error)
696 }
697}
698
699impl core::fmt::Display for ReplayReport {
700 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
701 for finding in &self.findings {
702 writeln!(f, "{finding}")?;
703 }
704 write!(
705 f,
706 "{} line(s), {} answered: {}",
707 self.lines,
708 self.answered,
709 if self.is_conforming() { "ok" } else { "FAILED" }
710 )
711 }
712}
713
714#[must_use]
738pub fn replay(entries: &[TranscriptEntry]) -> ReplayReport {
739 replay_with(entries, Analyzer::new())
740}
741
742#[must_use]
745pub fn replay_with(entries: &[TranscriptEntry], mut analyzer: Analyzer) -> ReplayReport {
746 let mut report = ReplayReport {
747 lines: entries.len(),
748 ..ReplayReport::default()
749 };
750
751 let mut answers: Vec<(Direction, Id, ReceptionStatusValues)> = Vec::new();
760 let mut sent: Vec<(Direction, Id)> = Vec::new();
761 for entry in entries {
762 if entry.kind == MessageKind::ReceptionStatus {
763 if let Ok(Message::ReceptionStatus(status)) = crate::codec::decode(&entry.text) {
764 answers.push((entry.direction, status.subject_message_id, status.status));
765 }
766 continue;
767 }
768 if let Ok(Some(id)) = crate::codec::peek(&entry.text).map(|p| p.message_id) {
769 sent.push((entry.direction, id));
770 }
771 }
772 answers.sort_unstable_by_key(|(direction, subject, _)| (*direction, *subject));
773 sent.sort_unstable();
774
775 for (index, entry) in entries.iter().enumerate() {
776 let line = index + 1;
777 let observed = analyzer.observe(entry.direction.sender(), &entry.text, entry.at);
778
779 for violation in observed.report.violations() {
780 report.findings.push(Finding::Violation {
781 line,
782 direction: entry.direction,
783 kind: entry.kind,
784 violation: violation.clone(),
785 });
786 }
787
788 let Some(message) = &observed.message else {
789 continue;
790 };
791
792 if let Message::ReceptionStatus(status) = message {
793 let was_sent = sent
798 .binary_search(&(entry.direction.other(), status.subject_message_id))
799 .is_ok();
800 if !was_sent && status.subject_message_id != Id::NIL {
801 report.findings.push(Finding::UnmatchedAnswer {
802 line,
803 direction: entry.direction,
804 subject: status.subject_message_id,
805 });
806 }
807 continue;
808 }
809
810 let Some(message_id) = message.id() else {
811 continue;
812 };
813 let recorded = answers
815 .binary_search_by_key(&(entry.direction.other(), message_id), |(d, s, _)| (*d, *s))
816 .ok()
817 .and_then(|i| answers.get(i))
818 .map(|(_, _, status)| *status);
819
820 match recorded {
821 None => report.findings.push(Finding::Unanswered {
822 line,
823 direction: entry.direction,
824 kind: entry.kind,
825 message_id,
826 }),
827 Some(recorded) => {
828 report.answered += 1;
829 let receiver_specific = matches!(
833 recorded,
834 ReceptionStatusValues::TemporaryError | ReceptionStatusValues::PermanentError
835 );
836 if recorded != observed.status && !receiver_specific {
837 report.findings.push(Finding::StatusDiffers {
838 line,
839 direction: entry.direction,
840 kind: entry.kind,
841 recorded,
842 expected: observed.status,
843 because: observed.diagnostic_label(),
844 });
845 }
846 }
847 }
848 }
849
850 report.findings.sort_by_key(Finding::line);
851 report
852}
853
854fn id(s: &str) -> Id {
859 Id::parse(s).unwrap_or(Id::NIL)
860}
861
862fn at() -> Timestamp {
863 Timestamp::from_unix(1_724_508_922, 0)
864}
865
866fn q() -> CommodityQuantity {
867 CommodityQuantity::ElectricPowerL1
868}
869
870fn number_range() -> NumberRange {
871 NumberRange::new(0.0, 100.0)
872}
873
874fn power_range() -> PowerRange {
875 PowerRange::new(0.0, 2000.0, q())
876}
877
878fn forecast_value() -> PowerForecastValue {
879 PowerForecastValue {
880 value_upper_limit: Some(1000.0),
881 value_upper_95ppr: Some(960.0),
882 value_upper_68ppr: Some(800.0),
883 value_expected: 545.1,
884 value_lower_68ppr: Some(340.0),
885 value_lower_95ppr: Some(100.0),
886 value_lower_limit: Some(0.0),
887 commodity_quantity: q(),
888 }
889}
890
891fn timer() -> Timer {
892 Timer {
893 id: id("timer0"),
894 diagnostic_label: Some("Minimum run time".into()),
895 duration: Duration::from_secs(7200),
896 }
897}
898
899fn transition(from: &str, to: &str) -> Transition {
900 Transition {
901 id: id("trans0"),
902 from: id(from),
903 to: id(to),
904 start_timers: vec![id("timer0")],
905 blocking_timers: vec![id("timer0")],
906 transition_costs: Some(0.0),
907 transition_duration: Some(Duration::from_secs(3)),
908 abnormal_condition_only: false,
909 }
910}
911
912fn frbc_actuator() -> frbc::ActuatorDescription {
913 frbc::ActuatorDescription {
914 id: id("actuator1"),
915 diagnostic_label: Some("heat pump".into()),
916 supported_commodities: vec![Commodity::Electricity],
917 operation_modes: vec![
918 frbc::OperationMode {
919 id: id("om0"),
920 diagnostic_label: Some("running".into()),
921 elements: vec![frbc::OperationModeElement {
922 fill_level_range: number_range(),
923 fill_rate: NumberRange::new(0.002_09, 0.008_35),
924 power_ranges: vec![power_range()],
925 running_costs: Some(NumberRange::new(0.0, 0.0)),
926 }],
927 abnormal_condition_only: false,
928 },
929 frbc::OperationMode {
930 id: id("om1"),
931 diagnostic_label: Some("Off".into()),
932 elements: vec![frbc::OperationModeElement {
933 fill_level_range: number_range(),
934 fill_rate: NumberRange::exactly(0.0),
935 power_ranges: vec![PowerRange::exactly(0.0, q())],
936 running_costs: None,
937 }],
938 abnormal_condition_only: false,
939 },
940 ],
941 transitions: vec![transition("om0", "om1")],
942 timers: vec![timer()],
943 }
944}
945
946fn ddbc_actuator() -> ddbc::ActuatorDescription {
947 ddbc::ActuatorDescription {
948 id: id("actuator1"),
949 diagnostic_label: Some("hybrid heat pump".into()),
950 supported_commodities: vec![Commodity::Electricity, Commodity::Gas],
951 operation_modes: vec![ddbc::OperationMode {
952 id: id("om0"),
953 diagnostic_label: Some("electric".into()),
954 power_ranges: vec![power_range()],
955 supply_range: NumberRange::new(0.0, 6000.0),
956 running_costs: Some(NumberRange::new(0.0, 0.0)),
957 abnormal_condition_only: false,
958 }],
959 transitions: vec![transition("om0", "om0")],
960 timers: vec![timer()],
961 }
962}
963
964#[must_use]
980pub fn every_message() -> Vec<Message> {
981 let versions = vec![ProtocolVersion::new("1.0.0")];
982 vec![
983 Handshake {
984 message_id: id("m1"),
985 role: EnergyManagementRole::Rm,
986 supported_protocol_versions: Some(versions),
987 }
988 .into(),
989 HandshakeResponse {
990 message_id: id("m1"),
991 selected_protocol_version: ProtocolVersion::new("1.0.0"),
992 }
993 .into(),
994 ResourceManagerDetails {
995 message_id: id("m1"),
996 resource_id: id("acme_heat_pump"),
997 name: Some("my_heat_pump".into()),
998 roles: vec![Role::new(RoleType::EnergyConsumer, Commodity::Electricity)],
999 manufacturer: Some("ACME".into()),
1000 model: Some("HeatPump2000".into()),
1001 serial_number: Some("123".into()),
1002 firmware_version: Some("v1.0".into()),
1003 instruction_processing_delay: Duration::from_millis(10_000),
1004 available_control_types: vec![ControlType::FillRateBasedControl],
1005 currency: Some(Currency::Eur),
1006 provides_forecast: true,
1007 provides_power_measurement_types: vec![q()],
1008 }
1009 .into(),
1010 SelectControlType {
1011 message_id: id("m1"),
1012 control_type: ControlType::FillRateBasedControl,
1013 }
1014 .into(),
1015 SessionRequest {
1016 message_id: id("m1"),
1017 request: SessionRequestType::Terminate,
1018 diagnostic_label: Some("shutting down".into()),
1019 }
1020 .into(),
1021 ReceptionStatus {
1022 subject_message_id: id("m1"),
1023 status: ReceptionStatusValues::Ok,
1024 diagnostic_label: Some("Processed okay.".into()),
1025 }
1026 .into(),
1027 InstructionStatusUpdate {
1028 message_id: id("m1"),
1029 instruction_id: id("instr0"),
1030 status_type: InstructionStatus::Succeeded,
1031 timestamp: at(),
1032 }
1033 .into(),
1034 PowerMeasurement {
1035 message_id: id("m1"),
1036 measurement_timestamp: at(),
1037 values: vec![PowerValue::new(q(), 510.6)],
1038 }
1039 .into(),
1040 PowerForecast {
1041 message_id: id("m1"),
1042 start_time: at(),
1043 elements: vec![PowerForecastElement {
1044 duration: Duration::from_millis(3_600_000),
1045 power_values: vec![forecast_value()],
1046 }],
1047 }
1048 .into(),
1049 RevokeObject {
1050 message_id: id("m1"),
1051 object_type: RevokableObjects::FrbcSystemDescription,
1052 object_id: id("sd1"),
1053 }
1054 .into(),
1055 pebc::PowerConstraints {
1057 message_id: id("m1"),
1058 id: id("powerConstraint1"),
1059 valid_from: at(),
1060 valid_until: Some(at()),
1061 consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1062 allowed_limit_ranges: vec![
1063 pebc::AllowedLimitRange {
1064 commodity_quantity: q(),
1065 limit_type: pebc::PowerEnvelopeLimitType::LowerLimit,
1066 range_boundary: NumberRange::new(-4000.0, 0.0),
1067 abnormal_condition_only: false,
1068 },
1069 pebc::AllowedLimitRange {
1070 commodity_quantity: q(),
1071 limit_type: pebc::PowerEnvelopeLimitType::UpperLimit,
1072 range_boundary: NumberRange::new(0.0, 0.0),
1073 abnormal_condition_only: false,
1074 },
1075 ],
1076 }
1077 .into(),
1078 pebc::EnergyConstraint {
1079 message_id: id("m1"),
1080 id: id("energyconstraint1"),
1081 valid_from: at(),
1082 valid_until: at(),
1083 upper_average_power: 3000.0,
1084 lower_average_power: 1000.0,
1085 commodity_quantity: q(),
1086 }
1087 .into(),
1088 pebc::Instruction {
1089 message_id: id("m1"),
1090 id: id("envelope1"),
1091 execution_time: at(),
1092 abnormal_condition: false,
1093 power_constraints_id: id("powerConstraint1"),
1094 power_envelopes: vec![pebc::PowerEnvelope {
1095 id: id("pe_xxx"),
1096 commodity_quantity: q(),
1097 power_envelope_elements: vec![pebc::PowerEnvelopeElement::new(
1098 Duration::from_millis(3_600_000),
1099 -2000.0,
1100 0.0,
1101 )],
1102 }],
1103 }
1104 .into(),
1105 ppbc::PowerProfileDefinition {
1107 message_id: id("m1"),
1108 id: id("profile1"),
1109 start_time: at(),
1110 end_time: at(),
1111 power_sequence_containers: vec![ppbc::PowerSequenceContainer {
1112 id: id("c1"),
1113 power_sequences: vec![ppbc::PowerSequence {
1114 id: id("s1"),
1115 elements: vec![ppbc::PowerSequenceElement {
1116 duration: Duration::from_secs(600),
1117 power_values: vec![forecast_value()],
1118 }],
1119 is_interruptible: true,
1120 max_pause_before: Some(Duration::from_secs(300)),
1121 abnormal_condition_only: false,
1122 }],
1123 }],
1124 }
1125 .into(),
1126 ppbc::PowerProfileStatus {
1127 message_id: id("m1"),
1128 sequence_container_status: vec![ppbc::PowerSequenceContainerStatus {
1129 power_profile_id: id("profile1"),
1130 sequence_container_id: id("c1"),
1131 selected_sequence_id: Some(id("s1")),
1132 progress: Some(Duration::from_secs(60)),
1133 status: ppbc::PowerSequenceStatus::Executing,
1134 }],
1135 }
1136 .into(),
1137 ppbc::ScheduleInstruction {
1138 message_id: id("m1"),
1139 id: id("instr0"),
1140 power_profile_id: id("profile1"),
1141 sequence_container_id: id("c1"),
1142 power_sequence_id: id("s1"),
1143 execution_time: at(),
1144 abnormal_condition: false,
1145 }
1146 .into(),
1147 ppbc::StartInterruptionInstruction {
1148 message_id: id("m1"),
1149 id: id("instr1"),
1150 power_profile_id: id("profile1"),
1151 sequence_container_id: id("c1"),
1152 power_sequence_id: id("s1"),
1153 execution_time: at(),
1154 abnormal_condition: false,
1155 }
1156 .into(),
1157 ppbc::EndInterruptionInstruction {
1158 message_id: id("m1"),
1159 id: id("instr2"),
1160 power_profile_id: id("profile1"),
1161 sequence_container_id: id("c1"),
1162 power_sequence_id: id("s1"),
1163 execution_time: at(),
1164 abnormal_condition: false,
1165 }
1166 .into(),
1167 ombc::SystemDescription {
1169 message_id: id("m1"),
1170 valid_from: at(),
1171 operation_modes: vec![ombc::OperationMode {
1172 id: id("om0"),
1173 diagnostic_label: Some("Off".into()),
1174 power_ranges: vec![power_range()],
1175 running_costs: Some(NumberRange::new(0.0, 0.0)),
1176 abnormal_condition_only: false,
1177 }],
1178 transitions: vec![transition("om0", "om0")],
1179 timers: vec![timer()],
1180 }
1181 .into(),
1182 ombc::Status {
1183 message_id: id("m1"),
1184 active_operation_mode_id: id("om0"),
1185 operation_mode_factor: 0.5,
1186 previous_operation_mode_id: Some(id("om1")),
1187 transition_timestamp: Some(at()),
1188 }
1189 .into(),
1190 ombc::TimerStatus {
1191 message_id: id("m1"),
1192 timer_id: id("timer0"),
1193 finished_at: at(),
1194 }
1195 .into(),
1196 ombc::Instruction {
1197 message_id: id("m1"),
1198 id: id("instr0"),
1199 execution_time: at(),
1200 operation_mode_id: id("om0"),
1201 operation_mode_factor: 1.0,
1202 abnormal_condition: false,
1203 }
1204 .into(),
1205 frbc::SystemDescription {
1207 message_id: id("m1"),
1208 valid_from: at(),
1209 actuators: vec![frbc_actuator()],
1210 storage: frbc::StorageDescription {
1211 diagnostic_label: Some("DHW Buffer".into()),
1212 fill_level_label: Some("temperature in Celsius".into()),
1213 provides_leakage_behaviour: true,
1214 provides_fill_level_target_profile: true,
1215 provides_usage_forecast: true,
1216 fill_level_range: number_range(),
1217 },
1218 }
1219 .into(),
1220 frbc::StorageStatus {
1221 message_id: id("m1"),
1222 present_fill_level: 52.0,
1223 }
1224 .into(),
1225 frbc::ActuatorStatus {
1226 message_id: id("m1"),
1227 actuator_id: id("actuator1"),
1228 active_operation_mode_id: id("om0"),
1229 operation_mode_factor: 0.0,
1230 previous_operation_mode_id: Some(id("om1")),
1231 transition_timestamp: Some(at()),
1232 }
1233 .into(),
1234 frbc::TimerStatus {
1235 message_id: id("m1"),
1236 timer_id: id("timer0"),
1237 actuator_id: id("actuator1"),
1238 finished_at: at(),
1239 }
1240 .into(),
1241 frbc::LeakageBehaviour {
1242 message_id: id("m1"),
1243 valid_from: at(),
1244 elements: vec![frbc::LeakageBehaviourElement {
1245 fill_level_range: number_range(),
1246 leakage_rate: 0.000_05,
1247 }],
1248 }
1249 .into(),
1250 frbc::UsageForecast {
1251 message_id: id("m1"),
1252 start_time: at(),
1253 elements: vec![frbc::UsageForecastElement {
1254 duration: Duration::from_secs(900),
1255 usage_rate_upper_limit: Some(1.0),
1256 usage_rate_upper_95ppr: Some(0.9),
1257 usage_rate_upper_68ppr: Some(0.8),
1258 usage_rate_expected: 0.5,
1259 usage_rate_lower_68ppr: Some(0.4),
1260 usage_rate_lower_95ppr: Some(0.2),
1261 usage_rate_lower_limit: Some(0.0),
1262 }],
1263 }
1264 .into(),
1265 frbc::FillLevelTargetProfile {
1266 message_id: id("m1"),
1267 start_time: at(),
1268 elements: vec![frbc::FillLevelTargetProfileElement {
1269 duration: Duration::from_secs(3600),
1270 fill_level_range: number_range(),
1271 }],
1272 }
1273 .into(),
1274 frbc::Instruction {
1275 message_id: id("m1"),
1276 id: id("instr0"),
1277 actuator_id: id("actuator1"),
1278 operation_mode: id("om0"),
1279 operation_mode_factor: 1.0,
1280 execution_time: at(),
1281 abnormal_condition: false,
1282 }
1283 .into(),
1284 ddbc::SystemDescription {
1286 message_id: id("m1"),
1287 valid_from: at(),
1288 actuators: vec![ddbc_actuator()],
1289 present_demand_rate: None,
1290 provides_average_demand_rate_forecast: true,
1291 }
1292 .into(),
1293 ddbc::ActuatorStatus {
1294 message_id: id("m1"),
1295 actuator_id: id("actuator1"),
1296 active_operation_mode_id: id("om0"),
1297 operation_mode_factor: 0.5,
1298 previous_operation_mode_id: Some(id("om1")),
1299 transition_timestamp: Some(at()),
1300 }
1301 .into(),
1302 ddbc::TimerStatus {
1303 message_id: id("m1"),
1304 timer_id: id("timer0"),
1305 actuator_id: id("actuator1"),
1306 finished_at: at(),
1307 }
1308 .into(),
1309 ddbc::AverageDemandRateForecast {
1310 message_id: id("m1"),
1311 start_time: at(),
1312 elements: vec![ddbc::AverageDemandRateForecastElement {
1313 duration: Duration::from_secs(900),
1314 demand_rate_upper_limit: Some(1.0),
1315 demand_rate_upper_95ppr: Some(0.9),
1316 demand_rate_upper_68ppr: Some(0.8),
1317 demand_rate_expected: 0.5,
1318 demand_rate_lower_68ppr: Some(0.4),
1319 demand_rate_lower_95ppr: Some(0.2),
1320 demand_rate_lower_limit: Some(0.0),
1321 }],
1322 }
1323 .into(),
1324 ddbc::PresentDemandStatus {
1325 message_id: id("m1"),
1326 present_demand_rate: NumberRange::new(0.0, 6000.0),
1327 }
1328 .into(),
1329 ddbc::Instruction {
1330 message_id: id("m1"),
1331 id: id("instr0"),
1332 execution_time: at(),
1333 abnormal_condition: false,
1334 actuator_id: id("actuator1"),
1335 operation_mode_id: id("om0"),
1336 operation_mode_factor: 1.0,
1337 }
1338 .into(),
1339 ]
1340}