async-opcua-types 0.19.0

OPC UA data types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// OPCUA for Rust
// SPDX-License-Identifier: MPL-2.0
// Copyright (C) 2017-2024 Adam Lock

//! Contains the implementation of `DataTime`.

use std::{
    cmp::Ordering,
    fmt,
    io::{Read, Write},
    ops::{Add, Sub},
    str::FromStr,
};

use chrono::{Duration, SecondsFormat, TimeDelta, TimeZone, Timelike, Utc};
use tracing::error;

use crate::{encoding::*, Context};

const NANOS_PER_SECOND: i64 = 1_000_000_000;
const NANOS_PER_TICK: i64 = 100;
const TICKS_PER_SECOND: i64 = NANOS_PER_SECOND / NANOS_PER_TICK;

const MIN_YEAR: u16 = 1601;
const MAX_YEAR: u16 = 9999;

/// Alias for a chrono datetime at UTC, which is how OPC UA represent timestmaps.
pub type DateTimeUtc = chrono::DateTime<Utc>;

/// A date/time value. This is a wrapper around the chrono type with extra functionality
/// for obtaining ticks in OPC UA measurements, endtimes, epoch etc.
#[derive(PartialEq, Debug, Clone, Copy, Eq)]
pub struct DateTime {
    date_time: DateTimeUtc,
}

impl crate::UaNullable for DateTime {
    fn is_ua_null(&self) -> bool {
        self.is_null()
    }
}

#[cfg(feature = "json")]
mod json {
    use crate::{json::*, Error};

    use super::DateTime;

    impl JsonEncodable for DateTime {
        fn encode(
            &self,
            stream: &mut JsonStreamWriter<&mut dyn std::io::Write>,
            _ctx: &crate::Context<'_>,
        ) -> super::EncodingResult<()> {
            Ok(stream.string_value(&self.to_rfc3339())?)
        }
    }

    impl JsonDecodable for DateTime {
        fn decode(
            stream: &mut JsonStreamReader<&mut dyn std::io::Read>,
            _ctx: &Context<'_>,
        ) -> super::EncodingResult<Self> {
            let v = stream.next_str()?;
            let dt = DateTime::parse_from_rfc3339(v)
                .map_err(|e| Error::decoding(format!("Cannot parse date time \"{v}\": {e}")))?;
            Ok(dt)
        }
    }
}

#[cfg(feature = "xml")]
mod xml {
    use crate::xml::*;
    use std::io::{Read, Write};

    use super::DateTime;

    impl XmlType for DateTime {
        const TAG: &'static str = "DateTime";
    }

    impl XmlEncodable for DateTime {
        fn encode(
            &self,
            writer: &mut XmlStreamWriter<&mut dyn Write>,
            context: &Context<'_>,
        ) -> EncodingResult<()> {
            self.to_rfc3339().encode(writer, context)
        }
    }

    impl XmlDecodable for DateTime {
        fn decode(
            read: &mut XmlStreamReader<&mut dyn Read>,
            _context: &Context<'_>,
        ) -> Result<Self, Error> {
            let v = read.consume_as_text()?;
            let dt = DateTime::parse_from_rfc3339(&v)
                .map_err(|e| Error::decoding(format!("Cannot parse date time \"{v}\": {e}")))?;
            Ok(dt)
        }
    }
}

/// DateTime encoded as 64-bit signed int
impl BinaryEncodable for DateTime {
    fn byte_len(&self, _ctx: &Context<'_>) -> usize {
        8
    }

    fn encode<S: Write + ?Sized>(&self, stream: &mut S, _ctx: &Context<'_>) -> EncodingResult<()> {
        let ticks = self.checked_ticks();
        write_i64(stream, ticks)
    }
}

impl BinaryDecodable for DateTime {
    fn decode<S: Read + ?Sized>(stream: &mut S, ctx: &Context<'_>) -> EncodingResult<Self> {
        let ticks = read_i64(stream)?;
        let date_time = DateTime::from(ticks);
        // Client offset is a value that can be overridden to account for time discrepancies between client & server -
        // note perhaps it is not a good idea to do it right here but it is the lowest point to intercept DateTime values.
        Ok(date_time - ctx.options().client_offset)
    }
}

impl Default for DateTime {
    fn default() -> Self {
        DateTime::epoch()
    }
}

impl Add<Duration> for DateTime {
    type Output = Self;

