asyncua.client package#

Subpackages#

Submodules#

asyncua.client.client module#

class asyncua.client.client.Client(url: str, timeout: float = 4, watchdog_intervall: float = 1.0)#

Bases: object

High level client to connect to an OPC-UA server. This class makes it easy to connect and browse address space. It attempts to expose as much functionality as possible but if you want more flexibility it is possible and advised to use UaClient object, available as self.uaclient which offers the raw OPC-UA services interface.

async activate_session(username: str | None = None, password: str | None = None, certificate: Certificate | None = None) ActivateSessionResult#

Activate session using either username and password or private_key

async browse_nodes(nodes: Iterable[Node]) List[Tuple[Node, BrowseResult]]#

Browses multiple nodes in one ua call returns a List of Tuples(Node, BrowseResult)

certificate_validator: Callable[[Certificate, ApplicationDescription], Awaitable[None]] | None#

hook to validate a certificate, raises a ServiceError when not valid

async check_connection() None#
async close_secure_channel()#
async close_session() None#

Close session

async connect() None#

High level method Connect, create and activate session

async connect_and_find_servers() List[ApplicationDescription]#

Connect, ask server for a list of known servers, and disconnect

async connect_and_find_servers_on_network() List[FindServersOnNetworkResult]#

Connect, ask server for a list of known servers on network, and disconnect

async connect_and_get_server_endpoints() List[EndpointDescription]#

Connect, ask server for endpoints, and disconnect

async connect_sessionless() None#

High level method Connect without a session

async connect_socket() None#

connect to socket defined in url

async create_session() CreateSessionResult#

send a CreateSessionRequest to server with reasonable parameters. If you want to modify settings look at code of these methods and make your own

async create_subscription(period: CreateSubscriptionParameters | float, handler: DataChangeNotificationHandler | EventNotificationHandler | StatusChangeNotificationHandler, publishing: bool = True) Subscription#

Create a subscription. Returns a Subscription object which allows to subscribe to events or data changes on server. :param period: Either a publishing interval in milliseconds or a CreateSubscriptionParameters instance.

The second option should be used, if the asyncua-server has problems with the default options.

Parameters:

handler – Class instance with data_change and/or event methods (see SubHandler base class for details). Remember not to block the main event loop inside the handler methods.

async delete_nodes(nodes: Iterable[Node], recursive=False) Tuple[List[Node], List[StatusCode]]#
async delete_subscriptions(subscription_ids: Iterable[int]) List[StatusCode]#

Deletes the provided list of subscription_ids

async disconnect() None#

High level method Close session, secure channel and socket

async disconnect_sessionless() None#

High level method Close secure channel and socket

disconnect_socket() None#
async export_xml(nodes, path, export_values: bool = False) None#

Export defined nodes to xml :param export_values: exports values from variants

static find_endpoint(endpoints: Iterable[EndpointDescription], security_mode: MessageSecurityMode, policy_uri: str) EndpointDescription#

Find endpoint with required security mode and policy URI

async find_servers(uris: Iterable[str] | None = None) List[ApplicationDescription]#

send a FindServer request to the server. The answer should be a list of servers the server knows about A list of uris can be provided, only server having matching uris will be returned

async find_servers_on_network() List[FindServersOnNetworkResult]#
async get_endpoints() List[EndpointDescription]#

Get a list of OPC-UA endpoints.

get_keepalive_count(period: float) int#

We request the server to send a Keepalive notification when no notification has been received for 75% of the session lifetime. This is especially useful to keep the session up when self.session_timeout < self.secure_channel_timeout.

Part4 5.13.2: If the requested value is 0, the Server shall revise with the smallest supported keep-alive count.

async get_namespace_array() List[str]#
async get_namespace_index(uri: str) int#
get_node(nodeid: Node | NodeId | str | int) Node#

Get node using NodeId object or a string representing a NodeId.

