QOpcUaClient Class

QOpcUaClient allows interaction with an OPC UA server. More...

Header: #include <QOpcUaClient>
qmake: QT += opcua
Inherits: QObject

Public Types

enum ClientError { NoError, InvalidUrl, AccessDenied, ConnectionError, UnknownError }
enum ClientState { Disconnected, Connecting, Connected, Closing }

Properties

  • error : const ClientError
  • state : const ClientState
  • 1 property inherited from QObject

Public Functions

virtual ~QOpcUaClient()
bool addNode(const QOpcUaAddNodeItem &nodeToAdd)
bool addReference(const QOpcUaAddReferenceItem &referenceToAdd)
QString backend() const
void connectToEndpoint(const QUrl &url)
bool deleteNode(const QString &nodeId, bool deleteTargetReferences = true)
bool deleteReference(const QOpcUaDeleteReferenceItem &referenceToDelete)
void disconnectFromEndpoint()
QOpcUaClient::ClientError error() const
bool findServers(const QUrl &url, const QStringList &localeIds = QStringList(), const QStringList &serverUris = QStringList())
bool isNamespaceAutoupdateEnabled() const
QStringList namespaceArray() const
int namespaceAutoupdateInterval() const
QOpcUaNode *node(const QString &nodeId)
QOpcUaNode *node(const QOpcUa::QExpandedNodeId &expandedNodeId)
QOpcUa::QQualifiedName qualifiedNameFromNamespaceUri(const QString &namespaceUri, const QString &name, bool *ok = nullptr) const
bool readNodeAttributes(const QVector<QOpcUaReadItem> &nodesToRead)
bool requestEndpoints(const QUrl &url)
QString resolveExpandedNodeId(const QOpcUa::QExpandedNodeId &expandedNodeId, bool *ok = nullptr) const
void setNamespaceAutoupdate(bool isEnabled)
void setNamespaceAutoupdateInterval(int interval)
QOpcUaClient::ClientState state() const
bool updateNamespaceArray()
QUrl url() const
bool writeNodeAttributes(const QVector<QOpcUaWriteItem> &nodesToWrite)
  • 34 public functions inherited from QObject

Signals

void addNodeFinished(QOpcUa::QExpandedNodeId requestedNodeId, QString assignedNodeId, QOpcUa::UaStatusCode statusCode)
void addReferenceFinished(QString sourceNodeId, QString referenceTypeId, QOpcUa::QExpandedNodeId targetNodeId, bool isForwardReference, QOpcUa::UaStatusCode statusCode)
void connected()
void deleteNodeFinished(QString nodeId, QOpcUa::UaStatusCode statusCode)
void deleteReferenceFinished(QString sourceNodeId, QString referenceTypeId, QOpcUa::QExpandedNodeId targetNodeId, bool isForwardReference, QOpcUa::UaStatusCode statusCode)
void disconnected()
void endpointsRequestFinished(QVector<QOpcUa::QEndpointDescription> endpoints, QOpcUa::UaStatusCode statusCode)
void errorChanged(QOpcUaClient::ClientError error)
void findServersFinished(QVector<QOpcUa::QApplicationDescription> servers, QOpcUa::UaStatusCode statusCode)
void namespaceArrayChanged(QStringList namespaces)
void namespaceArrayUpdated(QStringList namespaces)
void readNodeAttributesFinished(QVector<QOpcUaReadResult> results, QOpcUa::UaStatusCode serviceResult)
void stateChanged(QOpcUaClient::ClientState state)
void writeNodeAttributesFinished(QVector<QOpcUaWriteResult> results, QOpcUa::UaStatusCode serviceResult)

Additional Inherited Members

  • 1 public slot inherited from QObject
  • 1 public variable inherited from QObject
  • 10 static public members inherited from QObject
  • 9 protected functions inherited from QObject
  • 2 protected variables inherited from QObject

Detailed Description

QOpcUaClient allows interaction with an OPC UA server.

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 and call connectToEndpoint() to connect to a server. 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";
    }
});
client->connectToEndpoint(QUrl("opc.tcp://127.0.0.1:4840")); // Connect the client to the server

Member Type Documentation

enum QOpcUaClient::ClientError

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

ConstantValueDescription
QOpcUaClient::NoError0No error occurred.
QOpcUaClient::InvalidUrl1The url to connect to has been wrongly specified or a connection to this url failed.
QOpcUaClient::AccessDenied2An attempt to connect to a server using username/password failed due to wrong credentials.
QOpcUaClient::ConnectionError3An error occurred with the connection.
QOpcUaClient::UnknownError4An unknown error occurred.

enum QOpcUaClient::ClientState

This enum type specifies the connection state of the client.

ConstantValueDescription
QOpcUaClient::Disconnected0The client is not connected to a server.
QOpcUaClient::Connecting1The client is currently connecting to a server.
QOpcUaClient::Connected2The client is connected to a server.
QOpcUaClient::Closing3The client has been connected and requests a disconnect from the server.