    fn add(self, duration: Duration) -> Self {
        DateTime::from(self.date_time + duration)
    }
}

impl Sub<DateTime> for DateTime {
    type Output = Duration;

    fn sub(self, other: Self) -> Duration {
        self.date_time - other.date_time
    }
}

impl Sub<Duration> for DateTime {
    type Output = Self;

    fn sub(self, duration: Duration) -> Self {
        DateTime::from(self.date_time - duration)
    }
}

impl PartialOrd for DateTime {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for DateTime {
    fn cmp(&self, other: &Self) -> Ordering {
        self.date_time.cmp(&other.date_time)
    }
}

// From ymd_hms
impl From<(u16, u16, u16, u16, u16, u16)> for DateTime {
    fn from(dt: (u16, u16, u16, u16, u16, u16)) -> Self {
        let (year, month, day, hour, minute, second) = dt;
        DateTime::from((year, month, day, hour, minute, second, 0))
    }
}

// From ymd_hms
impl From<(u16, u16, u16, u16, u16, u16, u32)> for DateTime {
    fn from(dt: (u16, u16, u16, u16, u16, u16, u32)) -> Self {
        let (year, month, day, hour, minute, second, nanos) = dt;
        if !(1..=12).contains(&month) {
            panic!("Invalid month");
        }
        if !(1..=31).contains(&day) {
            panic!("Invalid day");
        }
        if hour > 23 {
            panic!("Invalid hour");
        }
        if minute > 59 {
            panic!("Invalid minute");
        }
        if second > 59 {
            panic!("Invalid second");
        }
        if nanos as i64 >= NANOS_PER_SECOND {
            panic!("Invalid nanosecond");
        }
        let dt = Utc
            .with_ymd_and_hms(
                year as i32,
                month as u32,
                day as u32,
                hour as u32,
                minute as u32,
                second as u32,
            )
            .unwrap()
            .with_nanosecond(nanos)
            .unwrap();
        DateTime::from(dt)
    }
}

impl From<DateTimeUtc> for DateTime {
    fn from(date_time: DateTimeUtc) -> Self {
        // OPC UA date time is more granular with nanos, so the value supplied is made granular too
        let nanos = (date_time.nanosecond() / NANOS_PER_TICK as u32) * NANOS_PER_TICK as u32;
        let date_time = date_time.with_nanosecond(nanos).unwrap();
        DateTime { date_time }
    }
}

impl From<i64> for DateTime {
    fn from(value: i64) -> Self {
        if value == i64::MAX {
            // Max signifies end times
            Self::endtimes()
        } else {
            let secs = value / TICKS_PER_SECOND;
            let nanos = (value - secs * TICKS_PER_SECOND) * NANOS_PER_TICK;
            let duration = TimeDelta::try_seconds(secs).unwrap() + Duration::nanoseconds(nanos);
            Self::from(Self::epoch_chrono() + duration)
        }
    }
}

impl From<DateTime> for i64 {
    fn from(value: DateTime) -> Self {
        value.checked_ticks()
    }
}

impl From<DateTime> for DateTimeUtc {
    fn from(value: DateTime) -> Self {
        value.as_chrono()
    }
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.date_time.to_rfc3339())
    }
}

impl FromStr for DateTime {
    type Err = chrono::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        DateTimeUtc::from_str(s)
            .map(DateTime::from)
            .inspect_err(|e| {
                error!("Cannot parse date {}, error = {}", s, e);
            })
    }
}

impl DateTime {
    /// Constructs from the current time
    pub fn now() -> DateTime {
        DateTime::from(Utc::now())
    }

    /// For testing purposes only. This produces a version of now with no nanoseconds so it converts
    /// in and out of rfc3999 without any loss of precision to make it easier to do comparison tests.
    #[cfg(test)]
    pub fn rfc3339_now() -> DateTime {
        use std::time::{SystemTime, UNIX_EPOCH};

        let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
        let now = DateTimeUtc::from_timestamp(duration.as_secs() as i64, 0).unwrap();
        DateTime::from(now)
    }

    /// Constructs from the current time with an offset
    pub fn now_with_offset(offset: Duration) -> DateTime {
        DateTime::from(Utc::now() + offset)
    }

    /// Creates a null date time (i.e. the epoch)
    pub fn null() -> DateTime {
        // The epoch is 0, so effectively null
        DateTime::epoch()
    }

