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
impl OcppTimestamp
Sourcepub const UNIX_EPOCH: Self
pub const UNIX_EPOCH: Self
The Unix epoch, 1970-01-01T00:00:00Z.
Sourcepub const fn from_unix(secs: i64, nanos: u32) -> Result<Self, TimestampError>
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.
Sourcepub const fn unix_seconds(&self) -> i64
pub const fn unix_seconds(&self) -> i64
Seconds since the Unix epoch, UTC, regardless of the written offset.
Sourcepub const fn subsec_nanos(&self) -> u32
pub const fn subsec_nanos(&self) -> u32
Nanoseconds within the second.
Sourcepub const fn utc_offset_minutes(&self) -> i16
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.
Sourcepub const fn with_utc_offset_minutes(
self,
offset_minutes: i16,
) -> Result<Self, TimestampError>
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.
Sourcepub fn parse_rfc3339(text: &str) -> Result<Self, TimestampError>
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?
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
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}Sourcepub fn to_rfc3339<'buf>(&self, buf: &'buf mut [u8]) -> Option<&'buf str>
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
impl Clone for OcppTimestamp
Source§fn clone(&self) -> OcppTimestamp
fn clone(&self) -> OcppTimestamp
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreimpl Copy for OcppTimestamp
Source§impl Debug for OcppTimestamp
impl Debug for OcppTimestamp
Source§impl<'de> Deserialize<'de> for OcppTimestamp
Available on crate feature serde only.
impl<'de> Deserialize<'de> for OcppTimestamp
serde only.Source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
Source§impl Display for OcppTimestamp
impl Display for OcppTimestamp
impl Eq for OcppTimestamp
Source§impl From<DateTime<FixedOffset>> for OcppTimestamp
impl From<DateTime<FixedOffset>> for OcppTimestamp
Source§fn from(value: DateTime<FixedOffset>) -> Self
fn from(value: DateTime<FixedOffset>) -> Self
Source§impl From<OcppTimestamp> for DateTime<Utc>
impl From<OcppTimestamp> for DateTime<Utc>
Source§fn from(value: OcppTimestamp) -> Self
fn from(value: OcppTimestamp) -> Self
Source§impl From<OcppTimestamp> for DateTime<FixedOffset>
impl From<OcppTimestamp> for DateTime<FixedOffset>
Source§fn from(value: OcppTimestamp) -> Self
fn from(value: OcppTimestamp) -> Self
Source§impl FromStr for OcppTimestamp
impl FromStr for OcppTimestamp
Source§impl Hash for OcppTimestamp
impl Hash for OcppTimestamp
Source§impl Ord for OcppTimestamp
impl Ord for OcppTimestamp
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialEq for OcppTimestamp
impl PartialEq for OcppTimestamp
Source§impl PartialOrd for OcppTimestamp
impl PartialOrd for OcppTimestamp
Source§impl Serialize for OcppTimestamp
Available on crate feature serde only.
impl Serialize for OcppTimestamp
serde only.