summaryrefslogtreecommitdiffstats
path: root/src/imports/opcua/opcuaconnection.cpp
blob: 93ec5ad68b8aecee22557db2c000361fe0c1e521 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt OPC UA module.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "opcuaconnection.h"
#include "opcuareadresult.h"
#include "opcuawriteitem.h"
#include "opcuawriteresult.h"
#include "universalnode.h"
#include <QJSEngine>
#include <QLoggingCategory>
#include <QOpcUaProvider>
#include <QOpcUaReadItem>
#include <QOpcUaReadResult>
#include <QOpcUaWriteItem>

QT_BEGIN_NAMESPACE

/*!
    \qmltype Connection
    \inqmlmodule QtOpcUa
    \brief Connects to a server.
    \since QtOpcUa 5.12

    The main API uses backends to make connections. You have to set the backend before
    any connection attempt.

    \code
    import QtOpcUa 5.13 as QtOpcUa

    QtOpcUa.Connection {
        backend: "open62541"
    }

    Component.onCompleted: {
        connection.connectToEndpoint("opc.tcp://127.0.0.1:43344");
    }
    \endcode
*/

/*!
    \qmlproperty stringlist Connection::availableBackends
    \readonly

    Returns the names of all available backends as a list.
    These are used to select a backend when connecting.

    \sa Connection::backend
*/

/*!
    \qmlproperty bool Connection::connected
    \readonly

    Status of the connection.
    \c true when there is a connection, otherwise \c false.
*/

/*!
    \qmlproperty string Connection::backend

    Set the backend to use for a connection to the server.
    Has to be set before any connection attempt.

    \sa Connection::availableBackends
*/

/*!
    \qmlproperty bool Connection::defaultConnection

    Makes this the default connection.
    Usually each node needs to be given a connection to use. If this property
    is set to \c true, this connection will be used in all cases where a node has no
    connection set. Already established connections are not affected.
    If \c defaultConnection is set to \c true on multiple connection the last one is used.

    \code
    QtOpcUa.Connection {
        ...
        defaultConnection: true
        ...
    }
    \endcode

    \sa Node
*/

/*!
    \qmlproperty stringlist Connection::namespaces
    \readonly

    List of strings of all namespace URIs registered on the connected server.
*/

/*!
    \qmlproperty AuthenticationInformation Connection::authenticationInformation

    Set the authentication information to this connection. The authentication information has
    to be set before calling \l connectToEndpoint. If no authentication information is set,
    the anonymous mode will be used.
    It has no effect on the current connection. If the client is disconnected and then reconnected,
    the new credentials are used.
    Reading and writing this property before a \l backend is set, writes are ignored and reads return
    and invalid \l AuthenticationInformation.
*/

/*!
    \qmlproperty stringlist Connection::supportedSecurityPolicies
    \since 5.13

    A list of strings containing the supported security policies

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

/*!
    \qmlproperty array[tokenTypes] Connection::supportedUserTokenTypes
    \since 5.13

    An array of user token policy types of all supported user token types.

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

/*!
    \qmlproperty QOpcUaEndpointDescription Connection::currentEndpoint
    \since 5.13

    An endpoint description of the server to which the connection is connected to.
    When the connection is not established, an empty endpoint description is returned.
*/

/*!
    \qmlsignal Connection::readNodeAttributesFinished(readResults)

    Emitted when the read request, started using \l readNodeAttributes(), is finished.
    The parameter of this signal is an array of \l ReadResult, which contains the
    values requested from the server.

    \code
    connection.onReadNodeAttributesFinished(results) {
        for (var i = 0; results.length; i++) {
            if (results[i].status.isGood) {
                console.log(results[i].value);
            } else {
                // handle error
            }
        }
    }
    \endcode

    \sa readNodeAttributes(), ReadResult
*/

Q_DECLARE_LOGGING_CATEGORY(QT_OPCUA_PLUGINS_QML)

