QtSerialPort and CPU usage



  • Hi

    I wrote simple application that reads and writes data from serial device. For some reason after sending and receiving just single packet, my application uses 100% of cpu time. The send-button in application still works (at least for some time) and I still can send and receive data, but otherwise the UI gets sluggish and stops working properly.

    Sometimes sending second packet clears the situation. Sometimes application works normally for hundred messages or so.

    I took the QtSerialPort from git yesterday and I compiled it with nmake. I'm using QtCreator 2.4.1 and Qt 4.8.0 on win7 64.

    I'm using "ATEN usb to serial bridge" to connect to the serial device. Connection settings are 19200 / no parity / one stop bit.

    When mainwindow is created:
    @
    sp = new SerialPort();

    connect(sp,SIGNAL(readyRead()), this, SLOT(readyRead()));
    @

    When connect is clicked
    @void MainWindow::on_connectButton_clicked()
    {
    qDebug()<< "on_connectButton_clicked";
    if (!connected)
    {
    QIODevice::OpenMode mode = QIODevice::ReadWrite;

        sp->setPort(ui->comCB->currentText()); // e.g. COM13
    
        if (sp->open(mode))
        {
            ..setup other connection settings from ui here
            // Set new settings
            if (sp->setRate(rate) &&
                sp->setDataBits(SerialPort::Data8) &&
                sp->setParity(parity) &&
                sp->setStopBits(stopBits) &&
                sp->setFlowControl(SerialPort::NoFlowControl))
            {
                ui->console->appendPlainText("Connection settings set successfully");
               
                connected = true;
                ui->connectButton->setText("Close");
            }
            else
            {
                ui->console->appendPlainText("Setting connection settings FAILED!");
            }
        }
        else
        {
            ui->console->appendPlainText("Opening COM port FAILED!");
        }
    }
    else
    {
        sp->close();
        connected = false;
        ui->connectButton->setText("Connect");
    }
    

    }@

    When sending data (here I just tested taking the data in to member variable, previously I used the 'data' directly):
    @void MainWindow::send(QByteArray data)
    {
    delete iSendBuf;
    iSendBuf = NULL;

    iSendBuf = new QByteArray(data);
    
    if (sp->write(*iSendBuf))
    {
        qDebug() << "Wrote data.";
    }
    else
    {
        qDebug() << "Write FAILED.";
    }
    

    }@

    And receiving data:
    @void MainWindow::readyRead()
    {
    QString str;
    QByteArray* bytes = new QByteArray(sp->readAll());

    qDebug()<< "readyRead - len: " + QString::number(bytes->length());
    
    if (ui->showAsHexCHB->isChecked())
    {
        str = fromArray(*bytes); // converts bytes to hex string
    }
    else
    {
        str.append(*bytes);
    }
    
    ui->console->appendPlainText("Received: "+str);
    delete bytes;
    

    }@

    Any ideas? I'm doing something wrong?

    Dolbyz



    1. What about the bytes Array, is it zero terminated? 2. You may want to put a debug message into each send and readyRead function to figure out where the application hangs. 3. Comment out each line of code until you get it.

    2. In Addition you could connect the serialPort with the Mainwindow asynchronous, using Qt::QueuedConnection, since there might be another thread working than the MainWindow thread (using QThread::currentThreadId() shows the current context's thread id).

    3. Besides, it is not advisable to write from an external thread into the UI nor read the data buffered from another thread without synching the threads as you did in readyByte as this can cause a reace condition. (Maybe I am wrong and someone can do this with QtSp.)



  • bq. I’m doing something wrong?

    Maybe this wrong:

    @
    ...
    iSendBuf = new QByteArray(data);
    ...
    QByteArray* bytes = new QByteArray(sp->readAll());
    @

    No need to call operator new().

    It is possible that your "ATEN usb to serial bridge" has a bad driver, try check on any other chip, such as FTDI or Prolific, but it's better - the "native" serial port on the motherboard (if available).



  • 2 franku,

    bq. What about the bytes Array, is it zero terminated?

    So what?

    bq. Besides, it is not advisable to write from an external thread into the UI nor read the data buffered from another thread without synching the threads as you did in readyByte as this can cause a reace condition. (Maybe I am wrong and someone can do this with QtSp.)

    Why are external threads? Here, they are not needed.



  • 1.) run in debug mode and stop execution a few times. Usually you land in the problematic section when having problems like these. (You'll need the debug version of your serial library to find the problem inside it though).

    2.) profile your application with valgrind and find out where the CPU-eater is.



  • I'll check do I have other usb to serial bridge-cables(on monday when I get back to work). I have only a laptop and it does not have any "native" serial ports.

    My program is really simple. It has only the mainwindow-class which contains all the code. I don't have there anything that could cause this cpu usage. I yesterday added debug prints to all slots (and other methods) in my program + I added prints also to QtSerialPort (all methods and to all while-loops). No prints were coming when cpu usage was 100%.

    I'm using windows so I can't use valgrind. I'll have to check it with debugger, but I would need debug versions of the windows dll's used in serial port connections?

    I'm actually developing something in embedded device with c which uses serial port. Purpose of this Qt application was just to send few "hardcoded" messages (at least for now) to check the functionality and response messages.

    Thanks for the advices.



  • QByteArray may not be zero terminated - forget this.

    Some ideas, try harder to figure out where actually the cpu time is consumed. We can only see the code you've applied but in my opinion you should look into the send signal and (more possible) the receive slot. Try to remove the lines from the above code until it stops hanging. Maybe it is hanging in some procedure you don't have the code for and you don't see the while loop where it is cycling. You may also look into the rest of your code, sometimes someone programs a recursive statement unintended especially when you filled up everything into a single class.

    good look!



  • 2Dolbyz,

    Previously had a similar problem with the CPU load, using the USB / Serial converter chip Prolific. The problem was that in a false fire notifier QWinEventNotifier at data receiving. Presumably the reason is the driver, although it is difficult to say. Previously, I seems to be fixed this problem, though .. I try will check again.



  • My colleague found another usb-to-serial cable (USB-SERIAL CH340 wch.cn). It works perfectly.

    When I debugged with the old cable it seemed to loop in qevendispatcher_win.cpp:770 for loop. With the old cable I got from two to eight readyRead-signals (message length about 16 bytes). With this "new" cable, just single signal with whole data.

    Thanks for your help.



  • Please try to fix the code in the source code library QtSerialPort to test, as described "here":https://bugreports.qt-project.org/browse/QTPLAYGROUND-2 and take there is an example of an "attached":https://bugreports.qt-project.org/secure/attachment/28890/TestSerial.zip for testing.



  • I tried this fix. The problem still occurs. I used my own code for testing.

    For second try I put debug print to that event-function. I guess it was called "few" times, because then qt creator jammed too :)



  • Bad bad bad. I do not have ideas how to fix it.



  • UPD: Please try repeat test with new test tool "CpuUsageTester":https://bugreports.qt-project.org/secure/attachment/28899/CpuUsageTester.zip



  • It works exactly same way with this test application.



  • Clear, thx

    So, most likely a problem in the drivers.



  • 2 Dolbyz,

    Please check CPU load with a new concept from "here":https://codereview.qt-project.org/#change,32186

    PS: If you have free time.



  • I'll try to test during this week.



  • With this version I could not reproduce the 100% CPU usage-bug.

    At least previously it happened almost immediately. Now I tried for some time, but no issues.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.