Skip to main content

opcua_kit/client/
units.rs

1use super::sample::Quality;
2use super::{Client, DataValue, EngineeringUnit, Namespaces, ReadError, ReadSession, Sample, ua};
3use crate::NodeId;
4
5pub(super) const MAX_REFERENCES: usize = 256;
6pub(super) const MAX_PAGES: usize = 256;
7const MAX_TOKEN_BYTES: usize = 64 * 1024;
8const HAS_PROPERTY: u32 = 46;
9const EU_INFORMATION: u32 = 887;
10
11/// Operation that supplied the decisive status and clocks for a unit lookup.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum UnitStage {
14    /// Lookup failed at Browse or completed without a standard EngineeringUnits property.
15    Browse,
16    /// The property's declared DataType was unavailable.
17    DataType,
18    /// The property's declared ValueRank was unavailable.
19    ValueRank,
20    /// The verified property's Value was read.
21    Value,
22}
23
24/// Unit evidence from a single signal, with the original operation status.
25#[derive(Debug)]
26pub struct EngineeringUnitEvidence {
27    /// The operation whose result appears in the sample.
28    pub stage: UnitStage,
29    /// Stable local property node, once the complete lookup found exactly one.
30    pub property: Option<NodeId>,
31    /// Original status and clocks; a Good Browse with no value means no matching property.
32    pub sample: Sample<EngineeringUnit>,
33}
34
35fn decode_unit(v: &ua::Variant) -> Result<Option<EngineeringUnit>, ReadError> {
36    let ua::Variant::ExtensionObject(object) = v else {
37        return Err(ReadError::InvalidUnitProperty);
38    };
39    let eu = object
40        .inner_as::<ua::EUInformation>()
41        .ok_or(ReadError::InvalidUnitProperty)?;
42    unit_from_fields(eu.namespace_uri.as_ref().as_bytes(), eu.unit_id).map(Some)
43}
44
45fn unit_from_fields(bytes: &[u8], unit_id: i32) -> Result<EngineeringUnit, ReadError> {
46    if bytes.len() > 4 * 1024 * 1024 {
47        return Err(ReadError::InvalidUnitProperty);
48    }
49    let namespace = std::str::from_utf8(bytes).map_err(|_| ReadError::InvalidUnitProperty)?;
50    if namespace.chars().any(char::is_control) {
51        return Err(ReadError::InvalidUnitProperty);
52    }
53    Ok(EngineeringUnit {
54        namespace_uri: namespace.to_owned(),
55        unit_id,
56    })
57}
58
59// Borrow the sole result so bounds are checked before copying reference names and IDs.
60pub(super) enum Page {
61    First(ua::BrowseResponse),
62    Next(ua::BrowseNextResponse),
63}
64
65impl Page {
66    pub(super) fn checked<'a>(
67        &'a self,
68        session: &mut ReadSession,
69    ) -> Result<(&'a ua::BrowseResult, Option<ua::ContinuationPoint>), ReadError> {
70        self.result()
71            .and_then(|result| Ok((result, continuation(result)?)))
72            .inspect_err(|_| {
73                // An invalid page may own a token that cannot safely be released. An
74                // explicit disconnect releases remaining resources on the old session.
75                session.interrupted = true;
76            })
77    }
78
79    fn result(&self) -> Result<&ua::BrowseResult, ReadError> {
80        let results = match self {
81            Self::First(r) => &r.results,
82            Self::Next(r) => &r.results,
83        };
84        match results.as_deref() {
85            Some([r]) => Ok(r),
86            _ => Err(ReadError::InvalidUnitReference),
87        }
88    }
89}
90
91pub(super) fn references(
92    result: &ua::BrowseResult,
93) -> Result<&[ua::ReferenceDescription], ReadError> {
94    let entries = result.references.as_deref().unwrap_or_default();
95    if entries.len() > MAX_REFERENCES {
96        return Err(ReadError::InvalidUnitReference);
97    }
98    Ok(entries)
99}
100
101fn continuation(result: &ua::BrowseResult) -> Result<Option<ua::ContinuationPoint>, ReadError> {
102    let point = &result.continuation_point;
103    if point.len() > MAX_TOKEN_BYTES {
104        return Err(ReadError::InvalidUnitReference);
105    }
106    Ok((!point.is_null_or_empty()).then(|| point.clone()))
107}
108
109pub(super) fn local_target(
110    namespaces: &Namespaces,
111    target: &ua::ExpandedNodeId,
112) -> Result<NodeId, ReadError> {
113    if target.server_index != 0 {
114        return Err(ReadError::InvalidUnitReference);
115    }
116    let uri = &target.namespace_uri;
117    if uri.as_ref().is_empty() {
118        namespaces.stable_node(&target.node_id)
119    } else {
120        let uri = uri
121            .value()
122            .as_deref()
123            .filter(|uri| namespaces.by_uri.contains_key(*uri))
124            .ok_or(ReadError::InvalidUnitReference)?;
125        Namespaces::node_in(uri, &target.node_id)
126    }
127    .map_err(|_| ReadError::InvalidUnitReference)
128}
129
130fn local_property(
131    namespaces: &Namespaces,
132    target: &ua::ExpandedNodeId,
133    signal: &NodeId,
134) -> Result<NodeId, ReadError> {
135    let node = local_target(namespaces, target)?;
136    if &node == signal {
137        return Err(ReadError::InvalidUnitReference);
138    }
139    Ok(node)
140}
141
142#[derive(Default)]
143struct Selection {
144    found: Option<NodeId>,
145    visited: usize,
146    pages: usize,
147}
148
149impl Selection {
150    fn inspect(
151        &mut self,
152        entries: &[ua::ReferenceDescription],
153        namespaces: &Namespaces,
154        signal: &NodeId,
155    ) -> Result<(), ReadError> {
156        if self.pages == MAX_PAGES || entries.len() > MAX_REFERENCES - self.visited {
157            return Err(ReadError::InvalidUnitReference);
158        }
159        self.pages += 1;
160        self.visited += entries.len();
161        for entry in entries {
162            if !entry.is_forward || entry.reference_type_id != ua::NodeId::new(0, HAS_PROPERTY) {
163                return Err(ReadError::InvalidUnitReference);
164            }
165            if entry.browse_name.namespace_index != 0
166                || entry.browse_name.name.as_ref() != "EngineeringUnits"
167            {
168                continue;
169            }
170            if self.found.is_some() || entry.node_class != ua::NodeClass::Variable {
171                return Err(ReadError::InvalidUnitReference);
172            }
173            self.found = Some(local_property(namespaces, &entry.node_id, signal)?);
174        }
175        Ok(())
176    }
177}
178
179fn gate(
180    raw: &DataValue,
181    stage: UnitStage,
182    quality: Quality,
183) -> Result<Option<Sample<EngineeringUnit>>, ReadError> {
184    let result = Sample::decode_with(raw, quality, |value| {
185        let matches = match stage {
186            UnitStage::DataType => {
187                matches!(value, ua::Variant::NodeId(id) if **id == ua::NodeId::new(0,EU_INFORMATION))
188            }
189            UnitStage::ValueRank => matches!(value, ua::Variant::Int32(-1)),
190            _ => false,
191        };
192        if !matches {
193            return Err(ReadError::InvalidUnitProperty);
194        }
195        Ok(Some(()))
196    })?;
197    Ok(result.value.is_none().then_some(Sample {
198        status: result.status,
199        value: None,
200        source_timestamp: result.source_timestamp,
201        server_timestamp: result.server_timestamp,
202    }))
203}
204
205impl ReadSession {
206    fn confirm_unit_release(
207        &mut self,
208        results: usize,
209        diagnostics: usize,
210    ) -> Result<(), ReadError> {
211        if results != 0 || diagnostics != 0 {
212            self.interrupted = true;
213            return Err(ReadError::InvalidUnitReference);
214        }
215        Ok(())
216    }
217}
218
219impl Client {
220    pub(super) async fn next_browse_page(
221        &self,
222        session: &mut ReadSession,
223        point: ua::ContinuationPoint,
224        release: bool,
225    ) -> Result<ua::BrowseNextResponse, ReadError> {
226        let request = ua::BrowseNextRequest {
227            release_continuation_points: release,
228            continuation_points: Some(vec![point]),
229            ..Default::default()
230        };
231        let response = self.guarded(session, self.inner.request(request)).await?;
232        if release {
233            session.confirm_unit_release(
234                response.results.as_ref().map_or(0, Vec::len),
235                response.diagnostic_infos.as_ref().map_or(0, Vec::len),
236            )?;
237        }
238        Ok(response)
239    }
240
241    async fn unit_target(
242        &self,
243        session: &mut ReadSession,
244        namespaces: &Namespaces,
245        signal: &NodeId,
246        quality: Quality,
247    ) -> Result<(u32, Option<NodeId>), ReadError> {
248        let description = ua::BrowseDescription {
249            node_id: namespaces.wire_node(signal, 0)?,
250            browse_direction: ua::BrowseDirection::Forward,
251            reference_type_id: ua::NodeId::new(0, HAS_PROPERTY),
252            include_subtypes: false,
253            result_mask: 0x0f,
254            node_class_mask: 0,
255        };
256        let request = ua::BrowseRequest {
257            requested_max_references_per_node: MAX_REFERENCES as u32,
258            nodes_to_browse: Some(vec![description]),
259            ..Default::default()
260        };
261        let mut page = Page::First(self.guarded(session, self.inner.request(request)).await?);
262        let mut selection = Selection::default();
263        loop {
264            let (result, point) = page.checked(session)?;
265            let status = result.status_code.bits();
266            if !quality.accepts(status) {
267                if let Some(point) = point {
268                    self.next_browse_page(session, point, true).await?;
269                }
270                return Ok((status, None));
271            }
272            let inspected = references(result)
273                .and_then(|entries| selection.inspect(entries, namespaces, signal));
274            let Some(point) = point else {
275                inspected?;
276                return Ok((status, selection.found));
277            };
278            if inspected.is_err() || selection.pages == MAX_PAGES {
279                self.next_browse_page(session, point, true).await?;
280                return Err(ReadError::InvalidUnitReference);
281            }
282            page = Page::Next(self.next_browse_page(session, point, false).await?);
283        }
284    }
285
286    /// Resolve the standard EngineeringUnits property and verify its declared type and rank
287    /// before reading its value. The signal's process Value is never requested.
288    /// Lookup visits at most 256 forward HasProperty references and 256 pages.
289    /// A malformed response envelope or an unusable continuation token (over
290    /// 64 KiB) retires the session. Disconnect to release its remaining resources.
291    ///
292    /// ```
293    /// # async fn inspect(client: &opcua_kit::Client, node: &opcua_kit::NodeId) -> Result<(), opcua_kit::ReadError> {
294    /// let evidence = client.read_engineering_units(node).await?;
295    /// if let Some(unit) = evidence.sample.value.filter(|unit| unit.is_identified()) {
296    ///     println!("{} {}", unit.namespace_uri, unit.unit_id);
297    /// }
298    /// # Ok(()) }
299    /// ```
300    pub async fn read_engineering_units(
301        &self,
302        signal: &NodeId,
303    ) -> Result<EngineeringUnitEvidence, ReadError> {
304        let (mut session, metadata) = self.read_session().await?;
305        self.units_locked(
306            &mut session,
307            &metadata.namespaces,
308            signal,
309            Quality::GoodSeverity,
310            |_| true,
311        )
312        .await
313    }
314
315    pub(super) async fn units_locked(
316        &self,
317        session: &mut ReadSession,
318        namespaces: &Namespaces,
319        signal: &NodeId,
320        quality: Quality,
321        allow_property: impl FnOnce(&NodeId) -> bool,
322    ) -> Result<EngineeringUnitEvidence, ReadError> {
323        let (status, property) = self
324            .unit_target(session, namespaces, signal, quality)
325            .await?;
326        let Some(property) = property else {
327            return Ok(EngineeringUnitEvidence {
328                stage: UnitStage::Browse,
329                property: None,
330                sample: Sample {
331                    status,
332                    value: None,
333                    source_timestamp: None,
334                    server_timestamp: None,
335                },
336            });
337        };
338        if !allow_property(&property) {
339            return Err(ReadError::UnitAliasesSignal);
340        }
341        let wire = namespaces.wire_node(&property, 0)?;
342        for (stage, attribute) in [
343            (UnitStage::DataType, ua::AttributeId::DataType),
344            (UnitStage::ValueRank, ua::AttributeId::ValueRank),
345        ] {
346            let raw = self.one_attribute(session, wire.clone(), attribute).await?;
347            if let Some(sample) = gate(&raw, stage, quality)? {
348                return Ok(EngineeringUnitEvidence {
349                    stage,
350                    property: Some(property),
351                    sample,
352                });
353            }
354        }
355        let raw = self
356            .one_attribute(session, wire, ua::AttributeId::Value)
357            .await?;
358        Ok(EngineeringUnitEvidence {
359            stage: UnitStage::Value,
360            property: Some(property),
361            sample: Sample::decode_with(&raw, quality, decode_unit)?,
362        })
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[cfg(feature = "cems")]
371    #[test]
372    fn meter_unit_pages_and_declarations_require_unqualified_good() {
373        let flagged = ua::StatusCode::GoodClamped;
374        assert!(Quality::GoodSeverity.accepts(flagged.bits()));
375        assert!(!Quality::ExactGood.accepts(flagged.bits()));
376        let data_type = ua::Variant::from(ua::NodeId::from(EU_INFORMATION));
377        let rank = ua::Variant::Int32(-1);
378        for (stage, declaration) in [
379            (UnitStage::DataType, data_type),
380            (UnitStage::ValueRank, rank),
381        ] {
382            let raw = ua::DataValue {
383                status: Some(flagged),
384                ..ua::DataValue::value_only(declaration)
385            };
386            assert!(gate(&raw, stage, Quality::GoodSeverity).unwrap().is_none());
387            let unavailable = gate(&raw, stage, Quality::ExactGood).unwrap().unwrap();
388            assert_eq!(unavailable.status, flagged.bits());
389            assert!(unavailable.value.is_none());
390        }
391    }
392
393    #[test]
394    fn only_an_empty_release_envelope_keeps_the_session_usable() {
395        let mut clean = ReadSession::default();
396        assert!(clean.confirm_unit_release(0, 0).is_ok());
397        assert!(!clean.interrupted);
398        for (results, diagnostics) in [(1, 0), (0, 1), (1, 1)] {
399            let mut session = ReadSession::default();
400            assert!(matches!(
401                session.confirm_unit_release(results, diagnostics),
402                Err(ReadError::InvalidUnitReference)
403            ));
404            assert!(session.interrupted);
405        }
406    }
407
408    #[test]
409    fn property_identity_resolves_local_indexes_and_explicit_namespaces() {
410        let table = ["http://opcfoundation.org/UA/", "urn:signal", "urn:property"]
411            .map(|s| ua::Variant::String(s.into()));
412        let ns = crate::client::namespace_map(&table).unwrap();
413        let signal = NodeId::new("urn:signal", "s=x").unwrap();
414        let explicit = |uri: &str, server: u32| ua::ExpandedNodeId {
415            node_id: ua::NodeId::new(0, "x"),
416            namespace_uri: uri.into(),
417            server_index: server,
418        };
419        let expected = NodeId::new("urn:property", "s=x").unwrap();
420        let zero = ua::ExpandedNodeId {
421            node_id: ua::NodeId::null(),
422            namespace_uri: "urn:property".into(),
423            server_index: 0,
424        };
425        assert_eq!(
426            local_property(&ns, &zero, &signal).unwrap(),
427            NodeId::new("urn:property", "i=0").unwrap()
428        );
429        assert_eq!(
430            local_property(&ns, &explicit("urn:property", 0), &signal).unwrap(),
431            expected
432        );
433        assert_eq!(
434            local_property(&ns, &ua::NodeId::new(2, "x").into(), &signal).unwrap(),
435            expected
436        );
437        for target in [
438            explicit("urn:property", 2),
439            explicit("urn:absent", 0),
440            explicit("urn:signal", 0),
441            ua::NodeId::new(1, "x").into(),
442            ua::ExpandedNodeId::null(),
443            ua::NodeId::new(9, 1u32).into(),
444        ] {
445            assert!(matches!(
446                local_property(&ns, &target, &signal),
447                Err(ReadError::InvalidUnitReference)
448            ));
449        }
450    }
451
452    #[test]
453    fn declaration_gates_require_exact_scalar_type_and_preserve_unavailable_clocks() {
454        let valid = ua::DataValue {
455            status: Some(ua::StatusCode::GoodClamped),
456            ..ua::DataValue::value_only(ua::Variant::from(ua::NodeId::from(887u32)))
457        };
458        assert!(
459            gate(&valid, UnitStage::DataType, Quality::GoodSeverity)
460                .unwrap()
461                .is_none()
462        );
463        let rank = ua::DataValue::value_only(ua::Variant::Int32(-1));
464        assert!(
465            gate(&rank, UnitStage::ValueRank, Quality::GoodSeverity)
466                .unwrap()
467                .is_none()
468        );
469        for (value, stage) in [
470            (
471                ua::Variant::from(ua::NodeId::new(2, 887u32)),
472                UnitStage::DataType,
473            ),
474            (ua::Variant::Int32(0), UnitStage::ValueRank),
475            (ua::Variant::from(vec![-1i32]), UnitStage::ValueRank),
476        ] {
477            assert!(matches!(
478                gate(
479                    &ua::DataValue::value_only(value),
480                    stage,
481                    Quality::GoodSeverity
482                ),
483                Err(ReadError::InvalidUnitProperty)
484            ));
485        }
486        let missing = gate(
487            &ua::DataValue::default(),
488            UnitStage::DataType,
489            Quality::GoodSeverity,
490        )
491        .unwrap()
492        .unwrap();
493        assert_eq!(missing.status, 0);
494        assert!(missing.value.is_none());
495        let raw = ua::DataValue {
496            status: Some(ua::StatusCode::UncertainLastUsableValue),
497            source_timestamp: Some(ua::DateTime::from_unix_timestamp_nanos(100).unwrap()),
498            source_picoseconds: Some(3),
499            ..ua::DataValue::value_only(ua::Variant::Int32(-1))
500        };
501        let unavailable = gate(&raw, UnitStage::ValueRank, Quality::GoodSeverity)
502            .unwrap()
503            .unwrap();
504        assert_eq!(
505            unavailable.status,
506            ua::StatusCode::UncertainLastUsableValue.bits()
507        );
508        assert_eq!(
509            unavailable.source_timestamp.unwrap().ten_picoseconds,
510            Some(3)
511        );
512        assert!(unavailable.value.is_none());
513    }
514
515    #[test]
516    fn actual_eu_structure_keeps_signed_identity_and_ignores_localized_labels() {
517        let eu = ua::EUInformation {
518            namespace_uri: "urn:Vendor".into(),
519            unit_id: i32::MIN,
520            display_name: ua::LocalizedText::new("de-DE", "nicht maßgeblich"),
521            ..Default::default()
522        };
523        let unit = decode_unit(&ua::Variant::ExtensionObject(ua::ExtensionObject::new(eu)))
524            .unwrap()
525            .unwrap();
526        assert_eq!(
527            (unit.namespace_uri.as_str(), unit.unit_id),
528            ("urn:Vendor", i32::MIN)
529        );
530        assert!(unit.is_identified());
531        assert!(!unit_from_fields(b"urn:vendor", -1).unwrap().is_identified());
532        assert!(!unit_from_fields(b"", 42).unwrap().is_identified());
533        assert!(matches!(
534            decode_unit(&ua::Variant::Int32(42)),
535            Err(ReadError::InvalidUnitProperty)
536        ));
537        assert!(unit_from_fields(&[255], 0).is_err());
538        assert!(unit_from_fields(b"urn:site\n", 0).is_err());
539        let mut namespace = vec![b'a'; 4 * 1024 * 1024];
540        assert!(unit_from_fields(&namespace, i32::MAX).is_ok());
541        namespace.push(b'a');
542        assert!(unit_from_fields(&namespace, 1).is_err());
543    }
544
545    #[test]
546    fn continuation_representation_and_page_budget_are_checked_before_cloning() {
547        let mut result = ua::BrowseResult::default();
548        assert!(continuation(&result).unwrap().is_none());
549        for size in [0, 1, MAX_TOKEN_BYTES, MAX_TOKEN_BYTES + 1] {
550            result.continuation_point = vec![1; size].into();
551            match size {
552                0 => assert!(continuation(&result).unwrap().is_none()),
553                1 | MAX_TOKEN_BYTES => assert!(continuation(&result).unwrap().is_some()),
554                _ => assert!(matches!(
555                    continuation(&result),
556                    Err(ReadError::InvalidUnitReference)
557                )),
558            }
559        }
560        // A terminal page with zero references is consumable even at the reference ceiling.
561        assert!(references(&result).unwrap().is_empty());
562        let mut session = ReadSession::default();
563        let page = Page::First(ua::BrowseResponse::default());
564        assert!(matches!(
565            page.checked(&mut session),
566            Err(ReadError::InvalidUnitReference)
567        ));
568        assert!(session.interrupted);
569    }
570
571    #[test]
572    fn bounded_pages_preserve_a_candidate_until_the_sequence_is_complete() {
573        let ns = crate::client::namespace_map(
574            &["http://opcfoundation.org/UA/", "urn:site"].map(|s| ua::Variant::String(s.into())),
575        )
576        .unwrap();
577        let signal = NodeId::new("urn:site", "i=10").unwrap();
578        let entry = |qualified_name: ua::QualifiedName| ua::ReferenceDescription {
579            is_forward: true,
580            reference_type_id: ua::NodeId::new(0, HAS_PROPERTY),
581            node_class: ua::NodeClass::Variable,
582            browse_name: qualified_name,
583            node_id: ua::NodeId::new(1, 11u32).into(),
584            ..Default::default()
585        };
586        let unrelated = entry(ua::QualifiedName::new(1, "EngineeringUnits"));
587        let matched = entry(ua::QualifiedName::new(0, "EngineeringUnits"));
588        let mut complete = Selection::default();
589        complete
590            .inspect(&vec![unrelated.clone(); 255], &ns, &signal)
591            .unwrap();
592        assert!(complete.found.is_none());
593        complete
594            .inspect(std::slice::from_ref(&matched), &ns, &signal)
595            .unwrap();
596        complete.inspect(&[], &ns, &signal).unwrap();
597        assert_eq!(
598            complete.found,
599            Some(NodeId::new("urn:site", "i=11").unwrap())
600        );
601        assert!(complete.inspect(&[unrelated], &ns, &signal).is_err());
602        let mut ambiguous = Selection::default();
603        ambiguous
604            .inspect(std::slice::from_ref(&matched), &ns, &signal)
605            .unwrap();
606        assert!(ambiguous.inspect(&[matched], &ns, &signal).is_err());
607        let mut empty = Selection::default();
608        for _ in 0..MAX_PAGES {
609            empty.inspect(&[], &ns, &signal).unwrap();
610        }
611        assert!(empty.inspect(&[], &ns, &signal).is_err());
612    }
613}