OpcUaConnection* OpcUaConnection::m_defaultConnection = nullptr;

OpcUaConnection::OpcUaConnection(QObject *parent):
    QObject(parent)
{
}

OpcUaConnection::~OpcUaConnection()
{
    setDefaultConnection(false);
    if (m_client) {
        m_client->deleteLater();
        m_client = nullptr;
    }
}

QStringList OpcUaConnection::availableBackends() const
{
    return QOpcUaProvider::availableBackends();
}

bool OpcUaConnection::connected() const
{
    return m_connected && m_client;
}

void OpcUaConnection::setBackend(const QString &name)
{
    if (name.isEmpty())
        return;

    if (!availableBackends().contains(name)) {
        qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Backend '%1' is not available").arg(name);
        qCDebug(QT_OPCUA_PLUGINS_QML) << tr("Available backends:") << availableBackends().join(QLatin1Char(','));
        return;
    }

    if (m_client) {
        if (m_client->backend() == name)
            return;

        m_client->disconnectFromEndpoint();
        m_client->disconnect(this);
        m_client->deleteLater();
    }

    QOpcUaProvider provider;
    m_client = provider.createClient(name);
    if (m_client) {
        qCDebug(QT_OPCUA_PLUGINS_QML) << "Created plugin" << m_client->backend();
        connect(m_client, &QOpcUaClient::stateChanged, this, &OpcUaConnection::clientStateHandler);
        connect(m_client, &QOpcUaClient::namespaceArrayUpdated, this, &OpcUaConnection::namespacesChanged);
        connect(m_client, &QOpcUaClient::namespaceArrayUpdated, this, [&]() {
            if (!m_connected) {
                m_connected = true;
                emit connectedChanged();
            }
        });
        m_client->setNamespaceAutoupdate(true);
        connect(m_client, &QOpcUaClient::readNodeAttributesFinished, this, &OpcUaConnection::handleReadNodeAttributesFinished);
        connect(m_client, &QOpcUaClient::writeNodeAttributesFinished, this, &OpcUaConnection::handleWriteNodeAttributesFinished);
    } else {
        qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Backend '%1' could not be created.").arg(name);
    }
    emit backendChanged();
}

QString OpcUaConnection::backend() const
{
    if (m_client)
        return m_client->backend();
    else
        return QString();
}

OpcUaConnection *OpcUaConnection::defaultConnection()
{
    return m_defaultConnection;
}

bool OpcUaConnection::isDefaultConnection() const
{
    return m_defaultConnection == this;
}

/*!
    \qmlmethod Connection::connectToEndpoint(endpointDescription)

    Connects to the given endpoint.

    \sa EndpointDescription endpoints
*/

void OpcUaConnection::connectToEndpoint(const QOpcUaEndpointDescription &endpointDescription)
{
    if (!m_client)
        return;

    m_client->connectToEndpoint(endpointDescription);
}

/*!
    \qmlmethod Connection::disconnectFromEndpoint(url)

    Disconnects an established connection.
*/

void OpcUaConnection::disconnectFromEndpoint()
{
    if (!m_client)
        return;

    m_client->disconnectFromEndpoint();
}

void OpcUaConnection::setDefaultConnection(bool defaultConnection)
{
    if (!defaultConnection && m_defaultConnection == this)
        m_defaultConnection = nullptr;

    if (defaultConnection)
        m_defaultConnection = this;

    emit defaultConnectionChanged();
}

void OpcUaConnection::clientStateHandler(QOpcUaClient::ClientState state)
{
    if (m_connected) {
        // don't immediately send the state; we have to wait for the namespace
        // array to be updated
        m_connected = (state == QOpcUaClient::ClientState::Connected);
        emit connectedChanged();
    }
}

QStringList OpcUaConnection::namespaces() const
{
    if (!m_client)
        return QStringList();

    return m_client->namespaceArray();
}

