import processing.serial.*;

//String serial_port="COM3";
String serial_port="/dev/ttyACM0";
Serial serial;
String serialString=""; //last read string
int serial_endchar=10; //10=ASCII Linefeed

float lastValue=0;

int valueNum=100;
float[] valueArray= new float[valueNum];
int valueArrayPos=0; //next to be written array position

long restartTime=0;

boolean running=false;

float resultAverage=0;
float resultSpan=0;

color bg=color(0);
color text=color(255);

Table table;


void setup() {
  size(400, 200);
  frameRate(100);
  
  printArray(Serial.list());
  // Open the port you are using at the rate you want:
  serial = new Serial(this, serial_port, 115200);
  
  serial.clear();
  // Throw out the first reading, in case we started reading 
  // in the middle of a string from the sender.
  println("readUntil");
  serialString = serial.readStringUntil(serial_endchar);
  println("read:"+serialString);
  serialString = null;
  
  table = new Table();
  
  
  table.addColumn("id");
  table.addColumn("value");
  
}

void draw() {
  if (serial.available() > 0) {
      serialString = serial.readStringUntil(serial_endchar);
      
      if (serialString != null) {
        serialString=trim(serialString);
        //println(serialString);
        String[] list = split(serialString, ',');
        lastValue=parseFloat(list[0]);
        
        if (running) {
          processNewValue(lastValue);
          if (valueArrayPos>=valueArray.length) { //full
            running=false;
            resultAverage=getAverage();
            resultSpan=getSpan();
            println("Finished reading "+valueNum+ " values in "+(millis()-restartTime)+" ms");
            println("Average="+resultAverage);
            println("Span="+resultSpan);
            
          }
        }
        
      }
  }
  
  background(bg);
  
  textAlign(LEFT);
  textSize(16);
  text(lastValue, 8,16);
  
  textAlign(CENTER);
  textSize(48);
  text(resultAverage, width/2,height/3);
  
  textAlign(CENTER);
  textSize(16);
  text("Span", width/2,height-48-20);
  textSize(48);
  text(resultSpan, width/2,height-20);
}

void keyPressed() {
  println("key="+keyCode);
  
  if (keyCode==10) { //10=enter
    println("restart");
    valueArrayPos=0;
    restartTime=millis();
    running=true;
  }else if(keyCode==83){ //83=s  save
    print("save value to table. ");
    
    TableRow newRow = table.addRow();
    newRow.setInt("id", table.getRowCount() - 1);
    newRow.setFloat("value", resultAverage);
    println("table size="+table.getRowCount());
  
  
  
  }else if(keyCode==87) { //87=w write to file
    String tableFilename="new.csv";
    println("write table to file "+tableFilename);
    saveTable(table, tableFilename);
  }
}

void processNewValue(float v) {
  if (valueArrayPos<valueArray.length){ //not full
    valueArray[valueArrayPos]=v;
    valueArrayPos++;
  }
}

float getAverage() {
  float average = 0;
  for ( int i = 0; i < valueArray.length; ++i )
  {
   average += valueArray[i];
  }
  average /= (float)(valueArray.length); 
  return average;
}

float getSpan() {
  return max(valueArray)-min(valueArray);
}
