Skip to content

Server

Canonical path: o6.server.Server

Root shortcut: o6.Server

Server

Bases: _NativeServer

High-level OPC UA server.

server = o6.Server(port=4840)
with server:
    temperature = server.addVariable("Temperature", server.objectsNode, 22.5)
    print(temperature())

Every method below returns a plain value when the server drives its own event loop, and an awaitable when it runs on an external one; see MaybeAwaitable.

See the Server guide for the whole picture, and Server callbacks for behaviour implementation.

Attributes

roles instance-attribute

roles = _RoleRegistry(self)

ns instance-attribute

ns = _ServerNamespaces(self)

T class-attribute instance-attribute

T = TypeVar('T')

objectsNode property

objectsNode

The Objects folder (i=85).

typesNode property

typesNode

The Types folder (i=86).

serverNode property

serverNode

The Server object (i=2253).

endpointUrl property

endpointUrl

The local endpoint URL, built from the configured port.

Functions

__init__

__init__(
    port=4840,
    logger=None,
    loop=None,
    *,
    certificate=None,
    privateKey=None,
    trustList=None,
    issuerList=None,
    revocationList=None,
    secureOnly=False,
    acceptAllCertificates=False,
    applicationUri=None,
    accessControl=None,
    allowNonePolicyPassword=False,
    rbacForAnonymous=False
)

Create a server. It is not listening until start() is called.

Parameters:

Name Type Description Default
port int

TCP port to bind.

4840
logger Logger | None

Logger for server output. Defaults to the o6.server logger.

None
loop AbstractEventLoop | None

Event loop to schedule non-blocking iterations on. When given, or when a running loop is detected, the server does not spawn a background thread; otherwise it creates its own loop and drives it from a daemon thread.

None
certificate str | Path | bytes | None

Server certificate, as a path or raw DER or PEM bytes. Encryption is configured only when a private key is given too.

None
privateKey str | Path | bytes | None

Matching private key, as a path or raw bytes.

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

Client certificates the server trusts.

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

Issuer certificates for chain validation.

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

Certificate revocation lists.

None
secureOnly bool

Refuse unencrypted connections.

False
acceptAllCertificates bool

Trust every client certificate. For development only.

False
applicationUri str | None

Override the advertised application URI. It must match the URI inside the server certificate on secured endpoints.

None
accessControl AccessControl | None

An AccessControl subclass instance that authenticates and authorizes sessions.

None
allowNonePolicyPassword bool

Permit username/password tokens on an unencrypted channel.

False
rbacForAnonymous bool

Enforce role permissions for anonymous sessions. Off by default, which leaves anonymous sessions permissive.

False

Raises:

Type Description
TypeError

accessControl is not an o6.AccessControl instance.

PermissionError

This build has no server feature entitlement.

implement

implement(
    declaration: type, implementation: type | None
) -> None
implement(target: MethodNode, behavior: None) -> None
implement(target: VariableNode, behavior: Any) -> None
implement(
    target: MethodNode | NodeIdLike,
    /,
    *,
    call: Callable[..., Any] | None,
) -> None
implement(
    target: (
        VariableNode | VariableTypeNode | type | NodeIdLike
    ),
    /,
    *,
    read: (
        VariableReadCallback | None | object
    ) = _CALLBACK_UNSET,
    write: (
        VariableWriteCallback | None | object
    ) = _CALLBACK_UNSET,
) -> None
implement(
    target,
    implementation=_CALLBACK_UNSET,
    /,
    *,
    call=_CALLBACK_UNSET,
    read=_CALLBACK_UNSET,
    write=_CALLBACK_UNSET,
)

Install server-local Python behaviour on a UA type or concrete node.

implement(DeclarationType, ImplementationType) binds an undecorated Python behaviour subclass to an existing ObjectType or VariableType on this server alone. Future instances created through native APIs or an AddNodes request receive that implementation, without modifying or subclassing the UA information model. Their implementation-selected children are created before the native Mandatory children, and their ordinary Python initializer runs once, after the complete subtree exists. Because AddNodes supplies no Python arguments, that initializer must be callable without required arguments. Passing None restores the declaration's own Python type for future instances.

Passing None positionally for a concrete Method or Variable restores the callback resolution performed during construction. A concrete value positionally supplied for a Variable removes both callbacks and installs that value in native storage.

call=, read=, and write= replace or clear one callback slot on a Method, Variable, or VariableType. Existing concrete instances are never changed by a type-level update.

