27
27
import processing.serial.* ;
28
28
import java.util.Map ;
29
29
30
+ import java.util.concurrent.Callable ;
31
+ import java.util.concurrent.ExecutorService ;
32
+ import java.util.concurrent.Executors ;
33
+ import java.util.concurrent.Future ;
34
+ import java.util.concurrent.TimeUnit ;
35
+ import java.util.concurrent.TimeoutException ;
36
+
30
37
// FLAG FOR DEBUG MODE
31
38
final boolean DEBUG = false ;
32
39
@@ -36,6 +43,7 @@ final String INNER_KEY = "@";
36
43
final int MARGIN_SZ = 20 ; // between plots
37
44
final int BG_COL = 75 ; // background
38
45
final int PORT_INTERVAL = 5000 ; // time to sit on each port
46
+ final int CONNECT_TIMEOUT = 2000 ; // force timeout on connecting to serial port
39
47
final int BAUD_RATE = 115200 ;
40
48
final HashMap<String , Integer > COLORMAP = new HashMap<String , Integer > ()
41
49
{
@@ -323,20 +331,55 @@ void attemptConnect( int index )
323
331
// Attempt connect on specified serial port
324
332
String portName = Serial . list()[portIndex];
325
333
println ( " Attempting connect on port: " + portName );
334
+
335
+ // Wrap Serial port connect in future to force timeout
336
+ ExecutorService exec = Executors . newSingleThreadExecutor();
337
+ Future<Serial > future = exec. submit( new ConnectWithTimeout ( this , portName, BAUD_RATE ) );
338
+
326
339
try
327
340
{
328
- // Configure
329
- port = new Serial ( this , portName, BAUD_RATE );
341
+ // Do connect with timeout
342
+ port = future . get( CONNECT_TIMEOUT , TimeUnit . MILLISECONDS );
330
343
331
344
lastPortSwitch = millis (); // at end so that we try again immediately on invalid port
332
345
println ( " Connected on " + portName + " . Listening for configuration..." );
333
346
}
347
+ catch ( TimeoutException e )
348
+ {
349
+ future. cancel( true );
350
+ if ( DEBUG )
351
+ {
352
+ println ( " Timeout." );
353
+ }
354
+ }
334
355
catch ( Exception e )
335
356
{
336
357
if ( DEBUG )
337
358
{
338
359
println ( e. getMessage() );
339
360
}
340
- delay ( 100 );
341
361
}
342
- }
362
+
363
+ exec. shutdownNow();
364
+ }
365
+
366
+ // Callable class to wrap Serial connect
367
+ class ConnectWithTimeout implements Callable<Serial >
368
+ {
369
+ private final PApplet parent;
370
+ private final String portName;
371
+ private final int baudRate;
372
+
373
+ public ConnectWithTimeout ( PApplet parent, String portName, int baud )
374
+ {
375
+ this . parent = parent;
376
+ this . portName = portName;
377
+ this . baudRate = baud;
378
+ }
379
+
380
+ @Override
381
+ public Serial call() throws Exception
382
+ {
383
+ return new Serial ( this . parent, this . portName, baudRate );
384
+ }
385
+ }
0 commit comments