0

I have a bidirectional communication through the serial port.

MyClass::MyClass(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    //setUp 

    connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
           SLOT(handleError(QSerialPort::SerialPortError)));
}

void MyClass::handleError(QSerialPort::SerialPortError error)
{ 
  //show error
  //close connection
}

void MyClass::send(QString data)
{
    if(!data.endsWith('\r'))
        data.append('\r');

    //should be like this:
    serial->write(data.toLocal8Bit()); 
    serial->waitForBytesWritten(TIMEOUT);


    //or this?
    if( serial->write(data.toLocal8Bit()) < 0 )
        emit serial->error(QSerialPort::WriteError);    

    if(!serial->waitForBytesWritten(TIMEOUT))
        emit serial->error(QSerialPort::TimeoutError);

}

void MyClass::receive(char &dest, int size)
{
    //similar to send
}

Namely, handleError will automatically handle the Serial Port Errors or should I detect & throw them?

Which of the 2 ways is more correct? Or none of them is correct?

anat0lius
  • 2,145
  • 6
  • 33
  • 60

1 Answers1

0

This:

if (serial->write(data.toLocal8Bit()) < 0 )
    emit serial->error(QSerialPort::WriteError);  

is wrong, since the QSerialPort class already emits the signal, why do you want to do it yourself?

You should both handle the error signal that the QSerialPort emits, and handle any immediate errors returned by the write, read and other methods. You need to handle the signal because the reading and writing happens asynchronously. A write that "succeeds" and returns the number of bytes you intended, does simply mean that the device was open and was in a "usable" state at the moment. The actual write happens in the background and may fail at any time.

The simple, and correct thing to do, is to have a state machine that implements the communications protocol you're after. The state machine framework is there to help you.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313