0

我正在使用qextserialport与 Windows 8.1 上的蓝牙设备进行通信。我定义了一个ComPort类。我需要先{0xA9,0x55}在“COM5”上写一条消息,要求蓝牙设备开始传输数据。然后我就可以开始读取数据了。我有一个终端应用程序,显示我已经编写了消息,并且数据在“COM5”上可用。

问题定义:

comport.cpp中,既不waitForBytesWritten()也不waitForReadyRead()返回true。可用字节数为零,并且onReadyRead()不调用插槽。我的代码有什么问题?

comport.h

#ifndef COMPORT_H
#define COMPORT_H

#include <QObject>
#include <QDebug>
#include "qextserialport.h"
#include "qextserialenumerator.h"

class QTimer;

class ComPort : public QObject
{
    Q_OBJECT

public:
    ComPort(const QString &portName);
    ~ComPort();

private:
    QextSerialPort* port;

    void     setupPort();


private slots:
    void onReadyRead();
};

#endif // COMPORT_H

comport.cpp

#include "comport.h"
ComPort::ComPort(const QString &portName)
{
    QString strPort;
    this->port = new QextSerialPort(portName);
    this->setupPort();

    connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

    if (port->open(QIODevice::ReadWrite) == true)
    {
        const char mydata[] = {static_cast<char>(0xA9),static_cast<char>(0x55)};
        QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
        port->write(data);
        if(port->waitForBytesWritten(100))
            qDebug() << "Wrote the message";

        QByteArray responseData = port->readAll();
        while (port->waitForReadyRead(2000))
               responseData += port->readAll();

        qDebug() << "Num of bytes: " << port->bytesAvailable();
    }
    else
    {
        qDebug() << "Device is not turned on";
    }
}

ComPort::~ComPort()
{
    delete port;
}

void ComPort::setupPort()
{
    port->setBaudRate(BAUD115200);
    port->setTimeout(100); // Does nothing in Eventdriven mode!
    port->setFlowControl(FLOW_OFF);
    port->setParity(PAR_NONE);
    port->setDataBits(DATA_8);
    port->setStopBits(STOP_1);
    port->setQueryMode(QextSerialPort::EventDriven);
}

void ComPort::onReadyRead()
{
    QByteArray bytes;
    int a = port->bytesAvailable();
    bytes.resize(a);
    port->read(bytes.data(), bytes.size());
    qDebug() << "bytes read:" << bytes.size();
    qDebug() << "bytes:" << bytes;
}
4

0 回答 0