QString MainWindow::serialErrorString() const
{
    QSerialPort* serial = qobject_cast<QSerialPort*>(_ioDevice);
    switch(serial->error())
    {
        case QSerialPort::NoError:
            return "no error";
        case QSerialPort::DeviceNotFoundError:
            return "device not found";
        case QSerialPort::PermissionError:
            return "permission error";
        case QSerialPort::OpenError:
            return "device is already opened";
        case QSerialPort::FramingError:
            return "framing error";
        case QSerialPort::ParityError:
            return "parity error";
        case QSerialPort::BreakConditionError:
            return "break condition error";
        case QSerialPort::ReadError:
            return "read error";
        case QSerialPort::WriteError:
            return "write error";
        case QSerialPort::UnsupportedOperationError:
            return "unsupported operation error";
        case QSerialPort::UnknownError:
        default:
            return "unknown error";
    }
}
Ejemplo n.º 2
0
void ConnectionThread::run()
{
    if(stepByStep)
        sendNextCommand = false;
    else
        sendNextCommand = true;

    QSerialPort serial;
    serial.setPortName(portName);
    if (!serial.open(QIODevice::ReadWrite))
    {
        emit error(tr("Can't open %1, error code %2").arg(portName).arg(serial.error()));
        return;
    }

    while (!quit) {
        if(stepByStep)
        {
            while(!sendNextCommand);
            mutex.lock();
            sendNextCommand = false;
            mutex.unlock();
        }
        // Envoi microcommande
        serial.write(test->recupProchaineMicrocommande().c_str());
        if(!serial.waitForBytesWritten(waitTimeout))
        {
            emit timeout(tr("Wait write microcommande timeout %1").arg(QTime::currentTime().toString()));
        }
        //Accusé de reception
        if(serial.waitForReadyRead(waitTimeout))
        {
            QByteArray received = serial.readAll();
            if(received.toStdString().compare(COMMANDE_RECEIVED) != 0)
            {
                emit error("Not wanted response");
            }
        }
        else
        {
            emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
        }
        //Pret a recevoir prochaine commande
        if(serial.waitForReadyRead(waitTimeout))
        {
            QByteArray received = serial.readAll();
            if(received.toStdString().compare(READY_FOR_NEXT_COMMAND) != 0)
            {
                emit error("Not wanted response");
            }
        }
        else
        {
            emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
        }
    }
}
Ejemplo n.º 3
0
QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    QCoreApplication coreApplication(argc, argv);
    int argumentCount = QCoreApplication::arguments().size();
    QStringList argumentList = QCoreApplication::arguments();

    QTextStream standardOutput(stdout);

    if (argumentCount == 1) {
        standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
        return 1;
    }

    QSerialPort serialPort;
    QString serialPortName = argumentList.at(1);
    serialPort.setPortName(serialPortName);

    int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
    serialPort.setBaudRate(serialPortBaudRate);

    if (!serialPort.open(QIODevice::ReadOnly)) {
        standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.error()) << endl;
        return 1;
    }

    QByteArray readData = serialPort.readAll();
    while (serialPort.waitForReadyRead(5000))
        readData.append(serialPort.readAll());

    if (serialPort.error() == QSerialPort::ReadError) {
        standardOutput << QObject::tr("Failed to read from port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    } else if (serialPort.error() == QSerialPort::TimeoutError && readData.isEmpty()) {
        standardOutput << QObject::tr("No data was currently available for reading from port %1").arg(serialPortName) << endl;
        return 0;
    }

    standardOutput << QObject::tr("Data successfully received from port %1").arg(serialPortName) << endl;
    standardOutput << readData << endl;

    return 0;
}
Ejemplo n.º 4
0
 void onRxData() {
    if (m_port.bytesAvailable() < 9) return;
    if (m_port.error() != QSerialPort::NoError)
       return;
    if (! check(m_port.peek(9)))
       return setIoStatus(ChecksumError);
    uint8_t dummy;
    m_str >> m_address >> dummy >> m_status >> dummy >> m_value;
    setIoStatus(Ok);
 }
