Skip to main content

s2_kit/types/
ombc.rs

1//! Operation Mode Based Control — a device that can adjust its power, with no
2//! constraint on how long the adjustment lasts.
3//!
4//! A generator, a variable resistor, an SG Ready heat pump. This is the plainest of the
5//! three state-machine control types: modes carry a power and nothing else, and there is
6//! one machine rather than one per actuator.
7
8use alloc::string::String;
9use alloc::vec::Vec;
10
11use bon::Builder;
12use serde::{Deserialize, Serialize};
13
14use super::common::{PowerRange, Timer, Transition};
15use super::{Id, NumberRange, Timestamp};
16
17/// One state of the device.
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
19#[serde(deny_unknown_fields)]
20#[builder(on(String, into))]
21pub struct OperationMode {
22    /// Unique within the Resource Manager for the session.
23    pub id: Id,
24    /// Human-readable, for debugging only.
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub diagnostic_label: Option<String>,
27    /// The power in this mode: start at factor 0, end at factor 1. At most one range per
28    /// commodity quantity.
29    pub power_ranges: Vec<PowerRange>,
30    /// Cost per second of running in this mode, excluding the commodity. The range
31    /// expresses uncertainty, not the factor.
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub running_costs: Option<NumberRange>,
34    /// Whether this mode may only be used during an abnormal condition.
35    pub abnormal_condition_only: bool,
36}
37
38/// The state machine: every mode, every move between them, every timer.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
40#[serde(deny_unknown_fields)]
41pub struct SystemDescription {
42    /// This message's identifier.
43    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
44    pub message_id: Id,
45    /// When this description becomes valid.
46    pub valid_from: Timestamp,
47    /// The states. At least one, at most a hundred.
48    pub operation_modes: Vec<OperationMode>,
49    /// The permitted moves.
50    pub transitions: Vec<Transition>,
51    /// The timers those moves start or wait for.
52    pub timers: Vec<Timer>,
53}
54
55impl SystemDescription {
56    /// The operation mode with this id, if the description has one.
57    #[must_use]
58    pub fn operation_mode(&self, id: &Id) -> Option<&OperationMode> {
59        self.operation_modes.iter().find(|m| m.id == *id)
60    }
61
62    /// The timer with this id, if the description has one.
63    #[must_use]
64    pub fn timer(&self, id: &Id) -> Option<&Timer> {
65        self.timers.iter().find(|t| t.id == *id)
66    }
67
68    /// The transition from `from` to `to`, if one is described.
69    #[must_use]
70    pub fn transition(&self, from: &Id, to: &Id) -> Option<&Transition> {
71        self.transitions
72            .iter()
73            .find(|t| t.from == *from && t.to == *to)
74    }
75}
76
77/// Which mode the device is in, and how far into it.
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
79#[serde(deny_unknown_fields)]
80pub struct Status {
81    /// This message's identifier.
82    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
83    pub message_id: Id,
84    /// The mode that is active now.
85    pub active_operation_mode_id: Id,
86    /// Where in that mode's ranges it is running, in `[0, 1]`.
87    pub operation_mode_factor: f64,
88    /// The mode that was active before. Required unless this is the first the Resource
89    /// Manager is aware of.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub previous_operation_mode_id: Option<Id>,
92    /// When the move began. Required under the same condition.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub transition_timestamp: Option<Timestamp>,
95}
96
97/// When one of the device's timers finishes.
98///
99/// Unlike the FRBC and DDBC forms, this one names no actuator — OMBC has a single state
100/// machine.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
102#[serde(deny_unknown_fields)]
103pub struct TimerStatus {
104    /// This message's identifier.
105    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
106    pub message_id: Id,
107    /// The timer this is about.
108    pub timer_id: Id,
109    /// When it finishes.
110    pub finished_at: Timestamp,
111}
112
113/// The CEM asking the device to change mode.
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
115#[serde(deny_unknown_fields)]
116pub struct Instruction {
117    /// This message's identifier.
118    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
119    pub message_id: Id,
120    /// The instruction's own identifier.
121    pub id: Id,
122    /// When to start. In the past means as soon as possible.
123    pub execution_time: Timestamp,
124    /// The mode to move to.
125    pub operation_mode_id: Id,
126    /// Where in the mode's ranges to run, in `[0, 1]`.
127    pub operation_mode_factor: f64,
128    /// Whether this is an abnormal-condition instruction.
129    pub abnormal_condition: bool,
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::types::common::CommodityQuantity;
136
137    #[test]
138    fn the_generator_example_from_the_whitepaper() {
139        // The whitepaper's diesel generator: off at 0 W, reduced at -1800 W, full at
140        // -3000 W. Production is negative.
141        let modes = alloc::vec![
142            OperationMode {
143                id: Id::new_const("off"),
144                diagnostic_label: Some("Off".into()),
145                power_ranges: alloc::vec![PowerRange::exactly(
146                    0.0,
147                    CommodityQuantity::ElectricPowerL1
148                )],
149                running_costs: None,
150                abnormal_condition_only: false,
151            },
152            OperationMode {
153                id: Id::new_const("reduced"),
154                diagnostic_label: Some("Reduced power".into()),
155                power_ranges: alloc::vec![PowerRange::exactly(
156                    -1800.0,
157                    CommodityQuantity::ElectricPowerL1
158                )],
159                running_costs: None,
160                abnormal_condition_only: false,
161            },
162        ];
163        let system = SystemDescription {
164            message_id: Id::new_const("m1"),
165            valid_from: Timestamp::UNIX_EPOCH,
166            operation_modes: modes,
167            transitions: alloc::vec![Transition::simple(
168                Id::new_const("t1"),
169                Id::new_const("off"),
170                Id::new_const("reduced")
171            )],
172            timers: Vec::new(),
173        };
174        assert!(system.operation_mode(&Id::new_const("reduced")).is_some());
175        assert!(
176            system
177                .transition(&Id::new_const("off"), &Id::new_const("reduced"))
178                .is_some()
179        );
180        // There is no transition the other way, which the state machine is entitled to
181        // say and a CEM is expected to respect.
182        assert!(
183            system
184                .transition(&Id::new_const("reduced"), &Id::new_const("off"))
185                .is_none()
186        );
187    }
188
189    #[test]
190    fn the_timer_status_has_no_actuator() {
191        let json = serde_json::to_string(&TimerStatus {
192            message_id: Id::new_const("m1"),
193            timer_id: Id::new_const("timer0"),
194            finished_at: Timestamp::UNIX_EPOCH,
195        })
196        .unwrap();
197        assert!(!json.contains("actuator_id"));
198    }
199}