/
SimpleSerial.java
392 lines (325 loc) · 15.3 KB
/
SimpleSerial.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jcan2;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Micha
*/
public class SimpleSerial {
private String serialPortName = "Error - no Port found";
private static final boolean SERIAL_DEBUG = false;
private static final int MAX_DATA_PER_IMPORT = 14;
private static final int WAIT_MS = 50; //time to wait for the device to respond
private static final int WAIT_MS_POINTS = WAIT_MS + 10*MAX_DATA_PER_IMPORT; //time to wait for the device to respond
//Test: 100ms = 15 points
//security factor 200% --> time_ms = 15 ms per point
private boolean deviceConnected = false;
private String currentPortName;
public SimpleSerial(){
super();
}
public String getPortName(){
return serialPortName;
}
public int searchDevicePort() throws InterruptedException{
String[] portNames = SerialPortList.getPortNames();
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nFound ports: " + Arrays.toString(portNames));
int portNumber = -1;
for(int i = 0; i < portNames.length; i++){
currentPortName = portNames[i];
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new PortSearchTask());
try {
String returnPort = future.get(3,TimeUnit.SECONDS);
if(!"NULL".equals(returnPort)){
portNumber = i;
i = portNames.length; //quit loop
}
} catch (ExecutionException ex) {
Logger.getLogger(SimpleSerial.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(SimpleSerial.class.getName()).log(Level.SEVERE, null, ex);
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nOpening port "+currentPortName+" has timed out");
}
executor.shutdownNow();
}
if(portNumber < 0) {
deviceConnected = false;
return 0;
}
else {
serialPortName = portNames[portNumber];
deviceConnected = true;
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nDevice detected on port "+serialPortName);
return 1; //success
}
}
public boolean deviceConnected(){
return deviceConnected;
}
public JSONObject getRealTimeData() throws InterruptedException, JSONException{
if(!"Error - no Port found".equals(serialPortName))
{
try {
SerialPort serialPort = new SerialPort(serialPortName);
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.writeBytes("$ORRTV*11\n".getBytes());//Write data to port
Thread.sleep(WAIT_MS*5);
String realTime = serialPort.readString();
serialPort.closePort();
int temp = 0;
JSONObject output = new JSONObject();
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\n"+realTime);
//decompose the received data
String[] lines = realTime.split("\n");
for (int i=0; i<lines.length; i++){
String[] seperated = lines[i].split(",");
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append(seperated[0]);
if("$BMRTV".equals(seperated[0])){
output.put("err",0);
output.put("temp", Double.parseDouble(seperated[8])); //temp data
output.put("hum", Double.parseDouble(seperated[7]));
output.put("gaz1", Integer.parseInt(seperated[5]));
output.put("gaz2", Integer.parseInt(seperated[6]));
output.put("ax", Double.parseDouble(seperated[9]));
output.put("ay", Double.parseDouble(seperated[10]));
output.put("az", Double.parseDouble(seperated[11]));
return output;
}
}
//error handling
output.put("err",1);
return output;
} catch (SerialPortException ex) {
Logger.getLogger(SimpleSerial.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
//returns the number of points stored or -1 if error
public int importDataFromDevice(JProgressBar progressBar, JTextArea status) throws InterruptedException{
if("Error - no Port found".equals(serialPortName)) return -1;
else{
SerialPort serialPort = new SerialPort(serialPortName);
try {
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.writeBytes("$ORUSR*11\n".getBytes());//Write data to port
Thread.sleep(WAIT_MS);
String userString = serialPort.readString();
long usr = decodeUserID(userString);
if(usr > 0){
BeMapEditor.mainWindow.setUsr(usr);
status.append("\nUser ID: "+usr);
}
else if (usr == -1){
//code for getting usr id from server
//$ORUSR,25*11\n
status.append("\nError: Getting user ID from server not yet supported!");
BeMapEditor.mainWindow.setUsr(3);
}
else {
status.append("\nError: No User ID found! Import aborted.");
return -1;
}
serialPort.writeBytes("$ORNUM*11\n".getBytes());
Thread.sleep(WAIT_MS);
String numberString = serialPort.readString();
int totalNumber = decodeNbPoints(numberString);
if(totalNumber > 0) status.append("\nNumber of points to import: "+totalNumber);
else if (totalNumber == 0) {
status.append("\nNo points stored to import! ");
return 0;
}
else{
status.append("\nError: Number of Points");
return -1;
}
//prepare track to import
BeMapEditor.trackOrganiser.createNewTrack("Import");
int nbRequests = (totalNumber/(MAX_DATA_PER_IMPORT))+1;
int rest = totalNumber - (nbRequests-1) * MAX_DATA_PER_IMPORT; //nb of points for the last request
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nNumber of requests necessary: "+ nbRequests);
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nPoints resting for last request: " + rest);
//init progress bar
progressBar.setMaximum(nbRequests);
for(int i=0; i< (nbRequests-1); i++){
//import serie of points
int offset = i*MAX_DATA_PER_IMPORT;
if(importSerieOfPoints(serialPort,MAX_DATA_PER_IMPORT,offset)<0) return 0;
//actualize progress bar
progressBar.setValue(i+1);
}
int final_offset = (nbRequests-1)*MAX_DATA_PER_IMPORT;
if(importSerieOfPoints(serialPort,rest,final_offset)<0) return 0; //import the rest of the points
progressBar.setValue(nbRequests);
status.append("\n"+totalNumber+" Points successfully imported");
serialPort.writeString("$ORMEM*11\n");
Thread.sleep(WAIT_MS);
decodeMemoryState(serialPort.readString());
serialPort.closePort();//Close serial port
return 1;
}
catch (SerialPortException ex) {
return 0;//do not print error
}
}
}
public int sendDeleteRequest(){
if("Error - no Port found".equals(serialPortName)) return -1;
else{
SerialPort serialPort = new SerialPort(serialPortName);
try {
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.writeString("$ORCLR*11\n");
serialPort.closePort();
return 1;
}
catch (SerialPortException ex) {
return 0;//do not print error
}
}
}
public int updateMemoryState() throws InterruptedException{
if("Error - no Port found".equals(serialPortName)) return -1;
else{
SerialPort serialPort = new SerialPort(serialPortName);
try {
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.writeString("$ORMEM*11\n");
Thread.sleep(WAIT_MS);
decodeMemoryState(serialPort.readString());
serialPort.closePort();
return 1;
}
catch (SerialPortException ex) {
return 0;//do not print error
}
}
}
private void decodeMemoryState(String memoryState){
//decompose the received data
String[] lines = memoryState.split("\n");
for (int i=0; i<lines.length; i++){
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append(lines[i]+"\n");
String[] seperated = lines[i].split(",");
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("Received: "+lines[i]+"\n");
if("$BMMEM".equals(seperated[0])){
int a = Integer.parseInt(seperated[1]);
int b = Integer.parseInt(seperated[2]);
int state = a / b;
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("Memory state: "+state+"\n");
BeMapEditor.mainWindow.setBar(state);
}
else if("$BMERR".equals(seperated[0])){
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("Memory state error\n");
}
else if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("Memory state error\n");
}
}
private int importSerieOfPoints(SerialPort serialPort, int nb,int offset) throws InterruptedException {
try {
String send = "$ORGET,"+offset+","+nb+"*11\n";
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nSent request: "+send);
serialPort.writeBytes(send.getBytes());
Thread.sleep(WAIT_MS_POINTS);
String answer = serialPort.readString();
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nAnswer: "+answer);
if(BeMapEditor.trackOrganiser.getData().treatData(answer)==nb) return 1;
else return 0;
} catch (SerialPortException ex) {
Logger.getLogger(SimpleSerial.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
private int decodeNbPoints(String numberString){
//decompose the received data
String[] lines = numberString.split("\n");
int nbPoints = -1;
for (int i=0; i<lines.length; i++){
String[] seperated = lines[i].split(",");
if("$BMNUM".equals(seperated[0])){
nbPoints = Integer.parseInt(seperated[1]);
return nbPoints;
}
}
return nbPoints;
}
//returns usr id from string or -1 if error
private long decodeUserID(String userString){
//decompose the received data
String[] lines = userString.split("\n");
for (int i=0; i<lines.length; i++){
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append(lines[i]+"\n");
String[] seperated = lines[i].split(",");
if("$BMUSR".equals(seperated[0])){
return Long.parseLong(seperated[1]);
}
else if("$BMERR".equals(seperated[0])){
return -1;
}
}
return -1;
}
class PortSearchTask implements Callable<String> {
@Override
public String call() throws Exception {
String port = "NULL";
SerialPort serialPort = new SerialPort(currentPortName);
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nOpening port "+currentPortName);
try {
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.writeBytes("$ORUSR*11\n".getBytes());//Write data to port
Thread.sleep(WAIT_MS);
byte[] buffer = serialPort.readBytes(1);//Read 1 bytes from serial port
if(buffer[0] == 36) port = currentPortName; //success on this port when device answers with $
else if (SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nError: Port found but device doesn't answer with $");
serialPort.closePort();//Close serial port
}
catch (SerialPortException ex) {
//do not print error
if(SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nOpening port "+currentPortName+" failed");
}
return port;
}
}
}