get_objects_node() Node#
get_root_node() Node#
get_server_node() Node#
get_subscription_revised_params(params: CreateSubscriptionParameters, results: CreateSubscriptionResult) ModifySubscriptionParameters | None#
async get_values(nodes: Iterable[Node]) List[Any]#

Read the value of multiple nodes in one ua call.

async import_xml(path=None, xmlstring=None, strict_mode=True) List[NodeId]#

Import nodes defined in xml

async load_client_certificate(path: str, extension: str | None = None) None#

load our certificate from file, either pem or der

async load_data_type_definitions(node: Node | None = None, overwrite_existing: bool = False) Dict[str, Type]#

Load custom types (custom structures/extension objects) definition from server Generate Python classes for custom structures/extension objects defined in server These classes will be available in ua module

async load_enums() Dict[str, Type]#

generate Python enums for custom enums on server. This enums will be available in ua module

async load_private_key(path: Path, password: str | bytes | None = None, extension: str | None = None) None#

Load user private key. This is used for authenticating using certificate

async load_type_definitions(nodes=None)#

Load custom types (custom structures/extension objects) definition from server Generate Python classes for custom structures/extension objects defined in server These classes will available in ua module WARNING: protocol has changed in 1.04. use load_data_type_definitions()

async open_secure_channel(renew: bool = False) None#

Open secure channel, if renew is True, renew channel

async read_attributes(nodes: Iterable[Node], attr: AttributeIds = AttributeIds.Value) List[DataValue]#

Read the attributes of multiple nodes.

async read_values(nodes: Iterable[Node]) List[Any]#

Read the value of multiple nodes in one ua call.

async register_namespace(uri: str) int#

Register a new namespace. Nodes should in custom namespace, not 0. This method is mainly implemented for symmetry with server

async register_nodes(nodes: Iterable[Node]) List[Node]#

Register nodes for faster read and write access (if supported by server) Rmw: This call modifies the nodeid of the nodes, the original nodeid is available as node.basenodeid

async register_server(server: Server, discovery_configuration: DiscoveryConfiguration | None = None) None#

register a server to discovery server if discovery_configuration is provided, the newer register_server2 service call is used

async send_hello() None#

Send OPC-UA hello to server

server_policy_id(token_type: UserTokenType, default: str) str#

Find PolicyId of server’s UserTokenPolicy by token_type. Return default if there’s no matching UserTokenPolicy.

server_policy_uri(token_type: UserTokenType) str#

Find SecurityPolicyUri of server’s UserTokenPolicy by token_type. If SecurityPolicyUri is empty, use default SecurityPolicyUri of the endpoint

property server_url#

Return the server URL with stripped credentials

if self.strip_url_credentials is True. Disabling this is not recommended for security reasons.

set_locale(locale: Sequence[str]) None#

Sets the preferred locales of the client, the server chooses which locale he can provide. Normally the first matching locale in the list will be chosen, by the server. Call this before connect()

set_password(pwd: str) None#

Set user password for the connection. initial password from the URL will be overwritten

async set_security(policy: Type[SecurityPolicy], certificate: str | CertProperties | bytes, private_key: str | CertProperties | bytes, private_key_password: str | bytes | None = None, server_certificate: str | CertProperties | bytes | None = None, mode: MessageSecurityMode = MessageSecurityMode.SignAndEncrypt) None#

Set SecureConnection mode. Call this before connect()

async set_security_string(string: str) None#

Set SecureConnection mode. :param string: Mode format Policy,Mode,certificate,private_key[,server_private_key] where: - Policy is Basic128Rsa15, Basic256 or Basic256Sha256 - Mode is Sign or SignAndEncrypt - certificate and server_private_key are paths to .pem or .der files - private_key may be a path to a .pem or .der file or a conjunction of path::password where

password is the private key password.

Call this before connect()

set_user(username: str) None#

Set user name for the connection. initial user from the URL will be overwritten

