Skip to main content

s2_kit/types/
common.rs

1//! Types common to every control type, and the ten messages that are not part of one.
2//!
3//! Measurements and forecasts are deliberately outside the control types: docs
4//! the S2 documentation, *Control types* — "Sending measurements and sending forecasts to the CEM is
5//! not part of any of the Control Types. This functionality can always be used, even if
6//! no Control Type has been activated by the CEM."
7
8use alloc::string::String;
9use alloc::vec::Vec;
10
11use bon::Builder;
12use serde::{Deserialize, Serialize};
13
14use super::{Duration, Id, ProtocolVersion, Timestamp};
15
16// ---------------------------------------------------------------------------
17// Enumerations
18// ---------------------------------------------------------------------------
19
20/// A form of energy a resource exchanges with the grid.
21///
22/// Only energy exchanged *with the grid* counts — never a device's internal flows.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "UPPERCASE")]
25#[non_exhaustive]
26pub enum Commodity {
27    /// Natural gas.
28    Gas,
29    /// Heat.
30    Heat,
31    /// Electricity.
32    Electricity,
33    /// Heating oil.
34    Oil,
35}
36
37/// A commodity combined with the quantity and unit its power is expressed in, and — for
38/// electricity — the phase.
39///
40/// Note that `HEAT.TEMPERATURE` is in this list although a temperature is not a power.
41/// The standard puts it here; the model follows.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
43#[non_exhaustive]
44pub enum CommodityQuantity {
45    /// Electric power in watts on phase 1. A single-phase device always uses L1.
46    #[serde(rename = "ELECTRIC.POWER.L1")]
47    ElectricPowerL1,
48    /// Electric power in watts on phase 2. Three-phase devices only.
49    #[serde(rename = "ELECTRIC.POWER.L2")]
50    ElectricPowerL2,
51    /// Electric power in watts on phase 3. Three-phase devices only.
52    #[serde(rename = "ELECTRIC.POWER.L3")]
53    ElectricPowerL3,
54    /// Electric power in watts, shared equally across three phases.
55    #[serde(rename = "ELECTRIC.POWER.3_PHASE_SYMMETRIC")]
56    ElectricPower3PhaseSymmetric,
57    /// Gas flow rate in litres per second.
58    #[serde(rename = "NATURAL_GAS.FLOW_RATE")]
59    NaturalGasFlowRate,
60    /// Hydrogen flow rate in grams per second.
61    #[serde(rename = "HYDROGEN.FLOW_RATE")]
62    HydrogenFlowRate,
63    /// Heat in degrees Celsius.
64    #[serde(rename = "HEAT.TEMPERATURE")]
65    HeatTemperature,
66    /// Flow rate of a heat-carrying gas or liquid, in litres per second.
67    #[serde(rename = "HEAT.FLOW_RATE")]
68    HeatFlowRate,
69    /// Thermal power in watts.
70    #[serde(rename = "HEAT.THERMAL_POWER")]
71    HeatThermalPower,
72    /// Oil flow rate in litres per hour.
73    #[serde(rename = "OIL.FLOW_RATE")]
74    OilFlowRate,
75}
76
77impl CommodityQuantity {
78    /// The commodity this quantity measures.
79    #[must_use]
80    pub const fn commodity(self) -> Commodity {
81        match self {
82            Self::ElectricPowerL1
83            | Self::ElectricPowerL2
84            | Self::ElectricPowerL3
85            | Self::ElectricPower3PhaseSymmetric => Commodity::Electricity,
86            Self::NaturalGasFlowRate | Self::HydrogenFlowRate => Commodity::Gas,
87            Self::HeatTemperature | Self::HeatFlowRate | Self::HeatThermalPower => Commodity::Heat,
88            Self::OilFlowRate => Commodity::Oil,
89        }
90    }
91
92    /// Whether this is one of the per-phase electric quantities.
93    #[must_use]
94    pub const fn is_per_phase_electric(self) -> bool {
95        matches!(
96            self,
97            Self::ElectricPowerL1 | Self::ElectricPowerL2 | Self::ElectricPowerL3
98        )
99    }
100
101    /// Whether this quantity is a power at all.
102    ///
103    /// `HEAT.TEMPERATURE` is the one that is not, and treating it as one is a mistake
104    /// the enum cannot otherwise stop.
105    #[must_use]
106    pub const fn is_power(self) -> bool {
107        !matches!(self, Self::HeatTemperature)
108    }
109}
110
111/// The way a Resource Manager expresses its flexibility.
112///
113/// Five control types cover the eight flexibility patterns the standard identifies, plus
114/// two values that are not control types at all: `NOT_CONTROLABLE`, a legal *selection*
115/// after which only measurements and forecasts flow, and `NO_SELECTION`, the deactivated
116/// state.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
118#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
119#[non_exhaustive]
120pub enum ControlType {
121    /// Power Envelope Based Control — a device that cannot be controlled but can be
122    /// bounded. Curtailable PV, a wallbox that only curtails.
123    PowerEnvelopeBasedControl,
124    /// Power Profile Based Control — a device with a task to perform that is flexible
125    /// about *when*. A washing machine, a dishwasher.
126    PowerProfileBasedControl,
127    /// Operation Mode Based Control — a device that can adjust its power with no
128    /// constraint on how long the adjustment lasts. A generator.
129    OperationModeBasedControl,
130    /// Fill Rate Based Control — anything that stores or buffers energy. A battery, an
131    /// EV, a hot-water tank, a fridge.
132    FillRateBasedControl,
133    /// Demand Driven Based Control — a device that must meet a demand but is flexible in
134    /// how. A hybrid heat pump.
135    DemandDrivenBasedControl,
136    /// No control is possible. Measurements and forecasts may still be sent.
137    ///
138    /// The wire spelling has one `l`. The Rust name does not inherit the typo; the
139    /// `serde` rename carries the bytes (erratum E15).
140    #[serde(rename = "NOT_CONTROLABLE")]
141    NotControllable,
142    /// No control type is, or has been, selected.
143    NoSelection,
144}
145
146impl ControlType {
147    /// Whether this is one of the five real control types, as opposed to
148    /// `NOT_CONTROLABLE` or `NO_SELECTION`.
149    #[must_use]
150    pub const fn is_controllable(self) -> bool {
151        matches!(
152            self,
153            Self::PowerEnvelopeBasedControl
154                | Self::PowerProfileBasedControl
155                | Self::OperationModeBasedControl
156                | Self::FillRateBasedControl
157                | Self::DemandDrivenBasedControl
158        )
159    }
160
161    /// Whether the control type is built on operation modes, transitions and timers.
162    ///
163    /// the S2 documentation, *Operation modes*: OMBC, FRBC and DDBC share that machinery; PEBC
164    /// and PPBC "each have their own approach".
165    #[must_use]
166    pub const fn uses_operation_modes(self) -> bool {
167        matches!(
168            self,
169            Self::OperationModeBasedControl
170                | Self::FillRateBasedControl
171                | Self::DemandDrivenBasedControl
172        )
173    }
174
175    /// The short name used in message types: `"FRBC"`, `"PEBC"`, and so on.
176    #[must_use]
177    pub const fn abbreviation(self) -> Option<&'static str> {
178        match self {
179            Self::PowerEnvelopeBasedControl => Some("PEBC"),
180            Self::PowerProfileBasedControl => Some("PPBC"),
181            Self::OperationModeBasedControl => Some("OMBC"),
182            Self::FillRateBasedControl => Some("FRBC"),
183            Self::DemandDrivenBasedControl => Some("DDBC"),
184            Self::NotControllable | Self::NoSelection => None,
185        }
186    }
187}
188
189/// The currency cost information is expressed in.
190///
191/// `S2J messages/ResourceManagerDetails.currency` is "Mandatory if cost information is
192/// published" — running costs and transition costs are in this currency per second, and
193/// never include the price of the commodity itself.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
195#[serde(rename_all = "UPPERCASE")]
196#[non_exhaustive]
197#[allow(missing_docs)] // ISO 4217 codes; the name is the documentation
198pub enum Currency {
199    Aed,
200    Ang,
201    Aud,
202    Che,
203    Chf,
204    Chw,
205    Eur,
206    Gbp,
207    Lbp,
208    Lkr,
209    Lrd,
210    Lsl,
211    Lyd,
212    Mad,
213    Mdl,
214    Mga,
215    Mkd,
216    Mmk,
217    Mnt,
218    Mop,
219    Mro,
220    Mur,
221    Mvr,
222    Mwk,
223    Mxn,
224    Mxv,
225    Myr,
226    Mzn,
227    Nad,
228    Ngn,
229    Nio,
230    Nok,
231    Npr,
232    Nzd,
233    Omr,
234    Pab,
235    Pen,
236    Pgk,
237    Php,
238    Pkr,
239    Pln,
240    Pyg,
241    Qar,
242    Ron,
243    Rsd,
244    Rub,
245    Rwf,
246    Sar,
247    Sbd,
248    Scr,
249    Sdg,
250    Sek,
251    Sgd,
252    Shp,
253    Sll,
254    Sos,
255    Srd,
256    Ssp,
257    Std,
258    Syp,
259    Szl,
260    Thb,
261    Tjs,
262    Tmt,
263    Tnd,
264    Top,
265    Try,
266    Ttd,
267    Twd,
268    Tzs,
269    Uah,
270    Ugx,
271    Usd,
272    Usn,
273    Uyi,
274    Uyu,
275    Uzs,
276    Vef,
277    Vnd,
278    Vuv,
279    Wst,
280    Xag,
281    Xau,
282    Xba,
283    Xbb,
284    Xbc,
285    Xbd,
286    Xcd,
287    Xof,
288    Xpd,
289    Xpf,
290    Xpt,
291    Xsu,
292    Xts,
293    Xua,
294    Xxx,
295    Yer,
296    Zar,
297    Zmw,
298    Zwl,
299}
300
301/// Which side of an S2 conversation a node is.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
303#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
304pub enum EnergyManagementRole {
305    /// Customer Energy Manager — decides *why* a device should behave a certain way.
306    Cem,
307    /// Resource Manager — describes *how* a device can behave.
308    Rm,
309}
310
311impl EnergyManagementRole {
312    /// The other side.
313    #[must_use]
314    pub const fn peer(self) -> Self {
315        match self {
316            Self::Cem => Self::Rm,
317            Self::Rm => Self::Cem,
318        }
319    }
320}
321
322/// What became of an instruction.
323///
324/// The order in which these must be sent is not documented (`[s2-json #26]`,
325/// erratum E11), so the session ledger accepts any order and warns
326/// only on a regression.
327#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
328#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
329#[non_exhaustive]
330pub enum InstructionStatus {
331    /// Newly created.
332    New,
333    /// Accepted.
334    Accepted,
335    /// Rejected.
336    Rejected,
337    /// Revoked.
338    Revoked,
339    /// Execution started.
340    Started,
341    /// Finished successfully.
342    Succeeded,
343    /// Aborted.
344    Aborted,
345}
346
347impl InstructionStatus {
348    /// Whether no further status can follow.
349    #[must_use]
350    pub const fn is_terminal(self) -> bool {
351        matches!(
352            self,
353            Self::Rejected | Self::Revoked | Self::Succeeded | Self::Aborted
354        )
355    }
356
357    /// How far through the lifecycle this status is, for detecting a regression.
358    #[must_use]
359    pub const fn progress_rank(self) -> u8 {
360        match self {
361            Self::New => 0,
362            Self::Accepted => 1,
363            Self::Started => 2,
364            Self::Succeeded | Self::Rejected | Self::Revoked | Self::Aborted => 3,
365        }
366    }
367}
368
369/// How a received message was processed, and what the sender should do about it.
370///
371/// The consequences are normative (`S2J schemas/ReceptionStatusValues`); see
372/// [`ReceptionStatusValues::consequence`].
373#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
374#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
375#[non_exhaustive]
376pub enum ReceptionStatusValues {
377    /// "Message not understood (e.g. not valid JSON, no message_id found)."
378    InvalidData,
379    /// "Message was not according to schema."
380    InvalidMessage,
381    /// "Message contents is invalid (e.g. contains a non-existing ID). Somewhat
382    /// equivalent to BAD_REQUEST in HTTP."
383    InvalidContent,
384    /// "Receiver encountered an error." The sender should try again.
385    TemporaryError,
386    /// "Receiver encountered an error which it cannot recover from." Disconnect.
387    PermanentError,
388    /// "Message processed normally."
389    Ok,
390}
391
392/// What the standard says the *sender* should do about a reception status.
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
394pub enum Consequence {
395    /// Proceed normally.
396    Proceed,
397    /// The message was ignored; proceed if possible.
398    Ignored,
399    /// Try to send the message again.
400    Retry,
401    /// Disconnect.
402    Disconnect,
403}
404
405impl ReceptionStatusValues {
406    /// The normative consequence for the sender.
407    #[must_use]
408    pub const fn consequence(self) -> Consequence {
409        match self {
410            Self::Ok => Consequence::Proceed,
411            Self::InvalidData | Self::InvalidMessage | Self::InvalidContent => Consequence::Ignored,
412            Self::TemporaryError => Consequence::Retry,
413            Self::PermanentError => Consequence::Disconnect,
414        }
415    }
416
417    /// Whether this status reports a problem.
418    #[must_use]
419    pub const fn is_error(self) -> bool {
420        !matches!(self, Self::Ok)
421    }
422}
423
424/// The kinds of object a [`RevokeObject`] message can withdraw.
425#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
426#[non_exhaustive]
427pub enum RevokableObjects {
428    /// A `PEBC.PowerConstraints`.
429    #[serde(rename = "PEBC.PowerConstraints")]
430    PebcPowerConstraints,
431    /// A `PEBC.EnergyConstraint`.
432    #[serde(rename = "PEBC.EnergyConstraint")]
433    PebcEnergyConstraint,
434    /// A `PEBC.Instruction`.
435    #[serde(rename = "PEBC.Instruction")]
436    PebcInstruction,
437    /// A `PPBC.PowerProfileDefinition`.
438    #[serde(rename = "PPBC.PowerProfileDefinition")]
439    PpbcPowerProfileDefinition,
440    /// A `PPBC.ScheduleInstruction`.
441    #[serde(rename = "PPBC.ScheduleInstruction")]
442    PpbcScheduleInstruction,
443    /// A `PPBC.StartInterruptionInstruction`.
444    #[serde(rename = "PPBC.StartInterruptionInstruction")]
445    PpbcStartInterruptionInstruction,
446    /// A `PPBC.EndInterruptionInstruction`.
447    #[serde(rename = "PPBC.EndInterruptionInstruction")]
448    PpbcEndInterruptionInstruction,
449    /// An `OMBC.SystemDescription`.
450    #[serde(rename = "OMBC.SystemDescription")]
451    OmbcSystemDescription,
452    /// An `OMBC.Instruction`.
453    #[serde(rename = "OMBC.Instruction")]
454    OmbcInstruction,
455    /// An `FRBC.SystemDescription`.
456    #[serde(rename = "FRBC.SystemDescription")]
457    FrbcSystemDescription,
458    /// An `FRBC.Instruction`.
459    #[serde(rename = "FRBC.Instruction")]
460    FrbcInstruction,
461    /// A `DDBC.SystemDescription`.
462    #[serde(rename = "DDBC.SystemDescription")]
463    DdbcSystemDescription,
464    /// A `DDBC.Instruction`.
465    #[serde(rename = "DDBC.Instruction")]
466    DdbcInstruction,
467}
468
469impl RevokableObjects {
470    /// Which role owns this kind of object, and may therefore revoke it.
471    ///
472    /// The S2 Connect state table lists `RevokeObject` only in the RM's column, but this
473    /// enum contains every instruction type, which only a CEM sends. The mismatch is
474    /// erratum E6; both roles are accepted and a mismatch is a warning.
475    #[must_use]
476    pub const fn owner(self) -> EnergyManagementRole {
477        match self {
478            Self::PebcInstruction
479            | Self::PpbcScheduleInstruction
480            | Self::PpbcStartInterruptionInstruction
481            | Self::PpbcEndInterruptionInstruction
482            | Self::OmbcInstruction
483            | Self::FrbcInstruction
484            | Self::DdbcInstruction => EnergyManagementRole::Cem,
485            Self::PebcPowerConstraints
486            | Self::PebcEnergyConstraint
487            | Self::PpbcPowerProfileDefinition
488            | Self::OmbcSystemDescription
489            | Self::FrbcSystemDescription
490            | Self::DdbcSystemDescription => EnergyManagementRole::Rm,
491        }
492    }
493
494    /// The control type this object belongs to.
495    #[must_use]
496    pub const fn control_type(self) -> ControlType {
497        match self {
498            Self::PebcPowerConstraints | Self::PebcEnergyConstraint | Self::PebcInstruction => {
499                ControlType::PowerEnvelopeBasedControl
500            }
501            Self::PpbcPowerProfileDefinition
502            | Self::PpbcScheduleInstruction
503            | Self::PpbcStartInterruptionInstruction
504            | Self::PpbcEndInterruptionInstruction => ControlType::PowerProfileBasedControl,
505            Self::OmbcSystemDescription | Self::OmbcInstruction => {
506                ControlType::OperationModeBasedControl
507            }
508            Self::FrbcSystemDescription | Self::FrbcInstruction => {
509                ControlType::FillRateBasedControl
510            }
511            Self::DdbcSystemDescription | Self::DdbcInstruction => {
512                ControlType::DemandDrivenBasedControl
513            }
514        }
515    }
516}
517
518/// What a resource does with a commodity.
519#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
520#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
521pub enum RoleType {
522    /// Produces energy.
523    EnergyProducer,
524    /// Consumes energy.
525    EnergyConsumer,
526    /// Stores energy.
527    EnergyStorage,
528}
529
530/// What a sender wants to happen to the session.
531#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
532#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
533pub enum SessionRequestType {
534    /// "Please reconnect the WebSocket session. Once reconnected, it starts from scratch
535    /// with a handshake."
536    Reconnect,
537    /// "Disconnect the session (client can try to reconnecting with exponential
538    /// backoff)."
539    Terminate,
540}
541
542// ---------------------------------------------------------------------------
543// Shared components
544// ---------------------------------------------------------------------------
545
546/// A range of numbers.
547///
548/// What "start" and "end" mean depends on the field: for a `power_range` or a
549/// `fill_rate` the start is the value at an operation-mode factor of 0 and the end the
550/// value at 1, so the range is *interpolated*; for `running_costs` the range expresses
551/// **uncertainty** and is not linked to the factor at all.
552#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
553#[serde(deny_unknown_fields)]
554pub struct NumberRange {
555    /// The start of the range.
556    pub start_of_range: f64,
557    /// The end of the range.
558    pub end_of_range: f64,
559}
560
561impl NumberRange {
562    /// A range from `start` to `end`.
563    #[must_use]
564    pub const fn new(start: f64, end: f64) -> Self {
565        Self {
566            start_of_range: start,
567            end_of_range: end,
568        }
569    }
570
571    /// A range with a single value.
572    #[must_use]
573    pub const fn exactly(value: f64) -> Self {
574        Self::new(value, value)
575    }
576
577    /// Whether `value` lies within the range, inclusive of both ends.
578    #[must_use]
579    pub fn contains(self, value: f64) -> bool {
580        let (lo, hi) = self.ordered();
581        value >= lo && value <= hi
582    }
583
584    /// The range as `(low, high)`, whichever way round it was written.
585    #[must_use]
586    pub fn ordered(self) -> (f64, f64) {
587        if self.start_of_range <= self.end_of_range {
588            (self.start_of_range, self.end_of_range)
589        } else {
590            (self.end_of_range, self.start_of_range)
591        }
592    }
593
594    /// The width of the range.
595    #[must_use]
596    pub fn span(self) -> f64 {
597        self.end_of_range - self.start_of_range
598    }
599
600    /// Linear interpolation: the value at operation-mode `factor`.
601    ///
602    /// the S2 documentation, *Operation modes*: `power = (end - start) * factor + start`.
603    ///
604    /// Factors 0 and 1 return `start` and `end` **exactly**: in floating point
605    /// `start + (end - start) * 1.0` is not always `end`, and both roles compare against
606    /// the number the description published (D30).
607    #[must_use]
608    #[allow(
609        clippy::float_cmp,
610        reason = "0 and 1 are the endpoints, not approximations"
611    )]
612    pub fn at_factor(self, factor: f64) -> f64 {
613        if factor == 0.0 {
614            self.start_of_range
615        } else if factor == 1.0 {
616            self.end_of_range
617        } else {
618            self.start_of_range + self.span() * factor
619        }
620    }
621
622    /// The inverse of [`at_factor`](Self::at_factor): which factor produces `value`.
623    ///
624    /// `None` when the range is a single point, where every factor gives that value and
625    /// the question has no answer.
626    #[must_use]
627    pub fn factor_of(self, value: f64) -> Option<f64> {
628        let span = self.span();
629        if span == 0.0 {
630            None
631        } else {
632            Some((value - self.start_of_range) / span)
633        }
634    }
635
636    /// Whether both ends are finite.
637    #[must_use]
638    pub fn is_finite(self) -> bool {
639        self.start_of_range.is_finite() && self.end_of_range.is_finite()
640    }
641
642    /// Whether the two ranges overlap in more than a single point.
643    #[must_use]
644    pub fn overlaps(self, other: Self) -> bool {
645        let (a_lo, a_hi) = self.ordered();
646        let (b_lo, b_hi) = other.ordered();
647        a_lo < b_hi && b_lo < a_hi
648    }
649}
650
651impl From<core::ops::Range<f64>> for NumberRange {
652    fn from(r: core::ops::Range<f64>) -> Self {
653        Self::new(r.start, r.end)
654    }
655}
656
657impl From<NumberRange> for core::ops::Range<f64> {
658    fn from(r: NumberRange) -> Self {
659        r.start_of_range..r.end_of_range
660    }
661}
662
663/// A range of power values for one commodity quantity.
664///
665/// The start is the power at an operation-mode factor of 0, the end the power at 1.
666/// Consumption is positive and production negative, always as seen at the grid.
667#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
668#[serde(deny_unknown_fields)]
669pub struct PowerRange {
670    /// The power at factor 0.
671    pub start_of_range: f64,
672    /// The power at factor 1.
673    pub end_of_range: f64,
674    /// The quantity the values refer to.
675    pub commodity_quantity: CommodityQuantity,
676}
677
678impl PowerRange {
679    /// A power range.
680    #[must_use]
681    pub const fn new(start: f64, end: f64, commodity_quantity: CommodityQuantity) -> Self {
682        Self {
683            start_of_range: start,
684            end_of_range: end,
685            commodity_quantity,
686        }
687    }
688
689    /// A power range with a single value.
690    #[must_use]
691    pub const fn exactly(value: f64, commodity_quantity: CommodityQuantity) -> Self {
692        Self::new(value, value, commodity_quantity)
693    }
694
695    /// The range without its commodity quantity.
696    #[must_use]
697    pub const fn range(self) -> NumberRange {
698        NumberRange::new(self.start_of_range, self.end_of_range)
699    }
700
701    /// The power at operation-mode `factor`.
702    #[must_use]
703    pub fn at_factor(self, factor: f64) -> f64 {
704        self.range().at_factor(factor)
705    }
706}
707
708/// A measured power for one commodity quantity.
709#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
710#[serde(deny_unknown_fields)]
711pub struct PowerValue {
712    /// The quantity the value refers to.
713    pub commodity_quantity: CommodityQuantity,
714    /// The power, in the unit the quantity implies. Consumption positive.
715    pub value: f64,
716}
717
718impl PowerValue {
719    /// A power value.
720    #[must_use]
721    pub const fn new(commodity_quantity: CommodityQuantity, value: f64) -> Self {
722        Self {
723            commodity_quantity,
724            value,
725        }
726    }
727}
728
729/// A forecast power for one commodity quantity, with optional confidence bands.
730///
731/// The bands are nested percentile ranges: the 68 % band lies inside the 95 % band,
732/// which lies inside the 100 % limits. Only `value_expected` and `commodity_quantity`
733/// are required.
734#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
735#[serde(deny_unknown_fields)]
736pub struct PowerForecastValue {
737    /// The upper bound with 100 % certainty.
738    #[serde(skip_serializing_if = "Option::is_none")]
739    pub value_upper_limit: Option<f64>,
740    /// The upper bound with 95 % certainty.
741    #[serde(rename = "value_upper_95PPR", skip_serializing_if = "Option::is_none")]
742    pub value_upper_95ppr: Option<f64>,
743    /// The upper bound with 68 % certainty.
744    #[serde(rename = "value_upper_68PPR", skip_serializing_if = "Option::is_none")]
745    pub value_upper_68ppr: Option<f64>,
746    /// The expected power.
747    pub value_expected: f64,
748    /// The lower bound with 68 % certainty.
749    #[serde(rename = "value_lower_68PPR", skip_serializing_if = "Option::is_none")]
750    pub value_lower_68ppr: Option<f64>,
751    /// The lower bound with 95 % certainty.
752    #[serde(rename = "value_lower_95PPR", skip_serializing_if = "Option::is_none")]
753    pub value_lower_95ppr: Option<f64>,
754    /// The lower bound with 100 % certainty.
755    #[serde(skip_serializing_if = "Option::is_none")]
756    pub value_lower_limit: Option<f64>,
757    /// The quantity the values refer to.
758    pub commodity_quantity: CommodityQuantity,
759}
760
761impl PowerForecastValue {
762    /// A forecast with no uncertainty bands.
763    #[must_use]
764    pub const fn expected(value: f64, commodity_quantity: CommodityQuantity) -> Self {
765        Self {
766            value_upper_limit: None,
767            value_upper_95ppr: None,
768            value_upper_68ppr: None,
769            value_expected: value,
770            value_lower_68ppr: None,
771            value_lower_95ppr: None,
772            value_lower_limit: None,
773            commodity_quantity,
774        }
775    }
776
777    /// The bands from the lowest to the highest, skipping those that are absent.
778    ///
779    /// Used by the validator to check that they are ordered.
780    #[must_use]
781    pub fn bands_ascending(&self) -> [(&'static str, Option<f64>); 7] {
782        [
783            ("value_lower_limit", self.value_lower_limit),
784            ("value_lower_95PPR", self.value_lower_95ppr),
785            ("value_lower_68PPR", self.value_lower_68ppr),
786            ("value_expected", Some(self.value_expected)),
787            ("value_upper_68PPR", self.value_upper_68ppr),
788            ("value_upper_95PPR", self.value_upper_95ppr),
789            ("value_upper_limit", self.value_upper_limit),
790        ]
791    }
792}
793
794/// One time slice of a [`PowerForecast`].
795#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
796#[serde(deny_unknown_fields)]
797pub struct PowerForecastElement {
798    /// How long this slice lasts.
799    pub duration: Duration,
800    /// The expected powers, at most one per commodity quantity.
801    pub power_values: Vec<PowerForecastValue>,
802}
803
804/// What a resource does with one commodity.
805#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
806#[serde(deny_unknown_fields)]
807pub struct Role {
808    /// Producer, consumer or storage.
809    pub role: RoleType,
810    /// The commodity the role refers to.
811    pub commodity: Commodity,
812}
813
814impl Role {
815    /// A role.
816    #[must_use]
817    pub const fn new(role: RoleType, commodity: Commodity) -> Self {
818        Self { role, commodity }
819    }
820}
821
822/// A timer that blocks or is started by a [`Transition`].
823#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
824#[serde(deny_unknown_fields)]
825#[builder(on(String, into))]
826pub struct Timer {
827    /// Unique within the system or actuator description that contains it.
828    pub id: Id,
829    /// Human-readable, for debugging only — never for a user interface.
830    #[serde(skip_serializing_if = "Option::is_none")]
831    pub diagnostic_label: Option<String>,
832    /// How long the timer runs once started.
833    pub duration: Duration,
834}
835
836/// A permitted move from one operation mode to another.
837#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
838#[serde(deny_unknown_fields)]
839pub struct Transition {
840    /// Unique within the system or actuator description that contains it.
841    pub id: Id,
842    /// The operation mode being left.
843    pub from: Id,
844    /// The operation mode being entered.
845    pub to: Id,
846    /// Timers that are (re)started when this transition is initiated.
847    pub start_timers: Vec<Id>,
848    /// Timers that block this transition while any of them is unfinished.
849    pub blocking_timers: Vec<Id>,
850    /// Absolute cost of making the transition, in the resource's currency.
851    #[serde(skip_serializing_if = "Option::is_none")]
852    pub transition_costs: Option<f64>,
853    /// Time between initiating the transition and the device behaving according to the
854    /// mode it moves to. Absent means negligible.
855    #[serde(skip_serializing_if = "Option::is_none")]
856    pub transition_duration: Option<Duration>,
857    /// Whether this transition may only be used during an abnormal condition.
858    pub abnormal_condition_only: bool,
859}
860
861impl Transition {
862    /// A transition with no timers, no costs and no duration.
863    #[must_use]
864    pub fn simple(id: Id, from: Id, to: Id) -> Self {
865        Self {
866            id,
867            from,
868            to,
869            start_timers: Vec::new(),
870            blocking_timers: Vec::new(),
871            transition_costs: None,
872            transition_duration: None,
873            abnormal_condition_only: false,
874        }
875    }
876}
877
878// ---------------------------------------------------------------------------
879// Messages
880// ---------------------------------------------------------------------------
881
882/// Announces a node's role and the S2 versions it speaks.
883///
884/// Not used under S2 Connect, where the version is negotiated during session initiation
885/// and `S2C §Communication - JSON messages` says the handshake messages "can not be
886/// sent".
887#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
888#[serde(deny_unknown_fields)]
889pub struct Handshake {
890    /// This message's identifier.
891    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
892    pub message_id: Id,
893    /// The role of the sender.
894    pub role: EnergyManagementRole,
895    /// "Protocol versions supported by the sender of this message. This field is
896    /// mandatory for the RM, but optional for the CEM."
897    #[serde(skip_serializing_if = "Option::is_none")]
898    pub supported_protocol_versions: Option<Vec<ProtocolVersion>>,
899}
900
901/// The CEM's answer to a [`Handshake`]: the version it selected for this session.
902#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
903#[serde(deny_unknown_fields)]
904pub struct HandshakeResponse {
905    /// This message's identifier.
906    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
907    pub message_id: Id,
908    /// The version the CEM chose, which must be one the RM offered.
909    pub selected_protocol_version: ProtocolVersion,
910}
911
912/// Everything static about a resource, and which control types it can be driven in.
913#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
914#[serde(deny_unknown_fields)]
915#[builder(on(String, into))]
916pub struct ResourceManagerDetails {
917    /// This message's identifier.
918    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
919    pub message_id: Id,
920    /// Identifies the resource. Unique within the scope of the CEM.
921    pub resource_id: Id,
922    /// A human-readable name, for user interfaces.
923    #[serde(skip_serializing_if = "Option::is_none")]
924    pub name: Option<String>,
925    /// What the resource does with each commodity. One to three roles.
926    pub roles: Vec<Role>,
927    /// The manufacturer's name.
928    #[serde(skip_serializing_if = "Option::is_none")]
929    pub manufacturer: Option<String>,
930    /// The model name.
931    #[serde(skip_serializing_if = "Option::is_none")]
932    pub model: Option<String>,
933    /// The serial number.
934    #[serde(skip_serializing_if = "Option::is_none")]
935    pub serial_number: Option<String>,
936    /// The firmware version.
937    #[serde(skip_serializing_if = "Option::is_none")]
938    pub firmware_version: Option<String>,
939    /// How long the resource takes, on average, to process and execute an instruction.
940    pub instruction_processing_delay: Duration,
941    /// The control types this Resource Manager supports. The CEM selects one of these.
942    pub available_control_types: Vec<ControlType>,
943    /// The currency every cost is expressed in. Mandatory if any cost is published.
944    #[serde(skip_serializing_if = "Option::is_none")]
945    pub currency: Option<Currency>,
946    /// Whether this Resource Manager can send a [`PowerForecast`].
947    pub provides_forecast: bool,
948    /// Which quantities it can measure. A [`PowerMeasurement`] may only use these.
949    pub provides_power_measurement_types: Vec<CommodityQuantity>,
950}
951
952/// The CEM activating a control type.
953#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
954#[serde(deny_unknown_fields)]
955pub struct SelectControlType {
956    /// This message's identifier.
957    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
958    pub message_id: Id,
959    /// The control type to activate. Must be one the resource offered.
960    pub control_type: ControlType,
961}
962
963/// Either side asking for the session to end or restart.
964#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
965#[serde(deny_unknown_fields)]
966#[builder(on(String, into))]
967pub struct SessionRequest {
968    /// This message's identifier.
969    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
970    pub message_id: Id,
971    /// Reconnect, or terminate.
972    pub request: SessionRequestType,
973    /// Human-readable, for debugging only.
974    #[serde(skip_serializing_if = "Option::is_none")]
975    pub diagnostic_label: Option<String>,
976}
977
978/// The answer every message except this one gets.
979///
980/// Note that `ReceptionStatus` has **no** `message_id` of its own — it names the message
981/// it is about, and is never itself acknowledged.
982#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
983#[serde(deny_unknown_fields)]
984#[builder(on(String, into))]
985pub struct ReceptionStatus {
986    /// The message this status is about.
987    pub subject_message_id: Id,
988    /// How it was processed.
989    pub status: ReceptionStatusValues,
990    /// Human-readable diagnostics. This crate puts the failing rule's identifier here —
991    /// `S2-STATE-001: FRBC.Instruction not allowed in WebSocketConnected` — so that
992    /// errors are greppable across a fleet.
993    #[serde(skip_serializing_if = "Option::is_none")]
994    pub diagnostic_label: Option<String>,
995}
996
997impl ReceptionStatus {
998    /// An `OK` status for `subject`.
999    #[must_use]
1000    pub fn ok(subject: Id) -> Self {
1001        Self {
1002            subject_message_id: subject,
1003            status: ReceptionStatusValues::Ok,
1004            diagnostic_label: None,
1005        }
1006    }
1007
1008    /// A failing status for `subject`, with a diagnostic.
1009    #[must_use]
1010    pub fn error(
1011        subject: Id,
1012        status: ReceptionStatusValues,
1013        diagnostic: impl Into<String>,
1014    ) -> Self {
1015        Self {
1016            subject_message_id: subject,
1017            status,
1018            diagnostic_label: Some(diagnostic.into()),
1019        }
1020    }
1021}
1022
1023/// What the Resource Manager did with an instruction.
1024///
1025/// The second of the two answers an instruction gets: the [`ReceptionStatus`] says the
1026/// message was read, this says what became of it.
1027#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
1028#[serde(deny_unknown_fields)]
1029pub struct InstructionStatusUpdate {
1030    /// This message's identifier.
1031    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
1032    pub message_id: Id,
1033    /// The instruction this is about, as the CEM identified it.
1034    pub instruction_id: Id,
1035    /// The present status.
1036    pub status_type: InstructionStatus,
1037    /// When the status last changed.
1038    pub timestamp: Timestamp,
1039}
1040
1041/// A measurement of the power a resource is exchanging with the grid.
1042#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
1043#[serde(deny_unknown_fields)]
1044pub struct PowerMeasurement {
1045    /// This message's identifier.
1046    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
1047    pub message_id: Id,
1048    /// When the values were measured.
1049    pub measurement_timestamp: Timestamp,
1050    /// The measured powers, at most one per commodity quantity.
1051    pub values: Vec<PowerValue>,
1052}
1053
1054/// What a resource expects to consume or produce over a period.
1055#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
1056#[serde(deny_unknown_fields)]
1057pub struct PowerForecast {
1058    /// This message's identifier.
1059    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
1060    pub message_id: Id,
1061    /// When the forecast starts.
1062    pub start_time: Timestamp,
1063    /// The slices, in chronological order.
1064    pub elements: Vec<PowerForecastElement>,
1065}
1066
1067/// Withdraws an object the sender published earlier.
1068#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
1069#[serde(deny_unknown_fields)]
1070pub struct RevokeObject {
1071    /// This message's identifier.
1072    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
1073    pub message_id: Id,
1074    /// The kind of object being withdrawn.
1075    pub object_type: RevokableObjects,
1076    /// Which one.
1077    pub object_id: Id,
1078}
1079
1080#[cfg(test)]
1081mod tests {
1082    use super::*;
1083
1084    #[test]
1085    fn control_type_wire_spellings_are_the_standards_own() {
1086        // Including the one with a missing `l`, which the Rust name does not inherit.
1087        for (value, wire) in [
1088            (
1089                ControlType::PowerEnvelopeBasedControl,
1090                "\"POWER_ENVELOPE_BASED_CONTROL\"",
1091            ),
1092            (
1093                ControlType::PowerProfileBasedControl,
1094                "\"POWER_PROFILE_BASED_CONTROL\"",
1095            ),
1096            (
1097                ControlType::OperationModeBasedControl,
1098                "\"OPERATION_MODE_BASED_CONTROL\"",
1099            ),
1100            (
1101                ControlType::FillRateBasedControl,
1102                "\"FILL_RATE_BASED_CONTROL\"",
1103            ),
1104            (
1105                ControlType::DemandDrivenBasedControl,
1106                "\"DEMAND_DRIVEN_BASED_CONTROL\"",
1107            ),
1108            (ControlType::NotControllable, "\"NOT_CONTROLABLE\""),
1109            (ControlType::NoSelection, "\"NO_SELECTION\""),
1110        ] {
1111            assert_eq!(serde_json::to_string(&value).unwrap(), wire);
1112            assert_eq!(serde_json::from_str::<ControlType>(wire).unwrap(), value);
1113        }
1114        // The correctly spelled string is not the wire value and must not be accepted.
1115        assert!(serde_json::from_str::<ControlType>("\"NOT_CONTROLLABLE\"").is_err());
1116    }
1117
1118    #[test]
1119    fn commodity_quantity_wire_spellings() {
1120        for (value, wire) in [
1121            (CommodityQuantity::ElectricPowerL1, "\"ELECTRIC.POWER.L1\""),
1122            (
1123                CommodityQuantity::ElectricPower3PhaseSymmetric,
1124                "\"ELECTRIC.POWER.3_PHASE_SYMMETRIC\"",
1125            ),
1126            (
1127                CommodityQuantity::NaturalGasFlowRate,
1128                "\"NATURAL_GAS.FLOW_RATE\"",
1129            ),
1130            (
1131                CommodityQuantity::HeatThermalPower,
1132                "\"HEAT.THERMAL_POWER\"",
1133            ),
1134            (CommodityQuantity::OilFlowRate, "\"OIL.FLOW_RATE\""),
1135        ] {
1136            assert_eq!(serde_json::to_string(&value).unwrap(), wire);
1137            assert_eq!(
1138                serde_json::from_str::<CommodityQuantity>(wire).unwrap(),
1139                value
1140            );
1141        }
1142    }
1143
1144    #[test]
1145    fn revokable_objects_keep_their_dots() {
1146        assert_eq!(
1147            serde_json::to_string(&RevokableObjects::FrbcInstruction).unwrap(),
1148            "\"FRBC.Instruction\""
1149        );
1150        // And the owner table is what makes E6 answerable.
1151        assert_eq!(
1152            RevokableObjects::FrbcInstruction.owner(),
1153            EnergyManagementRole::Cem
1154        );
1155        assert_eq!(
1156            RevokableObjects::FrbcSystemDescription.owner(),
1157            EnergyManagementRole::Rm
1158        );
1159    }
1160
1161    #[test]
1162    fn currency_codes_are_uppercase() {
1163        assert_eq!(serde_json::to_string(&Currency::Eur).unwrap(), "\"EUR\"");
1164        assert_eq!(
1165            serde_json::from_str::<Currency>("\"XXX\"").unwrap(),
1166            Currency::Xxx
1167        );
1168    }
1169
1170    #[test]
1171    fn reception_status_consequences_are_the_normative_ones() {
1172        use Consequence as C;
1173        use ReceptionStatusValues as R;
1174        assert_eq!(R::Ok.consequence(), C::Proceed);
1175        assert_eq!(R::InvalidData.consequence(), C::Ignored);
1176        assert_eq!(R::InvalidMessage.consequence(), C::Ignored);
1177        assert_eq!(R::InvalidContent.consequence(), C::Ignored);
1178        assert_eq!(R::TemporaryError.consequence(), C::Retry);
1179        assert_eq!(R::PermanentError.consequence(), C::Disconnect);
1180    }
1181
1182    #[test]
1183    fn factor_interpolation_matches_the_documented_formula() {
1184        // the S2 documentation, *Operation modes*: a mode from 1000 W to 2500 W at factor 0.5
1185        // is 1750 W.
1186        let r = NumberRange::new(1000.0, 2500.0);
1187        assert!((r.at_factor(0.5) - 1750.0).abs() < 1e-9);
1188        assert!((r.at_factor(0.0) - 1000.0).abs() < 1e-9);
1189        assert!((r.at_factor(1.0) - 2500.0).abs() < 1e-9);
1190        assert!((r.factor_of(1750.0).unwrap() - 0.5).abs() < 1e-9);
1191        // A single-valued range gives the same value for every factor, so the inverse
1192        // has no answer.
1193        assert_eq!(NumberRange::exactly(0.0).factor_of(0.0), None);
1194        assert!((NumberRange::exactly(7.0).at_factor(0.3) - 7.0).abs() < 1e-12);
1195    }
1196
1197    #[test]
1198    fn unknown_fields_are_refused() {
1199        let json = r#"{"start_of_range":0,"end_of_range":1,"extra":true}"#;
1200        assert!(serde_json::from_str::<NumberRange>(json).is_err());
1201    }
1202
1203    #[test]
1204    fn absent_optionals_are_absent_rather_than_null() {
1205        let v = PowerForecastValue::expected(-3450.1, CommodityQuantity::ElectricPowerL1);
1206        let json = serde_json::to_string(&v).unwrap();
1207        assert_eq!(
1208            json,
1209            r#"{"value_expected":-3450.1,"commodity_quantity":"ELECTRIC.POWER.L1"}"#
1210        );
1211    }
1212
1213    #[test]
1214    fn percentile_bands_keep_their_capitalised_wire_names() {
1215        let json = r#"{
1216            "value_upper_limit": -3400.0, "value_upper_95PPR": -3440.0,
1217            "value_upper_68PPR": -3445.0, "value_expected": -3450.1,
1218            "value_lower_68PPR": -3455.0, "value_lower_95PPR": -3460.0,
1219            "value_lower_limit": -3500.0, "commodity_quantity": "ELECTRIC.POWER.L1"
1220        }"#;
1221        let v: PowerForecastValue = serde_json::from_str(json).unwrap();
1222        assert_eq!(v.value_upper_95ppr, Some(-3440.0));
1223        assert_eq!(v.value_lower_68ppr, Some(-3455.0));
1224        let back = serde_json::to_string(&v).unwrap();
1225        assert!(back.contains("\"value_upper_95PPR\":-3440.0"));
1226    }
1227}