Skip to main content

opcua_tag_browser/
lib.rs

1//! An OPC UA client for PLC data.
2//!
3//! Point a [`Collector`] at a PLC and it discovers every tag, subscribes to as
4//! many as the server will monitor, polls the rest, reconnects when the link
5//! drops, and streams every change to a sink you choose. [`TagClient`] reads
6//! and writes individual values on demand.
7//!
8//! ```no_run
9//! use opcua_tag_browser::{Collector, TagChange};
10//!
11//! # fn main() -> opcua_tag_browser::Result<()> {
12//! Collector::new("line1", "opc.tcp://192.168.201.2:4840")
13//!     .insecure()
14//!     .sink(|e: &TagChange<'_>| println!("{} = {}", e.path(), e.value))
15//!     .run()
16//! # }
17//! ```
18//!
19//! # Selecting what to collect
20//!
21//! A PLC may expose thousands of nodes, and servers cap how many can be
22//! monitored at once. Selecting fewer than the ceiling means everything arrives
23//! by subscription and polling never engages.
24//!
25//! ```no_run
26//! # use opcua_tag_browser::Collector;
27//! # fn c() -> Collector { Collector::new("a", "b") }
28//! c().only(["Machine/Axis1/Speed", "Machine/Axis1/Position"]);
29//! c().matching("Machine/Axis*/Speed");
30//! c().select(|tag| tag.path.starts_with("Machine/") && !tag.path.contains("Diag"));
31//! ```
32//!
33//! # Writing values
34//!
35//! ```no_run
36//! use opcua_tag_browser::Collector;
37//!
38//! # fn main() -> opcua_tag_browser::Result<()> {
39//! let plc = Collector::new("line1", "opc.tcp://192.168.201.2:4840")
40//!     .insecure()
41//!     .client()?;
42//!
43//! plc.set("Machine/Axis1/Setpoint", 1500.0)?;
44//! plc.set("Machine/Enable", true)?;
45//!
46//! println!("{}", plc.get("Machine/Axis1/Speed")?);
47//! # Ok(())
48//! # }
49//! ```
50//!
51//! [`TagClient`] is `Clone` and `Send`, so it can be moved into another thread
52//! while a collector's event loop runs.
53//!
54//! # Security
55//!
56//! [`ConnectOptions::default`] signs and encrypts with `Basic256Sha256` and
57//! rejects untrusted server certificates. That fails against a server
58//! configured for plaintext, which is deliberate: calling
59//! [`Collector::insecure`] records the decision in your source instead of
60//! inheriting it from a default.
61//!
62//! ```
63//! use opcua_tag_browser::{ConnectOptions, Security};
64//! use opcua_tag_browser::opcua::client::prelude::SecurityPolicy;
65//!
66//! let secure = ConnectOptions::default()
67//!     .security(Security::SignAndEncrypt(SecurityPolicy::Basic256Sha256))
68//!     .user_name("collector", "hunter2");
69//! ```
70//!
71//! Sending a username over an unencrypted channel returns
72//! [`Error::InsecureCredentials`] rather than transmitting it, and
73//! [`Credentials`] redacts passwords in `Debug` output so they cannot reach a
74//! log by accident.
75//!
76//! # Sinks
77//!
78//! [`TagSink`] is the seam between the crate and your application; the crate
79//! decides nothing about where data goes. A closure implements it, and
80//! [`sinks::LogSink`] and [`sinks::JsonlSink`] ship ready to use.
81//!
82//! ```
83//! use opcua_tag_browser::{TagChange, TagSink};
84//!
85//! struct Threshold;
86//!
87//! impl TagSink for Threshold {
88//!     fn tag_changed(&self, event: &TagChange<'_>) {
89//!         if event.as_f64().is_some_and(|v| v > 100.0) {
90//!             println!("{} is high: {}", event.path(), event.value);
91//!         }
92//!     }
93//! }
94//! ```
95//!
96//! # Shutting down
97//!
98//! The crate never calls `process::exit`. In a binary,
99//! [`Collector::handle_ctrl_c`] wires up a handler; inside a larger
100//! application, take a [`CollectorHandle`] and stop it yourself.
101//!
102//! Closing sessions on exit matters more than it looks. A server does not learn
103//! an abandoned session is gone until it times out, and until then its
104//! monitored items still count against the budget.
105//!
106//! # Lower-level pieces
107//!
108//! [`Collector`] composes parts that stay public. Reach for them when you want
109//! the address space but not the monitoring:
110//!
111//! | Type | Role |
112//! | --- | --- |
113//! | [`connect`] | open a session |
114//! | [`PlcSession`] | session operations, with `opcua` panics contained |
115//! | [`NodeBrowser`] | list a node's children, pagination handled |
116//! | [`NodeFilter`] | reject server furniture |
117//! | [`TreeScanner`] | walk the tree into [`PlcTag`] values |
118//! | [`TagSet`] | index tags for lookup by path, name, or glob |
119//! | [`TagRepository`] | cache the result |
120//!
121//! # Feature flags
122//!
123//! | Feature | Default | Effect |
124//! | --- | --- | --- |
125//! | `monitoring` | yes | [`Collector`], subscriptions, polling |
126//! | `write` | yes | [`TagClient`], `Collector::client`, `PlcSession::write`, `OpcUaSession::inner`: everything that can change a PLC |
127//! | `json-cache` | yes | [`JsonFileTagRepository`] and tag caching |
128//! | `jsonl-sink` | no | [`sinks::JsonlSink`] and [`Collector::jsonl`] |
129//! | `ctrl-c` | no | [`Collector::handle_ctrl_c`] |
130//! | `full` | no | all of the above |
131//!
132//! # Version compatibility
133//!
134//! This crate re-exports the [`opcua`] crate it was built against. Use that
135//! path rather than your own `opcua` dependency, or a version mismatch produces
136//! type errors that look unrelated to their cause.
137//!
138//! | `opcua-tag-browser` | `opcua` |
139//! | --- | --- |
140//! | `0.2` | `0.12` |
141//! | `0.1` | `0.12` |
142//!
143//! # Minimum supported Rust version
144//!
145//! 1.75. Raising it is a breaking change.
146
147#![deny(missing_docs)]
148#![deny(rustdoc::broken_intra_doc_links)]
149#![forbid(unsafe_code)]
150
151mod browser;
152mod connection;
153mod endpoint;
154mod error;
155mod filter;
156mod scanner;
157mod session;
158mod tag;
159mod tagset;
160mod variant;
161
162#[cfg(feature = "json-cache")]
163mod repository;
164
165#[cfg(feature = "monitoring")]
166mod attributes;
167#[cfg(feature = "monitoring")]
168mod backoff;
169#[cfg(feature = "monitoring")]
170mod collector;
171#[cfg(feature = "monitoring")]
172mod live;
173#[cfg(feature = "monitoring")]
174mod monitor;
175#[cfg(feature = "monitoring")]
176mod sink;
177#[cfg(feature = "monitoring")]
178pub mod sinks;
179#[cfg(all(feature = "monitoring", feature = "write"))]
180mod writer;
181
182pub use browser::{BrowsedNode, NodeBrowser, OpcUaNodeBrowser};
183pub use connection::{
184    client_certificate, connect, ClientCertificate, ConnectOptions, ConnectionInfo, Credentials,
185    Security,
186};
187pub use error::{Error, Result};
188pub use filter::{AcceptAll, DefaultNodeFilter, NodeFilter};
189pub use scanner::{ScanOptions, ScanProgress, ScanReport, TreeScanner};
190pub use session::{catch_panic, panic_message, OpcUaSession, PlcSession};
191pub use tag::PlcTag;
192pub use tagset::TagSet;
193pub use variant::{
194    format_quality, format_variant, variant_as_bool, variant_as_f64, variant_as_i64,
195};
196
197#[cfg(feature = "json-cache")]
198pub use repository::{JsonFileTagRepository, TagRepository};
199
200#[cfg(feature = "monitoring")]
201pub use collector::{Collector, CollectorHandle};
202#[cfg(feature = "monitoring")]
203pub use monitor::MonitorOptions;
204#[cfg(feature = "monitoring")]
205pub use sink::{ConnectionChange, Source, TagChange, TagSink};
206#[cfg(all(feature = "monitoring", feature = "write"))]
207pub use writer::TagClient;
208
209/// Scans an endpoint and returns its tags.
210///
211/// Convenience over [`Collector::discover`] for a one-off look at a server.
212/// Connects insecurely and does not cache.
213///
214/// ```no_run
215/// let tags = opcua_tag_browser::discover("opc.tcp://192.168.201.2:4840")?;
216/// for tag in tags.iter().take(20) {
217///     println!("{}", tag.path);
218/// }
219/// # Ok::<(), opcua_tag_browser::Error>(())
220/// ```
221#[cfg(all(feature = "monitoring", feature = "json-cache"))]
222pub fn discover(endpoint_url: &str) -> Result<TagSet> {
223    Collector::new("discover", endpoint_url)
224        .insecure()
225        .no_cache()
226        .discover()
227}
228
229/// The `opcua` crate this library was compiled against.
230///
231/// The public API exposes `NodeId`, `StatusCode`, `Variant`, `NodeClass`, and
232/// `SecurityPolicy` from it. Use this re-export rather than declaring your own
233/// `opcua` dependency.
234///
235/// ```
236/// use opcua_tag_browser::opcua::client::prelude::NodeId;
237///
238/// let node = NodeId::new(2, "MyTag".to_string());
239/// ```
240pub use opcua;