learner learner - 1 year ago 115
C++ Question

QSocketnotifier does not work on windows for serialport reading?

I am developing an application which reads data from the device (Microcontroller) connected on SerialPort of Windows 7 and display all read data into the Qt based UI application.

Qt: Qt 5.6.0
OS: Windows 7

Before implementing the continious reading from the Windows Serial port. I implemented a test application to read data from Serial port on button press (Some button in Qt GUI) using QSerialPort Class and it worked properly.

So I started implementing the continious reading from the device connected at serial port example:
1. Connect PushButton Press. Connect to the Device.
2. Start Push Button Press. Start Reading.
3. Stop Push Button Press. Stop Reading.

Here my code is same as like my test application but for continious reading. I implemented the QSocketNotifier functionality when I connect to the Device (Connect Push Button press). Below is the code for the same:

bool Test::openPort()
bool result = false;

//SerialPortManager: Class to Open, Read, Write to the device connected at Serial Port
if(serialPortManager != NULL)
result = serialPortManager->open(); // Returns TRUE

//socketNotifier pointer defined in TestClass.h file
socketNotifier = new QSocketNotifier(serialPortManager->getSerialPortFileDescriptor(), QSocketNotifier::Read);
connect(socketNotifier , SIGNAL(activated(int)), this, SLOT(onReadData()));

socketNotifier ->setEnabled(true);

return result ;

qint32 SerialPortManager::getSerialPortFileDescriptor()
int readFileDescriptor = _open_osfhandle((qintptr)serialPort.handle(), _O_RDONLY | _O_WRONLY);

return readFileDescriptor;
//return (qintptr)serialPort.handle();

where QSerialPort serialPort; is public variable defined in Class Header File.

Here Problem is SLOT onReadData() which is connected to the SocketNotifier is never get called. It looks like to me that the activated(int) signal is never emitted.

I did some google and on one link I found that QSocketNotifier does not work for SerialPort reading on Windows. Since the link is very old So wanted to confirm.

Please advise what I am doing wrong?


Answer Source

You don't need to use QSocketNotifier with serial ports in Qt.

QSerialPort inherits from QIODevice, so you can connect its signal readyRead() to your slot onReadData.

On Windows, QSocketNotifier seems to only work with sockets, because it uses a WinSock2 function internally. For other Window handles, you could use QWinEventNotifier (QSerialPort has a similar private class QWinOverlappedIoNotifier).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download