Skip to main content

ocpp_kit/
metering.rs

1//! Signed meter values: the record a customer may actually be billed for.
2//!
3//! An OCPP meter value is *telemetry*. Under German calibration law (`MessEG` §33) a customer
4//! may be billed for a measured value only if they can check it, and what they check is the
5//! data set the meter itself signed — an OCMF or EDL record, carried through OCPP as an
6//! opaque blob. This module is the protocol knowledge around that blob: how each version
7//! carries it, and how to read the public-key field, which is not what its name suggests.
8//!
9//! # The signed value is not the protocol's number
10//!
11//! They are not even the same quantity. In the Open Charge Alliance's own example message
12//! (*Signed Meter Values in OCPP* v1.0 §5.2) the 1.6 `StopTransaction` reports
13//! `meterStop: 108814` — the meter's **lifetime** register, in Wh — while the signed data set
14//! in the same message reports the transaction running `0.000 → 0.636` kWh. A CSMS that bills
15//! `meterStop − meterStart` is not billing a slightly different number; it is billing a
16//! different register. Whatever the protocol's own fields say, the billable figure comes out
17//! of the signed record.
18//!
19//! # Where each version puts it
20//!
21//! * **2.0.1 and 2.1** — `SampledValue.signedMeterValue`, a typed object. Nothing to do.
22//! * **1.6** — there is no such field. The OCA application note (§3.2.1) reuses 2.x's
23//!   `SignedMeterValueType` by serializing the whole object into the `value` **string** of a
24//!   `SampledValue` whose `format` is `SignedData`: a string holding JSON holding Base64
25//!   holding the record. Nothing about that is guessable from the 1.6 schema, and it is how
26//!   every calibration-law-compliant 1.6 station sends its billable value. Reading it is
27//!   [`v1_6::SampledValue::signed_meter_value`](crate::v1_6::SampledValue::signed_meter_value).
28//!
29//! Both shapes reach [`SignedMeterValue`], which is what the version-neutral
30//! [`csms::events`](crate::csms::events) funnel carries.
31//!
32//! # The bytes are a claim, not a binding
33//!
34//! [`SignedMeterValue::public_key`] answers what the station *said* the key is. OCMF requires
35//! the public key to reach the customer out of band — from the certified meter, or a
36//! registry — precisely because a key arriving on the same socket as the record it signs
37//! proves only that whoever holds that socket owns some private key. Verify against a key you
38//! obtained elsewhere; use this one to *display*, and to notice when a station's key changes.
39
40use alloc::borrow::ToOwned;
41use alloc::string::String;
42use alloc::vec::Vec;
43use core::fmt;
44
45use base64::Engine as _;
46use serde::{Deserialize, Serialize};
47
48/// Base64 that does not mind whether the padding is there.
49///
50/// Both shapes are in the field, and refusing one of them would reject a station over a
51/// character that carries no information.
52const BASE64: base64::engine::general_purpose::GeneralPurpose =
53    base64::engine::general_purpose::GeneralPurpose::new(
54        &base64::alphabet::STANDARD,
55        base64::engine::general_purpose::GeneralPurposeConfig::new()
56            .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
57    );
58
59/// A meter reading carrying the meter's own digital signature.
60///
61/// Version-neutral: 2.x's `SignedMeterValueType` and 1.6's `SignedData` string both become
62/// this. The fields are carried through **verbatim** — the signature covers those exact
63/// bytes, so nothing here re-encodes, re-wraps or normalizes them.
64#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
65#[serde(rename_all = "camelCase")]
66pub struct SignedMeterValue {
67    /// `signedMeterData`: the signed record, Base64 as sent. An OCMF data set, an EDL file —
68    /// whatever [`encoding_method`](Self::encoding_method) names.
69    pub signed_meter_data: String,
70    /// `encodingMethod`: `OCMF`, `EDL`, …
71    ///
72    /// Required by both 2.x schemas, so always `Some` there. A 1.6 `SignedData` payload may
73    /// omit it; the record is still the billable one, so it is carried rather than refused —
74    /// an OCMF data set announces itself with an `OCMF|` prefix in any case.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub encoding_method: Option<String>,
77    /// `signingMethod`: the signature algorithm, when it is not already inside the record.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub signing_method: Option<String>,
80    /// `publicKey`: the key the station claims signed the record.
81    ///
82    /// Not key bytes — see [`public_key`](Self::public_key) for the two shapes this field is
83    /// actually sent in, and for why it is a claim rather than a binding.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub public_key: Option<String>,
86}
87
88impl SignedMeterValue {
89    /// A signed meter value carrying just the record.
90    #[must_use]
91    pub fn new(signed_meter_data: impl Into<String>) -> Self {
92        Self {
93            signed_meter_data: signed_meter_data.into(),
94            encoding_method: None,
95            signing_method: None,
96            public_key: None,
97        }
98    }
99
100    /// Sets `encodingMethod`.
101    #[must_use]
102    pub fn with_encoding_method(mut self, method: impl Into<String>) -> Self {
103        self.encoding_method = Some(method.into());
104        self
105    }
106
107    /// Sets `signingMethod`.
108    #[must_use]
109    pub fn with_signing_method(mut self, method: impl Into<String>) -> Self {
110        self.signing_method = Some(method.into());
111        self
112    }
113
114    /// Sets `publicKey`.
115    #[must_use]
116    pub fn with_public_key(mut self, key: impl Into<String>) -> Self {
117        self.public_key = Some(key.into());
118        self
119    }
120
121    /// Parses the JSON document a 1.6 station puts in a `SignedData` sampled value.
122    ///
123    /// # Errors
124    ///
125    /// [`SignedDataError`] when the string is not the JSON object the application note
126    /// describes.
127    pub fn from_signed_data(value: &str) -> Result<Self, SignedDataError> {
128        let parsed: Self = serde_json::from_str(value).map_err(|error| {
129            SignedDataError::new(alloc::format!("not a SignedMeterValue document: {error}"))
130        })?;
131        if parsed.signed_meter_data.is_empty() {
132            return Err(SignedDataError::new("signedMeterData is empty"));
133        }
134        Ok(parsed)
135    }
136
137    /// The record itself: the bytes the meter signed.
138    ///
139    /// Equivalent to [`record`](Self::record) discarding the encoding. Use `record` where the
140    /// encoding matters — a station sending the record in plain is not conforming, and that
141    /// is worth reporting rather than absorbing.
142    ///
143    /// Nothing is re-encoded on the way out: these are the bytes the signature covers.
144    ///
145    /// # Errors
146    ///
147    /// [`SignedDataError`] when the field is empty — an empty record is not a record.
148    pub fn decoded(&self) -> Result<Vec<u8>, SignedDataError> {
149        self.record().map(|record| record.bytes)
150    }
151
152    /// The record, with **how the station wrote it**.
153    ///
154    /// 2.0.1 Part 2 §2.46 specifies Base64; plenty of stations send the record in plain, and
155    /// refusing those is a quiet failure — the station keeps sending and its sessions stop
156    /// being billable. Both are read, and which arrived is reported rather than absorbed, the
157    /// same contract [`decode_public_key`] has: only one of them conforms, and the consumer
158    /// billing from the record is the one who has to raise it with the vendor.
159    ///
160    /// Told apart by alphabet: OCMF begins `OCMF|`, EDL is XML beginning `<`, and neither
161    /// character is in the Base64 alphabet. Text made *only* of Base64 characters is taken as
162    /// Base64 — the one ambiguous case, unreachable for either format OCPP names here, and
163    /// resolved the way the specification says the field is written.
164    ///
165    /// # Errors
166    ///
167    /// [`SignedDataError`] when the field is empty — an empty record is not a record.
168    pub fn record(&self) -> Result<SignedRecord, SignedDataError> {
169        let text = self.signed_meter_data.trim();
170        if text.is_empty() {
171            return Err(SignedDataError::new("signedMeterData is empty"));
172        }
173        let plain = |bytes: &str| SignedRecord {
174            bytes: bytes.as_bytes().to_vec(),
175            encoding: RecordEncoding::Plain,
176        };
177        if text.starts_with(OCMF_PREFIX) {
178            return Ok(plain(text));
179        }
180        // Whitespace inside a Base64 field carries no information, so a line-wrapped record
181        // is still one; the decoder does not skip it for us.
182        let compact: Vec<u8> = text
183            .bytes()
184            .filter(|byte| !byte.is_ascii_whitespace())
185            .collect();
186        if !is_base64_alphabet(&compact) {
187            return Ok(plain(text));
188        }
189        // Padding-indifferent, so a station that omits `=` is not refused over a character
190        // that carries no information either.
191        BASE64.decode(&compact).map_or_else(
192            |_| Ok(plain(text)),
193            |bytes| {
194                Ok(SignedRecord {
195                    bytes,
196                    encoding: RecordEncoding::Base64,
197                })
198            },
199        )
200    }
201
202    /// [`decoded`](Self::decoded) as text.
203    ///
204    /// OCMF is textual — a `|`-separated header, a JSON payload and a JSON signature — so
205    /// this is what a consumer of an OCMF record actually wants. EDL is XML, also text.
206    ///
207    /// # Errors
208    ///
209    /// [`SignedDataError`] when the field is empty, or when the record is not UTF-8 — which
210    /// means it is a binary format, and [`decoded`](Self::decoded) is the right call for it.
211    pub fn decoded_str(&self) -> Result<String, SignedDataError> {
212        String::from_utf8(self.decoded()?)
213            .map_err(|_| SignedDataError::new("the signed record is not UTF-8 text"))
214    }
215
216    /// The JSON document a 1.6 station puts in a `SignedData` sampled value.
217    ///
218    /// The inverse of
219    /// [`v1_6::SampledValue::signed_meter_value`](crate::v1_6::SampledValue::signed_meter_value),
220    /// and the reason it is here rather than in every station: getting the shape right means
221    /// knowing that 1.6 reuses 2.x's type by serialising it into a string, which nothing in
222    /// the 1.6 schema says. [`v1_6::SampledValue::signed`](crate::v1_6::SampledValue::signed)
223    /// wraps this together with the `format` the shape also requires.
224    #[must_use]
225    pub fn to_signed_data(&self) -> String {
226        // The fields are the ones this type holds and all of them are strings, so this cannot
227        // fail; a `Result` here would only make every caller unwrap it.
228        serde_json::to_string(self).unwrap_or_else(|_| String::from("{}"))
229    }
230
231    /// The public key the station claims, in both shapes the field is sent in.
232    ///
233    /// `None` when the station sent no key at all — which is normal: OCPP 2.x gates the field
234    /// on the `PublicKeyWithSignedMeterValue` configuration variable, and a key that travels
235    /// out of band is the stronger arrangement anyway.
236    ///
237    /// # Errors
238    ///
239    /// [`PublicKeyError`] when the field is not Base64, or is an `oca:` envelope this cannot
240    /// read. See [`PublicKey`] for what the two shapes are and why there are two.
241    pub fn public_key(&self) -> Option<Result<PublicKey, PublicKeyError>> {
242        self.public_key.as_deref().map(decode_public_key)
243    }
244
245    /// Just the key bytes — [`public_key`](Self::public_key) without the provenance.
246    ///
247    /// # Errors
248    ///
249    /// As [`public_key`](Self::public_key).
250    pub fn public_key_bytes(&self) -> Option<Result<Vec<u8>, PublicKeyError>> {
251        self.public_key().map(|result| result.map(|key| key.bytes))
252    }
253}
254
255/// The `publicKey` field could not be read.
256#[derive(Clone, Debug, PartialEq, Eq)]
257#[non_exhaustive]
258pub enum PublicKeyError {
259    /// The field is not Base64.
260    NotBase64,
261    /// An `oca:` envelope with fewer than four colon-separated parts.
262    MalformedEnvelope,
263    /// An `oca:` envelope naming an encoding this does not implement. The token is kept, so a
264    /// caller that knows it can still act on the printed form.
265    UnsupportedEncoding(String),
266    /// The printed key does not spell a whole number of bytes in the encoding it names.
267    MalformedKey,
268}
269
270impl fmt::Display for PublicKeyError {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        match self {
273            PublicKeyError::NotBase64 => f.write_str("publicKey is not Base64"),
274            PublicKeyError::MalformedEnvelope => {
275                f.write_str("publicKey is an oca: envelope with too few parts")
276            }
277            PublicKeyError::UnsupportedEncoding(encoding) => {
278                write!(f, "publicKey names an unsupported encoding {encoding:?}")
279            }
280            PublicKeyError::MalformedKey => f.write_str("publicKey does not spell whole bytes"),
281        }
282    }
283}
284
285#[cfg(feature = "std")]
286impl std::error::Error for PublicKeyError {}
287
288/// A signed meter value that could not be read: a 1.6 `SignedData` string that is not the
289/// JSON document the application note describes, or a `signedMeterData` field with no record
290/// in it.
291#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct SignedDataError {
293    reason: String,
294}
295
296impl SignedDataError {
297    fn new(reason: impl Into<String>) -> Self {
298        Self {
299            reason: reason.into(),
300        }
301    }
302
303    /// What was wrong, for a log line an operator can act on.
304    ///
305    /// A station that *says* it is sending signed data and is not looks, from the outside,
306    /// exactly like a station sending none — and the difference only surfaces when a month of
307    /// sessions turns out to be unbillable. This is the string that stops that happening.
308    #[must_use]
309    pub fn reason(&self) -> &str {
310        &self.reason
311    }
312}
313
314impl fmt::Display for SignedDataError {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        f.write_str(&self.reason)
317    }
318}
319
320#[cfg(feature = "std")]
321impl std::error::Error for SignedDataError {}
322
323/// How a station wrote `signedMeterData`.
324///
325/// Reported by [`SignedMeterValue::record`], because only one of these is conforming and a
326/// consumer billing from the record is the party that needs to know.
327#[derive(Clone, Copy, Debug, PartialEq, Eq)]
328#[non_exhaustive]
329pub enum RecordEncoding {
330    /// Base64, as 2.0.1 Part 2 §2.46 specifies.
331    Base64,
332    /// The record in plain, which the specification does not permit and many stations send.
333    ///
334    /// Unambiguous — both formats OCPP names for this field carry a non-Base64 character in
335    /// their first bytes — but worth reporting to whoever owns the fleet.
336    Plain,
337}
338
339impl RecordEncoding {
340    /// Whether this is the encoding 2.0.1 Part 2 §2.46 specifies.
341    #[must_use]
342    pub const fn is_conforming(self) -> bool {
343        matches!(self, RecordEncoding::Base64)
344    }
345}
346
347/// A signed record and the encoding it arrived in.
348#[derive(Clone, Debug, PartialEq, Eq)]
349pub struct SignedRecord {
350    /// The record itself — the bytes the signature covers, never re-encoded.
351    pub bytes: Vec<u8>,
352    /// How the station wrote it.
353    pub encoding: RecordEncoding,
354}
355
356impl SignedRecord {
357    /// The record as text, which is what OCMF and EDL both are.
358    ///
359    /// # Errors
360    ///
361    /// [`SignedDataError`] when the record is not UTF-8, which means it is a binary format
362    /// and [`bytes`](Self::bytes) is the right field for it.
363    pub fn as_text(&self) -> Result<String, SignedDataError> {
364        core::str::from_utf8(&self.bytes)
365            .map(ToOwned::to_owned)
366            .map_err(|_| SignedDataError::new("the signed record is not UTF-8 text"))
367    }
368}
369
370/// How the `publicKey` field was written.
371#[derive(Clone, Copy, Debug, PartialEq, Eq)]
372#[non_exhaustive]
373pub enum PublicKeyShape {
374    /// Base64 over `oca:<encoding>:<content-type>:<printed key>`, as the application note
375    /// §3.2.2 specifies.
376    Envelope,
377    /// Base64 over the key printed as hexadecimal, with no envelope — the shape the same
378    /// document's own example message uses.
379    PrintedHex,
380    /// Base64 over bytes that are not text in either shape; taken as the key itself.
381    Opaque,
382}
383
384/// The public key a station claims signed a record.
385///
386/// # Two shapes, both conformant in practice
387///
388/// The OCA application note §3.2.2 specifies Base64 over a colon-separated envelope —
389/// `oca:<encoding>:<content-type>:<printed public key>` — where the last part is the key **as
390/// printed on the certified meter**, so that a customer can compare it against the label on
391/// the cabinet. For `base16` it adds that non-hexadecimal characters and a leading `0x`
392/// "SHALL be ignored", because a printed key has spaces in it.
393///
394/// The same document's example message (§5.2) then sends Base64 over plain uppercase
395/// hexadecimal with no envelope at all. A reader that implements only the specification
396/// rejects the whitepaper's own example; one that implements only the example rejects every
397/// conformant station. Both are in the field, so both are read here, and
398/// [`shape`](Self::shape) says which arrived.
399#[derive(Clone, Debug, PartialEq, Eq)]
400#[non_exhaustive]
401pub struct PublicKey {
402    /// The key bytes.
403    pub bytes: Vec<u8>,
404    /// The key as it was written — what to show a customer comparing it with the meter's
405    /// label. `None` for [`PublicKeyShape::Opaque`], where there was no text.
406    pub printed: Option<String>,
407    /// The envelope's encoding token (`base16`, `base32`, `base64`), when there was an
408    /// envelope.
409    pub encoding: Option<String>,
410    /// The envelope's content type — the key's own format, such as a curve name — when there
411    /// was an envelope.
412    pub content_type: Option<String>,
413    /// Which shape the field arrived in.
414    pub shape: PublicKeyShape,
415}
416
417/// A field the target version requires that a version-neutral value does not carry.
418///
419/// The versions disagree about which parts of a signed meter value are mandatory — 2.0.1
420/// requires all four, 2.1 requires the record and its encoding — so a value read from one
421/// version does not always fit another. Saying which field is missing is more use than
422/// refusing without a reason.
423#[derive(Clone, Copy, Debug, PartialEq, Eq)]
424pub struct MissingField {
425    /// The member the target version requires.
426    pub field: &'static str,
427    /// The version that requires it.
428    pub version: crate::version::Version,
429}
430
431impl fmt::Display for MissingField {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        write!(
434            f,
435            "OCPP {} requires signedMeterValue.{}",
436            self.version, self.field
437        )
438    }
439}
440
441#[cfg(feature = "std")]
442impl std::error::Error for MissingField {}
443
444/// How an OCMF record announces itself, in the text form (OCMF v1.0 §5).
445const OCMF_PREFIX: &str = "OCMF|";
446
447/// Whether every byte could appear in Base64 — the test that tells an encoded record from one
448/// sent in plain.
449fn is_base64_alphabet(bytes: &[u8]) -> bool {
450    bytes
451        .iter()
452        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
453}
454
455/// Reads a `publicKey` field in either of the two shapes it is sent in.
456///
457/// # Errors
458///
459/// [`PublicKeyError`] when the field is not Base64, or is an envelope this cannot read.
460pub fn decode_public_key(field: &str) -> Result<PublicKey, PublicKeyError> {
461    let raw = BASE64
462        .decode(field.trim())
463        .map_err(|_| PublicKeyError::NotBase64)?;
464
465    // Everything below only applies if the Base64 covered *text*. Anything else is the key.
466    let Ok(text) = core::str::from_utf8(&raw) else {
467        return Ok(PublicKey {
468            bytes: raw,
469            printed: None,
470            encoding: None,
471            content_type: None,
472            shape: PublicKeyShape::Opaque,
473        });
474    };
475    let text = text.trim();
476
477    if let Some(rest) = text.strip_prefix("oca:") {
478        // `oca:<encoding>:<content-type>:<printed key>`. The printed key may itself contain
479        // colons, so only the first two are separators.
480        let mut parts = rest.splitn(3, ':');
481        let (Some(encoding), Some(content_type), Some(printed)) =
482            (parts.next(), parts.next(), parts.next())
483        else {
484            return Err(PublicKeyError::MalformedEnvelope);
485        };
486        let bytes = decode_printed(printed, encoding)?;
487        return Ok(PublicKey {
488            bytes,
489            printed: Some(printed.to_owned()),
490            encoding: Some(encoding.to_owned()),
491            content_type: Some(content_type.to_owned()),
492            shape: PublicKeyShape::Envelope,
493        });
494    }
495
496    // No envelope. The example message's shape is hexadecimal text; anything else is bytes.
497    match decode_printed_hex(text) {
498        Some(bytes) => Ok(PublicKey {
499            bytes,
500            printed: Some(text.to_owned()),
501            encoding: None,
502            content_type: None,
503            shape: PublicKeyShape::PrintedHex,
504        }),
505        None => Ok(PublicKey {
506            bytes: raw,
507            printed: None,
508            encoding: None,
509            content_type: None,
510            shape: PublicKeyShape::Opaque,
511        }),
512    }
513}
514
515/// Decodes a printed key in the encoding its envelope names.
516fn decode_printed(printed: &str, encoding: &str) -> Result<Vec<u8>, PublicKeyError> {
517    // The tokens are lower-case in the note; stations are not.
518    if encoding.eq_ignore_ascii_case("base16") || encoding.eq_ignore_ascii_case("hex") {
519        decode_base16(printed).ok_or(PublicKeyError::MalformedKey)
520    } else if encoding.eq_ignore_ascii_case("base32") {
521        decode_base32(printed).ok_or(PublicKeyError::MalformedKey)
522    } else if encoding.eq_ignore_ascii_case("base64") {
523        BASE64
524            .decode(strip_ignored(printed, |byte| {
525                byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/' || byte == b'='
526            }))
527            .map_err(|_| PublicKeyError::MalformedKey)
528    } else {
529        Err(PublicKeyError::UnsupportedEncoding(encoding.to_owned()))
530    }
531}
532
533/// Keeps only the bytes the encoding's alphabet contains.
534///
535/// §3.2.2 requires it for `base16` — a key printed on a meter has spaces in it so a human can
536/// read it back — and it is harmless for the others, whose alphabets do not contain the
537/// separators either.
538fn strip_ignored(text: &str, keep: impl Fn(u8) -> bool) -> Vec<u8> {
539    text.bytes().filter(|byte| keep(*byte)).collect()
540}
541
542/// Hexadecimal, ignoring *every* character that is not a hex digit, and a leading `0x`.
543///
544/// That is what §3.2.2 requires of an envelope's `base16`: a key printed on a meter is broken
545/// up with spaces so a human can read it back, and the note says those "SHALL be ignored".
546fn decode_base16(text: &str) -> Option<Vec<u8>> {
547    let text = text.trim();
548    let text = text
549        .strip_prefix("0x")
550        .or_else(|| text.strip_prefix("0X"))
551        .unwrap_or(text);
552    let digits = strip_ignored(text, |byte| byte.is_ascii_hexdigit());
553    if digits.is_empty() || digits.len() % 2 != 0 {
554        return None;
555    }
556    let mut bytes = Vec::with_capacity(digits.len() / 2);
557    for pair in digits.chunks(2) {
558        let high = (pair[0] as char).to_digit(16)?;
559        let low = (pair[1] as char).to_digit(16)?;
560        bytes.push(u8::try_from(high * 16 + low).ok()?);
561    }
562    Some(bytes)
563}
564
565/// The same, but only when the text is *nothing but* hex digits and separators.
566///
567/// Used to recognise the un-enveloped shape, where there is no `oca:` prefix to say that the
568/// text is a printed key. Ignoring stray characters there — which is right inside an envelope
569/// that has already declared itself — would let any text at all be read as a key.
570fn decode_printed_hex(text: &str) -> Option<Vec<u8>> {
571    let trimmed = text.trim();
572    let body = trimmed
573        .strip_prefix("0x")
574        .or_else(|| trimmed.strip_prefix("0X"))
575        .unwrap_or(trimmed);
576    if body
577        .bytes()
578        .any(|byte| !byte.is_ascii_hexdigit() && !is_separator(byte))
579    {
580        return None;
581    }
582    decode_base16(trimmed)
583}
584
585/// What a printed key may be broken up with.
586const fn is_separator(byte: u8) -> bool {
587    matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'-' | b':' | b'.')
588}
589
590/// RFC 4648 base32, ignoring separators and padding.
591fn decode_base32(text: &str) -> Option<Vec<u8>> {
592    let mut accumulator: u32 = 0;
593    let mut bits = 0u32;
594    let mut bytes = Vec::new();
595    for byte in text.bytes() {
596        if byte == b'=' || is_separator(byte) {
597            continue;
598        }
599        let value = match byte {
600            b'A'..=b'Z' => byte - b'A',
601            b'a'..=b'z' => byte - b'a',
602            b'2'..=b'7' => byte - b'2' + 26,
603            _ => return None,
604        };
605        accumulator = (accumulator << 5) | u32::from(value);
606        bits += 5;
607        if bits >= 8 {
608            bits -= 8;
609            bytes.push(((accumulator >> bits) & 0xff) as u8);
610        }
611    }
612    // Whatever is left is the encoding's tail padding, and must be zero.
613    if accumulator & ((1 << bits) - 1) != 0 || bytes.is_empty() {
614        return None;
615    }
616    Some(bytes)
617}
618
619// ---------------------------------------------------------------------------
620// Per-version bridges
621// ---------------------------------------------------------------------------
622
623/// Generates the conversion from a version's generated `SignedMeterValueType`.
624///
625/// 2.0.1 makes `signingMethod` and `publicKey` mandatory and 2.1 makes both optional;
626/// `Option::from` absorbs exactly that difference and nothing else.
627#[cfg(any(feature = "v2_0_1", feature = "v2_1"))]
628macro_rules! from_generated {
629    ($module:ident) => {
630        impl From<&crate::$module::SignedMeterValue> for SignedMeterValue {
631            fn from(value: &crate::$module::SignedMeterValue) -> Self {
632                Self {
633                    signed_meter_data: value.signed_meter_data.clone(),
634                    encoding_method: Option::from(value.encoding_method.clone()),
635                    signing_method: Option::from(value.signing_method.clone()),
636                    public_key: Option::from(value.public_key.clone()),
637                }
638            }
639        }
640    };
641}
642
643#[cfg(feature = "v2_0_1")]
644from_generated!(v2_0_1);
645#[cfg(feature = "v2_1")]
646from_generated!(v2_1);
647
648#[cfg(feature = "v2_0_1")]
649impl TryFrom<&SignedMeterValue> for crate::v2_0_1::SignedMeterValue {
650    type Error = MissingField;
651
652    /// 2.0.1 makes every member of `SignedMeterValueType` mandatory, so a value that came
653    /// from 2.1 or from a 1.6 `SignedData` document may not fit — those two let a station
654    /// omit the signing method and the public key.
655    fn try_from(value: &SignedMeterValue) -> Result<Self, MissingField> {
656        let missing = |field| MissingField {
657            field,
658            version: crate::version::Version::V2_0_1,
659        };
660        Ok(Self::new(
661            value.signed_meter_data.clone(),
662            value
663                .signing_method
664                .clone()
665                .ok_or_else(|| missing("signingMethod"))?,
666            value
667                .encoding_method
668                .clone()
669                .ok_or_else(|| missing("encodingMethod"))?,
670            value
671                .public_key
672                .clone()
673                .ok_or_else(|| missing("publicKey"))?,
674        ))
675    }
676}
677
678#[cfg(feature = "v2_1")]
679impl TryFrom<&SignedMeterValue> for crate::v2_1::SignedMeterValue {
680    type Error = MissingField;
681
682    /// 2.1 requires only the record and the method it is encoded in; the signing method and
683    /// the public key became optional, because both can already be inside the record and the
684    /// key is better obtained out of band.
685    fn try_from(value: &SignedMeterValue) -> Result<Self, MissingField> {
686        let mut out = Self::new(
687            value.signed_meter_data.clone(),
688            value.encoding_method.clone().ok_or(MissingField {
689                field: "encodingMethod",
690                version: crate::version::Version::V2_1,
691            })?,
692        );
693        out.signing_method.clone_from(&value.signing_method);
694        out.public_key.clone_from(&value.public_key);
695        Ok(out)
696    }
697}
698
699#[cfg(feature = "v1_6")]
700impl crate::v1_6::SampledValue {
701    /// A sampled value carrying a signed meter value, in the shape 1.6 defines for it.
702    ///
703    /// Sets both halves of that shape: the record serialised into `value`, and the `format`
704    /// of `SignedData` without which a CSMS reads the document as a measurement. A station
705    /// writing this by hand gets the second half wrong, and nothing tells it so — the message
706    /// is schema-valid either way.
707    ///
708    /// ```
709    /// use ocpp_kit::metering::SignedMeterValue;
710    /// use ocpp_kit::v1_6::{Measurand, ReadingContext, SampledValue};
711    ///
712    /// let record = SignedMeterValue::new("T0NNRnx7fQ==").with_encoding_method("OCMF");
713    /// let sample = SampledValue::signed(&record)
714    ///     .with_measurand(Measurand::EnergyActiveImportRegister)
715    ///     .with_context(ReadingContext::TransactionEnd);
716    ///
717    /// // …and it reads back as what went in.
718    /// assert_eq!(sample.signed_meter_value().unwrap().unwrap(), record);
719    /// ```
720    #[must_use]
721    pub fn signed(value: &SignedMeterValue) -> Self {
722        Self::new(value.to_signed_data()).with_format(crate::v1_6::ValueFormat::SignedData)
723    }
724    /// The signed meter value this sampled value carries, if it carries one.
725    ///
726    /// 1.6 has no `signedMeterValue` field. The OCA application note (§3.2.1) reuses 2.x's
727    /// `SignedMeterValueType` by serializing the whole object into this sampled value's
728    /// `value` **string**, with `format` set to `SignedData`:
729    ///
730    /// ```json
731    /// {"format": "SignedData",
732    ///  "value": "{\"signedMeterData\":\"T0NNRnx7…\",\"encodingMethod\":\"OCMF\"}",
733    ///  "context": "Transaction.End", "measurand": "Energy.Active.Import.Register"}
734    /// ```
735    ///
736    /// So `value` is a string holding JSON holding Base64 holding the record, and a CSMS
737    /// reading it as a measurement — which is what the field is for everywhere else — finds a
738    /// JSON document where it expected kilowatt-hours. Every calibration-law-compliant German
739    /// 1.6 station sends its billable value this way.
740    ///
741    /// Returns `None` when `format` is not `SignedData`, and `Some(Err(_))` when it is but
742    /// the string is not the document the note describes — which is worth surfacing rather
743    /// than dropping, since the station is then unbillable and does not know it.
744    #[must_use]
745    pub fn signed_meter_value(&self) -> Option<Result<SignedMeterValue, SignedDataError>> {
746        if self.format.as_ref()? != &crate::v1_6::ValueFormat::SignedData {
747            return None;
748        }
749        Some(SignedMeterValue::from_signed_data(&self.value))
750    }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756    use alloc::string::ToString;
757
758    /// Base64 over uppercase hexadecimal, no envelope — the shape the OCA's own example
759    /// message (§5.2) uses, and the one a reader of §3.2.2 alone would reject.
760    const EXAMPLE_KEY: &str = "MzA1OTMwMTMwNjA3MkE4NjQ4Q0UzRDAyMDEwNjA4MkE4NjQ4Q0UzRDAzMDEwNw==";
761
762    /// Base64 over `oca:base16:secp256r1:<printed key>` — what §3.2.2 specifies, spaces and
763    /// all, because the key is meant to be compared with the label on the cabinet.
764    const ENVELOPE_KEY: &str =
765        "b2NhOmJhc2UxNjpzZWNwMjU2cjE6MzAgNTkgMzAgMTMgMDYgMDcgMkEgODYgNDggQ0UgM0QgMDIgMDE=";
766
767    #[test]
768    fn both_shapes_of_the_public_key_field_are_read() {
769        let bare = decode_public_key(EXAMPLE_KEY).expect("the example message's shape");
770        assert_eq!(bare.shape, PublicKeyShape::PrintedHex);
771        assert_eq!(&bare.bytes[..4], &[0x30, 0x59, 0x30, 0x13]);
772        assert_eq!(bare.printed.as_deref().map(|key| &key[..4]), Some("3059"));
773        assert_eq!(bare.encoding, None);
774
775        let enveloped = decode_public_key(ENVELOPE_KEY).expect("the specified shape");
776        assert_eq!(enveloped.shape, PublicKeyShape::Envelope);
777        // The separators a human needs are ignored, exactly as §3.2.2 requires.
778        assert_eq!(&enveloped.bytes[..4], &[0x30, 0x59, 0x30, 0x13]);
779        assert_eq!(enveloped.encoding.as_deref(), Some("base16"));
780        assert_eq!(enveloped.content_type.as_deref(), Some("secp256r1"));
781        assert_eq!(
782            enveloped.printed.as_deref(),
783            Some("30 59 30 13 06 07 2A 86 48 CE 3D 02 01"),
784            "the printed form is what a customer compares with the meter's label"
785        );
786
787        // Both decode to the same key, which is the whole point of reading both.
788        assert_eq!(bare.bytes[..13], enveloped.bytes[..]);
789    }
790
791    #[test]
792    fn base64_over_key_bytes_is_taken_as_the_key() {
793        // Not text, so there is no printed form to show and no transformation to undo.
794        let key = decode_public_key("MFkTAQ==").expect("bytes");
795        assert_eq!(key.shape, PublicKeyShape::Opaque);
796        assert_eq!(key.bytes, alloc::vec![0x30, 0x59, 0x13, 0x01]);
797        assert_eq!(key.printed, None);
798    }
799
800    #[test]
801    fn a_leading_0x_and_an_odd_digit_count_are_handled_as_the_note_says() {
802        // "a hexadecimal prefix 0x SHALL be ignored"
803        assert_eq!(decode_base16("0x3059").unwrap(), alloc::vec![0x30, 0x59]);
804        assert_eq!(decode_base16("30-59:30.13").unwrap().len(), 4);
805        // Half a byte is not a key.
806        assert_eq!(decode_base16("305"), None);
807        // Text that merely contains hex digits is not a printed key.
808        assert_eq!(decode_printed_hex("hello dead beef"), None);
809    }
810
811    #[test]
812    fn an_unreadable_field_says_which_way_it_is_unreadable() {
813        assert_eq!(decode_public_key("!!!!"), Err(PublicKeyError::NotBase64));
814        // base64("oca:base16") — an envelope with two parts instead of four.
815        assert_eq!(
816            decode_public_key("b2NhOmJhc2UxNg=="),
817            Err(PublicKeyError::MalformedEnvelope)
818        );
819        // base64("oca:base99:x:3059")
820        assert_eq!(
821            decode_public_key("b2NhOmJhc2U5OTp4OjMwNTk="),
822            Err(PublicKeyError::UnsupportedEncoding("base99".to_string()))
823        );
824    }
825
826    #[test]
827    fn base32_and_base64_envelopes_decode_too() {
828        // base64("oca:base32:x:GBMTC===") — GBMTC base32-decodes to 0x30 0x59 0x31.
829        let field = BASE64.encode("oca:base32:x:GBMTC===");
830        assert_eq!(
831            decode_public_key(&field).unwrap().bytes,
832            alloc::vec![0x30, 0x59, 0x31]
833        );
834        let field = BASE64.encode("oca:base64:x:MFkTAQ==");
835        assert_eq!(
836            decode_public_key(&field).unwrap().bytes,
837            alloc::vec![0x30, 0x59, 0x13, 0x01]
838        );
839    }
840
841    /// The record has to come out of the transport intact, whichever way the station put it
842    /// in. Refusing the plain form would be a *quiet* failure: the station keeps sending, and
843    /// its sessions stop being billable for a reason nobody looks for.
844    #[test]
845    fn the_record_comes_out_whether_it_was_base64_or_plain() {
846        const RECORD: &str = "OCMF|{\"FV\":\"1.0\",\"RD\":[{\"RV\":0.636}]}|{\"SD\":\"304402\"}";
847
848        // Base64, as the specification says.
849        let encoded = SignedMeterValue::new(BASE64.encode(RECORD)).with_encoding_method("OCMF");
850        assert_eq!(encoded.decoded_str().unwrap(), RECORD);
851
852        // Plain, as a great many stations actually send it. `|` is not in the Base64
853        // alphabet, so the two shapes cannot be confused for one another.
854        let plain = SignedMeterValue::new(RECORD).with_encoding_method("OCMF");
855        assert_eq!(plain.decoded_str().unwrap(), RECORD);
856        assert_eq!(plain.decoded().unwrap(), RECORD.as_bytes());
857
858        // An EDL record is XML, which is not Base64 either.
859        let xml = SignedMeterValue::new("<?xml version=\"1.0\"?><edl/>");
860        assert_eq!(xml.decoded_str().unwrap(), "<?xml version=\"1.0\"?><edl/>");
861
862        // Binary after decoding: bytes are available, text is not, and the error says so.
863        let binary = SignedMeterValue::new(BASE64.encode([0xff, 0xfe, 0x00]));
864        assert_eq!(binary.decoded().unwrap(), alloc::vec![0xff, 0xfe, 0x00]);
865        assert!(binary.decoded_str().is_err());
866
867        // Line-wrapped Base64 is still Base64; the decoder does not skip whitespace itself.
868        let wrapped = SignedMeterValue::new(
869            "T0NNRnx7IkZWIjoiMS4w\nIiwiUkQiOlt7IlJWIjowLjYzNn1dfXx7IlNEIjoiMzA0NDAyIn0=",
870        );
871        assert_eq!(wrapped.decoded_str().unwrap(), RECORD);
872
873        // An empty record is not a record.
874        assert!(SignedMeterValue::new("").decoded().is_err());
875        assert!(SignedMeterValue::new("   ").decoded().is_err());
876    }
877
878    #[test]
879    fn which_encoding_the_station_used_is_reported_not_absorbed() {
880        const RECORD: &str = "OCMF|{\"FV\":\"1.0\"}|{\"SD\":\"3044\"}";
881
882        // The conforming shape (2.0.1 Part 2 §2.46).
883        let encoded = SignedMeterValue::new(BASE64.encode(RECORD));
884        let record = encoded.record().unwrap();
885        assert_eq!(record.encoding, RecordEncoding::Base64);
886        assert!(record.encoding.is_conforming());
887        assert_eq!(record.as_text().unwrap(), RECORD);
888
889        // The shape a great many stations send, which is *not* conforming — a consumer that
890        // wants to tell its vendor so needs this, and cannot get it from the bytes.
891        let plain = SignedMeterValue::new(RECORD);
892        let record = plain.record().unwrap();
893        assert_eq!(record.encoding, RecordEncoding::Plain);
894        assert!(!record.encoding.is_conforming());
895        assert_eq!(record.as_text().unwrap(), RECORD);
896
897        // EDL is XML, and `<` is not in the Base64 alphabet either.
898        let xml = SignedMeterValue::new("<?xml version=\"1.0\"?><edl/>");
899        assert_eq!(xml.record().unwrap().encoding, RecordEncoding::Plain);
900
901        // `decoded` stays the shorthand, and cannot disagree with `record`.
902        assert_eq!(plain.decoded().unwrap(), plain.record().unwrap().bytes);
903        assert_eq!(encoded.decoded().unwrap(), encoded.record().unwrap().bytes);
904    }
905
906    /// The bridge has to work in both directions. A Local Controller relaying between
907    /// versions, a test harness, and a station emitting its own records all need the write
908    /// side — and a station writing the 1.6 shape by hand gets it wrong silently, because the
909    /// message is schema-valid whether or not `format` says `SignedData`.
910    #[test]
911    fn a_signed_meter_value_round_trips_through_every_version() {
912        let record = SignedMeterValue::new("T0NNRnx7fQ==")
913            .with_encoding_method("OCMF")
914            .with_signing_method("ECDSA-secp256r1-SHA256")
915            .with_public_key("MzA1OQ==");
916
917        // 1.6: a JSON document inside the `value` string, with the format that says so.
918        let sample = crate::v1_6::SampledValue::signed(&record);
919        assert_eq!(sample.format, Some(crate::v1_6::ValueFormat::SignedData));
920        assert_eq!(sample.signed_meter_value().unwrap().unwrap(), record);
921
922        // 2.1: the record and its encoding are required, the rest optional.
923        let modern = crate::v2_1::SignedMeterValue::try_from(&record).unwrap();
924        assert_eq!(SignedMeterValue::from(&modern), record);
925
926        // 2.0.1: every member is mandatory, so the same value fits — and one that came from
927        // 2.1 without a signing method does not, which is worth saying out loud.
928        let legacy = crate::v2_0_1::SignedMeterValue::try_from(&record).unwrap();
929        assert_eq!(SignedMeterValue::from(&legacy), record);
930
931        let partial = SignedMeterValue::new("T0NNRnx7fQ==").with_encoding_method("OCMF");
932        let error = crate::v2_0_1::SignedMeterValue::try_from(&partial).unwrap_err();
933        assert_eq!(error.field, "signingMethod");
934        assert_eq!(
935            error.to_string(),
936            "OCPP 2.0.1 requires signedMeterValue.signingMethod"
937        );
938        // 2.1 takes it as it stands.
939        assert!(crate::v2_1::SignedMeterValue::try_from(&partial).is_ok());
940
941        // A record with no encoding named fits nowhere typed, and says which member is missing.
942        let bare = SignedMeterValue::new("T0NNRnx7fQ==");
943        assert_eq!(
944            crate::v2_1::SignedMeterValue::try_from(&bare)
945                .unwrap_err()
946                .field,
947            "encodingMethod"
948        );
949    }
950
951    /// The 1.6 shape: a `value` string holding JSON holding Base64 holding the record.
952    #[test]
953    fn a_16_signed_data_value_is_a_json_document_in_a_string() {
954        let document = r#"{"signedMeterData":"T0NNRnx7InBhZ2luYXRpb24iOiJUMSJ9",
955             "encodingMethod":"OCMF","publicKey":"MzA1OQ=="}"#;
956        let value = SignedMeterValue::from_signed_data(document).expect("the note's document");
957        assert_eq!(value.signed_meter_data, "T0NNRnx7InBhZ2luYXRpb24iOiJUMSJ9");
958        assert_eq!(value.encoding_method.as_deref(), Some("OCMF"));
959        // signingMethod is absent from the OCA's own example, so it cannot be required.
960        assert_eq!(value.signing_method, None);
961        assert_eq!(
962            value.public_key_bytes().unwrap().unwrap(),
963            alloc::vec![0x30, 0x59]
964        );
965
966        // A measurement where a document belongs is reported, not silently dropped: the
967        // station is unbillable and does not know it.
968        assert!(SignedMeterValue::from_signed_data("12345.6").is_err());
969        assert!(SignedMeterValue::from_signed_data(r#"{"encodingMethod":"OCMF"}"#).is_err());
970    }
971}