Skip to content

Commit 8c74ef1

Browse files
committed
Wrapped serial port connect in ExecutorService and Future to force timeout
1 parent 4868342 commit 8c74ef1

File tree

1 file changed

+47
-4
lines changed

1 file changed

+47
-4
lines changed

listener/listener.pde

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@
2727
import processing.serial.*;
2828
import java.util.Map;
2929

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+
3037
// FLAG FOR DEBUG MODE
3138
final boolean DEBUG = false;
3239

@@ -36,6 +43,7 @@ final String INNER_KEY = "@";
3643
final int MARGIN_SZ = 20; // between plots
3744
final int BG_COL = 75; // background
3845
final int PORT_INTERVAL = 5000; // time to sit on each port
46+
final int CONNECT_TIMEOUT = 2000; // force timeout on connecting to serial port
3947
final int BAUD_RATE = 115200;
4048
final HashMap<String, Integer> COLORMAP = new HashMap<String, Integer>()
4149
{
@@ -323,20 +331,55 @@ void attemptConnect( int index )
323331
// Attempt connect on specified serial port
324332
String portName = Serial.list()[portIndex];
325333
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+
326339
try
327340
{
328-
// Configure
329-
port = new Serial( this, portName, BAUD_RATE );
341+
// Do connect with timeout
342+
port = future.get( CONNECT_TIMEOUT, TimeUnit.MILLISECONDS );
330343

331344
lastPortSwitch = millis(); // at end so that we try again immediately on invalid port
332345
println( "Connected on " + portName + ". Listening for configuration..." );
333346
}
347+
catch ( TimeoutException e )
348+
{
349+
future.cancel( true );
350+
if ( DEBUG )
351+
{
352+
println( "Timeout." );
353+
}
354+
}
334355
catch ( Exception e )
335356
{
336357
if ( DEBUG )
337358
{
338359
println( e.getMessage() );
339360
}
340-
delay( 100 );
341361
}
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

Comments
 (0)