QOpcUaEndpointDescription OpcUaConnection::currentEndpoint() const
{
    if (!m_client || !m_connected)
        return QOpcUaEndpointDescription();

    return m_client->endpoint();
}

void OpcUaConnection::setAuthenticationInformation(const QOpcUaAuthenticationInformation &authenticationInformation)
{
    if (!m_client)
        return;
    m_client->setAuthenticationInformation(authenticationInformation);
}

QOpcUaAuthenticationInformation OpcUaConnection::authenticationInformation() const
{
    if (!m_client)
        return QOpcUaAuthenticationInformation();

    return m_client->authenticationInformation();
}

/*!
    \qmlmethod Connection::readNodeAttributes(valuesToBeRead)

    This function is used to read multiple values from a server in one go.
    Returns \c true if the read request was dispatched successfully.

    The values to be read have to be passed as JavaScript array of \l ReadItem.

    \code
    // List of items to read
    var readItemList = [];
    // Item to be added to the list of items to be read
    var readItem;

    // Prepare an item to be read

    // Create a new read item and fill properties
    readItem = QtOpcUa.ReadItem.create();
    readItem.ns = "http://qt-project.org";
    readItem.nodeId = "s=Demo.Static.Scalar.Double";
    readItem.attribute = QtOpcUa.Constants.NodeAttribute.DisplayName;

    // Add the prepared item to the list of items to be read
    readItemList.push(readItem);

    // Add further items
    [...]

    if (!connection.readNodeAttributes(readItemList)) {
        // handle error
    }
    \endcode

    The result of the read request are provided by the signal
    \l readNodeAttributesFinished().

    \sa readNodeAttributesFinished(), ReadItem
*/
bool OpcUaConnection::readNodeAttributes(const QJSValue &value)
{
    if (!m_client || !m_connected) {
        qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Not connected to server.");
        return false;
    }
    if (!value.isArray()) {
        qCWarning(QT_OPCUA_PLUGINS_QML) << tr("List of ReadItems it not an array.");
        return false;
    }

    QVector<QOpcUaReadItem> readItemList;

    for (int i = 0; i < value.property("length").toInt(); ++i){
        const auto &readItem = qjsvalue_cast<OpcUaReadItem>(value.property(i));
        if (readItem.nodeId().isEmpty()) {
            qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Invalid ReadItem in list of items at index %1").arg(i);
            return false;
        }

        QString finalNode;
        bool ok;
        int index = readItem.namespaceIdentifier().toInt(&ok);
        if (ok) {
            QString identifier;
            UniversalNode::splitNodeIdAndNamespace(readItem.nodeId(), nullptr, &identifier);
            finalNode = UniversalNode::createNodeString(index, identifier);
        } else {
            finalNode = UniversalNode::resolveNamespaceToNode(readItem.nodeId(), readItem.namespaceIdentifier().toString(), m_client);
        }

        if (finalNode.isEmpty()) {
            qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Failed to resolve node.");
            return false;
        }
        readItemList.push_back(QOpcUaReadItem(finalNode,
                                              readItem.attribute(),
                                              readItem.indexRange())
                               );
    }

    return m_client->readNodeAttributes(readItemList);
}

