Skip to main content

opcua_kit/client/
sample.rs

1use time::OffsetDateTime;
2
3use super::{DataValue, ReadError, ua};
4use crate::{Severity, status_severity};
5
6/// One clock reported by the server, including its optional sub-tick precision.
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8pub struct SampleTimestamp {
9    /// UTC nanoseconds since 1970-01-01, from the 100 ns OPC UA DateTime field.
10    pub base_unix_nanos: i128,
11    /// Additional 10 ps intervals supplied with this clock, if present.
12    pub ten_picoseconds: Option<u16>,
13}
14
15/// The original timestamp cannot be represented exactly by the application clock.
16#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
17pub enum TimestampError {
18    /// The timestamp falls between two whole nanoseconds.
19    #[error("OPC UA timestamp has sub-nanosecond precision")]
20    Subnanosecond,
21    /// The timestamp exceeds the calendar range of `time::OffsetDateTime`.
22    #[error("OPC UA timestamp is outside the representable calendar range")]
23    OutOfRange,
24}
25
26impl SampleTimestamp {
27    pub(super) fn from_parts(base: Option<&ua::DateTime>, increments: Option<u16>) -> Option<Self> {
28        base.map(|base| Self {
29            base_unix_nanos: base.unix_timestamp_nanos(),
30            ten_picoseconds: increments,
31        })
32    }
33
34    /// Convert to UTC when the complete timestamp is exactly representable in nanoseconds.
35    pub fn to_datetime(self) -> Result<OffsetDateTime, TimestampError> {
36        // OPC UA Part 6 ยง5.2.2.17 defines any wire increment >= 10000 as 9999.
37        let increments = self.ten_picoseconds.unwrap_or(0).min(9999);
38        if !increments.is_multiple_of(100) {
39            return Err(TimestampError::Subnanosecond);
40        }
41        let nanos = self
42            .base_unix_nanos
43            .checked_add(i128::from(increments / 100))
44            .ok_or(TimestampError::OutOfRange)?;
45        OffsetDateTime::from_unix_timestamp_nanos(nanos).map_err(|_| TimestampError::OutOfRange)
46    }
47}
48
49/// One typed Value attribute, with its per-node status and optional source and server timestamps.
50#[derive(Clone, Debug, PartialEq)]
51pub struct Sample<T> {
52    /// OPC UA StatusCode, including subcodes and flags. An omitted status means Good (0).
53    pub status: u32,
54    /// A scalar of the requested wire type, present only for Good severity and a non-null value.
55    pub value: Option<T>,
56    /// Source timestamp reported by the server.
57    pub source_timestamp: Option<SampleTimestamp>,
58    /// Server timestamp reported by the server.
59    pub server_timestamp: Option<SampleTimestamp>,
60}
61
62/// Exact Good is required to qualify a meter. General reads retain qualified Good data.
63#[derive(Clone, Copy)]
64pub(super) enum Quality {
65    GoodSeverity,
66    #[cfg(feature = "cems")]
67    ExactGood,
68}
69
70impl Quality {
71    pub(super) fn accepts(self, status: u32) -> bool {
72        match self {
73            Self::GoodSeverity => status_severity(status) == Severity::Good,
74            #[cfg(feature = "cems")]
75            Self::ExactGood => status == 0,
76        }
77    }
78}
79
80impl<T: Scalar> Sample<T> {
81    /// Decode one raw result, including a member of a heterogeneous [`super::Client::read_many`] batch.
82    pub fn from_raw(raw: &DataValue) -> Result<Self, ReadError> {
83        Self::from_raw_with(raw, Quality::GoodSeverity)
84    }
85
86    pub(super) fn from_raw_with(raw: &DataValue, quality: Quality) -> Result<Self, ReadError> {
87        Self::decode_with(raw, quality, T::decode)
88    }
89}
90
91impl<T> Sample<T> {
92    pub(super) fn decode_with(
93        raw: &DataValue,
94        quality: Quality,
95        decode: impl FnOnce(&ua::Variant) -> Result<Option<T>, ReadError>,
96    ) -> Result<Self, ReadError> {
97        let status = raw.status.map_or(0, |s| s.bits());
98        let value = match raw.value.as_ref() {
99            Some(v) if quality.accepts(status) && !matches!(v, ua::Variant::Empty) => decode(v)?,
100            _ => None,
101        };
102        Ok(Self {
103            status,
104            value,
105            source_timestamp: SampleTimestamp::from_parts(
106                raw.source_timestamp.as_ref(),
107                raw.source_picoseconds,
108            ),
109            server_timestamp: SampleTimestamp::from_parts(
110                raw.server_timestamp.as_ref(),
111                raw.server_picoseconds,
112            ),
113        })
114    }
115}
116
117pub(super) fn decode_borrowed<T>(
118    raw: &DataValue,
119    decode: impl FnOnce(&ua::Variant) -> Result<Option<T>, ReadError>,
120) -> Result<Sample<T>, ReadError> {
121    Sample::decode_with(raw, Quality::GoodSeverity, decode)
122}
123
124pub(super) fn exact_datetime(time: time::OffsetDateTime) -> Option<ua::DateTime> {
125    let ns = time.unix_timestamp_nanos();
126    // UA Binary reserves both the 1601 epoch and the last second of year 9999.
127    if ns % 100 != 0
128        || ns <= -11_644_473_600_000_000_000
129        || time.unix_timestamp() >= 253_402_300_799
130    {
131        return None;
132    }
133    ua::DateTime::from_unix_timestamp_nanos(ns)
134}
135
136/// A Rust type with an exact built-in OPC UA scalar mapping.
137///
138/// Supported types are `bool`, signed and unsigned 8/16/32/64-bit integers,
139/// `f32`, `f64`, UTF-8 `String`, ByteString (`Vec<u8>`), Guid ([`uuid::Uuid`]), and DateTime ([`time::OffsetDateTime`]).
140pub trait Scalar: sealed::Decode {
141    /// Decode one Variant with this exact wire type. A null Variant or null string/bytes yields None.
142    fn from_variant(value: &ua::Variant) -> Result<Option<Self>, ReadError> {
143        if matches!(value, ua::Variant::Empty) {
144            return Ok(None);
145        }
146        Self::decode(value)
147    }
148
149    /// Encode a scalar for a Write value or a method input argument.
150    #[cfg(feature = "control")]
151    fn into_variant(self) -> Result<ua::Variant, super::ControlError> {
152        self.encode()
153    }
154}
155impl<T: sealed::Decode> Scalar for T {}
156
157/// Fixed-width numeric and Boolean types supported by arrays and raw history reads.
158pub trait FixedScalar: Scalar + sealed::Element {}
159impl<T: Scalar + sealed::Element> FixedScalar for T {}
160
161mod sealed {
162    pub trait Element {
163        const TYPE: ua::VariantScalarTypeId;
164    }
165    use super::{ReadError, ua};
166
167    pub trait Decode: Sized {
168        fn decode(value: &ua::Variant) -> Result<Option<Self>, ReadError>;
169        #[cfg(feature = "control")]
170        fn encode(self) -> Result<ua::Variant, super::super::ControlError>;
171    }
172
173    macro_rules! scalars {
174        ($($rust:ty => $wire:ident),+ $(,)?) => {$(
175            impl Element for $rust {
176                const TYPE: ua::VariantScalarTypeId = ua::VariantScalarTypeId::$wire;
177            }
178            impl Decode for $rust {
179                #[cfg(feature = "control")]
180                fn encode(self) -> Result<ua::Variant, super::super::ControlError> {
181                    Ok(ua::Variant::$wire(self))
182                }
183                fn decode(value: &ua::Variant) -> Result<Option<Self>, ReadError> {
184                    match value { ua::Variant::$wire(v) => Ok(Some(*v)), _ => Err(ReadError::ScalarTypeMismatch { expected: stringify!($wire) }) }
185                }
186            }
187        )+};
188    }
189
190    scalars! {
191        bool => Boolean, i8 => SByte, u8 => Byte, i16 => Int16, u16 => UInt16,
192        i32 => Int32, u32 => UInt32, i64 => Int64, u64 => UInt64,
193        f32 => Float, f64 => Double,
194    }
195
196    impl Decode for Vec<u8> {
197        #[cfg(feature = "control")]
198        fn encode(self) -> Result<ua::Variant, super::super::ControlError> {
199            use super::super::control::{ControlError, MAX_BYTES};
200            if self.len() > MAX_BYTES - 5 {
201                return Err(ControlError::InputLimit);
202            }
203            Ok(ua::Variant::ByteString(self.into()))
204        }
205        fn decode(value: &ua::Variant) -> Result<Option<Self>, ReadError> {
206            match value {
207                ua::Variant::ByteString(bytes) => Ok(bytes.value.clone()),
208                _ => Err(ReadError::ScalarTypeMismatch {
209                    expected: "ByteString",
210                }),
211            }
212        }
213    }
214
215    impl Decode for uuid::Uuid {
216        #[cfg(feature = "control")]
217        fn encode(self) -> Result<ua::Variant, super::super::ControlError> {
218            Ok(ua::Variant::Guid(Box::new(self)))
219        }
220        fn decode(value: &ua::Variant) -> Result<Option<Self>, ReadError> {
221            match value {
222                ua::Variant::Guid(id) => Ok(Some(**id)),
223                _ => Err(ReadError::ScalarTypeMismatch { expected: "Guid" }),
224            }
225        }
226    }
227
228    impl Decode for time::OffsetDateTime {
229        #[cfg(feature = "control")]
230        fn encode(self) -> Result<ua::Variant, super::super::ControlError> {
231            super::exact_datetime(self)
232                .map(|v| ua::Variant::DateTime(Box::new(v)))
233                .ok_or(super::super::ControlError::InvalidDateTime)
234        }
235        fn decode(value: &ua::Variant) -> Result<Option<Self>, ReadError> {
236            let ua::Variant::DateTime(date) = value else {
237                return Err(ReadError::ScalarTypeMismatch {
238                    expected: "DateTime",
239                });
240            };
241            Self::from_unix_timestamp_nanos(date.unix_timestamp_nanos())
242                .map(Some)
243                .map_err(|_| ReadError::DateTimeRange)
244        }
245    }
246
247    impl Decode for String {
248        #[cfg(feature = "control")]
249        fn encode(self) -> Result<ua::Variant, super::super::ControlError> {
250            use super::super::control::{ControlError, MAX_BYTES};
251            if self.len() > MAX_BYTES - 5 {
252                return Err(ControlError::InputLimit);
253            }
254            Ok(ua::Variant::String(self.into()))
255        }
256        fn decode(value: &ua::Variant) -> Result<Option<Self>, ReadError> {
257            match value {
258                ua::Variant::String(s) => Ok(s.value().clone()),
259                _ => Err(ReadError::ScalarTypeMismatch { expected: "String" }),
260            }
261        }
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    // Preserve the wire quality and independent clocks.
270    #[test]
271    fn typed_results_preserve_qualified_status_and_clock_evidence() {
272        let base = ua::DateTime::from_unix_timestamp_nanos(100).unwrap();
273        let value = ua::DataValue {
274            source_timestamp: Some(base),
275            source_picoseconds: Some(201),
276            server_picoseconds: Some(600),
277            ..ua::DataValue::value_only(ua::Variant::UInt64(u64::MAX))
278        };
279        let good = Sample::<u64>::from_raw(&ua::DataValue {
280            status: Some(ua::StatusCode::GoodClamped),
281            ..value.clone()
282        })
283        .unwrap();
284        assert_eq!(good.status, ua::StatusCode::GoodClamped.bits());
285        assert_eq!(good.value, Some(u64::MAX));
286        assert_eq!(good.source_timestamp.unwrap().ten_picoseconds, Some(201));
287        assert_eq!(
288            good.source_timestamp.unwrap().to_datetime(),
289            Err(TimestampError::Subnanosecond)
290        );
291        assert_eq!(good.server_timestamp, None);
292        for status in [
293            ua::StatusCode::UncertainLastUsableValue,
294            ua::StatusCode::BadNodeIdUnknown,
295        ] {
296            let raw = ua::DataValue {
297                status: Some(status),
298                ..value.clone()
299            };
300            let result = Sample::<u64>::from_raw(&raw).unwrap();
301            assert_eq!(result.status, status.bits());
302            assert_eq!(result.value, None);
303            assert_eq!(result.source_timestamp, good.source_timestamp);
304        }
305    }
306
307    #[test]
308    fn exact_wire_type_distinguishes_arrays_null_strings_and_empty_strings() {
309        let null = ua::DataValue::value_only(ua::Variant::from(ua::UAString::null()));
310        assert_eq!(Sample::<String>::from_raw(&null).unwrap().value, None);
311        let empty = ua::DataValue::value_only(ua::Variant::from(ua::UAString::from("")));
312        assert_eq!(
313            Sample::<String>::from_raw(&empty).unwrap().value.as_deref(),
314            Some("")
315        );
316        let array = vec![1u32];
317        let raw = ua::DataValue::value_only(ua::Variant::from(array));
318        assert!(matches!(
319            Sample::<u32>::from_raw(&raw),
320            Err(ReadError::ScalarTypeMismatch { expected: "UInt32" })
321        ));
322        let bits = 0xfff8_0000_0000_0001;
323        let raw = ua::DataValue::value_only(ua::Variant::Double(f64::from_bits(bits)));
324        assert_eq!(
325            Sample::<f64>::from_raw(&raw)
326                .unwrap()
327                .value
328                .unwrap()
329                .to_bits(),
330            bits
331        );
332    }
333
334    #[test]
335    fn clock_conversion_requires_the_exact_tick_and_fraction() {
336        let base = ua::DateTime::from_unix_timestamp_nanos(-100).unwrap();
337        for (increments, expected) in [(None, -100), (Some(100), -99), (Some(9900), -1)] {
338            let stamp = SampleTimestamp::from_parts(Some(&base), increments).unwrap();
339            assert_eq!(stamp.ten_picoseconds, increments);
340            assert_eq!(
341                stamp.to_datetime().unwrap().unix_timestamp_nanos(),
342                expected
343            );
344        }
345        for increments in [1, 9999, 10000, u16::MAX] {
346            let stamp = SampleTimestamp::from_parts(Some(&base), Some(increments)).unwrap();
347            assert_eq!(stamp.to_datetime(), Err(TimestampError::Subnanosecond));
348        }
349        assert!(SampleTimestamp::from_parts(None, Some(100)).is_none());
350        let future = SampleTimestamp {
351            base_unix_nanos: i128::from(i64::MAX) * 100,
352            ten_picoseconds: None,
353        };
354        assert_eq!(future.to_datetime(), Err(TimestampError::OutOfRange));
355    }
356}