Parameters:

Name Type Description Default
target MethodNode | VariableNode | VariableTypeNode | NodeIdLike | type

The declared type to implement, or a concrete Method, Variable, VariableType, or NodeId-like value.

required
implementation Any

An implementation class for a type target, None to reset, or a value to store for a Variable target. Cannot be combined with the keyword slots.

_CALLBACK_UNSET
call Callable[..., Any] | None | object

Method implementation, or None to clear the slot.

_CALLBACK_UNSET
read VariableReadCallback | None | object

Variable value-read implementation, or None to clear the slot.

_CALLBACK_UNSET
write VariableWriteCallback | None | object

Variable value-write implementation, or None to clear the slot.

_CALLBACK_UNSET

Raises:

Type Description
TypeError

An implementation class is combined with call=, read=, or write=; a Method is given a positional value other than None; or a positional value targets something that is neither a Method nor a Variable.

See Implementing behaviour and Server callbacks.

createEvent

createEvent(
    eventType=ns0.objtypes.BaseEventType,
    *,
    source=ns0.instances.server,
    message="",
    severity=1,
    fields=None,
    payloadSource=None
)

Create a reusable event draft without emitting it.

emitEvent

emitEvent(
    eventType=ns0.objtypes.BaseEventType,
    *,
    source=ns0.instances.server,
    message="",
    severity=1,
    fields=None,
    payloadSource=None
)

Emit an event and return its generated EventId.

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.

__enter__

__enter__()

Start the server and return it.

__exit__

__exit__(exc_type, exc_val, exc_tb)

Stop the server on leaving the block, including on an exception.

__aenter__ async

__aenter__()

Start the server and return it.

__aexit__ async

__aexit__(exc_type, exc_val, exc_tb)

Stop the server on leaving the block, including on an exception.

__del__

__del__()

addReverseConnect