/*!
    \qmlmethod Connection::writeNodeAttributes(valuesToBeWritten)

    This function is used to write multiple values to a server in one go.
    Returns \c true if the write request was dispatched successfully.

    The values to be written have to be passed as JavaScript array of \l WriteItem.

    \code
    // List of items to write
    var writeItemList = [];
    // Item to be added to the list of items to be written
    var writeItem;

    // Prepare an item to be written

    // Create a new write item and fill properties
    writeItem = QtOpcUa.WriteItem.create();
    writeItem.ns = "http://qt-project.org";
    writeItem.nodeId = "s=Demo.Static.Scalar.Double";
    writeItem.attribute = QtOpcUa.Constants.NodeAttribute.Value;
    writeItem.value = 32.1;
    writeItem.valueType = QtOpcUa.Constants.Double;

    // Add the prepared item to the list of items to be written
    writeItemList.push(writeItem);

    // Add further items
    [...]

    if (!connection.writeNodeAttributes(writeItemList)) {
        // handle error
    }
    \endcode

    The result of the write request are provided by the signal
    \l writeNodeAttributesFinished().

    \sa writeNodeAttributesFinished(), WriteItem
*/
bool OpcUaConnection::writeNodeAttributes(const QJSValue &value)
{
    if (!m_client || !m_connected) {
        qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Not connected to server.");
        return false;
    }
    if (!value.isArray()) {
        qCWarning(QT_OPCUA_PLUGINS_QML) << tr("List of WriteItems it not an array.");
        return false;
    }

    QVector<QOpcUaWriteItem> writeItemList;

    for (int i = 0; i < value.property("length").toInt(); ++i){
        const auto &writeItem = qjsvalue_cast<OpcUaWriteItem>(value.property(i));
        if (writeItem.nodeId().isEmpty()) {
            qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Invalid WriteItem in list of items at index %1").arg(i);
            return false;
        }

        QString finalNode;
        bool ok;
        int index = writeItem.namespaceIdentifier().toInt(&ok);
        if (ok) {
            QString identifier;
            UniversalNode::splitNodeIdAndNamespace(writeItem.nodeId(), nullptr, &identifier);
            finalNode = UniversalNode::createNodeString(index, identifier);
        } else {
            finalNode = UniversalNode::resolveNamespaceToNode(writeItem.nodeId(), writeItem.namespaceIdentifier().toString(), m_client);
        }

        if (finalNode.isEmpty()) {
            qCWarning(QT_OPCUA_PLUGINS_QML) << tr("Failed to resolve node.");
            return false;
        }

        auto tmp = QOpcUaWriteItem(finalNode,
                                   writeItem.attribute(),
                                   writeItem.value(),
                                   writeItem.valueType(),
                                   writeItem.indexRange());

        tmp.setSourceTimestamp(writeItem.sourceTimestamp());
        tmp.setServerTimestamp(writeItem.serverTimestamp());
        if (writeItem.hasStatusCode())
            tmp.setStatusCode(static_cast<QOpcUa::UaStatusCode>(writeItem.statusCode()));
        writeItemList.push_back(tmp);
    }

    return m_client->writeNodeAttributes(writeItemList);
}

QStringList OpcUaConnection::supportedSecurityPolicies() const
{
    if (!m_client)
        return QStringList();
    return m_client->supportedSecurityPolicies();
}

QJSValue OpcUaConnection::supportedUserTokenTypes() const
{
    if (!m_client)
        return QJSValue();

    auto engine = qjsEngine(this);
    if (!engine)
        return QJSValue();

    const auto tokenTypes = m_client->supportedUserTokenTypes();
    auto returnValue = engine->newArray(tokenTypes.size());
    for (int i = 0; i < tokenTypes.size(); ++i)
        returnValue.setProperty(i, tokenTypes[i]);

    return returnValue;
}

void OpcUaConnection::handleReadNodeAttributesFinished(const QVector<QOpcUaReadResult> &results)
{
    QVariantList returnValue;

    for (const auto &result : results)
        returnValue.append(QVariant::fromValue(OpcUaReadResult(result, m_client)));

    emit readNodeAttributesFinished(QVariant::fromValue(returnValue));
}

void OpcUaConnection::handleWriteNodeAttributesFinished(const QVector<QOpcUaWriteResult> &results)
{
    QVariantList returnValue;

    for (const auto &result : results)
        returnValue.append(QVariant::fromValue(OpcUaWriteResult(result, m_client)));

    emit writeNodeAttributesFinished(QVariant::fromValue(returnValue));
}

QT_END_NAMESPACE