correct disconnect

This commit is contained in:
2025-07-04 03:37:30 +07:00
parent 868b770e0e
commit d11dcdd885
2 changed files with 4 additions and 1 deletions

View File

@@ -70,6 +70,7 @@ private:
QLabel* m_statusLabel{}; QLabel* m_statusLabel{};
int m_requestCounter; int m_requestCounter;
int m_responseCounter; int m_responseCounter;
bool m_disconnectRequested{false};
}; };
#endif // MAINWINDOW_H #endif // MAINWINDOW_H

View File

@@ -154,19 +154,21 @@ void MainWindows::onStateChanged(QModbusDevice::State state) {
void MainWindows::onConnectButtonClicked() { void MainWindows::onConnectButtonClicked() {
if (!m_connected) { if (!m_connected) {
m_disconnectRequested = false;
if (!m_modbusClient->connectDevice()) { if (!m_modbusClient->connectDevice()) {
QMessageBox::critical(this, tr("Connection Error"), QMessageBox::critical(this, tr("Connection Error"),
tr("Could not connect to the Modbus device!")); tr("Could not connect to the Modbus device!"));
} }
// Start connection timeout timer // Start connection timeout timer
QTimer::singleShot(m_connectTimeout, this, [this]() { QTimer::singleShot(m_connectTimeout, this, [this]() {
if (!m_connected) { if (!m_connected && !m_disconnectRequested) {
m_modbusClient->disconnectDevice(); m_modbusClient->disconnectDevice();
QMessageBox::warning(this, tr("Connection Timeout"), QMessageBox::warning(this, tr("Connection Timeout"),
tr("Connection attempt timed out!")); tr("Connection attempt timed out!"));
} }
}); });
} else { } else {
m_disconnectRequested = true;
m_modbusClient->disconnectDevice(); m_modbusClient->disconnectDevice();
} }
} }