Skip to content

Client

Canonical path: o6.client.Client

Root shortcut: o6.Client

Client

Bases: _NativeClient

High-level OPC UA client.

with o6.Client("opc.tcp://localhost:4840") as client:
    print(client.read("ns=1;s=Temperature"))

Every request-issuing method returns a plain value when the client drives its own event loop, and an awaitable when it runs on an external one; see MaybeAwaitable. Operations on a client that is not connected raise instead of silently doing nothing.

See the Client guide for the whole picture, and the tutorials for task-by-task walkthroughs.

Attributes

config instance-attribute

config

This client's ClientConfig.

root instance-attribute

root = ObjectNode(
    _node_backend, "i=84", QualifiedName(0, "Root")
)

Node handle for the standard Root folder (i=84).

objects instance-attribute

objects = ObjectNode(
    _node_backend, "i=85", QualifiedName(0, "Objects")
)

Node handle for the standard Objects folder (i=85).

types instance-attribute

types = ObjectNode(
    _node_backend, "i=86", QualifiedName(0, "Types")
)

Node handle for the standard Types folder (i=86).

views instance-attribute

views = ObjectNode(
    _node_backend, "i=87", QualifiedName(0, "Views")
)

Node handle for the standard Views folder (i=87).

T class-attribute instance-attribute

T = TypeVar('T')

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.

subscriptions property

subscriptions

A copy of the active subscriptions for this client, keyed by id.

defaultSubscription property

defaultSubscription

The clients' default subscription.

Raises RuntimeError when accessed in a not-connected state.

Functions

__init__

__init__(
    endpointUrl="",
    loop=None,
    *,
    logger=None,
    certificate=None,
    privateKey=None,
    trustList=None,
    revocationList=None,
    securityMode=None,
    securityPolicy=None,
    applicationUri=None,
    username=None,
    password=None,
    name=""
)

Create a new OPC UA client.

The constructor accepts the most commonly needed settings as keyword arguments. Everything else — sessionName, requestedSessionTimeout, sessionLocaleIds, endpoint, and every other ClientConfig property — is set on client.config before calling connect():

client = o6.Client("opc.tcp://localhost:4840")
client.config.sessionName = "my-session"
client.config.requestedSessionTimeout = 60_000
client.config.sessionLocaleIds = ["en-US"]
client.config.endpoint = my_endpoint_description
client.config.setUsernamePassword("user", "secret")
client.connect()

Parameters:

Name Type Description Default
endpointUrl str

OPC UA endpoint to connect to, e.g. "opc.tcp://localhost:4840". May also be passed later via client.config.endpointUrl and/or connect().

''
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
privateKey str | Path | bytes | None

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

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

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

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

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

None
securityMode int | None

OPC UA message security mode (UA_MessageSecurityMode integer or o6.ns.ns0.datatypes.MessageSecurityMode enum). Equivalent to client.config.securityMode.

None
securityPolicy str | None

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

None
applicationUri str | None

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

None
username str | None

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

None
password str | None

Password for UserNameIdentityToken authentication. Used together with username.

None
name str

Optional client name. Must be a valid Python identifier, not match server<digits> or ::global/global, and must be unique within the process. When omitted, an auto-generated clientN name is assigned.

''

__del__

__del__()

connect

connect(noSession=False)

Connect to the server.

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

If noSession 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.

# sync
client.connect()

# async
await client.connect()

Parameters:

Name Type Description Default
noSession bool

Open only the SecureChannel, skip Session creation.

False

disconnect

disconnect(closeSession=True, deleteSubscriptions=True)

Disconnect from the server.

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

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

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

# sync
client.disconnect()

# async
await client.disconnect()

Parameters:

Name Type Description Default
closeSession bool

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

True
deleteSubscriptions bool

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

True

startReverseConnect

