# OPC UA

The `instro-opcua` package exposes the synchronous client in
`instro.opcua` and protocol primitives in `instro.opcua.types`.
See the [client guide](https://dev.nominal.io/instro/library/protocols/opcua.md) for installation options and
examples of browsing, reading, writing, and monitoring nodes.

## Client and subscriptions

| [`OpcUaClient`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.OpcUaClient.md#instro.opcua.OpcUaClient "instro.opcua.OpcUaClient") | A shared synchronous OPC UA session, created with `connect()`. |
| --- | --- |
| [`Node`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.Node.md#instro.opcua.Node "instro.opcua.Node") | A server Node with retained client ownership and a path from RootFolder. |
| [`Subscription`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.Subscription.md#instro.opcua.Subscription "instro.opcua.Subscription") | Iterate over `(Node, AttributeValue)` pairs from a subscription. |
| [`IdentityToken`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.IdentityToken.md#instro.opcua.IdentityToken "instro.opcua.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*](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"))

      OPC UA discovery endpoint URL.
    - **pki_dir** ([*str*](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)") *|* [*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.15)")*[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")*]* *|* *None*)

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

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

Raises:
:   - [**OpcUaError**](https://dev.nominal.io/instro/ref/protocols/opcua.md#instro.opcua.OpcUaError "instro.opcua.OpcUaError") – Native endpoint discovery fails.
    - [**KeyboardInterrupt**](https://docs.python.org/3/builtins/exceptions.html#KeyboardInterrupt "(in Python v3.15)") – Python interrupts the discovery wait.

### exception OpcUaError

Bases: [`Exception`](https://docs.python.org/3/builtins/exceptions.html#Exception "(in Python v3.15)")

### 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](https://dev.nominal.io/instro/library/protocols/opcua.md#recovery-and-shutdown).

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`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.AttributeValue.md#instro.opcua.types.AttributeValue "instro.opcua.types.AttributeValue") | An attribute sample with its value, status, and timestamps. |
| --- | --- |
| [`DateTime`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.DateTime.md#instro.opcua.types.DateTime "instro.opcua.types.DateTime") | A native OPC UA timestamp used by attribute metadata. |
| [`Duration`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.Duration.md#instro.opcua.types.Duration "instro.opcua.types.Duration") | A nonnegative duration with nanosecond precision. |
| [`XmlElement`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.XmlElement.md#instro.opcua.types.XmlElement "instro.opcua.types.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`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.NodeId.md#instro.opcua.types.NodeId "instro.opcua.types.NodeId") | A namespace index and numeric, string, UUID, or byte-string identifier. |
| --- | --- |
| [`ExpandedNodeId`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.ExpandedNodeId.md#instro.opcua.types.ExpandedNodeId "instro.opcua.types.ExpandedNodeId") | A NodeId with optional namespace URI and server index. |
| [`QualifiedName`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.QualifiedName.md#instro.opcua.types.QualifiedName "instro.opcua.types.QualifiedName") | A browse name qualified by its namespace index. |
| [`LocalizedText`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.LocalizedText.md#instro.opcua.types.LocalizedText "instro.opcua.types.LocalizedText") | Text with an optional locale identifier. |
| [`RelativePath`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.RelativePath.md#instro.opcua.types.RelativePath "instro.opcua.types.RelativePath") | An ordered native browse route, parsed or constructed from qualified names. |
| [`RelativePathElement`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.RelativePathElement.md#instro.opcua.types.RelativePathElement "instro.opcua.types.RelativePathElement") | One directed reference step and target qualified name. |
| [`BrowsePath`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.BrowsePath.md#instro.opcua.types.BrowsePath "instro.opcua.types.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`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.AttributeId.md#instro.opcua.types.AttributeId "instro.opcua.types.AttributeId") | A semantic OPC UA integer value with typed constants and equality. |
| --- | --- |
| [`NodeClass`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.NodeClass.md#instro.opcua.types.NodeClass "instro.opcua.types.NodeClass") | A semantic OPC UA integer value with typed constants and equality. |
| [`AttributeWriteMask`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.AttributeWriteMask.md#instro.opcua.types.AttributeWriteMask "instro.opcua.types.AttributeWriteMask") | A semantic OPC UA integer value with typed constants and equality. |
| [`AccessLevelType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.AccessLevelType.md#instro.opcua.types.AccessLevelType "instro.opcua.types.AccessLevelType") | A semantic OPC UA integer value with typed constants and equality. |
| [`AccessLevelExType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.AccessLevelExType.md#instro.opcua.types.AccessLevelExType "instro.opcua.types.AccessLevelExType") | A semantic OPC UA integer value with typed constants and equality. |
| [`AccessRestrictionType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.AccessRestrictionType.md#instro.opcua.types.AccessRestrictionType "instro.opcua.types.AccessRestrictionType") | A semantic OPC UA integer value with typed constants and equality. |
| [`EventNotifierType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.EventNotifierType.md#instro.opcua.types.EventNotifierType "instro.opcua.types.EventNotifierType") | A semantic OPC UA integer value with typed constants and equality. |
| [`PermissionType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.PermissionType.md#instro.opcua.types.PermissionType "instro.opcua.types.PermissionType") | A semantic OPC UA integer value with typed constants and equality. |
| [`StatusCode`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.StatusCode.md#instro.opcua.types.StatusCode "instro.opcua.types.StatusCode") | An OPC UA status retaining quality and all original status bits. |
| [`StructureType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.StructureType.md#instro.opcua.types.StructureType "instro.opcua.types.StructureType") | A semantic OPC UA integer value with typed constants and equality. |
| [`RolePermissionType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.RolePermissionType.md#instro.opcua.types.RolePermissionType "instro.opcua.types.RolePermissionType") | A role identifier and its PermissionType flags. |
| [`StructureField`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.StructureField.md#instro.opcua.types.StructureField "instro.opcua.types.StructureField") | One field in a StructureDefinition, including type and array metadata. |
| [`StructureDefinition`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.StructureDefinition.md#instro.opcua.types.StructureDefinition "instro.opcua.types.StructureDefinition") | A decoded structure schema, not a decoder for arbitrary instances. |
| [`EnumField`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.EnumField.md#instro.opcua.types.EnumField "instro.opcua.types.EnumField") | One named integer field in an EnumDefinition. |
| [`EnumDefinition`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.EnumDefinition.md#instro.opcua.types.EnumDefinition "instro.opcua.types.EnumDefinition") | A decoded enumeration schema with its field metadata. |
| [`MessageSecurityMode`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.MessageSecurityMode.md#instro.opcua.types.MessageSecurityMode "instro.opcua.types.MessageSecurityMode") | A semantic OPC UA integer value with typed constants and equality. |
| [`SecurityPolicy`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.SecurityPolicy.md#instro.opcua.types.SecurityPolicy "instro.opcua.types.SecurityPolicy") | A supported OPC UA security policy, with case-insensitive name matching. |
| [`ApplicationType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.ApplicationType.md#instro.opcua.types.ApplicationType "instro.opcua.types.ApplicationType") | A semantic OPC UA integer value with typed constants and equality. |
| [`UserTokenType`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.UserTokenType.md#instro.opcua.types.UserTokenType "instro.opcua.types.UserTokenType") | A semantic OPC UA integer value with typed constants and equality. |
| [`ApplicationDescription`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.ApplicationDescription.md#instro.opcua.types.ApplicationDescription "instro.opcua.types.ApplicationDescription") | Server application identity and discovery metadata. |
| [`UserTokenPolicy`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.UserTokenPolicy.md#instro.opcua.types.UserTokenPolicy "instro.opcua.types.UserTokenPolicy") | A user-token policy advertised by an endpoint. |
| [`EndpointDescription`](https://dev.nominal.io/instro/ref/protocols/instro.opcua.types.EndpointDescription.md#instro.opcua.types.EndpointDescription "instro.opcua.types.EndpointDescription") | Endpoint security, user-token policies, and flattened application metadata. |
