Skip to main content

opcua_kit/ua/
scalar.rs

1use super::{BinaryDecodable, BinaryEncodable, Context, ObjectId, binary};
2use base64::{Engine, engine::general_purpose::STANDARD};
3use std::{
4    fmt,
5    io::{Read, Write},
6    str::FromStr,
7};
8
9/// Full 32-bit OPC UA status, including quality and information bits.
10#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
11pub struct StatusCode(pub(super) u32);
12impl StatusCode {
13    pub fn bits(self) -> u32 {
14        self.0
15    }
16    pub fn is_good(self) -> bool {
17        self.0 >> 30 == 0
18    }
19    pub fn is_bad(self) -> bool {
20        self.0 >> 31 != 0
21    }
22}
23impl From<u32> for StatusCode {
24    fn from(n: u32) -> Self {
25        Self(n)
26    }
27}
28impl fmt::Display for StatusCode {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self.name() {
31            Some(name) => write!(f, "{name} (0x{:08X})", self.0),
32            None => write!(f, "0x{:08X}", self.0),
33        }
34    }
35}
36impl std::error::Error for StatusCode {}
37impl From<std::io::Error> for StatusCode {
38    fn from(_: std::io::Error) -> Self {
39        Self::BadDecodingError
40    }
41}
42
43macro_rules! wrapped {
44    ($ty:ident, $base:ty) => {
45        impl BinaryEncodable for $ty {
46            fn encode<W: Write + ?Sized>(
47                &self,
48                w: &mut W,
49                c: &Context<'_>,
50            ) -> Result<(), StatusCode> {
51                self.0.encode(w, c)
52            }
53        }
54        impl BinaryDecodable for $ty {
55            fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
56                Ok(Self(<$base>::decode(r, c)?))
57            }
58        }
59    };
60}
61wrapped!(StatusCode, u32);
62
63/// Number of 100 ns ticks since 1601-01-01 UTC, as transmitted.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
65pub struct DateTime(i64);
66wrapped!(DateTime, i64);
67impl From<i64> for DateTime {
68    fn from(ticks: i64) -> Self {
69        Self(ticks)
70    }
71}
72impl DateTime {
73    pub fn null() -> Self {
74        Self::default()
75    }
76    /// 100 ns intervals between the UA epoch in 1601 and the Unix epoch.
77    const UNIX_EPOCH_TICKS: i128 = 116_444_736_000_000_000;
78
79    /// Construct a wire DateTime when the instant fits exactly on a 100 ns tick.
80    pub fn from_unix_timestamp_nanos(nanos: i128) -> Option<Self> {
81        if nanos % 100 != 0 {
82            return None;
83        }
84        i64::try_from(nanos / 100 + Self::UNIX_EPOCH_TICKS)
85            .ok()
86            .map(Self)
87    }
88
89    /// Exact timestamp in Unix nanoseconds, including values outside the application calendar.
90    pub fn unix_timestamp_nanos(self) -> i128 {
91        (i128::from(self.0) - Self::UNIX_EPOCH_TICKS) * 100
92    }
93
94    pub fn ticks(self) -> i64 {
95        self.0
96    }
97    pub fn endtimes() -> Self {
98        Self(i64::MAX)
99    }
100    pub fn now() -> Self {
101        let ns = time::OffsetDateTime::now_utc().unix_timestamp_nanos();
102        Self((ns / 100 + Self::UNIX_EPOCH_TICKS) as i64)
103    }
104}
105
106/// A nullable OPC UA UTF-8 string. Use `value` to distinguish absent and empty text.
107#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
108pub struct UAString(Option<String>);
109impl UAString {
110    pub fn null() -> Self {
111        Self(None)
112    }
113    pub fn len(&self) -> usize {
114        self.as_ref().len()
115    }
116    pub fn value(&self) -> &Option<String> {
117        &self.0
118    }
119    pub fn is_null(&self) -> bool {
120        self.0.is_none()
121    }
122    pub fn is_empty(&self) -> bool {
123        self.as_ref().is_empty()
124    }
125}
126impl AsRef<str> for UAString {
127    fn as_ref(&self) -> &str {
128        self.0.as_deref().unwrap_or_default()
129    }
130}
131impl From<String> for UAString {
132    fn from(s: String) -> Self {
133        Self(Some(s))
134    }
135}
136impl From<&str> for UAString {
137    fn from(s: &str) -> Self {
138        s.to_owned().into()
139    }
140}
141impl fmt::Display for UAString {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(self.as_ref())
144    }
145}
146impl BinaryEncodable for UAString {
147    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
148        binary::write_bytes(self.0.as_deref().map(str::as_bytes), w, c)
149    }
150}
151impl BinaryDecodable for UAString {
152    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
153        Ok(Self(
154            binary::read_bytes(r, c, c.max_string_length)?
155                .map(String::from_utf8)
156                .transpose()
157                .map_err(|_| StatusCode::BadDecodingError)?,
158        ))
159    }
160}
161#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
162/// Nullable opaque bytes. An empty byte string has a present, zero-length value.
163pub struct ByteString {
164    pub value: Option<Vec<u8>>,
165}
166impl ByteString {
167    pub fn null() -> Self {
168        Self::default()
169    }
170    pub fn len(&self) -> usize {
171        self.as_ref().len()
172    }
173    pub fn is_empty(&self) -> bool {
174        self.as_ref().is_empty()
175    }
176    pub fn is_null_or_empty(&self) -> bool {
177        self.is_empty()
178    }
179}
180impl AsRef<[u8]> for ByteString {
181    fn as_ref(&self) -> &[u8] {
182        self.value.as_deref().unwrap_or_default()
183    }
184}
185impl From<Vec<u8>> for ByteString {
186    fn from(v: Vec<u8>) -> Self {
187        Self { value: Some(v) }
188    }
189}
190impl From<&[u8]> for ByteString {
191    fn from(v: &[u8]) -> Self {
192        v.to_vec().into()
193    }
194}
195impl BinaryEncodable for ByteString {
196    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
197        binary::write_bytes(self.value.as_deref(), w, c)
198    }
199}
200impl BinaryDecodable for ByteString {
201    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
202        Ok(Self {
203            value: binary::read_bytes(r, c, c.max_byte_string_length)?,
204        })
205    }
206}
207/// A UUID encoded with UA Binary field byte order.
208pub type Guid = uuid::Uuid;
209impl BinaryEncodable for Guid {
210    fn encode<W: Write + ?Sized>(&self, w: &mut W, _: &Context<'_>) -> Result<(), StatusCode> {
211        w.write_all(&self.to_bytes_le())
212            .map_err(|_| StatusCode::BadEncodingError)
213    }
214}
215impl BinaryDecodable for Guid {
216    fn decode<R: Read + ?Sized>(r: &mut R, _: &Context<'_>) -> Result<Self, StatusCode> {
217        let mut bytes = [0; 16];
218        r.read_exact(&mut bytes)?;
219        Ok(Self::from_bytes_le(bytes))
220    }
221}
222
223#[derive(Debug, Clone, Eq, PartialEq, Hash)]
224pub enum Identifier {
225    Numeric(u32),
226    String(UAString),
227    Guid(Guid),
228    ByteString(ByteString),
229}
230impl From<u32> for Identifier {
231    fn from(n: u32) -> Self {
232        Self::Numeric(n)
233    }
234}
235impl From<String> for Identifier {
236    fn from(s: String) -> Self {
237        Self::String(s.into())
238    }
239}
240impl From<&str> for Identifier {
241    fn from(s: &str) -> Self {
242        Self::String(s.into())
243    }
244}
245impl From<Guid> for Identifier {
246    fn from(v: Guid) -> Self {
247        Self::Guid(v)
248    }
249}
250impl From<ByteString> for Identifier {
251    fn from(v: ByteString) -> Self {
252        Self::ByteString(v)
253    }
254}
255#[derive(Debug, Clone, Eq, PartialEq, Hash)]
256/// A session-local namespace index and a numeric, string, UUID or opaque identifier.
257pub struct NodeId {
258    pub namespace: u16,
259    pub identifier: Identifier,
260}
261impl NodeId {
262    pub fn new(namespace: u16, id: impl Into<Identifier>) -> Self {
263        Self {
264            namespace,
265            identifier: id.into(),
266        }
267    }
268    pub fn null() -> Self {
269        Self::new(0, 0)
270    }
271    pub fn is_null(&self) -> bool {
272        self.namespace == 0 && self.identifier == Identifier::Numeric(0)
273    }
274    pub fn as_u32(&self) -> Option<u32> {
275        match self.identifier {
276            Identifier::Numeric(n) => Some(n),
277            _ => None,
278        }
279    }
280    pub fn as_object_id(&self) -> Result<ObjectId, StatusCode> {
281        match self {
282            Self {
283                namespace: 0,
284                identifier: Identifier::Numeric(n),
285            } => (*n).try_into(),
286            _ => Err(StatusCode::BadServiceUnsupported),
287        }
288    }
289    fn write_tagged<W: Write + ?Sized>(
290        &self,
291        w: &mut W,
292        c: &Context<'_>,
293        flags: u8,
294    ) -> Result<(), StatusCode> {
295        match &self.identifier {
296            Identifier::Numeric(n) if self.namespace == 0 && *n <= 255 => {
297                flags.encode(w, c)?;
298                (*n as u8).encode(w, c)
299            }
300            Identifier::Numeric(n) if self.namespace <= 255 && *n <= 65535 => {
301                (flags | 1).encode(w, c)?;
302                (self.namespace as u8).encode(w, c)?;
303                (*n as u16).encode(w, c)
304            }
305            id => {
306                let tag = match id {
307                    Identifier::Numeric(_) => 2,
308                    Identifier::String(_) => 3,
309                    Identifier::Guid(_) => 4,
310                    Identifier::ByteString(_) => 5,
311                };
312                (flags | tag).encode(w, c)?;
313                self.namespace.encode(w, c)?;
314                match id {
315                    Identifier::Numeric(n) => n.encode(w, c),
316                    Identifier::String(s) => s.encode(w, c),
317                    Identifier::Guid(id) => id.encode(w, c),
318                    Identifier::ByteString(bytes) => bytes.encode(w, c),
319                }
320            }
321        }
322    }
323    fn read_tagged<R: Read + ?Sized>(
324        r: &mut R,
325        c: &Context<'_>,
326        tag: u8,
327    ) -> Result<Self, StatusCode> {
328        match tag {
329            0 => Ok(Self::new(0, u32::from(u8::decode(r, c)?))),
330            1 => Ok(Self::new(
331                u16::from(u8::decode(r, c)?),
332                u32::from(u16::decode(r, c)?),
333            )),
334            2..=5 => {
335                let namespace = u16::decode(r, c)?;
336                let identifier = match tag {
337                    2 => Identifier::Numeric(u32::decode(r, c)?),
338                    3 => Identifier::String(UAString::decode(r, c)?),
339                    4 => Identifier::Guid(Guid::decode(r, c)?),
340                    _ => Identifier::ByteString(ByteString::decode(r, c)?),
341                };
342                Ok(Self {
343                    namespace,
344                    identifier,
345                })
346            }
347            _ => Err(StatusCode::BadDecodingError),
348        }
349    }
350}
351impl Default for NodeId {
352    fn default() -> Self {
353        Self::null()
354    }
355}
356impl From<u32> for NodeId {
357    fn from(n: u32) -> Self {
358        Self::new(0, n)
359    }
360}
361impl From<ObjectId> for NodeId {
362    fn from(id: ObjectId) -> Self {
363        Self::new(0, id as u32)
364    }
365}
366impl FromStr for NodeId {
367    type Err = StatusCode;
368    fn from_str(s: &str) -> Result<Self, Self::Err> {
369        let bad = StatusCode::BadNodeIdInvalid;
370        let (ns, s) = if let Some(body) = s.strip_prefix("ns=") {
371            let (ns, id) = body.split_once(';').ok_or(bad)?;
372            (ns.parse().map_err(|_| bad)?, id)
373        } else {
374            (0, s)
375        };
376        let (kind, value) = s.split_once('=').ok_or(bad)?;
377        let id = match kind {
378            "i" => Identifier::Numeric(value.parse().map_err(|_| bad)?),
379            "s" => value.into(),
380            "g" => Identifier::Guid(value.parse().map_err(|_| bad)?),
381            "b" => Identifier::ByteString(STANDARD.decode(value).map_err(|_| bad)?.into()),
382            _ => return Err(bad),
383        };
384        Ok(Self::new(ns, id))
385    }
386}
387impl fmt::Display for NodeId {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        if self.namespace != 0 {
390            write!(f, "ns={};", self.namespace)?;
391        }
392        match &self.identifier {
393            Identifier::Numeric(n) => write!(f, "i={n}"),
394            Identifier::String(s) => write!(f, "s={s}"),
395            Identifier::Guid(id) => write!(f, "g={id}"),
396            Identifier::ByteString(bytes) => write!(f, "b={}", STANDARD.encode(bytes.as_ref())),
397        }
398    }
399}
400impl BinaryEncodable for NodeId {
401    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
402        self.write_tagged(w, c, 0)
403    }
404}
405impl BinaryDecodable for NodeId {
406    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
407        let tag = u8::decode(r, c)?;
408        Self::read_tagged(r, c, tag)
409    }
410}
411
412#[derive(Clone, Debug, Default, PartialEq, Eq)]
413pub struct ExpandedNodeId {
414    pub node_id: NodeId,
415    pub namespace_uri: UAString,
416    pub server_index: u32,
417}
418impl ExpandedNodeId {
419    pub fn null() -> Self {
420        Self::default()
421    }
422}
423impl From<NodeId> for ExpandedNodeId {
424    fn from(node_id: NodeId) -> Self {
425        Self {
426            node_id,
427            ..Default::default()
428        }
429    }
430}
431impl BinaryEncodable for ExpandedNodeId {
432    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
433        let uri = !self.namespace_uri.is_empty();
434        let server = self.server_index != 0;
435        self.node_id
436            .write_tagged(w, c, (u8::from(uri) << 7) | (u8::from(server) << 6))?;
437        if uri {
438            self.namespace_uri.encode(w, c)?;
439        }
440        if server {
441            self.server_index.encode(w, c)?;
442        }
443        Ok(())
444    }
445}
446impl BinaryDecodable for ExpandedNodeId {
447    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
448        let tag = u8::decode(r, c)?;
449        let node_id = NodeId::read_tagged(r, c, tag & 63)?;
450        let namespace_uri = if tag & 128 != 0 {
451            UAString::decode(r, c)?
452        } else {
453            UAString::null()
454        };
455        let server_index = if tag & 64 != 0 { u32::decode(r, c)? } else { 0 };
456        Ok(Self {
457            node_id,
458            namespace_uri,
459            server_index,
460        })
461    }
462}
463#[derive(Clone, Debug, Default, PartialEq, Eq)]
464pub struct QualifiedName {
465    pub namespace_index: u16,
466    pub name: UAString,
467}
468impl QualifiedName {
469    pub fn null() -> Self {
470        Self::default()
471    }
472    pub fn new(ns: u16, name: impl Into<UAString>) -> Self {
473        Self {
474            namespace_index: ns,
475            name: name.into(),
476        }
477    }
478    pub fn is_null(&self) -> bool {
479        self.namespace_index == 0 && self.name.is_empty()
480    }
481}
482impl BinaryEncodable for QualifiedName {
483    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
484        self.namespace_index.encode(w, c)?;
485        self.name.encode(w, c)
486    }
487}
488impl BinaryDecodable for QualifiedName {
489    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
490        Ok(Self::new(u16::decode(r, c)?, UAString::decode(r, c)?))
491    }
492}
493
494#[derive(Clone, Debug, Default, PartialEq, Eq)]
495pub struct LocalizedText {
496    pub locale: UAString,
497    pub text: UAString,
498}
499impl From<&str> for LocalizedText {
500    fn from(text: &str) -> Self {
501        Self {
502            locale: UAString::null(),
503            text: text.into(),
504        }
505    }
506}
507impl LocalizedText {
508    pub fn new(locale: &str, text: &str) -> Self {
509        Self {
510            locale: locale.into(),
511            text: text.into(),
512        }
513    }
514    pub fn null() -> Self {
515        Self::default()
516    }
517}
518impl BinaryEncodable for LocalizedText {
519    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
520        let mask = u8::from(!self.locale.is_null()) | (u8::from(!self.text.is_null()) << 1);
521        mask.encode(w, c)?;
522        if mask & 1 != 0 {
523            self.locale.encode(w, c)?;
524        }
525        if mask & 2 != 0 {
526            self.text.encode(w, c)?;
527        }
528        Ok(())
529    }
530}
531impl BinaryDecodable for LocalizedText {
532    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
533        let mask = u8::decode(r, c)?;
534        if mask > 3 {
535            return Err(StatusCode::BadDecodingError);
536        }
537        Ok(Self {
538            locale: if mask & 1 != 0 {
539                UAString::decode(r, c)?
540            } else {
541                UAString::null()
542            },
543            text: if mask & 2 != 0 {
544                UAString::decode(r, c)?
545            } else {
546                UAString::null()
547            },
548        })
549    }
550}
551/// Attribute numbers from OPC UA Part 3, Table 1.
552#[derive(Clone, Copy, Debug, Eq, PartialEq)]
553#[repr(u32)]
554pub enum AttributeId {
555    NodeId = 1,
556    NodeClass,
557    BrowseName,
558    DisplayName,
559    Description,
560    WriteMask,
561    UserWriteMask,
562    IsAbstract,
563    Symmetric,
564    InverseName,
565    ContainsNoLoops,
566    EventNotifier,
567    Value,
568    DataType,
569    ValueRank,
570    ArrayDimensions,
571    AccessLevel,
572    UserAccessLevel,
573    MinimumSamplingInterval,
574    Historizing,
575    Executable,
576    UserExecutable,
577    DataTypeDefinition,
578    RolePermissions,
579    UserRolePermissions,
580    AccessRestrictions,
581    AccessLevelEx,
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587    use crate::ua::ContextOwned;
588
589    #[test]
590    fn node_id_forms_use_part_six_layout_and_leave_the_next_field_unread() {
591        let context = ContextOwned::default();
592        let ctx = context.context();
593        let cases = [
594            ("i=255", vec![0, 255]),
595            ("ns=1;i=512", vec![1, 1, 0, 2]),
596            ("ns=256;i=1", vec![2, 0, 1, 1, 0, 0, 0]),
597            ("ns=2;s=x;y", vec![3, 2, 0, 3, 0, 0, 0, b'x', b';', b'y']),
598            ("ns=2;b=+/8A", vec![5, 2, 0, 3, 0, 0, 0, 251, 255, 0]),
599            (
600                "ns=3;g=12345678-90ab-cdef-0102-030405060708",
601                vec![
602                    4, 3, 0, 0x78, 0x56, 0x34, 0x12, 0xab, 0x90, 0xef, 0xcd, 1, 2, 3, 4, 5, 6, 7, 8,
603                ],
604            ),
605        ];
606        for (text, bytes) in cases {
607            let node: NodeId = text.parse().unwrap();
608            let mut body = Vec::new();
609            node.encode(&mut body, &ctx).unwrap();
610            assert_eq!(body, bytes);
611            body.push(0xab);
612            let mut input = body.as_slice();
613            assert_eq!(NodeId::decode(&mut input, &ctx).unwrap().to_string(), text);
614            assert_eq!(input, [0xab]);
615        }
616    }
617
618    #[test]
619    fn distinguishes_an_absent_comment_from_an_explicit_empty_translation() {
620        let context = ContextOwned::default();
621        let ctx = context.context();
622        for (text, bytes) in [
623            (LocalizedText::null(), vec![0]),
624            (LocalizedText::new("", ""), vec![3, 0, 0, 0, 0, 0, 0, 0, 0]),
625        ] {
626            let mut out = Vec::new();
627            text.encode(&mut out, &ctx).unwrap();
628            assert_eq!(out, bytes);
629            assert_eq!(
630                LocalizedText::decode(&mut out.as_slice(), &ctx).unwrap(),
631                text
632            );
633        }
634        assert!(LocalizedText::decode(&mut [0x80].as_slice(), &ctx).is_err());
635    }
636
637    #[test]
638    fn status_names_preserve_qualified_and_unknown_statuses() {
639        assert_eq!(
640            StatusCode::from(StatusCode::BadNodeIdUnknown.bits() | 0x480).name(),
641            Some("BadNodeIdUnknown")
642        );
643        assert_eq!(StatusCode::from(0xafab0000).name(), None);
644    }
645}