-
Notifications
You must be signed in to change notification settings - Fork 18
/
adu.cpp
101 lines (92 loc) · 2.19 KB
/
adu.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
#include "adu.h"
//#define QS_LOG_DISABLE
#include "QsLog.h"
ADU::ADU() :
PDU(),
mSocket(0),
mTransID(0),
mProdID(0),
mLength(0),
mUnitID(0)
{
}
ADU::ADU(QTcpSocket * const socket, const QByteArray & aduRequest) :
PDU(aduRequest),
mSocket(socket),
// Decode MBAP Header
mTransID(toUInt16(aduRequest, 0)),
mProdID(toUInt16(aduRequest, 2)),
mLength(toUInt16(aduRequest, 4)),
mUnitID(static_cast<quint8>(aduRequest[6]))
{
}
ADU::~ADU()
{
}
QByteArray ADU::toQByteArray() const
{
quint16 length = 0;
quint8 functionCode = getFunctionCode();
ExceptionCode exeptionCode = getExceptionCode();
if (exeptionCode == NoExeption) {
switch(functionCode) {
case ReadHoldingRegisters:
case ReadInputRegisters:
length = static_cast<quint16>(3 + mReplyData.size());
break;
case WriteSingleRegister:
length = 6;
break;
case WriteMultipleRegisters:
length = 6;
break;
default:
break;
}
} else {
length = 3;
}
QByteArray reply;
reply.reserve(length + 6);
// Create MBAP Header
appendUInt16(reply, mTransID);
appendUInt16(reply, mProdID);
appendUInt16(reply, length);
reply.append(static_cast<char>(mUnitID));
// Create PDU
reply.append(static_cast<char>(functionCode));
if (exeptionCode == NoExeption) {
switch(functionCode) {
case ReadHoldingRegisters:
case ReadInputRegisters:
reply.append(static_cast<char>(mReplyData.size()));
reply.append(mReplyData);
break;
case WriteSingleRegister:
appendUInt16(reply, getAddres());
reply.append(mReplyData);
break;
case WriteMultipleRegisters:
appendUInt16(reply, getAddres());
reply.append(static_cast<char>(0));
reply.append(static_cast<char>(getByteCount() / 2));
break;
default:
break;
}
} else {
reply.append(exeptionCode);
}
Q_ASSERT(reply.size() == length + 6);
return reply;
}
QString ADU::aduToString() const
{
QString string;
string += "\n\tTransaction Identifier: " + QString::number(mTransID,16).toUpper() + "\n";
string += "\tProtocol Identifier: " + QString::number(mProdID,16).toUpper() + "\n";
string += "\tLength: " + QString::number(mLength) + "\n";
string += "\tUnit Identifier: " + QString::number(mUnitID,16).toUpper() + "\n";
string += pduToString();
return string;
}