OPC UA#
Use the synchronous OPC UA client to browse nodes, read and write attributes, and subscribe to changes.
Install#
Install the OPC UA extra with uv or pip. The extra is also included in instro[all].
uv add "instro[opcua]"
pip install "instro[opcua]"
To install the standalone package, run uv add instro-opcua or pip install instro-opcua.
If you used a prerelease checkout, update your imports from instro.unstable.opcua to instro.opcua.
Connect and read#
Read the server clock and check the status returned with the sample.
from instro.opcua import OpcUaClient
with OpcUaClient.connect("opc.tcp://localhost:4840") as client:
clock = client.get_node("/Objects/Server/ServerStatus/CurrentTime")
sample = clock.value
if sample.status.is_good:
print(clock.node_id, sample.value)
else:
print(sample.status.name())
Connections default to anonymous identity with security policy and mode None.
Use get_endpoints(endpoint_url) to discover available endpoints before choosing
an identity and security settings. Endpoint descriptions include policy, mode,
server certificate, supported user tokens, and application metadata.
For this username example, set OPCUA_PASSWORD and put your application’s
certificate and private key in the pki directory. Configure the server to trust
the application certificate and trust the server certificate
in the client PKI. Set application_uri to the URI in the application certificate.
import os
from instro.opcua import IdentityToken, OpcUaClient, get_endpoints
from instro.opcua.types import MessageSecurityMode, SecurityPolicy
endpoint = "opc.tcp://localhost:4840"
pki_dir = "pki"
for description in get_endpoints(endpoint, pki_dir=pki_dir):
print(description.endpoint_url, description.security_policy, description.security_mode)
with OpcUaClient.connect(
endpoint,
identity=IdentityToken.user_name("operator", os.environ["OPCUA_PASSWORD"]),
security_policy=SecurityPolicy.BASIC256_SHA256,
security_mode=MessageSecurityMode.SIGN_AND_ENCRYPT,
application_uri="urn:line-1:opcua-client",
pki_dir=pki_dir,
certificate_path="client.der",
private_key_path="client.pem",
) as client:
print(client.objects.children)
IdentityToken.x509() supplies a user certificate and key. The connection’s
certificate_path and private_key_path supply the application certificate
and key. Provide both together. Relative certificate and key paths resolve under
pki_dir. Use trust_server_certs to trust new server certificates automatically.
verify_server_certs controls hostname, application URI, and validity-date checks.
The API reference lists the connection settings.
The client disconnects when you leave the with block. If you open it without a
context manager, call client.disconnect() when you finish.
Trust the server certificate#
When the client rejects an untrusted server certificate, it saves the certificate
under <pki_dir>/rejected/. Verify its fingerprint with the server administrator.
Move the verified file to <pki_dir>/trusted/ using its original filename, then
connect again.
Read several Nodes at once#
client.read_nodes(nodes) accepts a mix of Nodes, strings, and RelativePath
objects. It resolves paths from RootFolder, then reads the selected attribute
for every Node. The client splits translation and read requests to fit its
decoded array limit. If the server returns BadTooManyOperations, submit fewer
inputs per call. Existing Nodes must belong to the client. Results
follow input order. An empty input returns [] without contacting the server.
from instro.opcua import OpcUaClient
with OpcUaClient.connect("opc.tcp://localhost:4840") as client:
clock_sample, state_sample = client.read_nodes([
"/Objects/Server/ServerStatus/CurrentTime",
"/Objects/Server/ServerStatus/State",
])
Construct paths with multi-digit namespace indexes#
For namespace indexes of 10 or higher, construct the path from qualified names.
The string parser can interpret 12:Machine as the literal name 12:Machine
in namespace 0.
from instro.opcua.types import QualifiedName, RelativePath
path = RelativePath.from_qualified_names([
QualifiedName(0, "Objects"),
QualifiedName(12, "Machine"),
QualifiedName(12, "Temperature"),
])
Pass this path to client.get_node() or include it in client.read_nodes().
Inspect payloads and quality#
Attribute reads return AttributeValue[T]. Named getters select semantic types:
node.node_class.value is a NodeClass, node.display_name.value is a
LocalizedText, and node.array_dimensions.value is a list[int], when present.
node.get_attribute(AttributeId.NODE_ID) queries the server’s NodeId attribute.
node.node_id reads the retained identifier.
A sample carries its status and timestamps even if the value is missing or its
type is unsupported. A Bad or Uncertain status can accompany a readable value.
A missing or Null payload yields None. Empty strings, byte strings, and arrays
yield "", b"", and [].
DateTime payloads are integer Unix nanoseconds. To timestamp a measurement,
use sample.source_unix_timestamp when the server supplies a source timestamp.
See the attribute reference for the
supported Python types and timestamp fields.
Write an attribute#
Assigning node.value = 42 writes an OPC UA Int64. If your server expects
an Int16 setpoint, pass dtype=DataType.INT16 to select that wire type.
Use the path to a writable variable on your server.
from instro.opcua import OpcUaClient
from instro.opcua.types import DataType
with OpcUaClient.connect("opc.tcp://localhost:4840") as client:
setpoint = client.get_node("/Objects/2:Setpoint")
# setpoint.value = 42 would send an Int64.
setpoint.set_attribute("Value", 42, dtype=DataType.INT16)
For a list or tuple, the first element selects the wire type. Supply dtype to write
an empty list or tuple. See the write type defaults.
To write an EnumField returned by a read, pass the field to the destination
node. Use the source and destination paths from your server.
from instro.opcua import OpcUaClient
from instro.opcua.types import DataType, EnumField
with OpcUaClient.connect("opc.tcp://localhost:4840") as client:
field = client.get_node("/Objects/2:EnumSource").value.value
assert isinstance(field, EnumField)
target = client.get_node("/Objects/2:EnumTarget")
target.set_attribute("Value", field, dtype=DataType.ENUM_FIELD)
Iterate subscription samples#
Subscribe to the nodes you want to monitor. Each sample pairs its node with the value and status of the selected attribute.
from instro.opcua import OpcUaClient
with OpcUaClient.connect("opc.tcp://localhost:4840") as client:
paths = ["/Objects/Server/ServerStatus/CurrentTime"]
with client.subscribe(paths, publishing_interval_ms=500, poll_interval_ms=2000) as samples:
node, sample = next(samples)
print(node.node_id, sample.status.name())
Use poll_interval_ms to set the fallback read period for nodes with no recent
notification. Pass poll_interval_ms=None to rely on notifications alone. Samples accumulate
if your application consumes them more slowly than they arrive.
All numeric subscription intervals are in milliseconds. Leaving the
subscription context closes it. You can also call samples.close() explicitly.
See the subscription reference
for the interval settings.
Recovery and shutdown#
The client can reconnect after a temporary connection loss. Use
session_retry_limit, session_retry_initial_s, and session_retry_max_s
to configure reconnection.
Operations during an outage can still fail.
Known defect in subscription cleanup. If recovery recreates a subscription
with a new server ID, close() can raise and leave the replacement active on
the server. If close() races with recovery and the server has reassigned the
old ID to another subscription, close() can delete that other subscription.