Skip to content

o6

o6

O6 - High-Level OPC UA Python Library

This package provides a high-level, pythonic interface to OPC UA functionality, built on top of the low-level _o6 C extension module.

Basic usage

from o6 import Client

client = Client("opc.tcp://localhost:4840") with client: value = client.read("ns=1;s=Temperature") client.write("ns=1;s=SetPoint", 25.0)

Classes

Client

Bases: Client

High-level OPC UA client. See the client guide for more details.

Attributes
ns instance-attribute
ns = Namespaces(self)

Namespace manager for the client. See the Namespaces API for details.

Example:

client = Client("opc.tcp://localhost:4840")
client.ns.append(o6.ns.di)
client.ns.load("nodesets/MyCustomTypes.xml", short_name="MyTypes")
client.connect()

After connecting, server-side namespaces that were not already loaded can be discovered through client.ns.remote.discover().

Important

All namespace registration or loading must happen before connect(). client.ns.append() and client.ns.load() are required pre-connection so that namespace index translation can be set up correctly. Attempting to add namespaces after the session is established raises RuntimeError.

root instance-attribute
root = ObjectNode(
    ClientBackend(self), "i=84", QualifiedName(0, "Root")
)

The OPC UA Root folder node (i=84) and primary entry point for the node-style API.

objects instance-attribute
objects = ObjectNode(
    ClientBackend(self), "i=85", QualifiedName(0, "Objects")
)

The Objects folder node (i=85); shortcut into the application-level address space.

types instance-attribute
types = ObjectNode(
    ClientBackend(self), "i=86", QualifiedName(0, "Types")
)

The Types folder node (i=86); entry point for browsing the server's type hierarchies.

views instance-attribute
views = ObjectNode(
    ClientBackend(self), "i=87", QualifiedName(0, "Views")
)

The Views folder node (i=87); entry point for server-defined address-space views.

loop property
loop

The asyncio event loop used by this client. Set at construction time, not modifiable afterwards.

state property
state

Return (channel_state, session_state, connect_status).

connected property
connected

Test if a client has both SecureChannel and Session connected.

Functions
__init__
__init__(
    endpoint_url=None,
    loop=None,
    *,
    logger=None,
    certificate=None,
    private_key=None,
    trust_list=None,
    revocation_list=None,
    security_mode=None,
    security_policy=None,
    application_uri=None,
    username=None,
    password=None
)

Create a new OPC UA client.

The constructor accepts the most commonly needed settings as keyword arguments. All remaining configuration — such as session_name, requested_session_timeout, session_locale_ids, endpoint, and any other ClientConfig property — can be set lazily on client.config before calling connect():

.. code-block:: python

client = Client("opc.tcp://localhost:4840")
client.config.session_name = "my-session"
client.config.requested_session_timeout = 60_000
client.config.session_locale_ids = ["en-US"]
client.config.endpoint = my_endpoint_description
client.config.set_username_password("user", "secret")
client.connect()

Parameters:

Name Type Description Default
endpoint_url str | None

OPC UA endpoint to connect to, e.g. "opc.tcp://localhost:4840". Can also be passed to connect().

None
loop AbstractEventLoop | None

Asyncio event loop to use. Defaults to the running loop, or a newly created one if none is running.

None
logger Logger | None

Python logger used for all client-level log output. Equivalent to client.config.logger.

None
certificate str | Path | bytes | None

Client certificate as a file path (str / Path) or raw bytes (DER/PEM). Equivalent to client.config.certificate.

None
private_key str | Path | bytes | None

Private key matching certificate, as a file path or raw bytes. Equivalent to client.config.private_key.

None
trust_list list[str | Path | bytes] | None

Trusted server certificates, each as a file path or raw bytes. Equivalent to client.config.trust_list.

None
revocation_list list[str | Path | bytes] | None

Certificate revocation lists (CRL), each as a file path or raw bytes. Equivalent to client.config.revocation_list.

None
security_mode int | None

OPC UA message security mode (UA_MessageSecurityMode integer or o6.MessageSecurityMode enum). Equivalent to client.config.security_mode.

None
security_policy str | None

URI or short name of the security policy, e.g. "Basic256Sha256". Equivalent to client.config.security_policy.

None
application_uri str | None

Application URI sent in the ApplicationDescription. Equivalent to client.config.application_uri.

None
username str | None

Username for UserNameIdentityToken authentication. Equivalent to calling client.config.set_username_password(username, password).

None
password str | None

Password for UserNameIdentityToken authentication. Used together with username.

None
connect
connect(no_session=False)

Connect to the server.

Establishes a SecureChannel and, by default, a Session. Finalizes encryption settings (certificate / key) before connecting.

If no_session is True, only the SecureChannel is opened (useful for discovery or when a session will be activated manually later).

Creates the default subscription.

Starts the background worker thread.

.. code-block:: python

# sync
client.connect()

# async
await client.connect()

Parameters:

Name Type Description Default
no_session bool

Open only the SecureChannel, skip Session creation.

False
disconnect
disconnect(close_session=True, delete_subscriptions=True)

Disconnect from the server.

