import processing.serial.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.time.LocalDateTime;
import java.util.Calendar;

Serial myPort;
String dataStr;
PrintWriter output;

int count = 1;

int x;
int values[] = new int[300];

Date tmpTime = new Date("2019/06/24 10:10:03");

String showvalues;

void setup(){
  
  size(800,600);
  frameRate(30);
  
 
  
  println(Serial.list());
  myPort = new Serial(this, Serial.list()[3],9600);
  //myPort.clear();
 output = createWriter("sensordata.csv");
 pixelDensity(displayDensity());
 
 
}

void draw(){
  
 background(color(30,30,30));
 stroke(255,255,255);
 textSize(16);
 text("Press 'r' key: to start serial communicatio  for getting sensor data from the robot.",20,20);
 text("Press 'a' key: to save sensor data into .csv file",20,40);
 
  /**line(50,250,750,250);
  line(50,50,750,50);
  line(50,50,50,250);
  line(750,50,750,250);
 
 for(int i=0;i<299;i++){
     float divide = 1;
     float a = 0.0;
     float b = 0.0;
     
     stroke(0,255,255);
          a = map(values[i],0,255,250,0);
          b = map(values[i+1],0,255,250,0);          
          line(50+(divide * i),a, 50+(divide * (i+1)),b);
          
     //print(values[i]);**/
      
 
  
}

void serialEvent(Serial p){

    if (p.available() > 0) {
    try {
      String input = p.readStringUntil('\n');
      if (input != null) {
        
        String sdFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(tmpTime);
        
        String insert = sdFormat + "," + input;
        
         output.print(insert);
         print(insert);
         String tmp = trim(input);
         
         append(values,int(tmp));
         Calendar calendar = Calendar.getInstance();
         calendar.setTime(tmpTime);
         calendar.add(Calendar.SECOND,1);
         tmpTime = calendar.getTime();
         
       }
    } catch (RuntimeException e) {
    }
  }
  
}

void keyPressed() { 
  if(key == 'a'){
    output.flush(); //残りを出力する
    output.close(); // ファイルを閉じる
    exit(); // 終了
  }
  
  if(key == 'r'){
    myPort.write("r");
  }
}
