/
modbusclient.cpp
189 lines (168 loc) · 5.19 KB
/
modbusclient.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
#include "modbusclient.h"
ModbusClient::ModbusClient(QObject *parent, QString _ip, QString _port, bool _keepAlive) :
QObject(parent)
{
ip = QVariant(_ip);
port = QVariant(_port);
keepAlive = _keepAlive;
initSetup();
}
ModbusClient::~ModbusClient()
{
if (modbusDevice)
modbusDevice->disconnectDevice();
delete modbusDevice;
}
void ModbusClient::initSetup()
{
if (modbusDevice)
{
modbusDevice = nullptr;
}
modbusDevice = new QModbusTcpClient(this);
// immediate response to connection status change
connect(modbusDevice, &QModbusClient::stateChanged, this, &ModbusClient::onStateChanged);
}
void ModbusClient::connectToPLC()
{
if (!modbusDevice)
return;
if (modbusDevice->state() != QModbusDevice::ConnectedState)
{
modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, ip);
modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortParameter, port);
modbusDevice->setTimeout(1000); // 1s
modbusDevice->setNumberOfRetries(3);
if (!modbusDevice->connectDevice())
{
qDebug() << "Modbus connection failure.";
}
}
}
void ModbusClient::disconnectToPLC()
{
if (!modbusDevice)
return;
if (modbusDevice->state() == QModbusDevice::ConnectedState)
{
modbusDevice->disconnectDevice();
}
}
// Client will lose connection if no any activity in 30s
void ModbusClient::onStateChanged(int state)
{
if (state == QModbusDevice::UnconnectedState)
{
connectionStatus = false;
emit sendConnectionStatus(connectionStatus);
if (keepAlive)
{
// auto connect to PLC if connection lose
connectToPLC();
}
}
else if (state == QModbusDevice::ConnectedState)
{
connectionStatus = true;
emit sendConnectionStatus(connectionStatus);
}
}
bool ModbusClient::connected()
{
return connectionStatus;
}
void ModbusClient::writeToPLC(int regAddress, int msgToSend)
{
if (!modbusDevice)
return;
if (modbusDevice->state() != QModbusDevice::ConnectedState)
{
connectToPLC();
}
// datatype, start register address, how many resgister to write
QModbusDataUnit writeUnit(QModbusDataUnit::HoldingRegisters, regAddress, 1);
for (uint i = 0; i < writeUnit.valueCount(); i++) {
writeUnit.setValue(int(i), msgToSend); // write integer directly
}
if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, 1))
{
if (!reply->isFinished())
{
//reply Returns true when the reply has finished or was aborted.
connect(reply, &QModbusReply::finished, this, [this, reply]() {
if (reply->error() == QModbusDevice::ProtocolError)
{
qDebug() << "Write response error:" << reply->errorString() << reply->rawResult().exceptionCode();
}
else if (reply->error() != QModbusDevice::NoError)
{
qDebug() << "Write response error:" << reply->errorString() << reply->error();
}
reply->deleteLater();
});
}
else
{
reply->deleteLater(); // broadcast replies return immediately
}
}
else
{
qDebug() << "Write error:" << modbusDevice->errorString();
}
}
void ModbusClient::readFromPLC(int regAddress)
{
if (!modbusDevice)
return;
if (modbusDevice->state() != QModbusDevice::ConnectedState)
{
connectToPLC();
}
QModbusDataUnit readUnit(QModbusDataUnit::HoldingRegisters, regAddress, 1);
if (auto *reply = modbusDevice->sendReadRequest(readUnit, 1))
{
if (!reply->isFinished())
{
connect(reply, &QModbusReply::finished, this, &ModbusClient::readReady);
}
else
{
delete reply; // broadcast replies return immediately
}
}
else
{
qDebug() << "Read Erroor:" << modbusDevice->errorString();
}
}
void ModbusClient::readReady()
{
auto reply = qobject_cast<QModbusReply *>(sender());
if (!reply)
return;
if (reply->error() == QModbusDevice::NoError)
{
// msg store in reply.reslut()
const QModbusDataUnit unit = reply->result();
for (uint i = 0; i < unit.valueCount(); i++)
{
const QString startAdd = tr("%1").arg(unit.startAddress());
bool ok;
// convert from hex to decimal
const unsigned int parsedValue = QString::number(unit.value(i),
unit.registerType() <= QModbusDataUnit::Coils ? 10 : 16).toUInt(&ok, 16);
qDebug() << "Read from" << startAdd << ":" << QString::number(parsedValue);
emit sendReadMsg(ip.toString(), startAdd.toInt(), int(parsedValue));
}
}
else if (reply->error() == QModbusDevice::ProtocolError)
{
qDebug() << "Read response error:" << reply->errorString() << reply->rawResult().exceptionCode();
}
else
{
qDebug() << "Read response error:" << reply->errorString() << reply->error();
}
reply->deleteLater();
}