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 /// `signedMeterData` is specified as Base64 (2.0.1 Part 2 §2.46) and is usually sent that
140 /// way. Stations that put the record in plain are common enough that refusing them is not
141 /// an option — and the refusal would be a quiet one, because a station whose record
142 /// "is not Base64" simply stops being billable for a reason nobody looks for.
143 ///
144 /// The two can never collide, so both are read:
145 ///
146 /// * An **OCMF** record announces itself with the ASCII prefix `OCMF|`, and `|` is not in
147 /// the Base64 alphabet. Nothing Base64 can start that way.
148 /// * Anything else containing a character outside the Base64 alphabet is likewise not
149 /// Base64 — an EDL record is XML, which starts `<`.
150 /// * What is left is Base64 and is decoded.
151 ///
152 /// Nothing is re-encoded on the way out: these are the bytes the signature covers.
153 ///
154 /// # Errors
155 ///
156 /// [`SignedDataError`] when the field is empty — an empty record is not a record.
157 pub fn decoded(&self) -> Result<Vec<u8>, SignedDataError> {
158 let text = self.signed_meter_data.trim();
159 if text.is_empty() {
160 return Err(SignedDataError::new("signedMeterData is empty"));
161 }
162 if text.starts_with(OCMF_PREFIX) {
163 return Ok(text.as_bytes().to_vec());
164 }
165 // Whitespace inside a Base64 field carries no information, so a line-wrapped record
166 // is still one; the decoder does not skip it for us.
167 let compact: Vec<u8> = text
168 .bytes()
169 .filter(|byte| !byte.is_ascii_whitespace())
170 .collect();
171 if !is_base64_alphabet(&compact) {
172 return Ok(text.as_bytes().to_vec());
173 }
174 // Padding-indifferent, so a station that omits `=` is not refused over a character
175 // that carries no information either.
176 BASE64
177 .decode(&compact)
178 .map_or_else(|_| Ok(text.as_bytes().to_vec()), Ok)
179 }
180
181 /// [`decoded`](Self::decoded) as text.
182 ///
183 /// OCMF is textual — a `|`-separated header, a JSON payload and a JSON signature — so
184 /// this is what a consumer of an OCMF record actually wants. EDL is XML, also text.
185 ///
186 /// # Errors
187 ///
188 /// [`SignedDataError`] when the field is empty, or when the record is not UTF-8 — which
189 /// means it is a binary format, and [`decoded`](Self::decoded) is the right call for it.
190 pub fn decoded_str(&self) -> Result<String, SignedDataError> {
191 String::from_utf8(self.decoded()?)
192 .map_err(|_| SignedDataError::new("the signed record is not UTF-8 text"))
193 }
194
195 /// The JSON document a 1.6 station puts in a `SignedData` sampled value.
196 ///
197 /// The inverse of
198 /// [`v1_6::SampledValue::signed_meter_value`](crate::v1_6::SampledValue::signed_meter_value),
199 /// and the reason it is here rather than in every station: getting the shape right means
200 /// knowing that 1.6 reuses 2.x's type by serialising it into a string, which nothing in
201 /// the 1.6 schema says. [`v1_6::SampledValue::signed`](crate::v1_6::SampledValue::signed)
202 /// wraps this together with the `format` the shape also requires.
203 #[must_use]
204 pub fn to_signed_data(&self) -> String {
205 // The fields are the ones this type holds and all of them are strings, so this cannot
206 // fail; a `Result` here would only make every caller unwrap it.
207 serde_json::to_string(self).unwrap_or_else(|_| String::from("{}"))
208 }
209
210 /// The public key the station claims, in both shapes the field is sent in.
211 ///
212 /// `None` when the station sent no key at all — which is normal: OCPP 2.x gates the field
213 /// on the `PublicKeyWithSignedMeterValue` configuration variable, and a key that travels
214 /// out of band is the stronger arrangement anyway.
215 ///
216 /// # Errors
217 ///
218 /// [`PublicKeyError`] when the field is not Base64, or is an `oca:` envelope this cannot
219 /// read. See [`PublicKey`] for what the two shapes are and why there are two.
220 pub fn public_key(&self) -> Option<Result<PublicKey, PublicKeyError>> {
221 self.public_key.as_deref().map(decode_public_key)
222 }
223
224 /// Just the key bytes — [`public_key`](Self::public_key) without the provenance.
225 ///
226 /// # Errors
227 ///
228 /// As [`public_key`](Self::public_key).
229 pub fn public_key_bytes(&self) -> Option<Result<Vec<u8>, PublicKeyError>> {
230 self.public_key().map(|result| result.map(|key| key.bytes))
231 }
232}
233
234/// The `publicKey` field could not be read.
235#[derive(Clone, Debug, PartialEq, Eq)]
236#[non_exhaustive]
237pub enum PublicKeyError {
238 /// The field is not Base64.
239 NotBase64,
240 /// An `oca:` envelope with fewer than four colon-separated parts.
241 MalformedEnvelope,
242 /// An `oca:` envelope naming an encoding this does not implement. The token is kept, so a
243 /// caller that knows it can still act on the printed form.
244 UnsupportedEncoding(String),
245 /// The printed key does not spell a whole number of bytes in the encoding it names.
246 MalformedKey,
247}
248
249impl fmt::Display for PublicKeyError {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 match self {
252 PublicKeyError::NotBase64 => f.write_str("publicKey is not Base64"),
253 PublicKeyError::MalformedEnvelope => {
254 f.write_str("publicKey is an oca: envelope with too few parts")
255 }
256 PublicKeyError::UnsupportedEncoding(encoding) => {
257 write!(f, "publicKey names an unsupported encoding {encoding:?}")
258 }
259 PublicKeyError::MalformedKey => f.write_str("publicKey does not spell whole bytes"),
260 }
261 }
262}
263
264#[cfg(feature = "std")]
265impl std::error::Error for PublicKeyError {}
266
267/// A signed meter value that could not be read: a 1.6 `SignedData` string that is not the
268/// JSON document the application note describes, or a `signedMeterData` field with no record
269/// in it.
270#[derive(Clone, Debug, PartialEq, Eq)]
271pub struct SignedDataError {
272 reason: String,
273}
274
275impl SignedDataError {
276 fn new(reason: impl Into<String>) -> Self {
277 Self {
278 reason: reason.into(),
279 }
280 }
281
282 /// What was wrong, for a log line an operator can act on.
283 ///
284 /// A station that *says* it is sending signed data and is not looks, from the outside,
285 /// exactly like a station sending none — and the difference only surfaces when a month of
286 /// sessions turns out to be unbillable. This is the string that stops that happening.
287 #[must_use]
288 pub fn reason(&self) -> &str {
289 &self.reason
290 }
291}
292
293impl fmt::Display for SignedDataError {
294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295 f.write_str(&self.reason)
296 }
297}
298
299#[cfg(feature = "std")]
300impl std::error::Error for SignedDataError {}
301
302/// How the `publicKey` field was written.
303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304#[non_exhaustive]
305pub enum PublicKeyShape {
306 /// Base64 over `oca:<encoding>:<content-type>:<printed key>`, as the application note
307 /// §3.2.2 specifies.
308 Envelope,
309 /// Base64 over the key printed as hexadecimal, with no envelope — the shape the same
310 /// document's own example message uses.
311 PrintedHex,
312 /// Base64 over bytes that are not text in either shape; taken as the key itself.
313 Opaque,
314}
315
316/// The public key a station claims signed a record.
317///
318/// # Two shapes, both conformant in practice
319///
320/// The OCA application note §3.2.2 specifies Base64 over a colon-separated envelope —
321/// `oca:<encoding>:<content-type>:<printed public key>` — where the last part is the key **as
322/// printed on the certified meter**, so that a customer can compare it against the label on
323/// the cabinet. For `base16` it adds that non-hexadecimal characters and a leading `0x`
324/// "SHALL be ignored", because a printed key has spaces in it.
325///
326/// The same document's example message (§5.2) then sends Base64 over plain uppercase
327/// hexadecimal with no envelope at all. A reader that implements only the specification
328/// rejects the whitepaper's own example; one that implements only the example rejects every
329/// conformant station. Both are in the field, so both are read here, and
330/// [`shape`](Self::shape) says which arrived.
331#[derive(Clone, Debug, PartialEq, Eq)]
332#[non_exhaustive]
333pub struct PublicKey {
334 /// The key bytes.
335 pub bytes: Vec<u8>,
336 /// The key as it was written — what to show a customer comparing it with the meter's
337 /// label. `None` for [`PublicKeyShape::Opaque`], where there was no text.
338 pub printed: Option<String>,
339 /// The envelope's encoding token (`base16`, `base32`, `base64`), when there was an
340 /// envelope.
341 pub encoding: Option<String>,
342 /// The envelope's content type — the key's own format, such as a curve name — when there
343 /// was an envelope.
344 pub content_type: Option<String>,
345 /// Which shape the field arrived in.
346 pub shape: PublicKeyShape,
347}
348
349/// A field the target version requires that a version-neutral value does not carry.
350///
351/// The versions disagree about which parts of a signed meter value are mandatory — 2.0.1
352/// requires all four, 2.1 requires the record and its encoding — so a value read from one
353/// version does not always fit another. Saying which field is missing is more use than
354/// refusing without a reason.
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub struct MissingField {
357 /// The member the target version requires.
358 pub field: &'static str,
359 /// The version that requires it.
360 pub version: crate::version::Version,
361}
362
363impl fmt::Display for MissingField {
364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365 write!(
366 f,
367 "OCPP {} requires signedMeterValue.{}",
368 self.version, self.field
369 )
370 }
371}
372
373#[cfg(feature = "std")]
374impl std::error::Error for MissingField {}
375
376/// How an OCMF record announces itself, in the text form (OCMF v1.0 §5).
377const OCMF_PREFIX: &str = "OCMF|";
378
379/// Whether every byte could appear in Base64 — the test that tells an encoded record from one
380/// sent in plain.
381fn is_base64_alphabet(bytes: &[u8]) -> bool {
382 bytes
383 .iter()
384 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
385}
386
387/// Reads a `publicKey` field in either of the two shapes it is sent in.
388///
389/// # Errors
390///
391/// [`PublicKeyError`] when the field is not Base64, or is an envelope this cannot read.
392pub fn decode_public_key(field: &str) -> Result<PublicKey, PublicKeyError> {
393 let raw = BASE64
394 .decode(field.trim())
395 .map_err(|_| PublicKeyError::NotBase64)?;
396
397 // Everything below only applies if the Base64 covered *text*. Anything else is the key.
398 let Ok(text) = core::str::from_utf8(&raw) else {
399 return Ok(PublicKey {
400 bytes: raw,
401 printed: None,
402 encoding: None,
403 content_type: None,
404 shape: PublicKeyShape::Opaque,
405 });
406 };
407 let text = text.trim();
408
409 if let Some(rest) = text.strip_prefix("oca:") {
410 // `oca:<encoding>:<content-type>:<printed key>`. The printed key may itself contain
411 // colons, so only the first two are separators.
412 let mut parts = rest.splitn(3, ':');
413 let (Some(encoding), Some(content_type), Some(printed)) =
414 (parts.next(), parts.next(), parts.next())
415 else {
416 return Err(PublicKeyError::MalformedEnvelope);
417 };
418 let bytes = decode_printed(printed, encoding)?;
419 return Ok(PublicKey {
420 bytes,
421 printed: Some(printed.to_owned()),
422 encoding: Some(encoding.to_owned()),
423 content_type: Some(content_type.to_owned()),
424 shape: PublicKeyShape::Envelope,
425 });
426 }
427
428 // No envelope. The example message's shape is hexadecimal text; anything else is bytes.
429 match decode_printed_hex(text) {
430 Some(bytes) => Ok(PublicKey {
431 bytes,
432 printed: Some(text.to_owned()),
433 encoding: None,
434 content_type: None,
435 shape: PublicKeyShape::PrintedHex,
436 }),
437 None => Ok(PublicKey {
438 bytes: raw,
439 printed: None,
440 encoding: None,
441 content_type: None,
442 shape: PublicKeyShape::Opaque,
443 }),
444 }
445}
446
447/// Decodes a printed key in the encoding its envelope names.
448fn decode_printed(printed: &str, encoding: &str) -> Result<Vec<u8>, PublicKeyError> {
449 // The tokens are lower-case in the note; stations are not.
450 if encoding.eq_ignore_ascii_case("base16") || encoding.eq_ignore_ascii_case("hex") {
451 decode_base16(printed).ok_or(PublicKeyError::MalformedKey)
452 } else if encoding.eq_ignore_ascii_case("base32") {
453 decode_base32(printed).ok_or(PublicKeyError::MalformedKey)
454 } else if encoding.eq_ignore_ascii_case("base64") {
455 BASE64
456 .decode(strip_ignored(printed, |byte| {
457 byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/' || byte == b'='
458 }))
459 .map_err(|_| PublicKeyError::MalformedKey)
460 } else {
461 Err(PublicKeyError::UnsupportedEncoding(encoding.to_owned()))
462 }
463}
464
465/// Keeps only the bytes the encoding's alphabet contains.
466///
467/// §3.2.2 requires it for `base16` — a key printed on a meter has spaces in it so a human can
468/// read it back — and it is harmless for the others, whose alphabets do not contain the
469/// separators either.
470fn strip_ignored(text: &str, keep: impl Fn(u8) -> bool) -> Vec<u8> {
471 text.bytes().filter(|byte| keep(*byte)).collect()
472}
473
474/// Hexadecimal, ignoring *every* character that is not a hex digit, and a leading `0x`.
475///
476/// That is what §3.2.2 requires of an envelope's `base16`: a key printed on a meter is broken
477/// up with spaces so a human can read it back, and the note says those "SHALL be ignored".
478fn decode_base16(text: &str) -> Option<Vec<u8>> {
479 let text = text.trim();
480 let text = text
481 .strip_prefix("0x")
482 .or_else(|| text.strip_prefix("0X"))
483 .unwrap_or(text);
484 let digits = strip_ignored(text, |byte| byte.is_ascii_hexdigit());
485 if digits.is_empty() || digits.len() % 2 != 0 {
486 return None;
487 }
488 let mut bytes = Vec::with_capacity(digits.len() / 2);
489 for pair in digits.chunks(2) {
490 let high = (pair[0] as char).to_digit(16)?;
491 let low = (pair[1] as char).to_digit(16)?;
492 bytes.push(u8::try_from(high * 16 + low).ok()?);
493 }
494 Some(bytes)
495}
496
497/// The same, but only when the text is *nothing but* hex digits and separators.
498///
499/// Used to recognise the un-enveloped shape, where there is no `oca:` prefix to say that the
500/// text is a printed key. Ignoring stray characters there — which is right inside an envelope
501/// that has already declared itself — would let any text at all be read as a key.
502fn decode_printed_hex(text: &str) -> Option<Vec<u8>> {
503 let trimmed = text.trim();
504 let body = trimmed
505 .strip_prefix("0x")
506 .or_else(|| trimmed.strip_prefix("0X"))
507 .unwrap_or(trimmed);
508 if body
509 .bytes()
510 .any(|byte| !byte.is_ascii_hexdigit() && !is_separator(byte))
511 {
512 return None;
513 }
514 decode_base16(trimmed)
515}
516
517/// What a printed key may be broken up with.
518const fn is_separator(byte: u8) -> bool {
519 matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'-' | b':' | b'.')
520}
521
522/// RFC 4648 base32, ignoring separators and padding.
523fn decode_base32(text: &str) -> Option<Vec<u8>> {
524 let mut accumulator: u32 = 0;
525 let mut bits = 0u32;
526 let mut bytes = Vec::new();
527 for byte in text.bytes() {
528 if byte == b'=' || is_separator(byte) {
529 continue;
530 }
531 let value = match byte {
532 b'A'..=b'Z' => byte - b'A',
533 b'a'..=b'z' => byte - b'a',
534 b'2'..=b'7' => byte - b'2' + 26,
535 _ => return None,
536 };
537 accumulator = (accumulator << 5) | u32::from(value);
538 bits += 5;
539 if bits >= 8 {
540 bits -= 8;
541 bytes.push(((accumulator >> bits) & 0xff) as u8);
542 }
543 }
544 // Whatever is left is the encoding's tail padding, and must be zero.
545 if accumulator & ((1 << bits) - 1) != 0 || bytes.is_empty() {
546 return None;
547 }
548 Some(bytes)
549}
550
551// ---------------------------------------------------------------------------
552// Per-version bridges
553// ---------------------------------------------------------------------------
554
555/// Generates the conversion from a version's generated `SignedMeterValueType`.
556///
557/// 2.0.1 makes `signingMethod` and `publicKey` mandatory and 2.1 makes both optional;
558/// `Option::from` absorbs exactly that difference and nothing else.
559#[cfg(any(feature = "v2_0_1", feature = "v2_1"))]
560macro_rules! from_generated {
561 ($module:ident) => {
562 impl From<&crate::$module::SignedMeterValue> for SignedMeterValue {
563 fn from(value: &crate::$module::SignedMeterValue) -> Self {
564 Self {
565 signed_meter_data: value.signed_meter_data.clone(),
566 encoding_method: Option::from(value.encoding_method.clone()),
567 signing_method: Option::from(value.signing_method.clone()),
568 public_key: Option::from(value.public_key.clone()),
569 }
570 }
571 }
572 };
573}
574
575#[cfg(feature = "v2_0_1")]
576from_generated!(v2_0_1);
577#[cfg(feature = "v2_1")]
578from_generated!(v2_1);
579
580#[cfg(feature = "v2_0_1")]
581impl TryFrom<&SignedMeterValue> for crate::v2_0_1::SignedMeterValue {
582 type Error = MissingField;
583
584 /// 2.0.1 makes every member of `SignedMeterValueType` mandatory, so a value that came
585 /// from 2.1 or from a 1.6 `SignedData` document may not fit — those two let a station
586 /// omit the signing method and the public key.
587 fn try_from(value: &SignedMeterValue) -> Result<Self, MissingField> {
588 let missing = |field| MissingField {
589 field,
590 version: crate::version::Version::V2_0_1,
591 };
592 Ok(Self::new(
593 value.signed_meter_data.clone(),
594 value
595 .signing_method
596 .clone()
597 .ok_or_else(|| missing("signingMethod"))?,
598 value
599 .encoding_method
600 .clone()
601 .ok_or_else(|| missing("encodingMethod"))?,
602 value
603 .public_key
604 .clone()
605 .ok_or_else(|| missing("publicKey"))?,
606 ))
607 }
608}
609
610#[cfg(feature = "v2_1")]
611impl TryFrom<&SignedMeterValue> for crate::v2_1::SignedMeterValue {
612 type Error = MissingField;
613
614 /// 2.1 requires only the record and the method it is encoded in; the signing method and
615 /// the public key became optional, because both can already be inside the record and the
616 /// key is better obtained out of band.
617 fn try_from(value: &SignedMeterValue) -> Result<Self, MissingField> {
618 let mut out = Self::new(
619 value.signed_meter_data.clone(),
620 value.encoding_method.clone().ok_or(MissingField {
621 field: "encodingMethod",
622 version: crate::version::Version::V2_1,
623 })?,
624 );
625 out.signing_method.clone_from(&value.signing_method);
626 out.public_key.clone_from(&value.public_key);
627 Ok(out)
628 }
629}
630
631#[cfg(feature = "v1_6")]
632impl crate::v1_6::SampledValue {
633 /// A sampled value carrying a signed meter value, in the shape 1.6 defines for it.
634 ///
635 /// Sets both halves of that shape: the record serialised into `value`, and the `format`
636 /// of `SignedData` without which a CSMS reads the document as a measurement. A station
637 /// writing this by hand gets the second half wrong, and nothing tells it so — the message
638 /// is schema-valid either way.
639 ///
640 /// ```
641 /// use ocpp_kit::metering::SignedMeterValue;
642 /// use ocpp_kit::v1_6::{Measurand, ReadingContext, SampledValue};
643 ///
644 /// let record = SignedMeterValue::new("T0NNRnx7fQ==").with_encoding_method("OCMF");
645 /// let sample = SampledValue::signed(&record)
646 /// .with_measurand(Measurand::EnergyActiveImportRegister)
647 /// .with_context(ReadingContext::TransactionEnd);
648 ///
649 /// // …and it reads back as what went in.
650 /// assert_eq!(sample.signed_meter_value().unwrap().unwrap(), record);
651 /// ```
652 #[must_use]
653 pub fn signed(value: &SignedMeterValue) -> Self {
654 Self::new(value.to_signed_data()).with_format(crate::v1_6::ValueFormat::SignedData)
655 }
656 /// The signed meter value this sampled value carries, if it carries one.
657 ///
658 /// 1.6 has no `signedMeterValue` field. The OCA application note (§3.2.1) reuses 2.x's
659 /// `SignedMeterValueType` by serializing the whole object into this sampled value's
660 /// `value` **string**, with `format` set to `SignedData`:
661 ///
662 /// ```json
663 /// {"format": "SignedData",
664 /// "value": "{\"signedMeterData\":\"T0NNRnx7…\",\"encodingMethod\":\"OCMF\"}",
665 /// "context": "Transaction.End", "measurand": "Energy.Active.Import.Register"}
666 /// ```
667 ///
668 /// So `value` is a string holding JSON holding Base64 holding the record, and a CSMS
669 /// reading it as a measurement — which is what the field is for everywhere else — finds a
670 /// JSON document where it expected kilowatt-hours. Every calibration-law-compliant German
671 /// 1.6 station sends its billable value this way.
672 ///
673 /// Returns `None` when `format` is not `SignedData`, and `Some(Err(_))` when it is but
674 /// the string is not the document the note describes — which is worth surfacing rather
675 /// than dropping, since the station is then unbillable and does not know it.
676 #[must_use]
677 pub fn signed_meter_value(&self) -> Option<Result<SignedMeterValue, SignedDataError>> {
678 if self.format.as_ref()? != &crate::v1_6::ValueFormat::SignedData {
679 return None;
680 }
681 Some(SignedMeterValue::from_signed_data(&self.value))
682 }
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688 use alloc::string::ToString;
689
690 /// Base64 over uppercase hexadecimal, no envelope — the shape the OCA's own example
691 /// message (§5.2) uses, and the one a reader of §3.2.2 alone would reject.
692 const EXAMPLE_KEY: &str = "MzA1OTMwMTMwNjA3MkE4NjQ4Q0UzRDAyMDEwNjA4MkE4NjQ4Q0UzRDAzMDEwNw==";
693
694 /// Base64 over `oca:base16:secp256r1:<printed key>` — what §3.2.2 specifies, spaces and
695 /// all, because the key is meant to be compared with the label on the cabinet.
696 const ENVELOPE_KEY: &str =
697 "b2NhOmJhc2UxNjpzZWNwMjU2cjE6MzAgNTkgMzAgMTMgMDYgMDcgMkEgODYgNDggQ0UgM0QgMDIgMDE=";
698
699 #[test]
700 fn both_shapes_of_the_public_key_field_are_read() {
701 let bare = decode_public_key(EXAMPLE_KEY).expect("the example message's shape");
702 assert_eq!(bare.shape, PublicKeyShape::PrintedHex);
703 assert_eq!(&bare.bytes[..4], &[0x30, 0x59, 0x30, 0x13]);
704 assert_eq!(bare.printed.as_deref().map(|key| &key[..4]), Some("3059"));
705 assert_eq!(bare.encoding, None);
706
707 let enveloped = decode_public_key(ENVELOPE_KEY).expect("the specified shape");
708 assert_eq!(enveloped.shape, PublicKeyShape::Envelope);
709 // The separators a human needs are ignored, exactly as §3.2.2 requires.
710 assert_eq!(&enveloped.bytes[..4], &[0x30, 0x59, 0x30, 0x13]);
711 assert_eq!(enveloped.encoding.as_deref(), Some("base16"));
712 assert_eq!(enveloped.content_type.as_deref(), Some("secp256r1"));
713 assert_eq!(
714 enveloped.printed.as_deref(),
715 Some("30 59 30 13 06 07 2A 86 48 CE 3D 02 01"),
716 "the printed form is what a customer compares with the meter's label"
717 );
718
719 // Both decode to the same key, which is the whole point of reading both.
720 assert_eq!(bare.bytes[..13], enveloped.bytes[..]);
721 }
722
723 #[test]
724 fn base64_over_key_bytes_is_taken_as_the_key() {
725 // Not text, so there is no printed form to show and no transformation to undo.
726 let key = decode_public_key("MFkTAQ==").expect("bytes");
727 assert_eq!(key.shape, PublicKeyShape::Opaque);
728 assert_eq!(key.bytes, alloc::vec![0x30, 0x59, 0x13, 0x01]);
729 assert_eq!(key.printed, None);
730 }
731
732 #[test]
733 fn a_leading_0x_and_an_odd_digit_count_are_handled_as_the_note_says() {
734 // "a hexadecimal prefix 0x SHALL be ignored"
735 assert_eq!(decode_base16("0x3059").unwrap(), alloc::vec![0x30, 0x59]);
736 assert_eq!(decode_base16("30-59:30.13").unwrap().len(), 4);
737 // Half a byte is not a key.
738 assert_eq!(decode_base16("305"), None);
739 // Text that merely contains hex digits is not a printed key.
740 assert_eq!(decode_printed_hex("hello dead beef"), None);
741 }
742
743 #[test]
744 fn an_unreadable_field_says_which_way_it_is_unreadable() {
745 assert_eq!(decode_public_key("!!!!"), Err(PublicKeyError::NotBase64));
746 // base64("oca:base16") — an envelope with two parts instead of four.
747 assert_eq!(
748 decode_public_key("b2NhOmJhc2UxNg=="),
749 Err(PublicKeyError::MalformedEnvelope)
750 );
751 // base64("oca:base99:x:3059")
752 assert_eq!(
753 decode_public_key("b2NhOmJhc2U5OTp4OjMwNTk="),
754 Err(PublicKeyError::UnsupportedEncoding("base99".to_string()))
755 );
756 }
757
758 #[test]
759 fn base32_and_base64_envelopes_decode_too() {
760 // base64("oca:base32:x:GBMTC===") — GBMTC base32-decodes to 0x30 0x59 0x31.
761 let field = BASE64.encode("oca:base32:x:GBMTC===");
762 assert_eq!(
763 decode_public_key(&field).unwrap().bytes,
764 alloc::vec![0x30, 0x59, 0x31]
765 );
766 let field = BASE64.encode("oca:base64:x:MFkTAQ==");
767 assert_eq!(
768 decode_public_key(&field).unwrap().bytes,
769 alloc::vec![0x30, 0x59, 0x13, 0x01]
770 );
771 }
772
773 /// The record has to come out of the transport intact, whichever way the station put it
774 /// in. Refusing the plain form would be a *quiet* failure: the station keeps sending, and
775 /// its sessions stop being billable for a reason nobody looks for.
776 #[test]
777 fn the_record_comes_out_whether_it_was_base64_or_plain() {
778 const RECORD: &str = "OCMF|{\"FV\":\"1.0\",\"RD\":[{\"RV\":0.636}]}|{\"SD\":\"304402\"}";
779
780 // Base64, as the specification says.
781 let encoded = SignedMeterValue::new(BASE64.encode(RECORD)).with_encoding_method("OCMF");
782 assert_eq!(encoded.decoded_str().unwrap(), RECORD);
783
784 // Plain, as a great many stations actually send it. `|` is not in the Base64
785 // alphabet, so the two shapes cannot be confused for one another.
786 let plain = SignedMeterValue::new(RECORD).with_encoding_method("OCMF");
787 assert_eq!(plain.decoded_str().unwrap(), RECORD);
788 assert_eq!(plain.decoded().unwrap(), RECORD.as_bytes());
789
790 // An EDL record is XML, which is not Base64 either.
791 let xml = SignedMeterValue::new("<?xml version=\"1.0\"?><edl/>");
792 assert_eq!(xml.decoded_str().unwrap(), "<?xml version=\"1.0\"?><edl/>");
793
794 // Binary after decoding: bytes are available, text is not, and the error says so.
795 let binary = SignedMeterValue::new(BASE64.encode([0xff, 0xfe, 0x00]));
796 assert_eq!(binary.decoded().unwrap(), alloc::vec![0xff, 0xfe, 0x00]);
797 assert!(binary.decoded_str().is_err());
798
799 // Line-wrapped Base64 is still Base64; the decoder does not skip whitespace itself.
800 let wrapped = SignedMeterValue::new(
801 "T0NNRnx7IkZWIjoiMS4w\nIiwiUkQiOlt7IlJWIjowLjYzNn1dfXx7IlNEIjoiMzA0NDAyIn0=",
802 );
803 assert_eq!(wrapped.decoded_str().unwrap(), RECORD);
804
805 // An empty record is not a record.
806 assert!(SignedMeterValue::new("").decoded().is_err());
807 assert!(SignedMeterValue::new(" ").decoded().is_err());
808 }
809
810 /// The bridge has to work in both directions. A Local Controller relaying between
811 /// versions, a test harness, and a station emitting its own records all need the write
812 /// side — and a station writing the 1.6 shape by hand gets it wrong silently, because the
813 /// message is schema-valid whether or not `format` says `SignedData`.
814 #[test]
815 fn a_signed_meter_value_round_trips_through_every_version() {
816 let record = SignedMeterValue::new("T0NNRnx7fQ==")
817 .with_encoding_method("OCMF")
818 .with_signing_method("ECDSA-secp256r1-SHA256")
819 .with_public_key("MzA1OQ==");
820
821 // 1.6: a JSON document inside the `value` string, with the format that says so.
822 let sample = crate::v1_6::SampledValue::signed(&record);
823 assert_eq!(sample.format, Some(crate::v1_6::ValueFormat::SignedData));
824 assert_eq!(sample.signed_meter_value().unwrap().unwrap(), record);
825
826 // 2.1: the record and its encoding are required, the rest optional.
827 let modern = crate::v2_1::SignedMeterValue::try_from(&record).unwrap();
828 assert_eq!(SignedMeterValue::from(&modern), record);
829
830 // 2.0.1: every member is mandatory, so the same value fits — and one that came from
831 // 2.1 without a signing method does not, which is worth saying out loud.
832 let legacy = crate::v2_0_1::SignedMeterValue::try_from(&record).unwrap();
833 assert_eq!(SignedMeterValue::from(&legacy), record);
834
835 let partial = SignedMeterValue::new("T0NNRnx7fQ==").with_encoding_method("OCMF");
836 let error = crate::v2_0_1::SignedMeterValue::try_from(&partial).unwrap_err();
837 assert_eq!(error.field, "signingMethod");
838 assert_eq!(
839 error.to_string(),
840 "OCPP 2.0.1 requires signedMeterValue.signingMethod"
841 );
842 // 2.1 takes it as it stands.
843 assert!(crate::v2_1::SignedMeterValue::try_from(&partial).is_ok());
844
845 // A record with no encoding named fits nowhere typed, and says which member is missing.
846 let bare = SignedMeterValue::new("T0NNRnx7fQ==");
847 assert_eq!(
848 crate::v2_1::SignedMeterValue::try_from(&bare)
849 .unwrap_err()
850 .field,
851 "encodingMethod"
852 );
853 }
854
855 /// The 1.6 shape: a `value` string holding JSON holding Base64 holding the record.
856 #[test]
857 fn a_16_signed_data_value_is_a_json_document_in_a_string() {
858 let document = r#"{"signedMeterData":"T0NNRnx7InBhZ2luYXRpb24iOiJUMSJ9",
859 "encodingMethod":"OCMF","publicKey":"MzA1OQ=="}"#;
860 let value = SignedMeterValue::from_signed_data(document).expect("the note's document");
861 assert_eq!(value.signed_meter_data, "T0NNRnx7InBhZ2luYXRpb24iOiJUMSJ9");
862 assert_eq!(value.encoding_method.as_deref(), Some("OCMF"));
863 // signingMethod is absent from the OCA's own example, so it cannot be required.
864 assert_eq!(value.signing_method, None);
865 assert_eq!(
866 value.public_key_bytes().unwrap().unwrap(),
867 alloc::vec![0x30, 0x59]
868 );
869
870 // A measurement where a document belongs is reported, not silently dropped: the
871 // station is unbillable and does not know it.
872 assert!(SignedMeterValue::from_signed_data("12345.6").is_err());
873 assert!(SignedMeterValue::from_signed_data(r#"{"encodingMethod":"OCMF"}"#).is_err());
874 }
875}