addReverseConnect(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:

Name Type Description Default
url str

The OPC UA endpoint URL of the listening client.

required
callback Callable[[int, int], None] | None

Called with (handle, state) on every state change.

None

Returns:

Type Description
int

A handle that can be passed to removeReverseConnect.

removeReverseConnect

removeReverseConnect(handle)

Remove a reverse connect registration.

Parameters:

Name Type Description Default
handle int

The handle returned by addReverseConnect.

required

addVariable

addVariable(
    name,
    parent,
    value=None,
    *,
    nodeId=None,
    dataType=None,
    typeDefinition=o6.NodeId(
        ns0.vartypes.BaseDataVariableType
    ),
    writable=True,
    historizing=False,
    ns=1
)

Add a variable node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the Variable.

required
parent NodeIdLike

Parent node, typically server.objectsNode.

required
value Any

Initial value. Its OPC UA DataType is inferred unless dataType is given explicitly.

None
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
dataType NodeIdLike | None

Explicit DataType. Inferred from value when omitted.

None
typeDefinition NodeIdLike

VariableType of the new node.

NodeId(BaseDataVariableType)
writable bool

Whether clients may write the Variable.

True
historizing bool

Whether the Variable supports historical access.

False
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
VariableNode

A handle to the new Variable node.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addObject

addObject(
    name,
    parent,
    *,
    nodeId=None,
    typeDefinition=o6.NodeId(ns0.objtypes.BaseObjectType),
    ns=1
)

Add an object node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the Object.

required
parent NodeIdLike

Parent node.

required
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
typeDefinition NodeIdLike

ObjectType of the new node. Defaults to BaseObjectType (i=58).

NodeId(BaseObjectType)
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
ObjectNode

A handle to the new Object node.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addObjectType

addObjectType(
    name,
    parent=o6.NodeId(ns0.objtypes.BaseObjectType),
    *,
    nodeId=None,
    ns=1
)

Add an object type node.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the ObjectType.

required
parent NodeIdLike

The HasSubtype parent. Defaults to BaseObjectType (i=58).

NodeId(BaseObjectType)
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
ObjectTypeNode

A handle to the new ObjectType node.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addVariableType

addVariableType(
    name,
    parent=o6.NodeId(ns0.vartypes.BaseVariableType),
    *,
    dataType=o6.NodeId(o6.Double),
    valueRank=-1,
    nodeId=None,
    ns=1
)

Add a variable type node.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the VariableType.

required
parent NodeIdLike

The HasSubtype parent. Defaults to BaseVariableType (i=62).

NodeId(BaseVariableType)
dataType NodeIdLike

DataType of the value. Defaults to Double (i=11).

NodeId(Double)
valueRank int

ValueRank of the value. Defaults to -1, a scalar.

-1
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
VariableTypeNode

A handle to the new VariableType node.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addReferenceType

addReferenceType(
    name,
    parent=ns0.reftypes.NonHierarchicalReferences,
    *,
    inverseName=None,
    symmetric=False,
    abstract=False,
    nodeId=None,
    ns=1
)

Add a ReferenceType node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

DisplayName of the node, also used as its BrowseName.

required
parent NodeIdLike

The HasSubtype parent. Defaults to NonHierarchicalReferences.

NonHierarchicalReferences
inverseName LocalizedTextLike | None

InverseName attribute, the name of the reverse direction. OPC UA requires it for a non-symmetric, non-abstract ReferenceType.

None
symmetric bool

Declare the reference symmetric, so it reads the same in both directions and needs no InverseName.

False
abstract bool

Declare the ReferenceType abstract, so only its subtypes may be used in references.

False
nodeId NodeIdLike | None

NodeId of the node. The server allocates one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
ReferenceTypeNode

A handle to the new ReferenceType node.

Raises:

Type Description
StatusCodeError

The AddNodes call failed, for example because the NodeId is taken or the parent does not exist.

addView

addView(
    name,
    parent=ns0.instances.views,
    *,
    eventNotifier=0,
    containsNoLoops=True,
    nodeId=None,
    ns=1
)

Add a View node to the address space.

The View starts out empty; add its members with addReference. For the declarative route, use o6.view instead.

Parameters:

Name Type Description Default
name LocalizedTextLike

DisplayName of the node, also used as its BrowseName.

required
parent NodeIdLike

Node that organizes the View. Defaults to the standard ViewsFolder.

views
eventNotifier int

EventNotifier attribute of the node.

0
containsNoLoops bool

ContainsNoLoops attribute, asserting that browsing the View cannot revisit a node.

True
nodeId NodeIdLike | None

NodeId of the node. The server allocates one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
ViewNode

A handle to the new View node.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addMethod

addMethod(
    name,
    parent,
    callback,
    *,
    inputArgs=None,
    outputArgs=None,
    nodeId=None,
    ns=1
)

Add a method node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the Method.

required
parent NodeIdLike

Parent node, typically an Object.

required
callback MethodCallback

Called when a client invokes the Method. See MethodCallback for the signature.

required
inputArgs list[Argument] | None

InputArguments descriptors.

None
outputArgs list[Argument] | None

OutputArguments descriptors.

None
nodeId NodeId | None

Requested NodeId. The server assigns one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
MethodNode

The unbound server Method node. Invoke it with object=parent, or

MethodNode

reach it through the parent Object's dot syntax to obtain a bound

MethodNode

call.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addReference

addReference(
    source, target, referenceType, *, forward=True
)

Add a reference between two nodes.

Parameters:

Name Type Description Default
source NodeIdLike

Source node id.

required
target NodeIdLike

Target NodeId or ExpandedNodeId. An ExpandedNodeId may name a node on another server.

required
referenceType NodeIdLike

Reference type NodeId.

required
forward bool

True for a forward reference, False for inverse.

True

deleteReference

deleteReference(
    source,
    target,
    referenceType,
    *,
    forward=True,
    bidirectional=True
)

Delete a reference between two nodes.

deleteNode

deleteNode(nodeId, *, deleteReferences=True)

Delete a node from the address space.

Parameters:

Name Type Description Default
nodeId NodeIdLike

The node id to delete.

required
deleteReferences bool

If True (default), also delete references pointing to the node.

True

call

call(objectId, methodId, inputArgs=[])

Call a method node server-side with admin privileges.

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

Parameters:

Name Type Description Default
objectId NodeIdLike

The Object that owns the Method.

required
methodId NodeIdLike

The Method to invoke.

required
inputArgs list[Any]

InputArguments values, in declaration order.

[]

Returns:

Type Description
MaybeAwaitable[tuple]

(statusCode, output1, output2, ...).

Raises:

Type Description
StatusCodeError

The Call service failed.

read

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

Read one or more node attributes from the server.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike]

A single node id or a list of node ids.

required
attr AttributeId | str

The attribute to read; defaults to o6.AttributeId.VALUE. Can also be an attribute name string.