async set_values(nodes: Iterable[Node], values: Iterable[Any], raise_on_partial_error: bool = True) List[StatusCode]#

Write values to multiple nodes in one ua call

strip_url_credentials = True#
async translate_browsepaths(starting_node: NodeId, relative_paths: Iterable[RelativePath | str]) List[BrowsePathResult]#
async unregister_nodes(nodes: Iterable[Node]) None#

Unregister nodes

async unregister_server(server: Server, discovery_configuration: DiscoveryConfiguration | None = None) None#

register a server to discovery server if discovery_configuration is provided, the newer register_server2 service call is used

async write_values(nodes: Iterable[Node], values: Iterable[Any], raise_on_partial_error: bool = True) List[StatusCode]#

Write values to multiple nodes in one ua call

asyncua.client.ua_client module#

Low level binary client

class asyncua.client.ua_client.UASocketProtocol(timeout: float = 1, security_policy: ~asyncua.ua.uaprotocol_hand.SecurityPolicy = <asyncua.ua.uaprotocol_hand.SecurityPolicy object>, limits: ~asyncua.common.connection.TransportLimits | None = None)#

Bases: Protocol

Handle socket connection and send ua messages. Timeout is the timeout used while waiting for an ua answer from server.

CLOSED = 'closed'#
INITIALIZED = 'initialized'#
OPEN = 'open'#
check_answer(data, context)#
async close_secure_channel()#

Close secure channel. It seems to trigger a shutdown of socket in most servers, so be prepared to reconnect. OPC UA specs Part 6, 7.1.4 say that Server does not send a CloseSecureChannel response and should just close socket.

connection_lost(exc: Exception | None)#

Called when the connection is lost or closed.

The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed).

connection_made(transport: Transport)#

Called when a connection is made.

The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called.

data_received(data: bytes)#

Called when some data is received.

The argument is a bytes object.

disconnect_socket()#
async open_secure_channel(params)#
async send_hello(url, max_messagesize: int = 0, max_chunkcount: int = 0)#
async send_request(request, timeout: float | None = None, message_type=b'MSG')#

Send a request to the server. Timeout is the timeout written in ua header. Returns response object if no callback is provided.

class asyncua.client.ua_client.UaClient(timeout: float = 1.0)#

Bases: AbstractSession

low level OPC-UA client.

It implements (almost) all methods defined in asyncua spec taking in argument the structures defined in asyncua spec.

In this Python implementation most of the structures are defined in uaprotocol_auto.py and uaprotocol_hand.py available under asyncua.ua

async activate_session(parameters)#
async add_nodes(nodestoadd)#

https://reference.opcfoundation.org/Core/Part4/v104/5.7.2/

This Service is used to add one or more Nodes into the AddressSpace hierarchy. Using this Service, each Node is added as the TargetNode of a HierarchicalReference to ensure that the AddressSpace is fully connected and that the Node is added as a child within the AddressSpace hierarchy (see OPC 10000-3).

async add_references(refs)#

https://reference.opcfoundation.org/Core/Part4/v104/5.7.3/

This Service is used to add one or more References to one or more Nodes. The NodeClass is an input parameter that is used to validate that the Reference to be added matches the NodeClass of the TargetNode. This parameter is not validated if the Reference refers to a TargetNode in a remote Server.

async browse(parameters)#

https://reference.opcfoundation.org/Core/Part4/v104/5.8.2/

This Service is used to discover the References of a specified Node. The browse can be further limited by the use of a View. This Browse Service also supports a primitive filtering capability.

async browse_next(parameters)#

https://reference.opcfoundation.org/Core/Part4/v104/5.8.3/

This Service is used to request the next set of Browse or BrowseNext response information that is too large to be sent in a single response. “Too large” in this context means that the Server is not able to return a larger response or that the number of results to return exceeds the maximum number of results to return that was specified by the Client in the original Browse request. The BrowseNext shall be submitted on the same Session that was used to submit the Browse or BrowseNext that is being continued.

