Skip to main content

ocpp_kit/
types.rs

1//! Primitive types shared by every OCPP version.
2
3use alloc::borrow::ToOwned;
4use alloc::format;
5use alloc::string::String;
6use core::fmt;
7use core::str::FromStr;
8
9use serde::{Deserialize, Serialize};
10
11use crate::validate::{Validate, ValidationPath, Violations};
12
13// ---------------------------------------------------------------------------
14// DateTime
15// ---------------------------------------------------------------------------
16
17/// An OCPP `dateTime`: an instant, serialized as RFC 3339 with an explicit offset.
18///
19/// Parsing accepts more than it emits, because the field is full of stations that omit the
20/// offset or use a space separator. Which of those are tolerated is decided by
21/// [`DecodeOptions::datetime`](crate::decode::DecodeOptions::datetime): the strict
22/// `Deserialize` impl below requires an offset, and the decoder repairs the input first when
23/// leniency is enabled. Serialization always emits UTC (`…Z`).
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub struct DateTime(jiff::Timestamp);
26
27impl DateTime {
28    /// The Unix epoch.
29    pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
30
31    #[must_use]
32    /// Wraps a `jiff` timestamp.
33    pub const fn from_timestamp(timestamp: jiff::Timestamp) -> Self {
34        Self(timestamp)
35    }
36
37    #[must_use]
38    /// The underlying `jiff` timestamp.
39    pub const fn timestamp(self) -> jiff::Timestamp {
40        self.0
41    }
42
43    /// The current time from the system clock.
44    #[cfg(feature = "std")]
45    #[must_use]
46    pub fn now() -> Self {
47        Self(jiff::Timestamp::now())
48    }
49
50    /// Parses an RFC 3339 timestamp. The offset is mandatory.
51    pub fn parse(text: &str) -> Result<Self, DateTimeError> {
52        jiff::Timestamp::from_str(text)
53            .map(Self)
54            .map_err(|_| DateTimeError {
55                input: text.to_owned(),
56            })
57    }
58
59    /// Parses leniently: also accepts a missing offset (interpreted as UTC) and a space
60    /// instead of `T`, both of which occur in the field.
61    ///
62    /// Reachable from the decoder via
63    /// [`DateTimeLeniency`](crate::decode::DateTimeLeniency).
64    pub fn parse_lenient(text: &str) -> Result<Self, DateTimeError> {
65        if let Ok(value) = Self::parse(text) {
66            return Ok(value);
67        }
68        let normalized = normalize_datetime(text);
69        Self::parse(&normalized)
70    }
71}
72
73/// Rewrites the common non-conforming timestamp spellings into strict RFC 3339.
74///
75/// Returns the input unchanged when it does not look like a bare local timestamp.
76#[must_use]
77pub fn normalize_datetime(text: &str) -> String {
78    let trimmed = text.trim();
79    let with_t = match trimmed.find(' ') {
80        Some(index) if !trimmed.contains('T') => {
81            let mut s = trimmed.to_owned();
82            s.replace_range(index..=index, "T");
83            s
84        }
85        _ => trimmed.to_owned(),
86    };
87    let has_offset = with_t.ends_with('Z')
88        || with_t.ends_with('z')
89        // `+01:00` / `-05:00`, but not the date's own separators.
90        || with_t.rfind(['+', '-']).is_some_and(|i| i > 10);
91    if has_offset {
92        with_t
93    } else {
94        format!("{with_t}Z")
95    }
96}
97
98impl fmt::Display for DateTime {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(f, "{}", self.0)
101    }
102}
103
104impl From<jiff::Timestamp> for DateTime {
105    fn from(value: jiff::Timestamp) -> Self {
106        Self(value)
107    }
108}
109
110impl From<DateTime> for jiff::Timestamp {
111    fn from(value: DateTime) -> Self {
112        value.0
113    }
114}
115
116impl FromStr for DateTime {
117    type Err = DateTimeError;
118
119    fn from_str(text: &str) -> Result<Self, Self::Err> {
120        Self::parse(text)
121    }
122}
123
124impl Serialize for DateTime {
125    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
126        ser.collect_str(&self.0)
127    }
128}
129
130impl<'de> Deserialize<'de> for DateTime {
131    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
132        struct Visitor;
133
134        impl serde::de::Visitor<'_> for Visitor {
135            type Value = DateTime;
136
137            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138                f.write_str("an RFC 3339 date-time with an offset")
139            }
140
141            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<DateTime, E> {
142                DateTime::parse(text).map_err(E::custom)
143            }
144        }
145
146        // A visitor rather than `<&str>::deserialize`: a JSON string containing an escape
147        // cannot be borrowed, and asking for a borrowed one would report that as
148        // "invalid type: string" — a *type* violation, when the value is really the problem.
149        de.deserialize_str(Visitor)
150    }
151}
152
153impl Validate for DateTime {
154    fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
155}
156
157/// A timestamp that is not valid RFC 3339.
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct DateTimeError {
160    input: String,
161}
162
163impl fmt::Display for DateTimeError {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        write!(
166            f,
167            "{:?} is not an RFC 3339 date-time with an offset",
168            self.input
169        )
170    }
171}
172
173#[cfg(feature = "std")]
174impl std::error::Error for DateTimeError {}
175
176// ---------------------------------------------------------------------------
177// Decimal
178// ---------------------------------------------------------------------------
179
180pub use crate::decimal::{Decimal, ParseDecimalError};
181
182// ---------------------------------------------------------------------------
183// CustomData
184// ---------------------------------------------------------------------------
185
186/// The OCPP 2.x `CustomDataType` extension point.
187///
188/// This is the one object the schemas deliberately leave open, so the unrecognised members
189/// are kept in [`extra`](Self::extra) instead of being dropped — a Local Controller can relay
190/// them and a CSMS can round-trip them.
191#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
192pub struct CustomData {
193    /// Vendor identifier, at most 255 characters.
194    #[serde(rename = "vendorId")]
195    pub vendor_id: String,
196    /// Everything else the vendor put in this object.
197    #[serde(flatten)]
198    pub extra: serde_json::Map<String, serde_json::Value>,
199}
200
201impl CustomData {
202    /// Creates custom data for one vendor.
203    #[must_use]
204    pub fn new(vendor_id: impl Into<String>) -> Self {
205        Self {
206            vendor_id: vendor_id.into(),
207            extra: serde_json::Map::new(),
208        }
209    }
210
211    /// Adds one custom member.
212    #[must_use]
213    pub fn with(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
214        self.extra.insert(key.into(), value.into());
215        self
216    }
217}
218
219impl Validate for CustomData {
220    fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
221        path.push_key("vendorId");
222        crate::validate::string(&self.vendor_id, None, Some(255), path, out);
223        path.pop();
224    }
225}
226
227// ---------------------------------------------------------------------------
228// Identity
229// ---------------------------------------------------------------------------
230
231/// A Charging Station identity.
232///
233/// Carried as the last segment of the WebSocket URL path and, under security profiles 1 and
234/// 2, as the HTTP Basic user name. At most 48 characters, and it must not contain `:`
235/// because that would make the Basic credentials ambiguous (A00.FR.204).
236#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
237#[serde(transparent)]
238pub struct Identity(String);
239
240/// The maximum length of a Charging Station identity, in characters.
241pub const IDENTITY_MAX_LEN: usize = 48;
242
243impl Identity {
244    /// Validates and wraps an identity.
245    pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
246        let value = value.into();
247        if value.is_empty() {
248            return Err(IdentityError::Empty);
249        }
250        let len = value.chars().count();
251        if len > IDENTITY_MAX_LEN {
252            return Err(IdentityError::TooLong(len));
253        }
254        // A00.FR.204 — the identity doubles as the Basic-Auth user name.
255        if value.contains(':') {
256            return Err(IdentityError::Colon);
257        }
258        if value.chars().any(char::is_control) {
259            return Err(IdentityError::Control);
260        }
261        Ok(Self(value))
262    }
263
264    #[must_use]
265    /// The identity as a string slice.
266    pub fn as_str(&self) -> &str {
267        &self.0
268    }
269
270    /// Unwraps the identity.
271    #[must_use]
272    pub fn into_string(self) -> String {
273        self.0
274    }
275}
276
277impl fmt::Display for Identity {
278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279        f.write_str(&self.0)
280    }
281}
282
283impl FromStr for Identity {
284    type Err = IdentityError;
285
286    fn from_str(value: &str) -> Result<Self, Self::Err> {
287        Self::new(value)
288    }
289}
290
291impl<'de> Deserialize<'de> for Identity {
292    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
293        let value = String::deserialize(de)?;
294        Self::new(value).map_err(serde::de::Error::custom)
295    }
296}
297
298/// Why an identity was rejected.
299#[derive(Clone, Copy, Debug, PartialEq, Eq)]
300#[non_exhaustive]
301pub enum IdentityError {
302    /// The identity is empty.
303    Empty,
304    /// Longer than [`IDENTITY_MAX_LEN`] characters.
305    TooLong(usize),
306    /// Contains `:`, which HTTP Basic authentication cannot represent (A00.FR.204).
307    Colon,
308    /// Contains a control character, which cannot appear in a URL path segment.
309    Control,
310}
311
312impl fmt::Display for IdentityError {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        match self {
315            IdentityError::Empty => f.write_str("charging station identity is empty"),
316            IdentityError::TooLong(len) => {
317                write!(
318                    f,
319                    "charging station identity is {len} characters, maximum is {IDENTITY_MAX_LEN}"
320                )
321            }
322            IdentityError::Colon => {
323                f.write_str("charging station identity must not contain ':' (A00.FR.204)")
324            }
325            IdentityError::Control => {
326                f.write_str("charging station identity contains a control character")
327            }
328        }
329    }
330}
331
332#[cfg(feature = "std")]
333impl std::error::Error for IdentityError {}
334
335// ---------------------------------------------------------------------------
336// MessageId
337// ---------------------------------------------------------------------------
338
339/// The maximum length of an OCPP-J message id, in characters (Part 4 §4.1.1).
340pub const MESSAGE_ID_MAX_LEN: usize = 36;
341
342/// An OCPP-J `MessageId` (1.6J calls it `UniqueId`): a string of at most 36 characters that
343/// correlates a `CALL` with its `CALLRESULT` / `CALLERROR`.
344#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
345#[serde(transparent)]
346pub struct MessageId(String);
347
348impl MessageId {
349    /// Validates and wraps a message id.
350    pub fn new(value: impl Into<String>) -> Result<Self, MessageIdError> {
351        let value = value.into();
352        if value.is_empty() {
353            return Err(MessageIdError::Empty);
354        }
355        let len = value.chars().count();
356        if len > MESSAGE_ID_MAX_LEN {
357            return Err(MessageIdError::TooLong(len));
358        }
359        Ok(Self(value))
360    }
361
362    /// Wraps an id exactly as a peer sent it, including one that is too long.
363    ///
364    /// The framing layer must echo the id it received verbatim or the peer cannot correlate
365    /// the answer, so length is *reported* — see [`is_conforming`](Self::is_conforming) —
366    /// rather than silently changed.
367    #[must_use]
368    pub fn from_wire(value: &str) -> Self {
369        Self(value.to_owned())
370    }
371
372    /// Whether the id respects the 36-character limit.
373    #[must_use]
374    pub fn is_conforming(&self) -> bool {
375        !self.0.is_empty() && self.0.chars().count() <= MESSAGE_ID_MAX_LEN
376    }
377
378    /// Wraps a value, truncating it to [`MESSAGE_ID_MAX_LEN`] characters.
379    ///
380    /// For ids this peer generates, so an over-long prefix cannot produce an invalid id.
381    #[must_use]
382    pub fn truncating(value: &str) -> Self {
383        match value.char_indices().nth(MESSAGE_ID_MAX_LEN) {
384            Some((cut, _)) => Self(value[..cut].to_owned()),
385            None => Self(value.to_owned()),
386        }
387    }
388
389    /// The id OCPP 2.x prescribes when the incoming `MessageId` itself could not be read
390    /// (Part 4 §4.1.1).
391    #[must_use]
392    pub fn unreadable() -> Self {
393        Self("-1".to_owned())
394    }
395
396    /// The id as a string slice.
397    #[must_use]
398    pub fn as_str(&self) -> &str {
399        &self.0
400    }
401
402    /// Unwraps the id.
403    #[must_use]
404    pub fn into_string(self) -> String {
405        self.0
406    }
407}
408
409impl fmt::Display for MessageId {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        f.write_str(&self.0)
412    }
413}
414
415impl FromStr for MessageId {
416    type Err = MessageIdError;
417
418    fn from_str(value: &str) -> Result<Self, Self::Err> {
419        Self::new(value)
420    }
421}
422
423impl<'de> Deserialize<'de> for MessageId {
424    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
425        let value = String::deserialize(de)?;
426        Self::new(value).map_err(serde::de::Error::custom)
427    }
428}
429
430/// Why a message id was rejected.
431#[derive(Clone, Copy, Debug, PartialEq, Eq)]
432#[non_exhaustive]
433pub enum MessageIdError {
434    /// The id is empty.
435    Empty,
436    /// Longer than [`MESSAGE_ID_MAX_LEN`] characters.
437    TooLong(usize),
438}
439
440impl fmt::Display for MessageIdError {
441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442        match self {
443            MessageIdError::Empty => f.write_str("message id is empty"),
444            MessageIdError::TooLong(len) => {
445                write!(
446                    f,
447                    "message id is {len} characters, maximum is {MESSAGE_ID_MAX_LEN}"
448                )
449            }
450        }
451    }
452}
453
454#[cfg(feature = "std")]
455impl std::error::Error for MessageIdError {}
456
457/// Source of outgoing [`MessageId`]s.
458///
459/// Pluggable because constrained devices cannot afford an entropy source, and a Local
460/// Controller needs ids that provably cannot collide with the CSMS's (Part 4 §6.4).
461///
462/// # The uniqueness rule
463///
464/// Part 4 §4.1.4 is stricter than it first looks: a `MessageId` must differ from every id the
465/// same sender has used for a `CALL` or a `SEND` **on any WebSocket connection under the same
466/// Charging Station identity** — not merely within one connection. A retransmission of the
467/// same message *may* reuse its id, and nothing else may.
468pub trait IdGenerator {
469    /// Produces the next id.
470    ///
471    /// Implementations must satisfy the uniqueness rule above.
472    fn next_id(&mut self) -> MessageId;
473}
474
475/// A random generator: a version 4 UUID per id, 36 characters exactly.
476///
477/// The default wherever an entropy source is available. 122 random bits make a collision
478/// across reboots — which is what Part 4 §4.1.4 actually forbids — not worth reasoning about.
479///
480/// It also carries a counter, which only matters in the case that should never happen: if the
481/// operating system's entropy source fails, the ids fall back to being *distinct* rather than
482/// random. A repeating `MessageId` is the one outcome §4.1.4 rules out, and it is exactly what
483/// a fixed fallback value would produce.
484#[cfg(feature = "getrandom")]
485#[derive(Clone, Copy, Debug, Default)]
486pub struct RandomIds {
487    counter: u64,
488}
489
490#[cfg(feature = "getrandom")]
491impl RandomIds {
492    /// A generator drawing from the operating system's entropy source.
493    #[must_use]
494    pub fn new() -> Self {
495        Self { counter: 0 }
496    }
497}
498
499#[cfg(feature = "getrandom")]
500impl IdGenerator for RandomIds {
501    fn next_id(&mut self) -> MessageId {
502        self.counter = self.counter.wrapping_add(1);
503        MessageId(uuid_v4().unwrap_or_else(|| degraded_uuid(self.counter)))
504    }
505}
506
507/// A random version 4 UUID, in the canonical 36-character hyphenated form.
508///
509/// `None` when the operating system's entropy source failed — which on a supported target
510/// means it is not merely low on entropy but unavailable. There is no safe constant to return:
511/// two OCPP identifiers are required to be unique across a Charging Station's whole lifetime —
512/// the `MessageId` (Part 4 §4.1.4) and the `transactionId` (E01.FR.08, which spells out "even
513/// when the Charging Station is rebooted, repaired, firmware is updated etc." and recommends
514/// UUIDs by name) — so a fixed fallback would break precisely the guarantee callers came for.
515/// Callers that must produce *something* use a counter instead; see [`RandomIds`].
516#[cfg(feature = "getrandom")]
517#[must_use]
518pub fn uuid_v4() -> Option<String> {
519    let mut bytes = [0u8; 16];
520    getrandom::fill(&mut bytes).ok()?;
521    bytes[6] = (bytes[6] & 0x0F) | 0x40; // version 4
522    bytes[8] = (bytes[8] & 0x3F) | 0x80; // variant RFC 4122
523    Some(hyphenate(bytes))
524}
525
526/// A UUID-shaped id built from a counter, for the case where entropy is unavailable.
527///
528/// Version 4 is *not* claimed — the version nibble is `8`, which no RFC 4122 version uses —
529/// so a reader can tell at a glance that these ids are unique within a process run and nothing
530/// more. Across a reboot they repeat, which is why this is a last resort and not a mode.
531#[cfg(feature = "getrandom")]
532#[must_use]
533fn degraded_uuid(counter: u64) -> String {
534    let mut bytes = [0u8; 16];
535    bytes[..8].copy_from_slice(&counter.to_be_bytes());
536    bytes[6] = (bytes[6] & 0x0F) | 0x80;
537    bytes[8] = (bytes[8] & 0x3F) | 0x80;
538    hyphenate(bytes)
539}
540
541/// Renders 16 bytes as `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`.
542#[cfg(feature = "getrandom")]
543fn hyphenate(bytes: [u8; 16]) -> String {
544    const HEX: &[u8; 16] = b"0123456789abcdef";
545    let mut out = [0u8; 36];
546    let mut index = 0;
547    for (position, byte) in bytes.iter().enumerate() {
548        if matches!(position, 4 | 6 | 8 | 10) {
549            out[index] = b'-';
550            index += 1;
551        }
552        out[index] = HEX[usize::from(byte >> 4)];
553        out[index + 1] = HEX[usize::from(byte & 0x0F)];
554        index += 2;
555    }
556    // Every byte written is ASCII hex or `-`.
557    core::str::from_utf8(&out)
558        .unwrap_or("00000000-0000-8000-8000-000000000000")
559        .to_owned()
560}
561
562/// A counter-based generator: `<prefix><counter>`, base-36 encoded.
563///
564/// For targets with no entropy source. It satisfies Part 4 §4.1.4 **only if the prefix is
565/// different on every boot** — a persisted boot counter, a serial number plus a session
566/// number, anything that does not repeat. With a constant prefix the ids restart at zero
567/// after a power cut and collide with the ones used before it, which is exactly what §4.1.4
568/// forbids and what makes a CSMS mismatch a response to the wrong request.
569///
570/// A Local Controller uses the prefix for a second purpose: keeping its own ids disjoint from
571/// the CSMS's (Part 4 §6.4).
572#[derive(Clone, Debug)]
573pub struct CounterIds {
574    prefix: String,
575    next: u64,
576}
577
578impl CounterIds {
579    /// Starts a generator with the given prefix. Read the type's documentation first: the
580    /// prefix is what makes the ids unique across reboots.
581    #[must_use]
582    pub fn with_prefix(prefix: impl Into<String>) -> Self {
583        Self {
584            prefix: prefix.into(),
585            next: 0,
586        }
587    }
588}
589
590impl Default for CounterIds {
591    fn default() -> Self {
592        Self::with_prefix("")
593    }
594}
595
596impl IdGenerator for CounterIds {
597    fn next_id(&mut self) -> MessageId {
598        let value = self.next;
599        self.next = self.next.wrapping_add(1);
600        let mut digits = [0u8; 13];
601        let mut index = digits.len();
602        let mut remaining = value;
603        loop {
604            index -= 1;
605            let digit = u8::try_from(remaining % 36).unwrap_or(0);
606            digits[index] = if digit < 10 {
607                b'0' + digit
608            } else {
609                b'a' + digit - 10
610            };
611            remaining /= 36;
612            if remaining == 0 {
613                break;
614            }
615        }
616        let suffix = core::str::from_utf8(&digits[index..]).unwrap_or("0");
617        MessageId::truncating(&format!("{}{suffix}", self.prefix))
618    }
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624
625    #[test]
626    fn identity_rejects_colon_per_a00_fr_204() {
627        assert_eq!(Identity::new("cs:1"), Err(IdentityError::Colon));
628        assert!(Identity::new("CS-0001").is_ok());
629        assert_eq!(
630            Identity::new("x".repeat(49)),
631            Err(IdentityError::TooLong(49))
632        );
633    }
634
635    #[test]
636    fn message_id_truncates_to_36_characters() {
637        let id = MessageId::truncating(&"a".repeat(80));
638        assert_eq!(id.as_str().chars().count(), 36);
639    }
640
641    #[test]
642    fn counter_ids_are_unique_and_prefixed() {
643        let mut ids = CounterIds::with_prefix("lc-");
644        assert_eq!(ids.next_id().as_str(), "lc-0");
645        assert_eq!(ids.next_id().as_str(), "lc-1");
646        for _ in 0..40 {
647            ids.next_id();
648        }
649        assert_eq!(ids.next_id().as_str(), "lc-16");
650    }
651
652    #[cfg(feature = "getrandom")]
653    #[test]
654    fn random_ids_are_uuids_and_do_not_repeat() {
655        let mut ids = RandomIds::new();
656        let mut seen = std::collections::HashSet::new();
657        for _ in 0..256 {
658            let id = ids.next_id();
659            assert_eq!(id.as_str().len(), 36, "{id}");
660            assert!(id.is_conforming());
661            assert_eq!(&id.as_str()[14..15], "4", "version nibble: {id}");
662            assert!(seen.insert(id.into_string()));
663        }
664    }
665
666    #[test]
667    fn datetime_leniency_matches_field_behaviour() {
668        assert!(DateTime::parse("2024-01-01T10:00:00").is_err());
669        assert_eq!(
670            DateTime::parse_lenient("2024-01-01T10:00:00").unwrap(),
671            DateTime::parse("2024-01-01T10:00:00Z").unwrap()
672        );
673        assert_eq!(
674            DateTime::parse_lenient("2024-01-01 10:00:00").unwrap(),
675            DateTime::parse("2024-01-01T10:00:00Z").unwrap()
676        );
677        assert_eq!(
678            DateTime::parse_lenient("2024-01-01T10:00:00+02:00").unwrap(),
679            DateTime::parse("2024-01-01T08:00:00Z").unwrap()
680        );
681    }
682}