import java.io.*;
import javax.comm.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;


public class COM_IO implements Runnable,SerialPortEventListener
	{	
		static CommPortIdentifier portId;
    static Enumeration portList;
	  
    SerialPort serialPort;
    Thread readThread;	
    private InputStream serialInput;
		private OutputStream serialOutput;
		private String AT_REQUEST="AT+CREG=2;+CREG?;+CSQ;+COPS=3,0;+COPS?\r\n";	
		private javax.swing.Timer timer=new javax.swing.Timer(3000,new Timeout());
		
		public static void main(String[] arg) throws Exception
			{	portList=CommPortIdentifier.getPortIdentifiers();
				
				while (portList.hasMoreElements())
        	{	portId=(CommPortIdentifier) portList.nextElement();
        	System.out.println(portId.getName());
        		//if ((portId.getPortType() == CommPortIdentifier.PORT_SERIAL) && (portId.getName().equals("COM5")))
        					{	System.out.println("**** SERIAL PORT COM5 FOUND.");
        						new COM_IO();
        						
        					};
         	};
	    } 	
   
	    
	  public COM_IO() throws Exception
     	{	serialPort=(SerialPort) portId.open("COM_IO",2000);
     		serialPort.addEventListener(this);
     		serialPort.notifyOnDataAvailable(true);
     		serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
				serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
				serialInput=serialPort.getInputStream();
     		serialOutput=serialPort.getOutputStream();
     		System.out.println("**** SERIAL PORT COM5 OPEN.");
     		readThread = new Thread(this);
        readThread.start(); 
        
     	}
     
     public void run() 
     	{	try
     			{ timer.start();
     				while (true);
     						
     			}
     		catch (Exception e)
     			{	e.printStackTrace();
     			}
     	}
     	
     	
     public void serialEvent(SerialPortEvent event) 
     	{	if (event.getEventType()==SerialPortEvent.DATA_AVAILABLE)
     			{	try 
     					{ while(serialInput.available()>0) System.out.print((char)serialInput.read()); 								
     						
     					} 
     				catch (Exception e) 
     					{	e.printStackTrace();
	  					}
     			}
     	}
     	
     public class Timeout implements ActionListener
			{	public void actionPerformed(ActionEvent e)
					{	try
							{	System.out.println("**** SENDING AT COMMAND:......"+AT_REQUEST);
     						System.out.println("**** RESPONSE:");
     						serialOutput.write(AT_REQUEST.getBytes());
							}
						catch (Exception ex)
							{	ex.printStackTrace();
							}
					}
			}

     		
     			
         
     		
     	}



