Skip to main content

ocpp_kit/
version.rs

1//! OCPP protocol versions and WebSocket subprotocol negotiation.
2
3use alloc::vec::Vec;
4use core::fmt;
5use core::str::FromStr;
6
7/// A supported OCPP version.
8///
9/// The ordering is oldest → newest, so `max()` picks the most capable version.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
11#[non_exhaustive]
12pub enum Version {
13    /// OCPP 1.6J (edition 2 + errata, plus the Security Whitepaper edition 2 extensions).
14    V1_6,
15    /// OCPP 2.0.1.
16    V2_0_1,
17    /// OCPP 2.1.
18    V2_1,
19}
20
21impl Version {
22    /// Every version this crate implements, oldest first.
23    pub const ALL: &'static [Version] = &[Version::V1_6, Version::V2_0_1, Version::V2_1];
24
25    /// The WebSocket subprotocol token, e.g. `ocpp2.1` (Part 4 §3.1.2).
26    #[must_use]
27    pub const fn subprotocol(self) -> &'static str {
28        match self {
29            Version::V1_6 => "ocpp1.6",
30            Version::V2_0_1 => "ocpp2.0.1",
31            Version::V2_1 => "ocpp2.1",
32        }
33    }
34
35    /// A short, filesystem-safe identifier: `v1_6`, `v2_0_1`, `v2_1`.
36    ///
37    /// Used for schema directories, metric labels and log fields.
38    #[must_use]
39    pub const fn slug(self) -> &'static str {
40        match self {
41            Version::V1_6 => "v1_6",
42            Version::V2_0_1 => "v2_0_1",
43            Version::V2_1 => "v2_1",
44        }
45    }
46
47    /// Parses a WebSocket subprotocol token.
48    #[must_use]
49    pub fn from_subprotocol(token: &str) -> Option<Self> {
50        match token.trim() {
51            "ocpp1.6" => Some(Version::V1_6),
52            "ocpp2.0.1" => Some(Version::V2_0_1),
53            "ocpp2.1" => Some(Version::V2_1),
54            _ => None,
55        }
56    }
57
58    /// Whether this version has `CALLRESULTERROR` (5) and `SEND` (6).
59    #[must_use]
60    pub const fn has_extended_message_types(self) -> bool {
61        matches!(self, Version::V2_1)
62    }
63
64    /// Whether this version defines the `RpcFrameworkError` error code.
65    ///
66    /// 1.6J does not; framing failures are reported as `GenericError` there.
67    #[must_use]
68    pub const fn has_rpc_framework_error(self) -> bool {
69        !matches!(self, Version::V1_6)
70    }
71
72    /// Whether an unreadable `MessageId` must be answered with the literal id `"-1"`
73    /// (2.x Part 4 §4.1.1). 1.6J has no such rule.
74    #[must_use]
75    pub const fn uses_unreadable_message_id(self) -> bool {
76        !matches!(self, Version::V1_6)
77    }
78
79    /// Whether the one-outstanding-`CALL` rule is a `SHALL NOT` (2.x, Part 4 §4.1.1) rather
80    /// than 1.6J's `SHOULD NOT`.
81    #[must_use]
82    pub const fn strict_synchronicity(self) -> bool {
83        !matches!(self, Version::V1_6)
84    }
85
86    /// Whether RFC 7692 `permessage-deflate` is part of the specification.
87    ///
88    /// 2.1 Part 4 §3.4 Table 2: the CSMS and a Local Controller **SHALL** support it; a
89    /// Charging Station **MAY**. 1.6J §5.1 recommends no compression, and 2.0.1 is silent.
90    #[must_use]
91    pub const fn supports_compression(self) -> bool {
92        matches!(self, Version::V2_1)
93    }
94}
95
96impl fmt::Display for Version {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.write_str(match self {
99            Version::V1_6 => "1.6",
100            Version::V2_0_1 => "2.0.1",
101            Version::V2_1 => "2.1",
102        })
103    }
104}
105
106impl FromStr for Version {
107    type Err = UnknownVersion;
108
109    fn from_str(value: &str) -> Result<Self, Self::Err> {
110        match value.trim() {
111            "1.6" | "1.6J" | "1.6j" | "ocpp1.6" => Ok(Version::V1_6),
112            "2.0.1" | "ocpp2.0.1" => Ok(Version::V2_0_1),
113            "2.1" | "ocpp2.1" => Ok(Version::V2_1),
114            _ => Err(UnknownVersion),
115        }
116    }
117}
118
119/// A version string this crate does not recognise.
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub struct UnknownVersion;
122
123impl fmt::Display for UnknownVersion {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str("unknown OCPP version")
126    }
127}
128
129#[cfg(feature = "std")]
130impl std::error::Error for UnknownVersion {}
131
132/// The `Sec-WebSocket-Protocol` value a client offers, in preference order.
133///
134/// OCPP 2.1 Part 4 §3.2 recommends that a 2.1 peer also offer 2.0.1, so a station can talk
135/// to a CSMS that has not migrated yet.
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct Subprotocol {
138    offered: Vec<Version>,
139}
140
141impl Subprotocol {
142    /// Offers the given versions, most preferred first. Duplicates are removed.
143    #[must_use]
144    pub fn new(versions: impl IntoIterator<Item = Version>) -> Self {
145        let mut offered = Vec::new();
146        for version in versions {
147            if !offered.contains(&version) {
148                offered.push(version);
149            }
150        }
151        Self { offered }
152    }
153
154    /// The versions offered, most preferred first.
155    #[must_use]
156    pub fn offered(&self) -> &[Version] {
157        &self.offered
158    }
159
160    /// The `Sec-WebSocket-Protocol` header value.
161    #[must_use]
162    pub fn header_value(&self) -> alloc::string::String {
163        let mut out = alloc::string::String::new();
164        for (index, version) in self.offered.iter().enumerate() {
165            if index > 0 {
166                out.push_str(", ");
167            }
168            out.push_str(version.subprotocol());
169        }
170        out
171    }
172
173    /// Picks the version a server should select: the first *client* preference that the
174    /// server also supports (Part 4 §3.1.2 — the server selects exactly one).
175    #[must_use]
176    pub fn select(&self, supported: &[Version]) -> Option<Version> {
177        self.offered.iter().copied().find(|v| supported.contains(v))
178    }
179
180    /// Validates a server's selection against what was offered.
181    ///
182    /// Part 4 §3.1.2: the server must echo exactly one of the offered subprotocols. A server
183    /// that answers with something else, or with nothing, is a negotiation failure.
184    pub fn accept(&self, selected: Option<&str>) -> Result<Version, NegotiationError> {
185        let Some(token) = selected else {
186            return Err(NegotiationError::NoSubprotocol);
187        };
188        let version =
189            Version::from_subprotocol(token).ok_or(NegotiationError::UnsupportedSubprotocol)?;
190        if self.offered.contains(&version) {
191            Ok(version)
192        } else {
193            Err(NegotiationError::NotOffered(version))
194        }
195    }
196}
197
198impl Default for Subprotocol {
199    /// Offers every version this crate implements, newest first.
200    fn default() -> Self {
201        Self::new([Version::V2_1, Version::V2_0_1, Version::V1_6])
202    }
203}
204
205/// Why subprotocol negotiation failed.
206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207#[non_exhaustive]
208pub enum NegotiationError {
209    /// The server did not send `Sec-WebSocket-Protocol`. Part 4 §3.1.2 requires it; the
210    /// connection must be closed.
211    NoSubprotocol,
212    /// The server selected a subprotocol that is not an OCPP one.
213    UnsupportedSubprotocol,
214    /// The server selected a version the client did not offer.
215    NotOffered(Version),
216}
217
218impl fmt::Display for NegotiationError {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        match self {
221            NegotiationError::NoSubprotocol => {
222                f.write_str("server did not select a WebSocket subprotocol (Part 4 §3.1.2)")
223            }
224            NegotiationError::UnsupportedSubprotocol => {
225                f.write_str("server selected a subprotocol that is not OCPP")
226            }
227            NegotiationError::NotOffered(version) => {
228                write!(f, "server selected OCPP {version}, which was not offered")
229            }
230        }
231    }
232}
233
234#[cfg(feature = "std")]
235impl std::error::Error for NegotiationError {}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn negotiation_follows_client_preference() {
243        let offer = Subprotocol::new([Version::V2_1, Version::V2_0_1, Version::V1_6]);
244        assert_eq!(offer.header_value(), "ocpp2.1, ocpp2.0.1, ocpp1.6");
245        assert_eq!(
246            offer.select(&[Version::V1_6, Version::V2_0_1]),
247            Some(Version::V2_0_1)
248        );
249        assert_eq!(offer.accept(Some("ocpp2.0.1")), Ok(Version::V2_0_1));
250        assert_eq!(offer.accept(None), Err(NegotiationError::NoSubprotocol));
251        assert_eq!(
252            offer.accept(Some("mqtt")),
253            Err(NegotiationError::UnsupportedSubprotocol)
254        );
255
256        let narrow = Subprotocol::new([Version::V1_6]);
257        assert_eq!(
258            narrow.accept(Some("ocpp2.1")),
259            Err(NegotiationError::NotOffered(Version::V2_1))
260        );
261    }
262}