import java.io.*;
import java.util.*;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Monitor6 implements Runnable
{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";              
	private static final long serialVersionUID = 8257386587L; 
	public Thread readThread;             // zaman içinde çalışma değişkeni
    public  CommPortIdentifier portId;    // seri bağlantı kanalı numarası
    public  SerialPort serialPort;        // seri kanal
    public  OutputStream outputStream;    // çıktı kanalı
    public  InputStream inputStream;      // girdi kanalı
    public  int sleep1;                   // readThread bekleme zamanı milisaniye
    public tplot2D d3;
     public dials1 d1;
    double T1,T1old;
    double ymin,ymax;
    //kontrol parametresi
    public String veritabani;
    public String veritablosu[];
    public  Connection connection = null;
    public  Statement statement;
        String zamanold,zamannew;
    SQLite_Table tt;
    public  String veri[][];              // String formunda ç?kt? de?i?kenleri
    public Monitor6(String s,String veritabanii,String veritablosui[],double ymini,double ymaxi)
    {  ymin=ymini;
       ymax=ymaxi;
	    veritabani=veritabanii; 
        veritablosu=veritablosui;
	    portId=portId(s);
    System.out.println("portID is read");
      try { serialPort = (SerialPort)
            portId.open(s, 2000);
                    } catch ( gnu.io.PortInUseException e) {}
                    try {
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {}
                    try {
                        serialPort.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                    } catch ( gnu.io.UnsupportedCommOperationException e) {}
    T1old=0;
                    dials(); 
                    listTable(0); 
                    timeplot();
}

    //seri ileti?im kanal? aç?lmas?
    public  CommPortIdentifier portId(String s)
    {    portId = PortChooser.select_port(null);            
                    try {
                        serialPort = (SerialPort)
                            portId.open(s, 2000);
                    } catch ( gnu.io.PortInUseException e) {}
    return portId;
    } 
    
    public  void start() 
    {readThread = new Thread(this);
    readThread.start();
    }
    public void run() 
     {  int ix=0;
     int n=1;
      int k=0;
	  while(true)
	  {	  
      try{
	  k++;	 	 
      Thread.sleep(100); 
      try {
      inputStream = serialPort.getInputStream();
                    byte[] readBuffer = new byte[30];
                    long[] readBuffer1 = new long[30];
                    byte numBytes = (byte)inputStream.read(readBuffer);
                    //System.out.println("numBytes="+numBytes);
                    //String s= new String(readBuffer, "US-ASCII");
                    String s= new String(readBuffer);
                    int i=0;
                    for(i=0;i<numBytes;i++)
                    {  readBuffer1[i]=readBuffer[i]&0xFF; 
                     //readBuffer1[i]=readBuffer[i]; 
                    //System.out.print("i = "+i+"*");    
	                //System.out.printf("%x ",readBuffer[i]);
	                }
	                if(s.matches(s2))
	                {  
		                T1=Double.parseDouble(s);}
	                else
	                {T1=T1old;}
	                double T2[]={T1};
	                d1.setData(T2);
	                T1old=T1;
	                veri=new String[n][T2.length+4];
           veri[ix][0]=""+k;
           String zaman[]=zaman();
           veri[ix][1]=zaman[0];
           veri[ix][2]=zaman[1];
           double tt=zaman1(zaman[1]);
           zamannew=zaman[1];
           int cihaz_adresi[]={0};
           veri[ix][3]=""+cihaz_adresi[ix];
           veri[ix][4]=""+T2[0];
           //System.out.print("k=   "+k+" "+zaman[0]+" "+zaman[1]+"cihaz = "+cihaz_adresi[ix]+" ");
           //for(int ii=0;i<T2.length;ii++)
           //     {System.out.print(" T["+ix+"]["+ii+"] ="+T2[ii]+" ");veri[ix][ii+4]=""+T2[ii];}
           d1.setData(T2);
           String ss1="";    
           ss1+="insert into "+veritablosu[ix]+" values(";
           int ii=0;
           for(ii=0;ii<veri[ix].length-1;ii++) {ss1+="'"+veri[ix][ii]+"',";}
           ss1+="'"+veri[ix][ii]+"');";
           System.out.println(ss1);
           try{ writeTable(ss1);
              } catch(ClassNotFoundException e4) {System.out.println("Class not found");}
         zamanold=zamannew;
	      d3.setXY(tt,T2,ymin,ymax);          
	                
	                //System.out.print("T1="+T1);
      } catch (IOException e) {}
      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}
      }
      }
      public double zaman1(String ss)
    {
     StringTokenizer token=new StringTokenizer(ss,":");
     int m=token.countTokens();
     String s1[]=new String[m];
         int j=0;           
         while(token.hasMoreTokens())
         { s1[j]=token.nextToken();j++;}
    double tt=Double.parseDouble(s1[0])*3600+Double.parseDouble(s1[1])*60+Double.parseDouble(s1[2]);
    return tt;
    }

    public  String[] zaman()
    {
	GregorianCalendar calendar;
	Date date=new Date();
	String[] ids = TimeZone.getAvailableIDs(+3 * 60 * 60 * 1000);
    SimpleTimeZone pdt = new SimpleTimeZone(+3 * 60 * 60 * 1000, ids[0]);
    calendar=new GregorianCalendar(pdt);
    calendar.setTime(date); 
    String dt=""+calendar.get(Calendar.DATE);
    if (dt.length()==1) dt="0"+dt;
    String mo=""+(calendar.get(Calendar.MONTH)+1);
    if (mo.length()==1) mo="0"+mo;
    String Sdate=dt+"/"+mo+"/"+calendar.get(Calendar.YEAR);
    String ho=""+(calendar.get(Calendar.AM_PM)*12+calendar.get(Calendar.HOUR));
    if (ho.length()==1) ho="0"+ho;     
    String min=""+calendar.get(Calendar.MINUTE);
     if (min.length()==1) min="0"+min;
    String sec=""+calendar.get(Calendar.SECOND);
    if (sec.length()==1) sec="0"+sec;    
    String Stime=ho+":"+min+":"+sec+" ";
    String z[]={Sdate,Stime};
    return z;
	}
	     	 //Database programs
	 public void createTable(int ix) throws ClassNotFoundException
	 { //  sqlite-JDBC sürücüsünü yükle 
       Class.forName("org.sqlite.JDBC");   
       Connection connection = null;
       int kanalsayisi=1;  //just one channel reading
       try
       {
      // veritaban? ile ba?lant? kur.
      connection = DriverManager.getConnection("jdbc:sqlite:"+veritabani+".db");
      statement = connection.createStatement();
      statement.setQueryTimeout(30);  // set timeout to 30 sec.      
      statement.executeUpdate("drop table if exists "+veritablosu[ix]+";");
      String ss="create table "+veritablosu[ix]+"(no String,tarih String,saat String,kanal String,";
      int i;
      for(i=0;i<kanalsayisi-1;i++) ss+="ch"+i+" String, ";
      ss+="ch"+i+" String);";
      statement.executeUpdate(ss);
      System.out.println("veritablosu = "+veritablosu[ix]);
      String ss1="select * from "+veritablosu[ix]; 
      //tt.setQuerry(ss1);
      }
      catch(SQLException e)
      {
      // if the error message is "out of memory", 
      // it probably means no database file is found
      System.err.println(e.getMessage());
    }
    finally
    {
      try
      {
        if(connection != null)
          connection.close();
      }
      catch(SQLException e)
      {
        // connection close failed.
        System.err.println(e);
      }
      }
      }
     public void writeTable(String querry) throws ClassNotFoundException
	 { //  sqlite-JDBC sürücüsünü yükle 
       Class.forName("org.sqlite.JDBC");   
       Connection connection = null;
       try
       {
      // veritabanı ile bağlantı kur.
      connection = DriverManager.getConnection("jdbc:sqlite:"+veritabani+".db");
      Statement statement = connection.createStatement();
      statement.setQueryTimeout(30);  // set timeout to 30 sec.      
      statement.executeUpdate(querry);
      }
      catch(SQLException e)
      {
      // if the error message is "out of memory", 
      // it probably means no database file is found
      System.err.println(e.getMessage());
    }
    finally
    {
      try
      {
        if(connection != null)
          connection.close();
      }
      catch(SQLException e)
      {
        // connection close failed.
        System.err.println(e);
      }
      }
      }
      public void listTable(int ix)
      { 
      try
      { tt=new SQLite_Table(veritablosu[ix]);tt.setVisible(true);
      } catch(ClassNotFoundException e)
      { // "out of memory" mesajı veri tabanının bulunamadığı anlamına gelir
        System.err.println(e.getMessage());
      }}
public void dials()
{ double n1=Math.PI/2;
double n2=3.0*n1;
String st[]={" Temperature T "};
double td[]={0};
double tmin=0;
double tmax=100.0;
double tetamax=100;
double teta1_rad=Math.PI/4;
double teta2_rad=3.0*Math.PI/2.0+teta1_rad;
d1=new dials1("Arduino analog read","Temperature T",st,td,tmin,tmax,teta1_rad,teta2_rad);
FrameGraphic.plot("ARDUINO Temperature ",d1);
}
//zamana bağlı grafik  
public void timeplot()
{ int nyi=1;
  int nquei=30;
  String pl="ARDUINO Temperature plot";
  String xl="time second";
  String yl="Temperature T";
  int xnt=10;
  int ynt=10;
  int xgr=1;
  int ygr=1;
  int ipti[]={5};
  Color ibg=Color.cyan;
  Color ifg[]={Color.black,Color.blue,Color.red,Color.black,Color.green,Color.cyan,Color.yellow,Color.black};
  d3=new tplot2D(nyi,nquei,pl,xl,yl,xnt,ynt,xgr,ygr,ipti,ibg,ifg); 
  FrameGraphic.plot("Zaman Grafiği ",d3,1300,800);
}       
      public static void main(String arg[]) throws ClassNotFoundException
      { String veritabani="VT";
        String veritablosu[]={"VT1"};
        double ymin=0.0;
        double ymax=100.0;
	      Monitor6 m=new Monitor6("ARDUNIO",veritabani,veritablosu,ymin,ymax);
	      m.createTable(0);
       m.start();
       }
}
