I tried to modify the Qt network tutorial, and implemented it like:
quint16 blockSize;
void Client::readData()
{
qDebug() << "Received Data!";
QByteArray data;
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
qDebug() << "Received DATA II with blocksize " << blockSize;
if (tcpSocket->bytesAvailable() < blockSize)
{
qDebug() << tcpSocket->bytesAvailable() << ' ' << blockSize;
return;
}
qDebug() << "Received DATA III";
in >> data;
qDebug() << data;
QByteArray dbg = data; // create a copy to not alter the buffer itself
dbg.replace('\\', "\\\\"); // escape the backslash itself
dbg.replace('\0', "\\0"); // get rid of 0 characters
dbg.replace('\n', "\\n");
//dbg.replace('"', "\\\""); // more special characters as you like
qDebug() << dbg;
QString data_string(data);
qDebug() << "Emitting Signal";
emit Client::gotData(data_string);
}
void Server::sendData(void)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << "Hello World, this is a very long text!";
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
qDebug() << "First number is: " << (quint16)(block.size() - sizeof(quint16));
qDebug() << "Blocksize is: " << block.size() << "with quint size: " << sizeof(quint16);
qDebug() << "Sending data!";
//Debug
QByteArray dbg = block; // create a copy to not alter the buffer itself
dbg.replace('\\', "\\\\"); // escape the backslash itself
dbg.replace('\0', "\\0"); // get rid of 0 characters
dbg.replace('\n', "\\n");
//dbg.replace('"', "\\\""); // more special characters as you like
qDebug() << dbg;
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
clientConnection->write(block);
//clientConnection->disconnectFromHost();
}
Connecting works fine, but when I call sendData(), I get (from the same function) the transmitted block:
First number is: 43
Blocksize is: 45 with quint size: 2
Sending data!
"\0+\0\0\0'Hello World, this is a very long text!\0"
My first problem is: Where do all the \0 come from? As far as I understand the code, first I'm creating a 0, then I write the text, and them I am going back to the front and write the full size of the block. Is it because of the size of the (quint16)? When entering nothing, I get \0\0 and a size of 0, which is correct. The size of the example above is 43, which corresponds to + in ascii (and this sign is in the block above, too).
My second problem is: My readData()-function does not recognize the block size, (it always returns 450 as block size, which is clearly wrong). Why? Did I miss something?
UPDATE: After changing QByteArray data; to QString data; my problems are gone, no more strange \0 in my code -> should have used the right data type -> Head->Desk
Related
I am trying to repeatedly write and read to/from a QBuffer object via QTextStream. First I construct both objects:
QBuffer b;
b.open(QIODevice::ReadWrite);
QTextStream s(&b);
// Setup text stream here
Then I write three different portions of information and read them back:
s << "Test" << 666 << endl << flush;
s.seek(0);
qDebug() << s.readAll();
s << "X" << endl << flush;
s.seek(0);
qDebug() << s.readAll();
s << "Test" << 777 << endl << flush;
s.seek(0);
qDebug() << s.readAll();
Of course I do not get the data portion I wrote immediately before, but the cumulated data:
"Test666\n"
"Test666\nX\n"
"Test666\nX\nTest777\n"
I could do adaptive seek calls to get the correct data but I do not want the QBuffer to grow infinitely.
I tried a s.reset() call between writes but the result is the same. Calling reset() or open()/close() directly on the buffer gives a crippled result (which is expected since the stream is bypassed):
"Test666\n"
"X\nst666\n"
"Test777\n"
I could probably build a new buffer for every cycle, open it and attach it to the stream but that is slow.
Is there a proper and fast solution for this use case?
You can access QBuffer's internal QByteArray storage directly with QBuffer::buffer() and then delete everything with QByteArray::clear(). Then manually seek() back to the start.
QBuffer b;
b.open(QIODevice::ReadWrite);
QTextStream s(&b);
s << "Test" << 666 << endl << flush;
s.seek(0);
qDebug() << s.readAll();
b.buffer().clear();
s.seek(0);
s << "X" << endl << flush;
s.seek(0);
qDebug() << s.readAll();
b.buffer().clear();
s.seek(0);
s << "Test" << 777 << endl << flush;
s.seek(0);
qDebug() << s.readAll();
"Test666\n"
"X\n"
"Test777\n"
QTextStream also has a constructor which takes a QByteArray directly and creates the QBuffer automatically, which may save a little code in this case.
I am attempting to compare a QByteArray of an already saved html file with a QByteArray that was just downloaded. I have to convert the QString of the file's contents to QByteArray in order to compare them (or vice versa) and comparing bytes seems like the cleanest method, however when converted from QString to QByteArray, the size of the new QByteArray is smaller than what it should be. QByteArray QString::toLocal8Bit() const states that if it is undefined, the characters will be suppressed or replaced. It also said that it uses toLatin1() by default and tried to use ASCII since that is what a website is encoded in. I still get the same results.
bool NewsBulletin::compareDownload(QByteArray new_contents, QString filename)
{
bool return_what = false;
qDebug() << "I am in compareDownload";
// qDebug() << new_contents[1];
// qDebug() << new_contents[1] << endl
// << new_contents[2];
QFile file(application_path + filename);
if (file.exists())
{
// QString new_contents_qstr(new_contents);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&file);
QTextCodec::setCodecForLocale(QTextCodec::codecForName("ASCII"));
QString file_contents = in.readAll();
QByteArray file_byte_array = file_contents.toLocal8Bit();
qDebug() << "outputting new file array";
qDebug() << new_contents[5] << new_contents.size();
qDebug() << "outputting old file array";
qDebug() << file_byte_array[5] << file_byte_array.size();
for (int i=0; i<=file_byte_array.size(); i++)
{
if (file_byte_array[i] != new_contents[i])
{
return_what = true;
break;
}
else if (i == file_byte_array.size())
{
qDebug() << "compareDownload will return false, duplicate file.";
return_what = false;
}
}
}
else
{
qDebug() << "compareDownload will return true, DNE.";
return_what = true;
}
return return_what;
}
The output of the qDebug() from the function is:
I am in compareDownload
outputting new file array
T 64704
outputting old file array
T 64576
After reading the api for hours, I found the reason for the bytes being different.
file.open(QIODevice::ReadOnly | QIODevice::Text);
QIODevice::Text needs to be removed. This flag changes end of line terminators into the terminator for cpp, "\n", thus giving a byte difference.
I'm trying to connect a micro-controller with my desktop PC via USB-serial cable.
The OS of my desktop PC is Windows 8.1, and USB-serial cable is TTL-232R-3V3. (FTDI)
(Qt version: 5.2.0 beta1, QtCreator Version: 3.0, Compiler: MSVC2012)
Now I'm trying read/write loop-back tests, and that's why RX/TX pin of USB-serial cable are connected with each other.
Here is my code.
#include <QtCore/QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#define PORT_NAME "COM3"
#define BAUDRATE 19600
#define TIMEOUT_MS 1000
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPort pSerial(PORT_NAME);
const char strMsg[] = "#1:Send data line \n #2:Send data line\n #3:Send data line end\n";
char strBuf[256];
qint64 nByte;
if(pSerial.open(QIODevice::ReadWrite)){
pSerial.setBaudRate(BAUDRATE);
qDebug() << "OPEN PASS";
pSerial.write(strMsg);
pSerial.flush();
if(pSerial.waitForBytesWritten(TIMEOUT_MS)){
qDebug() << "WRITE PASS";
}
pSerial.waitForReadyRead(TIMEOUT_MS);
while(true){
if( pSerial.canReadLine()){
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
}
}
pSerial.close();
} else {
qDebug() << "OPEN FAIL\n";
}
return a.exec();
}
When the program starts to run, the result is different than I expected.
Only first line of sent data can be received. So, "Read data: #1 Send data line" is printed
on console. But the rest of sent data will never be received. Does anyone know why?
Any help would be appreciated.
Thanks in advance.
EDIT: I revised my code according to Papp's comment.Then it works as I expected.
All sent message has been received.
Does it mean I misunderstand the usage about readLine() or canReadLine()?
// while(true){
// if( pSerial.canReadLine()){
// qDebug() << "CAN READ LINE";
// nByte = pSerial.readLine(strBuf,sizeof(strBuf));
// qDebug() << "Length: " << nByte;
// qDebug() << "Read data: " << strBuf;
// }
// }
pSerial.waitForReadyRead(TIMEOUT_MS);
QByteArray readData = pSerial.readAll();
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
readData.append(pSerial.readAll());
}
qDebug() << "Read data: " << readData;
EDIT 2nd time : Following code also works for me.
while(true){
if( pSerial.waitForReadyRead(TIMEOUT_MS) && pSerial.canReadLine()){ // I revised this line
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
That is because you need to read in a loop like this:
QByteArray readData = serialPort.readAll();
while (serialPort.waitForReadyRead(5000))
readData.append(serialPort.readAll());
Please see the creadersync example for the details what I added to 5.2. You can also check the creaderasync example for non-blocking operation.
To be fair, we have not tested readLine that much, but it works for me on Unix, so does it on Windows for someone else.
The mistake that you've made is expecting to receive all the sent data when waitForReadyRead returns. When waitForReadyRead finishes, all you're guaranteed is some data being available to be read. It may be as little as one character, not necessarily a whole line.
The loop from your last modification is the almost correct way to do it. You should nest reading of the lines in a separate loop. The following code is how it should be done, and agrees with the semantics of QIODevice:
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
while (pSerial.canReadLine()) {
qDebug() << "NEW LINE";
QByteArray line = pSerial.readLine();
qDebug() << "Length: " << line.size();
qDebug() << "Read data: " << line;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
qDebug << "TIMED OUT";
Note that none of this code should even run in the GUI thread. Ideally you should move it to a QObject, use the signals emitted by QIODevice (and thus QSerialPort), and move that object to a separate thread.
The GUI thread can sometimes block for long periods of time, it's not normally desirable to have it disturb the timeliness of your device communication. Similarly, you don't want device timeouts to block the GUI thread. Both are equally bad and are a very common source of bad user experience. Qt makes multithreading very easy - leverage it for your user's sake, and do it properly.
On Linux I have to do it this way to receive ASCII text ending with '\n'
QByteArray readData = pSerial.readAll();
while (readData[readData.length() - 1] != '\n') {
pSerial.waitForReadyRead(5000);
readData.append(pSerial.readAll());
}
QString result(readData);
QSerialPort::readLine() doesn't work for me either
So my main function looks like this:
void main {
uint32 errmsg;
uint32 mydata;
if (LOG) {
std::ofstream file;
file.open(fileName,ios_base::app);
file << "!!!mydata: " << mydata << ",&mydata: " << &mydata << endl;
file.close();
}
errmsg = ReadReg32(0, 0, &mydata);
if (LOG) {
std::ofstream file;
file.open(fileName,ios_base::app);
file << "!!! returned mydata: " << mydata << ",&mydata: " << &mydata << endl;
file.close();
}
}
and calls ReadReg32 below:
static uint32 ReadReg32(uint32 brdNum, uint32 address, uint32 *data)
{
std::ofstream file;
if (LOG) {
file.open(fileName,ios_base::app);
file << " ReadReg32: brdNum =" << brdNum << ", address =" << address << endl;
file << " ReadReg32 ... Data WAS: " << *data << endl;
file.close();
}
/* AD:TW Check if we need to do init */
bool initstatus = checkDeferredInit();
ADMXRC3_HANDLE phCard;
ADMXRC3_STATUS status;
//open card
if((status = ADMXRC3_Open(brdNum, &phCard)) != ADMXRC3_SUCCESS)
return status;
//read data
if((status = ADMXRC3_Read(phCard, NON_PREFETCHABLE_SPACE, 0, address, 4, &data)) != ADMXRC3_SUCCESS){
ADMXRC3_Close(phCard);
return status;
}
if (LOG) {
file.open(fileName,ios_base::app);
file << " ReadReg32 ... Data IS: " << data << ", &data: " << &data << ", Read status =" << status << endl;
file.close();
}
//close card
status = ADMXRC3_Close(phCard);
if (LOG) {
file.open(fileName,ios_base::app);
file << " ReadReg32 ... Close card status =" << status << ", Returning ..." << endl;
file.close();
}
return status;
}
The relevant output is this:
!!!mydata: 348,&mydata: 000000000012F050
ReadReg32: brdNum =0, address =0
ReadReg32 ... Data WAS: 348
checkDeferredInit
ReadReg32 ... Data IS: 0000000081040102, &data: 000000000012EF30, Read status =0
ReadReg32 ... Close card status =0, Returning ...
!!! returned mydata: 348,&mydata: 000000000012F050
where 0000000081040102 is the correct number i expect to see, but it never returns that to the calling function, i.e. mydata is never updated.
Interesting notes:
in ADMXRC3_Read, if I don't use &data, i get "incorrect" data values
in ADMXRC3_Read, the type for where i'm sticking in &data is
supposed to be void *pbuffer?
Any thoughts are worth like a case of beer, or a moderately fine boxed wine. ;)
I do appreciate any thoughts you have, this has me stumped...
Well at first glance it seems you are using & too much.
static uint32 ReadReg32(uint32 brdNum, uint32 address, uint32 *data)
{
....
//read data
if((status = ADMXRC3_Read(phCard, NON_PREFETCHABLE_SPACE, 0, address, 4, &data)) != ADMXRC3_SUCCESS){
ADMXRC3_Close(phCard);
return status;
}
Here in read data part, you are calling ADMXRC3_Read with &data param. But data is already pointer! So you actually pass adress of variable that is local to your function.
To fix this, call the ADMXRC3_Read with data only.
IMPORTANT: In C and C++ everything is passed by value! So the data is just an variable holding 32-bit number (if you have 32bit addresses), nothing more.
EDIT: In my note I was referring to this FAQ: http://c-faq.com/ptrs/passbyref.html and I wrote it wrong. See the FAQ for more info.
I'm writing a simple network application. Client sending to server message server printing it in QTextEdit and responding to client .
I'm using QTcpServer and QTcpSocket.
There is a problem I can't solve. Receiving data is quint16 + QTime + QString which is sending as QByteArrey.
I use quint16 for receiving size of data blocks. And for some reason when client send to server
next block size: 16 (quint16 value)
block size: 18
Server get:
next block size: 30073 (quint16 value)
block size: 18
As you can see, for some reason server getting from QDataStrem wrong variable value and it is always 30073. I don't understand why?
void Widget::slotSendToServer()
{
logTextEdit->append("slotSendToServer()");
QByteArray arrBlock;
QDataStream serverSendStream(&arrBlock, QIODevice::ReadWrite);
QString messageStr = messageLineEdit->text();
serverSendStream << quint16(0) << QTime::currentTime()
<< messageStr;
serverSendStream.device()->seek(0);
serverSendStream << (quint16)(arrBlock.size() - sizeof(quint16));
qDebug() << "next_block_size:"
<<(quint16)(arrBlock.size() - sizeof(quint16))
<< endl
<< "full size of Byte arrey:" << arrBlock.size();
tcpSocket->write(arrBlock);
messageLineEdit->clear();
}
void Widget::slotReadClient()
{
logTextEdit->append("slotReadClient()");
QTcpSocket *tcpSocket = (QTcpSocket*)sender();
QDataStream clientReadStream(tcpSocket);
while(true)
{
if (!next_block_size)
{
if (tcpSocket->bytesAvailable() < sizeof(quint16))
{
break;
}
clientReadStream >> next_block_size;
}
if (tcpSocket->bytesAvailable() < next_block_size)
{
break;
}
QTime time;
QString messageTextStr;
clientReadStream >> time >> messageTextStr;
QString messageCompleteStr =
time.toString() + " " + "Client has sent - "
+ messageTextStr;
logTextEdit->append("Message received: ");
logTextEdit->append(messageCompleteStr);
next_block_size = 0;
sendToClient(tcpSocket,
"Server Response: Received \""
+ messageTextStr + "\"");
}
}
You should ensure that the variable next_block_size is initialized to 0 each time the socket is connected.
If you don't reuse the same QTcpSocket object, this can be done in your Widget class constructor, or if you do, in a slot connected to signal connected().
I have no idea why you did it it so complicated.
This should work:
void Widget::slotSendToServer()
{
logTextEdit->append("slotSendToServer()");
QByteArray arrBlock;
QDataStream serverSendStream(tcpSocket);
serverSendStream << QTime::currentTime()
<< messageLineEdit->text();
messageLineEdit->clear();
}
void Widget::slotReadClient()
{
logTextEdit->append("slotReadClient()");
QTcpSocket *tcpSocket = (QTcpSocket*)sender();
QDataStream clientReadStream(tcpSocket);
QTime time;
QString message;
clientReadStream >> time >> message;
emit YourSignal(time, message);
}
You don't have to worry about sizes, QDataStream keep track of it, you only have to maintain same sequence of read as it was done on write, so your buffer arrBlock is waste of code.
According to documentation my code should block when not all data are available at the moment of reading and this is only disadvantage. For small data like date and some string it will never happen.
About your code, you have messed up your reader with while loop for sure, so here is correction without this loop.
void Widget::slotReadClient()
{
logTextEdit->append("slotReadClient()");
QTcpSocket *tcpSocket = (QTcpSocket*)sender();
QDataStream clientReadStream(tcpSocket);
if (next_block_size==0) {
// need to read data size
if (tcpSocket->bytesAvailable() < sizeof(quint16))
return; // wait for next signal
// next_block_size must be type of qint16
clientReadStream >> next_block_size;
}
if (tcpSocket->bytesAvailable() < next_block_size) {
// not enought data to complete read immediately
return; // wait for next signal
}
QTime time;
QString messageTextStr;
clientReadStream >> time >> messageTextStr;
QString messageCompleteStr =
time.toString() + " " + "Client has sent - "
+ messageTextStr;
logTextEdit->append("Message received: ");
logTextEdit->append(messageCompleteStr);
// mark that data read has been finished
next_block_size = 0;
}