Skip to main content

ocmf/payload/
tables.rs

1//! The closed value sets of the specification, one type per table.
2//!
3//! Every one of these carries an escape variant for a value the tables do not
4//! define. That is not laxity: a station that writes an unknown meter state has
5//! written *something*, and the only safe reading of "something" is "not
6//! `OK`". Throwing the record away instead would lose the evidence; mapping the
7//! unknown value onto a known one would invent it. So the unknown value is kept
8//! verbatim, and every predicate that could authorise money answers `false` for
9//! it.
10
11use alloc::borrow::Cow;
12use core::fmt;
13
14use crate::json::RawStr;
15
16/// Matches a table value against the string's **decoded** form, keeping the
17/// borrowed source text for the escape variant.
18///
19/// `"\u006bWh"` is a lawful spelling of `"kWh"` and must match the table; a
20/// value the table does not define must survive verbatim. Two different
21/// strings, and this is the one place both are in hand.
22fn decoded_or_raw<'a, T>(
23    decoded: &str,
24    raw: &'a str,
25    table: impl Fn(&str) -> Option<T>,
26    other: fn(&'a str) -> T,
27) -> T {
28    table(decoded).unwrap_or_else(|| other(raw))
29}
30
31/// State of the meter at the moment of a reading `[OCMF Tab. 10]`.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum MeterState {
35    /// `N` — meter not present or not found.
36    NotPresent,
37    /// `G` — working correctly (Good). The only state that is not a fault.
38    Ok,
39    /// `T` — timeout controlling the meter.
40    Timeout,
41    /// `D` — meter was disconnected from the signature component.
42    Disconnected,
43    /// `R` — meter no longer found, having been found before (Removed).
44    NotFound,
45    /// `M` — manipulation detected.
46    Manipulated,
47    /// `X` — meter exchanged; the serial no longer matches.
48    Exchanged,
49    /// `I` — meter or its API incompatible with the signature component.
50    Incompatible,
51    /// `O` — read value outside the value range.
52    OutOfRange,
53    /// `S` — a substitute value was formed.
54    Substitute,
55    /// `E` — other, unknown error.
56    OtherError,
57    /// `F` — register not read correctly; the value is not valid.
58    ReadError,
59    /// A letter `[OCMF Tab. 10]` does not define. Never [`Self::is_ok`].
60    Undefined(char),
61}
62
63impl MeterState {
64    /// Parses the single-letter code.
65    #[must_use]
66    pub fn parse(s: &str) -> Self {
67        let mut chars = s.chars();
68        match (chars.next(), chars.next()) {
69            (Some(c), None) => match c {
70                'N' => Self::NotPresent,
71                'G' => Self::Ok,
72                'T' => Self::Timeout,
73                'D' => Self::Disconnected,
74                'R' => Self::NotFound,
75                'M' => Self::Manipulated,
76                'X' => Self::Exchanged,
77                'I' => Self::Incompatible,
78                'O' => Self::OutOfRange,
79                'S' => Self::Substitute,
80                'E' => Self::OtherError,
81                'F' => Self::ReadError,
82                other => Self::Undefined(other),
83            },
84            _ => Self::Undefined('?'),
85        }
86    }
87
88    /// Whether `[OCMF Tab. 10]` defines this letter.
89    #[must_use]
90    pub const fn is_defined(self) -> bool {
91        !matches!(self, Self::Undefined(_))
92    }
93
94    /// The letter as written in `ST`.
95    #[must_use]
96    pub const fn letter(self) -> char {
97        match self {
98            Self::NotPresent => 'N',
99            Self::Ok => 'G',
100            Self::Timeout => 'T',
101            Self::Disconnected => 'D',
102            Self::NotFound => 'R',
103            Self::Manipulated => 'M',
104            Self::Exchanged => 'X',
105            Self::Incompatible => 'I',
106            Self::OutOfRange => 'O',
107            Self::Substitute => 'S',
108            Self::OtherError => 'E',
109            Self::ReadError => 'F',
110            Self::Undefined(c) => c,
111        }
112    }
113
114    /// Whether the meter was working correctly.
115    ///
116    /// The reference verifier refuses a transaction whose start or stop reading
117    /// is in any other state, and so should anything that bills.
118    #[must_use]
119    pub const fn is_ok(self) -> bool {
120        matches!(self, Self::Ok)
121    }
122
123    /// A human-readable identifier, as `[OCMF Tab. 10]` names it.
124    #[must_use]
125    pub const fn identifier(self) -> &'static str {
126        match self {
127            Self::NotPresent => "NOT_PRESENT",
128            Self::Ok => "OK",
129            Self::Timeout => "TIMEOUT",
130            Self::Disconnected => "DISCONNECTED",
131            Self::NotFound => "NOT_FOUND",
132            Self::Manipulated => "MANIPULATED",
133            Self::Exchanged => "EXCHANGED",
134            Self::Incompatible => "INCOMPATIBLE",
135            Self::OutOfRange => "OUT_OF_RANGE",
136            Self::Substitute => "SUBSTITUTE",
137            Self::OtherError => "OTHER_ERROR",
138            Self::ReadError => "READ_ERROR",
139            Self::Undefined(_) => "UNDEFINED",
140        }
141    }
142}
143
144#[cfg(feature = "serde")]
145impl serde::Serialize for MeterState {
146    /// The letter, as `ST` writes it — a stable one-character string rather
147    /// than a variant name a refactor could rename out from under a consumer.
148    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
149        s.serialize_str(&alloc::string::String::from(self.letter()))
150    }
151}
152
153impl fmt::Display for MeterState {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        write!(f, "{}", self.letter())
156    }
157}
158
159/// Why a reading was taken, and where it sits in a transaction
160/// `[OCMF Tab. 7, TX]`.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162#[non_exhaustive]
163pub enum TransactionMarker {
164    /// `B` — begin of transaction.
165    Begin,
166    /// `C` — charging (optional intermediate).
167    Charging,
168    /// `X` — exception: time and/or energy are unusable from here on.
169    Exception,
170    /// `E` — end of transaction.
171    End,
172    /// `L` — ended locally.
173    EndedLocally,
174    /// `R` — ended remotely.
175    EndedRemotely,
176    /// `A` — aborted by an error.
177    Aborted,
178    /// `P` — ended by a power failure.
179    PowerFailure,
180    /// `S` — suspended: transaction active, not charging.
181    Suspended,
182    /// `T` — tariff change.
183    TariffChange,
184    /// A letter the table does not define. Neither a begin nor an end.
185    Undefined(char),
186}
187
188impl TransactionMarker {
189    /// Parses the single-letter code.
190    #[must_use]
191    pub fn parse(s: &str) -> Self {
192        let mut chars = s.chars();
193        match (chars.next(), chars.next()) {
194            (Some(c), None) => match c {
195                'B' => Self::Begin,
196                'C' => Self::Charging,
197                'X' => Self::Exception,
198                'E' => Self::End,
199                'L' => Self::EndedLocally,
200                'R' => Self::EndedRemotely,
201                'A' => Self::Aborted,
202                'P' => Self::PowerFailure,
203                'S' => Self::Suspended,
204                'T' => Self::TariffChange,
205                other => Self::Undefined(other),
206            },
207            _ => Self::Undefined('?'),
208        }
209    }
210
211    /// Whether `[OCMF Tab. 7]` defines this letter.
212    #[must_use]
213    pub const fn is_defined(self) -> bool {
214        !matches!(self, Self::Undefined(_))
215    }
216
217    /// The letter as written in `TX`.
218    #[must_use]
219    pub const fn letter(self) -> char {
220        match self {
221            Self::Begin => 'B',
222            Self::Charging => 'C',
223            Self::Exception => 'X',
224            Self::End => 'E',
225            Self::EndedLocally => 'L',
226            Self::EndedRemotely => 'R',
227            Self::Aborted => 'A',
228            Self::PowerFailure => 'P',
229            Self::Suspended => 'S',
230            Self::TariffChange => 'T',
231            Self::Undefined(c) => c,
232        }
233    }
234
235    /// Whether this marks the start of a transaction.
236    #[must_use]
237    pub const fn is_begin(self) -> bool {
238        matches!(self, Self::Begin)
239    }
240
241    /// Whether this marks the end of a transaction, in any of its five
242    /// spellings.
243    #[must_use]
244    pub const fn is_end(self) -> bool {
245        matches!(
246            self,
247            Self::End
248                | Self::EndedLocally
249                | Self::EndedRemotely
250                | Self::Aborted
251                | Self::PowerFailure
252        )
253    }
254
255    /// Whether the transaction ended in a way that makes the readings after it
256    /// suspect: an abort, a power failure, or an exception.
257    #[must_use]
258    pub const fn is_fault(self) -> bool {
259        matches!(self, Self::Aborted | Self::PowerFailure | Self::Exception)
260    }
261}
262
263#[cfg(feature = "serde")]
264impl serde::Serialize for TransactionMarker {
265    /// The letter, as `TX` writes it.
266    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
267        s.serialize_str(&alloc::string::String::from(self.letter()))
268    }
269}
270
271impl fmt::Display for TransactionMarker {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        write!(f, "{}", self.letter())
274    }
275}
276
277/// Which quantities an error has made unusable for billing
278/// `[OCMF Tab. 7, EF]`.
279///
280/// Carrying the value matters twice over. An undefined flag character is still
281/// a statement that *something* is wrong, and this type refuses to lose it; and
282/// the value is the **decoded** one, because `"\u0045"` is a lawful JSON
283/// spelling of `"E"` and a reader that compared source bytes would report a
284/// station's own energy fault as an unknown flag character.
285#[derive(Debug, Clone, PartialEq, Eq, Default)]
286pub struct ErrorFlags<'a> {
287    raw: Cow<'a, str>,
288}
289
290impl<'a> ErrorFlags<'a> {
291    /// Reads the flag string.
292    #[must_use]
293    pub const fn new(raw: Cow<'a, str>) -> Self {
294        Self { raw }
295    }
296
297    /// Reads a flag string that is already plain text.
298    #[must_use]
299    pub const fn borrowed(raw: &'a str) -> Self {
300        Self {
301            raw: Cow::Borrowed(raw),
302        }
303    }
304
305    /// The flags as the record means them, escapes resolved.
306    #[must_use]
307    pub fn as_str(&self) -> &str {
308        &self.raw
309    }
310
311    /// `E` — energy is no longer usable for billing.
312    #[must_use]
313    pub fn energy_unusable(&self) -> bool {
314        self.raw.contains('E')
315    }
316
317    /// `t` — time is no longer usable for billing.
318    #[must_use]
319    pub fn time_unusable(&self) -> bool {
320        self.raw.contains('t')
321    }
322
323    /// Whether any flag at all is set, including one the table does not define.
324    #[must_use]
325    pub fn any(&self) -> bool {
326        !self.raw.is_empty()
327    }
328
329    /// Flag characters outside `[OCMF Tab. 7]`'s `E` and `t`.
330    pub fn undefined(&self) -> impl Iterator<Item = char> + '_ {
331        self.raw.chars().filter(|c| !matches!(c, 'E' | 't'))
332    }
333}
334
335impl fmt::Display for ErrorFlags<'_> {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        f.write_str(&self.raw)
338    }
339}
340
341/// Unit of a reading `[OCMF Tab. 20]`.
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
343#[non_exhaustive]
344pub enum Unit<'a> {
345    /// `kWh`.
346    KWh,
347    /// `Wh`.
348    Wh,
349    /// `mOhm` — cable resistance, not energy.
350    MilliOhm,
351    /// `uOhm` — cable resistance, not energy.
352    MicroOhm,
353    /// A unit the table does not define, kept verbatim.
354    Other(&'a str),
355}
356
357impl<'a> Unit<'a> {
358    /// Reads a unit.
359    #[must_use]
360    pub const fn parse(s: &'a str) -> Self {
361        // `match` on strings is not const; a small chain is.
362        if str_eq(s, "kWh") {
363            Self::KWh
364        } else if str_eq(s, "Wh") {
365            Self::Wh
366        } else if str_eq(s, "mOhm") {
367            Self::MilliOhm
368        } else if str_eq(s, "uOhm") {
369            Self::MicroOhm
370        } else {
371            Self::Other(s)
372        }
373    }
374
375    /// Reads a unit from a JSON string, matching the table on its decoded
376    /// value.
377    #[must_use]
378    pub fn parse_decoded(s: &RawStr<'a>) -> Self {
379        Self::from_parts(&s.decode(), s.as_raw())
380    }
381
382    /// Reads a value whose decoded form and source text are already in hand.
383    ///
384    /// The two differ when the source used a `\uXXXX` escape, and — for a
385    /// field a real record wrote as a JSON *number* — when there was no string
386    /// to decode at all.
387    #[must_use]
388    pub fn from_parts(decoded: &str, raw: &'a str) -> Self {
389        decoded_or_raw(
390            decoded,
391            raw,
392            |d| match d {
393                "kWh" => Some(Self::KWh),
394                "Wh" => Some(Self::Wh),
395                "mOhm" => Some(Self::MilliOhm),
396                "uOhm" => Some(Self::MicroOhm),
397                _ => None,
398            },
399            Self::Other,
400        )
401    }
402
403    /// Whether `[OCMF Tab. 20]` defines this unit.
404    #[must_use]
405    pub const fn is_defined(&self) -> bool {
406        !matches!(self, Self::Other(_))
407    }
408
409    /// The unit as written.
410    #[must_use]
411    pub const fn as_str(&self) -> &'a str {
412        match self {
413            Self::KWh => "kWh",
414            Self::Wh => "Wh",
415            Self::MilliOhm => "mOhm",
416            Self::MicroOhm => "uOhm",
417            Self::Other(s) => s,
418        }
419    }
420
421    /// Whether this unit measures energy — the question a bill asks.
422    ///
423    /// `false` for an unknown unit: a quantity whose unit is not understood is
424    /// not energy, whatever else it might be.
425    #[must_use]
426    pub const fn is_energy(&self) -> bool {
427        matches!(self, Self::KWh | Self::Wh)
428    }
429
430    /// Watt-hours per unit, for converting between `kWh` and `Wh` exactly.
431    #[must_use]
432    pub const fn watt_hours_scale(&self) -> Option<u32> {
433        match self {
434            Self::KWh => Some(1000),
435            Self::Wh => Some(1),
436            _ => None,
437        }
438    }
439}
440
441const fn str_eq(a: &str, b: &str) -> bool {
442    let (a, b) = (a.as_bytes(), b.as_bytes());
443    if a.len() != b.len() {
444        return false;
445    }
446    let mut i = 0;
447    while i < a.len() {
448        if a[i] != b[i] {
449            return false;
450        }
451        i += 1;
452    }
453    true
454}
455
456impl fmt::Display for Unit<'_> {
457    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458        f.write_str(self.as_str())
459    }
460}
461
462/// Kind of current measured `[OCMF Tab. 21]`.
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
464#[non_exhaustive]
465pub enum CurrentType<'a> {
466    /// `AC`.
467    Ac,
468    /// `DC`.
469    Dc,
470    /// Something else, kept verbatim.
471    Other(&'a str),
472}
473
474impl<'a> CurrentType<'a> {
475    /// Reads a current type.
476    #[must_use]
477    pub const fn parse(s: &'a str) -> Self {
478        if str_eq(s, "AC") {
479            Self::Ac
480        } else if str_eq(s, "DC") {
481            Self::Dc
482        } else {
483            Self::Other(s)
484        }
485    }
486
487    /// Reads a current type from a JSON string, matching the table on its
488    /// decoded value.
489    #[must_use]
490    pub fn parse_decoded(s: &RawStr<'a>) -> Self {
491        Self::from_parts(&s.decode(), s.as_raw())
492    }
493
494    /// Reads a value whose decoded form and source text are already in hand.
495    ///
496    /// The two differ when the source used a `\uXXXX` escape, and — for a
497    /// field a real record wrote as a JSON *number* — when there was no string
498    /// to decode at all.
499    #[must_use]
500    pub fn from_parts(decoded: &str, raw: &'a str) -> Self {
501        decoded_or_raw(
502            decoded,
503            raw,
504            |d| match d {
505                "AC" => Some(Self::Ac),
506                "DC" => Some(Self::Dc),
507                _ => None,
508            },
509            Self::Other,
510        )
511    }
512
513    /// Whether `[OCMF Tab. 21]` defines this value.
514    #[must_use]
515    pub const fn is_defined(&self) -> bool {
516        !matches!(self, Self::Other(_))
517    }
518
519    /// The value as written.
520    #[must_use]
521    pub const fn as_str(&self) -> &'a str {
522        match self {
523            Self::Ac => "AC",
524            Self::Dc => "DC",
525            Self::Other(s) => s,
526        }
527    }
528}
529
530impl fmt::Display for CurrentType<'_> {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        f.write_str(self.as_str())
533    }
534}
535
536/// Overall status of the user assignment `[OCMF Tab. 11]`.
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
538#[non_exhaustive]
539pub enum IdentificationLevel<'a> {
540    /// `NONE` — no user assignment; the other user fields mean nothing.
541    None,
542    /// `HEARSAY` — unsecured, e.g. a plain RFID UID.
543    Hearsay,
544    /// `TRUSTED` — trustworthy but not absolutely reliable, e.g. backend
545    /// authorisation.
546    Trusted,
547    /// `VERIFIED` — verified by the signature component and special measures.
548    Verified,
549    /// `CERTIFIED` — verified by a cryptographic signature certifying the
550    /// assignment.
551    Certified,
552    /// `SECURE` — established by a secure feature, e.g. Plug & Charge.
553    Secure,
554    /// `MISMATCH` — error: UIDs do not match.
555    Mismatch,
556    /// `INVALID` — error: certificate check negative.
557    Invalid,
558    /// `OUTDATED` — error: referenced trust certificate expired.
559    Outdated,
560    /// `UNKNOWN` — no matching trust certificate found.
561    Unknown,
562    /// A value the table does not define.
563    Other(&'a str),
564}
565
566impl<'a> IdentificationLevel<'a> {
567    /// Reads a level.
568    #[must_use]
569    pub fn parse(s: &'a str) -> Self {
570        match s {
571            "NONE" => Self::None,
572            "HEARSAY" => Self::Hearsay,
573            "TRUSTED" => Self::Trusted,
574            "VERIFIED" => Self::Verified,
575            "CERTIFIED" => Self::Certified,
576            "SECURE" => Self::Secure,
577            "MISMATCH" => Self::Mismatch,
578            "INVALID" => Self::Invalid,
579            "OUTDATED" => Self::Outdated,
580            "UNKNOWN" => Self::Unknown,
581            other => Self::Other(other),
582        }
583    }
584
585    /// Reads a level from a JSON string, matching the table on its decoded
586    /// value.
587    #[must_use]
588    pub fn parse_decoded(s: &RawStr<'a>) -> Self {
589        Self::from_parts(&s.decode(), s.as_raw())
590    }
591
592    /// Reads a value whose decoded form and source text are already in hand.
593    ///
594    /// The two differ when the source used a `\uXXXX` escape, and — for a
595    /// field a real record wrote as a JSON *number* — when there was no string
596    /// to decode at all.
597    #[must_use]
598    pub fn from_parts(decoded: &str, raw: &'a str) -> Self {
599        decoded_or_raw(
600            decoded,
601            raw,
602            |d| {
603                Some(match d {
604                    "NONE" => Self::None,
605                    "HEARSAY" => Self::Hearsay,
606                    "TRUSTED" => Self::Trusted,
607                    "VERIFIED" => Self::Verified,
608                    "CERTIFIED" => Self::Certified,
609                    "SECURE" => Self::Secure,
610                    "MISMATCH" => Self::Mismatch,
611                    "INVALID" => Self::Invalid,
612                    "OUTDATED" => Self::Outdated,
613                    "UNKNOWN" => Self::Unknown,
614                    _ => return None,
615                })
616            },
617            Self::Other,
618        )
619    }
620
621    /// Whether `[OCMF Tab. 11]` defines this level.
622    #[must_use]
623    pub const fn is_defined(&self) -> bool {
624        !matches!(self, Self::Other(_))
625    }
626
627    /// The value as written.
628    #[must_use]
629    pub const fn as_str(&self) -> &'a str {
630        match self {
631            Self::None => "NONE",
632            Self::Hearsay => "HEARSAY",
633            Self::Trusted => "TRUSTED",
634            Self::Verified => "VERIFIED",
635            Self::Certified => "CERTIFIED",
636            Self::Secure => "SECURE",
637            Self::Mismatch => "MISMATCH",
638            Self::Invalid => "INVALID",
639            Self::Outdated => "OUTDATED",
640            Self::Unknown => "UNKNOWN",
641            Self::Other(s) => s,
642        }
643    }
644
645    /// Whether this level reports an *error* in the assignment.
646    ///
647    /// The reference verifier refuses a transaction whose level is one of
648    /// `MISMATCH`, `INVALID`, `OUTDATED` or `UNKNOWN`, and so does
649    /// [`crate::session`].
650    #[must_use]
651    pub const fn is_error(&self) -> bool {
652        matches!(
653            self,
654            Self::Mismatch | Self::Invalid | Self::Outdated | Self::Unknown
655        )
656    }
657}
658
659impl fmt::Display for IdentificationLevel<'_> {
660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661        f.write_str(self.as_str())
662    }
663}
664
665/// Type of the identification data in `ID` `[OCMF Tab. 17]`.
666#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
667#[non_exhaustive]
668pub enum IdentificationType<'a> {
669    /// `NONE` — no assignment available.
670    None,
671    /// `DENIED` — assignment withheld (two-factor authorisation).
672    Denied,
673    /// `UNDEFINED` — type not specified.
674    Undefined,
675    /// `ISO14443` — RFID UID, 4 or 7 bytes hex.
676    Iso14443,
677    /// `ISO15693` — RFID UID, 8 bytes hex.
678    Iso15693,
679    /// `EMAID` — e-mobility account ID (ISO 15118), 14 or 15 characters.
680    Emaid,
681    /// `EVCCID` — vehicle ID (ISO 15118).
682    Evccid,
683    /// `EVCOID` — EV contract ID (DIN 91286).
684    Evcoid,
685    /// `ISO7812` — payment card number.
686    Iso7812,
687    /// `CARD_TXN_NR` — terminal card transaction number.
688    CardTxnNr,
689    /// `CENTRAL` — centrally generated ID (OCPP 2.0).
690    Central,
691    /// `CENTRAL_1` — centrally generated, e.g. start by SMS (to OCPP 1.6).
692    Central1,
693    /// `CENTRAL_2` — centrally generated, e.g. operator start (to OCPP 1.6).
694    Central2,
695    /// `LOCAL` — locally generated ID (OCPP 2.0).
696    Local,
697    /// `LOCAL_1` — locally generated by the charge point (to OCPP 1.6).
698    Local1,
699    /// `LOCAL_2` — locally generated, other cases (to OCPP 1.6).
700    Local2,
701    /// `PHONE_NUMBER` — international number with a leading `+`.
702    PhoneNumber,
703    /// `KEY_CODE` — user-related private key code.
704    KeyCode,
705    /// A value the table does not define.
706    Other(&'a str),
707}
708
709impl<'a> IdentificationType<'a> {
710    /// Reads a type.
711    #[must_use]
712    pub fn parse(s: &'a str) -> Self {
713        match s {
714            "NONE" => Self::None,
715            "DENIED" => Self::Denied,
716            "UNDEFINED" => Self::Undefined,
717            "ISO14443" => Self::Iso14443,
718            "ISO15693" => Self::Iso15693,
719            "EMAID" => Self::Emaid,
720            "EVCCID" => Self::Evccid,
721            "EVCOID" => Self::Evcoid,
722            "ISO7812" => Self::Iso7812,
723            "CARD_TXN_NR" => Self::CardTxnNr,
724            "CENTRAL" => Self::Central,
725            "CENTRAL_1" => Self::Central1,
726            "CENTRAL_2" => Self::Central2,
727            "LOCAL" => Self::Local,
728            "LOCAL_1" => Self::Local1,
729            "LOCAL_2" => Self::Local2,
730            "PHONE_NUMBER" => Self::PhoneNumber,
731            "KEY_CODE" => Self::KeyCode,
732            other => Self::Other(other),
733        }
734    }
735
736    /// Reads a type from a JSON string, matching the table on its decoded
737    /// value.
738    #[must_use]
739    pub fn parse_decoded(s: &RawStr<'a>) -> Self {
740        Self::from_parts(&s.decode(), s.as_raw())
741    }
742
743    /// Reads a value whose decoded form and source text are already in hand.
744    ///
745    /// The two differ when the source used a `\uXXXX` escape, and — for a
746    /// field a real record wrote as a JSON *number* — when there was no string
747    /// to decode at all.
748    #[must_use]
749    pub fn from_parts(decoded: &str, raw: &'a str) -> Self {
750        decoded_or_raw(
751            decoded,
752            raw,
753            |d| {
754                Some(match d {
755                    "NONE" => Self::None,
756                    "DENIED" => Self::Denied,
757                    "UNDEFINED" => Self::Undefined,
758                    "ISO14443" => Self::Iso14443,
759                    "ISO15693" => Self::Iso15693,
760                    "EMAID" => Self::Emaid,
761                    "EVCCID" => Self::Evccid,
762                    "EVCOID" => Self::Evcoid,
763                    "ISO7812" => Self::Iso7812,
764                    "CARD_TXN_NR" => Self::CardTxnNr,
765                    "CENTRAL" => Self::Central,
766                    "CENTRAL_1" => Self::Central1,
767                    "CENTRAL_2" => Self::Central2,
768                    "LOCAL" => Self::Local,
769                    "LOCAL_1" => Self::Local1,
770                    "LOCAL_2" => Self::Local2,
771                    "PHONE_NUMBER" => Self::PhoneNumber,
772                    "KEY_CODE" => Self::KeyCode,
773                    _ => return None,
774                })
775            },
776            Self::Other,
777        )
778    }
779
780    /// Whether `[OCMF Tab. 17]` defines this type.
781    #[must_use]
782    pub const fn is_defined(&self) -> bool {
783        !matches!(self, Self::Other(_))
784    }
785
786    /// Whether `data` has the shape this type prescribes for `ID`
787    /// `[OCMF Tab. 17]`.
788    ///
789    /// `None` for the thirteen types the table describes as having "no exact
790    /// format defined" — there is nothing to check, and inventing a rule would
791    /// report a deviation from something nobody wrote. Five of the eighteen
792    /// rows state a format, and those five are checked.
793    #[must_use]
794    pub fn data_is_well_formed(&self, data: &str) -> Option<bool> {
795        let hex =
796            |n: [usize; 2]| n.contains(&data.len()) && data.bytes().all(|c| c.is_ascii_hexdigit());
797        Some(match self {
798            // "Represented as 4 or 7 bytes in hexadecimal notation."
799            Self::Iso14443 => hex([8, 14]),
800            // "Represented as 8 bytes in hexadecimal notation."
801            Self::Iso15693 => hex([16, 16]),
802            // "string with length 14 or 15"
803            Self::Emaid => matches!(data.chars().count(), 14 | 15),
804            // "maximum length 6 characters"
805            Self::Evccid => data.chars().count() <= 6,
806            // "International phone number with leading \"+\"."
807            Self::PhoneNumber => data.starts_with('+'),
808            _ => return None,
809        })
810    }
811
812    /// The value as written.
813    #[must_use]
814    pub const fn as_str(&self) -> &'a str {
815        match self {
816            Self::None => "NONE",
817            Self::Denied => "DENIED",
818            Self::Undefined => "UNDEFINED",
819            Self::Iso14443 => "ISO14443",
820            Self::Iso15693 => "ISO15693",
821            Self::Emaid => "EMAID",
822            Self::Evccid => "EVCCID",
823            Self::Evcoid => "EVCOID",
824            Self::Iso7812 => "ISO7812",
825            Self::CardTxnNr => "CARD_TXN_NR",
826            Self::Central => "CENTRAL",
827            Self::Central1 => "CENTRAL_1",
828            Self::Central2 => "CENTRAL_2",
829            Self::Local => "LOCAL",
830            Self::Local1 => "LOCAL_1",
831            Self::Local2 => "LOCAL_2",
832            Self::PhoneNumber => "PHONE_NUMBER",
833            Self::KeyCode => "KEY_CODE",
834            Self::Other(s) => s,
835        }
836    }
837}
838
839impl fmt::Display for IdentificationType<'_> {
840    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
841        f.write_str(self.as_str())
842    }
843}
844
845/// One detail flag of the user assignment `[OCMF Tab. 13–16]`.
846///
847/// The four tables are four independent groups — RFID, OCPP, ISO 15118 and
848/// PLMN — and `IF` carries at most one flag from each.
849#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
850#[non_exhaustive]
851pub enum IdentificationFlag<'a> {
852    /// A flag from `[OCMF Tab. 13]` (`RFID_*`).
853    Rfid(&'a str),
854    /// A flag from `[OCMF Tab. 14]` (`OCPP_*`).
855    Ocpp(&'a str),
856    /// A flag from `[OCMF Tab. 15]` (`ISO15118_*`).
857    Iso15118(&'a str),
858    /// A flag from `[OCMF Tab. 16]` (`PLMN_*`).
859    Plmn(&'a str),
860    /// A flag none of the four tables defines.
861    Other(&'a str),
862}
863
864impl<'a> IdentificationFlag<'a> {
865    /// All flags `[OCMF Tab. 13–16]` define.
866    pub const DEFINED: [&'static str; 17] = [
867        "RFID_NONE",
868        "RFID_PLAIN",
869        "RFID_RELATED",
870        "RFID_PSK",
871        "OCPP_NONE",
872        "OCPP_RS",
873        "OCPP_AUTH",
874        "OCPP_RS_TLS",
875        "OCPP_AUTH_TLS",
876        "OCPP_CACHE",
877        "OCPP_WHITELIST",
878        "OCPP_CERTIFIED",
879        "ISO15118_NONE",
880        "ISO15118_PNC",
881        "PLMN_NONE",
882        "PLMN_RING",
883        "PLMN_SMS",
884    ];
885
886    /// Classifies a flag by its group.
887    #[must_use]
888    pub fn parse(s: &'a str) -> Self {
889        if !Self::DEFINED.contains(&s) {
890            return Self::Other(s);
891        }
892        if s.starts_with("RFID_") {
893            Self::Rfid(s)
894        } else if s.starts_with("OCPP_") {
895            Self::Ocpp(s)
896        } else if s.starts_with("ISO15118_") {
897            Self::Iso15118(s)
898        } else {
899            Self::Plmn(s)
900        }
901    }
902
903    /// Classifies a flag from a JSON string, matching the tables on its
904    /// decoded value.
905    ///
906    /// A flag the tables define keeps its **raw** text, because the four
907    /// variants borrow: an escaped `RFID_PLAIN` is still an RFID flag, and the
908    /// text a caller reads back is the one the record wrote.
909    #[must_use]
910    pub fn parse_decoded(s: &RawStr<'a>) -> Self {
911        let raw = s.as_raw();
912        let decoded = s.decode();
913        let group = match IdentificationFlag::parse(decoded.as_ref()) {
914            IdentificationFlag::Rfid(_) => 0u8,
915            IdentificationFlag::Ocpp(_) => 1,
916            IdentificationFlag::Iso15118(_) => 2,
917            IdentificationFlag::Plmn(_) => 3,
918            IdentificationFlag::Other(_) => 4,
919        };
920        match group {
921            0 => Self::Rfid(raw),
922            1 => Self::Ocpp(raw),
923            2 => Self::Iso15118(raw),
924            3 => Self::Plmn(raw),
925            _ => Self::Other(raw),
926        }
927    }
928
929    /// Which of the four tables this flag belongs to, as a small index —
930    /// `None` for a flag none of them defines.
931    ///
932    /// `[OCMF Tab. 4]` gives `IF` a cardinality of `0..4` because there are
933    /// four groups and a user assignment has one statement to make about each.
934    #[must_use]
935    pub const fn group(&self) -> Option<u8> {
936        Some(match self {
937            Self::Rfid(_) => 0,
938            Self::Ocpp(_) => 1,
939            Self::Iso15118(_) => 2,
940            Self::Plmn(_) => 3,
941            Self::Other(_) => return None,
942        })
943    }
944
945    /// Whether `[OCMF Tab. 13–16]` define this flag.
946    #[must_use]
947    pub const fn is_defined(&self) -> bool {
948        !matches!(self, Self::Other(_))
949    }
950
951    /// The flag as written.
952    #[must_use]
953    pub const fn as_str(&self) -> &'a str {
954        match self {
955            Self::Rfid(s) | Self::Ocpp(s) | Self::Iso15118(s) | Self::Plmn(s) | Self::Other(s) => s,
956        }
957    }
958}
959
960impl fmt::Display for IdentificationFlag<'_> {
961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962        f.write_str(self.as_str())
963    }
964}
965
966/// How a charge point is identified `[OCMF Tab. 18]`.
967#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
968#[non_exhaustive]
969pub enum ChargePointIdType<'a> {
970    /// `EVSEID`.
971    EvseId,
972    /// `CBIDC` — charge box ID and connector ID, space separated.
973    ChargeBoxAndConnector,
974    /// A value the table does not define.
975    Other(&'a str),
976}
977
978impl<'a> ChargePointIdType<'a> {
979    /// Reads a type.
980    #[must_use]
981    pub fn parse(s: &'a str) -> Self {
982        match s {
983            "EVSEID" => Self::EvseId,
984            "CBIDC" => Self::ChargeBoxAndConnector,
985            other => Self::Other(other),
986        }
987    }
988
989    /// Reads a type from a JSON string, matching the table on its decoded
990    /// value.
991    #[must_use]
992    pub fn parse_decoded(s: &RawStr<'a>) -> Self {
993        Self::from_parts(&s.decode(), s.as_raw())
994    }
995
996    /// Reads a value whose decoded form and source text are already in hand.
997    ///
998    /// The two differ when the source used a `\uXXXX` escape, and — for a
999    /// field a real record wrote as a JSON *number* — when there was no string
1000    /// to decode at all.
1001    #[must_use]
1002    pub fn from_parts(decoded: &str, raw: &'a str) -> Self {
1003        decoded_or_raw(
1004            decoded,
1005            raw,
1006            |d| match d {
1007                "EVSEID" => Some(Self::EvseId),
1008                "CBIDC" => Some(Self::ChargeBoxAndConnector),
1009                _ => None,
1010            },
1011            Self::Other,
1012        )
1013    }
1014
1015    /// Whether `[OCMF Tab. 18]` defines this type.
1016    #[must_use]
1017    pub const fn is_defined(&self) -> bool {
1018        !matches!(self, Self::Other(_))
1019    }
1020
1021    /// Whether `id` has the shape this type prescribes for `CI`
1022    /// `[OCMF Tab. 18]`.
1023    ///
1024    /// `None` for `EVSEID`, whose format the table leaves to the EVSE ID
1025    /// specification rather than stating.
1026    #[must_use]
1027    pub fn id_is_well_formed(&self, id: &str) -> Option<bool> {
1028        match self {
1029            // "Charge box ID and connector ID …, a space is used as field
1030            // separator, e.g. \"STEVE_01 1\"."
1031            Self::ChargeBoxAndConnector => {
1032                Some(id.split_once(' ').is_some_and(|(box_id, connector)| {
1033                    !box_id.is_empty() && !connector.is_empty() && !connector.contains(' ')
1034                }))
1035            }
1036            _ => None,
1037        }
1038    }
1039
1040    /// The value as written.
1041    #[must_use]
1042    pub const fn as_str(&self) -> &'a str {
1043        match self {
1044            Self::EvseId => "EVSEID",
1045            Self::ChargeBoxAndConnector => "CBIDC",
1046            Self::Other(s) => s,
1047        }
1048    }
1049}
1050
1051impl fmt::Display for ChargePointIdType<'_> {
1052    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1053        f.write_str(self.as_str())
1054    }
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059    use super::*;
1060    use alloc::string::ToString;
1061
1062    #[test]
1063    fn every_meter_state_letter_round_trips() {
1064        for c in "NGTDRMXIOSEF".chars() {
1065            let st = MeterState::parse(&c.to_string());
1066            assert_eq!(st.letter(), c);
1067            assert_eq!(st.is_ok(), c == 'G');
1068        }
1069    }
1070
1071    #[test]
1072    fn an_undefined_meter_state_is_never_ok() {
1073        let st = MeterState::parse("Q");
1074        assert_eq!(st, MeterState::Undefined('Q'));
1075        assert!(!st.is_ok());
1076        assert_eq!(st.letter(), 'Q');
1077    }
1078
1079    #[test]
1080    fn all_five_spellings_of_an_ending_are_endings() {
1081        for c in "ELRAP".chars() {
1082            assert!(TransactionMarker::parse(&c.to_string()).is_end(), "{c}");
1083        }
1084        for c in "BCXST".chars() {
1085            assert!(!TransactionMarker::parse(&c.to_string()).is_end(), "{c}");
1086        }
1087        assert!(TransactionMarker::parse("B").is_begin());
1088        assert!(!TransactionMarker::parse("Q").is_begin());
1089    }
1090
1091    #[test]
1092    fn error_flags_keep_what_they_cannot_interpret() {
1093        let f = ErrorFlags::borrowed("Et");
1094        assert!(f.energy_unusable() && f.time_unusable() && f.any());
1095        let f = ErrorFlags::borrowed("");
1096        assert!(!f.any());
1097        let f = ErrorFlags::borrowed("Q");
1098        assert!(f.any(), "an undefined flag is still a fault");
1099        assert!(!f.energy_unusable());
1100        assert_eq!(f.undefined().collect::<alloc::vec::Vec<_>>(), ['Q']);
1101    }
1102
1103    #[test]
1104    fn an_unknown_unit_is_not_energy() {
1105        assert!(Unit::parse("kWh").is_energy());
1106        assert!(Unit::parse("Wh").is_energy());
1107        assert!(!Unit::parse("mOhm").is_energy());
1108        assert!(!Unit::parse("MWh").is_energy());
1109        assert_eq!(Unit::parse("MWh"), Unit::Other("MWh"));
1110    }
1111
1112    #[test]
1113    fn the_four_error_levels_are_the_ones_the_reference_refuses() {
1114        for s in ["MISMATCH", "INVALID", "OUTDATED", "UNKNOWN"] {
1115            assert!(IdentificationLevel::parse(s).is_error(), "{s}");
1116        }
1117        for s in [
1118            "NONE",
1119            "HEARSAY",
1120            "TRUSTED",
1121            "VERIFIED",
1122            "CERTIFIED",
1123            "SECURE",
1124        ] {
1125            assert!(!IdentificationLevel::parse(s).is_error(), "{s}");
1126        }
1127    }
1128
1129    #[test]
1130    fn identification_flags_are_grouped_by_their_table() {
1131        assert!(matches!(
1132            IdentificationFlag::parse("RFID_PLAIN"),
1133            IdentificationFlag::Rfid(_)
1134        ));
1135        assert!(matches!(
1136            IdentificationFlag::parse("OCPP_RS_TLS"),
1137            IdentificationFlag::Ocpp(_)
1138        ));
1139        assert!(matches!(
1140            IdentificationFlag::parse("ISO15118_PNC"),
1141            IdentificationFlag::Iso15118(_)
1142        ));
1143        assert!(matches!(
1144            IdentificationFlag::parse("PLMN_SMS"),
1145            IdentificationFlag::Plmn(_)
1146        ));
1147        assert!(matches!(
1148            IdentificationFlag::parse("VENDOR_X"),
1149            IdentificationFlag::Other(_)
1150        ));
1151    }
1152
1153    #[test]
1154    fn an_escaped_table_value_still_matches_its_table() {
1155        // `"\u006bWh"` is a lawful JSON spelling of `"kWh"`. Comparing raw
1156        // text would read it as an unknown unit — and an unknown unit is not
1157        // energy, so a lawful record would silently stop being billable.
1158        let raw = crate::json::parse_value(
1159            r#"{"RU":"kWh","IT":"ISO14443","IL":"VERIFIED","CT":"EVSEID","IF":"RFID_PLAIN"}"#,
1160            0,
1161            &crate::Limits::DEFAULT,
1162            &mut alloc::vec::Vec::new(),
1163        )
1164        .unwrap();
1165        let o = raw.as_object().unwrap();
1166        let f = |k: &str| o.get(k).unwrap().as_str().unwrap();
1167
1168        assert_eq!(Unit::parse_decoded(f("RU")), Unit::KWh);
1169        assert!(Unit::parse_decoded(f("RU")).is_energy());
1170        assert_eq!(
1171            IdentificationType::parse_decoded(f("IT")),
1172            IdentificationType::Iso14443
1173        );
1174        assert_eq!(
1175            IdentificationLevel::parse_decoded(f("IL")),
1176            IdentificationLevel::Verified
1177        );
1178        assert_eq!(
1179            ChargePointIdType::parse_decoded(f("CT")),
1180            ChargePointIdType::EvseId
1181        );
1182        assert!(matches!(
1183            IdentificationFlag::parse_decoded(f("IF")),
1184            IdentificationFlag::Rfid(_)
1185        ));
1186
1187        // …and a value the table does not define keeps the record's own text.
1188        let raw = crate::json::parse_value(
1189            r#"{"RU":"MWh"}"#,
1190            0,
1191            &crate::Limits::DEFAULT,
1192            &mut alloc::vec::Vec::new(),
1193        )
1194        .unwrap();
1195        let u = Unit::parse_decoded(
1196            raw.as_object()
1197                .unwrap()
1198                .get("RU")
1199                .unwrap()
1200                .as_str()
1201                .unwrap(),
1202        );
1203        assert_eq!(u, Unit::Other("MWh"));
1204    }
1205
1206    #[test]
1207    fn all_eighteen_identification_types_round_trip() {
1208        let all = [
1209            "NONE",
1210            "DENIED",
1211            "UNDEFINED",
1212            "ISO14443",
1213            "ISO15693",
1214            "EMAID",
1215            "EVCCID",
1216            "EVCOID",
1217            "ISO7812",
1218            "CARD_TXN_NR",
1219            "CENTRAL",
1220            "CENTRAL_1",
1221            "CENTRAL_2",
1222            "LOCAL",
1223            "LOCAL_1",
1224            "LOCAL_2",
1225            "PHONE_NUMBER",
1226            "KEY_CODE",
1227        ];
1228        assert_eq!(all.len(), 18, "[OCMF Tab. 17] has 18 rows");
1229        for s in all {
1230            assert_eq!(IdentificationType::parse(s).as_str(), s);
1231            assert!(!matches!(
1232                IdentificationType::parse(s),
1233                IdentificationType::Other(_)
1234            ));
1235        }
1236    }
1237}