Skip to main content

OcppTimestamp

Struct OcppTimestamp 

Source
pub struct OcppTimestamp { /* private fields */ }
Expand description

A dateTime value from any OCPP version.

See this module’s documentation for the representation and its equality semantics.

Implementations§

Source§

impl OcppTimestamp

Source

pub const UNIX_EPOCH: Self

The Unix epoch, 1970-01-01T00:00:00Z.

Source

pub const fn from_unix(secs: i64, nanos: u32) -> Result<Self, TimestampError>

Builds a UTC timestamp from Unix seconds and nanoseconds.

Returns TimestampError::OutOfRange if nanos is not a valid subsecond value.

Source

pub const fn unix_seconds(&self) -> i64

Seconds since the Unix epoch, UTC, regardless of the written offset.

Source

pub const fn subsec_nanos(&self) -> u32

Nanoseconds within the second.

Source

pub const fn utc_offset_minutes(&self) -> i16

The UTC offset this timestamp was written with, in minutes. Zero for a Z timestamp, and for anything built from Unix time.

Source

pub const fn with_utc_offset_minutes( self, offset_minutes: i16, ) -> Result<Self, TimestampError>

Returns the same instant, to be written with offset_minutes instead.

Returns TimestampError::OutOfRange for an offset beyond ±24 hours.

Source

pub fn parse_rfc3339(text: &str) -> Result<Self, TimestampError>

Parses an RFC 3339 date-time, as every OCPP version’s dateTime fields carry.

Examples found in repository?
examples/unbounded_fields.rs (line 53)
11fn main() {
12    #[cfg(not(feature = "alloc"))]
13    {
14        // Uses the default capacity (1024).
15        let response: DataTransferResponse = DataTransferResponse {
16            data: Some(heapless::String::try_from("vendor payload").unwrap()),
17            status: DataTransferResponseStatus::Accepted,
18        };
19        println!(
20            "default capacity: {}",
21            response.data.as_ref().unwrap().capacity()
22        );
23
24        // Or pick a smaller one explicitly.
25        let response: DataTransferResponse<64> = DataTransferResponse {
26            data: Some(heapless::String::try_from("vendor payload").unwrap()),
27            status: DataTransferResponseStatus::Accepted,
28        };
29        println!(
30            "chosen capacity: {}",
31            response.data.as_ref().unwrap().capacity()
32        );
33    }
34
35    #[cfg(feature = "alloc")]
36    {
37        // With `alloc`, the const generic disappears entirely -- this is
38        // a plain, growable string (`alloc::string::String`, the same type
39        // as `std::string::String`).
40        let response = DataTransferResponse {
41            data: Some(String::from("vendor payload")),
42            status: DataTransferResponseStatus::Accepted,
43        };
44        println!("alloc mode, no capacity limit: {:?}", response.data);
45    }
46
47    // Timestamps are *not* in this category any more. Every OCPP version
48    // types them `{"type": "string", "format": "date-time"}` with no
49    // `maxLength`, so they used to take the 1024-byte default too -- they
50    // are now `OcppTimestamp`, which is 16 bytes and needs no parameter in
51    // either build.
52    let heartbeat = ocpp_types::v16::HeartbeatResponse {
53        current_time: ocpp_types::OcppTimestamp::parse_rfc3339("2024-01-01T00:00:00Z").unwrap(),
54    };
55    println!(
56        "timestamp: {} ({} bytes)",
57        heartbeat.current_time,
58        core::mem::size_of::<ocpp_types::OcppTimestamp>()
59    );
60}
More examples
Hide additional examples
examples/envelope.rs (line 35)
8fn main() {
9    // A CALL wraps a request with a correlation id. The wire's "Action"
10    // string is derived from `AuthorizeRequest::ACTION`, not stored
11    // redundantly -- and validated against it when parsing one back.
12    let call = Call {
13        message_id: MessageId::try_from("19223201").unwrap(),
14        payload: AuthorizeRequest {
15            id_tag: IdTag::try_from("ABC123").unwrap(),
16        },
17    };
18
19    let mut buf = [0u8; 256];
20    let len = serde_json_core::to_slice(&call, &mut buf).unwrap();
21    let json = core::str::from_utf8(&buf[..len]).unwrap();
22    println!("CALL:        {json}");
23
24    let (parsed, _): (Call<AuthorizeRequest>, usize) =
25        serde_json_core::from_slice(&buf[..len]).unwrap();
26    assert_eq!(parsed, call);
27
28    // A CALLRESULT correlates back to the CALL by `message_id` alone --
29    // there's no Action on the wire for it, since the receiver already
30    // knows (from tracking its own outstanding CALLs) what kind of
31    // response to expect.
32    // One type in both builds: `dateTime` fields are `OcppTimestamp`, not a
33    // capacity-parameterized string.
34    let current_time =
35        ocpp_types::OcppTimestamp::parse_rfc3339("2024-01-01T00:00:00Z").unwrap();
36
37    let result: CallResult<HeartbeatResponse> = CallResult {
38        message_id: MessageId::try_from("19223201").unwrap(),
39        payload: HeartbeatResponse { current_time },
40    };
41
42    let mut buf = [0u8; 256];
43    let len = serde_json_core::to_slice(&result, &mut buf).unwrap();
44    println!("CALLRESULT:  {}", core::str::from_utf8(&buf[..len]).unwrap());
45
46    // A CALLERROR carries the version's own RpcErrorCode. `errorDetails`
47    // defaults to `EmptyPayload` ({}), since the spec leaves it
48    // deliberately undefined in shape.
49    let error: CallError<RpcErrorCode> = CallError {
50        message_id: MessageId::try_from("19223201").unwrap(),
51        error_code: RpcErrorCode::NotImplemented,
52        error_description: heapless::String::try_from("unrecognized action").unwrap(),
53        error_details: EmptyPayload,
54    };
55
56    let mut buf = [0u8; 256];
57    let len = serde_json_core::to_slice(&error, &mut buf).unwrap();
58    println!("CALLERROR:   {}", core::str::from_utf8(&buf[..len]).unwrap());
59
60    // A frame with the wrong MessageTypeId or a mismatched Action is
61    // rejected outright, not silently accepted.
62    let wrong_type: Result<(Call<AuthorizeRequest>, usize), _> =
63        serde_json_core::from_str(r#"[3,"1","Authorize",{"idTag":"ABC123"}]"#);
64    println!(
65        "a CALLRESULT-shaped frame parsed as Call<T> is rejected: {}",
66        wrong_type.is_err()
67    );
68}
Source

pub fn to_rfc3339<'buf>(&self, buf: &'buf mut [u8]) -> Option<&'buf str>

