Skip to main content

opcua_kit/client/
definition.rs

1use base64::{Engine, engine::general_purpose::STANDARD};
2
3use super::sample::Quality;
4use super::{Client, DataValue, Namespaces, ReadError, ReadMetadata, ReadSession, Sample, ua};
5use crate::NodeId;
6
7pub use crate::ua::AttributeId as ReadAttribute;
8
9/// A URI-qualified node and the attribute to read from it.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub struct ReadOperand<'a> {
12    /// Stable node identity supplied by the application.
13    pub node: &'a NodeId,
14    /// Attribute requested at this position in the batch.
15    pub attribute: ReadAttribute,
16}
17
18impl<'a> ReadOperand<'a> {
19    /// Select an attribute of a node for [`Client::read_attributes`].
20    pub const fn new(node: &'a NodeId, attribute: ReadAttribute) -> Self {
21        Self { node, attribute }
22    }
23
24    pub(super) fn value(node: &'a NodeId) -> Self {
25        Self::new(node, ReadAttribute::Value)
26    }
27}
28
29/// Two independent attribute results. Each sample preserves its status and clocks.
30#[derive(Debug)]
31pub struct VariableDefinition {
32    /// Declared DataType, translated into a stable namespace URI.
33    pub data_type: Result<Sample<NodeId>, ReadError>,
34    /// OPC UA ValueRank as a signed integer (-3 or greater).
35    pub value_rank: Result<Sample<i32>, ReadError>,
36}
37
38impl Namespaces {
39    pub(super) fn stable_node(&self, wire: &ua::NodeId) -> Result<NodeId, ReadError> {
40        let namespace = self
41            .by_index
42            .get(usize::from(wire.namespace))
43            .ok_or(ReadError::InvalidDataType)?;
44        Self::node_in(namespace, wire)
45    }
46
47    pub(super) fn node_in(namespace: &str, wire: &ua::NodeId) -> Result<NodeId, ReadError> {
48        let id = match &wire.identifier {
49            ua::Identifier::Numeric(n) => format!("i={n}"),
50            ua::Identifier::String(text) => {
51                let text = text
52                    .value()
53                    .as_deref()
54                    .filter(|text| text.len() <= 4 * 4096)
55                    .ok_or(ReadError::InvalidDataType)?;
56                format!("s={text}")
57            }
58            ua::Identifier::Guid(id) => format!("g={id}"),
59            ua::Identifier::ByteString(bytes) => {
60                let data = bytes
61                    .value
62                    .as_deref()
63                    .filter(|bytes| bytes.len() <= 4096)
64                    .ok_or(ReadError::InvalidDataType)?;
65                format!("b={}", STANDARD.encode(data))
66            }
67        };
68        NodeId::new(namespace, id).map_err(|_| ReadError::InvalidDataType)
69    }
70}
71
72pub(super) fn decode_data_type(
73    namespaces: &Namespaces,
74    raw: &DataValue,
75    quality: Quality,
76) -> Result<Sample<NodeId>, ReadError> {
77    Sample::decode_with(raw, quality, |v| {
78        let ua::Variant::NodeId(wire) = v else {
79            return Err(ReadError::ScalarTypeMismatch { expected: "NodeId" });
80        };
81        namespaces.stable_node(wire).map(Some)
82    })
83}
84
85impl VariableDefinition {
86    fn decode(
87        namespaces: &Namespaces,
88        data_type: &DataValue,
89        value_rank: &DataValue,
90        quality: Quality,
91    ) -> Self {
92        let data_type = decode_data_type(namespaces, data_type, quality);
93        let value_rank = Sample::<i32>::from_raw_with(value_rank, quality).and_then(|rank| {
94            if rank.value.is_some_and(|n| n < -3) {
95                Err(ReadError::InvalidValueRank)
96            } else {
97                Ok(rank)
98            }
99        });
100        Self {
101            data_type,
102            value_rank,
103        }
104    }
105}
106
107impl Client {
108    /// Read any combination of standard node attributes in caller order.
109    /// Each operand counts toward the logical and per-request limits. NodeId
110    /// values in these raw results carry the server's session-local indices.
111    pub async fn read_attributes(
112        &self,
113        operands: &[ReadOperand<'_>],
114    ) -> Result<Vec<DataValue>, ReadError> {
115        self.read_batch(operands.iter().copied(), std::convert::identity)
116            .await
117    }
118
119    /// Read only DataType and ValueRank. A malformed attribute affects its own
120    /// field. Service and session failures apply to the whole definition.
121    ///
122    /// ```
123    /// # async fn inspect(client: &opcua_kit::Client, node: &opcua_kit::NodeId) -> Result<(), opcua_kit::ReadError> {
124    /// let definition = client.read_definition(node).await?;
125    /// let data_type = definition.data_type?;
126    /// let value_rank = definition.value_rank?;
127    /// if let (Some(id), Some(rank)) = (data_type.value, value_rank.value) {
128    ///     println!("{} {} has rank {rank}", id.namespace(), id.identifier());
129    /// }
130    /// # Ok(()) }
131    /// ```
132    pub async fn read_definition(&self, node: &NodeId) -> Result<VariableDefinition, ReadError> {
133        let (mut session, metadata) = self.read_session().await?;
134        self.definition_locked(&mut session, metadata, node, Quality::GoodSeverity)
135            .await
136    }
137
138    pub(super) async fn definition_locked(
139        &self,
140        session: &mut ReadSession,
141        metadata: &ReadMetadata,
142        node: &NodeId,
143        quality: Quality,
144    ) -> Result<VariableDefinition, ReadError> {
145        let response = self
146            .read_locked(
147                session,
148                metadata,
149                [
150                    ReadOperand::new(node, ReadAttribute::DataType),
151                    ReadOperand::new(node, ReadAttribute::ValueRank),
152                ]
153                .into_iter(),
154                std::convert::identity,
155            )
156            .await?;
157        let [data_type, value_rank] = response.as_slice() else {
158            return Err(ReadError::InvalidServerMetadata);
159        };
160        Ok(VariableDefinition::decode(
161            &metadata.namespaces,
162            data_type,
163            value_rank,
164            quality,
165        ))
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    fn namespaces() -> Namespaces {
174        let entries = [
175            "http://opcfoundation.org/UA/",
176            "urn:site:signals",
177            "urn:site:datatypes",
178        ]
179        .map(|s| ua::Variant::String(s.into()));
180        crate::client::namespace_map(&entries).unwrap()
181    }
182
183    #[test]
184    fn declared_node_ids_use_the_session_uri_and_preserve_all_four_identifier_forms() {
185        let ns = namespaces();
186        for (wire, expected) in [
187            (ua::NodeId::new(2, u32::MAX), "i=4294967295"),
188            (
189                ua::NodeId::new(2, "Rate;ns=3;温度%2F"),
190                "s=Rate;ns=3;温度%2F",
191            ),
192            (
193                ua::NodeId::new(
194                    2,
195                    "12345678-90ab-cdef-0102-030405060708"
196                        .parse::<ua::Guid>()
197                        .unwrap(),
198                ),
199                "g=12345678-90ab-cdef-0102-030405060708",
200            ),
201            (
202                ua::NodeId::new(2, ua::ByteString::from(vec![0xfb, 0xff, 0])),
203                "b=+/8A",
204            ),
205        ] {
206            let stable = ns.stable_node(&wire).unwrap();
207            assert_eq!(stable.namespace(), "urn:site:datatypes");
208            assert_eq!(stable.identifier(), expected);
209        }
210        for invalid in [
211            ua::NodeId::from(0u32),
212            ua::NodeId::new(3, 1u32),
213            ua::NodeId::new(2, "x\ny"),
214            ua::NodeId::new(2, "x".repeat(4097)),
215            ua::NodeId::new(2, ua::ByteString::from(vec![1; 4097])),
216        ] {
217            assert!(matches!(
218                ns.stable_node(&invalid),
219                Err(ReadError::InvalidDataType)
220            ));
221        }
222    }
223
224    #[test]
225    fn definition_preserves_independent_status_clocks_and_malformed_results() {
226        let ns = namespaces();
227        let at = ua::DateTime::from_unix_timestamp_nanos(100).unwrap();
228        let data = ua::DataValue {
229            source_timestamp: Some(at),
230            source_picoseconds: Some(5),
231            status: Some(ua::StatusCode::GoodClamped),
232            ..ua::DataValue::value_only(ua::Variant::from(ua::NodeId::from(9u32)))
233        };
234        let rank = ua::DataValue::value_only(ua::Variant::Int32(-3));
235        let valid = VariableDefinition::decode(&ns, &data, &rank, Quality::GoodSeverity);
236        let ty = valid.data_type.unwrap();
237        assert_eq!(
238            ty.value.unwrap().namespace(),
239            "http://opcfoundation.org/UA/"
240        );
241        assert_eq!(ty.status, ua::StatusCode::GoodClamped.bits());
242        assert_eq!(ty.source_timestamp.unwrap().ten_picoseconds, Some(5));
243        assert_eq!(valid.value_rank.unwrap().value, Some(-3));
244
245        let wrong_type = ua::DataValue::value_only(ua::Variant::Int32(9));
246        let partial = VariableDefinition::decode(&ns, &wrong_type, &rank, Quality::GoodSeverity);
247        assert!(matches!(
248            partial.data_type,
249            Err(ReadError::ScalarTypeMismatch { expected: "NodeId" })
250        ));
251        assert_eq!(partial.value_rank.unwrap().value, Some(-3));
252        let invalid_rank = ua::DataValue::value_only(ua::Variant::Int32(-4));
253        let partial = VariableDefinition::decode(&ns, &data, &invalid_rank, Quality::GoodSeverity);
254        assert_eq!(
255            partial.data_type.unwrap().value.unwrap().identifier(),
256            "i=9"
257        );
258        assert!(matches!(
259            partial.value_rank,
260            Err(ReadError::InvalidValueRank)
261        ));
262        let bad = ua::DataValue {
263            status: Some(ua::StatusCode::BadAttributeIdInvalid),
264            ..ua::DataValue::default()
265        };
266        let missing =
267            VariableDefinition::decode(&ns, &bad, &ua::DataValue::default(), Quality::GoodSeverity);
268        let missing_type = missing.data_type.unwrap();
269        assert_eq!(
270            missing_type.status,
271            ua::StatusCode::BadAttributeIdInvalid.bits()
272        );
273        assert!(missing_type.value.is_none());
274        assert!(missing.value_rank.unwrap().value.is_none());
275    }
276
277    #[test]
278    fn rank_accepts_all_standard_categories_and_rejects_arrays_and_unsigned_integers() {
279        let ns = namespaces();
280        let type_array = ua::DataValue::value_only(ua::Variant::from(vec![ua::NodeId::from(9u32)]));
281        for n in [-3, -2, -1, 0, 1, 2, i32::MAX] {
282            let raw = ua::DataValue::value_only(ua::Variant::Int32(n));
283            let result = VariableDefinition::decode(&ns, &type_array, &raw, Quality::GoodSeverity);
284            assert!(matches!(
285                result.data_type,
286                Err(ReadError::ScalarTypeMismatch { expected: "NodeId" })
287            ));
288            assert_eq!(result.value_rank.unwrap().value, Some(n));
289        }
290        for wrong in [ua::Variant::UInt32(1), ua::Variant::from(vec![-1i32])] {
291            let result = VariableDefinition::decode(
292                &ns,
293                &type_array,
294                &ua::DataValue::value_only(wrong),
295                Quality::GoodSeverity,
296            );
297            assert!(matches!(
298                result.value_rank,
299                Err(ReadError::ScalarTypeMismatch { expected: "Int32" })
300            ));
301        }
302    }
303}