pub struct Client { /* private fields */ }Expand description
A native OPC UA client connected to one pinned server.
Implementations§
Source§impl Client
impl Client
Sourcepub async fn read_array<T: FixedScalar>(
&self,
node: &NodeId,
) -> Result<Sample<ArrayValue<T>>, ReadError>
pub async fn read_array<T: FixedScalar>( &self, node: &NodeId, ) -> Result<Sample<ArrayValue<T>>, ReadError>
Read a numeric or Boolean array, preserving status, both clocks, and matrix dimensions. Accepts at most 65,536 elements and 16 dimensions after response decoding.
Sourcepub async fn read_array_range<T: FixedScalar>(
&self,
node: &NodeId,
ranges: &[RangeInclusive<u32>],
) -> Result<Sample<ArrayValue<T>>, ReadError>
pub async fn read_array_range<T: FixedScalar>( &self, node: &NodeId, ranges: &[RangeInclusive<u32>], ) -> Result<Sample<ArrayValue<T>>, ReadError>
Read a rectangular section using OPC UA NumericRange. Each inclusive range selects one dimension; at most 65,536 elements and 16 dimensions are requested.
Source§impl Client
impl Client
Sourcepub async fn browse_children(
&self,
node: &NodeId,
) -> Result<Vec<BrowseEntry>, BrowseError>
pub async fn browse_children( &self, node: &NodeId, ) -> Result<Vec<BrowseEntry>, BrowseError>
List all forward local hierarchical children of one node, including reference subtypes. Output preserves server order. A listing is limited to 256 references, 256 pages, and 1 MiB of retained identifier/name text. A failure discards the partial listing.
Sourcepub async fn resolve_path(
&self,
start: &NodeId,
path: &[BrowseName],
) -> Result<NodeId, BrowseError>
pub async fn resolve_path( &self, start: &NodeId, path: &[BrowseName], ) -> Result<NodeId, BrowseError>
Follow 1–16 exact forward hierarchical browse names. Each step must match exactly one child on this server. The complete path shares one 256-page budget.
Source§impl Client
impl Client
Sourcepub fn connect(config: ConnectionConfig<'_>) -> Result<Self, ConnectError>
pub fn connect(config: ConnectionConfig<'_>) -> Result<Self, ConnectError>
Opens a Basic256Sha256 SignAndEncrypt channel and an anonymous user session.
The initial handshake is synchronous. On an async executor, call this method on a blocking worker. Each channel establishment checks the pinned server leaf.
Examples found in repository?
7fn main() -> Result<(), Box<dyn Error>> {
8 let args: Vec<_> = env::args().skip(1).collect();
9 if matches!(args.as_slice(), [arg] if arg == "-h" || arg == "--help") {
10 println!("Read UInt64 variables from an OPC UA server.\n\nUsage: {USAGE}");
11 return Ok(());
12 }
13 let [
14 endpoint,
15 server_uri,
16 server_cert,
17 client_uri,
18 client_cert,
19 key,
20 namespace,
21 ids @ ..,
22 ] = args.as_slice()
23 else {
24 return Err(format!("usage: {USAGE}").into());
25 };
26 if ids.is_empty() || ids.len() > opcua_kit::MAX_READ_NODES {
27 return Err("supply 1 to 1024 node identifiers".into());
28 }
29 let nodes = ids
30 .iter()
31 .map(|id| NodeId::new(namespace, id))
32 .collect::<Result<Vec<_>, _>>()?;
33 let client = Client::connect(ConnectionConfig {
34 endpoint,
35 server_application_uri: server_uri,
36 server_certificate_der: &fs::read(server_cert)?,
37 client_application_uri: client_uri,
38 client_certificate_der: &fs::read(client_cert)?,
39 client_private_key_der: &fs::read(key)?,
40 timeout: Duration::from_secs(5),
41 })?;
42 tokio::runtime::Builder::new_current_thread()
43 .enable_all()
44 .build()?
45 .block_on(async {
46 let result = client.read_scalars::<u64>(&nodes).await;
47 client.disconnect().await;
48 let mut unavailable = 0;
49 for (node, item) in nodes.iter().zip(result?) {
50 let id = node.identifier().escape_debug();
51 match item {
52 Ok(opcua_kit::Sample {
53 status: 0,
54 value: Some(value),
55 ..
56 }) => println!("{id} {value}"),
57 Ok(sample) => {
58 eprintln!("{id} unavailable (0x{:08X})", sample.status);
59 unavailable += 1;
60 }
61 Err(error) => {
62 eprintln!("{id} {error}");
63 unavailable += 1;
64 }
65 }
66 }
67 if unavailable != 0 {
68 return Err(format!("{unavailable} variable(s) unavailable").into());
69 }
70 Ok(())
71 })
72}Sourcepub fn connect_with(
config: ConnectionConfig<'_>,
options: ConnectionOptions<'_>,
) -> Result<Self, ConnectError>
pub fn connect_with( config: ConnectionConfig<'_>, options: ConnectionOptions<'_>, ) -> Result<Self, ConnectError>
Open a pinned encrypted session with an explicit policy and user identity.
Sourcepub fn connect_with_rollover(
config: ConnectionConfig<'_>,
options: ConnectionOptions<'_>,
rollover: CertificateRollover<'_>,
) -> Result<Self, ConnectError>
pub fn connect_with_rollover( config: ConnectionConfig<'_>, options: ConnectionOptions<'_>, rollover: CertificateRollover<'_>, ) -> Result<Self, ConnectError>
Open a pinned session during a planned certificate replacement. New handshakes accept the original leaf until the specified deadline, or the replacement within its certificate validity period. Both must identify the configured host and URI.
Sourcepub async fn disconnect(self)
pub async fn disconnect(self)
Closes the session and stops the client’s background driver.
Examples found in repository?
7fn main() -> Result<(), Box<dyn Error>> {
8 let args: Vec<_> = env::args().skip(1).collect();
9 if matches!(args.as_slice(), [arg] if arg == "-h" || arg == "--help") {
10 println!("Read UInt64 variables from an OPC UA server.\n\nUsage: {USAGE}");
11 return Ok(());
12 }
13 let [
14 endpoint,
15 server_uri,
16 server_cert,
17 client_uri,
18 client_cert,
19 key,
20 namespace,
21 ids @ ..,
22 ] = args.as_slice()
23 else {
24 return Err(format!("usage: {USAGE}").into());
25 };
26 if ids.is_empty() || ids.len() > opcua_kit::MAX_READ_NODES {
27 return Err("supply 1 to 1024 node identifiers".into());
28 }
29 let nodes = ids
30 .iter()
31 .map(|id| NodeId::new(namespace, id))
32 .collect::<Result<Vec<_>, _>>()?;
33 let client = Client::connect(ConnectionConfig {
34 endpoint,
35 server_application_uri: server_uri,
36 server_certificate_der: &fs::read(server_cert)?,
37 client_application_uri: client_uri,
38 client_certificate_der: &fs::read(client_cert)?,
39 client_private_key_der: &fs::read(key)?,
40 timeout: Duration::from_secs(5),
41 })?;
42 tokio::runtime::Builder::new_current_thread()
43 .enable_all()
44 .build()?
45 .block_on(async {
46 let result = client.read_scalars::<u64>(&nodes).await;
47 client.disconnect().await;
48 let mut unavailable = 0;
49 for (node, item) in nodes.iter().zip(result?) {
50 let id = node.identifier().escape_debug();
51 match item {
52 Ok(opcua_kit::Sample {
53 status: 0,
54 value: Some(value),
55 ..
56 }) => println!("{id} {value}"),
57 Ok(sample) => {
58 eprintln!("{id} unavailable (0x{:08X})", sample.status);
59 unavailable += 1;
60 }
61 Err(error) => {
62 eprintln!("{id} {error}");
63 unavailable += 1;
64 }
65 }
66 }
67 if unavailable != 0 {
68 return Err(format!("{unavailable} variable(s) unavailable").into());
69 }
70 Ok(())
71 })
72}Source§impl Client
impl Client
Sourcepub async fn read_attributes(
&self,
operands: &[ReadOperand<'_>],
) -> Result<Vec<DataValue>, ReadError>
pub async fn read_attributes( &self, operands: &[ReadOperand<'_>], ) -> Result<Vec<DataValue>, ReadError>
Read any combination of standard node attributes in caller order. Each operand counts toward the logical and per-request limits. NodeId values in these raw results carry the server’s session-local indices.
Sourcepub async fn read_definition(
&self,
node: &NodeId,
) -> Result<VariableDefinition, ReadError>
pub async fn read_definition( &self, node: &NodeId, ) -> Result<VariableDefinition, ReadError>
Read only DataType and ValueRank. A malformed attribute affects its own field. Service and session failures apply to the whole definition.
let definition = client.read_definition(node).await?;
let data_type = definition.data_type?;
let value_rank = definition.value_rank?;
if let (Some(id), Some(rank)) = (data_type.value, value_rank.value) {
println!("{} {} has rank {rank}", id.namespace(), id.identifier());
}Source§impl Client
impl Client
Sourcepub async fn read_history<T: FixedScalar>(
&self,
node: &NodeId,
start: OffsetDateTime,
end: OffsetDateTime,
limit: usize,
) -> Result<HistoricalRead<T>, HistoryError>
pub async fn read_history<T: FixedScalar>( &self, node: &NodeId, start: OffsetDateTime, end: OffsetDateTime, limit: usize, ) -> Result<HistoricalRead<T>, HistoryError>
Read raw historical Boolean or numeric values with both timestamps, without interpolation. The server must support raw HistoryRead for the chosen variable. Requests up to 256 values per page, 64 pages and 4096 total samples. A truncated interval returns an error.
Source§impl Client
impl Client
Sourcepub async fn read_meter(
&self,
contract: &Contract,
) -> Result<MeterReading, MeterReadError>
pub async fn read_meter( &self, contract: &Contract, ) -> Result<MeterReading, MeterReadError>
Read one approved import register as a serializable commissioning meter reading.
Each call checks the pinned server, the register’s DataType and scalar rank, and its independently resolved watt-hour property before requesting the process Value. The caller supplies and reviews the site’s register identity and import direction.
let reading = client.read_meter(contract).await?;
let json = serde_json::to_string(&reading)?;
println!("{json}");Source§impl Client
impl Client
Sourcepub async fn read_snapshot(
&self,
contract: &Contract,
) -> Result<Snapshot, SnapshotReadError>
pub async fn read_snapshot( &self, contract: &Contract, ) -> Result<Snapshot, SnapshotReadError>
Observe only the commissioned declarations and requested standard unit properties. The snapshot preserves the contract order and actual operation status, including a Good status without a value. A missing namespace yields a row with just the identity. The compact document plus newline is bounded at 4 MiB before appending each row. Service-response decoding occurs before this application-level output check. ServerArray, NamespaceArray and MaxNodesPerRead are reserved session bootstrap nodes. Selecting one in the contract fails before the client reads any of those Values.
let snapshot = client.read_snapshot(contract).await?;
let report = opcua_kit::commissioning::assess(contract, &snapshot)?;
println!("{:?}", report.decision);Source§impl Client
impl Client
Sourcepub async fn subscribe(
&self,
node: &NodeId,
interval: Duration,
) -> Result<DataChanges<'_>, SubscriptionError>
pub async fn subscribe( &self, node: &NodeId, interval: Duration, ) -> Result<DataChanges<'_>, SubscriptionError>
Subscribe to sampled data changes for one selected Value. The supplied interval applies to sampling and publishing (10 ms to 60 s); inspect the revised intervals on the returned handle. Up to eight handles can be active per client.
Sourcepub async fn subscribe_many(
&self,
nodes: &[NodeId],
interval: Duration,
) -> Result<MonitoredDataChanges<'_>, SubscriptionError>
pub async fn subscribe_many( &self, nodes: &[NodeId], interval: Duration, ) -> Result<MonitoredDataChanges<'_>, SubscriptionError>
Monitor 1–32 nodes in one subscription. Each result refers to the corresponding input index, including repeated nodes. All namespaces are resolved before creation. An item rejection fails the entire setup and releases any accepted siblings. A timeout leaves the subscription usable. After a terminal loss, resynchronize all values and create a fresh subscription. The shared local queue holds 32 notifications.
let mut changes = client.subscribe_many(&[pressure, fan], Duration::from_millis(250)).await?;
let change = changes.next(Duration::from_secs(5)).await?;
let source = &changes.items()[change.index].node;
println!("{}: {:?}", source.identifier(), change.value);Source§impl Client
impl Client
Sourcepub async fn read_engineering_units(
&self,
signal: &NodeId,
) -> Result<EngineeringUnitEvidence, ReadError>
pub async fn read_engineering_units( &self, signal: &NodeId, ) -> Result<EngineeringUnitEvidence, ReadError>
Resolve the standard EngineeringUnits property and verify its declared type and rank before reading its value. The signal’s process Value is never requested. Lookup visits at most 256 forward HasProperty references and 256 pages. A malformed response envelope or an unusable continuation token (over 64 KiB) retires the session. Disconnect to release its remaining resources.
let evidence = client.read_engineering_units(node).await?;
if let Some(unit) = evidence.sample.value.filter(|unit| unit.is_identified()) {
println!("{} {}", unit.namespace_uri, unit.unit_id);
}Source§impl Client
impl Client
Sourcepub async fn read(&self, node: &NodeId) -> Result<DataValue, ReadError>
pub async fn read(&self, node: &NodeId) -> Result<DataValue, ReadError>
Read a single Value attribute, including its raw status and both clock fields.
Sourcepub async fn read_scalar<T: Scalar>(
&self,
node: &NodeId,
) -> Result<Sample<T>, ReadError>
pub async fn read_scalar<T: Scalar>( &self, node: &NodeId, ) -> Result<Sample<T>, ReadError>
Read an exact OPC UA scalar as its native Rust type, preserving node status and clocks.
Sourcepub async fn read_scalars<T: Scalar>(
&self,
nodes: &[NodeId],
) -> Result<Vec<Result<Sample<T>, ReadError>>, ReadError>
pub async fn read_scalars<T: Scalar>( &self, nodes: &[NodeId], ) -> Result<Vec<Result<Sample<T>, ReadError>>, ReadError>
Read a batch as one Rust scalar type. Results follow input order, including duplicates. A scalar-decoding error affects only its entry. A node with Bad or Uncertain status yields a sample with its status and an absent value. A service or namespace error fails the entire batch.
Examples found in repository?
7fn main() -> Result<(), Box<dyn Error>> {
8 let args: Vec<_> = env::args().skip(1).collect();
9 if matches!(args.as_slice(), [arg] if arg == "-h" || arg == "--help") {
10 println!("Read UInt64 variables from an OPC UA server.\n\nUsage: {USAGE}");
11 return Ok(());
12 }
13 let [
14 endpoint,
15 server_uri,
16 server_cert,
17 client_uri,
18 client_cert,
19 key,
20 namespace,
21 ids @ ..,
22 ] = args.as_slice()
23 else {
24 return Err(format!("usage: {USAGE}").into());
25 };
26 if ids.is_empty() || ids.len() > opcua_kit::MAX_READ_NODES {
27 return Err("supply 1 to 1024 node identifiers".into());
28 }
29 let nodes = ids
30 .iter()
31 .map(|id| NodeId::new(namespace, id))
32 .collect::<Result<Vec<_>, _>>()?;
33 let client = Client::connect(ConnectionConfig {
34 endpoint,
35 server_application_uri: server_uri,
36 server_certificate_der: &fs::read(server_cert)?,
37 client_application_uri: client_uri,
38 client_certificate_der: &fs::read(client_cert)?,
39 client_private_key_der: &fs::read(key)?,
40 timeout: Duration::from_secs(5),
41 })?;
42 tokio::runtime::Builder::new_current_thread()
43 .enable_all()
44 .build()?
45 .block_on(async {
46 let result = client.read_scalars::<u64>(&nodes).await;
47 client.disconnect().await;
48 let mut unavailable = 0;
49 for (node, item) in nodes.iter().zip(result?) {
50 let id = node.identifier().escape_debug();
51 match item {
52 Ok(opcua_kit::Sample {
53 status: 0,
54 value: Some(value),
55 ..
56 }) => println!("{id} {value}"),
57 Ok(sample) => {
58 eprintln!("{id} unavailable (0x{:08X})", sample.status);
59 unavailable += 1;
60 }
61 Err(error) => {
62 eprintln!("{id} {error}");
63 unavailable += 1;
64 }
65 }
66 }
67 if unavailable != 0 {
68 return Err(format!("{unavailable} variable(s) unavailable").into());
69 }
70 Ok(())
71 })
72}Sourcepub async fn read_many(
&self,
nodes: &[NodeId],
) -> Result<Vec<DataValue>, ReadError>
pub async fn read_many( &self, nodes: &[NodeId], ) -> Result<Vec<DataValue>, ReadError>
Read up to MAX_READ_NODES Value attributes in order, including repeated nodes.
The client splits requests at the session’s advertised MaxNodesPerRead and
uses singleton requests when the limit is unavailable or zero. Each request
can observe a different instant. A failed service returns no partial batch.
An empty slice succeeds without contacting the server.