PDA

View Full Version : QtModbus Help



facste
18th July 2019, 21:28
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::NetworkAddre ssParameter, "127.0.0.1");
modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortP arameter, 502);
if(!modbusDevice->connectDevice()){
ui->lbl_result->setText("Error");
return false;
}

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;


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();
}


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

anda_skoa
19th July 2019, 10:29
Are you making sure that you call the read function only after the device object has signalled it is in connected state?

Cheers,
_

facste
20th July 2019, 15:05
I hope yes but... I try to check modbusDevice->state(); and in effect it is afer connection in QModbusDevice::ConnectingState. Maybe i need other instruction for connection, or maybe there is a problem in localhost slave?

Thanks for reply!