package atcommandes;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.Enumeration;
import java.util.Vector;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;


public class Test {

 


    static BufferedReader bufRead; //flux de lecture du port
    static OutputStream outStream; //flux d'écriture du port
    static CommPortIdentifier portId; //identifiant du port
    static SerialPort sPort; //le port série
    static BufferedOutputStream out;
    static InputStream in;

    public boolean run(String port, String sMessage, String sNum) {
    try {
    Runtime run=Runtime.getRuntime();
    String cmd="java -classpath D:\\dev_hugu\\DemoSOA\\ATCommandes\\classes;D:\\productORACLE\\10.1.3.1\\jdev10.1.3.3\\jdk\\lib\\comm.jar atcommandes.Test "+port+" \""+sMessage+"\" "+sNum;
    System.out.println("== SMS ============= "+ cmd);
    run.exec(cmd);
    return true;
    } catch (Exception ex) {ex.printStackTrace();return false;}
    } 
            
             /**
              * Méthode principale de l'exemple.
              */
              public static void main(String[] args) {
                  String port = args[0];
                  String sMessage = args[1];
                  String sNum = args[2];

                  String commande [] = new String[6];
                  commande[0]="AT";
                  commande[1]="ATi3";
                  commande[2]="AT+CMGF=1";
                  commande[3]="AT+CSMP?";
                  commande[4]="AT+CSMP=17,167,0,16";
                  commande[5]="AT+CMGS=\""+sNum+"\"";
                  //commande[6]="Test from java";

                  Test test = new Test();
                  test.getPortList();
                  test.UtilisationFlux(port);

                    try {
                    
                        for (int i=0;i<commande.length;i++)
                        {
                        System.out.println("-cde AT ="+commande[i]);
                        test.sendAT(commande[i]);
                        Thread.sleep(1000);
                        }
                        test.sendMessageText(sMessage);                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    test.close();
              }
            
            public void SMS (String sMessage, String port)
            {
            

              String commande [] = new String[5];
              commande[0]="AT";
              commande[1]="ATi3";
              commande[2]="AT+CMGF=1";
              //commande[3]="AT+CSMP?";
              commande[3]="AT+CSMP=17,167,0,16";
              commande[4]="AT+CMGS=\"0629338379\"";

                
              System.out.println("-- sMessage ="+sMessage+" -- port="+port);

              Test test = new Test();
              test.getPortList();
              test.UtilisationFlux(port);

                  try {
                  
                      for (int i=0;i<commande.length;i++)
                      {
                      System.out.println("-cde AT ="+commande[i]);
                      test.sendAT(commande[i]);
                      Thread.sleep(1000);
                      test.sendMessageText(sMessage);
                      }
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  test.close();
            }
            /**
             * Constructeur
             */
            public static void UtilisationFlux(String port) {
                    //initialisation du driver
                    /*
                    Win32Driver w32Driver = new Win32Driver();
                    w32Driver.initialize();
                    */
                    //récupération de l'identifiant du port
                    try {
                            portId = CommPortIdentifier.getPortIdentifier(port);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //ouverture du port
                    try {
                            sPort = (SerialPort) portId.open("SMShugu", 30000);
                    } catch (Exception e) {
                    e.printStackTrace();
                    }
                    //règle les paramètres de la connexion
                    try {
                            sPort.setSerialPortParams(
                                    9600,
                                    SerialPort.DATABITS_8,
                                    SerialPort.STOPBITS_1,
                                    SerialPort.PARITY_NONE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //récupération du flux de lecture et écriture du port
          
                    
                    try {
                        in =  sPort.getInputStream();
                        out = new BufferedOutputStream(sPort.getOutputStream());
                        Thread.sleep(3000);

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                    e.printStackTrace();
            // TODO
        }
    }

            /**
             * Méthode de fermeture des flux et port.
             */
            public static void close(){
                    try {
                            in.close();
                            out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    sPort.close();
            }
          
    private static String sendMessageText(String command) throws Exception 
    {
            byte b = 0x1A;    //CTRL-Z character
            
            System.out.println("Sending: "+command);
            out.write(command.getBytes());
            out.write(b);
            out.flush();
            String response = read();
            System.out.println("Response: "+response);
            return response;
            
    }

    private static String sendAT(String command) throws Exception {
       
          //System.out.println("AT: "+command);
          out.write((command+"\r\n").getBytes());
          out.flush();
          String response = read();
          //System.out.println("Response: "+response);
          return response;
       
    }

    private static String read() throws Exception {
       int n, i;
       char c;
       String answer = new String("");
       System.out.println("Reading ...\n");
       do {
          Thread.sleep(100);
       }
       while (!(in.available()>0));
       for (i = 0; i < 5; i++) {
          while (in.available()>0) {
             //System.out.println("Available: "+in.available());
             n = in.read();
             if (n != -1) {
                c = (char) n;
                answer = answer + c;
                Thread.sleep(2);
                Thread.sleep(2);
             }else{
                break;
             }
          }
          Thread.sleep(100);
       }
        System.out.println("answer="+answer);
       return answer.trim();
    }

    
    public static void getPortList()
    {
    
        //initialisation du driver
        /*
        Win32Driver w32Driver= new Win32Driver();
        w32Driver.initialize();
        */
        //récupération de l'énumération
        Enumeration portList=CommPortIdentifier.getPortIdentifiers();
        //affichage des noms des ports
        CommPortIdentifier portId;
        while (portList.hasMoreElements()){
                portId=(CommPortIdentifier)portList.nextElement();
                System.out.println(portId.getName());
        } 

    
    }

    public static Vector getAvailableSerialPorts() {

        CommPortIdentifier pId=null;

        SerialPort sPort=null;

        Enumeration pList=null;

        boolean foundport=false;

        pList = CommPortIdentifier.getPortIdentifiers();

        String port=null;

        Vector ports=new Vector();

 

        if(!pList.hasMoreElements()) {

            System.err.print("warning: no ports found - "); 

            System.err.println("make sure javax.comm.properties file is found");

            return ports;

        }

        while (pList.hasMoreElements()) {

            pId = (CommPortIdentifier) pList.nextElement();

            if (pId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

                foundport=true;

                try {

                    sPort = (SerialPort)pId.open("serialport", 1000);                    

                } catch (PortInUseException e) {

                    foundport=false;

                    System.out.println(pId.getName()+ " is closed");

                } finally {

                    if(sPort!=null) { 

                        try { sPort.close(); } catch(Exception e) {}

                    }

                    if(foundport) {

                        ports.add(pId.getName());

                        System.out.println(pId.getName()+ " is open");

                    }

                }

            }

        }

        return ports;

    }

}

