Blame view

PercTeacher/Sources/SerialCom.java 2.1 KB
04949080   pfrison   PercTeacher stabl...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  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;
  	}
  }