Hi guys, I need someone help to resolve my problem, I've created a program which connect with QtModbus via TCP to the server.
For prototype I use slave program created From qt which is connected on 127.0.0.1 port 502
with this code:
modbusDevice = new QModbusTcpClient(this);
modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, "127.0.0.1");
modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortParameter, 502);
if(!modbusDevice->connectDevice()){
ui->lbl_result->setText("Error");
return false;
}
modbusDevice = new QModbusTcpClient(this);
modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, "127.0.0.1");
modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortParameter, 502);
if(!modbusDevice->connectDevice()){
ui->lbl_result->setText("Error");
return false;
}
To copy to clipboard, switch view to plain text mode
The program continue so I suppose that connection work
next I need to Read a register, for example Holding Register at address 1 inside the device so I code:
QModbusDataUnit readUnit(QModbusDataUnit::HoldingRegisters, 1, 1);
if (auto *reply = modbusDevice->sendReadRequest(readUnit, 1)){
if (!reply->isFinished()){
connect(reply, &QModbusReply::finished, this, &MainWindow::show_result);
}else{
delete reply;
}
}else
ui->lbl_result->setText("Error");
return true;
QModbusDataUnit readUnit(QModbusDataUnit::HoldingRegisters, 1, 1);
if (auto *reply = modbusDevice->sendReadRequest(readUnit, 1)){
if (!reply->isFinished()){
connect(reply, &QModbusReply::finished, this, &MainWindow::show_result);
}else{
delete reply;
}
}else
ui->lbl_result->setText("Error");
return true;
To copy to clipboard, switch view to plain text mode
and the show_result function is:
void MainWindow::show_result(){
auto reply = qobject_cast<QModbusReply *>(sender());
if (!reply){
qDebug() << modbusDevice->errorString();
return;
}
if (reply->error() == QModbusDevice::NoError){
const QModbusDataUnit unit = reply->result();
int startAddress = unit.startAddress();
int value = unit.value(0);
qDebug() << startAddress + " valore: " + value;
}
else
ui->lbl_result->setText("Error");
reply->deleteLater();
}
void MainWindow::show_result(){
auto reply = qobject_cast<QModbusReply *>(sender());
if (!reply){
qDebug() << modbusDevice->errorString();
return;
}
if (reply->error() == QModbusDevice::NoError){
const QModbusDataUnit unit = reply->result();
int startAddress = unit.startAddress();
int value = unit.value(0);
qDebug() << startAddress + " valore: " + value;
}
else
ui->lbl_result->setText("Error");
reply->deleteLater();
}
To copy to clipboard, switch view to plain text mode
But always when this function was called, return an error in the first line: "Device is not connected"
How I can fix this, I try to check all example or someting but i not find error.
Thanks for your help and attention
Bookmarks