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#

OpcUaClient

A shared synchronous OPC UA session, created with connect().

Node

A server Node with retained client ownership and a path from RootFolder.

Subscription

Iterate over (Node, AttributeValue) pairs from a subscription.

IdentityToken

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:
  • endpoint_url (str)

    OPC UA discovery endpoint URL.

  • pki_dir (str | PathLike[str] | None)

    Certificate store directory. Defaults to the same location as OpcUaClient.connect().

Returns:

list[EndpointDescription] – Endpoints reported by the server, in response order.

Raises:
exception OpcUaError#

Bases: Exception

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

bool

Boolean

int

Int64

enum.IntEnum

Int32

float

Double

str, bytes, uuid.UUID

String, ByteString, Guid, respectively

NodeId, ExpandedNodeId, StatusCode, QualifiedName, LocalizedText, XmlElement

Corresponding OPC UA type

EnumField

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

node_class

NodeClass

browse_name

QualifiedName

display_name, description, inverse_name

LocalizedText

write_mask, user_write_mask

AttributeWriteMask

is_abstract, symmetric, contains_no_loops, historizing, executable, user_executable

bool

event_notifier

EventNotifierType

value

Supported scalar or list[T] below

data_type

NodeId

value_rank

int

array_dimensions

list[int]

access_level, user_access_level

AccessLevelType

minimum_sampling_interval

datetime.timedelta

data_type_definition

StructureDefinition or EnumDefinition

role_permissions, user_role_permissions

list[RolePermissionType]

access_restrictions

AccessRestrictionType

access_level_ex

AccessLevelExType

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

bool

SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64

int

Float, Double

float

String

str

XmlElement

XmlElement

ByteString

bytes

DateTime

int Unix nanoseconds

Guid

uuid.UUID

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.

AttributeValue

An attribute sample with its value, status, and timestamps.

DateTime

A native OPC UA timestamp used by attribute metadata.

Duration

A nonnegative duration with nanosecond precision.

XmlElement

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.

NodeId

A namespace index and numeric, string, UUID, or byte-string identifier.

ExpandedNodeId

A NodeId with optional namespace URI and server index.

QualifiedName

A browse name qualified by its namespace index.

LocalizedText

Text with an optional locale identifier.

RelativePath

An ordered native browse route, parsed or constructed from qualified names.

RelativePathElement

One directed reference step and target qualified name.

BrowsePath

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.

AttributeId

A semantic OPC UA integer value with typed constants and equality.

NodeClass

A semantic OPC UA integer value with typed constants and equality.

AttributeWriteMask

A semantic OPC UA integer value with typed constants and equality.

AccessLevelType

A semantic OPC UA integer value with typed constants and equality.

AccessLevelExType

A semantic OPC UA integer value with typed constants and equality.

AccessRestrictionType

A semantic OPC UA integer value with typed constants and equality.

EventNotifierType

A semantic OPC UA integer value with typed constants and equality.

PermissionType

A semantic OPC UA integer value with typed constants and equality.

StatusCode

An OPC UA status retaining quality and all original status bits.

StructureType

A semantic OPC UA integer value with typed constants and equality.

RolePermissionType

A role identifier and its PermissionType flags.

StructureField

One field in a StructureDefinition, including type and array metadata.

StructureDefinition

A decoded structure schema, not a decoder for arbitrary instances.

EnumField

One named integer field in an EnumDefinition.

EnumDefinition

A decoded enumeration schema with its field metadata.

MessageSecurityMode

A semantic OPC UA integer value with typed constants and equality.

SecurityPolicy

A supported OPC UA security policy, with case-insensitive name matching.

ApplicationType

A semantic OPC UA integer value with typed constants and equality.

UserTokenType

A semantic OPC UA integer value with typed constants and equality.

ApplicationDescription

Server application identity and discovery metadata.

UserTokenPolicy

A user-token policy advertised by an endpoint.

EndpointDescription

Endpoint security, user-token policies, and flattened application metadata.