Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a signal when a USB serial cable is unplugged

Is there a way to send a signal, or any other way to tell if a USB serial cable is unplugged, using Qt?

like image 939
Jared Price Avatar asked Sep 27 '13 20:09

Jared Price


3 Answers

You could use the error signal of the QSerialPort class in the QtSerialPort add-on. See the details for that in our documentation.

http://qt-project.org/doc/qt-5.1/qtserialport/qserialport.html#error-prop

You will need to write this basically:

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

...

void MyClass::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        QMessageBox::critical(this, tr("Critical Error"), serial->errorString());
        closeSerialPort();
    }
}

QtSerialPort can be installed easily with Qt 5.1 < as the packages are distributed. However, we have made sure QtSerialPort works with prior versions, including Qt 4.8.X. Here you can find the instructions for Qt 4 to get this installed for you:

  • git clone [email protected]:qt/qtserialport.git

  • cd qtserialport

  • qmake

  • make

  • sudo make install.

Then, you will need the following lines in your qmake project file if you happen to use qmake:

Qt 5: QT += serialport
Qt 4: COMFIG += serialport
like image 139
lpapp Avatar answered Nov 20 '22 01:11

lpapp


Using QSerialPortInfo will achieve the result:

bool MyClass::checkPort()
{
    QSerialPortInfo *portInfo = new QSerialPortInfo(ui->serialDevice->currentText());
    // ui->serialDevice being a combobox of available serial ports

    if (portInfo->isValid())
    {
        return true;
    }
    else
    {
        return false;
    }
}
like image 37
Jared Price Avatar answered Nov 20 '22 02:11

Jared Price


isValid() is now obsolete. isBusy() can be used instead as it will return true when you have opened the port and false when the port is no longer there (and you still have it open). This is also the case when availablePorts() keeps returning the non-existent, but opened port, because you are keeping the port in the list by having it opened.

like image 41
Stig Hornang Avatar answered Nov 20 '22 00:11

Stig Hornang