By default closes all subscriptions, ends the Session, and closes the SecureChannel, then stops the background worker thread.

Pass close_session=False to close only the SecureChannel while keeping the Session alive (e.g. for session transfer). In that case delete_subscriptions is ignored.

Safe to call when already disconnected or when the event loop is closed — returns None without raising.

.. code-block:: python

# sync
client.disconnect()

# async
await client.disconnect()

Parameters:

Name Type Description Default
close_session bool

Close the Session (and SecureChannel). When False, only the SecureChannel is closed.

True
delete_subscriptions bool

Delete all active subscriptions before disconnecting. Ignored when close_session is False.

True
start_reverse_connect
start_reverse_connect(port, hostnames=None)

Listen for an incoming OPC UA reverse connection from the server.

In the reverse-connect scenario the server initiates the TCP connection to the client. The client opens a listen socket on port and waits for the server to connect.

Close the connection with the standard disconnect.

.. code-block:: python

client.start_reverse_connect(port=4840, hostnames=["0.0.0.0"])
# ... use client ...
client.disconnect()

Parameters:

Name Type Description Default
port int

TCP port to listen on.

required
hostnames list[str] | None

Network interfaces to advertise. None or an empty list lets the stack decide (typically all interfaces).

None
activate_current_session
activate_current_session()

Re-activate the session that is already associated with this client.

Sends an ActivateSession request using the client's stored identity token and credentials. Also creates the default subscription.

Typical use — session transfer, step 2 on the receiving client when the session was originally opened by this client and the SecureChannel has been renewed or re-established:

.. code-block:: python

client.connect()                  # establishes session
# ... channel re-established ...
client.activate_current_session() # re-bind session to new channel
activate_session
activate_session(auth_token, server_nonce)

Activate a session that was created by another client.

Used for session transfer: client A's session is handed off to client B. Client B must first open a SecureChannel without a session (connect(no_session=True)), then call this method with the token and nonce retrieved from client A via get_session_authentication_token().

.. code-block:: python

# Client A — get transfer credentials
token, nonce = client_a.get_session_authentication_token()

# Client B — take over the session
client_b.connect(no_session=True)
client_b.activate_session(token, nonce)

Parameters:

Name Type Description Default
auth_token NodeId

Authentication token (NodeId) from the originating client's get_session_authentication_token().

required
server_nonce bytes

Server nonce bytes from the same call.

required
__enter__
__enter__()

Enter the sync context manager; connect if not already connected.

Calls connect when the client is not yet connected, then returns self. __exit__ calls disconnect if the client is still connected when the block ends.

.. code-block:: python

with Client("opc.tcp://localhost:4840") as client:
    value = client.read("ns=1;s=Temperature")
__exit__
__exit__(exc_type, exc_value, traceback)

Exit the sync context manager; disconnect if still connected.

Calls disconnect when the client is still connected. Exceptions from the with block are not suppressed. See __enter__ for full usage.

__aenter__ async
__aenter__()

Async counterpart of __enter__.

Same semantics — connects if not already connected and returns self — but uses await internally. __aexit__ awaits disconnect.

.. code-block:: python

async with Client("opc.tcp://localhost:4840") as client:
    value = await client.read("ns=1;s=Temperature")
__aexit__ async
__aexit__(exc_type, exc_value, traceback)

Exit the async context manager; disconnect if still connected.

Awaits disconnect when the client is still connected. Exceptions from the async with block are not suppressed. See __aenter__ for full usage.

__getitem__
__getitem__(key)

Resolve a node ID to a typed Node object.

Reads NodeClass and BrowseName from the server and returns the matching Node subclass (e.g. VariableNode, ObjectNode, …).

key accepts anything that can be converted to a NodeId: a string ("ns=1;s=Temperature"), an integer (numeric node id in namespace 0), or a [NodeId][o6.NodeId] instance.

.. code-block:: python

node = client["ns=1;s=Temperature"]        # sync
node = await client["ns=1;s=Temperature"]  # async
service_find_servers
service_find_servers(request)

Raw FindServers service call — discover servers known to a discovery server.

OPC UA Part 4 §5.5.2

service_find_servers_on_network
service_find_servers_on_network(request)

Raw FindServersOnNetwork service call — enumerate servers registered via mDNS/LDS.

OPC UA Part 4 §5.5.3

service_get_endpoints
service_get_endpoints(request)

Raw GetEndpoints service call — retrieve the endpoint descriptions of a server.

OPC UA Part 4 §5.5.4

service_add_nodes
service_add_nodes(request)

Raw AddNodes service call — add one or more nodes to the address space.

OPC UA Part 4 §5.8.2

service_delete_nodes
service_delete_nodes(request)

Raw DeleteNodes service call — remove one or more nodes from the address space.

OPC UA Part 4 §5.8.4

service_add_references
service_add_references(request)

Raw AddReferences service call — add references between nodes.

OPC UA Part 4 §5.8.3

service_delete_references
service_delete_references(request)

Raw DeleteReferences service call — remove references between nodes.

OPC UA Part 4 §5.8.5

service_browse
service_browse(request)

Raw Browse service call — navigate the address space from one or more start nodes.

