QOpcUaClient#

QOpcUaClient allows interaction with an OPC UA server. More

Inheritance diagram of PySide6.QtOpcUa.QOpcUaClient

Synopsis#

Functions#

Signals#

Detailed Description#

QOpcUaClient#

QOpcUaClient implements basic client capabilities to communicate with OPC UA enabled devices and applications. This includes querying a discovery server for known servers, requesting a list of endpoints from a server, connecting and disconnecting.

After successfully connecting to a server, QOpcUaClient allows getting QOpcUaNode objects which enable further interaction with nodes on the OPC UA server. For operations that concern multiple nodes, QOpcUaClient offers an API which supports reading multiple attributes of multiple nodes in a single request to the server.

QOpcUaClient also keeps a local copy of the server’s namespace array which is created after a successful connect. This information can be queried or updated while the connection lasts. The copy of the namespace array is also used for the resolution of expanded node ids and the creation of qualified names from a namespace URI.

Addressing Nodes#

For an introduction to nodes and node ids, see QOpcUaNode .

Usage#

Create a QOpcUaClient using QOpcUaProvider , request a list of endpoints from the server using requestEndpoints and call connectToEndpoint() to connect to one of the available endpoints. After the connection is established, a QOpcUaNode object for the root node is requested.

QOpcUaProvider provider;
if (provider.availableBackends().isEmpty())
    return;
QOpcUaClient *client = provider.createClient(provider.availableBackends()[0]);
if (!client)
    return;
// Connect to the stateChanged signal. Compatible slots of QObjects can be used instead of a lambda.
QObject::connect(client, &QOpcUaClient::stateChanged, [client](QOpcUaClient::ClientState state) {
    qDebug() << "Client state changed:" << state;
    if (state == QOpcUaClient::ClientState::Connected) {
        QOpcUaNode *node = client->node("ns=0;i=84");
        if (node)
            qDebug() << "A node object has been created";
    }
});

QObject::connect(client, &QOpcUaClient::endpointsRequestFinished,
                 [client](QList<QOpcUaEndpointDescription> endpoints) {
    qDebug() << "Endpoints returned:" << endpoints.count();
    if (endpoints.size())
        client->connectToEndpoint(endpoints.first()); // Connect to the first endpoint in the list
});

client->requestEndpoints(QUrl("opc.tcp://127.0.0.1:4840")); // Request a list of endpoints from the server
class PySide6.QtOpcUa.QOpcUaClient#
PySide6.QtOpcUa.QOpcUaClient.ClientState#

This enum type specifies the connection state of the client.

Constant

Description

QOpcUaClient.Disconnected

The client is not connected to a server.

QOpcUaClient.Connecting

The client is currently connecting to a server.

QOpcUaClient.Connected

The client is connected to a server.

QOpcUaClient.Closing

The client has been connected and requests a disconnect from the server.

PySide6.QtOpcUa.QOpcUaClient.ClientError#

This enum type specifies the current error state of the client.

Constant

Description

QOpcUaClient.NoError

No error occurred.

QOpcUaClient.InvalidUrl

The url to connect to has been wrongly specified or a connection to this url failed.

QOpcUaClient.AccessDenied

An attempt to connect to a server using username/password failed due to wrong credentials.

QOpcUaClient.ConnectionError

An error occurred with the connection.

QOpcUaClient.UnknownError

An unknown error occurred.

QOpcUaClient.UnsupportedAuthenticationInformation

The given type or data of authentication information is not supported.

PySide6.QtOpcUa.QOpcUaClient.addNode(nodeToAdd)#
Parameters

nodeToAddPySide6.QtOpcUa.QOpcUaAddNodeItem

Return type

bool

Adds the node described by nodeToAdd on the server.

Returns true if the asynchronous call has been successfully dispatched.

The success of the operation is returned in the addNodeFinished() signal.

The following example code adds new a Variable node on the server:

QOpcUaNodeCreationAttributes attributes;
attributes.setDisplayName(QOpcUaLocalizedText("en", "My new Variable node"));
attributes.setDescription(QOpcUaLocalizedText("en", "A node which has been added at runtime"));
attributes.setValue(23.0, QOpcUa::Types::Double);
attributes.setDataTypeId(QOpcUa::ns0ID(QOpcUa::NodeIds::Namespace0::Double));
attributes.setValueRank(-2); // Scalar or array
attributes.setAccessLevel(QOpcUa::AccessLevelBit::CurrentRead);
attributes.setUserAccessLevel(QOpcUa::AccessLevelBit::CurrentRead);