startReverseConnect(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.

client.startReverseConnect(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

activateCurrentSession

activateCurrentSession()

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:

client.connect()                  # establishes session
# ... channel re-established ...
client.activateCurrentSession() # re-bind session to new channel

activateSession

activateSession(authToken, serverNonce)

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(noSession=True)), then call this method with the token and nonce obtained from the originating session.

# Client B — take over a session using credentials supplied
# by the originating session
client_b.connect(noSession=True)
client_b.activateSession(token, nonce)

Parameters:

Name Type Description Default
authToken NodeId

Authentication token (NodeId) from the originating session.

required
serverNonce bytes

Server nonce bytes from the originating session.

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.

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.

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 instance.

node = client["ns=1;s=Temperature"]        # sync
node = await client["ns=1;s=Temperature"]  # async

serviceFindServers

serviceFindServers(request)

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

OPC UA Part 4 §5.5.2

serviceFindServersOnNetwork

serviceFindServersOnNetwork(request)

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

OPC UA Part 4 §5.5.3

serviceGetEndpoints

serviceGetEndpoints(request)

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

OPC UA Part 4 §5.5.4

serviceAddNodes

serviceAddNodes(request)

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

OPC UA Part 4 §5.8.2

serviceDeleteNodes

serviceDeleteNodes(request)

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

OPC UA Part 4 §5.8.4

serviceAddReferences

serviceAddReferences(request)

Raw AddReferences service call — add references between nodes.

OPC UA Part 4 §5.8.3

serviceDeleteReferences

serviceDeleteReferences(request)

Raw DeleteReferences service call — remove references between nodes.

OPC UA Part 4 §5.8.5

serviceBrowse

serviceBrowse(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 serviceBrowseNext to continue if the response indicates more results are available.

OPC UA Part 4 §5.9.2

serviceBrowseNext

serviceBrowseNext(request)

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

OPC UA Part 4 §5.9.3

serviceTranslateBrowsePathsToNodeIds

serviceTranslateBrowsePathsToNodeIds(request)

Raw TranslateBrowsePathsToNodeIds service call — resolve browse paths to NodeIds.

OPC UA Part 4 §5.9.4

serviceRegisterNodes

serviceRegisterNodes(request)

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

OPC UA Part 4 §5.9.5

serviceUnregisterNodes

serviceUnregisterNodes(request)

Raw UnregisterNodes service call — release NodeIds obtained via RegisterNodes.

OPC UA Part 4 §5.9.6

serviceRead

serviceRead(request)

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

OPC UA Part 4 §5.11.2

serviceHistoryRead

serviceHistoryRead(request)

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

OPC UA Part 4 §5.11.3

serviceWrite

serviceWrite(request)

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

OPC UA Part 4 §5.11.4

serviceHistoryUpdate

serviceHistoryUpdate(request)

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

OPC UA Part 4 §5.11.5

serviceCall

serviceCall(request)

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

OPC UA Part 4 §5.12.2

getRemoteDataTypes

getRemoteDataTypes(typeNodes=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 typeNodes 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:

  • typeName (str) — BrowseName.name of the DataType node.
  • typeId (NodeId) — NodeId of the DataType node.
  • binaryEncodingId (NodeId) — default binary encoding NodeId (StructureDefinition.defaultEncodingId).
  • structureType ([StructureType][o6.ns.ns0.datatypes.StructureType]) — the information-model structure category.
  • membersSize (int) — number of fields in the structure.

Parameters:

Name Type Description Default
typeNodes list[NodeIdLike] | None

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

None

updateRemoteNamespaces

updateRemoteNamespaces()

Atomically synchronize namespace mappings and custom datatypes.

The client first installs a provisional wire-index mapping when a URI has several compiled versions, reads the server's NamespaceMetadata, then selects an exact version or the latest available fallback. The final Python mapping, SecureChannel decoder mapping, and custom datatype chain are replaced as one snapshot. A failed refresh leaves the preceding snapshot usable. Call this again if a connected server adds namespaces at runtime; unchanged snapshots are not rebuilt.

getEndpoints

getEndpoints(
    endpointUrl, *, localeIds=None, profileUris=None
)

Return the endpoints advertised by a server.

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

Each [EndpointDescription][o6.ns.ns0.datatypes.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.ns.ns0.datatypes.UserTokenPolicy] entries.

client.connect(noSession=True)
endpoints = client.getEndpoints("opc.tcp://localhost:4840")
for ep in endpoints:
    print(ep.endpointUrl, ep.securityMode, ep.securityPolicyUri)

Parameters:

Name Type Description Default
endpointUrl str

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

required
localeIds 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
profileUris list[str] | None

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

None

findServers

findServers(
    endpointUrl, *, serverUris=None, localeIds=None
)

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

Sends a FindServers request to endpointUrl. 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.ns.ns0.datatypes.ApplicationDescription].

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

Each [ApplicationDescription][o6.ns.ns0.datatypes.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 getEndpoints.

client.connect(noSession=True)
servers = client.findServers("opc.tcp://localhost:4840")
for srv in servers:
    print(srv.applicationUri, srv.discovery_urls)

Parameters:

Name Type Description Default
endpointUrl str

URL of the discovery server or server to query.

required
localeIds list[str] | None

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

None
serverUris list[str] | None

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

None

findServersOnNetwork

findServersOnNetwork(
    startingRecordId=0,
    maxRecordsToReturn=0,
    serverCapabilityFilter=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 startingRecordId and maxRecordsToReturn to page through large registries. The record_id field on each [ServerOnNetwork][o6.ns.ns0.datatypes.ServerOnNetwork] entry can be used as the startingRecordId for the next page.

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

# Fetch the first 100 servers that support Data Access
servers = client.findServersOnNetwork(
    maxRecordsToReturn=100,
    serverCapabilityFilter=["DA"],
)

Parameters:

Name Type Description Default
startingRecordId int

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

0
maxRecordsToReturn int

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

0
serverCapabilityFilter list[str] | None

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

None

read

read(
    target,
    *,
    attr=o6.AttributeId.VALUE,
    timestampsToReturn=None,
    valueOnly=True,
    range=None
)

Read multiple node attributes from the server in a single batch.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike]

A list of node ids to read.

required
attr AttributeId | str

The attribute to read, typically o6.AttributeId.VALUE. Can also be an attribute name as string, such as 'browseName'.

VALUE
timestampsToReturn TimestampsToReturn | None

If provided, return the data value timestamps.

None
valueOnly bool

If True, return only the data values (default). If False, return the raw DataValue objects.

True
range IndexRange | list[IndexRange]

An OPC UA range string or tuple of Python slices. A list supplies one range per target. "1:3" and (slice(1, 4),) select the same elements.

None

Returns:

Type Description
Any

A list of attribute values, one per target node. If valueOnly is

Any

False, the list contains the corresponding DataValue objects.

write

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

Write values to multiple nodes given as a {node: value} mapping.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike] | dict[NodeIdLike, Any]

A mapping of node ids to the values to write.

required
attr AttributeId | str

The attribute to write, typically o6.AttributeId.VALUE. Can also be an attribute name as string, such as 'browseName'.

VALUE
range IndexRange | list[IndexRange]

An OPC UA range string or tuple of stop-exclusive Python slices. A list supplies one range per target. "1:3" and (slice(1, 4),) select the same elements.

None

Returns:

Type Description
MaybeAwaitable[StatusCode | list[StatusCode]]

A list of StatusCode values, one per entry in target, in the

MaybeAwaitable[StatusCode | list[StatusCode]]

mapping's iteration order.

Note

The range argument is not supported for this form — use the list form (target=[...], value=[...], range=...) if per-node ranges are needed.

call

call(objectId, methodId, inputArgs=[])

Invoke a method on a node.

Parameters:

Name Type Description Default
objectId NodeIdLike

The object node id that owns the method.

required
methodId NodeIdLike

The method node id to invoke.

required
inputArgs list[Any]

Positional input arguments to pass to the method.

[]

Returns:

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

A tuple of (StatusCode, *output_arguments).

browse

browse(
    target,
    *,
    direction=ns0.datatypes.BrowseDirection.FORWARD,
    reftype=ns0.reftypes.HierarchicalReferences,
    refsubtypes=True,
    nodeClassMask=ns0.datatypes.NodeClass.UNSPECIFIED,
    resultMask=ns0.datatypes.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).

FORWARD
reftype NodeIdLike

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

HierarchicalReferences
refsubtypes bool

If True, include subtypes of the reference type.

True
nodeClassMask NodeClass

A node-class mask to filter the target nodes.

UNSPECIFIED
resultMask BrowseResultMask

A browse result mask to customize returned fields.

BrowseResultMask(0)

Returns:

Type Description
MaybeAwaitable[BrowseResult]

A list of ReferenceDescription objects describing the found

MaybeAwaitable[BrowseResult]

references.

browseInteractive

browseInteractive(nodeId=None)

Open a curses-based interactive browser for the address space.

Requires the curses module (install windows-curses on Windows). Returns the selected NodeId string (or BrowsePath string) when the user quits with n / p; returns None otherwise.

Parameters:

Name Type Description Default
nodeId NodeIdLike | None

Optional starting node id (defaults to Objects).

None

historyRead

historyRead(
    target,
    startTime,
    endTime,
    numValuesPerNode=0,
    returnBounds=False,
    timestampsToReturn=ns0.datatypes.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
startTime datetime

The start time for the history interval.

required
endTime datetime

The end time for the history interval.

required
numValuesPerNode int

Maximum number of values to return per node.

0
returnBounds bool

If True, include boundary values at the interval edges.

False
timestampsToReturn TimestampsToReturn

Which timestamps to return with each value.

BOTH

Returns:

Type Description
Any

Historical values or data values for the requested nodes.

historyUpdateInsert

historyUpdateInsert(target, values)

Insert new historical values into a node's history.

Insertion fails for any timestamp that already has a value stored. Use historyUpdateReplace 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.

historyUpdateReplace

historyUpdateReplace(target, values)

Replace existing historical values for a node.

Replacement requires that a value already exists at each provided timestamp. Use historyUpdateInsert 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.

historyUpdateDelete

historyUpdateDelete(target, startTime, endTime)

Delete historical values from a node.

Parameters:

Name Type Description Default
target NodeIdLike

The node id whose history should be deleted.

required
startTime datetime

The start of the deletion interval.

required
endTime datetime

The end of the deletion interval.

required

Returns:

Type Description
Any

The raw result of the history delete operation.

addVariableNode

addVariableNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasComponent,
    browseName,
    requestedNodeId=None,
    attributes,
    typeDefinition=ns0.vartypes.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

The variable attributes.

required
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the variable.

HasComponent
typeDefinition NodeIdLike

The variable type definition node id.

BaseDataVariableType

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created variable node id.

addVariableTypeNode

addVariableTypeNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasSubtype,
    browseName,
    requestedNodeId=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the type node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created variable type node id.

addObjectNode

addObjectNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasComponent,
    browseName,
    requestedNodeId=None,
    attributes,
    typeDefinition=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the object.

HasComponent
typeDefinition NodeIdLike

The object type definition node id.

BaseObjectType

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created object node id.

addObjectTypeNode

addObjectTypeNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasSubtype,
    browseName,
    requestedNodeId=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the type node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created object type node id.

addViewNode

addViewNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasComponent,
    browseName,
    requestedNodeId=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the view.

HasComponent

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created view node id.

addReferenceTypeNode

addReferenceTypeNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasSubtype,
    browseName,
    requestedNodeId=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created reference type node id.

addDataTypeNode

addDataTypeNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasSubtype,
    browseName,
    requestedNodeId=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the node.

HasSubtype

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created data type node id.

addMethodNode

addMethodNode(
    *,
    parent,
    parentReference=ns0.reftypes.HasComponent,
    browseName,
    requestedNodeId=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
requestedNodeId NodeIdLike | None

Optionally request a specific node id.

None
parentReference NodeIdLike

The reference type used to link the method.

HasComponent

Returns:

Type Description
MaybeAwaitable[NodeId]

The newly created method node id.

deleteNode

deleteNode(nodeId, deleteTargetReferences=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
deleteTargetReferences 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.

addReference

addReference(
    source,
    reftype,
    target,
    forward=True,
    targetNodeClass=ns0.datatypes.NodeClass.UNSPECIFIED,
    targetServerUri="",
)

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
targetNodeClass NodeClass

Optional target node class for the reference.

UNSPECIFIED
targetServerUri str

Optional server uri when referencing an external node.

''

Returns:

Type Description
MaybeAwaitable[StatusCode]

The StatusCode returned by the server for this reference.

deleteReference

deleteReference(
    source,
    reftype,
    target,
    forward=True,
    deleteBidirectional=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
deleteBidirectional bool

If True, also delete the reverse reference.

True

Returns:

Type Description
MaybeAwaitable[StatusCode]

The StatusCode returned by the server for this deletion.

createSubscription

createSubscription(
    publishingInterval=100.0,
    lifetimeCount=36000,
    maxKeepaliveCount=10,
    maxNotificationsPerPublish=10,
    publishingEnabled=True,
    *,
    onCreated=None,
    onStatusChange=None,
    onDeleted=None
)

Create a subscription to monitor data or events.

Parameters:

Name Type Description Default
publishingInterval float

The desired publishing interval in milliseconds.

100.0
lifetimeCount int

The subscription lifetime count.

36000
maxKeepaliveCount int

The maximum keepalive count.

10
maxNotificationsPerPublish int

The maximum number of notifications per publish.

10
publishingEnabled bool

Whether the subscription is initially enabled.

True
onCreated Callable[['o6.subscription.Subscription', CreateSubscriptionResponse], None] | None

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

None
onStatusChange Callable[['o6.subscription.Subscription', StatusChangeNotification], None] | None

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

None
onDeleted Callable[['o6.subscription.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 o6.subscription.Subscription object representing the created subscription.

monitor

monitor(
    target,
    callback=None,
    samplingInterval=100.0,
    *,
    valueOnly=True,
    subscription=None,
    filter=None,
    monitoringMode=ns0.datatypes.MonitoringMode.REPORTING,
    queueSize=1,
    discardOldest=True,
    onCreated=None,
    onDeleted=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.ns.ns0.datatypes.ReadValueId], or list thereof to monitor.

required
callback DataChangeCallback | None

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

None
samplingInterval float

The requested sampling interval in milliseconds.

100.0
valueOnly bool

If True (default), the callback receives the unwrapped value. If False, it receives the full 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.ns.ns0.datatypes.DataChangeFilter] to control triggering.

None
monitoringMode MonitoringMode

Monitoring mode for the item (default: REPORTING).

REPORTING
queueSize int

Requested queue size (default: 1).

1
discardOldest bool

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

True
onCreated CreatedCallback | None

Optional lifecycle callback; see o6.subscription.MonitoredItem._data_change.

None
onDeleted DeletedCallback | None

Optional lifecycle callback; see o6.subscription.MonitoredItem._data_change.

None

Returns:

Type Description
MaybeAwaitable[MonitoredItem | list[MonitoredItem]]

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

monitorEvent

monitorEvent(
    nodeId,
    callback,
    filter=None,
    *,
    subscription=None,
    monitoringMode=ns0.datatypes.MonitoringMode.REPORTING,
    queueSize=100,
    discardOldest=True,
    onCreated=None,
    onDeleted=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 defaultSubscription.

None
monitoringMode MonitoringMode

Monitoring mode for the item (default: REPORTING).

REPORTING
queueSize int

Requested queue size (default: 100).

100
discardOldest bool

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

True
onCreated CreatedCallback | None

Optional lifecycle callback; see o6.subscription.MonitoredItem._event.

None
onDeleted DeletedCallback | None

Optional lifecycle callback; see o6.subscription.MonitoredItem._event.

None

Returns:

Type Description
MaybeAwaitable[MonitoredItem]

The created monitored event item.