From e8dc58ab8a57a9d1a3da0aaf9a161d86551a323f Mon Sep 17 00:00:00 2001 From: jskubick Date: Wed, 21 Feb 2024 12:52:50 -0500 Subject: [PATCH] Improved Javadoc for SerialPort.isOpen() to reduce confusion when used with USB serial adapters and Arduino/esp32 boards. --- .../com/fazecast/jSerialComm/SerialPort.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/java/com/fazecast/jSerialComm/SerialPort.java b/src/main/java/com/fazecast/jSerialComm/SerialPort.java index 10e6daf1..030f0571 100644 --- a/src/main/java/com/fazecast/jSerialComm/SerialPort.java +++ b/src/main/java/com/fazecast/jSerialComm/SerialPort.java @@ -656,6 +656,31 @@ public final boolean closePort() /** * Returns whether the port is currently open and available for communication. + *

Warning! This method alone might not reliably indicate the unplugging of a USB serial port, + * including USB ports on popular microcontrollers like Arduino and ESP32. + * (ie, it'll return true after you open the port, then continue to return true even after the interface + * has been unplugged from the USB port). + * In order to detect the port's unplugging, add the following code to your program after opening the SerialPort: + *
+	 *	port.addDataListener(new SerialPortDataListener() {
+	 *	// (atOverride annotations omitted to avoid confusing Javadoc generator, but necessary in actual use)
+     *       public int getListeningEvents() {
+     *           return SerialPort.LISTENING_EVENT_PORT_DISCONNECTED;
+     *       }
+     *       public void serialEvent(SerialPortEvent serialPortEvent) {
+     *           port.closePort();
+     *       }
+     *   });
+	 *	
+ * Once the port has been closed by the event handler, isOpen() will return false, and you can periodically + * attempt to reopen it within your event loop without creating a new SerialPort object: + *
+	 *	if (port.isOpen() == false)
+	 *		port.open();
+	 *	
+ * Note that once a USB serial port has been unplugged and reconnected, it's unlikely (certain?) to + * not work again until the SerialPort object's close() and open() methods have both been called to + * re-establish the connection. * * @return Whether the port is opened. */