import java.io.*;
import javax.comm.*;

public class ComListener {
	private static CommPortIdentifier portId;
	private static InputStream inputStream;
	private static OutputStream outputStream;
	private static SerialPort serialPort;

	ComListener(String comPort) {
		try{
		    portId = (CommPortIdentifier) CommPortIdentifier.getPortIdentifier(comPort);
		}catch(NoSuchPortException e){
		    e.printStackTrace();
		}
		
		if (portId.isCurrentlyOwned()) {
		    System.out.println("Detected " + portId.getName() + " in use by " + portId.getCurrentOwner());
		    return;
		}
	
		try {
			serialPort = (SerialPort) portId.open("Smart-Its Listener", 2000);
		} catch (PortInUseException e) {
			e.printStackTrace();
			return;
		}
	
		try {
			serialPort.setSerialPortParams(
				115200,
				SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1,
				SerialPort.PARITY_NONE);
				serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
		} catch (UnsupportedCommOperationException e) {
			e.printStackTrace();
			stop();
			return;
		}
	
		try {
			inputStream = serialPort.getInputStream();
			outputStream = serialPort.getOutputStream();
		} catch (IOException e) {
			stop();
		}

	}

	public void stop() {
		if (outputStream != null)
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		if (inputStream != null)
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		if (serialPort != null)
			serialPort.close();

		outputStream = null;
		inputStream = null;
		serialPort = null;
	}

	
	public String readComLine () {
		BufferedReader b = new BufferedReader(new InputStreamReader(inputStream));
		String s="";
		
		try{
			s = b.readLine();
		}catch (Exception e){
			e.printStackTrace();
		}
		return s;
	}
	
	private static void usage(){
		System.out.println("Usage: java ComListener Port");
	}
	
	
	public static void main(String[] args)  {
	
		if (args.length < 1){
			usage();
		}else{
			ComListener comL1 = new ComListener(args[0]);
			System.out.print("Port ");
			System.out.print(args[0]);
			System.out.println(" open...");
			
			while(true){
				String l = comL1.readComLine ();
				System.out.println(l);
			}
		}
	}
	
}
