/
Communicator.java
269 lines (230 loc) · 8.42 KB
/
Communicator.java
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package thePackage;
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
public class Communicator implements SerialPortEventListener
{
//passed from main GUI
popUpGUI window = null;
//for containing the ports that will be found
@SuppressWarnings("rawtypes")
private Enumeration ports = null;
//map the port names to CommPortIdentifiers
@SuppressWarnings("rawtypes")
private HashMap portMap = new HashMap();
//this is the object that contains the opened port
private CommPortIdentifier selectedPortIdentifier = null;
private SerialPort serialPort = null;
//input and output streams for sending and receiving data
private InputStream input = null;
private static OutputStream output = null;
//just a boolean flag that i use for enabling
//and disabling buttons depending on whether the program
//is connected to a serial port or not
private boolean bConnected = false;
//the timeout value for connecting with the port
final static int TIMEOUT = 2000;
//some ascii values for for certain things
final static int SPACE_ASCII = 32;
final static int DASH_ASCII = 45;
final static int NEW_LINE_ASCII = 10;
//a string for recording what goes on in the program
//this string is written to the GUI
static String logText = "";
static String outPut = "";
public Communicator(popUpGUI window)
{
this.window = window;
}
//search for all the serial ports
//pre: none
//post: adds all the found ports to a combo box on the GUI
@SuppressWarnings("unchecked")
public void searchForPorts()
{
ports = CommPortIdentifier.getPortIdentifiers();
while (ports.hasMoreElements())
{
CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();
//get only serial ports
if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
window.cboxPorts.addItem(curPort.getName());
portMap.put(curPort.getName(), curPort);
}
}
}
//connect to the selected port in the combo box
//pre: ports are already found by using the searchForPorts method
//post: the connected comm port is stored in commPort, otherwise,
//an exception is generated
public void connect()
{
String selectedPort = (String)window.cboxPorts.getSelectedItem();
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try
{
//the method below returns an object of type CommPort
commPort = selectedPortIdentifier.open("theControlPanel", TIMEOUT);
//the CommPort object can be casted to a SerialPort object
serialPort = (SerialPort)commPort;
//for controlling GUI elements
setConnected(true);
//logging
logText = selectedPort + " opened successfully.";
window.txtLog.setForeground(Color.black);
window.txtLog.append(logText + "\n");
//CODE ON SETTING BAUD RATE ETC OMITTED
//XBEE PAIR ASSUMED TO HAVE SAME SETTINGS ALREADY
setSerialPortParameters();
//enables the controls on the GUI if a successful connection is made
window.keybindingController.toggleControls();
}
catch (PortInUseException e)
{
logText = selectedPort + " is in use. (" + e.toString() + ")";
window.txtLog.setForeground(Color.RED);
window.txtLog.append(logText + "\n");
}
catch (Exception e)
{
logText = "Failed to open " + selectedPort + "(" + e.toString() + ")";
window.txtLog.append(logText + "\n");
window.txtLog.setForeground(Color.RED);
}
}
// Sets the Serial Port Parameters such as BAUD Rate, DataBites, Stopbits...
private void setSerialPortParameters() throws IOException {
int baudRate = 9600;
try {
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException ex) {
throw new IOException("Unsupported serial port parameter");
}
}
//open the input and output streams
//pre: an open port
//post: initialized intput and output streams for use to communicate data
public boolean initIOStream()
{
//return value for whather opening the streams is successful or not
boolean successful = false;
try {
//
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
writeData(0);
successful = true;
return successful;
}
catch (IOException e) {
logText = "I/O Streams failed to open. (" + e.toString() + ")";
window.txtLog.setForeground(Color.red);
window.txtLog.append(logText + "\n");
return successful;
}
}
//starts the event listener that knows whenever data is available to be read
//pre: an open serial port
//post: an event listener for the serial port that knows when data is received
public void initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
logText = "Too many listeners. (" + e.toString() + ")";
window.txtLog.setForeground(Color.red);
window.txtLog.append(logText + "\n");
}
}
//disconnect the serial port
//pre: an open serial port
//post: closed serial port
public void disconnect()
{
//close the serial port
try
{
writeData(0);
serialPort.removeEventListener();
serialPort.close();
input.close();
output.close();
setConnected(false);
window.keybindingController.toggleControls();
logText = "Disconnected.";
window.txtLog.setForeground(Color.red);
window.txtLog.append(logText + "\n");
}
catch (Exception e)
{
logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")";
window.txtLog.setForeground(Color.red);
window.txtLog.append(logText + "\n");
}
}
final public boolean getConnected()
{
return bConnected;
}
public void setConnected(boolean bConnected)
{
this.bConnected = bConnected;
}
//what happens when data is received
//pre: serial event is triggered
//post: processing on the data it reads
public void serialEvent(SerialPortEvent evt) {
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
byte singleData = (byte)input.read();
if (singleData != NEW_LINE_ASCII) {
logText = new String(new byte[] {singleData});
window.txtLog.append(logText);
outPut = logText;
System.out.println(logText);
} else {
window.txtLog.append("\n");
System.out.println("\n");
}
}
catch (Exception e) {
logText = "Failed to read data. (" + e.toString() + ")";
window.txtLog.setForeground(Color.red);
window.txtLog.append(logText + "\n");
}
}
}
//method that can be called to send data
//pre: open serial port
//post: data sent to the other device
public static void writeData(int asciiToWrite) {
try {
output.write(asciiToWrite);
output.flush();
} catch (Exception e) {
logText = "Failed to write data. (" + e.toString() + ")";
//window.txtLog.setForeground(Color.red);
//window.txtLog.append(logText + "\n");
}
}
public static String getOutPut() {
return outPut;
}
}