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