opcua_kit/client/conditions.rs
1//! Standard OPC UA Part 9 methods for a retained state or a specific condition event.
2use super::{CallOutcome, Control, ControlError, Events, ua};
3use crate::NodeId;
4
5const UA: &str = "http://opcfoundation.org/UA/";
6
7fn standard(id: &str) -> NodeId {
8 NodeId::new(UA, id).expect("standard numeric NodeId")
9}
10
11/// Optional localized operator comment applied to the state identified by an EventId.
12/// Pass `None` to preserve the existing comment, or a locale with empty text to clear it.
13#[derive(Clone, Copy, Debug)]
14pub struct ConditionComment<'a> {
15 /// Locale identifier of the supplied text, for example `"en-US"`.
16 pub locale: &'a str,
17 /// Operator comment in the supplied locale.
18 pub text: &'a str,
19}
20
21/// A condition method could not be prepared or its Call response could not be obtained.
22/// An operation-level rejection from the server is returned in [`CallOutcome::status`].
23#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum ConditionError {
26 /// A standard condition type was supplied where the method requires a condition instance.
27 #[error("use the ConditionId of the reported condition instance")]
28 InvalidCondition,
29 /// EventIds are opaque and must contain one through 65,536 bytes.
30 #[error("a condition EventId must contain 1 to 65536 bytes")]
31 InvalidEventId,
32 /// The encoded comment strings contain NUL or exceed the combined 16 KiB limit.
33 #[error("the comment must be NUL-free and its locale and text must fit in 16 KiB")]
34 InvalidComment,
35 /// The event subscription has already failed. Recreate it before requesting refresh.
36 #[error("the event stream has ended")]
37 Ended,
38 /// The standard Call failed locally or has an indeterminate remote outcome.
39 #[error(transparent)]
40 Call(#[from] ControlError),
41}
42
43impl Control<'_> {
44 /// Acknowledge the reported branch state by its condition instance and opaque EventId.
45 /// Supply the ConditionId and EventId from the same notification on this server where
46 /// AckedState/Id was false. The separate BranchId identifies a retained branch.
47 /// A server can reject an unknown EventId or an already acknowledged state.
48 ///
49 /// ```
50 /// use opcua_kit::{Client, ConditionComment, ConditionError, Control, NodeId};
51 ///
52 /// async fn acknowledge(client: &Client, condition: &NodeId, event_id: &[u8])
53 /// -> Result<u32, ConditionError>
54 /// {
55 /// let comment = ConditionComment { locale: "en", text: "Operator reviewed" };
56 /// let result = Control::new(client)
57 /// .acknowledge_condition(condition, event_id, Some(comment))
58 /// .await?;
59 /// Ok(result.status)
60 /// }
61 /// ```
62 pub async fn acknowledge_condition(
63 &self,
64 condition: &NodeId,
65 event_id: &[u8],
66 comment: Option<ConditionComment<'_>>,
67 ) -> Result<CallOutcome, ConditionError> {
68 self.condition_method("i=9111", condition, event_id, comment)
69 .await
70 }
71
72 /// Confirm the reported branch state by its condition instance and opaque EventId.
73 /// Use the EventId for the state whose ConfirmedState/Id was false, including when the
74 /// server issued a new EventId after acknowledgement. Confirm requires server support.
75 pub async fn confirm_condition(
76 &self,
77 condition: &NodeId,
78 event_id: &[u8],
79 comment: Option<ConditionComment<'_>>,
80 ) -> Result<CallOutcome, ConditionError> {
81 self.condition_method("i=9113", condition, event_id, comment)
82 .await
83 }
84
85 async fn condition_method(
86 &self,
87 method: &str,
88 condition: &NodeId,
89 event_id: &[u8],
90 comment: Option<ConditionComment<'_>>,
91 ) -> Result<CallOutcome, ConditionError> {
92 if condition.namespace() == UA
93 && matches!(condition.identifier(), "i=2782" | "i=2881" | "i=2915")
94 {
95 return Err(ConditionError::InvalidCondition);
96 }
97 if !(1..=65536).contains(&event_id.len()) {
98 return Err(ConditionError::InvalidEventId);
99 }
100 let text = match comment {
101 Some(c) => {
102 if c.locale.len().saturating_add(c.text.len()) > 16 * 1024
103 || c.locale.contains('\0')
104 || c.text.contains('\0')
105 {
106 return Err(ConditionError::InvalidComment);
107 }
108 ua::LocalizedText::new(c.locale, c.text)
109 }
110 None => ua::LocalizedText::default(),
111 };
112 let arguments = [
113 ua::Variant::ByteString(ua::ByteString::from(event_id.to_vec())),
114 ua::Variant::LocalizedText(Box::new(text)),
115 ];
116 Ok(self
117 .call_method(condition, &standard(method), &arguments)
118 .await?)
119 }
120}
121
122impl Events {
123 /// Request retained condition events for this subscription on its own authenticated session.
124 /// It can run while an outstanding Publish waits for a notification or keepalive.
125 /// A Good method result accepts the request. Observe RefreshStart and RefreshEnd events and
126 /// retained notifications through [`Events::next`] to complete a refresh.
127 pub async fn refresh_conditions(&mut self) -> Result<CallOutcome, ConditionError> {
128 let (client, subscription) = self.condition_session().ok_or(ConditionError::Ended)?;
129 let args = [ua::Variant::UInt32(subscription)];
130 Ok(Control::new(client)
131 .call_method(&standard("i=2782"), &standard("i=3875"), &args)
132 .await?)
133 }
134}