async call(methodstocall)#

https://reference.opcfoundation.org/Core/Part4/v104/5.11.2/

This Service is used to call (invoke) a list of Methods.

async close_secure_channel()#

close secure channel. It seems to trigger a shutdown of socket in most servers, so be prepared to reconnect

async close_session(delete_subscriptions)#
async connect_socket(host: str, port: int)#

Connect to server socket.

async create_monitored_items(params)#

https://reference.opcfoundation.org/Core/Part4/v104/5.12.2/

This Service is used to create and add one or more MonitoredItems to a Subscription.

A MonitoredItem is deleted automatically by the Server when the Subscription is deleted.

Deleting a MonitoredItem causes its entire set of triggered item links to be deleted, but has no effect on the MonitoredItems referenced by the triggered items.

async create_session(parameters)#
async create_subscription(params: CreateSubscriptionParameters, callback) CreateSubscriptionResult#

https://reference.opcfoundation.org/Core/Part4/v104/5.13.2/

This Service is used to create a Subscription.

Subscriptions monitor a set of MonitoredItems for Notifications and return them to the Client in response to Publish requests.

async delete_monitored_items(params)#

https://reference.opcfoundation.org/Core/Part4/v104/5.12.6/

This Service is used to remove one or more MonitoredItems of a Subscription. When a MonitoredItem is deleted, its triggered item links are also deleted.

async delete_nodes(params)#

https://reference.opcfoundation.org/Core/Part4/v104/5.7.4/

This Service is used to delete one or more Nodes from the AddressSpace.

async delete_references(refs)#

https://reference.opcfoundation.org/Core/Part4/v104/5.7.5/

This Service is used to delete one or more References of a Node.

async delete_subscriptions(subscription_ids)#

https://reference.opcfoundation.org/Core/Part4/v104/5.13.8/

This Service is invoked to delete one or more Subscriptions that belong to the Client’s Session.

disconnect_socket()#
async find_servers(params)#
async find_servers_on_network(params)#
async get_endpoints(params)#
async history_read(params)#

https://reference.opcfoundation.org/Core/Part4/v104/5.10.3/

This Service is used to read historical values or Events of one or more Nodes. For constructed Attribute values whose elements are indexed, such as an array, this Service allows Clients to read the entire set of indexed values as a composite, to read individual elements or to read ranges of elements of the composite. Servers may make historical values available to Clients using this Service, although the historical values themselves are not visible in the AddressSpace.

async inform_subscriptions(status: StatusCode)#

Inform all current subscriptions with a status code. This calls the handler’s status_change_notification

async modify_monitored_items(params)#

https://reference.opcfoundation.org/Core/Part4/v104/5.12.3/

This Service is used to modify MonitoredItems of a Subscription. Changes to the MonitoredItem settings shall be applied immediately by the Server. They take effect as soon as practical but not later than twice the new revisedSamplingInterval.

async modify_subscription(params: ModifySubscriptionParameters) ModifySubscriptionResult#

https://reference.opcfoundation.org/Core/Part4/v104/5.13.3/

This Service is used to modify a Subscription.

async open_secure_channel(params)#
property pre_request_hook: Callable[[], Awaitable[None]] | None#
async publish(acks: List[SubscriptionAcknowledgement]) PublishResponse#

Send a PublishRequest to the server.

async read(parameters)#

https://reference.opcfoundation.org/Core/Part4/v104/5.10.2/

This Service is used to read one or more Attributes of one or more Nodes. For constructed Attribute values whose elements are indexed, such as an array, this Service allows Clients to read the entire set of indexed values as a composite, to read individual elements or to read ranges of elements of the composite.

async read_attributes(nodeids, attr)#
async register_nodes(nodes)#

https://reference.opcfoundation.org/Core/Part4/v104/5.8.5/

