-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsmodbusrtu.cpp
666 lines (580 loc) · 16.7 KB
/
wsmodbusrtu.cpp
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*********************************************************************
* Copyright EoF Software Labs. All Rights Reserved.
* Copyright EoF Software Labs Authors.
* Written by B. Eschrich ([email protected])
* SPDX-License-Identifier: GPL v3
**********************************************************************/
#include <QDebug>
#include <wsmodbusrtu.h>
#define QUERY_STATUS_WITH_WORKER
#define NULL_MBO_MSG "Modbus NULL pointer object!"
#define CHECK_MODBUS(m) \
do { \
Q_ASSERT_X(m != 0L, Q_FUNC_INFO, NULL_MBO_MSG); \
} while (false)
WSModbusRtu::WSModbusRtu(MBRtuClient* modbus, QObject* parent)
: QObject {parent}
, m_modbus(modbus)
, m_fwVersion(0)
, m_address(1)
, m_function(RtuUnspecified)
, m_funcQueue()
, m_timer(nullptr)
{
CHECK_MODBUS(m_modbus);
connect(m_modbus, &MBRtuClient::opened, this, &WSModbusRtu::onModbusOpened);
connect(m_modbus, &MBRtuClient::closed, this, &WSModbusRtu::onModbusClosed);
connect(m_modbus, &MBRtuClient::received, this, &WSModbusRtu::onModbusReceived);
connect(m_modbus, &MBRtuClient::complete, this, &WSModbusRtu::onModbusComplete);
connect(m_modbus, &MBRtuClient::error, this, &WSModbusRtu::onModbusError);
}
WSModbusRtu::~WSModbusRtu()
{
CHECK_MODBUS(m_modbus);
if (m_timer && m_timer->isActive()) {
m_timer->stop();
m_timer->deleteLater();
}
if (m_modbus->isOpen()) {
m_modbus->close();
}
}
/* -------------------------------------------------------
* Api Methods
* ------------------------------------------------------- */
void WSModbusRtu::open()
{
Q_ASSERT_X(m_modbus != 0L, Q_FUNC_INFO, "Null pointer modbus object!");
if (!m_modbus->isOpen()) {
m_modbus->open();
}
else {
onModbusOpened();
}
}
void WSModbusRtu::close()
{
CHECK_MODBUS(m_modbus);
if (m_timer && m_timer->isActive()) {
m_timer->stop();
m_timer->deleteLater();
}
if (m_modbus->isOpen()) {
m_modbus->close();
}
else {
onModbusClosed();
}
}
const quint16& WSModbusRtu::firmwareVersion() const
{
return m_fwVersion;
}
const uint& WSModbusRtu::queryInterval() const
{
return m_interval;
}
void WSModbusRtu::setQueryInterval(uint interval)
{
if (m_interval != interval) {
m_interval = interval;
/* notify consumer */
emit intervalChanged(deviceAddress(), m_interval);
}
}
const uint& WSModbusRtu::function() const
{
return m_function;
}
void WSModbusRtu::scheduleFunction(const uint function)
{
m_funcQueue.append(function);
}
const quint8& WSModbusRtu::deviceAddress() const
{
return m_address;
}
void WSModbusRtu::setDeviceAddress(const quint8 address, const bool updateDevice)
{
if (m_address != address) {
if (!updateDevice) {
m_address = address;
emit addressChanged(m_address);
return;
}
CHECK_MODBUS(m_modbus);
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Set Device Address:" << address;
}
setFunction(RtuWriteDeviceAddr);
m_modbus->send(
deviceAddress(),
QModbusRequest( //
QModbusRequest::WriteSingleRegister,
(quint16) 0x4000, // 16bit startAddress [ Coil ]
(quint8) 0x00, // 16bit address - byte HI
(quint8) address) // 16bit address - byte LO
);
}
}
const QString& WSModbusRtu::portName() const
{
CHECK_MODBUS(m_modbus);
return m_modbus->portName();
}
void WSModbusRtu::setPortName(const QString& name)
{
CHECK_MODBUS(m_modbus);
m_modbus->setPortName(name);
}
const QSerialPort::BaudRate& WSModbusRtu::baudRate() const
{
CHECK_MODBUS(m_modbus);
return m_modbus->baudRate();
}
void WSModbusRtu::setBaudRate(const QSerialPort::BaudRate rate, const bool updateDevice)
{
CHECK_MODBUS(m_modbus);
if (m_modbus->baudRate() != rate) {
if (!updateDevice) {
m_modbus->setBaudRate(rate);
return;
}
setDeviceUartParams(rate, m_modbus->parity());
}
}
const QSerialPort::Parity& WSModbusRtu::parity() const
{
CHECK_MODBUS(m_modbus);
return m_modbus->parity();
}
void WSModbusRtu::setParity(const QSerialPort::Parity parity, const bool updateDevice)
{
CHECK_MODBUS(m_modbus);
if (m_modbus->parity() != parity) {
if (!updateDevice) {
m_modbus->setParity(parity);
return;
}
setDeviceUartParams(m_modbus->baudRate(), parity);
}
}
const QSerialPort::DataBits& WSModbusRtu::dataBits() const
{
CHECK_MODBUS(m_modbus);
return m_modbus->dataBits();
}
void WSModbusRtu::setDataBits(const QSerialPort::DataBits bits)
{
CHECK_MODBUS(m_modbus);
m_modbus->setDataBits(bits);
}
const QSerialPort::StopBits& WSModbusRtu::stopBits() const
{
CHECK_MODBUS(m_modbus);
return m_modbus->stopBits();
}
void WSModbusRtu::setStopBits(const QSerialPort::StopBits bits)
{
CHECK_MODBUS(m_modbus);
m_modbus->setStopBits(bits);
}
bool WSModbusRtu::isValidModbus() const
{
CHECK_MODBUS(m_modbus);
return m_modbus->isOpen();
}
/* -------------------------------------------------------
* Protected Methods
* ------------------------------------------------------- */
bool WSModbusRtu::isTrace(uint mask) const
{
CHECK_MODBUS(m_modbus);
return m_modbus->isTrace(mask);
}
bool WSModbusRtu::isFunctionQueueEmpty() const
{
return m_funcQueue.isEmpty();
}
void WSModbusRtu::resetFunctionQueue()
{
m_funcQueue.clear();
}
uint WSModbusRtu::takeFirstFunction()
{
if (m_funcQueue.isEmpty()) {
return RtuUnspecified;
}
return m_funcQueue.takeFirst();
}
void WSModbusRtu::startStatusWorker()
{
/* nothing here, may overridden */
}
void WSModbusRtu::send(uint function, quint8 device, const QModbusRequest& mr)
{
CHECK_MODBUS(m_modbus);
setFunction(function);
m_modbus->send(device, mr);
}
void WSModbusRtu::read(uint function, quint8 device, const QModbusDataUnit& du)
{
CHECK_MODBUS(m_modbus);
setFunction(function);
m_modbus->read(device, du);
}
void WSModbusRtu::write(uint function, quint8 device, const QModbusDataUnit& du)
{
CHECK_MODBUS(m_modbus);
setFunction(function);
m_modbus->write(device, du);
}
bool WSModbusRtu::checkValueCount(const uint count, const QModbusDataUnit& unit)
{
if (count != unit.valueCount()) {
qWarning() << id() << "Invalid number of values in function:" //
<< function() << "count:" << count;
return false;
}
return true;
}
void WSModbusRtu::readVersion()
{
CHECK_MODBUS(m_modbus);
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Read Version";
}
setFunction(RtuReadVersion);
m_modbus->send(
deviceAddress(),
QModbusRequest(
QModbusRequest::ReadHoldingRegisters,
(quint16) 0x8000, // 16bit Command Register 'FW Version'
(quint8) 0x00, // 16bit Fixed register value HI
(quint8) 0x01) // 16bit Fixed register value LO
);
}
void WSModbusRtu::readDeviceAddress()
{
CHECK_MODBUS(m_modbus);
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Read Device Address";
}
setFunction(RtuReadDeviceAddr);
m_modbus->send(
deviceAddress(),
QModbusRequest(
QModbusRequest::ReadHoldingRegisters,
(quint16) 0x4000, // 16bit Command Register 'Device Address'
(quint8) 0x00, // 16bit Fixed register value HI
(quint8) 0x01) // 16bit Fixed register value LO
);
}
bool WSModbusRtu::doMduCoils(const QModbusDataUnit&)
{
return false;
}
bool WSModbusRtu::doMduDiscreteInputs(const QModbusDataUnit&)
{
return false;
}
bool WSModbusRtu::doMduInputRegisters(const QModbusDataUnit& unit)
{
switch (function()) {
case RtuWriteDeviceAddr: {
if (checkValueCount(2, unit) && unit.value(0) == 0x4000) {
/* set to object instance only */
quint8 addr = static_cast<quint8>( //
(unit.value(1) & 0x00ff));
/* set to object instance only */
setDeviceAddress(addr, false);
}
return true;
}
}
return false;
}
bool WSModbusRtu::doMduHoldingRegisters(const QModbusDataUnit& unit)
{
switch (function()) {
case RtuReadDeviceAddr: {
if (checkValueCount(1, unit)) {
/* set to object instance only */
quint8 addr = static_cast<quint8>( //
(unit.value(0) & 0x00ff));
setDeviceAddress(addr, false);
}
return true;
}
case RtuReadVersion: {
if (checkValueCount(1, unit)) {
m_fwVersion = unit.value(0);
}
return true;
}
}
return false;
}
void WSModbusRtu::doModbusOpened()
{
}
void WSModbusRtu::doModbusClosed()
{
}
void WSModbusRtu::doModbusError(quint8, int, const QString&)
{
}
void WSModbusRtu::doComplete(uint function)
{
setFunction(function);
}
void WSModbusRtu::doFunction(uint)
{
}
/* -------------------------------------------------------
* Private Methods
* ------------------------------------------------------- */
inline void WSModbusRtu::setFunction(const uint function)
{
m_function = function;
}
inline void WSModbusRtu::setDeviceUartParams( //
const QSerialPort::BaudRate baud,
const QSerialPort::Parity parity)
{
CHECK_MODBUS(m_modbus);
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Set device UART parameters";
}
quint8 parval = 0x00; // default: None
quint8 baudval = 0x01; // default: 9600
switch (parity) {
case QSerialPort::Parity::NoParity: {
parval = 0x00;
break;
}
case QSerialPort::Parity::EvenParity: {
parval = 0x01;
break;
}
case QSerialPort::Parity::OddParity: {
parval = 0x02;
break;
}
default: {
qWarning() << id() << "Unsupported UART parameter. Parity:" << parity;
return;
}
}
switch (baud) {
case QSerialPort::BaudRate::Baud4800: {
baudval = 0x00;
break;
}
case QSerialPort::BaudRate::Baud9600: {
baudval = 0x01;
break;
}
case QSerialPort::BaudRate::Baud19200: {
baudval = 0x02;
break;
}
case QSerialPort::BaudRate::Baud38400: {
baudval = 0x03;
break;
}
case QSerialPort::BaudRate::Baud57600: {
baudval = 0x04;
break;
}
case QSerialPort::BaudRate::Baud115200: {
baudval = 0x05;
break;
}
default: {
/* 0x06 = 128000 and 0x07 = 256000 not supported by QT */
qWarning() << id() << "Unsupported UART parameter. BaudRate:" << baud;
return;
}
}
setFunction(RtuWriteUartParams);
m_modbus->send(
deviceAddress(),
QModbusRequest( //
QModbusRequest::WriteSingleRegister,
(quint16) 0x2000, // 16bit uart config register
(quint8) parval, // 16bit parity - byte HI
(quint8) baudval) // 16bit baud rate - byte LO
);
m_modbus->setBaudRate(baud);
m_modbus->setParity(parity);
}
/* -------------------------------------------------------
* Event Methods
* ------------------------------------------------------- */
void WSModbusRtu::onModbusOpened()
{
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Modbus opened";
}
/* reset internals */
setFunction(RtuUnspecified);
resetFunctionQueue();
/* schedule inital queries */
scheduleFunction(RtuReadVersion);
scheduleFunction(RtuReadDeviceAddr);
/* processing by derived classes */
doModbusOpened();
m_timer = new QTimer(this);
connect(m_timer, &QTimer::destroyed, this, &WSModbusRtu::onTimerDestroyed);
connect(m_timer, &QTimer::timeout, this, &WSModbusRtu::onWorkerQueue);
m_timer->setTimerType(Qt::PreciseTimer);
m_timer->setSingleShot(false);
m_timer->setInterval(50);
m_timer->start();
/* notify consumer */
emit opened(deviceAddress());
}
void WSModbusRtu::onModbusClosed()
{
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Modbus closed";
}
if (m_timer && m_timer->isActive()) {
m_timer->stop();
m_timer->deleteLater();
}
/* processing by derived classes */
doModbusClosed();
emit closed(deviceAddress());
}
void WSModbusRtu::onModbusError(uint server, const int code, const QString& message)
{
/* skip, if event context not mine */
if (server != deviceAddress() || function() == RtuUnspecified) {
return;
}
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qCritical() << id() << "Modbus error:" << code << message;
}
if (m_timer && m_timer->isActive()) {
m_timer->stop();
m_timer->deleteLater();
}
emit errorOccured(server, code, message);
/* processing by derived classes */
doModbusError(server, code, message);
}
void WSModbusRtu::onModbusReceived(uint server, const QModbusResponse& resp, const QModbusDataUnit& unit, bool isDataUnit)
{
/* skip, if event context not mine */
if (server != deviceAddress() || function() == RtuUnspecified) {
return;
}
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "FUNC>" << function() //
<< "RSP>" << resp //
<< "UNIT>" << isDataUnit //
<< "RT:" << Qt::dec << unit.registerType() //
<< "VC:" << Qt::dec << unit.valueCount() //
<< "VD:" << Qt::hex << unit.values();
}
if (isDataUnit) {
switch (unit.registerType()) {
case QModbusDataUnit::Coils: {
doMduCoils(unit);
break;
}
case QModbusDataUnit::DiscreteInputs: {
doMduDiscreteInputs(unit);
break;
}
case QModbusDataUnit::InputRegisters: {
doMduInputRegisters(unit);
break;
}
case QModbusDataUnit::HoldingRegisters: {
doMduHoldingRegisters(unit);
break;
}
default: {
qWarning() << id() << "Unhandled modbus data unit:" //
<< unit.registerType();
break;
}
}
}
}
void WSModbusRtu::onModbusComplete(uint server)
{
/* skip, if event context not mine */
if (server != deviceAddress() || function() == RtuUnspecified) {
return;
}
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Modbus complete";
}
emit complete(deviceAddress(), function());
doComplete(function());
/* reset current progress */
setFunction(RtuUnspecified);
}
void WSModbusRtu::onWorkerQueue()
{
/* nothing to do or just in work */
if (isFunctionQueueEmpty() || function() != RtuUnspecified) {
return;
}
QTimer* timer;
if (!(timer = dynamic_cast<QTimer*>(sender()))) {
qDebug() << id() << "OOPS! Sender object not timer!";
resetFunctionQueue();
return;
}
/* kill timer if modbus closed */
if (!isValidModbus()) {
timer->stop();
timer->deleteLater();
resetFunctionQueue();
return;
}
uint function;
switch ((function = takeFirstFunction())) {
case RtuReadVersion: {
readVersion();
break;
}
case RtuReadDeviceAddr: {
readDeviceAddress();
break;
}
default: {
doFunction(function);
break;
}
}
#if defined(QUERY_STATUS_WITH_WORKER)
/* restart query cycle */
if (isFunctionQueueEmpty()) {
/* derived class schedule queries */
startStatusWorker();
/* remove timer if nothing to do */
if (isFunctionQueueEmpty()) {
timer->stop();
timer->deleteLater();
return;
}
/* update timer to query interval */
if (timer->interval() != ((int) queryInterval())) {
timer->setInterval(queryInterval());
}
}
#endif
}
void WSModbusRtu::onTimerDestroyed()
{
if (m_modbus->isTrace(MBRtuClient::TRACE_CONTROL)) {
qDebug() << id() << "Timer destroyed";
}
m_timer = nullptr;
}