OPC UA#
The instro-opcua package exposes the synchronous client in
instro.opcua and protocol primitives in instro.opcua.types.
See the client guide for installation options and
examples of browsing, reading, writing, and monitoring nodes.
Client and subscriptions#
A shared synchronous OPC UA session, created with |
|
A server Node with retained client ownership and a path from RootFolder. |
|
Iterate over |
|
Credentials used to authenticate one OPC UA session. |
- get_endpoints(endpoint_url, *, pki_dir=None)#
Discover endpoint security, identity, and application metadata.
The discovery wait releases the GIL and can be interrupted by Python signals.
- Parameters:
- Returns:
list[EndpointDescription] – Endpoints reported by the server, in response order.
- Raises:
OpcUaError – Native endpoint discovery fails.
KeyboardInterrupt – Python interrupts the discovery wait.
Batch reads#
OpcUaClient.read_nodes(nodes, attribute=None) resolves path inputs together from
RootFolder, then reads one attribute for all inputs and returns the results in
input order. It defaults to the Value attribute and returns an empty list
for empty input. The client splits requests by its decoded array limit. A server
can impose a lower per-request operation limit.
Attribute writes#
Assign to node.value or call node.set_attribute("Value", value) to write
Value. The client selects the wire type locally and sends one Write request.
The server determines which writes it accepts.
Python value |
Default OPC UA wire type |
|---|---|
|
Boolean |
|
Int64 |
|
Int32 |
|
Double |
|
String, ByteString, Guid, respectively |
|
Corresponding OPC UA type |
|
ExtensionObject containing an EnumField |
A list or tuple uses the wire type of its first element. Every element must be
encodable as that type. To specify the type, including for an empty list or tuple, pass dtype
from instro.opcua.types.DataType. For example,
node.set_attribute("Value", 42, dtype=DataType.INT16) sends an Int16.
For DateTime, pass dtype=DataType.DATE_TIME and integer Unix nanoseconds in
multiples of 100.
To write DisplayName, assign a LocalizedText to node.display_name. With
set_attribute("DisplayName", ...), omit dtype or use DataType.LOCALIZED_TEXT.
Connection settings#
Connection durations take finite nonnegative numbers. Use seconds for
session_retry_initial_s, session_retry_max_s, keep_alive_interval_s,
request_timeout_s, and publish_timeout_s. These settings accept up to 365
days, and keep_alive_interval_s must be positive. Use milliseconds for
min_publish_interval_ms, which must fit the native clock range.
channel_lifetime and session_timeout take integer milliseconds. The generated
client page lists all options and identifies those that use the native defaults.
session_retry_limit=-1 permits unlimited retries. Set it to 0 to disable retries.
max_failed_keep_alive_count=0 disables termination due to that failure count.
max_chunk_count=0 permits unlimited chunks per message. max_message_size=0
means no outgoing message-size limit. Zero string, byte-string, and array lengths
permit no elements. If the client recreates a subscription during recovery, see
the known cleanup defect.
Security mode strings are case-insensitive None, Sign, and SignAndEncrypt.
Policy strings are case-insensitive None, Basic128Rsa15, Basic256,
Basic256Sha256, Aes128-Sha256-RsaOaep, and Aes256-Sha256-RsaPss, or their
full OPC Foundation URIs. The AES aliases Aes128Sha256RsaOaep and
Aes256Sha256RsaPss are also accepted. Typed MessageSecurityMode and
SecurityPolicy values avoid string parsing.
Wrong types and unknown keywords raise TypeError. Invalid values raise
ValueError. Protocol failures raise OpcUaError, whose status_code is a
StatusCode. Item-level subscription setup failures are grouped in an
ExceptionGroup, with each exception retaining node and status_code.
Subscription iteration#
client.subscribe(nodes, publishing_interval_ms) returns an iterator of (Node, AttributeValue) pairs.
It monitors the same attribute on every node, defaulting to Value.
The publishing, sampling, and poll intervals are in milliseconds. The publishing
interval is required, and the server request uses whole milliseconds. Zero or
negative values request the fastest supported publishing interval.
sampling_interval_ms defaults to -1 and inherits the negotiated publishing
interval. Zero requests the fastest practical sampling rate.
poll_interval_ms defaults to 2000. Pass None to disable fallback reads.
A slow consumer can accumulate samples without a client-side buffer limit.
Samples already queued when you call close() remain available for iteration.
Attribute selection and named getters#
Node.get_attribute() and subscribe(attribute=...) accept AttributeId, an
integer attribute ID, or a case-insensitive canonical or snake-case name, such as
"DisplayName" or "display_name". Omitting the subscription attribute selects
Value.
Named getters return AttributeValue[T] with the following payload types.
All payloads can also be None when absent.
Getter |
Payload type |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
Supported scalar or |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The generic NodeId attribute query also returns AttributeValue[NodeId].
node.node_id is local identity and returns NodeId directly. Dynamic
get_attribute() uses the same semantic conversion as the named getters.
Supported values#
Reading the Value attribute returns the Python types below. One-dimensional
arrays return a list of the corresponding type.
OPC UA payload |
Python representation |
|---|---|
Boolean |
|
SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64 |
|
Float, Double |
|
String |
|
XmlElement |
|
ByteString |
|
DateTime |
|
Guid |
|
NodeId, ExpandedNodeId, StatusCode, QualifiedName, LocalizedText |
Corresponding wrapper |
Decoded RolePermissionType, StructureDefinition, StructureField, EnumDefinition, EnumField |
Corresponding wrapper |
Use str(element) to retrieve the text of an XmlElement.
A missing value or Null Variant yields None. Accessing .value on a sample
with an unsupported payload, including a multidimensional array, raises
OpcUaError with BadNotSupported. An incompatible type for a fixed attribute
raises BadTypeMismatch. You can still inspect the status and timestamps.
AttributeValue[T] associates one attribute with payload and quality metadata.
source_timestamp and server_timestamp are optional DateTime wrappers.
source_picoseconds and server_picoseconds are optional native integer fields
in units of 10 picoseconds. The corresponding *_unix_timestamp properties return
integer Unix nanoseconds with subnanosecond precision truncated. An absent
source timestamp is not replaced with the server timestamp or vice versa.
An attribute sample with its value, status, and timestamps. |
|
A native OPC UA timestamp used by attribute metadata. |
|
A nonnegative duration with nanosecond precision. |
|
XML text carried as an OPC UA XmlElement. |
Identifiers and paths#
NodeId accepts native textual identifiers, including numeric, string, Guid,
and byte-string forms. Its identifier property returns int, str,
uuid.UUID, or bytes, respectively. It is an identity value, not a direct
Node lookup input.
RelativePath.parse() uses the native path parser, including its known
multi-digit namespace string limitation. RelativePath.from_qualified_names()
provides structured hierarchical paths. A Node’s BrowsePath always starts at
RootFolder and retains the accumulated relative_path.
A namespace index and numeric, string, UUID, or byte-string identifier. |
|
A NodeId with optional namespace URI and server index. |
|
A browse name qualified by its namespace index. |
|
Text with an optional locale identifier. |
|
An ordered native browse route, parsed or constructed from qualified names. |
|
One directed reference step and target qualified name. |
|
A starting NodeId and relative route; Node paths start at RootFolder. |
Semantic and discovery types#
Enum and flag wrappers have integer .value and int() conversion. Constants
use uppercase snake case. String conversion uses the lowercase native variant
name without separators, or its numeric value when no named variant matches.
Flag types expose NONE, &, |, and Boolean
is_<flag>_set properties. StatusCode.code retains all status bits;
StatusCode.name() returns the native subcode name, and is_good, is_uncertain,
and is_bad are properties.
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
An OPC UA status retaining quality and all original status bits. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A role identifier and its PermissionType flags. |
|
One field in a StructureDefinition, including type and array metadata. |
|
A decoded structure schema, not a decoder for arbitrary instances. |
|
One named integer field in an EnumDefinition. |
|
A decoded enumeration schema with its field metadata. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A supported OPC UA security policy, with case-insensitive name matching. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
A semantic OPC UA integer value with typed constants and equality. |
|
Server application identity and discovery metadata. |
|
A user-token policy advertised by an endpoint. |
|
Endpoint security, user-token policies, and flattened application metadata. |