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 Monitor7 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 T2[],T2old[];
    double ymin,ymax;
    //kontrol parametresi
    public String veritabani;
    public String veritablosu[];
    public  Connection connection = null;
    public  Statement statement;
        String zamanold,zamannew;
       public  int ntable;
    SQLite_Table tt;
    public  String veri[][];              // String formunda çıkt? de?i?kenleri
    public Monitor7(String s,String veritabanii,String veritablosui[],double ymini,double ymaxi,int nt)
    {  ntable=nt;
	    ymin=ymini;
       ymax=ymaxi;
	    veritabani=veritabanii; 
        veritablosu=veritablosui;
	    portId=portId(s);
	    T2=new double[nt];
    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) {}
                    
                    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++;	 	 

      try {  
      inputStream = serialPort.getInputStream();
      outputStream = serialPort.getOutputStream();
            int n3=ntable*6;
           byte[] readBuffer = new byte[8];
      // int[] readBuffer1 = new int[40];
    byte numBytes; 
    String s="";  
                   String ssx[]=new String[T2.length];
	                for(int i=1;i<=ntable;i++)
	                {   outputStream.write(i);  
	                     Thread.sleep(800);     
		                 numBytes = (byte)inputStream.read(readBuffer);   
		                 s= new String(readBuffer);  
		                 s=s.trim();		                 	                      
	                     if(s.equals("")) s+=T2old[i]; 
	                     {numBytes = (byte)inputStream.read(readBuffer);   	
		                  Thread.sleep(50);    		
		                 } 
                    if(s.matches(s2))
	                {  
		                T2[i-1]=Double.parseDouble(s);}
	                else
	                {T2[i-1]=T2old[i-1];}
   	                T2old[i-1]=T2[i-1];
                    }
        for(int i=0;i<ntable;i++)
                {//T2[i]=readBuffer[i];
                if(i==3)  System.out.println("fi[2]  = "+T2[i] +" %"); 
                else System.out.println("T["+i+"]  = "+T2[i]+" derece C" );                 
                  }
                d1.setData(T2);
	            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];
           for(int ii=0;ii<T2.length;ii++) veri[ix][4+ii]=""+T2[ii];
           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 
	 T2=new double[ntable];
	 T2old=new double[ntable];
       Class.forName("org.sqlite.JDBC");   
       Connection connection = null;
       int kanalsayisi=ntable;  
       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 T[]=new double[ntable];
System.out.println("ntable="+ntable);
   for(int i=0;i<ntable;i++) {T[i]=0.0;}
	double n1=Math.PI/2;
   double n2=3.0*n1;
   String st[]={" Sıcaklık T1 "," Sıcaklık T2 "," Sıcaklık T3 ","Bağıl nem "+'\u03A6'+"3"};
    String unit[]={" derece C ","derece C "," derece C "," %"};
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",unit,st,T,tmin,tmax,teta1_rad,teta2_rad);
FrameGraphic.plot("ARDUINO Temperature ",d1);
}

//zamana bağlı grafik  
public void timeplot()
{ int nyi=ntable;
  int nquei=30;
  String pl="ARDUINO Sıcaklık ve nem grafiği";
  String xl="zaman saniye";
  String yl="sıcaklık T";
  int xnt=10;
  int ynt=10;
  int xgr=1;
  int ygr=1;
  int ipti[]={0,1,2,3};
  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;
        int nt=4;
	      Monitor7 m=new Monitor7("ARDUNIO",veritabani,veritablosu,ymin,ymax,nt);
	      m.createTable(0);
          m.start();
       }
}