Property Documentation

error : const ClientError

Specifies the current error state of the client.

Access functions:

QOpcUaClient::ClientError error() const

Notifier signal:

void errorChanged(QOpcUaClient::ClientError error)

state : const ClientState

Specifies the current connection state of the client.

Access functions:

QOpcUaClient::ClientState state() const

Notifier signal:

void stateChanged(QOpcUaClient::ClientState state)

Member Function Documentation

[virtual] QOpcUaClient::~QOpcUaClient()

Destroys the QOpcUaClient instance.

bool QOpcUaClient::addNode(const QOpcUaAddNodeItem &nodeToAdd)

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(QOpcUa::QLocalizedText("en", "My new Variable node"));
attributes.setDescription(QOpcUa::QLocalizedText("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(QOpcUa::QExpandedNodeId("ns=3;s=TestFolder"));
item.setReferenceTypeId(QOpcUa::nodeIdFromReferenceType(QOpcUa::ReferenceTypeId::Organizes));
item.setRequestedNewNodeId(QOpcUa::QExpandedNodeId("ns=3;s=MyNewVariableNode"));
item.setBrowseName(QOpcUa::QQualifiedName(3, "MyNewVariableNode"));
item.setNodeClass(QOpcUa::NodeClass::Variable);
item.setNodeAttributes(attributes);

m_client->addNode(item);

See also deleteNode(), addNodeFinished(), and QOpcUaAddNodeItem.

[signal] void QOpcUaClient::addNodeFinished(QOpcUa::QExpandedNodeId requestedNodeId, QString assignedNodeId, QOpcUa::UaStatusCode statusCode)

This signal is emitted after an addNode() operation has finished. requestedNodeId is the requested node id from the addNode() call, assignedNodeId is the node id the server has assigned to the new node. statusCode contains the result of the operation. If the result is Bad, assignedNodeId is empty and no node has been added to the server's address space.

bool QOpcUaClient::addReference(const QOpcUaAddReferenceItem &referenceToAdd)

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(QOpcUa::QExpandedNodeId("ns=3;s=MyNewVariableNode"));
item.setTargetNodeClass(QOpcUa::NodeClass::Variable);

m_client->addReference(item);

See also deleteReference(), addReferenceFinished(), and QOpcUaAddReferenceItem.

[signal] void QOpcUaClient::addReferenceFinished(QString sourceNodeId, QString referenceTypeId, QOpcUa::QExpandedNodeId targetNodeId, bool isForwardReference, QOpcUa::UaStatusCode statusCode)

This signal is emitted after an addReference() operation has finished. sourceNodeId, referenceTypeId, targetNodeId and isForwardReference are the values from the addReference() call. statusCode contains the result of the operation.

QString QOpcUaClient::backend() const

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

void QOpcUaClient::connectToEndpoint(const QUrl &url)

Connects to the OPC UA endpoint given in url.

If the endpoint requires username and password, they must be included in url.

QUrl url("opc.tcp://localhost:4840");
url.setUserName("user");
url.setPassword("password");

m_client->connectToEndpoint(url);

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also disconnectFromEndpoint().

[signal] void QOpcUaClient::connected()

This signal is emitted when a connection has been established.

bool QOpcUaClient::deleteNode(const QString &nodeId, bool deleteTargetReferences = true)

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(QOpcUa::QExpandedNodeId("ns=3;s=MyNewVariableNode"), true);

See also addNode() and deleteNodeFinished().

[signal] void QOpcUaClient::deleteNodeFinished(QString nodeId, QOpcUa::UaStatusCode statusCode)

This signal is emitted after a deleteNode() operation has finished. nodeId is the node id from the deleteNode() call. statusCode contains the result of the operation.

bool QOpcUaClient::deleteReference(const QOpcUaDeleteReferenceItem &referenceToDelete)

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(QOpcUa::QExpandedNodeId("ns=3;s=MyNewVariableNode"));
item.setDeleteBidirectional(true);

m_client->deleteReference(item);

See also addReference(), deleteReferenceFinished(), and QOpcUaDeleteReferenceItem.

[signal] void QOpcUaClient::deleteReferenceFinished(QString sourceNodeId, QString referenceTypeId, QOpcUa::QExpandedNodeId targetNodeId, bool isForwardReference, QOpcUa::UaStatusCode statusCode)

This signal is emitted after a deleteReference() operation has finished. sourceNodeId, referenceTypeId, targetNodeId and isForwardReference are the values from the deleteReference() call. statusCode contains the result of the operation.

void QOpcUaClient::disconnectFromEndpoint()

Disconnects from the server.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also connectToEndpoint().

[signal] void QOpcUaClient::disconnected()

This signal is emitted when a connection has been closed following to a close request.

[signal] void QOpcUaClient::endpointsRequestFinished(QVector<QOpcUa::QEndpointDescription> endpoints, QOpcUa::UaStatusCode statusCode)

This signal is emitted after a requestEndpoints() operation has finished. statusCode contains the result of the operation. If the result is Good, endpoints contains the descriptions of all endpoints that are available on the server.

QOpcUaClient::ClientError QOpcUaClient::error() const

Returns the current error state of the client.

Note: Getter function for property error.

bool QOpcUaClient::findServers(const QUrl &url, const QStringList &localeIds = QStringList(), const QStringList &serverUris = QStringList())

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.

[signal] void QOpcUaClient::findServersFinished(QVector<QOpcUa::QApplicationDescription> servers, QOpcUa::UaStatusCode statusCode)

This signal is emitted after a findServers() operation has finished. statusCode contains the result of the operation. If the result is Good, servers contains the application descriptions of all servers known to the queried server that matched the filter criteria.

bool QOpcUaClient::isNamespaceAutoupdateEnabled() const

Returns whether autoupdate of the namespace array is enabled.

QStringList QOpcUaClient::namespaceArray() const

Returns the cached value of the namespace array.

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

See also updateNamespaceArray() and namespaceArrayUpdated().

[signal] void QOpcUaClient::namespaceArrayChanged(QStringList namespaces)

This signal is emitted after the namespace array has changed. namespaces contains the content of the server's namespace table. The index of an entry in namespaces corresponds to the namespace index used in the node id.

See also namespaceArrayUpdated() and updateNamespaceArray().

[signal] void QOpcUaClient::namespaceArrayUpdated(QStringList namespaces)

This signal is emitted after an updateNamespaceArray operation has finished. namespaces contains the content of the server's namespace table. The index of an entry in namespaces corresponds to the namespace index used in the node id.

If the namespace array content stays the same after the update this signal is emitted nevertheless.

See also namespaceArrayChanged() and updateNamespaceArray().

int QOpcUaClient::namespaceAutoupdateInterval() const

Returns the current revised update inverval of the namespace array.

See also setNamespaceAutoupdateInterval(int interval).

QOpcUaNode *QOpcUaClient::node(const QString &nodeId)

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

QOpcUaNode *QOpcUaClient::node(const QOpcUa::QExpandedNodeId &expandedNodeId)

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.

See also updateNamespaceArray().

QOpcUa::QQualifiedName QOpcUaClient::qualifiedNameFromNamespaceUri(const QString &namespaceUri, const QString &name, bool *ok = nullptr) const

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.

bool QOpcUaClient::readNodeAttributes(const QVector<QOpcUaReadItem> &nodesToRead)

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:

QVector<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);

See also QOpcUaReadItem and readNodeAttributesFinished().

[signal] void QOpcUaClient::readNodeAttributesFinished(QVector<QOpcUaReadResult> results, QOpcUa::UaStatusCode serviceResult)

This signal is emitted after a readNodeAttributes() operation has finished.

The elements in results have the same order as the elements in the request. For each requested element, there is a value together with timestamps and the status code in results. serviceResult contains the status code from the OPC UA Read service.

See also readNodeAttributes(), QOpcUaReadResult, and QOpcUaReadItem.

bool QOpcUaClient::requestEndpoints(const QUrl &url)

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.

QString QOpcUaClient::resolveExpandedNodeId(const QOpcUa::QExpandedNodeId &expandedNodeId, bool *ok = nullptr) const

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.

void QOpcUaClient::setNamespaceAutoupdate(bool isEnabled)

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.

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.

See also namespaceArray() and namespaceArrayUpdated().

void QOpcUaClient::setNamespaceAutoupdateInterval(int interval)

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() and QOpcUaClient::setNamespaceAutoupdate(bool isEnabled).

bool QOpcUaClient::updateNamespaceArray()

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.

See also namespaceArray() and namespaceArrayUpdated().

QUrl QOpcUaClient::url() const

Returns the URL of the OPC UA server the client is currently connected to or was last connected to.

bool QOpcUaClient::writeNodeAttributes(const QVector<QOpcUaWriteItem> &nodesToWrite)

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:

QVector<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);

See also QOpcUaWriteItem and writeNodeAttributesFinished().

[signal] void QOpcUaClient::writeNodeAttributesFinished(QVector<QOpcUaWriteResult> results, QOpcUa::UaStatusCode serviceResult)

This signal is emitted after a writeNodeAttributes() operation has finished.

The elements in results have the same order as the elements in the write request. They contain the value, timestamps and status code received from the server as well as the node id, attribute and index range from the write item. This facilitates matching the result with the request.

serviceResult is the status code from the the OPC UA Write service. If serviceResult is not Good, the entries in results also have an invalid status code and must not be used.

See also writeNodeAttributes() and QOpcUaWriteResult.

© 2018 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.