A Server often has no direct access to the information that it manages. Variables or services might be in underlying systems where additional effort is required to establish a connection to these systems. The RegisterNodes Service can be used by Clients to register the Nodes that they know they will access repeatedly (e.g. Write, Call). It allows Servers to set up anything needed so that the access operations will be more efficient. Clients can expect performance improvements when using registered NodeIds, but the optimization measures are vendor-specific. For Variable Nodes Servers shall concentrate their optimization efforts on the Value Attribute.

async register_server(registered_server)#
async register_server2(params)#
async send_hello(url, max_messagesize: int = 0, max_chunkcount: int = 0)#
async set_monitoring_mode(params) List[StatusCode]#

Update the subscription monitoring mode

async set_publishing_mode(params) List[StatusCode]#

Update the subscription publishing mode

set_security(policy: SecurityPolicy)#
async transfer_subscriptions(params: TransferSubscriptionsParameters) List[TransferResult]#

https://reference.opcfoundation.org/Core/Part4/v104/5.13.7/

This Service is used to transfer a Subscription and its MonitoredItems from one Session to another. For example, a Client may need to reopen a Session and then transfer its Subscriptions to that Session. It may also be used by one Client to take over a Subscription from another Client by transferring the Subscription to its Session.

async translate_browsepaths_to_nodeids(browse_paths)#

https://reference.opcfoundation.org/Core/Part4/v104/5.8.4/

This Service is used to request that the Server translates one or more browse paths to NodeIds. Each browse path is constructed of a starting Node and a RelativePath. The specified starting Node identifies the Node from which the RelativePath is based. The RelativePath contains a sequence of ReferenceTypes and BrowseNames.

async unregister_nodes(nodes)#

https://reference.opcfoundation.org/Core/Part4/v104/5.8.6/

This Service is used to unregister NodeIds that have been obtained via the RegisterNodes service.

async unregister_server(registered_server)#
async unregister_server2(params)#
async update_subscription(params: ModifySubscriptionParameters) ModifySubscriptionResult#
async write(params)#

https://reference.opcfoundation.org/Core/Part4/v104/5.10.4/

This Service is used to write values to one or more Attributes of one or more Nodes. For constructed Attribute values whose elements are indexed, such as an array, this Service allows Clients to write the entire set of indexed values as a composite, to write individual elements or to write ranges of elements of the composite.

async write_attributes(nodeids, datavalues, attributeid=AttributeIds.Value)#

Set an attribute of multiple nodes datavalue is a ua.DataValue object

asyncua.client.ua_file module#

class asyncua.client.ua_file.UaFile(file_node, open_mode)#

Bases: object

async close()#

close file method

async get_size()#

gets size of file

async open(open_mode)#

open file method

async read()#

reads file contents

async write(data: bytes)#

writes file contents

asyncua.client.ua_file_transfer module#

Low level implementation of OPC UA File Transfer. This module contains the mandatory functionality specified by the OPC Foundation.

See also: OPC 10000-5: OPC Unified Architecture V1.04 Part 5: Information Model - Annex C (normative) File Transfer https://reference.opcfoundation.org/Core/docs/Part5/C.1/

class asyncua.client.ua_file_transfer.UaDirectory(directory_node)#

Bases: object

Provides the functionality to work with “C.3 File System”.

async create_directory(directory_name: str) NodeId#

CreateDirectory is used to create a new FileDirectoryType Object organized by this Object. :param directory_name: The name of the directory to create. The name is used for the BrowseName and DisplayName of the directory object and also for the directory in the file system. For the BrowseName, the directoryName is used for the name part of the QualifiedName. The namespace index is Server specific. For the DisplayName, the directoryName is used for the text part of the LocalizedText. The locale part is Server specific. :return: The NodeId of the created directory Object.

async create_file(file_name: str, request_file_open: bool) Tuple[NodeId, int]#

