SerialCom.java 2.1 KB
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

public class SerialCom {
	private static final int DATA_RATE = 9600;
	private static final int TIME_OUT = 2000;
	private static final int BUFFER_SIZE = 1024;
	
	private SerialPort serialPort;
	private InputStream input;
	private OutputStream output;
	
	public SerialCom(int portNumberWindows) { this("COM" + String.valueOf(portNumberWindows)); }
	public SerialCom(String portName) {
		CommPortIdentifier portId = null;
		Enumeration<?> portEnum = CommPortIdentifier.getPortIdentifiers();
		
		// Search for serial port
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
			if (currPortId.getName().equals(portName)) {
				portId = currPortId;
				break;
			}
		}
		if (portId == null)
			throw new SerialComPortException(portName);
		
		// open connection
		try {
			serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
			serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

			input = serialPort.getInputStream();
			output = serialPort.getOutputStream();
		} catch (IOException
				| UnsupportedCommOperationException
				| PortInUseException e) {
			throw new SerialComPortException(portName);
		}
	}
	
	public void close() {
		try {
			input.close();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		serialPort.removeEventListener();
		serialPort.close();
	}
	public void send(byte[] bytes) {
		try {
			this.output.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public byte[] recieve() {
		byte[] buffer = new byte[BUFFER_SIZE];
		int len = -1;
		
		try { len = this.input.read(buffer); }
		catch (IOException e) { return null; }
		
		if(len == -1 || len == 0)
			return null;
		byte[] data = new byte[len];
		for(int i=0; i<len; i++)
			data[i] = buffer[i];
		return data;
	}
}