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

public class Wind2SerialLink extends Wind2Link
{
	protected SerialPort p = null;
	protected BufferedReader i = null;
//	protected PrintWriter o = null;

	protected String wantedPortName;

	public Wind2SerialLink(IniFile ini) {
		wantedPortName = ini.getValue("SERIAL", "port");
	}
		
	public boolean Connect() {
		/* Get all available ports */
		Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();

		/* Find requested port */
		CommPortIdentifier portId = null;
		while (portIdentifiers.hasMoreElements()) {
			CommPortIdentifier p = 
				(CommPortIdentifier)portIdentifiers.nextElement();
			if (p.getPortType() == CommPortIdentifier.PORT_SERIAL
					&& p.getName().equals(wantedPortName)) {
				portId = p;
				break;
			}
		}

		/* Found port? */
		if (portId == null) {
			System.err.println("# Failed to find serial port.");
			return false;
		}

		/* Open port */
		try {
			p = (SerialPort)portId.open("name", 100);
		} catch (PortInUseException e) {
			System.err.println("# Serial port already in use." + e);
			return false;
		}

		/* Setup port */
		try {
			p.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
			p.enableReceiveTimeout(65000); /* as long of timeout as possible, fight win32 rxtx bug */
		} catch ( Exception e ) {
			System.err.println("# Error configuring serial port.");
			return false;
		}

		/* Create streams for port */
		try {
			i = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
//			o = new PrintStream(p.getOutputStream(), true);
		} catch (IOException e) {
			System.err.println("# Failed to create stream.");
			return false;
		}

		p.disableReceiveThreshold();

		return true;
	}
	
	public String getLine() {
		String line;

      while ( true ) {
			try {
				line=i.readLine();
				
				/* reached the end of the stream */
				if ( line == null ) {
					break;
				}
			} catch ( IOException e ) {
				System.err.println("# readLine had an exception. Probably due to windows rxtx bug: " + e);
				continue;
			}
			
			if ( line != null ) {
				return line;
			}
		}

		return "";

/*
		try {
			line = i.readLine();
		} catch (IOException e) {
			line = null;
		}
		return line;
*/
	}
	
	public boolean Disconnect() {
		try {
//			o.close();
			i.close();
			p.close();
		} catch (IOException e) {
			System.err.println("Failed to close.");
			return false;
		}

		return true;
	}

	public static void main (String args[]) {
		Wind2Link l = new Wind2SerialLink(new IniFile(args[0]));

		System.out.println("Connecting...");
		l.Connect();
		System.out.println("Connected.");

		System.out.println("Reading...");
		String line = null;
		while ((line = l.getLine()) != null)
			System.out.println(line);
		System.out.println("Done.");

		l.Disconnect();
	}
}
