mirror of
https://github.com/mik3y/usb-serial-for-android
synced 2025-06-08 00:16:13 +00:00
Merge branch 'master' of https://github.com/mik3y/usb-serial-for-android
This commit is contained in:
commit
92b16a8c24
@ -7,19 +7,14 @@ android {
|
|||||||
defaultConfig {
|
defaultConfig {
|
||||||
minSdkVersion 17
|
minSdkVersion 17
|
||||||
targetSdkVersion 28
|
targetSdkVersion 28
|
||||||
|
consumerProguardFiles 'proguard-rules.pro'
|
||||||
|
|
||||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||||
testInstrumentationRunnerArguments = [ // Raspi Windows LinuxVM ...
|
testInstrumentationRunnerArguments = [ // Raspi Windows LinuxVM ...
|
||||||
'rfc2217_server_host': '192.168.0.100',
|
'rfc2217_server_host': '192.168.0.100',
|
||||||
'rfc2217_server_nonstandard_baudrates': 'true', // true false false
|
'rfc2217_server_nonstandard_baudrates': 'true', // true false false
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
|
||||||
release {
|
|
||||||
minifyEnabled false
|
|
||||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
1
usbSerialForAndroid/proguard-rules.pro
vendored
Normal file
1
usbSerialForAndroid/proguard-rules.pro
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
-keep class com.hoho.android.usbserial.driver.* { *; }
|
@ -5,7 +5,7 @@ publishing {
|
|||||||
maven(MavenPublication) {
|
maven(MavenPublication) {
|
||||||
groupId 'com.github.mik3y'
|
groupId 'com.github.mik3y'
|
||||||
artifactId 'usb-serial-for-android'
|
artifactId 'usb-serial-for-android'
|
||||||
version '1.x.0'
|
version '2.1.0a'
|
||||||
afterEvaluate {
|
afterEvaluate {
|
||||||
artifact androidSourcesJar
|
artifact androidSourcesJar
|
||||||
artifact bundleReleaseAar
|
artifact bundleReleaseAar
|
||||||
|
@ -25,6 +25,7 @@ import android.util.Log;
|
|||||||
|
|
||||||
import com.hoho.android.usbserial.driver.CdcAcmSerialDriver;
|
import com.hoho.android.usbserial.driver.CdcAcmSerialDriver;
|
||||||
import com.hoho.android.usbserial.driver.Ch34xSerialDriver;
|
import com.hoho.android.usbserial.driver.Ch34xSerialDriver;
|
||||||
|
import com.hoho.android.usbserial.driver.CommonUsbSerialPort;
|
||||||
import com.hoho.android.usbserial.driver.Cp21xxSerialDriver;
|
import com.hoho.android.usbserial.driver.Cp21xxSerialDriver;
|
||||||
import com.hoho.android.usbserial.driver.FtdiSerialDriver;
|
import com.hoho.android.usbserial.driver.FtdiSerialDriver;
|
||||||
import com.hoho.android.usbserial.driver.ProbeTable;
|
import com.hoho.android.usbserial.driver.ProbeTable;
|
||||||
@ -42,7 +43,11 @@ import org.junit.After;
|
|||||||
import org.junit.AfterClass;
|
import org.junit.AfterClass;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.BeforeClass;
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
import org.junit.rules.TestRule;
|
||||||
|
import org.junit.rules.TestWatcher;
|
||||||
|
import org.junit.runner.Description;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@ -103,6 +108,13 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
private int telnetWriteDelay = 0;
|
private int telnetWriteDelay = 0;
|
||||||
private boolean isCp21xxRestrictedPort = false; // second port of Cp2105 has limited dataBits, stopBits, parity
|
private boolean isCp21xxRestrictedPort = false; // second port of Cp2105 has limited dataBits, stopBits, parity
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public TestRule watcher = new TestWatcher() {
|
||||||
|
protected void starting(Description description) {
|
||||||
|
Log.i(TAG, "===== starting test: " + description.getMethodName()+ " =====");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setUpFixture() throws Exception {
|
public static void setUpFixture() throws Exception {
|
||||||
rfc2217_server_host = InstrumentationRegistry.getArguments().getString("rfc2217_server_host");
|
rfc2217_server_host = InstrumentationRegistry.getArguments().getString("rfc2217_server_host");
|
||||||
@ -164,32 +176,35 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
isCp21xxRestrictedPort = usbSerialDriver instanceof Cp21xxSerialDriver && usbSerialDriver.getPorts().size()==2 && test_device_port == 1;
|
isCp21xxRestrictedPort = usbSerialDriver instanceof Cp21xxSerialDriver && usbSerialDriver.getPorts().size()==2 && test_device_port == 1;
|
||||||
|
|
||||||
if (!usbManager.hasPermission(usbSerialPort.getDriver().getDevice())) {
|
if (!usbManager.hasPermission(usbSerialPort.getDriver().getDevice())) {
|
||||||
final Boolean[] granted = {Boolean.FALSE};
|
Log.d(TAG,"USB permission ...");
|
||||||
|
final Boolean[] granted = {null};
|
||||||
BroadcastReceiver usbReceiver = new BroadcastReceiver() {
|
BroadcastReceiver usbReceiver = new BroadcastReceiver() {
|
||||||
@Override
|
@Override
|
||||||
public void onReceive(Context context, Intent intent) {
|
public void onReceive(Context context, Intent intent) {
|
||||||
granted[0] = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
|
granted[0] = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
|
||||||
synchronized (granted) {
|
|
||||||
granted.notify();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent("com.android.example.USB_PERMISSION"), 0);
|
PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent("com.android.example.USB_PERMISSION"), 0);
|
||||||
IntentFilter filter = new IntentFilter("com.android.example.USB_PERMISSION");
|
IntentFilter filter = new IntentFilter("com.android.example.USB_PERMISSION");
|
||||||
context.registerReceiver(usbReceiver, filter);
|
context.registerReceiver(usbReceiver, filter);
|
||||||
usbManager.requestPermission(usbSerialDriver.getDevice(), permissionIntent);
|
usbManager.requestPermission(usbSerialDriver.getDevice(), permissionIntent);
|
||||||
synchronized (granted) {
|
for(int i=0; i<5000; i++) {
|
||||||
granted.wait(5000);
|
if(granted[0] != null) break;
|
||||||
|
Thread.sleep(1);
|
||||||
}
|
}
|
||||||
assertTrue("USB permission dialog not confirmed", granted[0]);
|
Log.d(TAG,"USB permission "+granted[0]);
|
||||||
|
assertTrue("USB permission dialog not confirmed", granted[0]==null?false:granted[0]);
|
||||||
|
telnetRead(-1); // doesn't look related here, but very often after usb permission dialog the first test failed with telnet garbage
|
||||||
}
|
}
|
||||||
usbOpen(true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() throws IOException {
|
public void tearDown() throws IOException {
|
||||||
try {
|
try {
|
||||||
|
if(usbIoManager != null)
|
||||||
usbRead(0);
|
usbRead(0);
|
||||||
|
else
|
||||||
|
usbSerialPort.purgeHwBuffers(true, true);
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {}
|
||||||
try {
|
try {
|
||||||
telnetRead(0);
|
telnetRead(0);
|
||||||
@ -208,6 +223,33 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
telnetClient = null;
|
telnetClient = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private class TestBuffer {
|
||||||
|
private byte[] buf;
|
||||||
|
private int len;
|
||||||
|
|
||||||
|
private TestBuffer(int length) {
|
||||||
|
len = 0;
|
||||||
|
buf = new byte[length];
|
||||||
|
int i=0;
|
||||||
|
int j=0;
|
||||||
|
for(j=0; j<length/16; j++)
|
||||||
|
for(int k=0; k<16; k++)
|
||||||
|
buf[i++]=(byte)j;
|
||||||
|
while(i<length)
|
||||||
|
buf[i++]=(byte)j;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean testRead(byte[] data) {
|
||||||
|
assertNotEquals(0, data.length);
|
||||||
|
assertTrue("got " + (len+data.length) +" bytes", (len+data.length) <= buf.length);
|
||||||
|
for(int j=0; j<data.length; j++)
|
||||||
|
assertEquals("at pos "+(len+j), (byte)((len+j)/16), data[j]);
|
||||||
|
len += data.length;
|
||||||
|
//Log.d(TAG, "read " + len);
|
||||||
|
return len == buf.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// wait full time
|
// wait full time
|
||||||
private byte[] telnetRead() throws Exception {
|
private byte[] telnetRead() throws Exception {
|
||||||
return telnetRead(-1);
|
return telnetRead(-1);
|
||||||
@ -215,7 +257,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
|
|
||||||
private byte[] telnetRead(int expectedLength) throws Exception {
|
private byte[] telnetRead(int expectedLength) throws Exception {
|
||||||
long end = System.currentTimeMillis() + TELNET_READ_WAIT;
|
long end = System.currentTimeMillis() + TELNET_READ_WAIT;
|
||||||
ByteBuffer buf = ByteBuffer.allocate(4096);
|
ByteBuffer buf = ByteBuffer.allocate(65536);
|
||||||
while(System.currentTimeMillis() < end) {
|
while(System.currentTimeMillis() < end) {
|
||||||
if(telnetReadStream.available() > 0) {
|
if(telnetReadStream.available() > 0) {
|
||||||
buf.put((byte) telnetReadStream.read());
|
buf.put((byte) telnetReadStream.read());
|
||||||
@ -257,13 +299,11 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usbSerialPort.close();
|
usbSerialPort.close();
|
||||||
} catch (IOException ignored) {
|
} catch (Exception ignored) {
|
||||||
}
|
}
|
||||||
usbSerialPort = null;
|
usbSerialPort = null;
|
||||||
}
|
}
|
||||||
if(usbDeviceConnection != null)
|
usbDeviceConnection = null; // closed in usbSerialPort.close()
|
||||||
usbDeviceConnection.close();
|
|
||||||
usbDeviceConnection = null;
|
|
||||||
if(usbIoManager != null) {
|
if(usbIoManager != null) {
|
||||||
for (int i = 0; i < 2000; i++) {
|
for (int i = 0; i < 2000; i++) {
|
||||||
if (SerialInputOutputManager.State.STOPPED == usbIoManager.getState()) break;
|
if (SerialInputOutputManager.State.STOPPED == usbIoManager.getState()) break;
|
||||||
@ -325,14 +365,11 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
} else {
|
} else {
|
||||||
byte[] b1 = new byte[256];
|
byte[] b1 = new byte[256];
|
||||||
while (System.currentTimeMillis() < end) {
|
while (System.currentTimeMillis() < end) {
|
||||||
int len = usbSerialPort.read(b1, USB_READ_WAIT / 10);
|
int len = usbSerialPort.read(b1, USB_READ_WAIT);
|
||||||
if (len > 0) {
|
if (len > 0)
|
||||||
buf.put(b1, 0, len);
|
buf.put(b1, 0, len);
|
||||||
} else {
|
|
||||||
if (expectedLength >= 0 && buf.position() >= expectedLength)
|
if (expectedLength >= 0 && buf.position() >= expectedLength)
|
||||||
break;
|
break;
|
||||||
Thread.sleep(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
byte[] data = new byte[buf.position()];
|
byte[] data = new byte[buf.position()];
|
||||||
@ -473,7 +510,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void openClose() throws Exception {
|
public void openClose() throws Exception {
|
||||||
byte[] data;
|
usbOpen(true);
|
||||||
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
doReadWrite("");
|
doReadWrite("");
|
||||||
@ -485,7 +522,8 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
}
|
}
|
||||||
doReadWrite("");
|
doReadWrite("");
|
||||||
|
|
||||||
usbSerialPort.close();
|
usbClose();
|
||||||
|
usbSerialPort = usbSerialDriver.getPorts().get(test_device_port);
|
||||||
try {
|
try {
|
||||||
usbSerialPort.close();
|
usbSerialPort.close();
|
||||||
fail("already closed expected");
|
fail("already closed expected");
|
||||||
@ -495,13 +533,11 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
usbWrite(new byte[]{0x00});
|
usbWrite(new byte[]{0x00});
|
||||||
fail("write error expected");
|
fail("write error expected");
|
||||||
} catch (IOException ignored) {
|
} catch (IOException ignored) {
|
||||||
} catch (NullPointerException ignored) {
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usbRead(1);
|
usbRead(1);
|
||||||
//fail("read error expected");
|
fail("read error expected");
|
||||||
} catch (IOException ignored) {
|
} catch (IOException ignored) {
|
||||||
} catch (NullPointerException ignored) {
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usbParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
@ -509,34 +545,28 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
} catch (IOException ignored) {
|
} catch (IOException ignored) {
|
||||||
} catch (NullPointerException ignored) {
|
} catch (NullPointerException ignored) {
|
||||||
}
|
}
|
||||||
|
usbSerialPort = null;
|
||||||
|
|
||||||
// partial re-open not supported
|
|
||||||
try {
|
|
||||||
usbSerialPort.open(usbDeviceConnection);
|
|
||||||
//usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
|
||||||
doReadWrite("");
|
|
||||||
fail("re-open not supported");
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
usbSerialPort.close();
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
|
|
||||||
if (usbSerialDriver instanceof Cp21xxSerialDriver) { // why needed?
|
|
||||||
usbIoManager.stop();
|
|
||||||
usbIoManager = null;
|
|
||||||
}
|
|
||||||
// full re-open supported
|
|
||||||
usbClose();
|
|
||||||
usbOpen(true);
|
usbOpen(true);
|
||||||
telnetParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usbParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
doReadWrite("");
|
doReadWrite("");
|
||||||
|
|
||||||
|
// close before iomanager
|
||||||
|
assertEquals(SerialInputOutputManager.State.RUNNING, usbIoManager.getState());
|
||||||
|
usbSerialPort.close();
|
||||||
|
for (int i = 0; i < 1000; i++) {
|
||||||
|
if (usbIoManager.getState() == SerialInputOutputManager.State.STOPPED)
|
||||||
|
break;
|
||||||
|
Thread.sleep(1);
|
||||||
|
}
|
||||||
|
assertEquals(SerialInputOutputManager.State.STOPPED, usbIoManager.getState());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void baudRate() throws Exception {
|
public void baudRate() throws Exception {
|
||||||
|
usbOpen(true);
|
||||||
|
|
||||||
if (false) { // default baud rate
|
if (false) { // default baud rate
|
||||||
// CP2102: only works if first connection after attaching device
|
// CP2102: only works if first connection after attaching device
|
||||||
// PL2303, FTDI: it's not 9600
|
// PL2303, FTDI: it's not 9600
|
||||||
@ -548,33 +578,12 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
// invalid values
|
// invalid values
|
||||||
try {
|
try {
|
||||||
usbParameters(-1, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(-1, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
if (usbSerialDriver instanceof Ch34xSerialDriver)
|
fail("invalid baud rate");
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof FtdiSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof ProlificSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof Cp21xxSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else
|
|
||||||
fail("invalid baudrate 0");
|
|
||||||
} catch (IOException ignored) { // cp2105 second port
|
|
||||||
} catch (IllegalArgumentException ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usbParameters(0, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(0, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
if (usbSerialDriver instanceof ProlificSerialDriver)
|
fail("invalid baud rate");
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof Cp21xxSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else
|
|
||||||
fail("invalid baudrate 0");
|
|
||||||
} catch (ArithmeticException ignored) { // ch340
|
|
||||||
} catch (IOException ignored) { // cp2105 second port
|
|
||||||
} catch (IllegalArgumentException ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -588,8 +597,9 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
else if (usbSerialDriver instanceof CdcAcmSerialDriver)
|
else if (usbSerialDriver instanceof CdcAcmSerialDriver)
|
||||||
;
|
;
|
||||||
else
|
else
|
||||||
fail("invalid baudrate 0");
|
fail("invalid baudrate 1");
|
||||||
} catch (IOException ignored) { // ch340
|
} catch (UnsupportedOperationException ignored) { // ch340
|
||||||
|
} catch (IOException ignored) { // cp2105 second port
|
||||||
} catch (IllegalArgumentException ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -670,14 +680,10 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
public void dataBits() throws Exception {
|
public void dataBits() throws Exception {
|
||||||
byte[] data;
|
byte[] data;
|
||||||
|
|
||||||
|
usbOpen(true);
|
||||||
for(int i: new int[] {0, 4, 9}) {
|
for(int i: new int[] {0, 4, 9}) {
|
||||||
try {
|
try {
|
||||||
usbParameters(19200, i, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, i, 1, UsbSerialPort.PARITY_NONE);
|
||||||
if (usbSerialDriver instanceof ProlificSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else if (usbSerialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
; // todo: add range check in driver
|
|
||||||
else
|
|
||||||
fail("invalid databits "+i);
|
fail("invalid databits "+i);
|
||||||
} catch (IllegalArgumentException ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
}
|
}
|
||||||
@ -687,21 +693,21 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(19200, 7, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 7, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetWrite(new byte[] {0x00});
|
telnetWrite(new byte[] {0x00});
|
||||||
Thread.sleep(1); // one bit is 0.05 milliseconds long, wait >> stop bit
|
Thread.sleep(10); // one bit is 0.05 milliseconds long, wait >> stop bit
|
||||||
telnetWrite(new byte[] {(byte)0xff});
|
telnetWrite(new byte[] {(byte)0xff});
|
||||||
data = usbRead(2);
|
data = usbRead(2);
|
||||||
assertThat("19200/7N1", data, equalTo(new byte[] {(byte)0x80, (byte)0xff}));
|
assertThat("19200/7N1", data, equalTo(new byte[] {(byte)0x80, (byte)0xff}));
|
||||||
|
|
||||||
telnetParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetWrite(new byte[] {0x00});
|
telnetWrite(new byte[] {0x00});
|
||||||
Thread.sleep(1);
|
Thread.sleep(10);
|
||||||
telnetWrite(new byte[] {(byte)0xff});
|
telnetWrite(new byte[] {(byte)0xff});
|
||||||
data = usbRead(2);
|
data = usbRead(2);
|
||||||
assertThat("19000/6N1", data, equalTo(new byte[] {(byte)0xc0, (byte)0xff}));
|
assertThat("19000/6N1", data, equalTo(new byte[] {(byte)0xc0, (byte)0xff}));
|
||||||
|
|
||||||
telnetParameters(19200, 5, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 5, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetWrite(new byte[] {0x00});
|
telnetWrite(new byte[] {0x00});
|
||||||
Thread.sleep(1);
|
Thread.sleep(10);
|
||||||
telnetWrite(new byte[] {(byte)0xff});
|
telnetWrite(new byte[] {(byte)0xff});
|
||||||
data = usbRead(2);
|
data = usbRead(2);
|
||||||
assertThat("19000/5N1", data, equalTo(new byte[] {(byte)0xe0, (byte)0xff}));
|
assertThat("19000/5N1", data, equalTo(new byte[] {(byte)0xe0, (byte)0xff}));
|
||||||
@ -711,33 +717,33 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usbParameters(19200, 7, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 7, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usbWrite(new byte[]{0x00});
|
usbWrite(new byte[]{0x00});
|
||||||
Thread.sleep(1);
|
Thread.sleep(10);
|
||||||
usbWrite(new byte[]{(byte) 0xff});
|
usbWrite(new byte[]{(byte) 0xff});
|
||||||
data = telnetRead(2);
|
data = telnetRead(2);
|
||||||
assertThat("19000/7N1", data, equalTo(new byte[]{(byte) 0x80, (byte) 0xff}));
|
assertThat("19000/7N1", data, equalTo(new byte[]{(byte) 0x80, (byte) 0xff}));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
if(!isCp21xxRestrictedPort)
|
if(!isCp21xxRestrictedPort)
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usbParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usbWrite(new byte[]{0x00});
|
usbWrite(new byte[]{0x00});
|
||||||
Thread.sleep(1);
|
Thread.sleep(10);
|
||||||
usbWrite(new byte[]{(byte) 0xff});
|
usbWrite(new byte[]{(byte) 0xff});
|
||||||
data = telnetRead(2);
|
data = telnetRead(2);
|
||||||
assertThat("19000/6N1", data, equalTo(new byte[]{(byte) 0xc0, (byte) 0xff}));
|
assertThat("19000/6N1", data, equalTo(new byte[]{(byte) 0xc0, (byte) 0xff}));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
if (!(isCp21xxRestrictedPort || usbSerialDriver instanceof FtdiSerialDriver))
|
if (!(isCp21xxRestrictedPort || usbSerialDriver instanceof FtdiSerialDriver))
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usbParameters(19200, 5, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 5, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usbWrite(new byte[] {0x00});
|
usbWrite(new byte[] {0x00});
|
||||||
Thread.sleep(1);
|
Thread.sleep(5);
|
||||||
usbWrite(new byte[] {(byte)0xff});
|
usbWrite(new byte[] {(byte)0xff});
|
||||||
data = telnetRead(2);
|
data = telnetRead(2);
|
||||||
assertThat("19000/5N1", data, equalTo(new byte[] {(byte)0xe0, (byte)0xff}));
|
assertThat("19000/5N1", data, equalTo(new byte[] {(byte)0xe0, (byte)0xff}));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
if (!(isCp21xxRestrictedPort || usbSerialDriver instanceof FtdiSerialDriver))
|
if (!(isCp21xxRestrictedPort || usbSerialDriver instanceof FtdiSerialDriver))
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
@ -753,6 +759,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
byte[] _7s1 = {(byte)0x00, (byte)0x01, (byte)0x7e, (byte)0x7f};
|
byte[] _7s1 = {(byte)0x00, (byte)0x01, (byte)0x7e, (byte)0x7f};
|
||||||
byte[] data;
|
byte[] data;
|
||||||
|
|
||||||
|
usbOpen(true);
|
||||||
for(int i: new int[] {-1, 5}) {
|
for(int i: new int[] {-1, 5}) {
|
||||||
try {
|
try {
|
||||||
usbParameters(19200, 8, 1, i);
|
usbParameters(19200, 8, 1, i);
|
||||||
@ -767,11 +774,11 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
try {
|
try {
|
||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_MARK);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_MARK);
|
||||||
fail("parity mark");
|
fail("parity mark");
|
||||||
} catch (IllegalArgumentException ignored) {}
|
} catch (UnsupportedOperationException ignored) {}
|
||||||
try {
|
try {
|
||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_SPACE);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_SPACE);
|
||||||
fail("parity space");
|
fail("parity space");
|
||||||
} catch (IllegalArgumentException ignored) {}
|
} catch (UnsupportedOperationException ignored) {}
|
||||||
return;
|
return;
|
||||||
// test below not possible as it requires unsupported 7 dataBits
|
// test below not possible as it requires unsupported 7 dataBits
|
||||||
}
|
}
|
||||||
@ -849,6 +856,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
public void stopBits() throws Exception {
|
public void stopBits() throws Exception {
|
||||||
byte[] data;
|
byte[] data;
|
||||||
|
|
||||||
|
usbOpen(true);
|
||||||
for (int i : new int[]{0, 4}) {
|
for (int i : new int[]{0, 4}) {
|
||||||
try {
|
try {
|
||||||
usbParameters(19200, 8, i, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, i, UsbSerialPort.PARITY_NONE);
|
||||||
@ -886,7 +894,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
usbWrite(new byte[]{(byte) 0x41, (byte) 0xf9});
|
usbWrite(new byte[]{(byte) 0x41, (byte) 0xf9});
|
||||||
data = telnetRead(2);
|
data = telnetRead(2);
|
||||||
assertThat("19200/8N1", data, equalTo(new byte[]{1, 11}));
|
assertThat("19200/8N1", data, equalTo(new byte[]{1, 11}));
|
||||||
} catch(IllegalArgumentException e) {
|
} catch(UnsupportedOperationException e) {
|
||||||
if(!isCp21xxRestrictedPort)
|
if(!isCp21xxRestrictedPort)
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
@ -894,7 +902,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
usbParameters(19200, 8, UsbSerialPort.STOPBITS_1_5, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, UsbSerialPort.STOPBITS_1_5, UsbSerialPort.PARITY_NONE);
|
||||||
// todo: could create similar test for 1.5 stopbits, by reading at double speed
|
// todo: could create similar test for 1.5 stopbits, by reading at double speed
|
||||||
// but only some devices support 1.5 stopbits and it is basically not used any more
|
// but only some devices support 1.5 stopbits and it is basically not used any more
|
||||||
} catch(IllegalArgumentException ignored) {
|
} catch(UnsupportedOperationException ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -924,11 +932,91 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
assertEquals(availableDrivers.get(0).getClass(), usbSerialDriver.getClass());
|
assertEquals(availableDrivers.get(0).getClass(), usbSerialDriver.getClass());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void writeTimeout() throws Exception {
|
||||||
|
usbOpen(true);
|
||||||
|
usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
|
// Basically all devices have a UsbEndpoint.getMaxPacketSize() 64. When the timeout
|
||||||
|
// in usbSerialPort.write() is reached, some packets have been written and the rest
|
||||||
|
// is discarded. bulkTransfer() does not return the number written so far, but -1.
|
||||||
|
// With 115200 baud and 1/2 second timeout, typical values are:
|
||||||
|
// ch340 6080 of 6144
|
||||||
|
// pl2302 5952 of 6144
|
||||||
|
// cp2102 6400 of 7168
|
||||||
|
// cp2105 6272 of 7168
|
||||||
|
// ft232 5952 of 6144
|
||||||
|
// ft2232 9728 of 10240
|
||||||
|
// arduino 128 of 144
|
||||||
|
int timeout = 500;
|
||||||
|
int len = 0;
|
||||||
|
int startLen = 1024;
|
||||||
|
int step = 1024;
|
||||||
|
int minLen = 4069;
|
||||||
|
int maxLen = 12288;
|
||||||
|
int bufferSize = 997;
|
||||||
|
TestBuffer buf = new TestBuffer(len);
|
||||||
|
if(usbSerialDriver instanceof CdcAcmSerialDriver) {
|
||||||
|
startLen = 16;
|
||||||
|
step = 16;
|
||||||
|
minLen = 128;
|
||||||
|
maxLen = 256;
|
||||||
|
bufferSize = 31;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (len = startLen; len < maxLen; len += step) {
|
||||||
|
buf = new TestBuffer(len);
|
||||||
|
Log.d(TAG, "write buffer size " + len);
|
||||||
|
usbSerialPort.write(buf.buf, timeout);
|
||||||
|
while (!buf.testRead(telnetRead(-1)))
|
||||||
|
;
|
||||||
|
}
|
||||||
|
fail("write timeout expected between " + minLen + " and " + maxLen + ", is " + len);
|
||||||
|
} catch (IOException e) {
|
||||||
|
Log.d(TAG, "usbWrite failed", e);
|
||||||
|
while (true) {
|
||||||
|
byte[] data = telnetRead(-1);
|
||||||
|
if (data.length == 0) break;
|
||||||
|
if (buf.testRead(data)) break;
|
||||||
|
}
|
||||||
|
Log.d(TAG, "received " + buf.len + " of " + len + " bytes of failing usbWrite");
|
||||||
|
assertTrue("write timeout expected between " + minLen + " and " + maxLen + ", is " + len, len > minLen);
|
||||||
|
}
|
||||||
|
|
||||||
|
// With smaller writebuffer, the timeout is used per bulkTransfer.
|
||||||
|
// Should further calls only use the remaining timout?
|
||||||
|
((CommonUsbSerialPort) usbSerialPort).setWriteBufferSize(bufferSize);
|
||||||
|
len = maxLen;
|
||||||
|
buf = new TestBuffer(len);
|
||||||
|
Log.d(TAG, "write buffer size " + len);
|
||||||
|
usbSerialPort.write(buf.buf, timeout);
|
||||||
|
while (!buf.testRead(telnetRead(-1)))
|
||||||
|
;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void writeFragments() throws Exception {
|
||||||
|
usbOpen(true);
|
||||||
|
usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
|
((CommonUsbSerialPort) usbSerialPort).setWriteBufferSize(12);
|
||||||
|
((CommonUsbSerialPort) usbSerialPort).setWriteBufferSize(12); // keeps last buffer
|
||||||
|
TestBuffer buf = new TestBuffer(256);
|
||||||
|
usbSerialPort.write(buf.buf, 5000);
|
||||||
|
while (!buf.testRead(telnetRead(-1)))
|
||||||
|
;
|
||||||
|
// todo: deduplicate write method, use bulkTransfer with offset
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
// provoke data loss, when data is not read fast enough
|
// provoke data loss, when data is not read fast enough
|
||||||
public void readBufferOverflow() throws Exception {
|
public void readBufferOverflow() throws Exception {
|
||||||
if(usbSerialDriver instanceof CdcAcmSerialDriver)
|
if(usbSerialDriver instanceof CdcAcmSerialDriver)
|
||||||
telnetWriteDelay = 10; // arduino_leonardo_bridge.ino sends each byte in own USB packet, which is horribly slow
|
telnetWriteDelay = 10; // arduino_leonardo_bridge.ino sends each byte in own USB packet, which is horribly slow
|
||||||
|
usbOpen(true);
|
||||||
usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
@ -990,6 +1078,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
// Using SERIAL_INPUT_OUTPUT_MANAGER_THREAD_PRIORITY=THREAD_PRIORITY_URGENT_AUDIO sometimes reduced errors by factor 10, sometimes not at all!
|
// Using SERIAL_INPUT_OUTPUT_MANAGER_THREAD_PRIORITY=THREAD_PRIORITY_URGENT_AUDIO sometimes reduced errors by factor 10, sometimes not at all!
|
||||||
//
|
//
|
||||||
int baudrate = 115200;
|
int baudrate = 115200;
|
||||||
|
usbOpen(true);
|
||||||
usbParameters(baudrate, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(baudrate, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(baudrate, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(baudrate, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
@ -1043,6 +1132,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
// all other devices can get near physical limit:
|
// all other devices can get near physical limit:
|
||||||
// longlines=true:, speed is near physical limit at 11.5k
|
// longlines=true:, speed is near physical limit at 11.5k
|
||||||
// longlines=false: speed is 3-4k for all devices, as more USB packets are required
|
// longlines=false: speed is 3-4k for all devices, as more USB packets are required
|
||||||
|
usbOpen(true);
|
||||||
usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
boolean longlines = !(usbSerialDriver instanceof CdcAcmSerialDriver);
|
boolean longlines = !(usbSerialDriver instanceof CdcAcmSerialDriver);
|
||||||
@ -1091,16 +1181,17 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void purgeHwBuffers() throws Exception {
|
public void purgeHwBuffers() throws Exception {
|
||||||
|
// purge write buffer
|
||||||
// 2400 is slowest baud rate for isCp21xxRestrictedPort
|
// 2400 is slowest baud rate for isCp21xxRestrictedPort
|
||||||
|
usbOpen(true);
|
||||||
usbParameters(2400, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(2400, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(2400, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(2400, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
byte[] buf = new byte[64];
|
byte[] buf = new byte[64];
|
||||||
for(int i=0; i<buf.length; i++) buf[i]='a';
|
for(int i=0; i<buf.length; i++) buf[i]='a';
|
||||||
StringBuilder data = new StringBuilder();
|
StringBuilder data = new StringBuilder();
|
||||||
|
|
||||||
// purge send buffer
|
|
||||||
usbWrite(buf);
|
usbWrite(buf);
|
||||||
Thread.sleep(50); // ~ 12 characters
|
Thread.sleep(50); // ~ 12 bytes
|
||||||
boolean purged = usbSerialPort.purgeHwBuffers(true, false);
|
boolean purged = usbSerialPort.purgeHwBuffers(true, false);
|
||||||
usbWrite("bcd".getBytes());
|
usbWrite("bcd".getBytes());
|
||||||
Thread.sleep(50);
|
Thread.sleep(50);
|
||||||
@ -1114,7 +1205,32 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
else
|
else
|
||||||
assertEquals(data.length(), buf.length + 3);
|
assertEquals(data.length(), buf.length + 3);
|
||||||
|
|
||||||
// todo: purge receive buffer
|
// purge read buffer
|
||||||
|
usbClose();
|
||||||
|
usbOpen(false);
|
||||||
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
telnetWrite("x".getBytes());
|
||||||
|
Thread.sleep(10); // ~ 20 bytes
|
||||||
|
purged = usbSerialPort.purgeHwBuffers(false, true);
|
||||||
|
Log.d(TAG, "purged = " + purged);
|
||||||
|
telnetWrite("y".getBytes());
|
||||||
|
Thread.sleep(10); // ~ 20 bytes
|
||||||
|
if(purged) {
|
||||||
|
if(usbSerialDriver instanceof Cp21xxSerialDriver) { // only working on some devices/ports
|
||||||
|
if(isCp21xxRestrictedPort) {
|
||||||
|
assertThat(usbRead(2), equalTo("xy".getBytes())); // cp2105/1
|
||||||
|
} else if(usbSerialDriver.getPorts().size() > 1) {
|
||||||
|
assertThat(usbRead(1), equalTo("y".getBytes())); // cp2105/0
|
||||||
|
} else {
|
||||||
|
assertThat(usbRead(2), equalTo("xy".getBytes())); // cp2102
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assertThat(usbRead(1), equalTo("y".getBytes()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assertThat(usbRead(2), equalTo("xy".getBytes()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -1122,6 +1238,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
public void writeAsync() throws Exception {
|
public void writeAsync() throws Exception {
|
||||||
if (usbSerialDriver instanceof FtdiSerialDriver)
|
if (usbSerialDriver instanceof FtdiSerialDriver)
|
||||||
return; // periodically sends status messages, so does not block here
|
return; // periodically sends status messages, so does not block here
|
||||||
|
usbOpen(true);
|
||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
@ -1156,6 +1273,7 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
public void readSync() throws Exception {
|
public void readSync() throws Exception {
|
||||||
if (usbSerialDriver instanceof FtdiSerialDriver)
|
if (usbSerialDriver instanceof FtdiSerialDriver)
|
||||||
return; // periodically sends status messages, so does not block here
|
return; // periodically sends status messages, so does not block here
|
||||||
|
final Boolean[] closed = {Boolean.FALSE};
|
||||||
|
|
||||||
Runnable closeThread = new Runnable() {
|
Runnable closeThread = new Runnable() {
|
||||||
@Override
|
@Override
|
||||||
@ -1166,10 +1284,10 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
usbClose();
|
usbClose();
|
||||||
|
closed[0] = true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
usbClose();
|
|
||||||
usbOpen(false);
|
usbOpen(false);
|
||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
@ -1182,19 +1300,139 @@ public class DeviceTest implements SerialInputOutputManager.Listener {
|
|||||||
assertEquals(1, len);
|
assertEquals(1, len);
|
||||||
|
|
||||||
time = System.currentTimeMillis();
|
time = System.currentTimeMillis();
|
||||||
|
closed[0] = false;
|
||||||
Executors.newSingleThreadExecutor().submit(closeThread);
|
Executors.newSingleThreadExecutor().submit(closeThread);
|
||||||
len = usbSerialPort.read(buf, 0); // blocking until close()
|
len = usbSerialPort.read(buf, 0); // blocking until close()
|
||||||
assertEquals(0, len);
|
assertEquals(0, len);
|
||||||
assertTrue(System.currentTimeMillis()-time >= 100);
|
assertTrue(System.currentTimeMillis()-time >= 100);
|
||||||
|
|
||||||
|
|
||||||
|
// read() terminates in the middle of close(). An immediate open() can fail with 'already connected'
|
||||||
|
// because close() is not finished yet. Wait here until fully closed. In a real-world application
|
||||||
|
// where it takes some time until the user clicks on reconnect, this very likely is not an issue.
|
||||||
|
for(int i=0; i<=100; i++) {
|
||||||
|
if(closed[0]) break;
|
||||||
|
assertTrue("not closed in time", i<100);
|
||||||
|
Thread.sleep(1);
|
||||||
|
}
|
||||||
usbOpen(false);
|
usbOpen(false);
|
||||||
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
time = System.currentTimeMillis();
|
time = System.currentTimeMillis();
|
||||||
|
closed[0] = false;
|
||||||
Executors.newSingleThreadExecutor().submit(closeThread);
|
Executors.newSingleThreadExecutor().submit(closeThread);
|
||||||
len = usbSerialPort.read(buf, 10); // timeout not used any more -> blocking until close()
|
len = usbSerialPort.read(buf, 10); // timeout not used any more -> blocking until close()
|
||||||
assertEquals(0, len);
|
assertEquals(0, len);
|
||||||
assertTrue(System.currentTimeMillis()-time >= 100);
|
assertTrue(System.currentTimeMillis()-time >= 100);
|
||||||
|
for(int i=0; i<=100; i++) {
|
||||||
|
if(closed[0]) break;
|
||||||
|
assertTrue("not closed in time", i<100);
|
||||||
|
Thread.sleep(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void wrongDriver() throws Exception {
|
||||||
|
|
||||||
|
UsbDeviceConnection wrongDeviceConnection;
|
||||||
|
UsbSerialDriver wrongSerialDriver;
|
||||||
|
UsbSerialPort wrongSerialPort;
|
||||||
|
|
||||||
|
if(!(usbSerialDriver instanceof CdcAcmSerialDriver)) {
|
||||||
|
wrongDeviceConnection = usbManager.openDevice(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialDriver = new CdcAcmSerialDriver(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||||
|
try {
|
||||||
|
wrongSerialPort.open(wrongDeviceConnection);
|
||||||
|
wrongSerialPort.setParameters(115200, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); // ch340 fails here
|
||||||
|
wrongSerialPort.write(new byte[]{1}, 1000); // pl2302 does not fail, but sends with wrong baud rate
|
||||||
|
if(!(usbSerialDriver instanceof ProlificSerialDriver))
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if(usbSerialDriver instanceof ProlificSerialDriver) {
|
||||||
|
assertNotEquals(new byte[]{1}, telnetRead());
|
||||||
|
}
|
||||||
|
wrongSerialPort.close();
|
||||||
|
if(!(usbSerialDriver instanceof Ch34xSerialDriver |
|
||||||
|
usbSerialDriver instanceof ProlificSerialDriver))
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!(usbSerialDriver instanceof Ch34xSerialDriver)) {
|
||||||
|
wrongDeviceConnection = usbManager.openDevice(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialDriver = new Ch34xSerialDriver(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||||
|
try {
|
||||||
|
wrongSerialPort.open(wrongDeviceConnection);
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
wrongSerialPort.close();
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// FTDI only recovers from Cp21xx control commands with power toggle, so skip this combination!
|
||||||
|
if(!(usbSerialDriver instanceof Cp21xxSerialDriver | usbSerialDriver instanceof FtdiSerialDriver)) {
|
||||||
|
wrongDeviceConnection = usbManager.openDevice(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialDriver = new Cp21xxSerialDriver(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||||
|
try {
|
||||||
|
wrongSerialPort.open(wrongDeviceConnection);
|
||||||
|
//if(usbSerialDriver instanceof FtdiSerialDriver)
|
||||||
|
// wrongSerialPort.setParameters(115200, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); // ch340 fails here
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
wrongSerialPort.close();
|
||||||
|
//if(!(usbSerialDriver instanceof FtdiSerialDriver))
|
||||||
|
// fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!(usbSerialDriver instanceof FtdiSerialDriver)) {
|
||||||
|
wrongDeviceConnection = usbManager.openDevice(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialDriver = new FtdiSerialDriver(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||||
|
try {
|
||||||
|
wrongSerialPort.open(wrongDeviceConnection);
|
||||||
|
if(usbSerialDriver instanceof Cp21xxSerialDriver)
|
||||||
|
wrongSerialPort.setParameters(115200, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); // ch340 fails here
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
wrongSerialPort.close();
|
||||||
|
if(!(usbSerialDriver instanceof Cp21xxSerialDriver))
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!(usbSerialDriver instanceof ProlificSerialDriver)) {
|
||||||
|
wrongDeviceConnection = usbManager.openDevice(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialDriver = new ProlificSerialDriver(usbSerialDriver.getDevice());
|
||||||
|
wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||||
|
try {
|
||||||
|
wrongSerialPort.open(wrongDeviceConnection);
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
wrongSerialPort.close();
|
||||||
|
fail("error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// test that device recovers from wrong commands
|
||||||
|
usbOpen(true);
|
||||||
|
telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
doReadWrite("");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,11 +26,9 @@ import android.hardware.usb.UsbDevice;
|
|||||||
import android.hardware.usb.UsbDeviceConnection;
|
import android.hardware.usb.UsbDeviceConnection;
|
||||||
import android.hardware.usb.UsbEndpoint;
|
import android.hardware.usb.UsbEndpoint;
|
||||||
import android.hardware.usb.UsbInterface;
|
import android.hardware.usb.UsbInterface;
|
||||||
import android.hardware.usb.UsbRequest;
|
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -50,7 +48,6 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
|
|
||||||
private final UsbDevice mDevice;
|
private final UsbDevice mDevice;
|
||||||
private final UsbSerialPort mPort;
|
private final UsbSerialPort mPort;
|
||||||
private UsbRequest mUsbRequest;
|
|
||||||
|
|
||||||
public CdcAcmSerialDriver(UsbDevice device) {
|
public CdcAcmSerialDriver(UsbDevice device) {
|
||||||
mDevice = device;
|
mDevice = device;
|
||||||
@ -73,8 +70,6 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
private UsbInterface mDataInterface;
|
private UsbInterface mDataInterface;
|
||||||
|
|
||||||
private UsbEndpoint mControlEndpoint;
|
private UsbEndpoint mControlEndpoint;
|
||||||
private UsbEndpoint mReadEndpoint;
|
|
||||||
private UsbEndpoint mWriteEndpoint;
|
|
||||||
|
|
||||||
private int mControlIndex;
|
private int mControlIndex;
|
||||||
|
|
||||||
@ -107,7 +102,6 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
mConnection = connection;
|
mConnection = connection;
|
||||||
boolean opened = false;
|
boolean opened = false;
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (1 == mDevice.getInterfaceCount()) {
|
if (1 == mDevice.getInterfaceCount()) {
|
||||||
Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
|
Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
|
||||||
openSingleInterface();
|
openSingleInterface();
|
||||||
@ -115,15 +109,10 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
Log.d(TAG,"trying default interface logic");
|
Log.d(TAG,"trying default interface logic");
|
||||||
openInterface();
|
openInterface();
|
||||||
}
|
}
|
||||||
|
|
||||||
opened = true;
|
opened = true;
|
||||||
} finally {
|
} finally {
|
||||||
if (!opened) {
|
if (!opened) {
|
||||||
mConnection = null;
|
close();
|
||||||
// just to be on the save side
|
|
||||||
mControlEndpoint = null;
|
|
||||||
mReadEndpoint = null;
|
|
||||||
mWriteEndpoint = null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -140,7 +129,7 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
Log.d(TAG, "data iface=" + mDataInterface);
|
Log.d(TAG, "data iface=" + mDataInterface);
|
||||||
|
|
||||||
if (!mConnection.claimInterface(mControlInterface, true)) {
|
if (!mConnection.claimInterface(mControlInterface, true)) {
|
||||||
throw new IOException("Could not claim shared control/data interface.");
|
throw new IOException("Could not claim shared control/data interface");
|
||||||
}
|
}
|
||||||
|
|
||||||
int endCount = mControlInterface.getEndpointCount();
|
int endCount = mControlInterface.getEndpointCount();
|
||||||
@ -204,26 +193,26 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(mControlInterface == null) {
|
if(mControlInterface == null) {
|
||||||
throw new IOException("no control interface.");
|
throw new IOException("No control interface");
|
||||||
}
|
}
|
||||||
Log.d(TAG, "Control iface=" + mControlInterface);
|
Log.d(TAG, "Control iface=" + mControlInterface);
|
||||||
|
|
||||||
if (!mConnection.claimInterface(mControlInterface, true)) {
|
if (!mConnection.claimInterface(mControlInterface, true)) {
|
||||||
throw new IOException("Could not claim control interface.");
|
throw new IOException("Could not claim control interface");
|
||||||
}
|
}
|
||||||
|
|
||||||
mControlEndpoint = mControlInterface.getEndpoint(0);
|
mControlEndpoint = mControlInterface.getEndpoint(0);
|
||||||
if (mControlEndpoint.getDirection() != UsbConstants.USB_DIR_IN || mControlEndpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
|
if (mControlEndpoint.getDirection() != UsbConstants.USB_DIR_IN || mControlEndpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
|
||||||
throw new IOException("invalid control endpoint");
|
throw new IOException("Invalid control endpoint");
|
||||||
}
|
}
|
||||||
|
|
||||||
if(mDataInterface == null) {
|
if(mDataInterface == null) {
|
||||||
throw new IOException("no data interface.");
|
throw new IOException("No data interface");
|
||||||
}
|
}
|
||||||
Log.d(TAG, "data iface=" + mDataInterface);
|
Log.d(TAG, "data iface=" + mDataInterface);
|
||||||
|
|
||||||
if (!mConnection.claimInterface(mDataInterface, true)) {
|
if (!mConnection.claimInterface(mDataInterface, true)) {
|
||||||
throw new IOException("Could not claim data interface.");
|
throw new IOException("Could not claim data interface");
|
||||||
}
|
}
|
||||||
|
|
||||||
mReadEndpoint = null;
|
mReadEndpoint = null;
|
||||||
@ -236,7 +225,7 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
mWriteEndpoint = ep;
|
mWriteEndpoint = ep;
|
||||||
}
|
}
|
||||||
if (mReadEndpoint == null || mWriteEndpoint == null) {
|
if (mReadEndpoint == null || mWriteEndpoint == null) {
|
||||||
throw new IOException("Could not get read&write endpoints.");
|
throw new IOException("Could not get read&write endpoints");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -244,98 +233,33 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
int len = mConnection.controlTransfer(
|
int len = mConnection.controlTransfer(
|
||||||
USB_RT_ACM, request, value, mControlIndex, buf, buf != null ? buf.length : 0, 5000);
|
USB_RT_ACM, request, value, mControlIndex, buf, buf != null ? buf.length : 0, 5000);
|
||||||
if(len < 0) {
|
if(len < 0) {
|
||||||
throw new IOException("controlTransfer failed.");
|
throw new IOException("controlTransfer failed");
|
||||||
}
|
}
|
||||||
return len;
|
return len;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void closeInt() {
|
||||||
if (mConnection == null) {
|
|
||||||
throw new IOException("Already closed");
|
|
||||||
}
|
|
||||||
synchronized (this) {
|
|
||||||
if (mUsbRequest != null)
|
|
||||||
mUsbRequest.cancel();
|
|
||||||
}
|
|
||||||
mConnection.close();
|
|
||||||
mConnection = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int read(byte[] dest, int timeoutMillis) throws IOException {
|
|
||||||
final UsbRequest request = new UsbRequest();
|
|
||||||
try {
|
try {
|
||||||
request.initialize(mConnection, mReadEndpoint);
|
mConnection.releaseInterface(mControlInterface);
|
||||||
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
mConnection.releaseInterface(mDataInterface);
|
||||||
if (!request.queue(buf, dest.length)) {
|
} catch(Exception ignored) {}
|
||||||
throw new IOException("Error queueing request.");
|
|
||||||
}
|
|
||||||
mUsbRequest = request;
|
|
||||||
final UsbRequest response = mConnection.requestWait();
|
|
||||||
synchronized (this) {
|
|
||||||
mUsbRequest = null;
|
|
||||||
}
|
|
||||||
if (response == null) {
|
|
||||||
throw new IOException("Null response");
|
|
||||||
}
|
|
||||||
|
|
||||||
final int nread = buf.position();
|
|
||||||
if (nread > 0) {
|
|
||||||
//Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
|
|
||||||
return nread;
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
mUsbRequest = null;
|
|
||||||
request.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int write(byte[] src, int timeoutMillis) throws IOException {
|
|
||||||
// TODO(mikey): Nearly identical to FtdiSerial write. Refactor.
|
|
||||||
int offset = 0;
|
|
||||||
|
|
||||||
while (offset < src.length) {
|
|
||||||
final int writeLength;
|
|
||||||
final int amtWritten;
|
|
||||||
|
|
||||||
synchronized (mWriteBufferLock) {
|
|
||||||
final byte[] writeBuffer;
|
|
||||||
|
|
||||||
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
|
|
||||||
if (offset == 0) {
|
|
||||||
writeBuffer = src;
|
|
||||||
} else {
|
|
||||||
// bulkTransfer does not support offsets, make a copy.
|
|
||||||
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
|
|
||||||
writeBuffer = mWriteBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
|
|
||||||
timeoutMillis);
|
|
||||||
}
|
|
||||||
if (amtWritten <= 0) {
|
|
||||||
throw new IOException("Error writing " + writeLength
|
|
||||||
+ " bytes at offset " + offset + " length=" + src.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
|
|
||||||
offset += amtWritten;
|
|
||||||
}
|
|
||||||
return offset;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
||||||
|
if(baudRate <= 0) {
|
||||||
|
throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
|
||||||
|
}
|
||||||
|
if(dataBits < DATABITS_5 || dataBits > DATABITS_8) {
|
||||||
|
throw new IllegalArgumentException("Invalid data bits: " + dataBits);
|
||||||
|
}
|
||||||
byte stopBitsByte;
|
byte stopBitsByte;
|
||||||
switch (stopBits) {
|
switch (stopBits) {
|
||||||
case STOPBITS_1: stopBitsByte = 0; break;
|
case STOPBITS_1: stopBitsByte = 0; break;
|
||||||
case STOPBITS_1_5: stopBitsByte = 1; break;
|
case STOPBITS_1_5: stopBitsByte = 1; break;
|
||||||
case STOPBITS_2: stopBitsByte = 2; break;
|
case STOPBITS_2: stopBitsByte = 2; break;
|
||||||
default: throw new IllegalArgumentException("Bad value for stopBits: " + stopBits);
|
default: throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
byte parityBitesByte;
|
byte parityBitesByte;
|
||||||
@ -345,9 +269,8 @@ public class CdcAcmSerialDriver implements UsbSerialDriver {
|
|||||||
case PARITY_EVEN: parityBitesByte = 2; break;
|
case PARITY_EVEN: parityBitesByte = 2; break;
|
||||||
case PARITY_MARK: parityBitesByte = 3; break;
|
case PARITY_MARK: parityBitesByte = 3; break;
|
||||||
case PARITY_SPACE: parityBitesByte = 4; break;
|
case PARITY_SPACE: parityBitesByte = 4; break;
|
||||||
default: throw new IllegalArgumentException("Bad value for parity: " + parity);
|
default: throw new IllegalArgumentException("Invalid parity: " + parity);
|
||||||
}
|
}
|
||||||
|
|
||||||
byte[] msg = {
|
byte[] msg = {
|
||||||
(byte) ( baudRate & 0xff),
|
(byte) ( baudRate & 0xff),
|
||||||
(byte) ((baudRate >> 8 ) & 0xff),
|
(byte) ((baudRate >> 8 ) & 0xff),
|
||||||
|
@ -25,11 +25,8 @@ import android.hardware.usb.UsbDevice;
|
|||||||
import android.hardware.usb.UsbDeviceConnection;
|
import android.hardware.usb.UsbDeviceConnection;
|
||||||
import android.hardware.usb.UsbEndpoint;
|
import android.hardware.usb.UsbEndpoint;
|
||||||
import android.hardware.usb.UsbInterface;
|
import android.hardware.usb.UsbInterface;
|
||||||
import android.hardware.usb.UsbRequest;
|
|
||||||
import android.util.Log;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -83,10 +80,6 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
private boolean dtr = false;
|
private boolean dtr = false;
|
||||||
private boolean rts = false;
|
private boolean rts = false;
|
||||||
|
|
||||||
private UsbEndpoint mReadEndpoint;
|
|
||||||
private UsbEndpoint mWriteEndpoint;
|
|
||||||
private UsbRequest mUsbRequest;
|
|
||||||
|
|
||||||
public Ch340SerialPort(UsbDevice device, int portNumber) {
|
public Ch340SerialPort(UsbDevice device, int portNumber) {
|
||||||
super(device, portNumber);
|
super(device, portNumber);
|
||||||
}
|
}
|
||||||
@ -99,7 +92,7 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
@Override
|
@Override
|
||||||
public void open(UsbDeviceConnection connection) throws IOException {
|
public void open(UsbDeviceConnection connection) throws IOException {
|
||||||
if (mConnection != null) {
|
if (mConnection != null) {
|
||||||
throw new IOException("Already opened.");
|
throw new IOException("Already open");
|
||||||
}
|
}
|
||||||
|
|
||||||
mConnection = connection;
|
mConnection = connection;
|
||||||
@ -108,7 +101,7 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
|
for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
|
||||||
UsbInterface usbIface = mDevice.getInterface(i);
|
UsbInterface usbIface = mDevice.getInterface(i);
|
||||||
if (!mConnection.claimInterface(usbIface, true)) {
|
if (!mConnection.claimInterface(usbIface, true)) {
|
||||||
throw new IOException("Could not claim data interface.");
|
throw new IOException("Could not claim data interface");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -130,95 +123,17 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
opened = true;
|
opened = true;
|
||||||
} finally {
|
} finally {
|
||||||
if (!opened) {
|
if (!opened) {
|
||||||
try {
|
|
||||||
close();
|
close();
|
||||||
} catch (IOException e) {
|
|
||||||
// Ignore IOExceptions during close()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void closeInt() {
|
||||||
if (mConnection == null) {
|
|
||||||
throw new IOException("Already closed");
|
|
||||||
}
|
|
||||||
synchronized (this) {
|
|
||||||
if (mUsbRequest != null)
|
|
||||||
mUsbRequest.cancel();
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
mConnection.close();
|
for (int i = 0; i < mDevice.getInterfaceCount(); i++)
|
||||||
} finally {
|
mConnection.releaseInterface(mDevice.getInterface(i));
|
||||||
mConnection = null;
|
} catch(Exception ignored) {}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int read(byte[] dest, int timeoutMillis) throws IOException {
|
|
||||||
final UsbRequest request = new UsbRequest();
|
|
||||||
try {
|
|
||||||
request.initialize(mConnection, mReadEndpoint);
|
|
||||||
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
|
||||||
if (!request.queue(buf, dest.length)) {
|
|
||||||
throw new IOException("Error queueing request.");
|
|
||||||
}
|
|
||||||
mUsbRequest = request;
|
|
||||||
final UsbRequest response = mConnection.requestWait();
|
|
||||||
synchronized (this) {
|
|
||||||
mUsbRequest = null;
|
|
||||||
}
|
|
||||||
if (response == null) {
|
|
||||||
throw new IOException("Null response");
|
|
||||||
}
|
|
||||||
|
|
||||||
final int nread = buf.position();
|
|
||||||
if (nread > 0) {
|
|
||||||
//Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
|
|
||||||
return nread;
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
mUsbRequest = null;
|
|
||||||
request.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int write(byte[] src, int timeoutMillis) throws IOException {
|
|
||||||
int offset = 0;
|
|
||||||
|
|
||||||
while (offset < src.length) {
|
|
||||||
final int writeLength;
|
|
||||||
final int amtWritten;
|
|
||||||
|
|
||||||
synchronized (mWriteBufferLock) {
|
|
||||||
final byte[] writeBuffer;
|
|
||||||
|
|
||||||
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
|
|
||||||
if (offset == 0) {
|
|
||||||
writeBuffer = src;
|
|
||||||
} else {
|
|
||||||
// bulkTransfer does not support offsets, make a copy.
|
|
||||||
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
|
|
||||||
writeBuffer = mWriteBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
|
|
||||||
timeoutMillis);
|
|
||||||
}
|
|
||||||
if (amtWritten <= 0) {
|
|
||||||
throw new IOException("Error writing " + writeLength
|
|
||||||
+ " bytes at offset " + offset + " length=" + src.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
|
|
||||||
offset += amtWritten;
|
|
||||||
}
|
|
||||||
return offset;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int controlOut(int request, int value, int index) {
|
private int controlOut(int request, int value, int index) {
|
||||||
@ -269,7 +184,7 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
checkState("init #1", 0x5f, 0, new int[]{-1 /* 0x27, 0x30 */, 0x00});
|
checkState("init #1", 0x5f, 0, new int[]{-1 /* 0x27, 0x30 */, 0x00});
|
||||||
|
|
||||||
if (controlOut(0xa1, 0, 0) < 0) {
|
if (controlOut(0xa1, 0, 0) < 0) {
|
||||||
throw new IOException("init failed! #2");
|
throw new IOException("Init failed: #2");
|
||||||
}
|
}
|
||||||
|
|
||||||
setBaudRate(DEFAULT_BAUD_RATE);
|
setBaudRate(DEFAULT_BAUD_RATE);
|
||||||
@ -277,13 +192,13 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
checkState("init #4", 0x95, 0x2518, new int[]{-1 /* 0x56, c3*/, 0x00});
|
checkState("init #4", 0x95, 0x2518, new int[]{-1 /* 0x56, c3*/, 0x00});
|
||||||
|
|
||||||
if (controlOut(0x9a, 0x2518, LCR_ENABLE_RX | LCR_ENABLE_TX | LCR_CS8) < 0) {
|
if (controlOut(0x9a, 0x2518, LCR_ENABLE_RX | LCR_ENABLE_TX | LCR_CS8) < 0) {
|
||||||
throw new IOException("init failed! #5");
|
throw new IOException("Init failed: #5");
|
||||||
}
|
}
|
||||||
|
|
||||||
checkState("init #6", 0x95, 0x0706, new int[]{0xff, 0xee});
|
checkState("init #6", 0x95, 0x0706, new int[]{0xff, 0xee});
|
||||||
|
|
||||||
if (controlOut(0xa1, 0x501f, 0xd90a) < 0) {
|
if (controlOut(0xa1, 0x501f, 0xd90a) < 0) {
|
||||||
throw new IOException("init failed! #7");
|
throw new IOException("Init failed: #7");
|
||||||
}
|
}
|
||||||
|
|
||||||
setBaudRate(DEFAULT_BAUD_RATE);
|
setBaudRate(DEFAULT_BAUD_RATE);
|
||||||
@ -307,25 +222,27 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (factor > 0xfff0) {
|
if (factor > 0xfff0) {
|
||||||
throw new IOException("Baudrate " + baudRate + " not supported");
|
throw new UnsupportedOperationException("Unsupported baud rate: " + baudRate);
|
||||||
}
|
}
|
||||||
|
|
||||||
factor = 0x10000 - factor;
|
factor = 0x10000 - factor;
|
||||||
|
|
||||||
int ret = controlOut(0x9a, 0x1312, (int) ((factor & 0xff00) | divisor));
|
int ret = controlOut(0x9a, 0x1312, (int) ((factor & 0xff00) | divisor));
|
||||||
if (ret < 0) {
|
if (ret < 0) {
|
||||||
throw new IOException("Error setting baud rate. #1)");
|
throw new IOException("Error setting baud rate: #1)");
|
||||||
}
|
}
|
||||||
|
|
||||||
ret = controlOut(0x9a, 0x0f2c, (int) (factor & 0xff));
|
ret = controlOut(0x9a, 0x0f2c, (int) (factor & 0xff));
|
||||||
if (ret < 0) {
|
if (ret < 0) {
|
||||||
throw new IOException("Error setting baud rate. #2");
|
throw new IOException("Error setting baud rate: #2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
|
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
||||||
throws IOException {
|
if(baudRate <= 0) {
|
||||||
|
throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
|
||||||
|
}
|
||||||
setBaudRate(baudRate);
|
setBaudRate(baudRate);
|
||||||
|
|
||||||
int lcr = LCR_ENABLE_RX | LCR_ENABLE_TX;
|
int lcr = LCR_ENABLE_RX | LCR_ENABLE_TX;
|
||||||
@ -344,7 +261,7 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
lcr |= LCR_CS8;
|
lcr |= LCR_CS8;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown dataBits value: " + dataBits);
|
throw new IllegalArgumentException("Invalid data bits: " + dataBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (parity) {
|
switch (parity) {
|
||||||
@ -363,19 +280,19 @@ public class Ch34xSerialDriver implements UsbSerialDriver {
|
|||||||
lcr |= LCR_ENABLE_PAR | LCR_MARK_SPACE | LCR_PAR_EVEN;
|
lcr |= LCR_ENABLE_PAR | LCR_MARK_SPACE | LCR_PAR_EVEN;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown parity value: " + parity);
|
throw new IllegalArgumentException("Invalid parity: " + parity);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (stopBits) {
|
switch (stopBits) {
|
||||||
case STOPBITS_1:
|
case STOPBITS_1:
|
||||||
break;
|
break;
|
||||||
case STOPBITS_1_5:
|
case STOPBITS_1_5:
|
||||||
throw new IllegalArgumentException("Unsupported stopBits value: 1.5");
|
throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
|
||||||
case STOPBITS_2:
|
case STOPBITS_2:
|
||||||
lcr |= LCR_STOP_BITS_2;
|
lcr |= LCR_STOP_BITS_2;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
|
throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
int ret = controlOut(0x9a, 0x2518, lcr);
|
int ret = controlOut(0x9a, 0x2518, lcr);
|
||||||
|
@ -23,31 +23,33 @@ package com.hoho.android.usbserial.driver;
|
|||||||
|
|
||||||
import android.hardware.usb.UsbDevice;
|
import android.hardware.usb.UsbDevice;
|
||||||
import android.hardware.usb.UsbDeviceConnection;
|
import android.hardware.usb.UsbDeviceConnection;
|
||||||
|
import android.hardware.usb.UsbEndpoint;
|
||||||
|
import android.hardware.usb.UsbRequest;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A base class shared by several driver implementations.
|
* A base class shared by several driver implementations.
|
||||||
*
|
*
|
||||||
* @author mike wakerly (opensource@hoho.com)
|
* @author mike wakerly (opensource@hoho.com)
|
||||||
*/
|
*/
|
||||||
abstract class CommonUsbSerialPort implements UsbSerialPort {
|
public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||||
|
|
||||||
public static final int DEFAULT_READ_BUFFER_SIZE = 16 * 1024;
|
private static final String TAG = CommonUsbSerialPort.class.getSimpleName();
|
||||||
public static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
|
private static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
|
||||||
|
|
||||||
protected final UsbDevice mDevice;
|
protected final UsbDevice mDevice;
|
||||||
protected final int mPortNumber;
|
protected final int mPortNumber;
|
||||||
|
|
||||||
// non-null when open()
|
// non-null when open()
|
||||||
protected UsbDeviceConnection mConnection = null;
|
protected UsbDeviceConnection mConnection = null;
|
||||||
|
protected UsbEndpoint mReadEndpoint;
|
||||||
|
protected UsbEndpoint mWriteEndpoint;
|
||||||
|
protected UsbRequest mUsbRequest;
|
||||||
|
|
||||||
protected final Object mReadBufferLock = new Object();
|
|
||||||
protected final Object mWriteBufferLock = new Object();
|
protected final Object mWriteBufferLock = new Object();
|
||||||
|
|
||||||
/** Internal read buffer. Guarded by {@link #mReadBufferLock}. */
|
|
||||||
protected byte[] mReadBuffer;
|
|
||||||
|
|
||||||
/** Internal write buffer. Guarded by {@link #mWriteBufferLock}. */
|
/** Internal write buffer. Guarded by {@link #mWriteBufferLock}. */
|
||||||
protected byte[] mWriteBuffer;
|
protected byte[] mWriteBuffer;
|
||||||
|
|
||||||
@ -55,7 +57,6 @@ abstract class CommonUsbSerialPort implements UsbSerialPort {
|
|||||||
mDevice = device;
|
mDevice = device;
|
||||||
mPortNumber = portNumber;
|
mPortNumber = portNumber;
|
||||||
|
|
||||||
mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
|
|
||||||
mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
|
mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,21 +90,6 @@ abstract class CommonUsbSerialPort implements UsbSerialPort {
|
|||||||
return mConnection.getSerial();
|
return mConnection.getSerial();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the size of the internal buffer used to exchange data with the USB
|
|
||||||
* stack for read operations. Most users should not need to change this.
|
|
||||||
*
|
|
||||||
* @param bufferSize the size in bytes
|
|
||||||
*/
|
|
||||||
public final void setReadBufferSize(int bufferSize) {
|
|
||||||
synchronized (mReadBufferLock) {
|
|
||||||
if (bufferSize == mReadBuffer.length) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
mReadBuffer = new byte[bufferSize];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the size of the internal buffer used to exchange data with the USB
|
* Sets the size of the internal buffer used to exchange data with the USB
|
||||||
* stack for write operations. Most users should not need to change this.
|
* stack for write operations. Most users should not need to change this.
|
||||||
@ -123,17 +109,101 @@ abstract class CommonUsbSerialPort implements UsbSerialPort {
|
|||||||
public abstract void open(UsbDeviceConnection connection) throws IOException;
|
public abstract void open(UsbDeviceConnection connection) throws IOException;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public abstract void close() throws IOException;
|
public void close() throws IOException {
|
||||||
|
if (mConnection == null) {
|
||||||
|
throw new IOException("Already closed");
|
||||||
|
}
|
||||||
|
synchronized (this) {
|
||||||
|
if (mUsbRequest != null)
|
||||||
|
mUsbRequest.cancel();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
closeInt();
|
||||||
|
} catch(Exception ignored) {}
|
||||||
|
try {
|
||||||
|
mConnection.close();
|
||||||
|
} finally {
|
||||||
|
mConnection = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract void closeInt();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public abstract int read(final byte[] dest, final int timeoutMillis) throws IOException;
|
public int read(final byte[] dest, final int timeoutMillis) throws IOException {
|
||||||
|
if(mConnection == null) {
|
||||||
|
throw new IOException("Connection closed");
|
||||||
|
}
|
||||||
|
final UsbRequest request = new UsbRequest();
|
||||||
|
try {
|
||||||
|
request.initialize(mConnection, mReadEndpoint);
|
||||||
|
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
||||||
|
if (!request.queue(buf, dest.length)) {
|
||||||
|
throw new IOException("Error queueing request");
|
||||||
|
}
|
||||||
|
mUsbRequest = request;
|
||||||
|
final UsbRequest response = mConnection.requestWait();
|
||||||
|
synchronized (this) {
|
||||||
|
mUsbRequest = null;
|
||||||
|
}
|
||||||
|
if (response == null) {
|
||||||
|
throw new IOException("Null response");
|
||||||
|
}
|
||||||
|
final int nread = buf.position();
|
||||||
|
if (nread > 0) {
|
||||||
|
return readFilter(dest, nread);
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
mUsbRequest = null;
|
||||||
|
request.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected int readFilter(final byte[] buffer, int len) throws IOException { return len; }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public abstract int write(final byte[] src, final int timeoutMillis) throws IOException;
|
public int write(final byte[] src, final int timeoutMillis) throws IOException {
|
||||||
|
int offset = 0;
|
||||||
|
|
||||||
|
if(mConnection == null) {
|
||||||
|
throw new IOException("Connection closed");
|
||||||
|
}
|
||||||
|
while (offset < src.length) {
|
||||||
|
final int writeLength;
|
||||||
|
final int amtWritten;
|
||||||
|
|
||||||
|
synchronized (mWriteBufferLock) {
|
||||||
|
final byte[] writeBuffer;
|
||||||
|
|
||||||
|
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
|
||||||
|
if (offset == 0) {
|
||||||
|
writeBuffer = src;
|
||||||
|
} else {
|
||||||
|
// bulkTransfer does not support offsets, make a copy.
|
||||||
|
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
|
||||||
|
writeBuffer = mWriteBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
|
||||||
|
timeoutMillis);
|
||||||
|
}
|
||||||
|
if (amtWritten <= 0) {
|
||||||
|
throw new IOException("Error writing " + writeLength
|
||||||
|
+ " bytes at offset " + offset + " length=" + src.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
|
||||||
|
offset += amtWritten;
|
||||||
|
}
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public abstract void setParameters(
|
public abstract void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException;
|
||||||
int baudRate, int dataBits, int stopBits, int parity) throws IOException;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public abstract boolean getCD() throws IOException;
|
public abstract boolean getCD() throws IOException;
|
||||||
|
@ -26,11 +26,8 @@ import android.hardware.usb.UsbDevice;
|
|||||||
import android.hardware.usb.UsbDeviceConnection;
|
import android.hardware.usb.UsbDeviceConnection;
|
||||||
import android.hardware.usb.UsbEndpoint;
|
import android.hardware.usb.UsbEndpoint;
|
||||||
import android.hardware.usb.UsbInterface;
|
import android.hardware.usb.UsbInterface;
|
||||||
import android.hardware.usb.UsbRequest;
|
|
||||||
import android.util.Log;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -106,10 +103,6 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
|||||||
private static final int CONTROL_WRITE_DTR = 0x0100;
|
private static final int CONTROL_WRITE_DTR = 0x0100;
|
||||||
private static final int CONTROL_WRITE_RTS = 0x0200;
|
private static final int CONTROL_WRITE_RTS = 0x0200;
|
||||||
|
|
||||||
private UsbEndpoint mReadEndpoint;
|
|
||||||
private UsbEndpoint mWriteEndpoint;
|
|
||||||
private UsbRequest mUsbRequest;
|
|
||||||
|
|
||||||
// second port of Cp2105 has limited baudRate, dataBits, stopBits, parity
|
// second port of Cp2105 has limited baudRate, dataBits, stopBits, parity
|
||||||
// unsupported baudrate returns error at controlTransfer(), other parameters are silently ignored
|
// unsupported baudrate returns error at controlTransfer(), other parameters are silently ignored
|
||||||
private boolean mIsRestrictedPort;
|
private boolean mIsRestrictedPort;
|
||||||
@ -123,15 +116,19 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
|||||||
return Cp21xxSerialDriver.this;
|
return Cp21xxSerialDriver.this;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int setConfigSingle(int request, int value) {
|
private int setConfigSingle(int request, int value) throws IOException {
|
||||||
return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value,
|
int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value,
|
||||||
mPortNumber, null, 0, USB_WRITE_TIMEOUT_MILLIS);
|
mPortNumber, null, 0, USB_WRITE_TIMEOUT_MILLIS);
|
||||||
|
if (result != 0) {
|
||||||
|
throw new IOException("Setting baudrate failed: result=" + result);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void open(UsbDeviceConnection connection) throws IOException {
|
public void open(UsbDeviceConnection connection) throws IOException {
|
||||||
if (mConnection != null) {
|
if (mConnection != null) {
|
||||||
throw new IOException("Already opened.");
|
throw new IOException("Already open");
|
||||||
}
|
}
|
||||||
|
|
||||||
mConnection = connection;
|
mConnection = connection;
|
||||||
@ -163,99 +160,19 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
|||||||
opened = true;
|
opened = true;
|
||||||
} finally {
|
} finally {
|
||||||
if (!opened) {
|
if (!opened) {
|
||||||
try {
|
|
||||||
close();
|
close();
|
||||||
} catch (IOException e) {
|
|
||||||
// Ignore IOExceptions during close()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void closeInt() {
|
||||||
if (mConnection == null) {
|
|
||||||
throw new IOException("Already closed");
|
|
||||||
}
|
|
||||||
synchronized (this) {
|
|
||||||
if(mUsbRequest != null) {
|
|
||||||
mUsbRequest.cancel();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE);
|
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE);
|
||||||
} catch (Exception ignored)
|
} catch (Exception ignored) {}
|
||||||
{}
|
|
||||||
try {
|
try {
|
||||||
mConnection.close();
|
mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
|
||||||
} finally {
|
} catch(Exception ignored) {}
|
||||||
mConnection = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int read(byte[] dest, int timeoutMillis) throws IOException {
|
|
||||||
final UsbRequest request = new UsbRequest();
|
|
||||||
try {
|
|
||||||
request.initialize(mConnection, mReadEndpoint);
|
|
||||||
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
|
||||||
if (!request.queue(buf, dest.length)) {
|
|
||||||
throw new IOException("Error queueing request.");
|
|
||||||
}
|
|
||||||
mUsbRequest = request;
|
|
||||||
final UsbRequest response = mConnection.requestWait();
|
|
||||||
synchronized (this) {
|
|
||||||
mUsbRequest = null;
|
|
||||||
}
|
|
||||||
if (response == null) {
|
|
||||||
throw new IOException("Null response");
|
|
||||||
}
|
|
||||||
|
|
||||||
final int nread = buf.position();
|
|
||||||
if (nread > 0) {
|
|
||||||
//Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
|
|
||||||
return nread;
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
mUsbRequest = null;
|
|
||||||
request.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int write(byte[] src, int timeoutMillis) throws IOException {
|
|
||||||
int offset = 0;
|
|
||||||
|
|
||||||
while (offset < src.length) {
|
|
||||||
final int writeLength;
|
|
||||||
final int amtWritten;
|
|
||||||
|
|
||||||
synchronized (mWriteBufferLock) {
|
|
||||||
final byte[] writeBuffer;
|
|
||||||
|
|
||||||
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
|
|
||||||
if (offset == 0) {
|
|
||||||
writeBuffer = src;
|
|
||||||
} else {
|
|
||||||
// bulkTransfer does not support offsets, make a copy.
|
|
||||||
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
|
|
||||||
writeBuffer = mWriteBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
|
|
||||||
timeoutMillis);
|
|
||||||
}
|
|
||||||
if (amtWritten <= 0) {
|
|
||||||
throw new IOException("Error writing " + writeLength
|
|
||||||
+ " bytes at offset " + offset + " length=" + src.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
|
|
||||||
offset += amtWritten;
|
|
||||||
}
|
|
||||||
return offset;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setBaudRate(int baudRate) throws IOException {
|
private void setBaudRate(int baudRate) throws IOException {
|
||||||
@ -268,37 +185,39 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
|||||||
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
|
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
|
||||||
0, mPortNumber, data, 4, USB_WRITE_TIMEOUT_MILLIS);
|
0, mPortNumber, data, 4, USB_WRITE_TIMEOUT_MILLIS);
|
||||||
if (ret < 0) {
|
if (ret < 0) {
|
||||||
throw new IOException("Error setting baud rate.");
|
throw new IOException("Error setting baud rate");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
|
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
||||||
throws IOException {
|
if(baudRate <= 0) {
|
||||||
|
throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
|
||||||
|
}
|
||||||
setBaudRate(baudRate);
|
setBaudRate(baudRate);
|
||||||
|
|
||||||
int configDataBits = 0;
|
int configDataBits = 0;
|
||||||
switch (dataBits) {
|
switch (dataBits) {
|
||||||
case DATABITS_5:
|
case DATABITS_5:
|
||||||
if(mIsRestrictedPort)
|
if(mIsRestrictedPort)
|
||||||
throw new IllegalArgumentException("Unsupported dataBits value: " + dataBits);
|
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
|
||||||
configDataBits |= 0x0500;
|
configDataBits |= 0x0500;
|
||||||
break;
|
break;
|
||||||
case DATABITS_6:
|
case DATABITS_6:
|
||||||
if(mIsRestrictedPort)
|
if(mIsRestrictedPort)
|
||||||
throw new IllegalArgumentException("Unsupported dataBits value: " + dataBits);
|
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
|
||||||
configDataBits |= 0x0600;
|
configDataBits |= 0x0600;
|
||||||
break;
|
break;
|
||||||
case DATABITS_7:
|
case DATABITS_7:
|
||||||
if(mIsRestrictedPort)
|
if(mIsRestrictedPort)
|
||||||
throw new IllegalArgumentException("Unsupported dataBits value: " + dataBits);
|
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
|
||||||
configDataBits |= 0x0700;
|
configDataBits |= 0x0700;
|
||||||
break;
|
break;
|
||||||
case DATABITS_8:
|
case DATABITS_8:
|
||||||
configDataBits |= 0x0800;
|
configDataBits |= 0x0800;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown dataBits value: " + dataBits);
|
throw new IllegalArgumentException("Invalid data bits: " + dataBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (parity) {
|
switch (parity) {
|
||||||
@ -312,30 +231,30 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
|||||||
break;
|
break;
|
||||||
case PARITY_MARK:
|
case PARITY_MARK:
|
||||||
if(mIsRestrictedPort)
|
if(mIsRestrictedPort)
|
||||||
throw new IllegalArgumentException("Unsupported parity value: mark");
|
throw new UnsupportedOperationException("Unsupported parity: mark");
|
||||||
configDataBits |= 0x0030;
|
configDataBits |= 0x0030;
|
||||||
break;
|
break;
|
||||||
case PARITY_SPACE:
|
case PARITY_SPACE:
|
||||||
if(mIsRestrictedPort)
|
if(mIsRestrictedPort)
|
||||||
throw new IllegalArgumentException("Unsupported parity value: space");
|
throw new UnsupportedOperationException("Unsupported parity: space");
|
||||||
configDataBits |= 0x0040;
|
configDataBits |= 0x0040;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown parity value: " + parity);
|
throw new IllegalArgumentException("Invalid parity: " + parity);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (stopBits) {
|
switch (stopBits) {
|
||||||
case STOPBITS_1:
|
case STOPBITS_1:
|
||||||
break;
|
break;
|
||||||
case STOPBITS_1_5:
|
case STOPBITS_1_5:
|
||||||
throw new IllegalArgumentException("Unsupported stopBits value: 1.5");
|
throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
|
||||||
case STOPBITS_2:
|
case STOPBITS_2:
|
||||||
if(mIsRestrictedPort)
|
if(mIsRestrictedPort)
|
||||||
throw new IllegalArgumentException("Unsupported stopBits value: 2");
|
throw new UnsupportedOperationException("Unsupported stop bits: 2");
|
||||||
configDataBits |= 2;
|
configDataBits |= 2;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
|
throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
|
||||||
}
|
}
|
||||||
setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
|
setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
|
||||||
}
|
}
|
||||||
|
@ -24,12 +24,9 @@ package com.hoho.android.usbserial.driver;
|
|||||||
import android.hardware.usb.UsbConstants;
|
import android.hardware.usb.UsbConstants;
|
||||||
import android.hardware.usb.UsbDevice;
|
import android.hardware.usb.UsbDevice;
|
||||||
import android.hardware.usb.UsbDeviceConnection;
|
import android.hardware.usb.UsbDeviceConnection;
|
||||||
import android.hardware.usb.UsbEndpoint;
|
|
||||||
import android.hardware.usb.UsbRequest;
|
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -196,31 +193,32 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Filter FTDI status bytes from buffer
|
* Filter FTDI status bytes from buffer
|
||||||
* @param src The source buffer (which contains status bytes)
|
* @param buffer The source buffer (which contains status bytes)
|
||||||
* @param dest The destination buffer to write the status bytes into (can be src)
|
* buffer The destination buffer to write the status bytes into (can be src)
|
||||||
* @param totalBytesRead Number of bytes read to src
|
* @param totalBytesRead Number of bytes read to src
|
||||||
* @param maxPacketSize The USB endpoint max packet size
|
|
||||||
* @return The number of payload bytes
|
* @return The number of payload bytes
|
||||||
*/
|
*/
|
||||||
private final int filterStatusBytes(byte[] src, byte[] dest, int totalBytesRead, int maxPacketSize) {
|
@Override
|
||||||
|
protected int readFilter(byte[] buffer, int totalBytesRead) throws IOException {
|
||||||
|
if (totalBytesRead < MODEM_STATUS_HEADER_LENGTH) {
|
||||||
|
throw new IOException("Expected at least " + MODEM_STATUS_HEADER_LENGTH + " bytes");
|
||||||
|
}
|
||||||
|
int maxPacketSize = mReadEndpoint.getMaxPacketSize();
|
||||||
final int packetsCount = (totalBytesRead + maxPacketSize -1 )/ maxPacketSize;
|
final int packetsCount = (totalBytesRead + maxPacketSize -1 )/ maxPacketSize;
|
||||||
for (int packetIdx = 0; packetIdx < packetsCount; ++packetIdx) {
|
for (int packetIdx = 0; packetIdx < packetsCount; ++packetIdx) {
|
||||||
final int count = (packetIdx == (packetsCount - 1))
|
final int count = (packetIdx == (packetsCount - 1))
|
||||||
? totalBytesRead - packetIdx * maxPacketSize - MODEM_STATUS_HEADER_LENGTH
|
? totalBytesRead - packetIdx * maxPacketSize - MODEM_STATUS_HEADER_LENGTH
|
||||||
: maxPacketSize - MODEM_STATUS_HEADER_LENGTH;
|
: maxPacketSize - MODEM_STATUS_HEADER_LENGTH;
|
||||||
if (count > 0) {
|
if (count > 0) {
|
||||||
System.arraycopy(src,
|
System.arraycopy(buffer, packetIdx * maxPacketSize + MODEM_STATUS_HEADER_LENGTH,
|
||||||
packetIdx * maxPacketSize + MODEM_STATUS_HEADER_LENGTH,
|
buffer, packetIdx * (maxPacketSize - MODEM_STATUS_HEADER_LENGTH),
|
||||||
dest,
|
|
||||||
packetIdx * (maxPacketSize - MODEM_STATUS_HEADER_LENGTH),
|
|
||||||
count);
|
count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return totalBytesRead - (packetsCount * 2);
|
return totalBytesRead - (packetsCount * 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reset() throws IOException {
|
void reset() throws IOException {
|
||||||
// TODO(mikey): autodetect.
|
// TODO(mikey): autodetect.
|
||||||
mType = DeviceType.TYPE_R;
|
mType = DeviceType.TYPE_R;
|
||||||
if(mDevice.getInterfaceCount() > 1) {
|
if(mDevice.getInterfaceCount() > 1) {
|
||||||
@ -252,89 +250,26 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
|||||||
} else {
|
} else {
|
||||||
throw new IOException("Error claiming interface " + mPortNumber);
|
throw new IOException("Error claiming interface " + mPortNumber);
|
||||||
}
|
}
|
||||||
|
if (mDevice.getInterface(mPortNumber).getEndpointCount() < 2) {
|
||||||
|
throw new IOException("Insufficient number of endpoints (" +
|
||||||
|
mDevice.getInterface(mPortNumber).getEndpointCount() + ")");
|
||||||
|
}
|
||||||
|
mReadEndpoint = mDevice.getInterface(mPortNumber).getEndpoint(0);
|
||||||
|
mWriteEndpoint = mDevice.getInterface(mPortNumber).getEndpoint(1);
|
||||||
reset();
|
reset();
|
||||||
opened = true;
|
opened = true;
|
||||||
} finally {
|
} finally {
|
||||||
if (!opened) {
|
if (!opened) {
|
||||||
close();
|
close();
|
||||||
mConnection = null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void closeInt() {
|
||||||
if (mConnection == null) {
|
|
||||||
throw new IOException("Already closed");
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
mConnection.close();
|
mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
|
||||||
} finally {
|
} catch(Exception ignored) {}
|
||||||
mConnection = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int read(byte[] dest, int timeoutMillis) throws IOException {
|
|
||||||
final UsbEndpoint endpoint = mDevice.getInterface(mPortNumber).getEndpoint(0);
|
|
||||||
final UsbRequest request = new UsbRequest();
|
|
||||||
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
|
||||||
try {
|
|
||||||
request.initialize(mConnection, endpoint);
|
|
||||||
if (!request.queue(buf, dest.length)) {
|
|
||||||
throw new IOException("Error queueing request.");
|
|
||||||
}
|
|
||||||
|
|
||||||
final UsbRequest response = mConnection.requestWait();
|
|
||||||
if (response == null) {
|
|
||||||
throw new IOException("Null response");
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
request.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
final int totalBytesRead = buf.position();
|
|
||||||
if (totalBytesRead < MODEM_STATUS_HEADER_LENGTH) {
|
|
||||||
throw new IOException("Expected at least " + MODEM_STATUS_HEADER_LENGTH + " bytes");
|
|
||||||
}
|
|
||||||
|
|
||||||
return filterStatusBytes(dest, dest, totalBytesRead, endpoint.getMaxPacketSize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int write(byte[] src, int timeoutMillis) throws IOException {
|
|
||||||
final UsbEndpoint endpoint = mDevice.getInterface(mPortNumber).getEndpoint(1);
|
|
||||||
int offset = 0;
|
|
||||||
|
|
||||||
while (offset < src.length) {
|
|
||||||
final int writeLength;
|
|
||||||
final int amtWritten;
|
|
||||||
|
|
||||||
synchronized (mWriteBufferLock) {
|
|
||||||
final byte[] writeBuffer;
|
|
||||||
|
|
||||||
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
|
|
||||||
if (offset == 0) {
|
|
||||||
writeBuffer = src;
|
|
||||||
} else {
|
|
||||||
// bulkTransfer does not support offsets, make a copy.
|
|
||||||
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
|
|
||||||
writeBuffer = mWriteBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
amtWritten = mConnection.bulkTransfer(endpoint, writeBuffer, writeLength,
|
|
||||||
timeoutMillis);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (amtWritten <= 0) {
|
|
||||||
throw new IOException("Error writing " + writeLength
|
|
||||||
+ " bytes at offset " + offset + " length=" + src.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.d(TAG, "Wrote amtWritten=" + amtWritten + " attempted=" + writeLength);
|
|
||||||
offset += amtWritten;
|
|
||||||
}
|
|
||||||
return offset;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int setBaudRate(int baudRate) throws IOException {
|
private int setBaudRate(int baudRate) throws IOException {
|
||||||
@ -352,21 +287,23 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
|
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
||||||
throws IOException {
|
if(baudRate <= 0) {
|
||||||
|
throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
|
||||||
|
}
|
||||||
setBaudRate(baudRate);
|
setBaudRate(baudRate);
|
||||||
|
|
||||||
int config = 0;
|
int config = 0;
|
||||||
switch (dataBits) {
|
switch (dataBits) {
|
||||||
case DATABITS_5:
|
case DATABITS_5:
|
||||||
case DATABITS_6:
|
case DATABITS_6:
|
||||||
throw new IllegalArgumentException("Unsupported dataBits value: " + dataBits);
|
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
|
||||||
case DATABITS_7:
|
case DATABITS_7:
|
||||||
case DATABITS_8:
|
case DATABITS_8:
|
||||||
config |= dataBits;
|
config |= dataBits;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown dataBits value: " + dataBits);
|
throw new IllegalArgumentException("Invalid data bits: " + dataBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (parity) {
|
switch (parity) {
|
||||||
@ -386,7 +323,7 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
|||||||
config |= (0x04 << 8);
|
config |= (0x04 << 8);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown parity value: " + parity);
|
throw new IllegalArgumentException("Invalid parity: " + parity);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (stopBits) {
|
switch (stopBits) {
|
||||||
@ -394,12 +331,12 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
|||||||
config |= (0x00 << 11);
|
config |= (0x00 << 11);
|
||||||
break;
|
break;
|
||||||
case STOPBITS_1_5:
|
case STOPBITS_1_5:
|
||||||
throw new IllegalArgumentException("Unsupported stopBits value: 1.5");
|
throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
|
||||||
case STOPBITS_2:
|
case STOPBITS_2:
|
||||||
config |= (0x02 << 11);
|
config |= (0x02 << 11);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
|
throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE,
|
int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE,
|
||||||
|
@ -65,25 +65,19 @@ public class ProbeTable {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
method = driverClass.getMethod("getSupportedDevices");
|
method = driverClass.getMethod("getSupportedDevices");
|
||||||
} catch (SecurityException e) {
|
} catch (SecurityException | NoSuchMethodException e) {
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (NoSuchMethodException e) {
|
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
final Map<Integer, int[]> devices;
|
final Map<Integer, int[]> devices;
|
||||||
try {
|
try {
|
||||||
devices = (Map<Integer, int[]>) method.invoke(null);
|
devices = (Map<Integer, int[]>) method.invoke(null);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (IllegalAccessException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (InvocationTargetException e) {
|
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Map.Entry<Integer, int[]> entry : devices.entrySet()) {
|
for (Map.Entry<Integer, int[]> entry : devices.entrySet()) {
|
||||||
final int vendorId = entry.getKey().intValue();
|
final int vendorId = entry.getKey();
|
||||||
for (int productId : entry.getValue()) {
|
for (int productId : entry.getValue()) {
|
||||||
addProduct(vendorId, productId, driverClass);
|
addProduct(vendorId, productId, driverClass);
|
||||||
}
|
}
|
||||||
|
@ -32,12 +32,10 @@ import android.hardware.usb.UsbDevice;
|
|||||||
import android.hardware.usb.UsbDeviceConnection;
|
import android.hardware.usb.UsbDeviceConnection;
|
||||||
import android.hardware.usb.UsbEndpoint;
|
import android.hardware.usb.UsbEndpoint;
|
||||||
import android.hardware.usb.UsbInterface;
|
import android.hardware.usb.UsbInterface;
|
||||||
import android.hardware.usb.UsbRequest;
|
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -111,8 +109,6 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
|||||||
|
|
||||||
private int mDeviceType = DEVICE_TYPE_HX;
|
private int mDeviceType = DEVICE_TYPE_HX;
|
||||||
|
|
||||||
private UsbEndpoint mReadEndpoint;
|
|
||||||
private UsbEndpoint mWriteEndpoint;
|
|
||||||
private UsbEndpoint mInterruptEndpoint;
|
private UsbEndpoint mInterruptEndpoint;
|
||||||
|
|
||||||
private int mControlLinesValue = 0;
|
private int mControlLinesValue = 0;
|
||||||
@ -336,17 +332,13 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
|||||||
opened = true;
|
opened = true;
|
||||||
} finally {
|
} finally {
|
||||||
if (!opened) {
|
if (!opened) {
|
||||||
mConnection = null;
|
close();
|
||||||
connection.releaseInterface(usbInterface);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void closeInt() {
|
||||||
if (mConnection == null) {
|
|
||||||
throw new IOException("Already closed");
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
mStopReadStatusThread = true;
|
mStopReadStatusThread = true;
|
||||||
synchronized (mReadStatusThreadLock) {
|
synchronized (mReadStatusThreadLock) {
|
||||||
@ -359,80 +351,14 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
resetDevice();
|
resetDevice();
|
||||||
} finally {
|
} catch(Exception ignored) {}
|
||||||
try {
|
try {
|
||||||
mConnection.releaseInterface(mDevice.getInterface(0));
|
mConnection.releaseInterface(mDevice.getInterface(0));
|
||||||
} finally {
|
} catch(Exception ignored) {}
|
||||||
mConnection = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int read(byte[] dest, int timeoutMillis) throws IOException {
|
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
||||||
final UsbRequest request = new UsbRequest();
|
|
||||||
try {
|
|
||||||
request.initialize(mConnection, mReadEndpoint);
|
|
||||||
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
|
||||||
if (!request.queue(buf, dest.length)) {
|
|
||||||
throw new IOException("Error queueing request.");
|
|
||||||
}
|
|
||||||
|
|
||||||
final UsbRequest response = mConnection.requestWait();
|
|
||||||
if (response == null) {
|
|
||||||
throw new IOException("Null response");
|
|
||||||
}
|
|
||||||
|
|
||||||
final int nread = buf.position();
|
|
||||||
if (nread > 0) {
|
|
||||||
//Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
|
|
||||||
return nread;
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
request.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int write(byte[] src, int timeoutMillis) throws IOException {
|
|
||||||
int offset = 0;
|
|
||||||
|
|
||||||
while (offset < src.length) {
|
|
||||||
final int writeLength;
|
|
||||||
final int amtWritten;
|
|
||||||
|
|
||||||
synchronized (mWriteBufferLock) {
|
|
||||||
final byte[] writeBuffer;
|
|
||||||
|
|
||||||
writeLength = Math.min(src.length - offset, mWriteBuffer.length);
|
|
||||||
if (offset == 0) {
|
|
||||||
writeBuffer = src;
|
|
||||||
} else {
|
|
||||||
// bulkTransfer does not support offsets, make a copy.
|
|
||||||
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
|
|
||||||
writeBuffer = mWriteBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
amtWritten = mConnection.bulkTransfer(mWriteEndpoint,
|
|
||||||
writeBuffer, writeLength, timeoutMillis);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (amtWritten <= 0) {
|
|
||||||
throw new IOException("Error writing " + writeLength
|
|
||||||
+ " bytes at offset " + offset + " length="
|
|
||||||
+ src.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
offset += amtWritten;
|
|
||||||
}
|
|
||||||
return offset;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setParameters(int baudRate, int dataBits, int stopBits,
|
|
||||||
int parity) throws IOException {
|
|
||||||
if ((mBaudRate == baudRate) && (mDataBits == dataBits)
|
if ((mBaudRate == baudRate) && (mDataBits == dataBits)
|
||||||
&& (mStopBits == stopBits) && (mParity == parity)) {
|
&& (mStopBits == stopBits) && (mParity == parity)) {
|
||||||
// Make sure no action is performed if there is nothing to change
|
// Make sure no action is performed if there is nothing to change
|
||||||
@ -441,6 +367,9 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
|||||||
|
|
||||||
byte[] lineRequestData = new byte[7];
|
byte[] lineRequestData = new byte[7];
|
||||||
|
|
||||||
|
if(baudRate <= 0) {
|
||||||
|
throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
|
||||||
|
}
|
||||||
lineRequestData[0] = (byte) (baudRate & 0xff);
|
lineRequestData[0] = (byte) (baudRate & 0xff);
|
||||||
lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff);
|
lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff);
|
||||||
lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff);
|
lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff);
|
||||||
@ -450,44 +379,39 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
|||||||
case STOPBITS_1:
|
case STOPBITS_1:
|
||||||
lineRequestData[4] = 0;
|
lineRequestData[4] = 0;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case STOPBITS_1_5:
|
case STOPBITS_1_5:
|
||||||
lineRequestData[4] = 1;
|
lineRequestData[4] = 1;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case STOPBITS_2:
|
case STOPBITS_2:
|
||||||
lineRequestData[4] = 2;
|
lineRequestData[4] = 2;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
|
throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (parity) {
|
switch (parity) {
|
||||||
case PARITY_NONE:
|
case PARITY_NONE:
|
||||||
lineRequestData[5] = 0;
|
lineRequestData[5] = 0;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PARITY_ODD:
|
case PARITY_ODD:
|
||||||
lineRequestData[5] = 1;
|
lineRequestData[5] = 1;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PARITY_EVEN:
|
case PARITY_EVEN:
|
||||||
lineRequestData[5] = 2;
|
lineRequestData[5] = 2;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PARITY_MARK:
|
case PARITY_MARK:
|
||||||
lineRequestData[5] = 3;
|
lineRequestData[5] = 3;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PARITY_SPACE:
|
case PARITY_SPACE:
|
||||||
lineRequestData[5] = 4;
|
lineRequestData[5] = 4;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Unknown parity value: " + parity);
|
throw new IllegalArgumentException("Invalid parity: " + parity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(dataBits < DATABITS_5 || dataBits > DATABITS_8) {
|
||||||
|
throw new IllegalArgumentException("Invalid data bits: " + dataBits);
|
||||||
|
}
|
||||||
lineRequestData[6] = (byte) dataBits;
|
lineRequestData[6] = (byte) dataBits;
|
||||||
|
|
||||||
ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);
|
ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);
|
||||||
|
@ -76,7 +76,7 @@ public final class UsbId {
|
|||||||
public static final int ARM_MBED = 0x0204;
|
public static final int ARM_MBED = 0x0204;
|
||||||
|
|
||||||
private UsbId() {
|
private UsbId() {
|
||||||
throw new IllegalAccessError("Non-instantiable class.");
|
throw new IllegalAccessError("Non-instantiable class");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -145,9 +145,9 @@ public interface UsbSerialPort {
|
|||||||
* {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or
|
* {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or
|
||||||
* {@link #PARITY_SPACE}.
|
* {@link #PARITY_SPACE}.
|
||||||
* @throws IOException on error setting the port parameters
|
* @throws IOException on error setting the port parameters
|
||||||
|
* @throws UnsupportedOperationException if not supported by a specific device
|
||||||
*/
|
*/
|
||||||
public void setParameters(
|
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException;
|
||||||
int baudRate, int dataBits, int stopBits, int parity) throws IOException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the CD (Carrier Detect) bit from the underlying UART.
|
* Gets the CD (Carrier Detect) bit from the underlying UART.
|
||||||
|
@ -95,15 +95,8 @@ public class UsbSerialProber {
|
|||||||
final Constructor<? extends UsbSerialDriver> ctor =
|
final Constructor<? extends UsbSerialDriver> ctor =
|
||||||
driverClass.getConstructor(UsbDevice.class);
|
driverClass.getConstructor(UsbDevice.class);
|
||||||
driver = ctor.newInstance(usbDevice);
|
driver = ctor.newInstance(usbDevice);
|
||||||
} catch (NoSuchMethodException e) {
|
} catch (NoSuchMethodException | IllegalArgumentException | InstantiationException |
|
||||||
throw new RuntimeException(e);
|
IllegalAccessException | InvocationTargetException e) {
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (InstantiationException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (IllegalAccessException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (InvocationTargetException e) {
|
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
return driver;
|
return driver;
|
||||||
|
@ -125,12 +125,12 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
public void run() {
|
public void run() {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
if (getState() != State.STOPPED) {
|
if (getState() != State.STOPPED) {
|
||||||
throw new IllegalStateException("Already running.");
|
throw new IllegalStateException("Already running");
|
||||||
}
|
}
|
||||||
mState = State.RUNNING;
|
mState = State.RUNNING;
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.i(TAG, "Running ..");
|
Log.i(TAG, "Running ...");
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
if (getState() != State.RUNNING) {
|
if (getState() != State.RUNNING) {
|
||||||
@ -148,7 +148,7 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
} finally {
|
} finally {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
mState = State.STOPPED;
|
mState = State.STOPPED;
|
||||||
Log.i(TAG, "Stopped.");
|
Log.i(TAG, "Stopped");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user