PDA

View Full Version : Synchronize serial data read from Rfcomm in Qt



Ksir
27th January 2017, 14:09
I have created a producer-consumer thread system to read data from a serial port /dev/rfcomm0. The producer is calling the serial read function and storing data in a circular buffer. The serial read fucntion also takes care to parse the data and return it in a readable format, which stores it in the circular buffer. The consumer accesses this data from the buffer and calls slots to update a graph.

The data being read from the serial buffer is correct as long as i run the code in debug mode. The breakpoint is set after the serial read function call. But if I execute the program in normal mode, only the first data is read correctly, but subsequent data is garbled. The read buffer has no readable data in it. I do not understand why the serial buffer is not being read correctly.

I'm using Qt 5.3.2 with Qt creator 3.2.1 on Raspberry Pi 3.

My serial read code is as follows:


int serialReadData (int fd, char * outStr)
{
char data[23];
bool flag = true;
bool valid_data = false;
int count = 0;
int i = 0;
int n = read(fd,&data,23);

if((n == 23) && (data[0] == 's') && (data[1] == 't'))
{
for(int i = 0; i < 21; i++)
{
if((data[i+3] != 'e') && (data[i+4] != 'n'))
{
outStr[i] = data[i+3];
}
else
{
outStr[i] = '\n';
break;
}
}
//serialFlush(fd);
return 1;
}
return 0;
}

My Producer thread is as follows:


void rxDatafromBT::run()
{
char readData[DataSize];
int dataCount = 0;

/*Open serial port connection to read data from /dev/rfcomm0*/
int fd = serialOpen("/dev/rfcomm0",9600);

/*If serial open not successful, report error and exit the thread*/
if(fd == -1)
{
qDebug("Error Opening Serial Port to /dev/rfcomm \n");
emit errorOpeningPort();
}
/*If successful, then enter into while(1) loop*/
else
{
/*Run this Forever-Until program is terminated*/
while(!this->isInterruptionRequested()) {
/*Acquire data here from serial port*/

/*If first byte of data is the correct validity byte
Copy the data to data buffer, else ignore data*/
//if((readData != NULL) && (readData[0] == 0x5A))

if(serialReadData(fd,readData))
{
freeBytes.acquire();
for(int i = 0; i < DataSize; i++)
{
if(*(readData + i) == '\n')
{
break;
}
buffer[dataCount][i] = *(readData + i);
}

usedBytes.release();

dataCount++;
if(dataCount>=BufferSize)
{
dataCount = 0;
}
}

}

}
}

Will be gald to accept any help/suggestion to resolve this issue.

Best Regards,
Ksir

anda_skoa
28th January 2017, 08:04
How do you transport the data to the consumer thread?
Is the data structure properly protected against concurrent access?

Cheers,
_