Skip to content

Commit

Permalink
improved error handling for read() with concurrent close() (#569)
Browse files Browse the repository at this point in the history
reworked previous solution from change 8b9ad7e / v3.7.1 because closeInt() was not working any more
  • Loading branch information
kai-morich committed Jun 2, 2024
1 parent b136241 commit b794092
Showing 1 changed file with 10 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
protected final int mPortNumber;

// non-null when open()
protected UsbDeviceConnection mConnection = null;
protected UsbDeviceConnection mConnection;
protected UsbEndpoint mReadEndpoint;
protected UsbEndpoint mWriteEndpoint;
protected UsbRequest mUsbRequest;
Expand Down Expand Up @@ -139,18 +139,18 @@ public void close() throws IOException {
if (mConnection == null) {
throw new IOException("Already closed");
}
UsbDeviceConnection connection = mConnection;
mConnection = null;
UsbRequest usbRequest = mUsbRequest;
mUsbRequest = null;
try {
mUsbRequest.cancel();
usbRequest.cancel();
} catch(Exception ignored) {}
mUsbRequest = null;
try {
closeInt();
} catch(Exception ignored) {}
try {
connection.close();
mConnection.close();
} catch(Exception ignored) {}
mConnection = null;
}

protected abstract void closeInt();
Expand All @@ -163,7 +163,7 @@ protected void testConnection(boolean full) throws IOException {
}

protected void testConnection(boolean full, String msg) throws IOException {
if(mConnection == null) {
if(mUsbRequest == null) {
throw new IOException("Connection closed");
}
if(!full) {
Expand All @@ -187,9 +187,7 @@ public int read(final byte[] dest, final int timeout) throws IOException {
public int read(final byte[] dest, final int length, final int timeout) throws IOException {return read(dest, length, timeout, true);}

protected int read(final byte[] dest, int length, final int timeout, boolean testConnection) throws IOException {
if(mConnection == null) {
throw new IOException("Connection closed");
}
testConnection(false);
if(length <= 0) {
throw new IllegalArgumentException("Read length too small");
}
Expand Down Expand Up @@ -240,9 +238,7 @@ public void write(final byte[] src, int length, final int timeout) throws IOExce
long startTime = MonotonicClock.millis();
length = Math.min(length, src.length);

if(mConnection == null) {
throw new IOException("Connection closed");
}
testConnection(false);
while (offset < length) {
int requestTimeout;
final int requestLength;
Expand Down Expand Up @@ -295,7 +291,7 @@ public void write(final byte[] src, int length, final int timeout) throws IOExce

@Override
public boolean isOpen() {
return mConnection != null;
return mUsbRequest != null;
}

@Override
Expand Down

0 comments on commit b794092

Please sign in to comment.