End QSerialPort open attempt on timeout
-
Hi. I have the following code. My main concern is with function 3, sendConnectionVerification.
//attempts a connection with the next device in the list of available ports void DeviceConnection::connectDevice(){ serialPort_Controller->close(); portsAvailable = QSerialPortInfo::availablePorts(); qDebug() << "connecting"; qDebug() << portsAvailable.count(); QSerialPortInfo port; if (currentPosInList < portsAvailable.count()){ portName = portsAvailable.at(currentPosInList).portName(); setPort(portName); currentPosInList++; // serialPort_Controller->open(QIODevice::ReadWrite); sendConnectionVerification(ConnectMode::Connect); if (!serialPort_Controller->isOpen()){ qDebug() << "Cannot open controller serial port"; } } else{ currentPosInList = 0; } emit portAttempted(alreadySetup); } //Configure port void DeviceConnection::setPort(QString port){ qDebug() << port; portName = port; serialPort_Controller->setPortName(port); //My computer serialPort_Controller->setBaudRate(QSerialPort::Baud115200); serialPort_Controller->setDataBits(QSerialPort::Data8); serialPort_Controller->setParity(QSerialPort::NoParity); serialPort_Controller->setStopBits(QSerialPort::OneStop); serialPort_Controller->setFlowControl(QSerialPort::SoftwareControl); } //Send connection verification. If we get more modes, overhaul the logic. void DeviceConnection::sendConnectionVerification(int mode){ bool open = serialPort_Controller->open(QIODevice::ReadWrite); if(open){ //Add timeout qDebug() << "Connected"; serialPort_Controller->clear(QSerialPort::Output); //NOTE There is overlap of sending methods. Figure out how to combine them. if(mode == ConnectMode::Reconnect){ addToQueue(reconnectMessage); //NOTE Add logic that notifies user that the reconnection has failed } else{ qDebug() << "Sending message: " << connectMessage; serialPort_Controller->write(connectMessage.toUtf8()); } } else if (!open){ //int error = serialPort_Controller->error(); qDebug() << "Connection error"; if(mode == ConnectMode::Reconnect){ removePortName(portName); } } }
The idea is to open the serialPort, determine whether it returns, and make decisions based on whether the port is opened.
I am facing an issue where the code stays on the line
bool open = serialPort_Controller->open(QIODevice::ReadWrite);
for far too long, and I would like to find a way to timeout it.My first attempt was this:
//Send connection verification. If we get more modes, overhaul the logic. void DeviceConnection::sendConnectionVerification(int mode){ if(serialPort_Controller->open(QIODevice::ReadWrite) || serialPort_Controller->waitForReadyRead(2000)){ //Add timeout qDebug() << "Connected"; serialPort_Controller->clear(QSerialPort::Output); //NOTE There is overlap of sending methods. Figure out how to combine them. if(mode == ConnectMode::Reconnect){ addToQueue(reconnectMessage); //NOTE Add logic that notifies user that the reconnection has failed } else{ qDebug() << "Sending message: " << connectMessage; serialPort_Controller->write(connectMessage.toUtf8()); } } else{ //int error = serialPort_Controller->error(); qDebug() << "Connection error"; if(mode == ConnectMode::Reconnect){ removePortName(portName); } } }
This didn't work, which I'm guessing is because that waitForReadyRead doesn't have anything to do with opening the port, but has something to do with data being ready. My second attempt was this:
//Send connection verification. If we get more modes, overhaul the logic. void DeviceConnection::sendConnectionVerification(int mode){ QTimer *timeout = new QTimer(this); QTimer::singleShot(1000, this, &DeviceConnection::closeConnection); bool open = serialPort_Controller->open(QIODevice::ReadWrite); if(open){ //Add timeout qDebug() << "Connected"; serialPort_Controller->clear(QSerialPort::Output); //NOTE There is overlap of sending methods. Figure out how to combine them. if(mode == ConnectMode::Reconnect){ addToQueue(reconnectMessage); //NOTE Add logic that notifies user that the reconnection has failed } else{ qDebug() << "Sending message: " << connectMessage; serialPort_Controller->write(connectMessage.toUtf8()); } } else if (!open){ //int error = serialPort_Controller->error(); qDebug() << "Connection error"; if(mode == ConnectMode::Reconnect){ removePortName(portName); } } } //closes connection to device void DeviceConnection::closeConnection(){ serialPort_Controller->close(); }
This didn't work either, because closeConnection is only seemingly reached when
serialPort_Controller->open(QIODevice::ReadWrite)
is completed.Please let me know if more information is required.
-
Hi,
Which version of Qt are you using ?
On which OS ?
What kind of device are you using that blocks like that ? -
Hi,
Which version of Qt are you using ?
On which OS ?
What kind of device are you using that blocks like that ?@SGaist Hi.
This is Qt 5.15.2 on Windows 10. This is for a desktop application, so also Win10. Please let me know if more info is required.
-
@SGaist Hi.
This is Qt 5.15.2 on Windows 10. This is for a desktop application, so also Win10. Please let me know if more info is required.
@Dummie1138
Serial ports is not my area. But I think it is relevant that @SGaist asked you:What kind of device are you using that blocks like that ?
I believe you are saying that your
serialPort_Controller->open(QIODevice::ReadWrite)
statement blocks, under whatever circumstances, such that you want a timeout to "cancel" it, rather than it returning false immediately? I don't think we/Qt is expecting that behaviour? -
@Dummie1138
Serial ports is not my area. But I think it is relevant that @SGaist asked you:What kind of device are you using that blocks like that ?
I believe you are saying that your
serialPort_Controller->open(QIODevice::ReadWrite)
statement blocks, under whatever circumstances, such that you want a timeout to "cancel" it, rather than it returning false immediately? I don't think we/Qt is expecting that behaviour?@JonB For whatever reason, my
serialPort_Controller->open(QIODevice::ReadWrite)
can sometimes take a long time. When testing with the debugger, this line is stuck on for a long time.I have tested this code with this, which results in the timer being called only after the
serialPort_Controller->open(QIODevice::ReadWrite)
is completed. My conclusion with the results is that "open" seems to be blocking. If it isn't supposed to be blocking, please let me know.//attempts a connection with the next device in the list of available ports void DeviceConnection::connectDevice(){ serialPort_Controller->close(); portsAvailable = QSerialPortInfo::availablePorts(); //isValid qDebug() << "connecting"; qDebug() << portsAvailable.count(); QSerialPortInfo port; if (currentPosInList < portsAvailable.count()){ portName = portsAvailable.at(currentPosInList).portName(); qDebug() << "Port status " << portsAvailable.at(currentPosInList).isNull(); setPort(portName); currentPosInList++; sendConnectionVerification(ConnectMode::Connect); if (!serialPort_Controller->isOpen()){ qDebug() << "Cannot open controller serial port"; } } else{ currentPosInList = 0; } emit portAttempted(alreadySetup); } //Configure port void DeviceConnection::setPort(QString port){ qDebug() << port; portName = port; serialPort_Controller->setPortName(port); //My computer serialPort_Controller->setBaudRate(QSerialPort::Baud115200); serialPort_Controller->setDataBits(QSerialPort::Data8); serialPort_Controller->setParity(QSerialPort::NoParity); serialPort_Controller->setStopBits(QSerialPort::OneStop); serialPort_Controller->setFlowControl(QSerialPort::SoftwareControl); } //Send connection verification. If we get more modes, overhaul the logic. void DeviceConnection::sendConnectionVerification(int mode){ //Build timeout for serialPort_Controller->open(QIODevice::ReadWrite). Still doesn't work. qDebug() << "timer"; QTimer *timeout = new QTimer; //NOTE This thing has a bit of unexpected behavior since it has no parent timeout->setSingleShot(true); connect(timeout, &QTimer::timeout, this, &DeviceConnection::closeConnection); connect(timeoutThread, SIGNAL(started()), timeout, SLOT(start())); connect(timeoutThread, SIGNAL(finished()), timeout, SLOT(stop())); timeout->moveToThread(timeoutThread); timeout->setInterval(500); timeoutThread->start(); qDebug() << serialPort_Controller->isOpen(); if(serialPort_Controller->open(QIODevice::ReadWrite)){ //Add timeout //qDebug() << serialPort_Controller->isOpen(); qDebug() << "Connected"; timeoutThread->exit(); serialPort_Controller->clear(QSerialPort::Output); //NOTE There is overlap of sending methods. Figure out how to combine them. if(mode == ConnectMode::Reconnect){ addToQueue(reconnectMessage); //NOTE Add logic that notifies user that the reconnection has failed } else{ qDebug() << "Sending message: " << connectMessage; serialPort_Controller->write(connectMessage.toUtf8()); } } else if(!serialPort_Controller->waitForReadyRead(2000)){ //int error = serialPort_Controller->error(); qDebug() << "Connection error"; if(mode == ConnectMode::Reconnect){ removePortName(portName); } } disconnect(timeoutThread, SIGNAL(started()), timeout, SLOT(start())); disconnect(timeoutThread, SIGNAL(finished()), timeout, SLOT(stop())); } //closes connection to device void DeviceConnection::closeConnection(){ qDebug() << "close connection"; serialPort_Controller->close(); //portList.clear(); }
The output:
Port status false "COM10" DateTime before open QDateTime(2023-07-17 09:31:28.242 GMT Daylight Time Qt::LocalTime) false Connection error DateTime after open QDateTime(2023-07-17 09:31:35.455 GMT Daylight Time Qt::LocalTime) Cannot open controller serial port close connection
An example of a successful open:
Port status false "COM9" DateTime before open QDateTime(2023-07-17 10:03:31.243 GMT Daylight Time Qt::LocalTime) false Connected Sending message: "TOARM_VALCN_00000000_4C\r\n" DateTime after open QDateTime(2023-07-17 10:03:31.244 GMT Daylight Time Qt::LocalTime)
such that you want a timeout to "cancel" it, rather than it returning false immediately?
I would want it to return false immediately if possible, but that's the problem; sometimes it takes a while (over 10 seconds) for
serialPort_Controller->open(QIODevice::ReadWrite)
to return false and I don't know why. It seems to be dependent on what device the serial port is attempting to open to and I would like a way to either ensure it always returns immediately (which hasn't worked out), or, failing that, have a timeout that says "if you don't return something by 10 seconds, thisserialPort_Controller->open(QIODevice::ReadWrite)
should returnfalse
."Please let me know if more clarification is needed.
-
@JonB For whatever reason, my
serialPort_Controller->open(QIODevice::ReadWrite)
can sometimes take a long time. When testing with the debugger, this line is stuck on for a long time.I have tested this code with this, which results in the timer being called only after the
serialPort_Controller->open(QIODevice::ReadWrite)
is completed. My conclusion with the results is that "open" seems to be blocking. If it isn't supposed to be blocking, please let me know.//attempts a connection with the next device in the list of available ports void DeviceConnection::connectDevice(){ serialPort_Controller->close(); portsAvailable = QSerialPortInfo::availablePorts(); //isValid qDebug() << "connecting"; qDebug() << portsAvailable.count(); QSerialPortInfo port; if (currentPosInList < portsAvailable.count()){ portName = portsAvailable.at(currentPosInList).portName(); qDebug() << "Port status " << portsAvailable.at(currentPosInList).isNull(); setPort(portName); currentPosInList++; sendConnectionVerification(ConnectMode::Connect); if (!serialPort_Controller->isOpen()){ qDebug() << "Cannot open controller serial port"; } } else{ currentPosInList = 0; } emit portAttempted(alreadySetup); } //Configure port void DeviceConnection::setPort(QString port){ qDebug() << port; portName = port; serialPort_Controller->setPortName(port); //My computer serialPort_Controller->setBaudRate(QSerialPort::Baud115200); serialPort_Controller->setDataBits(QSerialPort::Data8); serialPort_Controller->setParity(QSerialPort::NoParity); serialPort_Controller->setStopBits(QSerialPort::OneStop); serialPort_Controller->setFlowControl(QSerialPort::SoftwareControl); } //Send connection verification. If we get more modes, overhaul the logic. void DeviceConnection::sendConnectionVerification(int mode){ //Build timeout for serialPort_Controller->open(QIODevice::ReadWrite). Still doesn't work. qDebug() << "timer"; QTimer *timeout = new QTimer; //NOTE This thing has a bit of unexpected behavior since it has no parent timeout->setSingleShot(true); connect(timeout, &QTimer::timeout, this, &DeviceConnection::closeConnection); connect(timeoutThread, SIGNAL(started()), timeout, SLOT(start())); connect(timeoutThread, SIGNAL(finished()), timeout, SLOT(stop())); timeout->moveToThread(timeoutThread); timeout->setInterval(500); timeoutThread->start(); qDebug() << serialPort_Controller->isOpen(); if(serialPort_Controller->open(QIODevice::ReadWrite)){ //Add timeout //qDebug() << serialPort_Controller->isOpen(); qDebug() << "Connected"; timeoutThread->exit(); serialPort_Controller->clear(QSerialPort::Output); //NOTE There is overlap of sending methods. Figure out how to combine them. if(mode == ConnectMode::Reconnect){ addToQueue(reconnectMessage); //NOTE Add logic that notifies user that the reconnection has failed } else{ qDebug() << "Sending message: " << connectMessage; serialPort_Controller->write(connectMessage.toUtf8()); } } else if(!serialPort_Controller->waitForReadyRead(2000)){ //int error = serialPort_Controller->error(); qDebug() << "Connection error"; if(mode == ConnectMode::Reconnect){ removePortName(portName); } } disconnect(timeoutThread, SIGNAL(started()), timeout, SLOT(start())); disconnect(timeoutThread, SIGNAL(finished()), timeout, SLOT(stop())); } //closes connection to device void DeviceConnection::closeConnection(){ qDebug() << "close connection"; serialPort_Controller->close(); //portList.clear(); }
The output:
Port status false "COM10" DateTime before open QDateTime(2023-07-17 09:31:28.242 GMT Daylight Time Qt::LocalTime) false Connection error DateTime after open QDateTime(2023-07-17 09:31:35.455 GMT Daylight Time Qt::LocalTime) Cannot open controller serial port close connection
An example of a successful open:
Port status false "COM9" DateTime before open QDateTime(2023-07-17 10:03:31.243 GMT Daylight Time Qt::LocalTime) false Connected Sending message: "TOARM_VALCN_00000000_4C\r\n" DateTime after open QDateTime(2023-07-17 10:03:31.244 GMT Daylight Time Qt::LocalTime)
such that you want a timeout to "cancel" it, rather than it returning false immediately?
I would want it to return false immediately if possible, but that's the problem; sometimes it takes a while (over 10 seconds) for
serialPort_Controller->open(QIODevice::ReadWrite)
to return false and I don't know why. It seems to be dependent on what device the serial port is attempting to open to and I would like a way to either ensure it always returns immediately (which hasn't worked out), or, failing that, have a timeout that says "if you don't return something by 10 seconds, thisserialPort_Controller->open(QIODevice::ReadWrite)
should returnfalse
."Please let me know if more clarification is needed.
@Dummie1138
Yes, we understand for you it takes 7 seconds to return false and you would want a timeout. Which (so far as I know)open()
does not offer.I assume you have nothing connected to COM10? I assume you would get this behaviour if you picked a different but empty com port?
You will have to await a Windows/serial/Qt expert to comment on whether this is expected behaviour or not.....
-
@Dummie1138
Yes, we understand for you it takes 7 seconds to return false and you would want a timeout. Which (so far as I know)open()
does not offer.I assume you have nothing connected to COM10? I assume you would get this behaviour if you picked a different but empty com port?
You will have to await a Windows/serial/Qt expert to comment on whether this is expected behaviour or not.....
@JonB COM10 is a bluetooth connection. At that moment, it is not connected to anything. COM9 is also a bluetooth connection. Please let me know if more info is required.
-
@JonB COM10 is a bluetooth connection. At that moment, it is not connected to anything. COM9 is also a bluetooth connection. Please let me know if more info is required.
@Dummie1138 My feeling is that you are looking for your keys where there is light and not where you lost them.
That time-out, which isn't all that high for a connection (network, wifi, bluetooth, etc.) is probably not due to the serial but to the bluetooth serial conversion.
My advice is that it's okay, or either to investigate the conversion, or to try on a real com port.
-
@Dummie1138 My feeling is that you are looking for your keys where there is light and not where you lost them.
That time-out, which isn't all that high for a connection (network, wifi, bluetooth, etc.) is probably not due to the serial but to the bluetooth serial conversion.
My advice is that it's okay, or either to investigate the conversion, or to try on a real com port.
@giusdbg
Not my area of expertise. But what time-out are you talking about? The OP's timings show that it takes 7 seconds forQSerialPort::open()
to return when, apparently, there is no device attached on the port. And during that time the code is blocked on that call. Is this normal? Would I, as a user, expect open serial port to take 7 seconds when nothing is there, and would I care that the UI will be blocked during this period? -
@giusdbg
Not my area of expertise. But what time-out are you talking about? The OP's timings show that it takes 7 seconds forQSerialPort::open()
to return when, apparently, there is no device attached on the port. And during that time the code is blocked on that call. Is this normal? Would I, as a user, expect open serial port to take 7 seconds when nothing is there, and would I care that the UI will be blocked during this period?@JonB open should be a blocking instand call and return. The OS should respond super quickly when the port can't be opened on request.
I have never, ever - in now 10 years - had the situation where open would not return immediately. Maybe once, where the complete OS crashed shortly after. But I also never had a Serial Over bluetooth link. Bluetooth handshake and service exchange does take a significant amount of time and may be the culprit here.
-
@JonB open should be a blocking instand call and return. The OS should respond super quickly when the port can't be opened on request.
I have never, ever - in now 10 years - had the situation where open would not return immediately. Maybe once, where the complete OS crashed shortly after. But I also never had a Serial Over bluetooth link. Bluetooth handshake and service exchange does take a significant amount of time and may be the culprit here.
@J-Hilk
Can you give the OP a command outside of his Qt program to show if the OS is taking a long time to open the port (so it's not a Qt issue)? For example, this might not work, but from a Command Prompt can you perhaps go something likecopy COM10 nul
and see that wait 7 seconds till it finishes? -
@J-Hilk
Can you give the OP a command outside of his Qt program to show if the OS is taking a long time to open the port (so it's not a Qt issue)? For example, this might not work, but from a Command Prompt can you perhaps go something likecopy COM10 nul
and see that wait 7 seconds till it finishes? -
@JonB you would need Putty or Hyperterminal or something similar and then the command depends on what the op chooses
@J-Hilk So, the way forward should be to test the COM port with a terminal to try and send data through? Or just test connections?
-
@J-Hilk So, the way forward should be to test the COM port with a terminal to try and send data through? Or just test connections?
@Dummie1138 yes, see if you also run into those timing issues with other already completed programs, I would also suggest updating drivers sometimes that fixes this too
-
@giusdbg
Not my area of expertise. But what time-out are you talking about? The OP's timings show that it takes 7 seconds forQSerialPort::open()
to return when, apparently, there is no device attached on the port. And during that time the code is blocked on that call. Is this normal? Would I, as a user, expect open serial port to take 7 seconds when nothing is there, and would I care that the UI will be blocked during this period?@JonB Those are not normal serial, they are bluethooth <-> serial converters (usually they are ethernet <-> serial).
When the serial port is opened, a series of conversion/connection operations are performed, which usually require a long timeout.
A test with Hyperterminal is a good idea
-
@Dummie1138 yes, see if you also run into those timing issues with other already completed programs, I would also suggest updating drivers sometimes that fixes this too
@J-Hilk I see. I shall do that then, thank you. However, I would still like to have a timeout for the serial port in case external users do not update their drivers and have bluetooth connections which take a long time. Would it be possible?
-
@J-Hilk I see. I shall do that then, thank you. However, I would still like to have a timeout for the serial port in case external users do not update their drivers and have bluetooth connections which take a long time. Would it be possible?
@Dummie1138 said in End QSerialPort open attempt on timeout:
Would it be possible?
In principle... yes. You could hook a timer to an interrupt or move your serialport in a thread and forcefully delete the QSerialPort instance while it's still busy with system calls.
That may or may not work and in general I would advice against it.
-
@Dummie1138 said in End QSerialPort open attempt on timeout:
Would it be possible?
In principle... yes. You could hook a timer to an interrupt or move your serialport in a thread and forcefully delete the QSerialPort instance while it's still busy with system calls.
That may or may not work and in general I would advice against it.
@J-Hilk What would be the issues that come form this approach?
-
@J-Hilk I see. I shall do that then, thank you. However, I would still like to have a timeout for the serial port in case external users do not update their drivers and have bluetooth connections which take a long time. Would it be possible?
@Dummie1138
You might move the serial port to a thread and do theopen()
there. (I believe you can move it back to another thread if you want.) That would mean the call would only block that thread, not the UI.(Personally) I would not try to destroy the port object while it is executing an
open()
. It probably won't abort it anyway, and likely leave things in a bad state.