import java.io.*;
import java.util.*;
import gnu.io.*;


public class PortList {

	private static SerialPort serialPort;
	private static InputStream inputStream;
	private static OutputStream outputStream;
	
	private static final String initcmd1 = "AT+CMGF=0";
	private static final String initcmd2 = "AT+CNMI=1,2,0,0,0";
	private static final String initcmd3 = "AT+CSCS=\'8859-1'";
	private static final String initcmd4 = "AT+CMEE=2";
	private static final String lfcr = "\015";
	private static boolean isInit = false;
	private static final String ctrl = "\032";
	


	public PortList(){}
	
	public boolean connect(CommPortIdentifier portId){
		try{
			serialPort = (SerialPort) portId.open("DiaUP", 3000);	//?what is '3000'		
			inputStream = serialPort.getInputStream();
			outputStream = serialPort.getOutputStream();
			serialPort.setSerialPortParams(9600,
							SerialPort.DATABITS_8,
							SerialPort.STOPBITS_1,
							SerialPort.PARITY_NONE);
			atcmd("");
			atcmd(initcmd1);
			atcmd(initcmd2);
			atcmd(initcmd3);
			atcmd(initcmd4);
			atcmd("");
			isInit = true;
		} catch (PortInUseException e){e.printStackTrace();}
		  catch (IOException e){e.printStackTrace();}	
		  catch (InterruptedException e){e.printStackTrace();}
		  catch (UnsupportedCommOperationException e){e.printStackTrace();}
		return isInit;
	}	

	private String atcmd(String AT_Command) throws InterruptedException, IOException{
		outputStream.write(AT_Command.getBytes());
		outputStream.write(lfcr.getBytes());
		Thread.sleep(1000);

		return getMessage();
	}

	private String getMessage() throws IOException{
		int n;
		String msg = "";
		try{
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			n = inputStream.available();
			for (int i=0; i<n; i++){
				msg += (char)in.read();
			}

		} catch (IOException e){
			System.out.println("Serial Event GetMessage Exception."+e.getMessage());
		}
		return msg;
		
	}


	public String send(String message) throws InterruptedException, Exception{
		return atcmd(message);
	}
	
	public void close () throws IOException {
		serialPort.close();
		inputStream.close();
		outputStream.close();
	}




	public static void main(String args[]) {


	
System.out.println("start...");

	/*
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
	while ( portList.hasMoreElements() ) {
		CommPortIdentifier port = (CommPortIdentifier)portList.nextElement();
		System.out.println("port : "+port.getName());
        }

	*/	

	try{
System.out.println("try-begin");
   		PortList client = new PortList();
		System.out.println(" Connect==>"+(client.connect(CommPortIdentifier.getPortIdentifier("/dev/ircomm_tty"))));
		System.out.println("AT command ==>"+client.send("AT"));
		client.close();
		
	} catch (Exception e){
System.out.println("catch");
		e.printStackTrace();
	}

System.out.println("end...");
    }

}


