Skip to main content

opcua_kit/client/
control.rs

1//! Explicit control capability for an authenticated session. The server enforces permissions.
2
3use super::{Client, ReadError, ReadSession, Scalar, ua, wire};
4use crate::{NodeId, Severity, status_severity};
5
6const MAX_ARGS: usize = 64;
7pub(super) const MAX_BYTES: usize = 128 * 1024;
8
9/// A local preflight failure or an operation whose effects need reconciliation.
10#[derive(Debug, thiserror::Error)]
11#[non_exhaustive]
12pub enum ControlError {
13    /// The operation was never submitted. The session or stable target identity was unusable.
14    #[error("control preflight failed: {0}")]
15    Preflight(#[source] ReadError),
16    /// The request exceeded 64 arguments or 128 KiB of encoded Variants, or could not be encoded.
17    #[error("control input exceeds the argument or encoded size limit")]
18    InputLimit,
19    /// The timestamp has no exact, non-sentinel OPC UA DateTime representation.
20    #[error("timestamp must be representable as a non-sentinel 100 ns OPC UA DateTime")]
21    InvalidDateTime,
22    /// A usable reply could not be obtained after entering dispatch. The operation may have executed.
23    #[error("control outcome is unknown after dispatch: {0}")]
24    Indeterminate(#[source] ReadError),
25    /// The response was malformed or too large. The session is retired and effects may have occurred.
26    #[error("control response was malformed or exceeded the result limit; verify the effect")]
27    InvalidResponse,
28}
29
30/// One Call result in wire order. Check the operation status before interpreting outputs.
31#[derive(Debug)]
32#[must_use]
33pub struct CallOutcome {
34    /// Full operation-level StatusCode, including flags and qualified Good results.
35    pub status: u32,
36    /// Per-input status codes, when provided by the server.
37    pub input_statuses: Vec<u32>,
38    /// Output Variants with their original types and shapes.
39    pub outputs: Vec<ua::Variant>,
40}
41
42/// Borrow a pinned client for explicit value writes and method calls.
43///
44/// Each call dispatches at most once. A dropped future after dispatch retires the session.
45/// If the reply is lost, inspect application state on a new session before deciding what to do.
46///
47/// ```
48/// use opcua_kit::{Client, Control, ControlError, NodeId};
49/// # async fn set_value(client: &Client, node: &NodeId) -> Result<(), ControlError> {
50/// let status = Control::new(client).write_scalar(node, 42_u32).await?;
51/// if status != 0 {
52///     eprintln!("write returned 0x{status:08X}");
53/// }
54/// # Ok(()) }
55/// ```
56pub struct Control<'a>(&'a Client);
57
58impl<'a> Control<'a> {
59    /// Use the existing session's credentials, authority, namespace map and service guard.
60    pub const fn new(client: &'a Client) -> Self {
61        Self(client)
62    }
63
64    /// Write one Rust scalar with its exact OPC UA type and return the full operation status.
65    pub async fn write_scalar<T: Scalar>(
66        &self,
67        node: &NodeId,
68        value: T,
69    ) -> Result<u32, ControlError> {
70        self.write_value(node, &value.into_variant()?).await
71    }
72
73    /// Write the Value attribute only. The Variant retains its exact type and dimensions.
74    /// The request supplies no data quality or timestamps. Limit: 128 KiB encoded Variant.
75    pub async fn write_value(
76        &self,
77        node: &NodeId,
78        value: &ua::Variant,
79    ) -> Result<u32, ControlError> {
80        check_values(std::iter::once(value)).ok_or(ControlError::InputLimit)?;
81        let (mut session, metadata) = self
82            .0
83            .read_session()
84            .await
85            .map_err(ControlError::Preflight)?;
86        let node = metadata
87            .namespaces
88            .wire_node(node, 0)
89            .map_err(ControlError::Preflight)?;
90        let request = ua::WriteRequest {
91            nodes_to_write: Some(vec![ua::WriteValue {
92                node_id: node,
93                attribute_id: ua::AttributeId::Value as u32,
94                value: ua::DataValue::value_only(value.clone()),
95                ..Default::default()
96            }]),
97            ..Default::default()
98        };
99        self.dispatch(
100            &mut session,
101            self.0.inner.request(request),
102            |reply| match reply.results.as_deref() {
103                Some([status]) => Some(status.bits()),
104                _ => None,
105            },
106        )
107        .await
108    }
109
110    /// Call one method on the supplied object. The wire inputs and outputs may be heterogeneous.
111    /// Up to 64 arguments and 128 KiB in aggregate encoded Variant data are accepted per direction.
112    /// Returns the server's operation status even for a rejected method or invalid input argument.
113    ///
114    /// ```
115    /// use opcua_kit::{Client, Control, NodeId, Scalar};
116    /// # async fn example(client: &Client, object: &NodeId, method: &NodeId) -> Result<(), Box<dyn std::error::Error>> {
117    /// let args = [42_u64.into_variant()?];
118    /// let reply = Control::new(client).call_method(object, method, &args).await?;
119    /// if reply.status == 0 && let [result] = reply.outputs.as_slice() {
120    ///     let value = u64::from_variant(result)?;
121    ///     println!("method returned {value:?}");
122    /// }
123    /// # Ok(()) }
124    /// ```
125    pub async fn call_method(
126        &self,
127        object: &NodeId,
128        method: &NodeId,
129        inputs: &[ua::Variant],
130    ) -> Result<CallOutcome, ControlError> {
131        check_values(inputs.iter()).ok_or(ControlError::InputLimit)?;
132        let (mut session, metadata) = self
133            .0
134            .read_session()
135            .await
136            .map_err(ControlError::Preflight)?;
137        let object = metadata
138            .namespaces
139            .wire_node(object, 0)
140            .map_err(ControlError::Preflight)?;
141        let method = metadata
142            .namespaces
143            .wire_node(method, 1)
144            .map_err(ControlError::Preflight)?;
145        let request = ua::CallRequest {
146            methods_to_call: Some(vec![ua::CallMethodRequest {
147                object_id: object,
148                method_id: method,
149                input_arguments: Some(inputs.to_vec()),
150            }]),
151            ..Default::default()
152        };
153        self.dispatch(&mut session, self.0.inner.request(request), |reply| {
154            call_outcome(reply, inputs.len())
155        })
156        .await
157    }
158
159    async fn dispatch<R, T>(
160        &self,
161        session: &mut ReadSession,
162        request: impl Future<Output = Result<R, ua::StatusCode>>,
163        decode: impl FnOnce(&R) -> Option<T>,
164    ) -> Result<T, ControlError> {
165        self.0.check_channel().map_err(ControlError::Preflight)?;
166        // Keep the session retired if this future is cancelled, if dispatch fails, or if
167        // the reply cannot be tied to exactly one operation on the original channel.
168        session.interrupted = true;
169        let response = request
170            .await
171            .map_err(|e| ControlError::Indeterminate(ReadError::Service(e)))?;
172        self.0
173            .check_channel()
174            .map_err(ControlError::Indeterminate)?;
175        let result = decode(&response).ok_or(ControlError::InvalidResponse)?;
176        session.interrupted = false;
177        Ok(result)
178    }
179}
180
181fn check_values<'a>(values: impl ExactSizeIterator<Item = &'a ua::Variant>) -> Option<()> {
182    if values.len() > MAX_ARGS {
183        return None;
184    }
185    let mut left = MAX_BYTES;
186    for value in values {
187        left = left.checked_sub(wire::variant_size(value)?)?;
188    }
189    Some(())
190}
191
192fn call_outcome(reply: &ua::CallResponse, inputs: usize) -> Option<CallOutcome> {
193    let [result] = reply.results.as_deref()? else {
194        return None;
195    };
196    let statuses = result.input_argument_results.as_deref().unwrap_or_default();
197    if !statuses.is_empty() && statuses.len() != inputs {
198        return None;
199    }
200    let outputs = result.output_arguments.as_deref().unwrap_or_default();
201    if status_severity(result.status_code.bits()) == Severity::Bad && !outputs.is_empty() {
202        return None;
203    }
204    check_values(outputs.iter())?;
205    Some(CallOutcome {
206        status: result.status_code.bits(),
207        input_statuses: statuses.iter().map(|s| s.bits()).collect(),
208        outputs: outputs.to_vec(),
209    })
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn variant_budgets_count_all_encoded_arguments() {
218        let bytes = |n| ua::Variant::ByteString(vec![0; n].into());
219        let at_limit = bytes(MAX_BYTES - 5);
220        assert!(check_values([&at_limit].into_iter()).is_some());
221        assert!(check_values([&at_limit, &bytes(0)].into_iter()).is_none());
222        assert!(check_values([&bytes(MAX_BYTES - 4)].into_iter()).is_none());
223        let values = (0..=MAX_ARGS).map(|_| bytes(0)).collect::<Vec<_>>();
224        assert!(check_values(values[..MAX_ARGS].iter()).is_some());
225        assert!(check_values(values.iter()).is_none());
226    }
227}