Writes this timestamp as RFC 3339 into buf, returning the written slice.

buf must be at least MAX_RFC3339_LEN bytes; a shorter buffer yields None rather than a truncated timestamp.

Trait Implementations§

Source§

impl Clone for OcppTimestamp

Source§

fn clone(&self) -> OcppTimestamp

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for OcppTimestamp

Source§

impl Debug for OcppTimestamp

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for OcppTimestamp

Available on crate feature serde only.
Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for OcppTimestamp

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for OcppTimestamp

Source§

impl From<DateTime<FixedOffset>> for OcppTimestamp

Source§

fn from(value: DateTime<FixedOffset>) -> Self

Converts to this type from the input type.
Source§

impl From<DateTime<Utc>> for OcppTimestamp

Source§

fn from(value: DateTime<Utc>) -> Self

Converts to this type from the input type.
Source§

impl From<OcppTimestamp> for DateTime<Utc>

Source§

fn from(value: OcppTimestamp) -> Self

Converts to this type from the input type.
Source§

impl From<OcppTimestamp> for DateTime<FixedOffset>

Source§

fn from(value: OcppTimestamp) -> Self

Converts to this type from the input type.
Source§

impl FromStr for OcppTimestamp

Source§

type Err = TimestampError

The associated error which can be returned from parsing.
Source§

fn from_str(text: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for OcppTimestamp

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for OcppTimestamp

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for OcppTimestamp

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for OcppTimestamp

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for OcppTimestamp

Available on crate feature serde only.
Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl TryFrom<&str> for OcppTimestamp

Source§

type Error = TimestampError

The type returned in the event of a conversion error.
Source§

fn try_from(text: &str) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.