    /// Tests if the date time is null (i.e. equal to epoch)
    pub fn is_null(&self) -> bool {
        self.ticks() == 0i64
    }

    /// Constructs a date time for the epoch
    pub fn epoch() -> DateTime {
        DateTime::from(Self::epoch_chrono())
    }

    /// Constructs a date time for the endtimes
    pub fn endtimes() -> DateTime {
        DateTime::from(Self::endtimes_chrono())
    }

    /// Returns the maximum tick value, corresponding to the end of time
    pub fn endtimes_ticks() -> i64 {
        Self::duration_to_ticks(Self::endtimes_chrono().signed_duration_since(Self::epoch_chrono()))
    }

    /// Constructs from a year, month, day
    pub fn ymd(year: u16, month: u16, day: u16) -> DateTime {
        DateTime::ymd_hms(year, month, day, 0, 0, 0)
    }

    /// Constructs from a year, month, day, hour, minute, second
    pub fn ymd_hms(
        year: u16,
        month: u16,
        day: u16,
        hour: u16,
        minute: u16,
        second: u16,
    ) -> DateTime {
        DateTime::from((year, month, day, hour, minute, second))
    }

    /// Constructs from a year, month, day, hour, minute, second, nanosecond
    pub fn ymd_hms_nano(
        year: u16,
        month: u16,
        day: u16,
        hour: u16,
        minute: u16,
        second: u16,
        nanos: u32,
    ) -> DateTime {
        DateTime::from((year, month, day, hour, minute, second, nanos))
    }

    /// Returns an RFC 3339 and ISO 8601 date and time string such as 1996-12-19T16:39:57-08:00.
    pub fn to_rfc3339(&self) -> String {
        self.date_time.to_rfc3339_opts(SecondsFormat::Millis, true)
    }

    /// Parses an RFC 3339 and ISO 8601 date and time string such as 1996-12-19T16:39:57-08:00, then returns a new DateTime
    pub fn parse_from_rfc3339(s: &str) -> Result<DateTime, chrono::ParseError> {
        let date_time = chrono::DateTime::parse_from_rfc3339(s)?;
        // Internally, the min date is going to get clipped to the epoch.
        let mut date_time = date_time.with_timezone(&Utc);
        if date_time < Self::epoch_chrono() {
            date_time = Self::epoch_chrono();
        }
        // Clip to endtimes too
        if date_time > Self::endtimes_chrono() {
            date_time = Self::endtimes_chrono();
        }

        Ok(Self { date_time })
    }

    /// Returns the time in ticks, of 100 nanosecond intervals
    pub fn ticks(&self) -> i64 {
        Self::duration_to_ticks(self.date_time.signed_duration_since(Self::epoch_chrono()))
    }

    /// To checked ticks. Function returns 0 or MAX_INT64
    /// if date exceeds valid OPC UA range
    pub fn checked_ticks(&self) -> i64 {
        let nanos = self.ticks();
        if nanos < 0 {
            return 0;
        }
        if nanos > Self::endtimes_ticks() {
            return i64::MAX;
        }
        nanos
    }

    /// Time as chrono
    pub fn as_chrono(&self) -> DateTimeUtc {
        self.date_time
    }

    /// The OPC UA epoch - Jan 1 1601 00:00:00
    fn epoch_chrono() -> DateTimeUtc {
        Utc.with_ymd_and_hms(MIN_YEAR as i32, 1, 1, 0, 0, 0)
            .unwrap()
    }

    /// The OPC UA endtimes - Dec 31 9999 23:59:59 i.e. the date after which dates are returned as MAX_INT64 ticks
    /// Spec doesn't say what happens in the last second before midnight...
    fn endtimes_chrono() -> DateTimeUtc {
        Utc.with_ymd_and_hms(MAX_YEAR as i32, 12, 31, 23, 59, 59)
            .unwrap()
    }

    /// Turns a duration to ticks
    fn duration_to_ticks(duration: Duration) -> i64 {
        // We can't directly ask for nanos because it will exceed i64,
        // so we have to subtract the total seconds before asking for the nano portion
        let seconds_part = TimeDelta::try_seconds(duration.num_seconds()).unwrap();
        let seconds = seconds_part.num_seconds();
        let nanos = (duration - seconds_part).num_nanoseconds().unwrap();
        // Put it back together in ticks
        seconds * TICKS_PER_SECOND + nanos / NANOS_PER_TICK
    }
}