1use alloc::vec::Vec;
4use core::fmt;
5use core::str::FromStr;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
11#[non_exhaustive]
12pub enum Version {
13 V1_6,
15 V2_0_1,
17 V2_1,
19}
20
21impl Version {
22 pub const ALL: &'static [Version] = &[Version::V1_6, Version::V2_0_1, Version::V2_1];
24
25 #[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 #[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 #[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 #[must_use]
60 pub const fn has_extended_message_types(self) -> bool {
61 matches!(self, Version::V2_1)
62 }
63
64 #[must_use]
68 pub const fn has_rpc_framework_error(self) -> bool {
69 !matches!(self, Version::V1_6)
70 }
71
72 #[must_use]
75 pub const fn uses_unreadable_message_id(self) -> bool {
76 !matches!(self, Version::V1_6)
77 }
78
79 #[must_use]
82 pub const fn strict_synchronicity(self) -> bool {
83 !matches!(self, Version::V1_6)
84 }
85
86 #[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#[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#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct Subprotocol {
138 offered: Vec<Version>,
139}
140
141impl Subprotocol {
142 #[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 #[must_use]
156 pub fn offered(&self) -> &[Version] {
157 &self.offered
158 }
159
160 #[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 #[must_use]
176 pub fn select(&self, supported: &[Version]) -> Option<Version> {
177 self.offered.iter().copied().find(|v| supported.contains(v))
178 }
179
180 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 fn default() -> Self {
201 Self::new([Version::V2_1, Version::V2_0_1, Version::V1_6])
202 }
203}
204
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207#[non_exhaustive]
208pub enum NegotiationError {
209 NoSubprotocol,
212 UnsupportedSubprotocol,
214 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}