QOpcUaAddNodeItem item;
item.setParentNodeId(QOpcUaExpandedNodeId("ns=3;s=TestFolder"));
item.setReferenceTypeId(QOpcUa::nodeIdFromReferenceType(QOpcUa::ReferenceTypeId::Organizes));
item.setRequestedNewNodeId(QOpcUaExpandedNodeId("ns=3;s=MyNewVariableNode"));
item.setBrowseName(QOpcUaQualifiedName(3, "MyNewVariableNode"));
item.setNodeClass(QOpcUa::NodeClass::Variable);
item.setNodeAttributes(attributes);

m_client->addNode(item);
PySide6.QtOpcUa.QOpcUaClient.addNodeFinished(requestedNodeId, assignedNodeId, statusCode)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.addReference(referenceToAdd)#
Parameters

referenceToAddPySide6.QtOpcUa.QOpcUaAddReferenceItem

Return type

bool

Adds the reference described by referenceToAdd to the server.

Returns true if the asynchronous call has been successfully dispatched.

The success of the operation is returned in the addReferenceFinished() signal.

The following example code adds a reference to a node to the “Objects” folder:

QOpcUaAddReferenceItem item;
item.setSourceNodeId(QOpcUa::namespace0Id(QOpcUa::NodeIds::Namespace0::ObjectsFolder));
item.setReferenceTypeId(QOpcUa::nodeIdFromInteger(0, static_cast<quint32>(QOpcUa::ReferenceTypeId::Organizes)));
item.setIsForwardReference(true);
item.setTargetNodeId(QOpcUaExpandedNodeId("ns=3;s=MyNewVariableNode"));
item.setTargetNodeClass(QOpcUa::NodeClass::Variable);

m_client->addReference(item);
PySide6.QtOpcUa.QOpcUaClient.addReferenceFinished(sourceNodeId, referenceTypeId, targetNodeId, isForwardReference, statusCode)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.applicationIdentity()#
Return type

PySide6.QtOpcUa.QOpcUaApplicationIdentity

Returns the application identity of this QOpcUaClient instance.

PySide6.QtOpcUa.QOpcUaClient.authenticationInformation()#
Return type

PySide6.QtOpcUa.QOpcUaAuthenticationInformation

Returns the current authentication information.

PySide6.QtOpcUa.QOpcUaClient.backend()#
Return type

str

Returns the name of the backend used by this instance of QOpcUaClient , e.g. “open62541”.

PySide6.QtOpcUa.QOpcUaClient.connectError(errorState)#
Parameters

errorStatePySide6.QtOpcUa.QOpcUaErrorState

PySide6.QtOpcUa.QOpcUaClient.connectToEndpoint(endpoint)#
Parameters

endpointPySide6.QtOpcUa.QOpcUaEndpointDescription

Connects to the OPC UA endpoint given in endpoint.

QEndpointDescription endpointDescription;
...
client->connectToEndpoint(endpointDescription);

A list of available endpoints is usually obtained by calling requestEndpoints() .

If the endpoint requires username authentication, at least a user name must be set in QOpcUaAuthenticationInformation . Calling this function before setting an authentication information will use the anonymous authentication.

QOpcUaAuthenticationInformation authInfo;
authInfo.setUsernameAuthentication("user", "password");

client->setAuthenticationInformation(authInfo);
PySide6.QtOpcUa.QOpcUaClient.connected()#
PySide6.QtOpcUa.QOpcUaClient.deleteNode(nodeId[, deleteTargetReferences=true])#
Parameters
  • nodeId – str

  • deleteTargetReferences – bool

Return type

bool

Deletes the node with node id nodeId from the server. If deleteTargetReferences is false, only the references with source node nodeId are deleted. If deleteTargetReferences is true, references with nodeId as target are deleted too.

Returns true if the asynchronous call has been successfully dispatched.

The success of the operation is returned in the deleteNodeFinished() signal.

The following example code deletes a node and all references to it from the server:

m_client->deleteNode(QOpcUaExpandedNodeId("ns=3;s=MyNewVariableNode"), true);
PySide6.QtOpcUa.QOpcUaClient.deleteNodeFinished(nodeId, statusCode)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.deleteReference(referenceToDelete)#
Parameters

referenceToDeletePySide6.QtOpcUa.QOpcUaDeleteReferenceItem

Return type

bool

Deletes the reference described by referenceToDelete from the server.

Returns true if the asynchronous call has been successfully dispatched.

The success of the operation is returned in the deleteReferenceFinished() signal.

The following example code deletes a reference to a node from the “Objects” folder:

QOpcUaDeleteReferenceItem item;
item.setSourceNodeId(QOpcUa::namespace0Id(QOpcUa::NodeIds::Namespace0::ObjectsFolder));
item.setReferenceTypeId(QOpcUa::nodeIdFromInteger(0, static_cast<quint32>(QOpcUa::ReferenceTypeId::Organizes)));
item.setIsForwardReference(true);
item.setTargetNodeId(QOpcUaExpandedNodeId("ns=3;s=MyNewVariableNode"));
item.setDeleteBidirectional(true);

m_client->deleteReference(item);
PySide6.QtOpcUa.QOpcUaClient.deleteReferenceFinished(sourceNodeId, referenceTypeId, targetNodeId, isForwardReference, statusCode)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.disconnectFromEndpoint()#

Disconnects from the server.

PySide6.QtOpcUa.QOpcUaClient.disconnected()#
PySide6.QtOpcUa.QOpcUaClient.endpoint()#
Return type

PySide6.QtOpcUa.QOpcUaEndpointDescription

Returns the description of the endpoint the client is currently connected to or was last connected to.

PySide6.QtOpcUa.QOpcUaClient.endpointsRequestFinished(endpoints, statusCode, requestUrl)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.error()#
Return type

ClientError

This property Specifies the current error state of the client..

PySide6.QtOpcUa.QOpcUaClient.errorChanged(error)#
Parameters

errorClientError

PySide6.QtOpcUa.QOpcUaClient.findServers(url[, localeIds=list()[, serverUris=list()]])#
Parameters
Return type

bool

Starts an asynchronous FindServers request to read a list of known servers from a server or discovery server at url. Returns true if the asynchronous call has been successfully dispatched.

localeIds can be used to select the language of the application names returned by the request. The format is specified in OPC-UA part 3, 8.4, for example “en” for English, or “de-DE” for German (Germany). If more than one locale ID is specified, the server uses the first match. If there is no match or localeIds is empty, a default locale is chosen by the server.

serverUris may be used to restrict the results to servers with a matching applicationUri in their application description. For example, finding the current URL of the server with the applicationUri “MyPLC”, the following call can be used:

client->findServers(discoveryServerUrl, QStringList(), QStringList({"MyPLC"}));

The results are returned in the findServersFinished() signal.

PySide6.QtOpcUa.QOpcUaClient.findServersFinished(servers, statusCode, requestUrl)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.isNamespaceAutoupdateEnabled()#
Return type

bool

Returns whether autoupdate of the namespace array is enabled.

PySide6.QtOpcUa.QOpcUaClient.namespaceArray()#
Return type

list of strings

Returns the cached value of the namespace array.

The value is only valid after the namespaceArrayUpdated() signal has been emitted.

PySide6.QtOpcUa.QOpcUaClient.namespaceArrayChanged(namespaces)#
Parameters

namespaces – list of strings

PySide6.QtOpcUa.QOpcUaClient.namespaceArrayUpdated(namespaces)#
Parameters

namespaces – list of strings

PySide6.QtOpcUa.QOpcUaClient.namespaceAutoupdateInterval()#
Return type

int

Returns the current revised update interval of the namespace array.

See also

setNamespaceAutoupdateInterval(int interval)

PySide6.QtOpcUa.QOpcUaClient.node(expandedNodeId)#
Parameters

expandedNodeIdPySide6.QtOpcUa.QOpcUaExpandedNodeId

Return type

PySide6.QtOpcUa.QOpcUaNode

Returns a QOpcUaNode object associated with the OPC UA node identified by expandedNodeId. The caller becomes owner of the node object.

If the node is not on the currently connected server, the namespace can’t be resolved, the node id is malformed or the client is not connected, nullptr is returned.

PySide6.QtOpcUa.QOpcUaClient.node(nodeId)
Parameters

nodeId – str

Return type

PySide6.QtOpcUa.QOpcUaNode

Returns a QOpcUaNode object associated with the OPC UA node identified by nodeId. The caller becomes owner of the node object.

If the client is not connected, nullptr is returned. The backends may also return nullptr for other error cases (for example for a malformed node id).

PySide6.QtOpcUa.QOpcUaClient.passwordForPrivateKeyRequired(keyFilePath, password, previousTryWasInvalid)#
Parameters
  • keyFilePath – str

  • password – str

  • previousTryWasInvalid – bool

PySide6.QtOpcUa.QOpcUaClient.pkiConfiguration()#
Return type

PySide6.QtOpcUa.QOpcUaPkiConfiguration

Returns the application’s PKI configuration of this QOpcUaClient instance.

