From 26a11e6c56f97a2dae0bb1cbb730f2c2bd27da9d Mon Sep 17 00:00:00 2001 From: Gerhard Hoffmann Date: Tue, 15 Oct 2024 10:00:34 +0200 Subject: [PATCH] writeToSerial(): Only write to serial interface if no current command has been sent to DC already. --- src/com.cpp | 47 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/src/com.cpp b/src/com.cpp index b89119d..d77c303 100644 --- a/src/com.cpp +++ b/src/com.cpp @@ -20,13 +20,48 @@ void T_com::writeToSerial(const QByteArray &data, uint16_t sendLength) { sendBuffer=data; sendLen=sendLength; - if (CatSerial->isOpen()) - { - //qDebug() << "sending..." << sendBuffer; - CatSerial->write(sendBuffer); - } else - qDebug() << "error sending, port is not open"; + if (readCmds.size() == 0) { // no other read command active + if (CatSerial->isOpen()) + { + if (CatSerial->error() != QSerialPort::NoError) { + qCritical() << __func__ << "" << __LINE__ << "ERROR on serial line" << CatSerial->errorString(); + CatSerial->clearError(); + qCritical() << __func__ << "" << __LINE__ << "cleared error on serial line"; + } + + if (!CatSerial->atEnd()) { + qCritical() << QString("ERROR %1 bytes available on serial line before write").arg(CatSerial->bytesAvailable()); + qCritical() << CatSerial->readAll().toHex(':'); + CatSerial->clear(); + qCritical() << __func__ << "" << __LINE__ << "read all data from serial line"; + } + + QByteArray buffer(data); + + int bytesToWrite = buffer.size(); + while (bytesToWrite > 0 && !buffer.isEmpty()) { + int bytesWritten = CatSerial->write(buffer); + if (bytesWritten != -1 && CatSerial->waitForBytesWritten(1000)) { + bytesToWrite -= bytesWritten; + buffer = buffer.right(bytesWritten); + } else { + qCritical() << __func__ << ":" << __LINE__ + << QString("ERROR %1 for sending %2").arg(CatSerial->errorString()).arg(data.toHex(':').constData()); + CatSerial->clearError(); + qCritical() << __func__ << ":" << __LINE__ << "cleared error on serial line. returning ..."; + return; + } + } + readCmds.append(data.constData()[2]); + } else { + qCritical() << __func__ << ":" << __LINE__ + << "ERROR sending" << data.toHex(':') << "port is not open"; + } + } else { + qCritical() << __func__ << "" << __LINE__ << "ERROR detected active read cmd" << readCmds[0]; + readCmds.clear(); + } }