summaryrefslogtreecommitdiffstats
path: root/src/imports/opcua/opcuavaluenode.cpp
blob: cd42595c744b9964ab72d54f58b639a8c9a88772 (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
/****************************************************************************
**
** 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 "opcuavaluenode.h"
#include "opcuaconnection.h"
#include "opcuanodeid.h"
#include "opcuaattributevalue.h"
#include <QLoggingCategory>
#include <QMetaEnum>

QT_BEGIN_NAMESPACE

/*!
    \qmltype ValueNode
    \inqmlmodule QtOpcUa
    \brief Represents a value node from a server.
    \inherits Node
    \since QtOpcUa 5.12

    \code
    import QtOpcUa 5.13 as QtOpcUa

    QtOpcUa.ValueNode {
        nodeId: QtOpcUa.NodeId {
            ns: "Test Namespace"
            identifier: "s=TestName"
        }
        connection: myConnection
    }
    \endcode

    A subscription will be created on the server in order to track value changes on the server.

    \sa NodeId, Connection, Node
*/

/*!
    \qmlproperty variant ValueNode::value

    Value of this node.
    Reading and writing this property will access the node on the server.
*/

/*!
    \qmlproperty variant ValueNode::valueType

    Type type of this node.
    The initial value will be \l {QtOpcUa::Undefined}{QtOpcUa.Constants.Undefined} and be fetched from the server when the first connection is established.
    Any value will be written to the server as the specified type.
*/

/*!
    \qmlproperty Date ValueNode::sourceTimestamp
    \readonly

    Source timestamp of the value attribute.
*/

/*!
    \qmlproperty Date ValueNode::serverTimestamp
    \readonly

    Server timestamp of the value attribute.
*/

Q_DECLARE_LOGGING_CATEGORY(QT_OPCUA_PLUGINS_QML)

OpcUaValueNode::OpcUaValueNode(QObject *parent):
    OpcUaNode(parent)
{
    connect(m_attributeCache.attribute(QOpcUa::NodeAttribute::Value), &OpcUaAttributeValue::changed, this, &OpcUaValueNode::valueChanged);
    connect(this, &OpcUaValueNode::filterChanged, this, &OpcUaValueNode::updateFilters);
}

OpcUaValueNode::~OpcUaValueNode()
{
}

void OpcUaValueNode::setValue(const QVariant &value)
{
    if (!m_connection || !m_node)
        return;
    m_node->writeAttribute(QOpcUa::NodeAttribute::Value, value, m_valueType);
}

template<typename T> QString enumToString(T value) {
    const auto metaEnum = QMetaEnum::fromType<T>();
    const auto key = metaEnum.valueToKey(static_cast<int>(value));
    if (key)
        return QString::fromLatin1(key);
    else
        return QString();
}

void OpcUaValueNode::setupNode(const QString &absolutePath)
{
    // Additionally read the value attribute
    setAttributesToRead(attributesToRead()
                        | QOpcUa::NodeAttribute::Value
                        | QOpcUa::NodeAttribute::DataType);

    OpcUaNode::setupNode(absolutePath);
    if (!m_node)
        return;

    connect(m_node, &QOpcUaNode::attributeWritten, this, [this](QOpcUa::NodeAttribute attribute, QOpcUa::UaStatusCode statusCode) {
        if (statusCode != QOpcUa::Good) {
            QString msg = "Failed to write attribute "
                    + enumToString(attribute)
                    + ": "
                    + enumToString(statusCode);
            setStatus(Status::FailedToWriteAttribute, msg);
            qCWarning(QT_OPCUA_PLUGINS_QML) << msg;
            }
      });


    connect(m_node, &QOpcUaNode::attributeUpdated, this, [this](QOpcUa::NodeAttribute attr, QVariant value) {
        if (attr == QOpcUa::NodeAttribute::DataType && m_valueType == QOpcUa::Types::Undefined) {
            const auto valueType = QOpcUa::opcUaDataTypeToQOpcUaType(value.toString());
            m_valueType = valueType;
        }
    });

    connect(m_node, &QOpcUaNode::enableMonitoringFinished, this, [this](QOpcUa::NodeAttribute attr, QOpcUa::UaStatusCode statusCode){
        if (attr != QOpcUa::NodeAttribute::Value)
            return;
        if (statusCode == QOpcUa::Good) {
            m_monitoredState = true;
            emit monitoredChanged(m_monitoredState);
            qCDebug(QT_OPCUA_PLUGINS_QML) << "Monitoring was enabled for node" << resolvedNode().fullNodeId();
            if (m_connection->backend() != QLatin1String("open62541")) {
                // This line triggers a bug in open62541. When it is fixed the call should be unconditional.
                updateFilters();
            }
        } else {
            qCWarning(QT_OPCUA_PLUGINS_QML) << "Failed to enable monitoring for node" << resolvedNode().fullNodeId();
            setStatus(Status::FailedToSetupMonitoring);
        }
    });
    connect(m_node, &QOpcUaNode::disableMonitoringFinished, this, [this](QOpcUa::NodeAttribute attr, QOpcUa::UaStatusCode statusCode){
        if (attr != QOpcUa::NodeAttribute::Value)
            return;
        if (statusCode == QOpcUa::Good) {
            m_monitoredState = false;
            emit monitoredChanged(m_monitoredState);
            qCDebug(QT_OPCUA_PLUGINS_QML) << "Monitoring was disabled for node "<< resolvedNode().fullNodeId();
        } else {
            qCWarning(QT_OPCUA_PLUGINS_QML) << "Failed to disable monitoring for node "<< resolvedNode().fullNodeId();
            setStatus(Status::FailedToDisableMonitoring);
        }
    });
    connect(m_node, &QOpcUaNode::monitoringStatusChanged, this, [this](QOpcUa::NodeAttribute attr, QOpcUaMonitoringParameters::Parameters items,
                                                                   QOpcUa::UaStatusCode statusCode) {
       if (attr != QOpcUa::NodeAttribute::Value && attr != QOpcUa::NodeAttribute::EventNotifier)
           return;
       if (statusCode != QOpcUa::Good) {
           setStatus(Status::FailedToModifyMonitoring);
           qCWarning(QT_OPCUA_PLUGINS_QML) << "Failed to modify monitoring";
       } else {
           if (items & QOpcUaMonitoringParameters::Parameter::PublishingInterval) {
               if (m_publishingInterval != m_node->monitoringStatus(QOpcUa::NodeAttribute::Value).publishingInterval()) {
                   m_publishingInterval = m_node->monitoringStatus(QOpcUa::NodeAttribute::Value).publishingInterval();
                   emit publishingIntervalChanged(m_publishingInterval);
               }
           }
       }
    });

    updateSubscription();
}

void OpcUaValueNode::updateFilters() const
{
    if (!m_connection || !m_node || !m_filter || !m_monitoredState)
        return;

    m_node->modifyDataChangeFilter(QOpcUa::NodeAttribute::Value, m_filter->filter());
}

bool OpcUaValueNode::checkValidity()
{
    if (!m_connection || !m_node)
        return false;

    if (m_node->attribute(QOpcUa::NodeAttribute::NodeClass).value<QOpcUa::NodeClass>() != QOpcUa::NodeClass::Variable) {
        setStatus(Status::InvalidNodeType);
        return false;
    } else {
        return true;
    }

}

QVariant OpcUaValueNode::value() const
{
    if (!m_connection || !m_node)
        return QVariant();
    return m_node->attribute(QOpcUa::NodeAttribute::Value);
}

QDateTime OpcUaValueNode::serverTimestamp() const
{
    return getServerTimestamp(QOpcUa::NodeAttribute::Value);
}

QDateTime OpcUaValueNode::sourceTimestamp() const
{
    return getSourceTimestamp(QOpcUa::NodeAttribute::Value);
}

bool OpcUaValueNode::monitored() const
{
    if (!m_connection || !m_node)
        return m_monitored;

    return m_monitoredState;
}

void OpcUaValueNode::updateSubscription()
{
    if (!m_connection || !m_node)
        return;

    QOpcUaMonitoringParameters parameters;
    parameters.setPublishingInterval(m_publishingInterval);

    if (m_filter)
        parameters.setFilter(m_filter->filter());

    if (m_monitoredState != m_monitored) {
        if (m_monitored) {
            m_node->enableMonitoring(QOpcUa::NodeAttribute::Value, parameters);
        } else {
            m_node->disableMonitoring(QOpcUa::NodeAttribute::Value);
        }
    }
}
void OpcUaValueNode::setMonitored(bool monitored)
{
    m_monitored = monitored;
    updateSubscription();
}

double OpcUaValueNode::publishingInterval() const
{
    if (!m_connection || !m_node)
        return 0.0;

    auto monitoringStatus = node()->monitoringStatus(QOpcUa::NodeAttribute::Value);
    if (monitoringStatus.statusCode() == QOpcUa::BadNoEntryExists)
        return 0.0;
    return monitoringStatus.publishingInterval();
}

OpcUaDataChangeFilter *OpcUaValueNode::filter() const
{
    return m_filter;
}

void OpcUaValueNode::setFilter(OpcUaDataChangeFilter *filter)
{
    bool changed = false;

    if (m_filter) {
        disconnect(m_filter, &OpcUaDataChangeFilter::filterChanged, this, &OpcUaValueNode::updateFilters);
        changed = !(*m_filter == *filter);
    } else {
        changed = true;
    }

    m_filter = filter;
    connect(m_filter, &OpcUaDataChangeFilter::filterChanged, this, &OpcUaValueNode::updateFilters);

    if (changed)
        emit filterChanged();
}

void OpcUaValueNode::setPublishingInterval(double publishingInterval)
{
    if (!m_connection || !m_node)
        return;
    if (qFuzzyCompare(m_publishingInterval, publishingInterval))
        return;

     m_node->modifyMonitoring(QOpcUa::NodeAttribute::Value, QOpcUaMonitoringParameters::Parameter::PublishingInterval, publishingInterval);
}

QOpcUa::Types OpcUaValueNode::valueType() const
{
    return m_valueType;
}

void OpcUaValueNode::setValueType(QOpcUa::Types valueType)
{
    m_valueType = valueType;
}

QT_END_NAMESPACE