PySide6.QtOpcUa.QOpcUaClient.qualifiedNameFromNamespaceUri(namespaceUri, name[, ok=None])#
Parameters
  • namespaceUri – str

  • name – str

  • ok – bool

Return type

PySide6.QtOpcUa.QOpcUaQualifiedName

Attempts to create a qualified name from namespaceUri and the name string name. Returns the resulting qualified name. An empty qualified name is returned if namespaceUri can’t be resolved.

ok will be set to true if the namespace URI resolution has been successful. If the namespace URI could not be resolved, ok will be set to false.

PySide6.QtOpcUa.QOpcUaClient.readHistoryData(request)#
Parameters

requestPySide6.QtOpcUa.QOpcUaHistoryReadRawRequest

Return type

PySide6.QtOpcUa.QOpcUaHistoryReadResponse

Starts a read raw history request for one or multiple nodes. This is the Qt OPC UA representation for the OPC UA ReadHistory service for reading raw historical data defined in OPC-UA part 4, 5.10.3 .

The start timestamp, end timestamp, number of values per node, returnBounds and nodes to read can be specified in a QOpcUaHistoryReadRawRequest .

Returns a QOpcUaHistoryReadResponse which contains the state of the request if the asynchronous request has been successfully dispatched. The results are returned in the UaStatusCode serviceResult) signal.

In the following example, the historic data from the last two days of two nodes are requested and printed. The result is limited to ten values per node.

QOpcUaHistoryReadRawRequest request(
            { QOpcUaReadItem("ns=1;s=myValue1"), QOpcUaReadItem("ns=1;s=myValue2") },
            QDateTime::currentDateTime(),
            QDateTime::currentDateTime().addDays(-2),
            10,
            true);

QOpcUaHistoryReadResponse *response = m_client->readHistoryData(request);
if (response) {
   QObject::connect(response, &QOpcUaHistoryReadResponse::readHistoryDataFinished,
                    [] (QList<QOpcUaHistoryData> results, QOpcUa::UaStatusCode serviceResult) {
                        if (serviceResult != QOpcUa::UaStatusCode::Good) {
                            qWarning() << "Fetching historical data failed with:" << serviceResult;
                        } else {
                            for (const auto& result : results) {
                                qInfo() << "NodeId:" << result.nodeId();
                                for (const auto &dataValue : result.result())
                                    qInfo() << "Value:" << dataValue.value();
                            }
                        }
                    });
}
PySide6.QtOpcUa.QOpcUaClient.readNodeAttributes(nodesToRead)#
Parameters

nodesToRead

Return type

bool

Starts a read of multiple attributes on different nodes. The node id, the attribute and an index range can be specified for every entry in nodesToRead.

Returns true if the asynchronous request has been successfully dispatched. The results are returned in the readNodeAttributesFinished() signal.

This read function offers an alternative way to read attributes of nodes which can be used for scenarios where the values of a large number of node attributes on different nodes must be read without requiring the other features of the QOpcUaNode based API like monitoring for value changes. All read items in the request are sent to the server in a single request and are answered in a single response which generates a single readNodeAttributesFinished() signal. This reduces the network overhead and the number of signal slot connections if many different nodes are involved.

In the following example, the display name attribute and the two index ranges “0:2” and “5:7” of the value attribute of the same node and the entire value attribute of a second node are read using a single service call:

QList<QOpcUaReadItem> request;
request.push_back(QOpcUaReadItem("ns=1;s=MyArrayNode",
                                 QOpcUa::NodeAttribute::DisplayName));
request.push_back(QOpcUaReadItem("ns=1;s=MyArrayNode",
                                 QOpcUa::NodeAttribute::Value, "0:2"));
request.push_back(QOpcUaReadItem("ns=1;s=MyArrayNode",
                                 QOpcUa::NodeAttribute::Value, "5:7"));
