|
|
@@ -3,6 +3,10 @@ |
|
|
|
|
|
|
|
MyModbus::MyModbus() |
|
|
|
{ |
|
|
|
this->stationAddress_ = 1; |
|
|
|
this->functionCode_ = 0x01; |
|
|
|
this->startAdress_ = 256; |
|
|
|
this->length_ = 1; |
|
|
|
} |
|
|
|
|
|
|
|
void MyModbus::Set(quint16 stationAddress, quint16 functionCode, quint16 startAdress, quint16 length) |
|
|
@@ -86,15 +90,37 @@ QByteArray MyModbus::SendCommand() |
|
|
|
QByteArray MyModbus::Receive(const QByteArray &revMessage) |
|
|
|
{ |
|
|
|
receive_.clear(); |
|
|
|
if (CrcCheck(revMessage)) |
|
|
|
|
|
|
|
// 最小Modbus响应长度检查 |
|
|
|
if(revMessage.size() < 4) |
|
|
|
{ // 地址1 + 功能码1 + CRC2 |
|
|
|
return receive_; |
|
|
|
} |
|
|
|
|
|
|
|
// 检查站地址匹配 |
|
|
|
if(static_cast<quint8>(revMessage[0]) != stationAddress_) |
|
|
|
{ |
|
|
|
return receive_; |
|
|
|
} |
|
|
|
|
|
|
|
// CRC校验 |
|
|
|
if (!CrcCheck(revMessage)) |
|
|
|
{ |
|
|
|
this->receive_ = revMessage; |
|
|
|
return receive_; |
|
|
|
} |
|
|
|
|
|
|
|
this->receive_ = revMessage; |
|
|
|
return receive_; |
|
|
|
} |
|
|
|
|
|
|
|
int MyModbus::ErrorCheck() |
|
|
|
{ |
|
|
|
// 异常响应最小长度检查 |
|
|
|
if(receive_.size() < 5) |
|
|
|
{ |
|
|
|
// 地址1 + 异常功能码1 + 异常码1 + CRC2 |
|
|
|
return -1; // 特殊错误码表示协议错误 |
|
|
|
} |
|
|
|
if ((receive_.at(1) & 0x80) == 0x80) |
|
|
|
{ |
|
|
|
// MODBUS异常响应结构:地址 | 功能码+0x80 | 异常码 | CRC |
|
|
@@ -109,8 +135,14 @@ int MyModbus::ErrorCheck() |
|
|
|
|
|
|
|
QVector<bool> MyModbus::AnalReadCoil() |
|
|
|
{ |
|
|
|
quint8 byteCount = static_cast<quint8>(receive_[2]); |
|
|
|
QVector<bool> coil; |
|
|
|
if(receive_.size() < 6) |
|
|
|
{ |
|
|
|
// 最小长度: 地址1 + 功能码1 + 长度1 + 数据1 + CRC2 |
|
|
|
return coil; |
|
|
|
} |
|
|
|
|
|
|
|
quint8 byteCount = static_cast<quint8>(receive_[2]); |
|
|
|
|
|
|
|
for (int byteIndex = 0; byteIndex < byteCount; byteIndex++) |
|
|
|
{ |
|
|
@@ -132,10 +164,16 @@ QVector<bool> MyModbus::AnalReadCoil() |
|
|
|
|
|
|
|
QVector<quint16> MyModbus::AnalReadReg() |
|
|
|
{ |
|
|
|
QVector<quint16> registers; |
|
|
|
if(receive_.size() < 7) |
|
|
|
{ |
|
|
|
// 最小长度: 地址1 + 功能码1 + 长度1 + 数据2 + CRC2 |
|
|
|
return registers; |
|
|
|
} |
|
|
|
|
|
|
|
int byteCount = receive_.at(2); |
|
|
|
QByteArray data = receive_.mid(3, byteCount); |
|
|
|
|
|
|
|
QVector<quint16> registers; |
|
|
|
for (int i = 0; i < data.size(); i += 2) |
|
|
|
{ |
|
|
|
quint16 value = (static_cast<quint8>(data[i]) << 8) | static_cast<quint8>(data[i+1]); |
|
|
|