# OPC UA The `instro-opcua` package exposes the synchronous client in `instro.opcua` and protocol primitives in `instro.opcua.types`. See the [client guide](/library/protocols/opcua.md) for installation options and examples of browsing, reading, writing, and monitoring nodes. ## Client and subscriptions ```{eval-rst} .. autosummary:: :toctree: . :nosignatures: ~instro.opcua.OpcUaClient ~instro.opcua.Node ~instro.opcua.Subscription ~instro.opcua.IdentityToken .. autofunction:: instro.opcua.get_endpoints .. autoexception:: instro.opcua.OpcUaError ``` ### 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](/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. ```{eval-rst} .. autosummary:: :toctree: . :nosignatures: ~instro.opcua.types.AttributeValue ~instro.opcua.types.DateTime ~instro.opcua.types.Duration ~instro.opcua.types.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`. ```{eval-rst} .. autosummary:: :toctree: . :nosignatures: ~instro.opcua.types.NodeId ~instro.opcua.types.ExpandedNodeId ~instro.opcua.types.QualifiedName ~instro.opcua.types.LocalizedText ~instro.opcua.types.RelativePath ~instro.opcua.types.RelativePathElement ~instro.opcua.types.BrowsePath ``` ## 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__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. ```{eval-rst} .. autosummary:: :toctree: . :nosignatures: ~instro.opcua.types.AttributeId ~instro.opcua.types.NodeClass ~instro.opcua.types.AttributeWriteMask ~instro.opcua.types.AccessLevelType ~instro.opcua.types.AccessLevelExType ~instro.opcua.types.AccessRestrictionType ~instro.opcua.types.EventNotifierType ~instro.opcua.types.PermissionType ~instro.opcua.types.StatusCode ~instro.opcua.types.StructureType ~instro.opcua.types.RolePermissionType ~instro.opcua.types.StructureField ~instro.opcua.types.StructureDefinition ~instro.opcua.types.EnumField ~instro.opcua.types.EnumDefinition ~instro.opcua.types.MessageSecurityMode ~instro.opcua.types.SecurityPolicy ~instro.opcua.types.ApplicationType ~instro.opcua.types.UserTokenType ~instro.opcua.types.ApplicationDescription ~instro.opcua.types.UserTokenPolicy ~instro.opcua.types.EndpointDescription ```