Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. End QSerialPort open attempt on timeout
Forum Updated to NodeBB v4.3 + New Features

End QSerialPort open attempt on timeout

Scheduled Pinned Locked Moved Unsolved General and Desktop
19 Posts 5 Posters 1.2k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • SGaistS SGaist

    Hi,

    Which version of Qt are you using ?
    On which OS ?
    What kind of device are you using that blocks like that ?

    Dummie1138D Offline
    Dummie1138D Offline
    Dummie1138
    wrote on last edited by
    #3

    @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.

    JonBJ 1 Reply Last reply
    0
    • Dummie1138D Dummie1138

      @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.

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by
      #4

      @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?

      Dummie1138D 1 Reply Last reply
      0
      • JonBJ JonB

        @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?

        Dummie1138D Offline
        Dummie1138D Offline
        Dummie1138
        wrote on last edited by Dummie1138
        #5

        @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, this serialPort_Controller->open(QIODevice::ReadWrite) should return false."

        Please let me know if more clarification is needed.

        JonBJ 1 Reply Last reply
        0
        • Dummie1138D Dummie1138

          @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, this serialPort_Controller->open(QIODevice::ReadWrite) should return false."

          Please let me know if more clarification is needed.

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by
          #6

          @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.....

          Dummie1138D 1 Reply Last reply
          1
          • JonBJ JonB

            @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.....

            Dummie1138D Offline
            Dummie1138D Offline
            Dummie1138
            wrote on last edited by
            #7

            @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.

            87acee0e-480c-4b6a-a18e-f7a3820a47e6-image.png

            G 1 Reply Last reply
            0
            • Dummie1138D Dummie1138

              @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.

              87acee0e-480c-4b6a-a18e-f7a3820a47e6-image.png

              G Offline
              G Offline
              giusdbg
              wrote on last edited by
              #8

              @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.

              JonBJ 1 Reply Last reply
              0
              • G giusdbg

                @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.

                JonBJ Offline
                JonBJ Offline
                JonB
                wrote on last edited by
                #9

                @giusdbg
                Not my area of expertise. But what time-out are you talking about? The OP's timings show that it takes 7 seconds for QSerialPort::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?

                J.HilkJ G 2 Replies Last reply
                0
                • JonBJ JonB

                  @giusdbg
                  Not my area of expertise. But what time-out are you talking about? The OP's timings show that it takes 7 seconds for QSerialPort::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?

                  J.HilkJ Offline
                  J.HilkJ Offline
                  J.Hilk
                  Moderators
                  wrote on last edited by J.Hilk
                  #10

                  @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.


                  Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                  Q: What's that?
                  A: It's blue light.
                  Q: What does it do?
                  A: It turns blue.

                  JonBJ 1 Reply Last reply
                  0
                  • J.HilkJ J.Hilk

                    @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.

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by JonB
                    #11

                    @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 like copy COM10 nul and see that wait 7 seconds till it finishes?

                    J.HilkJ 1 Reply Last reply
                    0
                    • JonBJ JonB

                      @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 like copy COM10 nul and see that wait 7 seconds till it finishes?

                      J.HilkJ Offline
                      J.HilkJ Offline
                      J.Hilk
                      Moderators
                      wrote on last edited by
                      #12

                      @JonB you would need Putty or Hyperterminal or something similar and then the command depends on what the op chooses


                      Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                      Q: What's that?
                      A: It's blue light.
                      Q: What does it do?
                      A: It turns blue.

                      Dummie1138D 1 Reply Last reply
                      1
                      • J.HilkJ J.Hilk

                        @JonB you would need Putty or Hyperterminal or something similar and then the command depends on what the op chooses

                        Dummie1138D Offline
                        Dummie1138D Offline
                        Dummie1138
                        wrote on last edited by
                        #13

                        @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.HilkJ 1 Reply Last reply
                        0
                        • Dummie1138D Dummie1138

                          @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.HilkJ Offline
                          J.HilkJ Offline
                          J.Hilk
                          Moderators
                          wrote on last edited by
                          #14

                          @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


                          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                          Q: What's that?
                          A: It's blue light.
                          Q: What does it do?
                          A: It turns blue.

                          Dummie1138D 1 Reply Last reply
                          0
                          • JonBJ JonB

                            @giusdbg
                            Not my area of expertise. But what time-out are you talking about? The OP's timings show that it takes 7 seconds for QSerialPort::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?

                            G Offline
                            G Offline
                            giusdbg
                            wrote on last edited by giusdbg
                            #15

                            @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

                            1 Reply Last reply
                            0
                            • J.HilkJ J.Hilk

                              @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

                              Dummie1138D Offline
                              Dummie1138D Offline
                              Dummie1138
                              wrote on last edited by
                              #16

                              @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.HilkJ JonBJ 2 Replies Last reply
                              0
                              • Dummie1138D Dummie1138

                                @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.HilkJ Offline
                                J.HilkJ Offline
                                J.Hilk
                                Moderators
                                wrote on last edited by
                                #17

                                @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.


                                Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                Q: What's that?
                                A: It's blue light.
                                Q: What does it do?
                                A: It turns blue.

                                Dummie1138D 1 Reply Last reply
                                0
                                • J.HilkJ J.Hilk

                                  @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.

                                  Dummie1138D Offline
                                  Dummie1138D Offline
                                  Dummie1138
                                  wrote on last edited by
                                  #18

                                  @J-Hilk What would be the issues that come form this approach?

                                  1 Reply Last reply
                                  0
                                  • Dummie1138D Dummie1138

                                    @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?

                                    JonBJ Offline
                                    JonBJ Offline
                                    JonB
                                    wrote on last edited by JonB
                                    #19

                                    @Dummie1138
                                    You might move the serial port to a thread and do the open() 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.

                                    1 Reply Last reply
                                    1

                                    • Login

                                    • Login or register to search.
                                    • First post
                                      Last post
                                    0
                                    • Categories
                                    • Recent
                                    • Tags
                                    • Popular
                                    • Users
                                    • Groups
                                    • Search
                                    • Get Qt Extensions
                                    • Unsolved