订单流程修改--QThread事件循环导致的逻辑修改
This commit is contained in:
+313
-207
@@ -1,36 +1,31 @@
|
||||
#include "modbustcpmanager.h"
|
||||
|
||||
#include <QEventLoop>
|
||||
#include <QModbusDataUnit>
|
||||
#include <QModbusReply>
|
||||
#include <QModbusTcpClient>
|
||||
#include <QTimer>
|
||||
#include <QVariant>
|
||||
|
||||
ModbusTcpManager &ModbusTcpManager::instance()
|
||||
{
|
||||
static ModbusTcpManager manager;
|
||||
return manager;
|
||||
}
|
||||
|
||||
ModbusTcpManager::ModbusTcpManager()
|
||||
: m_config(ModbusConfig::defaultConfig()),
|
||||
m_client(nullptr)
|
||||
ModbusTcpManager::ModbusTcpManager(const ModbusConfig &config,
|
||||
QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_config(config)
|
||||
, m_client(nullptr)
|
||||
, m_reply(nullptr)
|
||||
, m_connectTimer(new QTimer(this))
|
||||
, m_hasCurrentRequest(false)
|
||||
, m_connecting(false)
|
||||
, m_aborting(false)
|
||||
, m_connectAttempts(0)
|
||||
{
|
||||
m_connectTimer->setSingleShot(true);
|
||||
connect(m_connectTimer, &QTimer::timeout,
|
||||
this, &ModbusTcpManager::onConnectTimeout);
|
||||
}
|
||||
|
||||
ModbusTcpManager::~ModbusTcpManager()
|
||||
{
|
||||
disconnectDevice();
|
||||
delete m_client;
|
||||
}
|
||||
|
||||
void ModbusTcpManager::setConfig(const ModbusConfig &config)
|
||||
{
|
||||
if (isConnected()) {
|
||||
disconnectDevice();
|
||||
}
|
||||
m_config = config;
|
||||
abortAll("Modbus manager is shutting down");
|
||||
}
|
||||
|
||||
ModbusConfig ModbusTcpManager::config() const
|
||||
@@ -38,206 +33,245 @@ ModbusConfig ModbusTcpManager::config() const
|
||||
return m_config;
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::connectDevice(QString *error)
|
||||
void ModbusTcpManager::readCoil(
|
||||
int address,
|
||||
const std::function<void(bool, bool, const QString &)> &callback)
|
||||
{
|
||||
ensureClient();
|
||||
if (isConnected()) {
|
||||
return true;
|
||||
enqueue({QModbusDataUnit::Coils, address, 0, false,
|
||||
[callback](bool success, quint16 value, const QString &error) {
|
||||
if (callback) {
|
||||
callback(success, value != 0, error);
|
||||
}
|
||||
}});
|
||||
}
|
||||
|
||||
void ModbusTcpManager::readHoldingRegister(
|
||||
int address,
|
||||
const std::function<void(bool, quint16, const QString &)> &callback)
|
||||
{
|
||||
enqueue({QModbusDataUnit::HoldingRegisters, address, 0, false, callback});
|
||||
}
|
||||
|
||||
void ModbusTcpManager::writeCoil(
|
||||
int address, bool value,
|
||||
const std::function<void(bool, const QString &)> &callback)
|
||||
{
|
||||
enqueue({QModbusDataUnit::Coils, address,
|
||||
static_cast<quint16>(value ? 1 : 0), true,
|
||||
[callback](bool success, quint16, const QString &error) {
|
||||
if (callback) {
|
||||
callback(success, error);
|
||||
}
|
||||
}});
|
||||
}
|
||||
|
||||
void ModbusTcpManager::writeHoldingRegister(
|
||||
int address, quint16 value,
|
||||
const std::function<void(bool, const QString &)> &callback)
|
||||
{
|
||||
enqueue({QModbusDataUnit::HoldingRegisters, address, value, true,
|
||||
[callback](bool success, quint16, const QString &error) {
|
||||
if (callback) {
|
||||
callback(success, error);
|
||||
}
|
||||
}});
|
||||
}
|
||||
|
||||
void ModbusTcpManager::abortAll(const QString &reason)
|
||||
{
|
||||
if (m_aborting) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_client->setConnectionParameter(QModbusDevice::NetworkAddressParameter, QVariant(m_config.host));
|
||||
m_client->setConnectionParameter(QModbusDevice::NetworkPortParameter, QVariant(m_config.port));
|
||||
const QString text = reason.isEmpty()
|
||||
? "Modbus request was canceled" : reason;
|
||||
|
||||
m_aborting = true;
|
||||
m_connectTimer->stop();
|
||||
m_connecting = false;
|
||||
|
||||
if (m_reply) {
|
||||
QModbusReply *reply = m_reply;
|
||||
m_reply = nullptr;
|
||||
reply->disconnect(this);
|
||||
reply->deleteLater();
|
||||
}
|
||||
|
||||
if (m_hasCurrentRequest) {
|
||||
const Completion callback = m_currentRequest.callback;
|
||||
m_currentRequest = Request();
|
||||
m_hasCurrentRequest = false;
|
||||
setError(text);
|
||||
if (callback) {
|
||||
callback(false, 0, text);
|
||||
}
|
||||
}
|
||||
|
||||
while (!m_requests.isEmpty()) {
|
||||
Request request = m_requests.dequeue();
|
||||
if (request.callback) {
|
||||
request.callback(false, 0, text);
|
||||
}
|
||||
}
|
||||
|
||||
if (m_client
|
||||
&& m_client->state() != QModbusDevice::UnconnectedState) {
|
||||
m_client->disconnectDevice();
|
||||
}
|
||||
|
||||
m_aborting = false;
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::isBusy() const
|
||||
{
|
||||
return m_hasCurrentRequest || !m_requests.isEmpty()
|
||||
|| m_connecting || m_reply;
|
||||
}
|
||||
|
||||
void ModbusTcpManager::enqueue(const Request &request)
|
||||
{
|
||||
if (m_aborting) {
|
||||
if (request.callback) {
|
||||
request.callback(false, 0, "Modbus request was canceled");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.address < 0) {
|
||||
if (request.callback) {
|
||||
request.callback(false, 0,
|
||||
"Modbus address must be greater than or equal to 0");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
m_requests.enqueue(request);
|
||||
startNext();
|
||||
}
|
||||
|
||||
void ModbusTcpManager::startNext()
|
||||
{
|
||||
if (m_aborting || m_hasCurrentRequest || m_requests.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_currentRequest = m_requests.dequeue();
|
||||
m_hasCurrentRequest = true;
|
||||
m_connectAttempts = 0;
|
||||
ensureConnected();
|
||||
}
|
||||
|
||||
void ModbusTcpManager::ensureConnected()
|
||||
{
|
||||
if (m_aborting || !m_hasCurrentRequest) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureClient();
|
||||
if (m_client->state() == QModbusDevice::ConnectedState) {
|
||||
startCurrentRequest();
|
||||
return;
|
||||
}
|
||||
if (m_connecting) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_client->setConnectionParameter(
|
||||
QModbusDevice::NetworkAddressParameter,
|
||||
QVariant(m_config.host));
|
||||
m_client->setConnectionParameter(
|
||||
QModbusDevice::NetworkPortParameter,
|
||||
QVariant(m_config.port));
|
||||
m_client->setTimeout(m_config.timeoutMs);
|
||||
m_client->setNumberOfRetries(m_config.retryCount);
|
||||
|
||||
++m_connectAttempts;
|
||||
m_connecting = true;
|
||||
if (!m_client->connectDevice()) {
|
||||
setError(m_client->errorString(), error);
|
||||
return false;
|
||||
handleConnectionFailure(m_client->errorString());
|
||||
return;
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
|
||||
QObject::connect(m_client, &QModbusClient::stateChanged, &loop, [&](QModbusDevice::State state) {
|
||||
if (state == QModbusDevice::ConnectedState || state == QModbusDevice::UnconnectedState) {
|
||||
loop.quit();
|
||||
}
|
||||
});
|
||||
QObject::connect(m_client, &QModbusClient::errorOccurred, &loop, [&](QModbusDevice::Error) {
|
||||
loop.quit();
|
||||
});
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
|
||||
timer.start(m_config.timeoutMs);
|
||||
loop.exec();
|
||||
|
||||
if (!isConnected()) {
|
||||
QString text = m_client->errorString();
|
||||
if (text.isEmpty()) {
|
||||
text = "Modbus TCP connect timeout";
|
||||
}
|
||||
setError(text, error);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_lastErrorText.clear();
|
||||
return true;
|
||||
m_connectTimer->start(qMax(1, m_config.timeoutMs));
|
||||
}
|
||||
|
||||
void ModbusTcpManager::disconnectDevice()
|
||||
void ModbusTcpManager::startCurrentRequest()
|
||||
{
|
||||
if (m_client) {
|
||||
if (m_aborting || !m_hasCurrentRequest || m_connecting || m_reply) {
|
||||
return;
|
||||
}
|
||||
|
||||
QModbusDataUnit unit(
|
||||
static_cast<QModbusDataUnit::RegisterType>(
|
||||
m_currentRequest.registerType),
|
||||
m_currentRequest.address, 1);
|
||||
if (m_currentRequest.write) {
|
||||
unit.setValue(0, m_currentRequest.value);
|
||||
m_reply = m_client->sendWriteRequest(unit, m_config.serverAddress);
|
||||
} else {
|
||||
m_reply = m_client->sendReadRequest(unit, m_config.serverAddress);
|
||||
}
|
||||
|
||||
if (!m_reply) {
|
||||
finishCurrent(false, 0,
|
||||
m_client->errorString().isEmpty()
|
||||
? "Failed to create Modbus request"
|
||||
: m_client->errorString());
|
||||
return;
|
||||
}
|
||||
|
||||
connect(m_reply, &QModbusReply::finished,
|
||||
this, &ModbusTcpManager::onReplyFinished);
|
||||
}
|
||||
|
||||
void ModbusTcpManager::finishCurrent(bool success, quint16 value,
|
||||
const QString &error)
|
||||
{
|
||||
if (!m_hasCurrentRequest) {
|
||||
return;
|
||||
}
|
||||
|
||||
const Completion callback = m_currentRequest.callback;
|
||||
m_currentRequest = Request();
|
||||
m_hasCurrentRequest = false;
|
||||
if (!success) {
|
||||
setError(error);
|
||||
} else {
|
||||
m_lastErrorText.clear();
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
callback(success, value, error);
|
||||
}
|
||||
if (!m_aborting) {
|
||||
startNext();
|
||||
}
|
||||
}
|
||||
|
||||
void ModbusTcpManager::handleConnectionFailure(const QString &error)
|
||||
{
|
||||
if (m_aborting) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_connectTimer->stop();
|
||||
m_connecting = false;
|
||||
|
||||
if (m_client
|
||||
&& m_client->state() != QModbusDevice::UnconnectedState) {
|
||||
m_client->disconnectDevice();
|
||||
}
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::isConnected() const
|
||||
{
|
||||
return m_client && m_client->state() == QModbusDevice::ConnectedState;
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::readCoil(int address, bool *value, QString *error)
|
||||
{
|
||||
if (!value) {
|
||||
setError("Output value pointer is null", error);
|
||||
return false;
|
||||
const int attempts = qMax(1, m_config.reconnectAttempts + 1);
|
||||
if (m_connectAttempts < attempts) {
|
||||
QTimer::singleShot(
|
||||
qMax(0, m_config.reconnectDelayMs),
|
||||
this, &ModbusTcpManager::ensureConnected);
|
||||
return;
|
||||
}
|
||||
|
||||
quint16 rawValue = 0;
|
||||
if (!readSingleValue(QModbusDataUnit::Coils, address, &rawValue, error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*value = rawValue != 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::readHoldingRegister(int address, quint16 *value, QString *error)
|
||||
{
|
||||
if (!value) {
|
||||
setError("Output value pointer is null", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
return readSingleValue(QModbusDataUnit::HoldingRegisters, address, value, error);
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::writeCoil(int address, bool value, QString *error)
|
||||
{
|
||||
return writeSingleValue(QModbusDataUnit::Coils, address, value ? 1 : 0, error);
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::writeHoldingRegister(int address, quint16 value, QString *error)
|
||||
{
|
||||
return writeSingleValue(QModbusDataUnit::HoldingRegisters, address, value, error);
|
||||
}
|
||||
|
||||
QString ModbusTcpManager::lastErrorText() const
|
||||
{
|
||||
return m_lastErrorText;
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::readSingleValue(int registerType, int address, quint16 *value, QString *error)
|
||||
{
|
||||
if (address < 0) {
|
||||
setError("Modbus address must be greater than or equal to 0", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!connectDevice(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QModbusDataUnit unit(static_cast<QModbusDataUnit::RegisterType>(registerType), address, 1);
|
||||
QModbusReply *reply = m_client->sendReadRequest(unit, m_config.serverAddress);
|
||||
if (!reply) {
|
||||
setError(m_client->errorString(), error);
|
||||
return false;
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
|
||||
QObject::connect(reply, &QModbusReply::finished, &loop, &QEventLoop::quit);
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
|
||||
timer.start(m_config.timeoutMs);
|
||||
loop.exec();
|
||||
|
||||
if (!reply->isFinished()) {
|
||||
reply->deleteLater();
|
||||
setError("Modbus TCP read timeout", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (reply->error() != QModbusDevice::NoError) {
|
||||
const QString text = reply->errorString();
|
||||
reply->deleteLater();
|
||||
setError(text, error);
|
||||
return false;
|
||||
}
|
||||
|
||||
const QModbusDataUnit result = reply->result();
|
||||
if (result.valueCount() < 1) {
|
||||
reply->deleteLater();
|
||||
setError("Modbus TCP read returned empty result", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
*value = result.value(0);
|
||||
reply->deleteLater();
|
||||
m_lastErrorText.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ModbusTcpManager::writeSingleValue(int registerType, int address, quint16 value, QString *error)
|
||||
{
|
||||
if (address < 0) {
|
||||
setError("Modbus address must be greater than or equal to 0", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!connectDevice(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QModbusDataUnit unit(static_cast<QModbusDataUnit::RegisterType>(registerType), address, 1);
|
||||
unit.setValue(0, value);
|
||||
|
||||
QModbusReply *reply = m_client->sendWriteRequest(unit, m_config.serverAddress);
|
||||
if (!reply) {
|
||||
setError(m_client->errorString(), error);
|
||||
return false;
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
|
||||
QObject::connect(reply, &QModbusReply::finished, &loop, &QEventLoop::quit);
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
|
||||
timer.start(m_config.timeoutMs);
|
||||
loop.exec();
|
||||
|
||||
if (!reply->isFinished()) {
|
||||
reply->deleteLater();
|
||||
setError("Modbus TCP write timeout", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (reply->error() != QModbusDevice::NoError) {
|
||||
const QString text = reply->errorString();
|
||||
reply->deleteLater();
|
||||
setError(text, error);
|
||||
return false;
|
||||
}
|
||||
|
||||
reply->deleteLater();
|
||||
m_lastErrorText.clear();
|
||||
return true;
|
||||
finishCurrent(false, 0,
|
||||
error.isEmpty() ? "Failed to connect to PLC" : error);
|
||||
}
|
||||
|
||||
void ModbusTcpManager::ensureClient()
|
||||
@@ -246,13 +280,85 @@ void ModbusTcpManager::ensureClient()
|
||||
return;
|
||||
}
|
||||
|
||||
m_client = new QModbusTcpClient();
|
||||
m_client = new QModbusTcpClient(this);
|
||||
connect(m_client, &QModbusClient::stateChanged,
|
||||
this, &ModbusTcpManager::onStateChanged);
|
||||
connect(m_client, &QModbusClient::errorOccurred,
|
||||
this, &ModbusTcpManager::onErrorOccurred);
|
||||
}
|
||||
|
||||
void ModbusTcpManager::setError(const QString &text, QString *error)
|
||||
void ModbusTcpManager::setError(const QString &text)
|
||||
{
|
||||
m_lastErrorText = text;
|
||||
if (error) {
|
||||
*error = m_lastErrorText;
|
||||
}
|
||||
|
||||
void ModbusTcpManager::onStateChanged(QModbusDevice::State state)
|
||||
{
|
||||
if (m_aborting) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == QModbusDevice::ConnectedState) {
|
||||
m_connectTimer->stop();
|
||||
m_connecting = false;
|
||||
startCurrentRequest();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == QModbusDevice::UnconnectedState && m_connecting) {
|
||||
handleConnectionFailure(m_client ? m_client->errorString()
|
||||
: QString());
|
||||
}
|
||||
}
|
||||
|
||||
void ModbusTcpManager::onErrorOccurred(QModbusDevice::Error error)
|
||||
{
|
||||
Q_UNUSED(error)
|
||||
if (m_aborting) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_connecting) {
|
||||
handleConnectionFailure(m_client ? m_client->errorString()
|
||||
: QString());
|
||||
}
|
||||
}
|
||||
|
||||
void ModbusTcpManager::onReplyFinished()
|
||||
{
|
||||
QModbusReply *reply = qobject_cast<QModbusReply *>(sender());
|
||||
if (!reply || reply != m_reply) {
|
||||
if (reply) {
|
||||
reply->deleteLater();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
m_reply = nullptr;
|
||||
const bool success = reply->error() == QModbusDevice::NoError;
|
||||
quint16 value = 0;
|
||||
QString error;
|
||||
if (!success) {
|
||||
error = reply->errorString();
|
||||
} else if (!m_currentRequest.write) {
|
||||
const QModbusDataUnit result = reply->result();
|
||||
if (result.valueCount() < 1) {
|
||||
error = "Modbus read returned an empty result";
|
||||
} else {
|
||||
value = result.value(0);
|
||||
}
|
||||
}
|
||||
|
||||
reply->deleteLater();
|
||||
if (!error.isEmpty()) {
|
||||
finishCurrent(false, 0, error);
|
||||
return;
|
||||
}
|
||||
|
||||
finishCurrent(true, value, QString());
|
||||
}
|
||||
|
||||
void ModbusTcpManager::onConnectTimeout()
|
||||
{
|
||||
handleConnectionFailure("Modbus TCP connect timeout");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user