Dynamic Graph Plotting with openGL in Android

2019-03-11 11:59发布

问题:

I want to plot real time data from a bluetooth device. I have a Bluetooth device that the phone will connect to and read the data coming from it. The data is voltage levels from some sensors and having a sample rate of 300 samples per sec. Most of the plotting libs(like aiChart, Androidplot, achartengine,...) I have seen can't handle that amount of data and repainting the graph. So I looked into openGL and Android NDK and it seems that I might be able to graph using either one of these with the sample rates I have. Does anyone have a sample code for openGL line graph plotting in android/Java and/or NDK code sample?

回答1:

We did something like this simply by creating a point array class with several pages and drawing in opengl with offset so the current point is always in the same place.

The idea use fixed size arrays with a separate counter so you aren't hitting memory alloc issues which would cause gc to kick in. Once a page is full, cycle to the next page displaying the old as well. The idea is that if you have 5 pages, you can write to one, display the other 3 and batch write the last one to sqlite on an sdcard in a seperate thread so you can pull all the data out later on.

As long as you only have one thread writing to the array you can get away with something like

arrayPoint[] p;
....
int currentPos = 0;
arrayPoint current = p[currentPos];

..... 
while(....

if(current.end < current.max)
{
      .... get datax and datay
     current.end++;
     current.x[current.end] = datax;
     current.y[current.end] = datay;
}
else
{
     currentPos = getNextPos();
     current = p[currentPos];
     current.end = -1; // truncate the array without actually freeing or allocating mem
     ..... flip volatile bool to let other thread know its ok to get exclusive access to its data etc      
}

Its very fast and should do what you need. You can then output as a point on a canvas or draw in opengl es

Hope that helps.