Skip to main content

s2_kit/types/
ddbc.rs

1//! Demand Driven Based Control — a device that must meet a demand but is flexible in
2//! how it meets it.
3//!
4//! A hybrid heat pump is the standard's own example: it must deliver a given amount of
5//! heat, and can choose between the heat pump and the gas boiler to do it. Like FRBC it
6//! has actuators that are state machines; unlike FRBC, a mode's states do not describe
7//! an effect on a store but a **supply rate** the CEM can match against the demand.
8//!
9//! DDBC is also the one place where the two tagged versions of S2 JSON differ. In
10//! `v0.0.2-beta` the present demand rate was a required field of
11//! [`SystemDescription`]; in `v1.0.0` it is a message of its own,
12//! [`PresentDemandStatus`]. See [`WireProfile`](crate::types::WireProfile).
13
14use alloc::string::String;
15use alloc::vec::Vec;
16
17use bon::Builder;
18use serde::{Deserialize, Serialize};
19
20use super::common::{Commodity, PowerRange, Timer, Transition};
21use super::{Duration, Id, NumberRange, Timestamp};
22
23/// One state of an actuator's state machine.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
25#[serde(deny_unknown_fields)]
26#[builder(on(String, into))]
27pub struct OperationMode {
28    /// Unique within the actuator description that contains it.
29    ///
30    /// The wire spells this field with a capital `I` — the only field in the whole of
31    /// S2 JSON that does (erratum E4).
32    #[serde(rename = "Id")]
33    pub id: Id,
34    /// Human-readable, for debugging only.
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub diagnostic_label: Option<String>,
37    /// The power in this mode: start at factor 0, end at factor 1.
38    pub power_ranges: Vec<PowerRange>,
39    /// The supply rate this mode can deliver, which the CEM matches against the demand.
40    /// Start at factor 0, end at factor 1.
41    pub supply_range: NumberRange,
42    /// Cost per second of running in this mode, excluding the commodity. The range
43    /// expresses uncertainty, not the factor.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub running_costs: Option<NumberRange>,
46    /// Whether this mode may only be used during an abnormal condition.
47    pub abnormal_condition_only: bool,
48}
49
50/// One of the ways the system can meet its demand.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
52#[serde(deny_unknown_fields)]
53#[builder(on(String, into))]
54pub struct ActuatorDescription {
55    /// Unique within the Resource Manager for the session.
56    pub id: Id,
57    /// Human-readable, for debugging only.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub diagnostic_label: Option<String>,
60    /// The commodities this actuator's modes use.
61    ///
62    /// The wire drops an `i` — `supported_commodites` (erratum E5).
63    #[serde(rename = "supported_commodites")]
64    pub supported_commodities: Vec<Commodity>,
65    /// The states of the machine.
66    pub operation_modes: Vec<OperationMode>,
67    /// The permitted moves between them.
68    pub transitions: Vec<Transition>,
69    /// Timers those moves start or wait for.
70    pub timers: Vec<Timer>,
71}
72
73impl ActuatorDescription {
74    /// The operation mode with this id, if the actuator has one.
75    #[must_use]
76    pub fn operation_mode(&self, id: &Id) -> Option<&OperationMode> {
77        self.operation_modes.iter().find(|m| m.id == *id)
78    }
79
80    /// The timer with this id, if the actuator has one.
81    #[must_use]
82    pub fn timer(&self, id: &Id) -> Option<&Timer> {
83        self.timers.iter().find(|t| t.id == *id)
84    }
85
86    /// The transition from `from` to `to`, if one is described.
87    #[must_use]
88    pub fn transition(&self, from: &Id, to: &Id) -> Option<&Transition> {
89        self.transitions
90            .iter()
91            .find(|t| t.from == *from && t.to == *to)
92    }
93}
94
95/// Expected demand over one slice of time.
96#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
97#[serde(deny_unknown_fields)]
98pub struct AverageDemandRateForecastElement {
99    /// How long this slice lasts.
100    pub duration: Duration,
101    /// The 100 % upper bound.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub demand_rate_upper_limit: Option<f64>,
104    /// The 95 % upper bound.
105    #[serde(
106        rename = "demand_rate_upper_95PPR",
107        skip_serializing_if = "Option::is_none"
108    )]
109    pub demand_rate_upper_95ppr: Option<f64>,
110    /// The 68 % upper bound.
111    #[serde(
112        rename = "demand_rate_upper_68PPR",
113        skip_serializing_if = "Option::is_none"
114    )]
115    pub demand_rate_upper_68ppr: Option<f64>,
116    /// The most likely demand rate.
117    pub demand_rate_expected: f64,
118    /// The 68 % lower bound.
119    #[serde(
120        rename = "demand_rate_lower_68PPR",
121        skip_serializing_if = "Option::is_none"
122    )]
123    pub demand_rate_lower_68ppr: Option<f64>,
124    /// The 95 % lower bound.
125    #[serde(
126        rename = "demand_rate_lower_95PPR",
127        skip_serializing_if = "Option::is_none"
128    )]
129    pub demand_rate_lower_95ppr: Option<f64>,
130    /// The 100 % lower bound.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub demand_rate_lower_limit: Option<f64>,
133}
134
135impl AverageDemandRateForecastElement {
136    /// The bands from lowest to highest, skipping those that are absent.
137    #[must_use]
138    pub fn bands_ascending(&self) -> [(&'static str, Option<f64>); 7] {
139        [
140            ("demand_rate_lower_limit", self.demand_rate_lower_limit),
141            ("demand_rate_lower_95PPR", self.demand_rate_lower_95ppr),
142            ("demand_rate_lower_68PPR", self.demand_rate_lower_68ppr),
143            ("demand_rate_expected", Some(self.demand_rate_expected)),
144            ("demand_rate_upper_68PPR", self.demand_rate_upper_68ppr),
145            ("demand_rate_upper_95PPR", self.demand_rate_upper_95ppr),
146            ("demand_rate_upper_limit", self.demand_rate_upper_limit),
147        ]
148    }
149}
150
151/// Every actuator that can meet the demand.
152#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
153#[serde(deny_unknown_fields)]
154pub struct SystemDescription {
155    /// This message's identifier.
156    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
157    pub message_id: Id,
158    /// When this description becomes valid.
159    pub valid_from: Timestamp,
160    /// Every actuator. At least one, at most ten.
161    pub actuators: Vec<ActuatorDescription>,
162    /// The demand that must be satisfied right now.
163    ///
164    /// **Required in `v0.0.2-beta` and absent in `v1.0.0`**, where it became
165    /// [`PresentDemandStatus`]. The codec enforces whichever the negotiated profile
166    /// requires, so this is the one field whose optionality is a function of the version
167    ///.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub present_demand_rate: Option<NumberRange>,
170    /// Whether an [`AverageDemandRateForecast`] may follow.
171    pub provides_average_demand_rate_forecast: bool,
172}
173
174impl SystemDescription {
175    /// The actuator with this id, if the description has one.
176    #[must_use]
177    pub fn actuator(&self, id: &Id) -> Option<&ActuatorDescription> {
178        self.actuators.iter().find(|a| a.id == *id)
179    }
180}
181
182/// The demand that must be satisfied right now.
183///
184/// New in S2 JSON v1.0.0; in `v0.0.2-beta` this was a field of [`SystemDescription`].
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
186#[serde(deny_unknown_fields)]
187pub struct PresentDemandStatus {
188    /// This message's identifier.
189    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
190    pub message_id: Id,
191    /// The demand rate the system has to satisfy.
192    pub present_demand_rate: NumberRange,
193}
194
195/// Which operation mode an actuator is in, and how far into it.
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
197#[serde(deny_unknown_fields)]
198pub struct ActuatorStatus {
199    /// This message's identifier.
200    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
201    pub message_id: Id,
202    /// The actuator this is about.
203    pub actuator_id: Id,
204    /// The mode that is active now.
205    pub active_operation_mode_id: Id,
206    /// Where in that mode's ranges it is running, in `[0, 1]`.
207    pub operation_mode_factor: f64,
208    /// The mode that was active before. Required unless this is the first the Resource
209    /// Manager is aware of.
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub previous_operation_mode_id: Option<Id>,
212    /// When the move began. Required under the same condition.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub transition_timestamp: Option<Timestamp>,
215}
216
217/// When one of an actuator's timers finishes.
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
219#[serde(deny_unknown_fields)]
220pub struct TimerStatus {
221    /// This message's identifier.
222    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
223    pub message_id: Id,
224    /// The timer this is about.
225    pub timer_id: Id,
226    /// The actuator it belongs to.
227    pub actuator_id: Id,
228    /// When it finishes.
229    pub finished_at: Timestamp,
230}
231
232/// What the system expects to be asked for.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
234#[serde(deny_unknown_fields)]
235pub struct AverageDemandRateForecast {
236    /// This message's identifier.
237    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
238    pub message_id: Id,
239    /// When the forecast starts.
240    pub start_time: Timestamp,
241    /// The slices, in chronological order.
242    pub elements: Vec<AverageDemandRateForecastElement>,
243}
244
245/// The CEM asking an actuator to change mode.
246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
247#[serde(deny_unknown_fields)]
248pub struct Instruction {
249    /// This message's identifier.
250    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
251    pub message_id: Id,
252    /// The instruction's own identifier.
253    pub id: Id,
254    /// When to start. In the past means as soon as possible.
255    pub execution_time: Timestamp,
256    /// Whether this is an abnormal-condition instruction.
257    pub abnormal_condition: bool,
258    /// Which actuator.
259    pub actuator_id: Id,
260    /// Which mode it should move to.
261    pub operation_mode_id: Id,
262    /// Where in the mode's ranges to run, in `[0, 1]`.
263    pub operation_mode_factor: f64,
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269    use crate::types::common::CommodityQuantity;
270
271    #[test]
272    fn the_two_misspellings_are_on_the_wire_and_not_in_rust() {
273        let mode = OperationMode {
274            id: Id::new_const("heatpump"),
275            diagnostic_label: None,
276            power_ranges: alloc::vec![PowerRange::exactly(
277                2000.0,
278                CommodityQuantity::ElectricPowerL1
279            )],
280            supply_range: NumberRange::new(0.0, 6000.0),
281            running_costs: None,
282            abnormal_condition_only: false,
283        };
284        let actuator = ActuatorDescription {
285            id: Id::new_const("a1"),
286            diagnostic_label: None,
287            supported_commodities: alloc::vec![Commodity::Electricity],
288            operation_modes: alloc::vec![mode],
289            transitions: Vec::new(),
290            timers: Vec::new(),
291        };
292        let json = serde_json::to_string(&actuator).unwrap();
293        assert!(json.contains("\"supported_commodites\""), "{json}");
294        assert!(json.contains("\"Id\":\"heatpump\""), "{json}");
295        assert!(!json.contains("\"supported_commodities\""));
296        let back: ActuatorDescription = serde_json::from_str(&json).unwrap();
297        assert_eq!(back, actuator);
298    }
299
300    #[test]
301    fn the_demand_rate_is_a_field_in_beta_and_a_message_in_one_zero() {
302        // v1.0.0 shape: no such field.
303        let one_zero = SystemDescription {
304            message_id: Id::new_const("m1"),
305            valid_from: Timestamp::UNIX_EPOCH,
306            actuators: Vec::new(),
307            present_demand_rate: None,
308            provides_average_demand_rate_forecast: false,
309        };
310        let json = serde_json::to_string(&one_zero).unwrap();
311        assert!(!json.contains("present_demand_rate"));
312
313        // beta shape: the field is there, between `actuators` and the forecast flag,
314        // which is where the beta schema declares it.
315        let beta = SystemDescription {
316            present_demand_rate: Some(NumberRange::new(0.0, 6000.0)),
317            ..one_zero
318        };
319        let json = serde_json::to_string(&beta).unwrap();
320        let demand_at = json.find("present_demand_rate").unwrap();
321        let actuators_at = json.find("actuators").unwrap();
322        let provides_at = json.find("provides_average").unwrap();
323        assert!(actuators_at < demand_at && demand_at < provides_at);
324    }
325}