Returns references according to the BrowseDescription filter in the request. Use service_browse_next to continue if the response indicates more results are available.

OPC UA Part 4 §5.9.2

service_browse_next
service_browse_next(request)

Raw BrowseNext service call — continue a Browse that returned a continuation point.

OPC UA Part 4 §5.9.3

service_translate_browse_paths_to_nodeids
service_translate_browse_paths_to_nodeids(request)

Raw TranslateBrowsePathsToNodeIds service call — resolve browse paths to NodeIds.

OPC UA Part 4 §5.9.4

service_register_nodes
service_register_nodes(request)

Raw RegisterNodes service call — obtain optimised NodeIds for repeated access.

OPC UA Part 4 §5.9.5

service_unregister_nodes
service_unregister_nodes(request)

Raw UnregisterNodes service call — release NodeIds obtained via RegisterNodes.

OPC UA Part 4 §5.9.6

service_read
service_read(request)

Raw Read service call — read one or more node attributes.

OPC UA Part 4 §5.11.2

service_history_read
service_history_read(request)

Raw HistoryRead service call — read historical values or events from nodes.

OPC UA Part 4 §5.11.3

service_write
service_write(request)

Raw Write service call — write one or more node attribute values.

OPC UA Part 4 §5.11.4

service_history_update
service_history_update(request)

Raw HistoryUpdate service call — insert, replace, or delete historical data.

OPC UA Part 4 §5.11.5

service_call
service_call(request)

Raw Call service call — invoke one or more OPC UA methods.

OPC UA Part 4 §5.12.2

get_remote_data_types
get_remote_data_types(type_nodes=None)

Read custom StructureDefinition data types from the server.

Browses the server's DataType hierarchy (rooted at Structure, NodeId i=22) and reads the DataTypeDefinition and BrowseName attributes for every discovered node. Only nodes that carry a StructureDefinition (structs, structs-with-optional-fields, and unions) are included in the result.

Pass type_nodes to restrict the query to a specific set of DataType NodeIds instead of walking the full hierarchy. Passing an empty list returns [] immediately without contacting the server.

Each entry in the returned list is a dict with the following keys:

  • type_name (str) — BrowseName.name of the DataType node.
  • type_id (NodeId) — NodeId of the DataType node.
  • binary_encoding_id (NodeId) — default binary encoding NodeId (StructureDefinition.defaultEncodingId).
  • type_kind (DataTypeKind) — Structure, OptStruct (structure with optional fields), or Union.
  • members_size (int) — number of fields in the structure.

The result can be passed directly to [register_data_types][o6.register_data_types] to enable encoding/decoding of these types on the client.

Parameters:

Name Type Description Default
type_nodes list[NodeIdLike] | None

Explicit DataType NodeIds to query. None (default) walks the full Structure subtype hierarchy.

None
get_endpoints
get_endpoints(
    endpoint_url, *, locale_ids=None, profile_uris=None
)

Return the endpoints advertised by a server.

Sends a GetEndpoints request to endpoint_url. No active session is required — connect with connect(no_session=True) first if the client is not yet connected.

Each [EndpointDescription][o6.EndpointDescription] in the result describes one available endpoint and includes the endpoint URL, security mode, security policy URI, transport profile URI, server certificate, and the list of supported [UserTokenPolicy][o6.UserTokenPolicy] entries.

client.connect(no_session=True)
endpoints = client.get_endpoints("opc.tcp://localhost:4840")
for ep in endpoints:
    print(ep.endpoint_url, ep.security_mode, ep.security_policy_uri)

Parameters:

Name Type Description Default
endpoint_url str

URL of the server to query, e.g. "opc.tcp://localhost:4840".

required
locale_ids list[str] | None

Preferred locales for localised strings in the response (e.g. ["en-US", "de-DE"]). None returns the server's default locale.

None
profile_uris list[str] | None

Restrict the result to endpoints that match one of these transport profile URIs. None returns all endpoints.

None
find_servers
find_servers(
    endpoint_url, *, server_uris=None, locale_ids=None
)

Return servers registered at a discovery server or known to a server.

Sends a FindServers request to endpoint_url. Typically called against a Local Discovery Server (LDS) at "opc.tcp://localhost:4840" to enumerate all servers registered on the host, or against any server to retrieve its own [ApplicationDescription][o6.ApplicationDescription].

No active session is required — connect(no_session=True) is sufficient.

Each [ApplicationDescription][o6.ApplicationDescription] in the result contains the application name, application URI, application type, product URI, and a list of discovery URLs that can be passed to get_endpoints.

.. code-block:: python

client.connect(no_session=True)
servers = client.find_servers("opc.tcp://localhost:4840")
for srv in servers:
    print(srv.application_uri, srv.discovery_urls)

Parameters:

Name Type Description Default
endpoint_url str

URL of the discovery server or server to query.

required
locale_ids list[str] | None

Preferred locales for the ApplicationDescription.application_name field. None uses the server's default locale.

None
server_uris list[str] | None

Restrict the result to servers whose applicationUri matches one of these strings. None returns all known servers.