VALUE
range IndexRange | list[IndexRange]

An OPC UA range string, a Python slice, or a tuple of slices. A list supplies one range per target.

None

Returns:

Type Description
MaybeAwaitable[Any]

The attribute value (or list of values when target is a list).

write

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

Write one or more node attributes on the server.

If value is a o6.DataValue, it is written directly via UA_Server_writeDataValue — preserving any explicit status code and timestamps stored in the object. Otherwise the value is wrapped in a DataValue before writing.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike]

A single node id or a list of node ids.

required
value Any

Value (or DataValue) to write.

required
attr AttributeId | str

The attribute to write; defaults to o6.AttributeId.VALUE.

VALUE
range IndexRange | list[IndexRange]

An OPC UA range string, a Python slice, or a tuple of slices. A list supplies one range per target.

None

translateBrowsePaths

translateBrowsePaths(request)

Server-side translate browse paths to node ids.

Parameters:

Name Type Description Default
request Any

A TranslateBrowsePathsToNodeIdsRequest instance.

required

Returns:

Type Description
MaybeAwaitable[Any]

The corresponding response.

findDataType

findDataType(nodeId)

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

Parameters:

Name Type Description Default
nodeId NodeIdLike

The DataType node id to look up.

required

Returns:

Type Description
MaybeAwaitable[Any]

Python type or DataType metadata for the requested NodeId.

browse

browse(
    target,
    *,
    maxReferences=0,
    direction=ns0.datatypes.BrowseDirection.FORWARD,
    reftype=ns0.reftypes.HierarchicalReferences,
    refsubtypes=True,
    nodeClassMask=ns0.datatypes.NodeClass.UNSPECIFIED,
    resultMask=ns0.datatypes.BrowseResultMask(0)
)

Browse one node's references.

Parameters:

Name Type Description Default
target NodeIdLike

The node to browse from.

required
maxReferences int

Cap on returned references. 0 means no cap, and any cap can leave a continuation point for browseNext.

0
direction BrowseDirection

FORWARD, INVERSE, or BOTH.

FORWARD
reftype NodeIdLike

Only follow this ReferenceType. Defaults to HierarchicalReferences.

HierarchicalReferences
refsubtypes bool

Also follow subtypes of reftype.

True
nodeClassMask NodeClass

Only return nodes of these NodeClasses. UNSPECIFIED returns all.

UNSPECIFIED
resultMask BrowseResultMask

Which reference fields to fill in. 0 returns only the target NodeIds.

BrowseResultMask(0)

Returns:

Type Description
MaybeAwaitable[Any]

The BrowseResult, holding the references and a continuation point

MaybeAwaitable[Any]

when the result was truncated.

Raises:

Type Description
StatusCodeError

The Browse call failed.

browseNext

browseNext(releaseContinuationPoint, continuationPoint)

Continue a truncated browse.

Parameters:

Name Type Description Default
releaseContinuationPoint bool

Discard the continuation point instead of fetching the next batch.

required
continuationPoint Any

The continuation point from the previous result.

required

Returns:

Type Description
MaybeAwaitable[Any]

The next BrowseResult.

Raises:

Type Description
StatusCodeError

The BrowseNext call failed, for example because the continuation point expired.

browseRecursive

browseRecursive(
    target,
    *,
    direction=ns0.datatypes.BrowseDirection.FORWARD,
    reftype=ns0.reftypes.HierarchicalReferences,
    refsubtypes=True,
    nodeClassMask=ns0.datatypes.NodeClass.UNSPECIFIED,
    resultMask=ns0.datatypes.BrowseResultMask(0)
)

Browse a whole subtree in one native traversal.

The arguments match browse, minus maxReferences, and the traversal is depth-unbounded, so scope it with reftype and nodeClassMask on a large address space.

Returns:

Type Description
MaybeAwaitable[Any]

Every reachable node as a flat list of ExpandedNodeId values.

Raises:

Type Description
StatusCodeError

The traversal failed.

translateBrowsePathsToNodeIds

translateBrowsePathsToNodeIds(browsePath)

Resolve full BrowsePaths to NodeIds.

The raw service form. translateBrowsePaths is the convenient wrapper.

Parameters:

Name Type Description Default
browsePath Any

One BrowsePath or a list of them.

required

Returns:

Type Description
MaybeAwaitable[Any]

One BrowsePathResult per requested path, each with its own

MaybeAwaitable[Any]

StatusCode, so unresolved paths do not fail the whole call.