CreateFile is used to create a new FileType Object organized by this Object. The created file can be written using the Write Method of the FileType. :param file_name: The name of the file to create. The name is used for the BrowseName and DisplayName of the file object and also for the file in the file system. For the BrowseName, the fileName is used for the name part of the QualifiedName. The namespace index is Server specific. For the DisplayName, the fileName is used for the text part of the LocalizedText. The locale part is Server specific. :param request_file_open: Flag indicating if the new file should be opened with the Write and Read bits set in the open mode after the creation of the file. If the flag is set to True, the file is created and opened for writing. If the flag is set to False, the file is just created. :return: The NodeId of the created file Object. The fileHandle is returned if the requestFileOpen is set to True. The fileNodeId and the fileHandle can be used to access the new file through the FileType Object representing the new file. If requestFileOpen is set to False, the returned value shall be 0 and shall be ignored by the caller.

async delete(object_to_delete: NodeId) None#

Delete is used to delete a file or directory organized by this Object. :param object_to_delete: The NodeId of the file or directory to delete. In the case of a directory, all file and directory Objects below the directory to delete are deleted recursively.

async move_or_copy(object_to_move_or_copy: NodeId, target_directory: NodeId, create_copy: bool, new_name: str) NodeId#

MoveOrCopy is used to move or copy a file or directory organized by this Object to another directory or to rename a file or directory. :param object_to_move_or_copy: The NodeId of the file or directory to move or copy. :param target_directory: The NodeId of the target directory of the move or copy command. If the file or directory is just renamed, the targetDirectory matches the ObjectId passed to the method call. :param create_copy: A flag indicating if a copy of the file or directory should be created at the target directory. :param new_name: The new name of the file or directory in the new location. If the string is empty, the name is unchanged. :return: The NodeId of the moved or copied object. Even if the Object is moved, the Server may return a new NodeId.

class asyncua.client.ua_file_transfer.UaFile(file_node: Node, open_mode: OpenFileMode = 1)#

Bases: object

Provides the functionality to work with “C.2 FileType”.

async close() None#

Close is used to close a file represented by a FileType. When a client closes a file the handle becomes invalid.

async get_open_count()#

OpenCount indicates the number of currently valid file handles on the file. :return: Amount of currently valid file handles on the file

async get_position() int#

GetPosition is used to provide the current position of the file handle. :return: The position of the fileHandle in the file. If a Read or Write is called it starts at that position.

async get_size() int#

Size defines the size of the file in Bytes. When a file is opened for write the size might not be accurate. :return: The size of the file in Bytes.

async get_user_writable() bool#

UserWritable indicates whether the file is writable taking user access rights into account. The Property does not take into account whether the file is currently opened for writing by another client and thus currently locked and not writable by others. :return: Indicates whether the file is writable taking user access rights into account

async get_writable() bool#

Writable indicates whether the file is writable. It does not take any user access rights into account, i.e. although the file is writable this may be restricted to a certain user / user group. The Property does not take into account whether the file is currently opened for writing by another client and thus currently locked and not writable by others. :return:

async open(open_mode: OpenFileMode | None = None) None#

Open is used to open a file represented by an Object of FileType. The open mode of OPC UA differs significantly from the python build-in functionality. => See the OPC UA specification for more information. :param open_mode: Open mode defined in C.2.1. :return: The file handle.

async read() bytes#

Read is used to read a part of the file starting from the current file position. The file position is advanced by the number of bytes read. :return: Contains the returned data of the file. If the ByteString is empty it indicates that the end of the file is reached.

async set_position(position: int) None#

SetPosition is used to set the current position of the file handle. :param position: The position to be set for the fileHandle in the file. If a Read or Write is called it starts at that position. If the position is higher than the file size the position is set to the end of the file.

async write(data: bytes) None#

Write is used to write a part of the file starting from the current file position. The file position is advanced by the number of bytes written. :param data: Contains the data to be written at the position of the file. It is server-dependent whether the written data are persistently stored if the session is ended without calling the Close Method with the fileHandle. Writing an empty or null ByteString returns a Good result code without any effect on the file.