PDA

View Full Version : Best Method to Plot Data Coming through a Socket.



babu198649
29th May 2009, 06:08
Hi
I want to plot the data which comes through socket continously.So i have created a thread which receives the data from the socket and emits it as shown in the code.


void Thread::run()
{
QTcpSocket socket;
qDebug()<<"Connecting to host";
do
{//Even if the server is not started keep trying
socket.connectToHost(QHostAddress::LocalHost,12345 );
if(socket.waitForConnected(-1))
break;
qDebug()<<"Unable to connect to host "<<socket.errorString()<<" retrying...";
}while(true);

qDebug()<<"Connected...";

while(true)
{
do
{
socket.waitForReadyRead(-1);
}while(socket.bytesAvailable() < sizeof(short int));

QByteArray byteArray = socket.read(socket.bytesAvailable() - (socket.bytesAvailable()%sizeof(short int)));
short int si;
for(int i=0; i<(byteArray.size() / sizeof(short int)); i++)
{
si = *((short int *)(byteArray.constData() + i*sizeof(short int)));
emit send(si);
}
}
}

In the gui thread the signal is caught and is plotted as shown in the below code.

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);

plot = new QwtPlot();
// Disable polygon clipping
QwtPainter::setDeviceClipping(false);

// We don't need the cache here
plot->canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false);
plot->canvas()->setPaintAttribute(QwtPlotCanvas::PaintPacked, false);
setCentralWidget(plot);
curve = new QwtPlotCurve();
curve->attach(plot);
memset(data,0,sizeof(data));
for(int i = 0; i< HISTORY;i++)
timeData[i] = i;
curve->setRawData(timeData,data,HISTORY);
plot->setAxisScale(QwtPlot::xBottom, timeData[0],timeData[HISTORY - 1]);
thread = new Thread;
connect(thread,SIGNAL(send(short)),this,SLOT(recei ve(short)));
thread->start();
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::receive(short si)//This is the slot which receives and updates the plot.
{
for(int i = 0; i < HISTORY-1; ++i)
data[i] = data[i+1];
data[HISTORY - 1] = si;

plot->replot();
QCoreApplication::processEvents();
}

But the above program gets crashed after some time of plotting .What is the bug in above code that causes the crash.

Should i follow the dataplot example in which a timerEvent is used for plotting ,or is there any other method available.

Thanks in advance.