我写了QModbus主站的程序,下位机是别人的modbus从机设备,我用标志位实现定时重连。
每次从机重启后(相当于断网),我的程序过很久才能重连上,但是用modbus助手可以很快地连接,请问我的代码哪里有问题呢?
QString strText= ui->mConBtn->text();
if(strText == QStringLiteral("连接"))//**若点击了连接按钮
{
//Modbus TCP
//new 主站对象
master = new QModbusTcpClient();
//走的网络,设置IP与端口
master->setConnectionParameter(
QModbusDevice::NetworkAddressParameter, ui->mIP_COM->text() );
master->setConnectionParameter(
QModbusDevice::NetworkPortParameter, ui->m_Port->text().toUInt() );
//**设置连接超时时间50ms
master->setTimeout(50);
//失败后禁用重发
master->setNumberOfRetries(0);
//连接信号槽
connect(master, &QModbusDevice::stateChanged ,this ,[this]()
{
//成连接状态了
if(master->state() == QModbusDevice::ConnectedState)
{
ui->mConBtn->setText(QStringLiteral("断开"));
ui->statusbar->showMessage("Connect Success!",3000);
Flag_Connect=1;//已连接了
qDebug()<<"设备已连接了";
}
else
{
ui->mConBtn->setText(QStringLiteral("连接"));
Flag_Connect=0;//已断开了
qDebug()<<"设备已断开了";
}
});
// 设备发生错误时信号、槽
connect(master, &QModbusClient::errorOccurred, [this](QModbusDevice::Error)
{
statusBar()->showMessage(master->errorString(), 3000);
ui->mConBtn->setText(QStringLiteral("连接"));
Flag_Connect=0;//已断开了
qDebug()<<"设备已断开了";
});
//连接设备
master->connectDevice();
//打开定时轮询的定时器
Timer->setTimerType(Qt::PreciseTimer);
Timer->setInterval(500);
Timer->start();
connect(Timer, &QTimer::timeout, this, [=]()
{
qDebug()<<"MODBUS TCP定时器在运行";
qDebug()<<"Flag_Connect"<<Flag_Connect;
//发现问题,大概要50s-60s才能重连上? 但是我用modbus助手,10s左右就能重连
if(Flag_Connect==0)
{master->connectDevice();qDebug()<<"触发一次MODBUS TCP重连";return;}
else if(Flag_Connect==1)
{}
});
}
else
{
if(master)
{
//断开连接
master->disconnectDevice();
delete master;
master = nullptr;
}
}