Allow the safety sleep timer to be user-configurable when opening a port.

This commit is contained in:
hedgecrw85 2016-12-05 15:24:49 -06:00
parent c943df001f
commit 46790676e6
1 changed files with 22 additions and 5 deletions

View File

@ -334,15 +334,16 @@ public final class SerialPort
private volatile boolean isOpened = false; private volatile boolean isOpened = false;
/** /**
* Opens this serial port for reading and writing. * Opens this serial port for reading and writing with an optional delay time.
* <p> * <p>
* All serial port parameters or timeouts can be changed at any time after the port has been opened. * All serial port parameters or timeouts can be changed at any time before or after the port has been opened.
* <p> * <p>
* Note that calling this method on an already opened port will simply return a value of true. * Note that calling this method on an already opened port will simply return a value of true.
* *
* @param safetySleepTime The number of milliseconds to sleep before opening the port in case of frequent closing/openings.
* @return Whether the port was successfully opened. * @return Whether the port was successfully opened.
*/ */
public final boolean openPort() public final boolean openPort(int safetySleepTime)
{ {
// Return true if already opened // Return true if already opened
if (isOpened) if (isOpened)
@ -379,7 +380,10 @@ public final class SerialPort
} }
} }
try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } // Force a sleep to ensure that the port does not become unusable due to rapid closing/opening on the part of the user
if (safetySleepTime > 0)
try { Thread.sleep(safetySleepTime); } catch (Exception e) { e.printStackTrace(); }
if ((portHandle = openPortNative()) > 0) if ((portHandle = openPortNative()) > 0)
{ {
inputStream = new SerialPortInputStream(); inputStream = new SerialPortInputStream();
@ -390,6 +394,19 @@ public final class SerialPort
return isOpened; return isOpened;
} }
/**
* Opens this serial port for reading and writing.
* <p>
* This method is equivalent to calling {@link #openPort} with a value of 1000.
* <p>
* All serial port parameters or timeouts can be changed at any time before or after the port has been opened.
* <p>
* Note that calling this method on an already opened port will simply return a value of true.
*
* @return Whether the port was successfully opened.
*/
public final boolean openPort() { return openPort(1000); }
/** /**
* Closes this serial port. * Closes this serial port.
* <p> * <p>