OPC UA Client
Learn how to connect to an OPC UA server using the Heisenware OPC UA client.
The OPC UA client connector (OpcuaClient) communicates with OPC UA servers. It manages secure connections, browses the server's address space, reads and writes variables, calls methods, monitors data for changes, and transfers files.
This connector requires instance creation before you can manage the connection and session with a server. For secure connections, generate certificates using createCertificates.
See the Video demo at the bottom of this page.
Security and certificates
For unencrypted connections, skip directly to Connection and lifecycle.
Secure OPC UA communication (Sign or SignAndEncrypt) requires a Public Key Infrastructure (PKI) to manage digital certificates and establish trust between the client and the server. Only create a PKI store when connecting with a securityMode of Sign or SignAndEncrypt. For unsecured connections, you can ignore certificate management.
Self-signed and CA-signed certificates
createCertificates prepares the client for secure connections in one of two modes:
Self-signed (default): The client creates its own certificate without a signature from a certificate authority. This is the simplest approach and works best for most scenarios.
CA-signed (set
useCAtotrue): The client creates its own Certificate Authority (CA) to sign the application and user certificates. Use this if the server trusts a single CA instead of multiple individual client certificates.
Establishing trust
OPC UA security requires a two-way trust model:
The server trusts the client: Configure the server to accept the client's public certificate.
The client trusts the server: Add the server's public certificate to the client's trust list to prevent man-in-the-middle attacks.
Manage this process using createCertificates and addServerCertificate.
Client PKI folder structure
createCertificates generates a standard pki folder structure:
pki/own/certs/: The client's public certificates (for example,heisenware_opcua_client.pem). Provide this file to the server administrator.pki/own/private/: The client's private keys. Keep these keys secret. The client automatically restricts access permissions.pki/trusted/certs/: The client's trust list. Place the public certificates of trusted OPC UA servers in this folder. UseaddServerCertificateto automate this.pki/issuers/certs/: In CA mode, this folder holds the public certificate of the CA that issues certificates. If an external CA signed the server certificate, add the server's public CA certificate here usingaddCertificateAuthority.
PKI store location
The location of the pki folder depends on where the client runs:
Agent: The folder resides in the same directory as your Agent executable.
Platform: The folder resides under
/shared/certificates. Click the refresh icon in the File Explorer to view it.
Certificate management
These static functions manage secure connection setup.
createCertificates
Initializes the local PKI store and creates a client certificate for the application and a user certificate for authentication. By default, this function creates self-signed certificates. Run this function once. Existing certificates are kept on repeated runs.
Parameters
options
useCA
Creates a local Certificate Authority to sign the certificates. Default false.
boolean
Output
Returns true when the PKI structure and certificates are successfully created.
addServerCertificate
Adds a server's public certificate to the client's trust list to establish a secure connection.
Parameters
certificateInput
The server's public certificate, specified as a file path or PEM string.
string
certificateName
An optional filename for the certificate. Required if providing a PEM string.
string
Output
Returns true when the certificate is saved successfully. Throws an error if the input is missing, the filename is missing for a PEM string, or saving fails.
Examples
Example 1: Add a certificate from a file
If the client runs on the platform (not in Agent mode), upload the server certificate using the File Explorer, drag the file to this parameter, and then delete it from the uploads folder.
Example 2: Add a certificate from a string
addCertificateAuthority
Adds a server's public CA certificate to the issuers directory of the PKI store. Use this if a Certificate Authority signed the server certificate.
Parameters
certificateInput
The CA's public certificate, specified as a file path or PEM string.
string
certificateName
An optional filename for the CA certificate. Required if providing a PEM string.
string
Output
Returns true when the certificate is saved successfully. Throws an error if the input is missing, the filename is missing for a PEM string, or saving fails.
Connection and lifecycle
create
Creates an OPC UA client instance. The security settings determine how the client connects.
Parameters
options
securityMode
The security mode to use (None, Sign, or SignAndEncrypt). Default None.
string
securityPolicy
The encryption algorithm to use (such as Basic256Sha256). Default None.
string
automaticallyAcceptUnknownCertificate
Disables server validation. Default false.
boolean
Security risk
Never set automaticallyAcceptUnknownCertificate to true in production. This disables server validation and exposes the system to man-in-the-middle attacks. Use it for debugging purposes only.
Output
Returns the name of the created instance.
Examples
Example 1: Create a client for an unsecured connection
Example 2: Create a client for a secure connection
connect
Connects to an OPC UA server. If a secure connection fails, see Tips and tricks for troubleshooting the chain of trust.
Parameters
endpointUrl
The full URL of the server endpoint (such as opc.tcp://my-server.com:4840).
string
userIdentity
username
The username for authentication.
string
password
The password for authentication.
string
userCertificate
The user certificate for certificate-based authentication.
string
userPrivateKey
The private key belonging to the user certificate.
string
useDefaultUserCertificate
Set to true to authenticate with the user certificate created by createCertificates. Default false.
boolean
Output
Returns true when the connection succeeds or the client is already connected. Returns the string reconnect ongoing if an automatic reconnection is in progress. Throws an error on failure.
Examples
Each scenario shows the inputs of both create and connect.
Example 1: Unsecured, anonymous connection
Requires no PKI setup and no user identity.
Example 2: Secure, anonymous connection
Requires the PKI setup (createCertificates and addServerCertificate) but no user identity.
Example 3: Secure connection with username and password
Requires the PKI setup for a secure channel, plus credentials for user authentication.
Example 4: Secure connection with a user certificate
The most secure method, using certificates for both channel security and user authentication.
disconnect
Disconnects from the OPC UA server and closes the active session.
Parameters
None.
Output
Returns true on successful disconnection, including when no connection exists.
isConnected
Checks whether the client is connected to the server.
Parameters
None.
Output
Returns true if connected, or false if disconnected.
delete
Removes the client instance and closes the connection.
Irreversible action
Deleting an instance removes its configuration. To communicate with the server again, you must create a new instance.
Parameters
None.
Output
Returns true upon removal.
Browsing
browse
Browses a node address on the server.
Parameters
address
The nodeId or browse path (such as /0:Objects/2:Demo) where browsing starts.
string
Output
Returns an array of objects representing each node found, including its name, ID, and class.
Example
browseObjects
Browses the server's Objects folder.
Parameters
path
An optional browse path starting inside the Objects folder, or a nodeId. Browses the Objects folder itself if omitted.
string
Output
Returns an array of objects representing each node found.
Example
browseTypes
Browses the server's Types folder to explore the data type hierarchy.
Parameters
path
An optional browse path starting inside the Types folder.
string
Output
Returns an array of objects representing each node found.
Example
browseViews
Browses the server's Views folder.
Parameters
path
An optional browse path starting inside the Views folder.
string
Output
Returns an array of objects representing each node found.
Example
Reading and writing
readNode
Reads all attributes of an OPC UA node.
Parameters
address
The nodeId or browse path of the node to read.
string
Output
Returns a JSON object containing the node's attributes, status code, and timestamps.
Examples
Example 1: Read using a nodeId
Example 2: Read using a browse path
readVariable
Reads the value of a single variable from the server.
Parameters
address
The nodeId or browse path of the variable to read.
string
Output
Returns the raw value of the variable.
Examples
Example 1: Read using a nodeId
Example 2: Read using a browse path
writeVariable
Writes a new value to a server variable. Converts the value to the required OPC UA data type before writing. If the variable is read-only, this function throws an error.
Parameters
address
The nodeId or browse path of the variable.
string
value
The new value to set.
any
options
skipTypeChecking
If true, the client skips reading metadata and permissions before writing. Default false.
boolean
Output
Returns nothing on a successful write. Throws an error on failure.
Example
callMethod
Invokes a method on an OPC UA object.
Parameters
methodAddress
The nodeId or browse path of the method to call.
string
inputValues
An array of input arguments. Default [].
array
Output
Returns an array containing the output arguments from the method call. Throws an error if the number of input values does not match the method definition or the call fails.
Example
Monitoring
monitorNode
Subscribes to changes of an OPC UA node. Triggers the callback on every change.
Parameters
address
The nodeId or browse path of the node.
string
listener
Callback evaluated on every change. Receives a JSON object containing the variable's dataType and value.
callback
options
samplingInterval
How often the server checks for changes, in milliseconds. Default 1000.
integer
queueSize
Maximum number of queued notifications on the server. Default 100.
integer
discardOldest
If true, drops the oldest notification when the queue is full. Default true.
boolean
Output
Returns the resolved nodeId of the monitored item. Use this ID with stopMonitor to terminate monitoring.
Example
monitorVariable
Subscribes to value changes of a variable. Triggers the callback with the new value on every change.
Parameters
address
The nodeId or browse path of the variable.
string
listener
Callback evaluated on every change. Receives the raw value of the variable.
callback
options
samplingInterval
How often the server checks for changes, in milliseconds. Default 1000.
integer
queueSize
Maximum number of queued notifications on the server. Default 100.
integer
discardOldest
If true, drops the oldest notification when the queue is full. Default true.
boolean
Output
Returns the resolved nodeId of the monitored item. Use this ID with stopMonitor to terminate monitoring.
Example
stopMonitor
Stops an active subscription for a monitored item.
Parameters
nodeId
The nodeId returned by monitorNode or monitorVariable.
string
Output
Returns true when the subscription terminates successfully. Throws an error on failure.
Example
File transfer
browseDirectory
Recursively browses a directory structure on the server.
Parameters
address
The nodeId or browse path of the directory node.
string
Output
Returns a nested array of objects representing the directory structure.
readFile
Reads the contents of a file on the server.
Parameters
address
The nodeId or browse path of the file.
string
options
encoding
The encoding of the returned content (such as ascii or utf8). Default base64.
string
Output
Returns the file content as a string in the requested encoding.
Example
writeFile
Creates a file on the server and uploads content to it.
Parameters
folderAddress
The nodeId or browse path of the target folder.
string
newFileName
The name of the new file.
string
pathOrBase64
The file content, specified as a base64 string or local file path.
string
Output
Returns the nodeId of the newly created file on the server.
Example
deleteFile
Deletes a file on the server.
Irreversible action
Deleting a file permanently removes it from the server. This action cannot be undone.
Parameters
folderAddress
The nodeId or browse path of the folder containing the file.
string
fileName
The name of the file to delete.
string
Output
Returns true when the file is successfully deleted, or false if the deletion fails or the folder provides no delete capability. Throws an error if the file cannot be found.
Example
Event listeners
listenToEvents
Registers a callback to receive client lifecycle events.
Parameters
listener
Callback evaluated on client lifecycle events. Receives one of the following event strings: Connected, Connection Failed, Connection Lost, Started Reconnection, Connection Re-Established, Back Off, Security Token Renewed, Request Timed Out, Session Closed, Subscription Started, Subscription Keep Alive, Subscription Terminated.
callback
Output
Returns true on successful registration.
Deprecated functions
The following functions are maintained for backward compatibility. Update your App logic to use the recommended replacements.
readVariableValue
readVariable
writeVariableValue
writeVariable
Tips and tricks
Establishing a secure certificate-based connection is the primary point of failure in OPC UA. An error usually indicates a broken link in the chain of trust. Use these troubleshooting steps to resolve common issues.
Switch an existing instance to a secure connection
To switch an unsecured instance to a secure connection, remove the instance and create it again. Right-click the existing active instance (green in the UI), click Remove, and the instance turns yellow to indicate it is not available. Trigger the create function again to apply your new security configuration.
Server rejects the client certificate
If the client attempts to connect and the server immediately closes the connection (often showing an error such as The connection has been disconnected by third party), the server does not trust the client's application certificate.
To resolve this (using Prosys Simulation Server as an example):
Attempt to connect the client to the Prosys server. This fails but registers the client's certificate with the server.
Open the Certificates tab in the Prosys Simulation Server UI.
Locate the client certificate (
HeisenwareOPCUAClient) in the Rejected Certificates list.Right-click the certificate and select Trust to move it to the Trusted Certificates list.
Connect again.
In CA mode, add the CA's public certificate (heisenware_ca_cert.pem) to the server's PKI issuers directory (pki/CA/issuers/certs/) instead of trusting individual certificates.
Client rejects the server certificate
If the client does not trust the server, it fails with the error server Certificate verification failed.
To resolve this, add the server's public certificate to the client's trust store:
Export the server's public certificate file (such as exporting from the Prosys Certificates tab).
Use
addServerCertificateto save the file to the client'spki/trusted/certsfolder.
SAN mismatch
Even with established trust, the client rejects the connection if the hostname in the endpoint URL does not match any address in the server certificate's Subject Alternative Name (SAN) field.
To resolve this (using Prosys as an example):
If connecting to
opc.tcp://localhost:53530fails, inspect the certificate. If the SAN field only listsDNS:lenovo, you must match that hostname.Update the endpoint URL to use the correct hostname, such as
opc.tcp://lenovo:53530/OPCUA/SimulationServer.
Certificate revocation list failures
If a server certificate points to a Certificate Revocation List (CRL), the client attempts to download this list to verify validity. In isolated networks without internet access, this lookup fails and blocks the connection.
To resolve this, download the CRL file manually and place it in the client's pki/issuers/crl or pki/trusted/crl folder. If you generated the server certificate with a custom CA, you can create an empty CRL file to satisfy this check.
Application and user authentication
These two certificate types serve distinct purposes:
Application certificate (
heisenware_opcua_client.pem): Identifies the application to establish the secure, encrypted channel between client and server. This is mandatory for secure connections.User certificate (
heisenware_opcua_user.pem): Identifies the user to handle authentication and permissions after the secure channel is established. This is optional.
User certificate authentication requires server-side configuration. The server administrator must create the user account and map it explicitly to the user's public certificate. For Prosys Simulation Server, this feature is only available in the Professional Edition.
Server and client clocks out of sync
OPC UA blocks secure connections if the clocks of the client and server differ substantially (for example, by an hour). When this occurs, the client logs a warning.
Video demo
Watch the video to learn how to connect to an OPC UA server, read, record, and visualize data.
Last updated
Was this helpful?