package com.xhochy.hsg;

import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;

public class NetzHW {
	private CommPortIdentifier portId;
	private SerialPort realPort;
	
	/**
	 * Der Konstruktor, öffnet direkt den seriellen Port und setzt das Ausgabebit auf 1
	 * 
	 * @param portName Der Name des Ports, bei Windwos z.B. COM1, bei Linux z.B. /dev/ttyS0 
	 * @throws NoSuchPortException
	 * @throws PortInUseException
	 * @throws UnsupportedCommOperationException
	 */
	public NetzHW (String portName) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
		portId = CommPortIdentifier.getPortIdentifier(portName);
		realPort = (SerialPort) portId.open("com.xhochy.hsg.NetzHW", 2000);
		realPort.setSerialPortParams(2400,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1 ,
                SerialPort.PARITY_NONE);
		
		// Setzte standardmäßig alle Ausgaben an
		realPort.setDTR(true);
		realPort.setRTS(true);
	}
	
	/**
	 * Setzt das Ausgabebit
	 * 
	 * @param ausgabe true -> 1 ; false -> 0
	 */
	public void setAus(boolean ausgabe) {
		realPort.setRTS(ausgabe);
	}
	
	public boolean getEin() {
		return realPort.isCTS();
	}
	
	/**
	 * Schließt den Port, dringend notwendig bei Benutzung einer 
	 * Entwicklungsumgebung wie Eclipse oder NetBeans.
	 * 
	 * !!! Aufruf nicht vergessen !!!
	 * 
	 * Achtung: Das Ausgabebit wird nicht direkt auf 0 gesetzt, sondern verbleibt
	 * je nach Umgebung noch bis zu 2 sec auf 1.
	 */
	public void close() {
		realPort.close();
	}
}

