Unsolved Adding custom ID String to Signal/Slot Event?
-
Hallo,
I have a Problem with QModbusServer. I want to pass an custom Identification string for every ModbusServer Instance.
void QModbusManager::onServerAddClick() { QModbusServer* device = new QModbusTcpServer(this); QModbusDataUnitMap reg; reg.insert(QModbusDataUnit::Coils, { QModbusDataUnit::Coils,0,20 }); reg.insert(QModbusDataUnit::DiscreteInputs, { QModbusDataUnit::DiscreteInputs,0,20 }); reg.insert(QModbusDataUnit::InputRegisters, { QModbusDataUnit::InputRegisters,0,20 }); reg.insert(QModbusDataUnit::HoldingRegisters, { QModbusDataUnit::HoldingRegisters,0,20 }); device->setMap(reg); auto name = this->ui.tb_servername->text(); connect(device, &QModbusServer::dataWritten, this, [&](QModbusDataUnit::RegisterType type, int address, int size) { this->DataWrittenCallback(name, type, address, size); }); //connect(device, &QModbusServer::dataWritten, this, &QModbusManager::DataWrittenCallbacktest); connect(device, &QModbusServer::errorOccurred, this, [&](QModbusDevice::Error error) { this->ErrorCallback(name, error); }); //Setting UP IP auto m = ui.lv_interfaces->currentIndex(); auto ip = m.data(Qt::DisplayRole).toString(); device->setServerAddress(1); device->setConnectionParameter(QModbusDevice::NetworkAddressParameter, ip); device->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->ui.tb_port->text()); QPair<QModbusServer*, QString> p(device, this->ui.tb_target->text()); this->deviceMap.insert(name, p); device->connectDevice(); this->setupTabPage(name); }
When I click Add Server. It registers the Server Name and in the deviceMap there is the correct name. But when the Event is invoked name = ??? (Debugger Visual Studio 2019). Why does it forget the value?
My Intention is to add a Sender Information like in C# Winforms eventcallback(object sender, EventArgs e) or POCO C++ eventCallback(void* sender, EventArgs& arg)
-
Hi
it seems
auto name = this->ui.tb_servername->text();
is a local variable and you seems to capture it by referene so when
onServerAddClick ends, its no longer valid. (and dataWritten fires much later)
Try
connect(device, &QModbusServer::dataWritten, this, [=] -
Thanks,
my bad, I misinterpreted the & inside the brackets. I thought [&] were for the lazies meaning include everything. Now I know it is = for values.
If you wonder why I need multiple Modbus Servers It shall be a Modbus to UDP JSON connector.
-
@SeppyQT
np :)
I shot my foot of a few times capturing locals by reference.