summaryrefslogtreecommitdiffstats
path: root/src/serialbus/qmodbusdevice.cpp
blob: ad215d903cd0841dba3b9828a7c9cb475511aabc (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
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qmodbusdevice.h"
#include "qmodbusdevice_p.h"
#include "qmodbusdataunit.h"

#include <QtCore/qloggingcategory.h>

QT_BEGIN_NAMESPACE

/*!
    \class QModbusDevice
    \inmodule QtSerialBus
    \since 5.8

    \brief The QModbusDevice class is the base class for Modbus classes, \l QModbusServer
    and \l QModbusClient.
*/

/*!
    Constructs a Modbus device with the specified \a parent.
*/
QModbusDevice::QModbusDevice(QObject *parent)
 : QObject(*new QModbusDevicePrivate, parent)
{
}

/*!
    \internal
*/
QModbusDevice::QModbusDevice(QModbusDevicePrivate &dd, QObject *parent)
 : QObject(dd, parent)
{
}

/*!
    Destroys the QModbusDevice instance
*/
QModbusDevice::~QModbusDevice()
{
}

/*!
    \enum QModbusDevice::ConnectionParameter

    This enum describes the possible values that can be set for a Modbus device
    connection.

    The general purpose value (and the associated types) are:

    \value SerialPortNameParameter   This parameter holds the serial port used for
                                     device communication, e.g. COM1. \c QString
    \value SerialParityParameter     This parameter holds the parity checking mode.
                                     \c QSerialPort::Parity
    \value SerialBaudRateParameter   This parameter holds the data baud rate for
                                     the communication. \c QSerialPort::BaudRate
    \value SerialDataBitsParameter   This parameter holds the data bits in a frame.
                                     \c QSerialPort::DataBits
    \value SerialStopBitsParameter   This parameter holds the number of stop bits in a
                                     frame. \c QSerialPort::StopBits
    \value NetworkPortParameter      This parameter holds the network port. \c int
    \value NetworkAddressParameter   This parameter holds the host address for network
                                     communication. \c QString
*/

/*!
    Returns the value associated with the given connection \a parameter. The
    returned value can be empty.

    By default the \c QModbusDevice is initialized with some common values. The
    serial port settings are even parity, a baud rate of 19200 bits per second,
    eight data bits and one stop bit. The network settings for the host address
    is set to local host and port to 502.

    \note For a serial connection to succeed, the \l SerialPortNameParameter
    needs to be set to a valid communication port. The information about valid
    serial ports can be obtained from \l QSerialPortInfo.

    \note If the device is already connected, the settings are taken into account
    after reconnecting the device.

    \sa ConnectionParameter
*/
QVariant QModbusDevice::connectionParameter(ConnectionParameter parameter) const
{
    Q_D(const QModbusDevice);
    switch (parameter) {
#if QT_CONFIG(modbus_serialport)
    case SerialPortNameParameter:
        return d->m_comPort;
    case SerialDataBitsParameter:
        return d->m_dataBits;
    case SerialParityParameter:
        return d->m_parity;
    case SerialStopBitsParameter:
        return d->m_stopBits;
    case SerialBaudRateParameter:
        return d->m_baudRate;
#endif
    case NetworkPortParameter:
        return d->m_networkPort;
    case NetworkAddressParameter:
        return d->m_networkAddress;
    default:
        break;
    }
    return {};
}

/*!
    Sets the value of \a parameter to \a value. If the \a parameter already
    exists, the previous value is overwritten. A active or running connection
    is not affected by such parameter changes.

    \sa ConnectionParameter
    \sa connectionParameter()
*/
void QModbusDevice::setConnectionParameter(ConnectionParameter parameter, const QVariant &value)
{
    Q_D(QModbusDevice);
    switch (parameter) {
#if QT_CONFIG(modbus_serialport)
    case SerialPortNameParameter:
        d->m_comPort = value.toString();
        break;
    case SerialDataBitsParameter:
        d->m_dataBits = QSerialPort::DataBits(value.toInt());
        break;
    case SerialParityParameter:
        d->m_parity = QSerialPort::Parity(value.toInt());
        break;
    case SerialStopBitsParameter:
        d->m_stopBits = QSerialPort::StopBits(value.toInt());
        break;
    case SerialBaudRateParameter:
        d->m_baudRate = QSerialPort::BaudRate(value.toInt());
        break;
#endif
    case NetworkPortParameter:
        d->m_networkPort = value.toInt();
        break;
    case NetworkAddressParameter:
        d->m_networkAddress = value.toString();
        break;
    default:
        Q_ASSERT_X(false, "", "Connection parameter not supported.");
        break;
    }
}

/*!
    \enum QModbusDevice::Error
    This enum describes all the possible error conditions.

    \value NoError              No errors have occurred.
    \value ReadError            An error occurred during a read operation.
    \value WriteError           An error occurred during a write operation.
    \value ConnectionError      An error occurred when attempting to open the
                                backend.
    \value ConfigurationError   An error occurred when attempting to set a
                                configuration parameter.
    \value TimeoutError         A timeout occurred during I/O. An I/O operation
                                did not finish within a given time frame.
    \value ProtocolError        A Modbus specific protocol error occurred.
    \value ReplyAbortedError    The reply was aborted due to a disconnection of
                                the device.
    \value UnknownError         An unknown error occurred.
*/

/*!
    \enum QModbusDevice::State
    This enum describes all possible device states.

    \value UnconnectedState The device is disconnected.
    \value ConnectingState  The device is being connected.
    \value ConnectedState   The device is connected to the Modbus network.
    \value ClosingState     The device is being closed.
*/

/*!
    \since 6.0
    \enum QModbusDevice::IntermediateError

    This enum describes possible errors that can happen during a full send and
    receive cycle for a Modbus reply.

    \value ResponseCrcError         A Modbus response with a wrong CRC was received.
    \value ResponseRequestMismatch  A Modbus response was received but did not
                                    match the open request, probably due to the
                                    PDU's function code not matching.

    If any of the above intermediate errors occurred, the frame is likely
    resent until the maximum number of retries has been reached.

    The list of intermediate errors can be inspected from the \l QModbusReply
    intermediate errors function.

    \sa QModbusClient::numberOfRetries(), QModbusReply::intermediateErrors()
*/

/*!
    \fn QModbusDevice::errorOccurred(QModbusDevice::Error error)

    This signal is emitted when an error of the type, \a error, occurs.
*/

/*!
    \fn void QModbusDevice::stateChanged(QModbusDevice::State state)

    This signal is emitted every time the state of the device changes.
    The new state is represented by \a state.

    \sa setState(), state()
*/

/*!
    Connects the device to the Modbus network. Returns \c true if the connection
    process was successfully initiated; otherwise \c false. Final connection
    success confirmation requires the \l state() changing to \l QModbusDevice::ConnectedState.


    This function calls \l open() as part of its implementation.

    \sa open()
*/
bool QModbusDevice::connectDevice()
{
    Q_D(QModbusDevice);

    if (d->state != QModbusDevice::UnconnectedState)
        return false;

    setState(ConnectingState);

    if (!open()) {
        setState(UnconnectedState);
        return false;
    }

    //Connected is set by backend -> might be delayed by event loop
    return true;
}

/*!
    Disconnects the device.

    This function calls \l close() as part of its implementation.
*/
void QModbusDevice::disconnectDevice()
{
    if (state() == QModbusDevice::UnconnectedState)
        return;

    setState(QModbusDevice::ClosingState);

    //Unconnected is set by backend -> might be delayed by event loop
    close();
}

/*!
    Sets the state of the device to \a newState. Modbus device implementations
    must use this function to update the device state.
*/
void QModbusDevice::setState(QModbusDevice::State newState)
{
    Q_D(QModbusDevice);

    if (newState == d->state)
        return;

    d->state = newState;
    emit stateChanged(newState);
}

/*!
    Returns the current state of the device.

    \sa setState(), stateChanged()
*/
QModbusDevice::State QModbusDevice::state() const
{
    return d_func()->state;
}

/*!
    Sets the error state of the device. ModBus device implementations
    must use this function in case of an error to set the \a error type and
    a descriptive \a errorText.

    \sa QModbusDevice::Error
*/
void QModbusDevice::setError(const QString &errorText, QModbusDevice::Error error)
{
    Q_D(QModbusDevice);

    d->error = error;
    d->errorString = errorText;
    emit errorOccurred(error);
}

/*!
    Returns the error state of the device.

    \sa QModbusDevice::Error
*/
QModbusDevice::Error QModbusDevice::error() const
{
    return d_func()->error;
}

/*!
    Returns descriptive error text for the device error.

    \sa QModbusDevice::Error
*/
QString QModbusDevice::errorString() const
{
    return d_func()->errorString;
}

/*!
    \since 5.14

    Returns the underlying \l QIODevice used for ModBus communication or
    \c nullptr if the device was not yet fully initialized.

    \note Do not store a pointer to the underlying device, because it can be
    invalidated at any point in time.
*/
QIODevice *QModbusDevice::device() const
{
    return d_func()->device();
}

/*!
    \fn bool QModbusDevice::open()

    This function is called by connectDevice(). Subclasses must provide
    an implementation that returns \c true on successful Modbus connection
    or connection initiation; otherwise returns \c false.

    The implementation must ensure that the instance's \l state()
    is set to \l QModbusDevice::ConnectingState or \l QModbusDevice::ConnectedState upon success; otherwise
    \l QModbusDevice::UnconnectedState. Typically, \l QModbusDevice::ConnectingState is used
    when the connection process reports back asynchronously and \l QModbusDevice::ConnectedState
    in case of synchronous connect behavior.

    \sa connectDevice()
*/

/*!
    \fn void QModbusDevice::close()

    This function is responsible for closing the Modbus connection.
    The implementation must ensure that the instance's
    \l state() is set to \l QModbusDevice::UnconnectedState.

    \sa disconnectDevice()
*/

Q_LOGGING_CATEGORY(QT_MODBUS, "qt.modbus")
Q_LOGGING_CATEGORY(QT_MODBUS_LOW, "qt.modbus.lowlevel")

QT_END_NAMESPACE