Ejemplo n.º 5
0
void SlaveThread::run()
{
    bool currentPortNameChanged = false;

    mutex.lock();
    QString currentPortName;
    if (currentPortName != portName) {
        currentPortName = portName;
        currentPortNameChanged = true;
    }

    int currentWaitTimeout = waitTimeout;
    QString currentRespone = response;
    mutex.unlock();

    QSerialPort serial;

    while (!quit) {

        if (currentPortNameChanged) {
            serial.close();
            serial.setPortName(currentPortName);

            if (!serial.open(QIODevice::ReadWrite)) {
                emit error(tr("Can't open %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }
        }

        if (serial.waitForReadyRead(currentWaitTimeout)) {

            // read all request
            QByteArray requestData = serial.readAll();
            while (serial.waitForReadyRead(10))
                requestData += serial.readAll();

            // write all response
            QByteArray responseData = currentRespone.toLocal8Bit();
            serial.write(responseData);
            if (serial.waitForBytesWritten(waitTimeout)) {
                QString request(requestData);
                emit this->request(request);
            } else {
                emit timeout(tr("Wait write response timeout %1")
                             .arg(QTime::currentTime().toString()));
            }
        } else {
            emit timeout(tr("Wait read request timeout %1")
                         .arg(QTime::currentTime().toString()));
        }

        mutex.lock();
        if (currentPortName != portName) {
            currentPortName = portName;
            currentPortNameChanged = true;
        } else {
            currentPortNameChanged = false;
        }
        currentWaitTimeout = waitTimeout;
        currentRespone = response;
        mutex.unlock();
    }
}
Ejemplo n.º 6
0
void SerialThread::run()
{
    QSerialPort serial;
    int cr;

    serial.setPortName(m_portName);
    if (!serial.setBaudRate(115200)) {
        qDebug() << "Serial set baud rate failed!";
        emit this->serialError(tr("Can't set baud rate for %1, error code %2. %3.")
            .arg(m_portName).arg(serial.error()).arg(serial.errorString()));
        return;
    }
    if (!serial.setDataBits(QSerialPort::Data8)) {
        qDebug() << "Serial set data bits failed!";
        emit this->serialError(tr("Can't set data bits for %1, error code %2. %3.")
            .arg(m_portName).arg(serial.error()).arg(serial.errorString()));
        return;
    }
    if (!serial.setParity(QSerialPort::NoParity)) {
        qDebug() << "Serial set parity failed!";
        emit this->serialError(tr("Can't set parity for %1, error code %2. %3.")
            .arg(m_portName).arg(serial.error()).arg(serial.errorString()));
        return;
    }
    if (!serial.setStopBits(QSerialPort::OneStop)) {
        qDebug() << "Serial set stop bits failed!";
        emit this->serialError(tr("Can't set stop bits for %1, error code %2. %3.")
            .arg(m_portName).arg(serial.error()).arg(serial.errorString()));
        return;
    }
    if (!serial.setFlowControl(QSerialPort::NoFlowControl)) {
        qDebug() << "Serial set flow control failed!";
        emit this->serialError(tr("Can't set flow control for %1, error code %2. %3.")
            .arg(m_portName).arg(serial.error()).arg(serial.errorString()));
        return;
    }
    for (cr = 0; cr < m_connectAttempts; cr++) {
        if (serial.open(QIODevice::ReadWrite)) {
            break;
        }
        sleep(1);
        qDebug() << "Serial connect retry...";
    }
    if (cr == m_connectAttempts) {
        qDebug() << "Connection failed!";
        emit this->serialError(tr("Can't open %1, error code %2. %3.")
            .arg(m_portName).arg(serial.error()).arg(serial.errorString()));
        return;
    }

    emit this->serialConnected();
    qDebug() << "Serial Thread is ready...";

    m_mutex.lock();
    /* Unlock resources and wait for the first job. */
    m_cond.wait(&m_mutex);
    m_mutex.unlock();

    while (!m_quit) {
        /* Protect shared resources while thread is working. */
        m_mutex.lock();

        if (m_txBuf.size() > 0) {
            qint64 bytesWritten = serial.write(m_txBuf);
            if (serial.waitForBytesWritten(SERIAL_WRITE_TIMEOUT_MS)) {
                m_txBuf.remove(0, bytesWritten);
            } else {
                qDebug() << "Write request timeout!";
                /* Unlock resources and exit. */
                m_mutex.unlock();
                emit serialTimeout(tr("Write request timeout!"));
                break;
            }
        }

        if (serial.waitForReadyRead(SERIAL_READ_TIMEOUT_MS)) {
            m_rxBuf += serial.readAll();
            while (serial.waitForReadyRead(SERIAL_READ_TIMEOUT_EXTRA_MS)) {
                m_rxBuf += serial.readAll();
            }
            if (m_rxBuf.size() >= TELEMETRY_MSG_SIZE_BYTES) {
                processInputData();
            }
        } else {
            qDebug() << "Read response timeout!";
            /* Unlock resources and exit. */
            m_mutex.unlock();
            emit serialTimeout(tr("Read response timeout!"));
            break;
        }

        //qDebug() << "Serial Thread is sleeping...";
        /* Unlock resources and wait for the next job. */
        m_cond.wait(&m_mutex);
        m_mutex.unlock();
    }

    qDebug() << "Serial Thread is terminating...";
    serial.close();
}
Ejemplo n.º 7
0
void ReceiveDataThread::run()
{
    bool currentPortNameChanged = false;

    quit = false;//这一句是必须的

    mutex.lock();
    QString currentPortName;
    if (currentPortName != portName)
    {
        currentPortName = portName;
        currentPortNameChanged = true;
    }
    mutex.unlock();
    QSerialPort serial;

    while (!quit)
    {
        if (currentPortNameChanged)
        {
            serial.close();
            serial.setPortName(currentPortName);
            serial.setBaudRate(baudRate);
            serial.setStopBits(stopBits);
            serial.setParity(parity);
            serial.setDataBits(dataBits);

            if (!serial.open(QIODevice::ReadWrite))
            {
                emit error(tr("无法打开串口%1, 错误码为%2")
                           .arg(portName).arg(serial.error()));
                return;
            }
            //成功打开串口
            emit success();
        }

        if (serial.waitForReadyRead(100))
        {
            //读取数据
//            QByteArray requestData = serial.readAll();
            data += serial.readAll();
//            while (serial.waitForReadyRead(1000))
//                requestData += serial.readAll();

//            qDebug() << "requestData.size() = " << requestData.size();

            //如果接收到的数据加起来超过了800个字节,则发送给主界面
//           if(requestData.size() > 800)
            if(data.size() > 400)
           {
//               QString request(requestData);
               qDebug() << "data.size() = " << data.size();
               QString request(data);
               emit this->request(request);//发送数据
               data.clear();
           }
        }
        mutex.lock();
        if (currentPortName != portName)
        {
            currentPortName = portName;
            currentPortNameChanged = true;
        }
        else
        {
            currentPortNameChanged = false;
        }
        mutex.unlock();
    }
    serial.close();

    qDebug() << "串口被关闭" << endl;

}
void PSerialPort::run()
{
    reinitPort = true;
    mutex.lock();
//    cond.wait(&mutex);
    QString currentRequest = request;
    mutex.unlock();

    QSerialPort serial;

    while (!quit) {

        if (reinitPort) {
            serial.close();
            mutex.lock();
//            cond.wait(&mutex);
            serial.setPortName(portName);

            if (!serial.open(QIODevice::ReadWrite)) {
                emit error(tr("Не удалось подключиться к порту %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setBaudRate(baudRate)) {
                emit error(tr("Не удалось установить скорость для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setDataBits(dataBits)) {
                emit error(tr("Не удалось установить количество бит для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setParity(parity)) {
                emit error(tr("Не удалось установить четность для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setStopBits(stopBits)) {
                emit error(tr("Не удалось установить стоповый бит для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setFlowControl(flowControl)) {
                emit error(tr("Не удалось установить контроль четности для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }
            reinitPort = false;
            mutex.unlock();
        }

        QByteArray requestData = 0;

        stringToByteArray(currentRequest, requestData);

        if (serial.write(requestData) == -1)
            reinitPort = true;
//        else
//            qDebug() << "Write" << requestData;
        serial.write(requestData);
        if (serial.waitForBytesWritten(PORT_WAIT_TIMEOUT)) {
//            qDebug() << "START" << adress;
            if (serial.waitForReadyRead(PORT_WAIT_TIMEOUT)) {
                QByteArray responseData = serial.readAll();
                while (serial.waitForReadyRead(10))
                    responseData += serial.readAll();

                 QString response;

                 byteArrayToString(responseData, response);
                emit this->response(response);
            } else {
                emit timeout(tr("Время ожидания ответа истекло: %1")
                             .arg(QTime::currentTime().toString()));
            }
        } else {
            emit timeout(tr("Время ожидания записи истекло: %1")
                         .arg(QTime::currentTime().toString()));
        }
        mutex.lock();
        cond.wait(&mutex);
        currentRequest = request;
        mutex.unlock();
    }
    //! [13]
}
Ejemplo n.º 9
0
//! [4]
void MasterThread::run()
{
    bool currentPortNameChanged = false;

    mutex.lock();
    //! [4] //! [5]
    QString currentPortName;
    if (currentPortName != portName) {
        currentPortName = portName;
        currentPortNameChanged = true;
    }

    int currentWaitTimeout = waitTimeout;
    QString currentRequest = request;
    mutex.unlock();
    //! [5] //! [6]
    QSerialPort serial;

    while (!quit) {
        //![6] //! [7]
        if (currentPortNameChanged) {
            serial.close();
            serial.setPortName(currentPortName);

            if (!serial.open(QIODevice::ReadWrite)) {
                emit error(tr("Can't open %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setBaudRate(QSerialPort::Baud9600)) {
                emit error(tr("Can't set baud rate 9600 baud to port %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setDataBits(QSerialPort::Data8)) {
                emit error(tr("Can't set 8 data bits to port %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setParity(QSerialPort::NoParity)) {
                emit error(tr("Can't set no parity to port %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setStopBits(QSerialPort::OneStop)) {
                emit error(tr("Can't set 1 stop bit to port %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

            if (!serial.setFlowControl(QSerialPort::NoFlowControl)) {
                emit error(tr("Can't set no flow control to port %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }
        }
        //! [7] //! [8]
        // write request
        QByteArray requestData = currentRequest.toLocal8Bit();
        serial.write(requestData);
        if (serial.waitForBytesWritten(waitTimeout)) {
            //! [8] //! [10]
            // read response
            if (serial.waitForReadyRead(currentWaitTimeout)) {
                QByteArray responseData = serial.readAll();
                while (serial.waitForReadyRead(10))
                    responseData += serial.readAll();

                QString response(responseData);
                //! [12]
                emit this->response(response);
                //! [10] //! [11] //! [12]
            } else {
                emit timeout(tr("Wait read response timeout %1")
                             .arg(QTime::currentTime().toString()));
            }
            //! [9] //! [11]
        } else {
            emit timeout(tr("Wait write request timeout %1")
                         .arg(QTime::currentTime().toString()));
        }
        //! [9]  //! [13]
        mutex.lock();
        cond.wait(&mutex);
        if (currentPortName != portName) {
            currentPortName = portName;
            currentPortNameChanged = true;
        } else {
            currentPortNameChanged = false;
        }
        currentWaitTimeout = waitTimeout;
        currentRequest = request;
        mutex.unlock();
    }
    //! [13]
}
Ejemplo n.º 10
0
//! [4]
void MasterThread::run()
{
    bool currentPortNameChanged = false;
    mutex.lock();
    //! [4] //! [5]
    QString currentPortName;
    quint32 currentBaudRate;
    QSerialPort::DataBits currentDataBits;
    QSerialPort::Parity currentParity;
    QSerialPort::StopBits currentStopBits;
    QSerialPort::FlowControl currentFlowControl;
    if ((currentPortName != portName) ||
        (currentBaudRate != baudRate) ||
        (currentDataBits != dataBits) ||
        (currentParity != parity) ||
        (currentStopBits != stopBits) ||
        (currentFlowControl != flowControl))
    {
        currentPortName = portName;
        currentBaudRate = baudRate;
        currentDataBits = dataBits;
        currentParity = parity;
        currentStopBits = stopBits;
        currentFlowControl = flowControl;
        currentPortNameChanged = true;
    }

    QString currentRequest = request;
    mutex.unlock();
    //! [5] //! [6]
    QSerialPort serial;



    while (!quit) {
        //![6] //! [7]
        if (currentPortNameChanged) {
            serial.close();
            serial.setPortName(currentPortName);

            if (!serial.open(QIODevice::ReadWrite)) {
                emit error(tr("Не удалось подключиться к порту %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

//            if (!serial.setBaudRate(QSerialPort::Baud9600)) {
            if (!serial.setBaudRate(currentBaudRate)) {
                emit error(tr("Не удалось установить скорость для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

//            if (!serial.setDataBits(QSerialPort::Data8)) {
            if (!serial.setDataBits(currentDataBits)) {
                emit error(tr("Не удалось установить количество бит для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

//            if (!serial.setParity(QSerialPort::NoParity)) {
            if (!serial.setParity(currentParity)) {
                emit error(tr("Не удалось установить четность для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

//            if (!serial.setStopBits(QSerialPort::OneStop)) {
            if (!serial.setStopBits(currentStopBits)) {
                emit error(tr("Не удалось установить стоповый бит для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }

//            if (!serial.setFlowControl(QSerialPort::NoFlowControl)) {
            if (!serial.setFlowControl(currentFlowControl)) {
                emit error(tr("Не удалось установить контроль четности для порта %1, код ошибки %2")
                           .arg(portName).arg(serial.error()));
                return;
            }
        }
        QByteArray requestData = 0;

        StringToByteArray(currentRequest, requestData);
        serial.write(requestData);
        if (serial.waitForBytesWritten(WAIT_TIMEOUT)) {
//             read response
            if (serial.waitForReadyRead(WAIT_TIMEOUT)) {
                QByteArray responseData = serial.readAll();
                while (serial.waitForReadyRead(10))
                    responseData += serial.readAll();

                QString response(responseData);
                emit this->response(response);
            } else {
                emit timeout(tr("Время ожидания ответа истекло: %1")
                             .arg(QTime::currentTime().toString()));
            }
        } else {
            emit timeout(tr("Время ожидания записи истекло: %1")
                         .arg(QTime::currentTime().toString()));
        }
        mutex.lock();
        cond.wait(&mutex);
        if ((currentPortName != portName) ||
            (currentBaudRate != baudRate) ||
            (currentDataBits != dataBits) ||
            (currentParity != parity) ||
            (currentStopBits != stopBits) ||
            (currentFlowControl != flowControl))
        {
            currentPortName = portName;
            currentBaudRate = baudRate;
            currentDataBits = dataBits;
            currentParity = parity;
            currentStopBits = stopBits;
            currentFlowControl = flowControl;
            currentPortNameChanged = true;
        }
        else {
            currentPortNameChanged = false;
        }
        currentRequest = request;
        mutex.unlock();
    }
    //! [13]
}
Ejemplo n.º 11
0
void MasterThread::run()
{
//    qDebug()<<"run()";
    bool currentPortNameChanged = false;
    bool currentBaudRateChanged = false;
    bool currentStopBitsChanged = false;
    bool currentDataBitsChanged = false;
    bool currentParityChanged = false;
    mutex.lock();
    //! [4] //! [5]
    QString currentPortName;
    if (currentPortName != portName) {
        currentPortName = portName;
        currentPortNameChanged = true;
    }
    int currentBaudRate = this->baudRate;
    int currentStopBits = this->stopBits;
    int currentDataBits = this->dataBits;
    int currentParity = this->parity;
    int currentWaitTimeout =  this->waitTimeout;
    mutex.unlock();
    //! [5] //! [6]
    QSerialPort serial;

    while (!quit) {
        //![6] //! [7]
        if (currentPortNameChanged) {
            serial.close();
            serial.setPortName(currentPortName);

            if (!serial.open(QIODevice::ReadWrite)) {
                emit error(tr("Can't open %1, error code %2")
                           .arg(portName).arg(serial.error()));
                return;
            }
        }
        if (currentBaudRateChanged) {
            serial.setBaudRate(currentBaudRate);
        }
        if (currentDataBitsChanged) {
            serial.setDataBits(QSerialPort::DataBits(currentDataBits));
        }
        if (currentStopBitsChanged) {
            serial.setStopBits(QSerialPort::StopBits(currentStopBits));
        }
        if (currentParityChanged) {
            serial.setParity(QSerialPort::Parity(currentParity));
        }

        if (serial.waitForReadyRead(currentWaitTimeout)) {
            QByteArray responseData = serial.readAll();
            while (serial.waitForReadyRead(10))
                responseData += serial.readAll();

            QString response(responseData);
            //! [12]
            Decoding(response);
            //            emit this->response(response);
            //! [10] //! [11] //! [12]
        } else {
            emit timeout(tr("Wait read response timeout %1")
                         .arg(QTime::currentTime().toString()));
        }

        mutex.lock();
        //        cond.wait(&mutex);
        if (currentPortName != portName) {
            currentPortName = portName;
            currentPortNameChanged = true;
        } else {
            currentPortNameChanged = false;
        }
        if (currentBaudRate != baudRate) {
            currentBaudRate = baudRate;
            currentBaudRateChanged = true;
        }
        else {
            currentBaudRateChanged = false;
        }
        if (currentDataBits != dataBits)
        {
            currentDataBits = dataBits;
            currentDataBitsChanged = true;
        } else {
            currentDataBitsChanged = false;
        }
        if (currentStopBits != stopBits)
        {
            currentStopBits = stopBits;
            currentStopBitsChanged = true;
        }
        else
        {
            currentStopBitsChanged = false;
        }
        if (currentParity != parity)
        {
            currentParity = parity;
            currentParityChanged = true;
        }
        else
        {
            currentParityChanged = false;
        }

        currentWaitTimeout = waitTimeout;
        mutex.unlock();
    }
    //! [13]
}