None
find_servers_on_network
find_servers_on_network(
    starting_record_id=0,
    max_records_to_return=0,
    server_capability_filter=None,
)

Return servers visible on the network via a Local Discovery Server (LDS).

Sends a FindServersOnNetwork request to the connected LDS. The LDS maintains a registry of servers that have announced themselves via mDNS or the RegisterServer2 service. This call is only meaningful when connected to an LDS; a regular OPC UA server will return an empty list or an error.

The result is paginated: use starting_record_id and max_records_to_return to page through large registries. The record_id field on each [ServerOnNetwork][o6.ServerOnNetwork] entry can be used as the starting_record_id for the next page.

Each [ServerOnNetwork][o6.ServerOnNetwork] entry contains the server name, discovery URL, and a list of capability strings (e.g. "DA" for Data Access, "HE" for Historical Events).

.. code-block:: python

# Fetch the first 100 servers that support Data Access
servers = client.find_servers_on_network(
    max_records_to_return=100,
    server_capability_filter=["DA"],
)

Parameters:

Name Type Description Default
starting_record_id int

Record ID to start from for pagination. 0 starts from the beginning of the registry.

0
max_records_to_return int

Maximum number of entries to return. 0 lets the server decide (typically returns all entries).

0
server_capability_filter list[str] | None

Restrict the result to servers that advertise all of the given capability strings. None returns servers regardless of capabilities.

None
call
call(object_id, method_id, input_args=[])

Invoke a method on a node.

Parameters:

Name Type Description Default
object_id

The object node id that owns the method.

required
method_id

The method node id to invoke.

required
input_args

Positional input arguments to pass to the method.

required

Returns:

Type Description
MaybeAwaitable[tuple[StatusCode, ...]]

A tuple of status codes for the method outputs.

browse
browse(
    target,
    *,
    direction=o6.BrowseDirection.FORWARD,
    reftype=o6.ns.ns0.reftypes.References.HierarchicalReferences,
    refsubtypes=True,
    nodeclass_mask=o6.NodeClass.UNSPECIFIED,
    result_mask=o6.BrowseResultMask(0)
)

Browse references from a node.

The method transparently follows server-issued continuation points by calling BrowseNext until all references have been collected, so the returned list is always complete even when the server splits the response into multiple batches.

Parameters:

Name Type Description Default
target NodeIdLike

The node id to browse from.

required
direction BrowseDirection

The browse direction (forward, inverse, or both).

...
reftype NodeIdLike

A reference type to filter by, or None for all types.

...
refsubtypes bool

If True, include subtypes of the reference type.

True
nodeclass_mask NodeClass

A node-class mask to filter the target nodes.

...
result_mask BrowseResultMask

A browse result mask to customize returned fields.

...

Returns:

Type Description
MaybeAwaitable[list[ReferenceDescription]]

A list of ReferenceDescription objects describing the found

MaybeAwaitable[list[ReferenceDescription]]

references.

history_read
history_read(
    target,
    start_time,
    end_time,
    num_values_per_node=0,
    return_bounds=False,
    timestamps_to_return=o6.TimestampsToReturn.BOTH,
)

Read raw historical values for one or more nodes.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike]

A node id or list of node ids to read history from.

required
start_time datetime

The start time for the history interval.

required
end_time datetime

The end time for the history interval.

required
num_values_per_node int

Maximum number of values to return per node.

0
return_bounds bool

If True, include boundary values at the interval edges.

False
timestamps_to_return TimestampsToReturn

Which timestamps to return with each value.

...

Returns:

Type Description
Any

Historical values or data values for the requested nodes.

history_update_insert
history_update_insert(target, values)

Insert new historical values into a node's history.

Insertion fails for any timestamp that already has a value stored. Use history_update_replace to overwrite existing entries.

Parameters:

Name Type Description Default
target NodeIdLike

The node id whose history is being updated.

required
values list[DataValue]

The historical values to insert.

required

Returns:

Type Description
Any

The raw result of the history update operation.

history_update_replace
history_update_replace(target, values)

Replace existing historical values for a node.

Replacement requires that a value already exists at each provided timestamp. Use history_update_insert to add new entries.

Parameters:

Name Type Description Default
target NodeIdLike

The node id whose history is being updated.

required
values list[DataValue]

The historical values to replace existing entries with.

required

Returns:

Type Description
Any

The raw result of the history update operation.

history_update_delete
history_update_delete(target, start_time, end_time)

Delete historical values from a node.

Parameters:

Name Type Description Default
target NodeIdLike

The node id whose history should be deleted.

required
start_time datetime

The start of the deletion interval.

required
end_time datetime

The end of the deletion interval.

required

Returns:

Type Description
Any

The raw result of the history delete operation.

add_variable_node
add_variable_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.Aggregates.HasComponent,
    browsename,
    requested_nodeid=None,
    attributes,
    type_definition=o6.ns.ns0.vartypes.BaseVariableType.BaseDataVariableType
)

Add a variable node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the variable.

required
browsename QualifiedName | str

The BrowseName for the variable.

required
attributes VariableAttributes | None

The variable attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the variable.

