Qextserialport breaks my xml - qt

I am trying to rewrite in c++ an application written in python.
All it does is to open a serial port and read some xml. In python i was using pyserial to read the xml and beautifulsoup to retrieve information. The output was like this.
<file><property>xx32</property></file>
Now i am using qextserialport to read from the serial port and the xml i get is something like this.
<
fil
e>
<prope
rty>xx32
</prop
erty>
</
file>
My problem is that i cant parse an xml like this. I get errors.
EDIT:
Qextserialport reads data from the serial port in set of bytes that are not fixed.
So how do i concatenate my xml into one string? I get an xml string every 4-5 seconds from the serial port.
here is my code
this->port = new QextSerialPort(com_port,QextSerialPort::EventDriven);
port->setBaudRate(BAUD57600);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_1);
port->setTimeout(0);
if (port->open(QIODevice::ReadOnly) == true)
{
//qDebug()<< "hello";
connect(port,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
}
and the function that actually reads from the serial port
void CurrentCost::onReadyRead()
{
QByteArray bytes;
bytes = port->readAll();
//qDebug() << "bytes read:" << bytes.size();
//qDebug() << "bytes:" << bytes;
ui->textBrowser->append(bytes);
}

I mean something like this:
class CurrentCost...{
private:
QByteArray xmlData;
private slots:
void onReadyRead();
};
void CurrentCost::onReadyRead()
{
xmlData.append(port->readAll());
if(xmlData.endsWith(/*what your port sending then xml is over&*/))
{
ui->textBrowser->append(xmlData);
xmlData.clear();
}
}

Related

QNetworkAccessManager HTTP Put request not working

After an exhaustive search on the web about this issue, none of the answers found solved it.
Using the technology Qt_5_15_2_MSVC2019_64/Microsoft Visual C++ Compiler,
I'm trying to send a JSON file through HTTP put request from QNetworkAccessManager to a custom QTcpServer, but when doing so, only HTTP headers are received (even twice) but not the JSON file in itself.
Snippet Code:
void Sender::putParameters(const QString& p_parameters) {
QJsonDocument docJson = QJsonDocument::fromJson(p_parameters.toUtf8());
QByteArray data = docJson.toJson();
QUrl url= QUrl("http://127.0.0.1:80/api/devices/1285/parameters");
QNetworkAccessManager* nam = new QNetworkAccessManager(this); // Even tried to put as member variable but still did not work
QNetworkRequest networkReq(url);
networkReq.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
networkReq.setRawHeader("Content-Length", QByteArray::number(data.size()));
QObject::connect(nam, &QNetworkAccessManager::finished, this,
&Sender::validateParameters);
nam->put(networkReq, data);
if(docJson.isEmpty())
qDebug() << "JSON was empty";
}
Result QTcpServer:
With Poco library there's no issue it works, or sending HTTP put request via Postman it does work.
#dabbler
Sorry for the late answer but here is the code snippet of the Server :
enter image description here
With postMan and Poco it's working perfectly, so I don't know if the issue is then related to the server, and for the client side #Dmitry you're right I should use QJsonDocument::isNull instead (but I used isEmpty() just for demonstration purpose that I wasn't sending an invalid Json which is not the case, the json is valid).
Yes my bad #Syfer
So I have the class Server inheriting from QTcpServer and overriding function incomingConnection such as : void incomingConnection(qintptr) Q_DECL_OVERRIDE;
Here is the code snippet:
Server::Server(QObject* parent) : QTcpServer(parent)
{
if(listen(QHostAddress::Any, 80))
qDebug() << "Ok listening port 80";
else
qCritical() << "Fail listening";
}
void Server::incomingConnection(qintptr p_intPtrSocket)
{
QTcpSocket* socketClient = new QTcpSocket(this);
socketClient->setSocketDescriptor(p_intPtrSocket);
connect(socketClient, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}
void Server::onReadyRead()
{
QTcpSocket* socketClient = (QTcpSocket*)sender();
QString fullClientRequest = QString::fromUtf8(socketClient->readAll());
QStringList clientReq = fullClientRequest.split("\n");
qDebug() << "client response: " << clientReq;
}

QBtyeArray QDataStream qCompress to file adding extra leading bytes

Qt/C++ program has a function which writes an objects data (_token) to a file as follows:
QFile f( _tokenFile);
if (!f.open( QIODevice::WriteOnly)) {
qDebug() << "Unable to open token file for writing" << f.errorString();
return false;
}
QByteArray tokenBa;
QDataStream ds( &tokenBa, QIODevice::WriteOnly);
ds << _token;
tokenBa = qCompress( tokenBa);
f.write( tokenBa);
f.close();
The _token is an instance of the following struct:
struct Token {
QString accessToken;
QString refreshToken;
QString clientSecret;
QString authCode;
QTime expiryTime;
enum AuthState {
A_Invalid,
A_RequestAuth,
A_Authenticated,
};
AuthState state;
Token() : state( A_Invalid) {}
bool isValid() const {
if (accessToken.isEmpty() ||
refreshToken.isEmpty()) {
return false;
}
return true;
}
void inValidate() {
accessToken.clear();
refreshToken.clear();
clientSecret.clear();
authCode.clear();
expiryTime = QTime();
}
void cleanUp() {
accessToken.clear();
refreshToken.clear();
clientSecret.clear();
authCode.clear();
expiryTime = QTime();
}
};
When the file is saved it has 4 extra bytes at the start which render the file as a invalid zlib file.
0000000 0000 5e01 9c78 904d 4f5d 5082 871c fa9f
0000020 353e 25cd 6975 2c2f d563 4c2c 62b8 cad1
We can see above bytes 5-6 are 9C 78 which is the zlib signature, but the 4 bytes before these are the issue.
To check the compressed data is correct I do the following:
dd if=file.token bs=1 skip=4 | openssl zlib -d
And this produces the expected result (for testing).
The problem is in the application reading this data back into the data object:
QFile f( _tokenFile);
if (!f.exists()) {
qDebug() << "Token file doesn't exist" << f.fileName();
return false;
}
if (!f.open( QIODevice::ReadOnly)) {
qDebug() << "Unable to open token file for reading" << f.errorString();
return false;
}
QByteArray tokenBa = f.readAll();
f.close();
if (tokenBa.isEmpty()) {
qDebug() << "Token file is empty.";
return false;
}
tokenBa = qUncompress( tokenBa);
QDataStream ds( &tokenBa, QIODevice::ReadOnly);
ds >> _token;
This returns null - because of the leading 4 extraneous bytes. I could put some code in to skip these 4 leading bytes, but how do I know it will always be 4 bytes? I'd like to instead have certainly that the files data is all zlib compressed.
My question is how to avoid those bytes being saved in the first place so that on re-read the format is known to be zlib type?
You can't avoid them since they're needed for qUncompress later on:
Note: If you want to use this function to uncompress external data that was compressed using zlib, you first need to prepend a four byte header to the byte array containing the data. The header must contain the expected length (in bytes) of the uncompressed data, expressed as an unsigned, big-endian, 32-bit integer.

QIODevice::read (QSerialPort) : device not open

I'm new with Qt Creator and I'm trying to read data from a light sensor communicating by I2C. I made a class PortListener that should return data received on the console once called.
PortListener::PortListener(const QString &portName)
{
this->port = new QSerialPort();
port->setPortName(portName);
port->setBaudRate(QSerialPort::Baud9600);
port->setDataBits(QSerialPort::Data8);
port->setParity(QSerialPort::NoParity);
port->setStopBits(QSerialPort::OneStop);
port->setFlowControl(QSerialPort::NoFlowControl);
port->open(QIODevice::ReadWrite);
QByteArray readData = port->readAll();
qDebug() << "message:" << readData;
}
But the only message I have is:
QIODevice::read (QSerialPort): device not open
message: ""
I don't understand what that mean?
1.Open the serialport,then set the parameters.
PortListener::PortListener(const QString &portName)
{
this->port = new QSerialPort();
port->open(QIODevice::ReadWrite);
port->setPortName(portName);
port->setBaudRate(QSerialPort::Baud9600);
port->setDataBits(QSerialPort::Data8);
port->setParity(QSerialPort::NoParity);
port->setStopBits(QSerialPort::OneStop);
port->setFlowControl(QSerialPort::NoFlowControl);
}
2.Connect the readyRead signal to a slot, and the slot is like this.
void PortListener::readyReadSlot()
{
while (!port.atEnd()) {
QByteArray data = port.readAll();
}
}
This is much more like the QextSerialPort, the following is the code from my application.
void SpClient::start()
{
myComClient = new QextSerialPort(Setting::devCom);
if(myComClient->open(QIODevice::ReadWrite))
{
qDebug() << "open " << Setting::devCom << "as client success";
}
myComClient->setBaudRate(BAUD9600);
myComClient->setDataBits(DATA_8);
myComClient->setParity(PAR_NONE);
myComClient->setStopBits(STOP_1);
myComClient->setFlowControl(FLOW_OFF);
myComClient->setTimeout(50);
....
}
My guess is your code is failing to open the serial port, I have run into permissions issues under linux opening USB ports. You will just need to do a chmod to grant your $USER access mostly.

QPixmap.loadFromData() does not load image from QByteArray

I'm creating a socket-based program to send a screenshot from one user to another user. I need to convert a screenshot to a byte array before sending. After I convert my screenshot to a QByteArray I insert 4 bytes to the beginning of the array to mark that it is a picture (it is the number 20 to tell me it is a picture and not text or something else).
After I send the byte array via a socket to other user, when it is received I read the first 4 bytes to know what it is. Since it was a picture I then convert it from a QByteArray to QPixmap to show it on a label. I use secondPixmap.loadFromData(byteArray,"JPEG") to load it but it not load any picture.
This is a sample of my code:
void MainWindow::shootScreen()
{
originalPixmap = QPixmap(); // clear image for low memory situations
// on embedded devices.
originalPixmap = QGuiApplication::primaryScreen()->grabWindow(0);
scaledPixmap = originalPixmap.scaled(500, 500);
QByteArray bArray;
QBuffer buffer(&bArray);
buffer.open(QIODevice::WriteOnly);
originalPixmap.save(&buffer,"JPEG",5);
qDebug() << bArray.size() << "diz0";
byteArray= QByteArray();
QDataStream ds(&byteArray,QIODevice::ReadWrite);
int32_t c = 20;
ds << c;
ds<<bArray;
}
void MainWindow::updateScreenshotLabel()
{
this->ui->label->setPixmap(secondPixmap.scaled(this->ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
void MainWindow::on_pushButton_clicked()
{
shootScreen();
}
void MainWindow::on_pushButton_2_clicked()
{
secondPixmap = QPixmap();
QDataStream ds(&byteArray,QIODevice::ReadOnly);
qint32 code;
ds>>code;
secondPixmap.loadFromData(byteArray,"JPEG");
updateScreenshotLabel();
}
Your MainWindow::on_pushButton_2_clicked implementation looks odd. You have...
QDataStream ds(&byteArray,QIODevice::ReadOnly);
which creates a read-only QDataStream that will read it's input data from byteArray. But later you have...
secondPixmap.loadFromData(byteArray,"JPEG");
which attempts to read the QPixmap directly from the same QByteArray -- bypassing the QDataStream completely.
You can also make use of the QPixmap static members that read from/write to a QDataStream. So I think you're looking for something like...
QDataStream ds(&byteArray,QIODevice::ReadOnly);
qint32 code;
ds >> code;
if (code == 20)
ds >> secondPixmap;
And likewise for your MainWindow::shootScreen implementation. You could reduce your code a fair bit by making use of QDataStream & operator<<(QDataStream &stream, const QPixmap &pixmap).

How to send data from server to client as QByteArray/QDataStream

In the fortuneserver sample of Qt, a QString is sent by the method sendFortune(). Therefore one QString is selected from the QStringList fortunes:
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << fortunes.at(qrand() % fortunes.size());
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
clientConnection->write(block);
Is it also possible to send another type of data, like files, images or multiple strings? Or is it just possible to send a single string?
My second question: What is the advantage of sending data as QByteArry and why do I have to define (quint16) by setting up the QDataStream?
You don't send the data as QDataStream, QDataStream is a class that impersonates a stream, a way to transfer data, like wire.
QByteArray represents a storage for your data.
So, you can send data as QByteArray.
You can try QTcpSocket's member function called "int write(QByteArray)", like in the example you provided. Just take the image, the file, any other data and convert it to QByteArray. Here is where you will need QDataStream. Bind the stream to bytearray like this.
QByteArray dat;
QDataStream out(&dat, QIODevice::WriteOnly);
and use out to fill dat.
out << myImage << myImage2;
When you had finished filling the QByteArray, send it:
mySocket.write(dat);
don't forget to check the return value.
Read the docs and you will succeed.
To know if you have read all the data send by the other side of the socket, I use the commitTransaction() function from QDataStream:
Client::Client()
{
....
connect(tcpSocket, &QIODevice::readyRead, this, &Client::readData);
....
}
void Client::readData()
{
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
qDebug() << TAG << "incomplete: " << data;
// readyRead will be called again when there is more data
return;
}
// data is complete, do something with it
....

Resources