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
use std::io::{Read, Write};

use chrono::{self, Utc, TimeZone, Datelike, Timelike};

use encoding::*;
use basic_types::*;

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: UInt16 = 1601;
const MAX_YEAR: UInt16 = 9999;

/// Data type ID 13
//
/// Holds a date/time. 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)]
pub struct DateTime {
    pub date_time: chrono::DateTime<Utc>,
}

/// DateTime encoded as 64-bit signed int
impl BinaryEncoder<DateTime> for DateTime {
    fn byte_len(&self) -> usize {
        8
    }

    fn encode<S: Write>(&self, stream: &mut S) -> EncodingResult<usize> {
        let ticks = self.checked_ticks();
        write_i64(stream, ticks)
    }

    fn decode<S: Read>(stream: &mut S) -> EncodingResult<Self> {
        let ticks = read_i64(stream)?;
        Ok(DateTime::from(ticks))
    }
}

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

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

// From ymd_hms
impl From<(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt32)> for DateTime {
    fn from(dt: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt32)) -> Self {
        let (year, month, day, hour, minute, second, nanos) = dt;
        if month < 1 || month > 12 {
            panic!("Invalid month");
        }
        if day < 1 || day > 31 {
            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.ymd(year as i32, month as u32, day as u32)
            .and_hms_nano(hour as u32, minute as u32, second as u32, nanos);
        DateTime::from(dt)
    }
}

impl From<chrono::DateTime<Utc>> for DateTime {
    fn from(date_time: chrono::DateTime<Utc>) -> Self {
        // OPC UA date time is more granular with nanos, so the value supplied is made granular too
        let year = date_time.year();
        let month = date_time.month();
        let day = date_time.day();
        let hour = date_time.hour();
        let minute = date_time.minute();
        let second = date_time.second();
        let nanos = (date_time.nanosecond() / NANOS_PER_TICK as u32) * NANOS_PER_TICK as u32;
        let date_time = Utc.ymd(year, month, day)
            .and_hms_nano(hour, minute, second, nanos);
        DateTime { date_time }
    }
}

impl From<Int64> for DateTime {
    fn from(value: Int64) -> Self {
        if value == i64::max_value() {
            // 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 = chrono::Duration::seconds(secs) + chrono::Duration::nanoseconds(nanos);
            Self::from(Self::epoch_chrono() + duration)
        }
    }
}

impl Into<Int64> for DateTime {
    fn into(self) -> Int64 {
        self.checked_ticks()
    }
}

impl Into<chrono::DateTime<Utc>> for DateTime {
    fn into(self) -> chrono::DateTime<Utc> {
        self.as_chrono()
    }
}

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

    /// 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: UInt16, month: UInt16, day: UInt16) -> DateTime {
        DateTime::ymd_hms(year, month, day, 0, 0, 0)
    }

    /// Constructs from a year, month, day, hour, minute, second
    pub fn ymd_hms(year: UInt16,
                   month: UInt16,
                   day: UInt16,
                   hour: UInt16,
                   minute: UInt16,
                   second: UInt16)
                   -> 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: UInt16,
                        month: UInt16,
                        day: UInt16,
                        hour: UInt16,
                        minute: UInt16,
                        second: UInt16,
                        nanos: UInt32) -> DateTime {
        DateTime::from((year, month, day, hour, minute, second, nanos))
    }

    /// 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_value();
        }
        nanos
    }

    /// Time as chrono
    pub fn as_chrono(&self) -> chrono::DateTime<Utc> {
        self.date_time.clone()
    }

    /// The OPC UA epoch - Jan 1 1601 00:00:00
    fn epoch_chrono() -> chrono::DateTime<Utc> {
        Utc.ymd(MIN_YEAR as i32, 1, 1).and_hms(0, 0, 0)
    }

    /// 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() -> chrono::DateTime<Utc> {
        Utc.ymd(MAX_YEAR as i32, 12, 31).and_hms(23, 59, 59)
    }

    /// Turns a duration to ticks
    fn duration_to_ticks(duration: chrono::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 = chrono::Duration::seconds(duration.num_seconds());
        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
    }
}