HasComponent
type_definition NodeIdLike

The variable type definition node id.

BaseDataVariableType

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created variable node id.

add_variable_type_node
add_variable_type_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.HasSubtype,
    browsename,
    requested_nodeid=None,
    attributes
)

Add a variable type node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the type node.

required
browsename QualifiedName | str

The BrowseName for the variable type.

required
attributes VariableTypeAttributes

The variable type attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the type node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created variable type node id.

add_object_node
add_object_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.Aggregates.HasComponent,
    browsename,
    requested_nodeid=None,
    attributes,
    type_definition=o6.ns.ns0.objtypes.BaseObjectType
)

Add an object node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the object.

required
browsename QualifiedName | str

The BrowseName for the object.

required
attributes ObjectAttributes

The object attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the object.

HasComponent
type_definition NodeIdLike

The object type definition node id.

BaseObjectType

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created object node id.

add_object_type_node
add_object_type_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.HasSubtype,
    browsename,
    requested_nodeid=None,
    attributes
)

Add an object type node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the type.

required
browsename QualifiedName | str

The BrowseName for the object type.

required
attributes ObjectTypeAttributes

The object type attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the type node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created object type node id.

add_view_node
add_view_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.Aggregates.HasComponent,
    browsename,
    requested_nodeid=None,
    attributes
)

Add a view node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the view.

required
browsename QualifiedName | str

The BrowseName for the view.

required
attributes ViewAttributes

The view attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the view.

HasComponent

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created view node id.

add_reference_type_node
add_reference_type_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.HasSubtype,
    browsename,
    requested_nodeid=None,
    attributes
)

Add a reference type node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the reference type.

required
browsename QualifiedName | str

The BrowseName for the reference type.

required
attributes ReferenceTypeAttributes

The reference type attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created reference type node id.

add_data_type_node
add_data_type_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.HasSubtype,
    browsename,
    requested_nodeid=None,
    attributes
)

Add a data type node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the data type.

required
browsename QualifiedName | str

The BrowseName for the data type.

required
attributes DataTypeAttributes

The data type attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created data type node id.

add_method_node
add_method_node(
    *,
    parent,
    parent_reference=o6.ns.ns0.reftypes.References.HierarchicalReferences.HasChild.Aggregates.HasComponent,
    browsename,
    requested_nodeid=None,
    attributes
)

Add a method node to the server.

Parameters:

Name Type Description Default
parent NodeIdLike

The parent node id for the method.

required
browsename QualifiedName | str

The BrowseName for the method.

required
attributes MethodAttributes

The method attributes.

required
requested_nodeid NodeIdLike | None

Optionally request a specific node id.

None
parent_reference NodeIdLike

The reference type used to link the method.

HasComponent

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created method node id.

delete_node
delete_node(nodeid, delete_target_references=True)

Delete one or more nodes from the address space.

Parameters:

Name Type Description Default
nodeid NodeIdLike | list[NodeIdLike]

A single node id or list of node ids to delete.

required
delete_target_references bool

If True, also delete references to the node targets.

True

Returns:

Type Description
MaybeAwaitable[StatusCode]

The first non-Good StatusCode from the per-node results, or

MaybeAwaitable[StatusCode]

StatusCode.Good if all deletions succeeded.

add_reference
add_reference(
    source,
    reftype,
    target,
    forward=True,
    target_nodeclass=o6.NodeClass.UNSPECIFIED,
    target_server_uri="",
)

Add a reference between two nodes.

Parameters:

Name Type Description Default
source NodeIdLike

The source node id for the reference.

required
reftype NodeIdLike

The reference type id.

required
target NodeIdLike | ExpandedNodeId

The target node id.

required
forward bool

If True, create a forward reference.

True
target_nodeclass NodeClass

Optional target node class for the reference.

...
target_server_uri str

Optional server uri when referencing an external node.

''

Returns:

Type Description
MaybeAwaitable[StatusCode]

The StatusCode returned by the server for this reference.

delete_reference
delete_reference(
    source,
    reftype,
    target,
    forward=True,
    delete_bidirectional=True,
)

Delete a reference between two nodes.

Parameters:

Name Type Description Default
source NodeIdLike

The source node id for the reference.

required
reftype NodeIdLike

The reference type id.

required
target NodeIdLike

The target node id.

required
forward bool

If True, delete the forward reference.

True
delete_bidirectional bool

If True, also delete the reverse reference.

True

Returns:

Type Description
MaybeAwaitable[StatusCode]

The StatusCode returned by the server for this deletion.

create_subscription
create_subscription(
    publishing_interval=100.0,
    lifetime_count=36000,
    max_keepalive_count=10,
    max_notifications_per_publish=10,
    publishing_enabled=True,
    *,
    on_created=None,
    on_status_change=None,
    on_deleted=None
)

Create a subscription to monitor data or events.

Parameters:

Name Type Description Default
req

Optional raw create subscription request object.

required
publishing_interval float

The desired publishing interval in milliseconds.

100.0
lifetime_count int

The subscription lifetime count.

36000
max_keepalive_count int

The maximum keepalive count.

10
max_notifications_per_publish int

