我的应用程序通过串行端口(usb 串行)与嵌入式系统通信。
我正在使用来自 gitorious ( https://qt.gitorious.org/qt/qtserialport/ ) 的 Qt 4.8 和 QtSerialPort 进行开发,并且我还在使用 Windows 7 和 Qt 5.2.1 的 VM 中进行测试
它在 Linux 下运行良好,但我得到了对同一条消息的双重、三重四重读取。我可以验证这些消息只发送一次,通过 puTTY 进行通信。
所以问题是,QtSerialPort、VM(尽管它可以与 putty 一起使用?)、串行驱动程序......等是否存在问题?
这是一个已知的问题?(不过,我什么也找不到)有什么想法可以解决这个问题吗?
这就是我的阅读方式:
编辑:摩尔代码:
ModuleCommunicator::ModuleCommunicator(const QString &device, SBStateModel &state_model)
: upstate(UpdateDone), model(state_model)
{
port = new QSerialPort(device);
if (!port->open(QIODevice::ReadWrite /*| QIODevice::Truncate*/)) {
qDebug() << "Failed to open - Portname: " << port->portName() << endl;
qDebug() << "Error: " << port->errorString() << endl;
return;
}
port->setBaudRate(QSerialPort::Baud115200, QSerialPort::AllDirections);
port->setParity(QSerialPort::NoParity);
port->setStopBits(QSerialPort::OneStop);
port->setDataBits(QSerialPort::Data8);
port->setFlowControl(QSerialPort::NoFlowControl);
msgBuffer = new QStringList();
log_init = false;
connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(onError(QSerialPort::SerialPortError)));
connect(port, SIGNAL(aboutToClose()), this, SLOT(devClosing()));
/* Timer for log level */
conTimer = new QTimer(this);
connect(conTimer, SIGNAL(timeout()), this, SLOT(timerFired()));
}
ModuleCommunicator::~ModuleCommunicator()
{
if (port->isOpen())
port->close();
delete msgBuffer;
delete port;
}
...
void ModuleCommunicator::onReadyRead()
{
if (port->bytesAvailable()) {
QString msg = QString(port->readAll());
msgBuffer->append(msg);
if (msg.endsWith("\n")) {
msg = msgBuffer->join("").trimmed();
msgBuffer->clear();
msgBuffer->append(msg.split("\r\n"));
} else {
return;
}
for (int i = 0; i < msgBuffer->size(); i++) {
msg = msgBuffer->at(i);
qDebug() << "MSG: " << msg << endl;
if (isResponse(msg)) {
handleMsg(msg);
}
}
msgBuffer->clear();
}
}
编辑:有趣。取消注释“flush()”会使事情正常进行。随着冲洗,我看到成倍的消息。但是在接收端呢?是否有可能因为“flush()”而多次发送消息?
void ModuleCommunicator::handleMsg(const QString &msg)
{
// Parse msg
QSharedPointer<USBResponse> resp = QSharedPointer<USBResponse>(parse_message(msg));
if (!resp->is_valid()) {
// LOG
return; // Invalid response
}
// omitted
/* Find completion handler for response
Match to first command in Queue with same command & address,
or same command and wildcard adress */
// Omitted
// Sending next msg in queue if there is one
if (!sendQueue.isEmpty()) {
QueuedCommand qc = sendQueue.takeFirst();
QString nxtcmd = qc.cmdstr;
completionHandlerQueue.append(qc.ch);
qDebug() << "handleMsg: Sending next msg: " << qc.cmdstr;
if (port->write(nxtcmd.toLatin1()) == -1) {
qDebug() << "handleMsg: write failed!";
}
// !!! Removing the following line makes things work?!
port->flush();
}
return;
}