//Note for HC12 433mhz module
/*
connect to 3v3 or 5v.
config: bridge set pin to ground and power on
connect with arduino serial monitor (can send written line at once). 9600baud
AT+RX  , shows all configs
default: 
  OK+B9600
  OK+RC001
  OK+RP:+20dBm
  OK+FU3

change baud to 115200:
  AT+B115200
 RC001 is frequency of 433.4MHz. rc100 is 473.0MHz 
*/

import processing.serial.*;

// The serial port:
Serial serial;
long last_send=0;
long last_update=0;




//Data
float time=0.0;

int cmd_FrontL;
int cmd_FrontR;
int cmd_RearL;
int cmd_RearR;
float current_FrontL;
float current_FrontR;
float current_RearL;
float current_RearR;
int speed_FrontL;
int speed_FrontR;
int speed_RearL;
int speed_RearR;
float temp_Front;
float temp_Rear;
float vbat_Front;
float vbat_Rear;
float currentAll;
int throttle;
int brake;


float n1=0.0;

void setup() {
  // List all the available serial ports:
  printArray(Serial.list());
  //String serialport=Serial.list()[0];
  String serialport="/dev/ttyUSB0";
  
  // Open the port you are using at the rate you want:
  serial = new Serial(this, serialport, 115200);
  
  serial.write("time,cmd_FrontL,cmd_FrontR,cmd_RearL,cmd_RearR,current_FrontL,current_FrontR,current_RearL,current_RearR,speed_FrontL,speed_FrontR,speed_RearL,speed_RearR,temp_Front,temp_Rear,vbat_Front,vbat_Rear,currentAll,throttle,brake\n"); //write header
}

void draw() {
  long loopmillis=millis();
  
  if (loopmillis>last_send+20) {
    last_send=loopmillis;
    
    String wstring=time+","+cmd_FrontL+","+cmd_FrontR+","+cmd_RearL+","+cmd_RearR+","+nfc(current_FrontL,3)+","+nfc(current_FrontR,3)+","+nfc(current_RearL,3)+","+nfc(current_RearR,3)+","+speed_FrontL+","+speed_FrontR+","+speed_RearL+","+speed_RearR+","+nfc(temp_Front,2)+","+nfc(temp_Rear,2)+","+nfc(vbat_Front,2)+","+nfc(vbat_Rear,2)+","+nfc(currentAll,3)+","+throttle+","+brake+"\n";
    serial.write(wstring);
    print(wstring);
  }
  
  if (loopmillis>last_update+20) {
    last_update=loopmillis;
    n1+=0.02;
    time=loopmillis/1000.0;
    updateValues();
  }
  
}


void updateValues() {
  
  cmd_FrontL=int(noise(n1,2)*1000);
  cmd_FrontR=int(noise(n1,2.001)*1000);
  cmd_RearL=int(noise(n1,2.02)*1000);
  cmd_RearR=int(noise(n1,2.021)*1000);
  current_FrontL=noise(n1-5,2)*10-3;
  current_FrontR=noise(n1-5,2.2)*10-3;
  current_RearL=noise(n1-5,2.4)*10-3;
  current_RearR=noise(n1-5,2.6)*10-3;
  speed_FrontL=int(noise(n1,5)*600);
  speed_FrontR=int(noise(n1,5.001)*600);
  speed_RearL=int(noise(n1,5.02)*600);
  speed_RearR=int(noise(n1,5.021)*600);
  temp_Front=noise(n1/100.0,10)*3+30;
  temp_Rear=noise(n1/100.0,10.1)*3+30;
  vbat_Front=-noise(n1/100.0,11)*4+12*4.2;
  vbat_Rear=-noise(n1/100.0,11.2)*4+12*4.2;
  currentAll=min(current_FrontL,min(current_FrontR,min(current_RearL,current_RearR)));
  throttle=int(noise(n1,15)*1000);
  brake=max(0,int(noise(n1,18)*1000-800));
}