The maximum number of notifications per publish.

10
publishing_enabled bool

Whether the subscription is initially enabled.

True
on_created Callable[[Subscription, CreateSubscriptionResponse], None] | None

Optional callback invoked with (subscription, response) once the server has acknowledged subscription creation.

None
on_status_change Callable[[Subscription, StatusChangeNotification], None] | None

Optional callback invoked with (subscription, notification) when the server publishes a StatusChangeNotification for this subscription.

None
on_deleted Callable[[Subscription], None] | None

Optional callback invoked with (subscription,) when the subscription is destroyed — explicitly via delete(), or implicitly on session close / disconnect.

None

Returns:

Type Description
MaybeAwaitable[Subscription]

A Subscription object representing the created subscription.

monitor
monitor(
    target,
    callback=None,
    sampling_interval=100.0,
    *,
    value_only=True,
    subscription=None,
    filter=None,
    monitoring_mode=o6.MonitoringMode.REPORTING,
    queue_size=1,
    discard_oldest=True,
    on_created=None,
    on_deleted=None
)

Monitor data changes on one or more nodes.

Parameters:

Name Type Description Default
target NodeIdLike | ReadValueId | list[NodeIdLike | ReadValueId]

A node id, [ReadValueId][o6.ReadValueId], or list thereof to monitor.

required
callback DataChangeCallback | None

Optional callback invoked for each data change. If None, a default callback that prints MonitoredItem {id}: {value} to stdout is used.

None
sampling_interval float

The requested sampling interval in milliseconds.

100.0
value_only bool

If True (default), the callback receives the unwrapped value. If False, it receives the full [DataValue][o6.DataValue].

True
subscription Subscription | None

Optional subscription to attach the monitored items to. If None (default), the clients' default subscription is used.

None
filter DataChangeFilter | None

Optional [DataChangeFilter][o6.DataChangeFilter] to control triggering.

None
monitoring_mode MonitoringMode

Monitoring mode for the item (default: REPORTING).

...
queue_size int

Requested queue size (default: 1).

1
discard_oldest bool

Whether to discard the oldest entry when the queue is full (default: True).

True
on_created CreatedCallback | None

Optional lifecycle callback; see MonitoredItem._data_change.

None
on_deleted DeletedCallback | None

Optional lifecycle callback; see MonitoredItem._data_change.

None

Returns:

Type Description
MaybeAwaitable[MonitoredItem | list[MonitoredItem]]

A monitored item or list of monitored items created for the target nodes.

monitor_event
monitor_event(
    nodeid,
    callback,
    filter=None,
    *,
    subscription=None,
    monitoring_mode=o6.MonitoringMode.REPORTING,
    queue_size=100,
    discard_oldest=True,
    on_created=None,
    on_deleted=None
)

Monitor events on a node.

Parameters:

Name Type Description Default
nodeid NodeIdLike

The node id to monitor for events.

required
callback EventCallback

Callback invoked for each matching event.

required
filter EventFilter | str | None

Optional event filter or filter expression string. If None, a default filter selecting EventId, EventType, SourceName, Time, Message, and Severity is used.

None
subscription Subscription | None

Optional subscription to attach the monitored item to. Defaults to :attr:default_subscription.

None
monitoring_mode MonitoringMode

Monitoring mode for the item (default: REPORTING).

...
queue_size int

Requested queue size (default: 100).

100
discard_oldest bool

Whether to discard the oldest entry when the queue is full (default: True).

True
on_created CreatedCallback | None

Optional lifecycle callback; see MonitoredItem._event.

None
on_deleted DeletedCallback | None

Optional lifecycle callback; see MonitoredItem._event.

None

Returns:

Type Description
MaybeAwaitable[MonitoredItem]

The created monitored event item.

Subscription

Represents an OPC UA subscription for monitoring data changes.

Functions
__await__
__await__()

Allow await Subscription(...) to work.

Creating a subscription requires a server round-trip, but __init__ cannot be async. The round-trip is therefore started in __init__ and awaited here, so callers can write sub = await Subscription(...) and be sure the subscription is fully set up before proceeding.

__bool__
__bool__()

Check if this is a valid subscription.

A deleted subscription evaluates to False. delete() cleans up the subscription on the server and client side, but cannot interfere with garbage collection of the Python object itself. Garbage collecting a deleted subscription is a noop in terms of state cleanup, but until then __bool__ indicates that the subscription is invalid.

delete
delete()

Delete this subscription from the server.

Returns:

Type Description
MaybeAwaitable[None]

The raw result of the delete operation.

modify
modify(
    publishing_interval=None,
    lifetime_count=None,
    max_keepalive_count=None,
    max_notifications_per_publish=None,
    publishing_enabled=None,
)

Modify subscription parameters.

Parameters:

Name Type Description Default
publishing_interval float | None

Optional new publishing interval.

None
lifetime_count int | None

Optional new lifetime count.

None
max_keepalive_count int | None

Optional new keepalive count.

None
max_notifications_per_publish int | None

Optional maximum notifications per publish.

None
publishing_enabled bool | None

Optional publishing enabled flag.

None

Returns:

Type Description
Any

The raw result of the modify operation.

MonitoredItem

Represents a monitored item within a subscription.

Functions
__await__
__await__()

Allow await MonitoredItem(...) to work.

Creating a monitored item requires a server round-trip, but __init__ cannot be async. The round-trip is therefore started in __init__ and awaited here, so callers can write item = await MonitoredItem(...) and be sure the item is fully set up before proceeding.

__bool__
__bool__()

Check if this is a valid MonitoredItem.

A deleted monitored item evaluates to False. delete() cleans up the monitored item on the server and client side, but cannot interfere with garbage collection of the Python object itself. Garbage collecting a deleted monitored item is a noop in terms of state cleanup, but until then __bool__ indicates that the monitored item is invalid.

delete
delete()

Delete this monitored item from its subscription.

Returns:

Type Description
MaybeAwaitable[None]

The raw result of the delete operation.

modify
modify(
    sampling_interval=None,
    queue_size=None,
    discard_oldest=None,
    filter=None,
)

Modify monitored item parameters.

Parameters:

Name Type Description Default
sampling_interval float | None

Optional new sampling interval.

None
queue_size int | None

Optional new queue size.

None
discard_oldest bool | None

Optional discard-oldest flag.

None
filter DataChangeFilter | EventFilter | str | None

Optional data change or event filter.

None

Returns:

Type Description
MaybeAwaitable[None]

The raw result of the modify operation.

set_monitoring_mode
set_monitoring_mode(mode)

Change the monitoring mode for this monitored item.

Parameters:

Name Type Description Default
mode MonitoringMode

The new monitoring mode.

required

Returns:

Type Description
MaybeAwaitable[None]

The raw result of the operation.

set_triggering
set_triggering(links_to_add=None, links_to_remove=None)

Configure triggering links for this monitored item.

Parameters:

Name Type Description Default
links_to_add list[MonitoredItem] | None

Monitored items to add as triggered links.

None
links_to_remove list[MonitoredItem] | None

Monitored items to remove from triggered links.

None

Returns:

Type Description
MaybeAwaitable[None]

The raw result of the operation.

Server

Bases: Server

High-level OPC UA Server.

Parameters

port : int, optional TCP port number (default 4840). logger : logging.Logger, optional Custom logger object. loop : asyncio.AbstractEventLoop, optional Event loop used for cooperative scheduling. When provided (or when a running loop is detected), the server avoids spawning a background thread and instead schedules non-blocking iterations on the loop. If None and no running loop exists, a daemon thread is used as a fallback. certificate : str, Path, or bytes, optional Server certificate (file path or raw bytes). private_key : str, Path, or bytes, optional Server private key (file path or raw bytes). trust_list : list, optional Trusted certificates for client verification. issuer_list : list, optional Issuer certificates. revocation_list : list, optional Certificate revocation lists. secure_only : bool If True, reject unencrypted connections (default False). accept_all_certificates : bool If True, trust all client certificates (default False). application_uri : str, optional Override the default application URI.

Example

server = Server(port=4840) with server: ... temp = server.add_variable("Temperature", ... server.objects_node, 22.5) ... print(temp.value) 22.5

Attributes
objects_node property
objects_node

The Objects folder (i=85).

types_node property
types_node

The Types folder (i=86).

server_node property
server_node

The Server object (i=2253).

Functions
add_namespace
add_namespace(uri)

Register a namespace URI in the client's local namespace table and return its assigned index.

If ns.append() is used to load pre-built companion specs, all ns.append() calls must come before any manual add_namespace() calls. Pre-built Namespaces expect specific canonical indices; a manual add_namespace() beforehand would occupy a slot and cause ns.append() to raise ValueError.

Calling add_namespace() after all ns.append() calls is safe and simply appends at the next free index.

.. note:: End users should never need to call this directly — all namespace registration goes through client.ns.append().

start
start()

Start the server networking layer.

The asyncio event loop handles all I/O, timers, and callbacks. When no running loop is detected (synchronous callers), a lightweight background daemon thread drives the loop instead.

stop
stop()

Shut down the server.

add_reverse_connect
add_reverse_connect(url, callback=None)

Register a reverse connect to a client listening at url.

