Skip to main content

s2_kit/types/
ppbc.rs

1//! Power Profile Based Control — a task that must be done, but not necessarily now.
2//!
3//! A washing machine, a dishwasher, a tumble dryer. The Resource Manager publishes a
4//! [`PowerProfileDefinition`]: a window (`start_time` to `end_time`) and one or more
5//! **containers**, each offering **alternative sequences** the CEM may choose between —
6//! a fast hot wash and a slow one, say. The CEM schedules one sequence per container,
7//! and may interrupt and resume a sequence that says it is interruptible.
8
9use alloc::vec::Vec;
10
11use bon::Builder;
12use serde::{Deserialize, Serialize};
13
14use super::common::PowerForecastValue;
15use super::{Duration, Id, Timestamp};
16
17/// How far a container's chosen sequence has got.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
20pub enum PowerSequenceStatus {
21    /// Nothing in this container is scheduled.
22    NotScheduled,
23    /// The chosen sequence will run in the future.
24    Scheduled,
25    /// It is running.
26    Executing,
27    /// It is running but paused, and will continue.
28    Interrupted,
29    /// It finished successfully.
30    Finished,
31    /// The device abandoned it; it will not continue.
32    Aborted,
33}
34
35impl PowerSequenceStatus {
36    /// Whether a sequence has been chosen at all.
37    #[must_use]
38    pub const fn has_selection(self) -> bool {
39        !matches!(self, Self::NotScheduled)
40    }
41
42    /// Whether the sequence has started — the condition under which
43    /// `PowerSequenceContainerStatus::progress` must be present.
44    #[must_use]
45    pub const fn has_started(self) -> bool {
46        matches!(
47            self,
48            Self::Executing | Self::Interrupted | Self::Finished | Self::Aborted
49        )
50    }
51}
52
53/// One step of a sequence: a power, for a while.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct PowerSequenceElement {
57    /// How long this step lasts.
58    pub duration: Duration,
59    /// The power drawn or produced, at most one value per commodity quantity.
60    pub power_values: Vec<PowerForecastValue>,
61}
62
63/// One way of performing the task.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
65#[serde(deny_unknown_fields)]
66pub struct PowerSequence {
67    /// Unique within the container that holds it.
68    pub id: Id,
69    /// The steps, in chronological order.
70    pub elements: Vec<PowerSequenceElement>,
71    /// Whether the CEM may pause it once started.
72    pub is_interruptible: bool,
73    /// The longest the device may be paused between the end of the previous sequence and
74    /// the start of this one.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub max_pause_before: Option<Duration>,
77    /// Whether this sequence may only be used during an abnormal condition.
78    pub abnormal_condition_only: bool,
79}
80
81impl PowerSequence {
82    /// How long the whole sequence takes.
83    #[must_use]
84    pub fn total_duration(&self) -> Duration {
85        self.elements.iter().fold(Duration::ZERO, |acc, e| {
86            acc.checked_add(e.duration).unwrap_or(acc)
87        })
88    }
89}
90
91/// A set of alternatives, exactly one of which the CEM chooses.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
93#[serde(deny_unknown_fields)]
94pub struct PowerSequenceContainer {
95    /// Unique within the profile that holds it.
96    pub id: Id,
97    /// The alternatives. At least one.
98    pub power_sequences: Vec<PowerSequence>,
99}
100
101impl PowerSequenceContainer {
102    /// The sequence with this id, if the container offers one.
103    #[must_use]
104    pub fn sequence(&self, id: &Id) -> Option<&PowerSequence> {
105        self.power_sequences.iter().find(|s| s.id == *id)
106    }
107}
108
109/// How one container is getting on.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
111#[serde(deny_unknown_fields)]
112pub struct PowerSequenceContainerStatus {
113    /// The profile the container belongs to.
114    pub power_profile_id: Id,
115    /// The container this is about.
116    pub sequence_container_id: Id,
117    /// Which alternative was chosen. Absent when none has been.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub selected_sequence_id: Option<Id>,
120    /// How long the chosen sequence has been running. Required once it has started.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub progress: Option<Duration>,
123    /// How far it has got.
124    pub status: PowerSequenceStatus,
125}
126
127/// The task, its window, and every way of performing it.
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
129#[serde(deny_unknown_fields)]
130pub struct PowerProfileDefinition {
131    /// This message's identifier.
132    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
133    pub message_id: Id,
134    /// The profile's own identifier, which every instruction refers back to.
135    pub id: Id,
136    /// The earliest the first sequence may start.
137    pub start_time: Timestamp,
138    /// The latest the last sequence must be finished.
139    pub end_time: Timestamp,
140    /// The containers, in chronological order.
141    ///
142    /// The wire name is plural in an unusual place — `power_sequences_containers` — and
143    /// the Rust field does not inherit that.
144    #[serde(rename = "power_sequences_containers")]
145    pub power_sequence_containers: Vec<PowerSequenceContainer>,
146}
147
148impl PowerProfileDefinition {
149    /// The container with this id, if the profile has one.
150    #[must_use]
151    pub fn container(&self, id: &Id) -> Option<&PowerSequenceContainer> {
152        self.power_sequence_containers.iter().find(|c| c.id == *id)
153    }
154
155    /// Resolve a container and a sequence together, as every instruction must.
156    #[must_use]
157    pub fn resolve(
158        &self,
159        container_id: &Id,
160        sequence_id: &Id,
161    ) -> Option<(&PowerSequenceContainer, &PowerSequence)> {
162        let container = self.container(container_id)?;
163        let sequence = container.sequence(sequence_id)?;
164        Some((container, sequence))
165    }
166}
167
168/// How every container of a profile is getting on.
169#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
170#[serde(deny_unknown_fields)]
171pub struct PowerProfileStatus {
172    /// This message's identifier.
173    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
174    pub message_id: Id,
175    /// One entry per container in the profile — all of them, not only the interesting
176    /// ones.
177    pub sequence_container_status: Vec<PowerSequenceContainerStatus>,
178}
179
180/// The CEM choosing a sequence and a start time.
181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
182#[serde(deny_unknown_fields)]
183pub struct ScheduleInstruction {
184    /// This message's identifier.
185    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
186    pub message_id: Id,
187    /// The instruction's own identifier.
188    pub id: Id,
189    /// The profile being scheduled.
190    pub power_profile_id: Id,
191    /// The container within it.
192    pub sequence_container_id: Id,
193    /// The alternative being chosen.
194    pub power_sequence_id: Id,
195    /// When it should start. In the past means as soon as possible.
196    pub execution_time: Timestamp,
197    /// Whether this is an abnormal-condition instruction.
198    pub abnormal_condition: bool,
199}
200
201/// The CEM pausing a running sequence.
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
203#[serde(deny_unknown_fields)]
204pub struct StartInterruptionInstruction {
205    /// This message's identifier.
206    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
207    pub message_id: Id,
208    /// The instruction's own identifier.
209    pub id: Id,
210    /// The profile.
211    pub power_profile_id: Id,
212    /// The container.
213    pub sequence_container_id: Id,
214    /// The sequence to interrupt. It must be one that says it is interruptible.
215    pub power_sequence_id: Id,
216    /// When to interrupt. In the past means as soon as possible.
217    pub execution_time: Timestamp,
218    /// Whether this is an abnormal-condition instruction.
219    pub abnormal_condition: bool,
220}
221
222/// The CEM resuming an interrupted sequence.
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
224#[serde(deny_unknown_fields)]
225pub struct EndInterruptionInstruction {
226    /// This message's identifier.
227    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
228    pub message_id: Id,
229    /// The instruction's own identifier.
230    pub id: Id,
231    /// The profile.
232    pub power_profile_id: Id,
233    /// The container.
234    pub sequence_container_id: Id,
235    /// The sequence to resume.
236    pub power_sequence_id: Id,
237    /// When to resume. In the past means as soon as possible.
238    pub execution_time: Timestamp,
239    /// Whether this is an abnormal-condition instruction.
240    pub abnormal_condition: bool,
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use crate::types::common::CommodityQuantity;
247
248    fn sequence(id: &str, seconds: u64) -> PowerSequence {
249        PowerSequence {
250            id: Id::parse(id).unwrap(),
251            elements: alloc::vec![PowerSequenceElement {
252                duration: Duration::from_secs(seconds),
253                power_values: alloc::vec![PowerForecastValue::expected(
254                    2000.0,
255                    CommodityQuantity::ElectricPowerL1
256                )],
257            }],
258            is_interruptible: false,
259            max_pause_before: None,
260            abnormal_condition_only: false,
261        }
262    }
263
264    #[test]
265    fn the_container_plural_is_on_the_wire_but_not_in_rust() {
266        let profile = PowerProfileDefinition {
267            message_id: Id::new_const("m1"),
268            id: Id::new_const("profile1"),
269            start_time: Timestamp::UNIX_EPOCH,
270            end_time: Timestamp::UNIX_EPOCH,
271            power_sequence_containers: alloc::vec![PowerSequenceContainer {
272                id: Id::new_const("c1"),
273                power_sequences: alloc::vec![sequence("s1", 3600)],
274            }],
275        };
276        let json = serde_json::to_string(&profile).unwrap();
277        assert!(json.contains("\"power_sequences_containers\""));
278        let back: PowerProfileDefinition = serde_json::from_str(&json).unwrap();
279        assert_eq!(back, profile);
280    }
281
282    #[test]
283    fn resolving_an_instruction_needs_both_ids() {
284        let profile = PowerProfileDefinition {
285            message_id: Id::new_const("m1"),
286            id: Id::new_const("profile1"),
287            start_time: Timestamp::UNIX_EPOCH,
288            end_time: Timestamp::UNIX_EPOCH,
289            power_sequence_containers: alloc::vec![PowerSequenceContainer {
290                id: Id::new_const("c1"),
291                power_sequences: alloc::vec![sequence("s1", 3600), sequence("s2", 7200)],
292            }],
293        };
294        let (container, seq) = profile
295            .resolve(&Id::new_const("c1"), &Id::new_const("s2"))
296            .unwrap();
297        assert_eq!(container.id, "c1");
298        assert_eq!(seq.total_duration(), Duration::from_secs(7200));
299        // A sequence from the wrong container does not resolve, which is what stops a
300        // Resource Manager starting a wash nobody asked for.
301        assert!(
302            profile
303                .resolve(&Id::new_const("c9"), &Id::new_const("s1"))
304                .is_none()
305        );
306        assert!(
307            profile
308                .resolve(&Id::new_const("c1"), &Id::new_const("s9"))
309                .is_none()
310        );
311    }
312
313    #[test]
314    fn progress_is_required_exactly_once_a_sequence_has_started() {
315        assert!(!PowerSequenceStatus::NotScheduled.has_started());
316        assert!(!PowerSequenceStatus::Scheduled.has_started());
317        assert!(PowerSequenceStatus::Executing.has_started());
318        assert!(PowerSequenceStatus::Interrupted.has_started());
319        assert!(PowerSequenceStatus::Finished.has_started());
320        assert!(PowerSequenceStatus::Aborted.has_started());
321        assert!(!PowerSequenceStatus::NotScheduled.has_selection());
322        assert!(PowerSequenceStatus::Scheduled.has_selection());
323    }
324}