1use core::fmt;
4use core::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use super::builder::strict_builder;
9use super::text::Text;
10use super::validate::{Validate, Validator, ViolationCode, validate_fields};
11
12#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
24#[non_exhaustive]
25pub enum Code {
26 Success,
28 HubjectSystemError,
30 HubjectDatabaseError,
32 DataTransactionError,
34 UnauthorizedAccess,
40 InconsistentEvseId,
42 InconsistentEvcoId,
44 SystemError,
46 DataError,
48 QrCodeAuthenticationFailed,
50 RfidInvalidUid,
52 RfidCardNotReadable,
54 PlcInvalidEvcoId,
56 NoPositiveAuthenticationResponse,
58 QrCodeAppTimeout,
60 PlcInvalidUnderlyingEvcoId,
63 PlcInvalidCertificate,
65 PlcTimeout,
67 EvcoIdLocked,
69 NoValidContract,
71 PartnerNotFound,
73 PartnerDidNotRespond,
75 ServiceNotAvailable,
77 SessionIsInvalid,
79 CommunicationToEvseFailed,
81 NoEvConnectedToEvse,
83 EvseAlreadyReserved,
85 EvseAlreadyInUse,
87 UnknownEvseId,
89 EvseIdNotHubjectCompatible,
91 EvseOutOfService,
93 Custom(String),
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
99#[non_exhaustive]
100pub enum CodeArea {
101 General,
103 InternalSystem,
105 Authentication,
107 Session,
109 Evse,
111 Unknown,
113}
114
115macro_rules! code_table {
116 ($( $variant:ident = $wire:literal, $area:ident, $text:literal );* $(;)?) => {
117 impl Code {
118 pub const ALL: &'static [Self] = &[ $( Self::$variant ),* ];
120
121 #[must_use]
123 pub fn as_str(&self) -> &str {
124 match self {
125 $( Self::$variant => $wire, )*
126 Self::Custom(s) => s.as_str(),
127 }
128 }
129
130 #[must_use]
132 pub fn description(&self) -> &str {
133 match self {
134 $( Self::$variant => $text, )*
135 Self::Custom(_) => "a status code this version of oicp-kit does not know",
136 }
137 }
138
139 #[must_use]
141 pub fn area(&self) -> CodeArea {
142 match self {
143 $( Self::$variant => CodeArea::$area, )*
144 Self::Custom(_) => CodeArea::Unknown,
145 }
146 }
147
148 #[must_use]
150 pub fn is_known(&self) -> bool {
151 !matches!(self, Self::Custom(_))
152 }
153 }
154
155 impl From<&str> for Code {
156 fn from(s: &str) -> Self {
157 match s {
158 $( $wire => Self::$variant, )*
159 other => Self::Custom(other.to_owned()),
160 }
161 }
162 }
163 };
164}
165
166code_table! {
167 Success = "000", General, "Success";
168 HubjectSystemError = "001", InternalSystem, "Hubject system error";
169 HubjectDatabaseError = "002", InternalSystem, "Hubject database error";
170 DataTransactionError = "009", InternalSystem, "Data transaction error";
171 UnauthorizedAccess = "017", InternalSystem, "Unauthorized Access";
172 InconsistentEvseId = "018", InternalSystem, "Inconsistent EvseID";
173 InconsistentEvcoId = "019", InternalSystem, "Inconsistent EvcoID";
174 SystemError = "021", General, "System error";
175 DataError = "022", General, "Data error";
176 QrCodeAuthenticationFailed = "101", Authentication, "QR Code Authentication failed - Invalid Credentials";
177 RfidInvalidUid = "102", Authentication, "RFID Authentication failed - invalid UID";
178 RfidCardNotReadable = "103", Authentication, "RFID Authentication failed - card not readable";
179 PlcInvalidEvcoId = "105", Authentication, "PLC Authentication failed - invalid EvcoID";
180 NoPositiveAuthenticationResponse = "106", Authentication, "No positive authentication response";
181 QrCodeAppTimeout = "110", Authentication, "QR Code App Authentication failed - time out error";
182 PlcInvalidUnderlyingEvcoId = "120", Authentication, "PLC (ISO/IEC 15118) Authentication failed - invalid underlying EvcoID";
183 PlcInvalidCertificate = "121", Authentication, "PLC (ISO/IEC 15118) Authentication failed - invalid certificate";
184 PlcTimeout = "122", Authentication, "PLC (ISO/IEC 15118) Authentication failed - time out error";
185 EvcoIdLocked = "200", Authentication, "EvcoID locked";
186 NoValidContract = "210", Session, "No valid contract";
187 PartnerNotFound = "300", Session, "Partner not found";
188 PartnerDidNotRespond = "310", Session, "Partner did not respond";
189 ServiceNotAvailable = "320", Session, "Service not available";
190 SessionIsInvalid = "400", Session, "Session is invalid";
191 CommunicationToEvseFailed = "501", Evse, "Communication to EVSE failed";
192 NoEvConnectedToEvse = "510", Evse, "No EV connected to EVSE";
193 EvseAlreadyReserved = "601", Evse, "EVSE already reserved";
194 EvseAlreadyInUse = "602", Evse, "EVSE already in use/ wrong token";
195 UnknownEvseId = "603", Evse, "Unknown EVSE ID";
196 EvseIdNotHubjectCompatible = "604", Evse, "EVSE ID is not Hubject compatible";
197 EvseOutOfService = "700", Evse, "EVSE out of service";
198}
199
200impl Code {
201 #[must_use]
203 pub fn is_success(&self) -> bool {
204 matches!(self, Self::Success)
205 }
206
207 #[must_use]
216 pub fn is_retryable(&self) -> bool {
217 matches!(
218 self,
219 Self::HubjectSystemError
220 | Self::HubjectDatabaseError
221 | Self::DataTransactionError
222 | Self::SystemError
223 | Self::PartnerDidNotRespond
224 | Self::ServiceNotAvailable
225 )
226 }
227
228 #[must_use]
233 pub fn is_authorization_failure(&self) -> bool {
234 self.area() == CodeArea::Authentication || matches!(self, Self::NoValidContract)
235 }
236
237 #[must_use]
239 pub fn is_evse_problem(&self) -> bool {
240 self.area() == CodeArea::Evse
241 }
242}
243
244impl fmt::Display for Code {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 write!(f, "{} {}", self.as_str(), self.description())
247 }
248}
249
250impl FromStr for Code {
251 type Err = core::convert::Infallible;
252 fn from_str(s: &str) -> Result<Self, Self::Err> {
253 Ok(Self::from(s))
254 }
255}
256
257impl Serialize for Code {
258 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
259 s.serialize_str(self.as_str())
260 }
261}
262
263impl<'de> Deserialize<'de> for Code {
264 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
265 struct V;
266 impl serde::de::Visitor<'_> for V {
267 type Value = Code;
268 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 f.write_str("an OICP status code")
270 }
271 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Code, E> {
272 Ok(Code::from(v))
273 }
274 fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Code, E> {
277 Ok(Code::from(format!("{v:03}").as_str()))
278 }
279 fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Code, E> {
280 Ok(Code::from(format!("{v:03}").as_str()))
281 }
282 }
283 d.deserialize_any(V)
284 }
285}
286
287#[cfg(feature = "schema")]
288impl schemars::JsonSchema for Code {
289 fn schema_name() -> std::borrow::Cow<'static, str> {
290 "StatusCodeValue".into()
291 }
292 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
293 schemars::json_schema!({ "type": "string", "pattern": "^[0-9]{3}$" })
294 }
295}
296
297#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
305#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
306#[builder(finish_fn = build_unchecked)]
307pub struct StatusCode {
308 #[serde(rename = "Code")]
310 pub code: Code,
311 #[serde(rename = "Description", default, skip_serializing_if = "Option::is_none")]
313 #[builder(into)]
314 pub description: Option<Text<200>>,
315 #[serde(rename = "AdditionalInfo", default, skip_serializing_if = "Option::is_none")]
317 #[builder(into)]
318 pub additional_info: Option<Text<1000>>,
319}
320
321impl StatusCode {
322 #[must_use]
324 pub fn new(code: Code) -> Self {
325 let description = Text::new(code.description()).ok();
326 Self { code, description, additional_info: None }
327 }
328
329 #[must_use]
331 pub fn success() -> Self {
332 Self::new(Code::Success)
333 }
334
335 #[must_use]
337 pub fn with_info(code: Code, additional_info: impl Into<String>) -> Self {
338 Self { additional_info: Text::new_unchecked(additional_info).into(), ..Self::new(code) }
339 }
340
341 #[must_use]
343 pub fn is_success(&self) -> bool {
344 self.code.is_success()
345 }
346}
347
348impl fmt::Display for StatusCode {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 write!(f, "{}", self.code)?;
351 if let Some(info) = &self.additional_info {
352 write!(f, " ({info})")?;
353 }
354 Ok(())
355 }
356}
357
358impl Validate for StatusCode {
359 fn validate_in(&self, v: &mut Validator) {
360 if let Code::Custom(value) = &self.code {
361 v.report_at(
362 "Code",
363 ViolationCode::PatternMismatch,
364 format!("{value:?} is not one of the {} status codes OICP 2.3 defines", Code::ALL.len()),
365 );
366 }
367 validate_fields!(self, v, description as "Description", additional_info as "AdditionalInfo");
368 }
369}
370
371impl From<Code> for StatusCode {
372 fn from(code: Code) -> Self {
373 Self::new(code)
374 }
375}
376
377strict_builder!(StatusCode, StatusCodeBuilder, status_code_builder);
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 #[test]
385 fn every_code_in_the_spec_table_round_trips() {
386 for code in Code::ALL {
387 let json = serde_json::to_string(code).unwrap();
388 let back: Code = serde_json::from_str(&json).unwrap();
389 assert_eq!(*code, back);
390 assert_eq!(code.as_str().len(), 3);
391 }
392 assert_eq!(Code::ALL.len(), 31);
393 }
394
395 #[test]
396 fn an_unknown_code_is_preserved_not_dropped() {
397 let code: Code = serde_json::from_str(r#""999""#).unwrap();
398 assert!(!code.is_known());
399 assert_eq!(code.as_str(), "999");
400 assert_eq!(serde_json::to_string(&code).unwrap(), r#""999""#);
401 }
402
403 #[test]
404 fn a_code_sent_as_a_number_is_understood() {
405 let code: Code = serde_json::from_str("0").unwrap();
406 assert_eq!(code, Code::Success);
407 assert_eq!(serde_json::to_string(&code).unwrap(), r#""000""#);
409 }
410
411 #[test]
412 fn retry_semantics_come_from_the_table_not_from_guesswork() {
413 assert!(Code::HubjectSystemError.is_retryable());
415 assert!(Code::PartnerDidNotRespond.is_retryable());
416 assert!(Code::ServiceNotAvailable.is_retryable());
417 assert!(!Code::NoValidContract.is_retryable());
419 assert!(!Code::EvseAlreadyReserved.is_retryable());
420 assert!(!Code::UnauthorizedAccess.is_retryable());
421 assert!(!Code::Success.is_retryable());
422 }
423
424 #[test]
425 fn authorization_failures_are_classified_as_such() {
426 assert!(Code::RfidInvalidUid.is_authorization_failure());
427 assert!(Code::EvcoIdLocked.is_authorization_failure());
428 assert!(Code::NoValidContract.is_authorization_failure());
429 assert!(!Code::EvseOutOfService.is_authorization_failure());
430 assert!(Code::EvseOutOfService.is_evse_problem());
431 }
432
433 #[test]
434 fn a_status_carries_the_specs_own_description_by_default() {
435 let status = StatusCode::new(Code::UnknownEvseId);
436 assert_eq!(status.description.as_ref().unwrap().as_str(), "Unknown EVSE ID");
437 assert!(status.validate().is_ok());
438 }
439}