Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

A native OPC UA client connected to one pinned server.

Implementations§

Source§

impl Client

Source

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.

Source

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

Source

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.

Source

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

Source

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?
examples/read.rs (lines 33-41)
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

pub fn connect_with( config: ConnectionConfig<'_>, options: ConnectionOptions<'_>, ) -> Result<Self, ConnectError>

Open a pinned encrypted session with an explicit policy and user identity.

Source

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.

Source

pub fn principal(&self) -> &str

Authenticated contract scope: anonymous or username:<account>.

Source

pub async fn disconnect(self)

Closes the session and stops the client’s background driver.

Examples found in repository?
examples/read.rs (line 47)
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

Source

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.

Source

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

Source

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

Source

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

Source

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

Source

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.

Source

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

Source

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

Source

pub async fn read(&self, node: &NodeId) -> Result<DataValue, ReadError>

Read a single Value attribute, including its raw status and both clock fields.

Source

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.

Source

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?
examples/read.rs (line 46)
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

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.

Auto Trait Implementations§

§

impl !Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Forget for Client

§

impl Move for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl UnsafeUnpin for Client

§

impl UnwindSafe for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.