The server will periodically attempt to establish a connection to the given client endpoint (e.g. opc.tcp://localhost:4841).

Parameters

url : str The OPC UA endpoint URL of the listening client. callback : callable, optional Called with (handle, state) on every state change.

Returns

int A handle that can be passed to :meth:remove_reverse_connect.

remove_reverse_connect
remove_reverse_connect(handle)

Remove a reverse connect registration.

Parameters

handle : int The handle returned by :meth:add_reverse_connect.

add_variable
add_variable(
    name,
    parent,
    value=None,
    *,
    nodeid=None,
    data_type=None,
    writable=True,
    historizing=False,
    ns=1
)

Add a variable node to the address space.

Parameters

name : str or LocalizedText Browse name (and display name) of the variable. parent : NodeIdLike Parent node (typically server.objects_node). value : any, optional Initial value. The OPC UA data-type is inferred automatically unless data_type is given explicitly. nodeid : NodeIdLike, optional Requested node id. None -> server assigns one. data_type : NodeIdLike, optional Explicit data type. If None, inferred from value. writable : bool Whether the variable is writable by clients (default True). historizing : bool Whether the variable supports historical data access (default False). ns : int Namespace index for the browse name (default 1).

Returns

VariableNode

add_object
add_object(
    name,
    parent,
    *,
    nodeid=None,
    type_definition=BASE_OBJECT_TYPE,
    ns=1
)

Add an object node to the address space.

Parameters

name : str or LocalizedText Browse name / display name. parent : NodeIdLike Parent node. nodeid : NodeIdLike, optional Requested node id. type_definition : NodeIdLike, optional Type definition node (default: BaseObjectType i=58). ns : int Namespace index for the browse name.

Returns

ObjectNode

add_object_type
add_object_type(
    name, parent=BASE_OBJECT_TYPE, *, nodeid=None, ns=1
)

Add an object type node.

Parameters

name : str or LocalizedText Browse name / display name. parent : NodeIdLike, optional Parent type node (default: BaseObjectType i=58). nodeid : NodeIdLike, optional Requested node id. ns : int Namespace index for the browse name.

Returns

ObjectTypeNode

add_variable_type
add_variable_type(
    name,
    parent=BASE_VARIABLE_TYPE,
    *,
    data_type=NS0_DT_DOUBLE,
    value_rank=-1,
    nodeid=None,
    ns=1
)

Add a variable type node.

Parameters

name : str or LocalizedText Browse name / display name. parent : NodeIdLike, optional Parent type (default: BaseVariableType i=62). data_type : NodeIdLike, optional Data type (default: Double i=11). value_rank : int Value rank (default: -1 = scalar). nodeid : NodeIdLike, optional Requested node id. ns : int Namespace index for the browse name.

Returns

VariableTypeNode

add_method
add_method(
    name,
    parent,
    callback,
    *,
    input_args=None,
    output_args=None,
    nodeid=None,
    ns=1
)

Add a method node to the address space.

Parameters

name : str or LocalizedText Browse name / display name. parent : NodeIdLike Parent node (typically an object node). callback : callable Python function called when a client invokes the method. Signature: callback(*inputs) -> list[output_values] input_args : list of Argument, optional Input argument descriptors. output_args : list of Argument, optional Output argument descriptors. nodeid : NodeId, optional Requested node id. ns : int Namespace index for the browse name.

Returns

MethodNode

add_reference
add_reference(
    source, target, reference_type, *, forward=True
)

Add a reference between two nodes.

delete_node
delete_node(nodeid, *, delete_references=True)

Delete a node from the address space.

call
call(object_id, method_id, input_args=[])

Call a method node server-side with admin privileges.

Matches client.call() — returns (StatusCode, *output_arguments).

Parameters

object_id : NodeIdLike The object node that owns the method. method_id : NodeIdLike The method node to invoke. input_args : list, optional Input argument values.

Returns

tuple (status_code, output1, output2, ...)

read
read(target, attr=o6.AttributeId.VALUE)

Read one or more node attributes from the server.

write
write(target, value, attr=o6.AttributeId.VALUE)

Write one or more node attributes on the server.

If value is a :class:DataValue, it is written directly via UA_Server_writeDataValue — preserving any explicit status code and timestamps stored in the object. Otherwise behaves as before.

browse_node
browse_node(nodeid, result_mask)

Browse children of a node.

translate_browse_paths
translate_browse_paths(request)

Server-side translate browse paths to node ids.

read_node_info
read_node_info(nodeid)

Return (node_class_int, browse_name) for a node.

find_data_type
find_data_type(nodeid)

Look up a DataType by NodeId and return the Python type or metadata.

read_attribute
read_attribute(nodeid, attr_id)

Read any standard attribute by its integer AttributeId.

read_object_property
read_object_property(object_id, property_name)

Read an object property by BrowseName.

write_object_property
write_object_property(object_id, property_name, value)

Write an object property by BrowseName.

ValueRank

Bases: IntEnum

Enum for the most common ValueRanks. ValueRanks >2 can also be used. They indicate an array with the given dimensions. But ValueRanks >2 don't have a shortname defined in this enum class.

AccessLevel

Bases: IntFlag

Bitmask values for the AccessLevel and UserAccessLevel attributes.

WriteMask

Bases: IntFlag

Bitmask values for the WriteMask and UserWriteMask attributes.

SecureChannelState

Bases: IntEnum

Possible status of a SecureChannel

SessionState

Bases: IntEnum

Possible status of a Session

SecurityMode

Bases: IntEnum

OPC UA MessageSecurityMode.

SecurityPolicy

Bases: str, Enum

OPC UA security policy URIs.

Functions

make_argument

make_argument(
    name, data_type, *, value_rank=-1, description=""
)

Create an OPC UA Argument descriptor.

Parameters

name : str Argument name. data_type : NodeIdLike Data type (e.g. "i=11" for Double). value_rank : int Value rank (-1 = scalar, 1 = 1D array, ...). description : str or LocalizedText Human-readable description.

Returns

o6.Argument