request.push_back(QOpcUaReadItem("ns=1;s=MyScalarNode));
m_client->readNodeAttributes(request);
PySide6.QtOpcUa.QOpcUaClient.readNodeAttributesFinished(results, serviceResult)#
Parameters
PySide6.QtOpcUa.QOpcUaClient.requestEndpoints(url)#
Parameters

urlPySide6.QtCore.QUrl

Return type

bool

Starts an asynchronous GetEndpoints request to read a list of available endpoints from the server at url. Returns true if the asynchronous call has been successfully dispatched.

The endpoint information is returned in the endpointsRequestFinished() signal.

PySide6.QtOpcUa.QOpcUaClient.resolveExpandedNodeId(expandedNodeId[, ok=None])#
Parameters
Return type

str

Attempts to resolve expandedNodeId to a node id string with numeric namespace index. Returns the node id string if the conversion was successful.

An empty string is returned if the namespace index can’t be resolved or if the identifier part of the expanded node id is malformed. ok will be set to true if the conversion has been successful. If the expanded node id could not be resolved, ok will be set to false.

PySide6.QtOpcUa.QOpcUaClient.setApplicationIdentity(identity)#
Parameters

identityPySide6.QtOpcUa.QOpcUaApplicationIdentity

Sets the application identity for this QOpcUaClient instance to identity.

PySide6.QtOpcUa.QOpcUaClient.setAuthenticationInformation(authenticationInformation)#
Parameters

authenticationInformationPySide6.QtOpcUa.QOpcUaAuthenticationInformation

Sets the authentication information of this client to authenticationInformation.

PySide6.QtOpcUa.QOpcUaClient.setNamespaceAutoupdate(isEnabled)#
Parameters

isEnabled – bool

Enables automatic update of the namespace table.

Enabling this will keep the local copy of the namespace table updated automatically. namespaceArrayUpdated will be emitted when the array changed. isEnabled determines if autoupdate is being enabled or disabled.

A subscription will be made on the node on the server to keep track of changes. In case a server does not support subscriptions this will not work and isNamespaceAutoupdateEnabled returns false.

PySide6.QtOpcUa.QOpcUaClient.setNamespaceAutoupdateInterval(interval)#
Parameters

interval – int

Sets the interval for the namespace table subscription.

The subscription may be revised by the server.

interval determines the interval to check for changes in milliseconds. The default is once per second.

See also

namespaceAutoupdateInterval() setNamespaceAutoupdate(bool isEnabled)

PySide6.QtOpcUa.QOpcUaClient.setPkiConfiguration(config)#
Parameters

configPySide6.QtOpcUa.QOpcUaPkiConfiguration

Sets the application PKI configuration for this QOpcUaClient instance to config.

PySide6.QtOpcUa.QOpcUaClient.state()#
Return type

ClientState

This property Specifies the current connection state of the client..

PySide6.QtOpcUa.QOpcUaClient.stateChanged(state)#
Parameters

stateClientState

PySide6.QtOpcUa.QOpcUaClient.supportedSecurityPolicies()#
Return type

list of strings

Returns the security policies supported by the used backend.

This function is currently available as a Technology Preview, and therefore the API and functionality provided by the function may be subject to change at any time without prior notice.

PySide6.QtOpcUa.QOpcUaClient.supportedUserTokenTypes()#
Return type

Returns the user token types supported by the used backend.

This function is currently available as a Technology Preview, and therefore the API and functionality provided by the function may be subject to change at any time without prior notice.

See also

TokenType

PySide6.QtOpcUa.QOpcUaClient.updateNamespaceArray()#
Return type

bool

Requests an update of the namespace array from the server. Returns true if the operation has been successfully dispatched.

The namespaceArrayUpdated() signal is emitted after the operation is finished.

PySide6.QtOpcUa.QOpcUaClient.writeNodeAttributes(nodesToWrite)#
Parameters

nodesToWrite

Return type

bool

Starts a write for multiple attributes on different nodes. The node id, the attribute, the value, the value type and an index range can be specified for every entry in nodesToWrite.

Returns true if the asynchronous request has been successfully dispatched. The results are returned in the writeNodeAttributesFinished() signal.

This write function offers an alternative way to write attributes of nodes which can be used for scenarios where the values of a large number of node attributes on different nodes must be written without requiring the other features of the QOpcUaNode based API like monitoring for value changes. All write items in the request are sent to the server in a single request and are answered in a single response which generates a single writeNodeAttributesFinished() signal. This reduces the network overhead and the number of signal slot connections if many different nodes are involved.

In the following example, the Values attributes of two different nodes are written in one call. The second node has an array value of which only the first two elements are overwritten:

QList<QOpcUaWriteItem> request;

request.append(QOpcUaWriteItem("ns=2;s=Demo.Static.Scalar.Double", QOpcUa::NodeAttribute::Value,
                                  23.0, QOpcUa::Types::Double));
request.append(QOpcUaWriteItem("ns=2;s=Demo.Static.Arrays.UInt32", QOpcUa::NodeAttribute::Value,
                                  QVariantList({0, 1, 2}), QOpcUa::Types::UInt32, "0:2"));

m_client->writeNodeAttributes(request);
PySide6.QtOpcUa.QOpcUaClient.writeNodeAttributesFinished(results, serviceResult)#
Parameters