Skip to main content

read/
read.rs

1//! Read one or more UInt64 variables through a pinned native OPC UA session.
2use opcua_kit::{Client, ConnectionConfig, NodeId};
3use std::{env, error::Error, fs, time::Duration};
4
5const USAGE: &str = "cargo run --example read -- ENDPOINT SERVER_URI SERVER.der CLIENT_URI CLIENT.der CLIENT_KEY.der NAMESPACE_URI NODE_ID [NODE_ID ...]";
6
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}