Raises:

Type Description
StatusCodeError

The service call itself failed.

browseSimplifiedBrowsePaths

browseSimplifiedBrowsePaths(origin, browsePath)

Resolve a BrowseName chain from one node, following any hierarchy.

Simpler than a full BrowsePath: every step is just a BrowseName, matched against hierarchical references.

Parameters:

Name Type Description Default
origin NodeIdLike

The node to start from.

required
browsePath Any

The QualifiedName chain to follow.

required

Returns:

Type Description
MaybeAwaitable[Any]

One BrowsePathResult per requested path.

Raises:

Type Description
StatusCodeError

The service call itself failed.

forEachChildNode

forEachChildNode(nodeId, callback)

Visit every reference of one node without building a result list.

The cheapest way to walk a node's references, because nothing is allocated per reference. The callback runs on the server's event loop while the node is locked, so it must not block or call back into the server.

Parameters:

Name Type Description Default
nodeId NodeIdLike

The node whose references are visited.

required
callback Callable[[NodeId, bool, NodeId], Any]

Called as (childId, isInverse, referenceTypeId) for each reference.

required

registerDiscovery

registerDiscovery(url, semaphoreFilePath=None)

Register this server at a Discovery Server (LDS).

Parameters:

Name Type Description Default
url str

The LDS endpoint URL, e.g. "opc.tcp://localhost:4840".

required
semaphoreFilePath str | Path | None

Path to a semaphore file used to coordinate shutdown across several instances. None sends an empty path.

None

Raises:

Type Description
StatusCodeError

The registration failed.

deregisterDiscovery

deregisterDiscovery(url)

Deregister this server from a Discovery Server (LDS).

Should be called once during server shutdown.

Parameters:

Name Type Description Default
url str

The LDS endpoint URL that was passed to registerDiscovery.

required

Raises:

Type Description
StatusCodeError

The deregistration failed.

setRegisterServerCallback

setRegisterServerCallback(callback)

Install / remove the callback invoked when another server registers with this LDS.

The callback receives a single dict argument with keys: server_uri, product_uri, discovery_urls (list of str), last_discovery_timestamp.

Pass None to remove the callback.

setServerOnNetworkCallback

setServerOnNetworkCallback(callback)

Install / remove the callback invoked when another server is detected on the network (via mDNS).

The callback receives a single dict argument with keys: record_id, server_name, discovery_url, server_capabilities (list of str), last_announce_time, next_announce_time, last_online_time, is_server_announce (bool), is_txt_received (bool).

Pass None to remove the callback. Requires UA_ENABLE_DISCOVERY_MULTICAST in the open62541 build.

createDataChangeMonitoredItem

createDataChangeMonitoredItem(
    nodeId,
    callback,
    *,
    timestamps=None,
    context=None,
    samplingInterval=0.0,
    monitoringMode=None
)

Create a local DataChange o6.subscription.MonitoredItem.

callback is called as::

callback(monitoredItemId, nodeId, attributeId, data_value, context)

It may be a regular function or an async def.

deleteMonitoredItem

deleteMonitoredItem(monitoredItemId)

Delete a local o6.subscription.MonitoredItem by its numeric ID.

createEventMonitoredItem

createEventMonitoredItem(
    nodeId,
    callback,
    *,
    context=None,
    selectClauses=None,
    whereClause=None
)

Create a local Event o6.subscription.MonitoredItem on nodeId.

callback(monitoredItemId, event_fields, context) where event_fields is a dict {QualifiedName: value}.

createEventMonitoredItemEx

createEventMonitoredItemEx(
    nodeId,
    callback,
    *,
    monitoringMode=None,
    clientHandle=0,
    samplingInterval=0.0,
    eventFilter=None,
    queueSize=0,
    discardOldest=True,
    context=None
)

Extended version of createEventMonitoredItem with full control.

Uses a MonitoredItemCreateRequest (attributeId = EventNotifier). Returns the monitoredItemId.

addRepeatedCallback

addRepeatedCallback(callback, intervalMs)

Register callback to be called every intervalMs milliseconds.

Returns an opaque integer callback ID that can be passed to changeRepeatedCallbackInterval or removeCallback.

changeRepeatedCallbackInterval

changeRepeatedCallbackInterval(callbackId, intervalMs)

Change the interval of an existing repeated callback.

removeCallback

removeCallback(callbackId)

Remove a repeated callback by ID.