1
0
mirror of https://github.com/mik3y/usb-serial-for-android synced 2025-06-08 00:16:13 +00:00
This commit is contained in:
Tim Vahlbrock 2019-11-14 14:15:39 +01:00
commit 92b16a8c24
15 changed files with 911 additions and 1000 deletions

View File

@ -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 {

View File

@ -0,0 +1 @@
-keep class com.hoho.android.usbserial.driver.* { *; }

View File

@ -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

View File

@ -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 {
usbRead(0); if(usbIoManager != null)
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,16 +299,14 @@ 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;
try { try {
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -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,15 +680,11 @@ 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) fail("invalid databits "+i);
; // todo: add range check in driver
else if (usbSerialDriver instanceof CdcAcmSerialDriver)
; // todo: add range check in driver
else
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("");
}
} }

View File

@ -1,445 +1,368 @@
/* Copyright 2011-2013 Google Inc. /* Copyright 2011-2013 Google Inc.
* Copyright 2013 mike wakerly <opensource@hoho.com> * Copyright 2013 mike wakerly <opensource@hoho.com>
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA. * USA.
* *
* Project home page: https://github.com/mik3y/usb-serial-for-android * Project home page: https://github.com/mik3y/usb-serial-for-android
*/ */
package com.hoho.android.usbserial.driver; 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.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.util.Collections;
import java.nio.ByteBuffer; import java.util.LinkedHashMap;
import java.util.Collections; import java.util.List;
import java.util.LinkedHashMap; import java.util.Map;
import java.util.List;
import java.util.Map; /**
* USB CDC/ACM serial driver implementation.
/** *
* USB CDC/ACM serial driver implementation. * @author mike wakerly (opensource@hoho.com)
* * @see <a
* @author mike wakerly (opensource@hoho.com) * href="http://www.usb.org/developers/devclass_docs/usbcdc11.pdf">Universal
* @see <a * Serial Bus Class Definitions for Communication Devices, v1.1</a>
* href="http://www.usb.org/developers/devclass_docs/usbcdc11.pdf">Universal */
* Serial Bus Class Definitions for Communication Devices, v1.1</a> public class CdcAcmSerialDriver implements UsbSerialDriver {
*/
public class CdcAcmSerialDriver implements UsbSerialDriver { private final String TAG = CdcAcmSerialDriver.class.getSimpleName();
private final String TAG = CdcAcmSerialDriver.class.getSimpleName(); private final UsbDevice mDevice;
private final UsbSerialPort mPort;
private final UsbDevice mDevice;
private final UsbSerialPort mPort; public CdcAcmSerialDriver(UsbDevice device) {
private UsbRequest mUsbRequest; mDevice = device;
mPort = new CdcAcmSerialPort(device, 0);
public CdcAcmSerialDriver(UsbDevice device) { }
mDevice = device;
mPort = new CdcAcmSerialPort(device, 0); @Override
} public UsbDevice getDevice() {
return mDevice;
@Override }
public UsbDevice getDevice() {
return mDevice; @Override
} public List<UsbSerialPort> getPorts() {
return Collections.singletonList(mPort);
@Override }
public List<UsbSerialPort> getPorts() {
return Collections.singletonList(mPort); class CdcAcmSerialPort extends CommonUsbSerialPort {
}
private UsbInterface mControlInterface;
class CdcAcmSerialPort extends CommonUsbSerialPort { private UsbInterface mDataInterface;
private UsbInterface mControlInterface; private UsbEndpoint mControlEndpoint;
private UsbInterface mDataInterface;
private int mControlIndex;
private UsbEndpoint mControlEndpoint;
private UsbEndpoint mReadEndpoint; private boolean mRts = false;
private UsbEndpoint mWriteEndpoint; private boolean mDtr = false;
private int mControlIndex; private static final int USB_RECIP_INTERFACE = 0x01;
private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;
private boolean mRts = false;
private boolean mDtr = false; private static final int SET_LINE_CODING = 0x20; // USB CDC 1.1 section 6.2
private static final int GET_LINE_CODING = 0x21;
private static final int USB_RECIP_INTERFACE = 0x01; private static final int SET_CONTROL_LINE_STATE = 0x22;
private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE; private static final int SEND_BREAK = 0x23;
private static final int SET_LINE_CODING = 0x20; // USB CDC 1.1 section 6.2 public CdcAcmSerialPort(UsbDevice device, int portNumber) {
private static final int GET_LINE_CODING = 0x21; super(device, portNumber);
private static final int SET_CONTROL_LINE_STATE = 0x22; }
private static final int SEND_BREAK = 0x23;
@Override
public CdcAcmSerialPort(UsbDevice device, int portNumber) { public UsbSerialDriver getDriver() {
super(device, portNumber); return CdcAcmSerialDriver.this;
} }
@Override @Override
public UsbSerialDriver getDriver() { public void open(UsbDeviceConnection connection) throws IOException {
return CdcAcmSerialDriver.this; if (mConnection != null) {
} throw new IOException("Already open");
}
@Override
public void open(UsbDeviceConnection connection) throws IOException { mConnection = connection;
if (mConnection != null) { boolean opened = false;
throw new IOException("Already open"); try {
} if (1 == mDevice.getInterfaceCount()) {
Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
mConnection = connection; openSingleInterface();
boolean opened = false; } else {
try { Log.d(TAG,"trying default interface logic");
openInterface();
if (1 == mDevice.getInterfaceCount()) { }
Log.d(TAG,"device might be castrated ACM device, trying single interface logic"); opened = true;
openSingleInterface(); } finally {
} else { if (!opened) {
Log.d(TAG,"trying default interface logic"); close();
openInterface(); }
} }
}
opened = true;
} finally { private void openSingleInterface() throws IOException {
if (!opened) { // the following code is inspired by the cdc-acm driver
mConnection = null; // in the linux kernel
// just to be on the save side
mControlEndpoint = null; mControlIndex = 0;
mReadEndpoint = null; mControlInterface = mDevice.getInterface(0);
mWriteEndpoint = null; Log.d(TAG, "Control iface=" + mControlInterface);
}
} mDataInterface = mDevice.getInterface(0);
} Log.d(TAG, "data iface=" + mDataInterface);
private void openSingleInterface() throws IOException { if (!mConnection.claimInterface(mControlInterface, true)) {
// the following code is inspired by the cdc-acm driver throw new IOException("Could not claim shared control/data interface");
// in the linux kernel }
mControlIndex = 0; int endCount = mControlInterface.getEndpointCount();
mControlInterface = mDevice.getInterface(0);
Log.d(TAG, "Control iface=" + mControlInterface); if (endCount < 3) {
Log.d(TAG,"not enough endpoints - need 3. count=" + mControlInterface.getEndpointCount());
mDataInterface = mDevice.getInterface(0); throw new IOException("Insufficient number of endpoints (" + mControlInterface.getEndpointCount() + ")");
Log.d(TAG, "data iface=" + mDataInterface); }
if (!mConnection.claimInterface(mControlInterface, true)) { // Analyse endpoints for their properties
throw new IOException("Could not claim shared control/data interface."); mControlEndpoint = null;
} mReadEndpoint = null;
mWriteEndpoint = null;
int endCount = mControlInterface.getEndpointCount(); for (int i = 0; i < endCount; ++i) {
UsbEndpoint ep = mControlInterface.getEndpoint(i);
if (endCount < 3) { if ((ep.getDirection() == UsbConstants.USB_DIR_IN) &&
Log.d(TAG,"not enough endpoints - need 3. count=" + mControlInterface.getEndpointCount()); (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) {
throw new IOException("Insufficient number of endpoints(" + mControlInterface.getEndpointCount() + ")"); Log.d(TAG,"Found controlling endpoint");
} mControlEndpoint = ep;
} else if ((ep.getDirection() == UsbConstants.USB_DIR_IN) &&
// Analyse endpoints for their properties (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
mControlEndpoint = null; Log.d(TAG,"Found reading endpoint");
mReadEndpoint = null; mReadEndpoint = ep;
mWriteEndpoint = null; } else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) &&
for (int i = 0; i < endCount; ++i) { (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
UsbEndpoint ep = mControlInterface.getEndpoint(i); Log.d(TAG,"Found writing endpoint");
if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && mWriteEndpoint = ep;
(ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) { }
Log.d(TAG,"Found controlling endpoint");
mControlEndpoint = ep;
} else if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && if ((mControlEndpoint != null) &&
(ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) { (mReadEndpoint != null) &&
Log.d(TAG,"Found reading endpoint"); (mWriteEndpoint != null)) {
mReadEndpoint = ep; Log.d(TAG,"Found all required endpoints");
} else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) && break;
(ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) { }
Log.d(TAG,"Found writing endpoint"); }
mWriteEndpoint = ep;
} if ((mControlEndpoint == null) ||
(mReadEndpoint == null) ||
(mWriteEndpoint == null)) {
if ((mControlEndpoint != null) && Log.d(TAG,"Could not establish all endpoints");
(mReadEndpoint != null) && throw new IOException("Could not establish all endpoints");
(mWriteEndpoint != null)) { }
Log.d(TAG,"Found all required endpoints"); }
break;
} private void openInterface() throws IOException {
} Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
if ((mControlEndpoint == null) || mControlInterface = null;
(mReadEndpoint == null) || mDataInterface = null;
(mWriteEndpoint == null)) { for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
Log.d(TAG,"Could not establish all endpoints"); UsbInterface usbInterface = mDevice.getInterface(i);
throw new IOException("Could not establish all endpoints"); if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM) {
} mControlIndex = i;
} mControlInterface = usbInterface;
}
private void openInterface() throws IOException { if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount()); mDataInterface = usbInterface;
}
mControlInterface = null; }
mDataInterface = null;
for (int i = 0; i < mDevice.getInterfaceCount(); i++) { if(mControlInterface == null) {
UsbInterface usbInterface = mDevice.getInterface(i); throw new IOException("No control interface");
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM) { }
mControlIndex = i; Log.d(TAG, "Control iface=" + mControlInterface);
mControlInterface = usbInterface;
} if (!mConnection.claimInterface(mControlInterface, true)) {
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) { throw new IOException("Could not claim control interface");
mDataInterface = usbInterface; }
}
} mControlEndpoint = mControlInterface.getEndpoint(0);
if (mControlEndpoint.getDirection() != UsbConstants.USB_DIR_IN || mControlEndpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
if(mControlInterface == null) { throw new IOException("Invalid control endpoint");
throw new IOException("no control interface."); }
}
Log.d(TAG, "Control iface=" + mControlInterface); if(mDataInterface == null) {
throw new IOException("No data interface");
if (!mConnection.claimInterface(mControlInterface, true)) { }
throw new IOException("Could not claim control interface."); Log.d(TAG, "data iface=" + mDataInterface);
}
if (!mConnection.claimInterface(mDataInterface, true)) {
mControlEndpoint = mControlInterface.getEndpoint(0); throw new IOException("Could not claim data interface");
if (mControlEndpoint.getDirection() != UsbConstants.USB_DIR_IN || mControlEndpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) { }
throw new IOException("invalid control endpoint");
} mReadEndpoint = null;
mWriteEndpoint = null;
if(mDataInterface == null) { for (int i = 0; i < mDataInterface.getEndpointCount(); i++) {
throw new IOException("no data interface."); UsbEndpoint ep = mDataInterface.getEndpoint(i);
} if (ep.getDirection() == UsbConstants.USB_DIR_IN && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
Log.d(TAG, "data iface=" + mDataInterface); mReadEndpoint = ep;
if (ep.getDirection() == UsbConstants.USB_DIR_OUT && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
if (!mConnection.claimInterface(mDataInterface, true)) { mWriteEndpoint = ep;
throw new IOException("Could not claim data interface."); }
} if (mReadEndpoint == null || mWriteEndpoint == null) {
throw new IOException("Could not get read&write endpoints");
mReadEndpoint = null; }
mWriteEndpoint = null; }
for (int i = 0; i < mDataInterface.getEndpointCount(); i++) {
UsbEndpoint ep = mDataInterface.getEndpoint(i); private int sendAcmControlMessage(int request, int value, byte[] buf) throws IOException {
if (ep.getDirection() == UsbConstants.USB_DIR_IN && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) int len = mConnection.controlTransfer(
mReadEndpoint = ep; USB_RT_ACM, request, value, mControlIndex, buf, buf != null ? buf.length : 0, 5000);
if (ep.getDirection() == UsbConstants.USB_DIR_OUT && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) if(len < 0) {
mWriteEndpoint = ep; throw new IOException("controlTransfer failed");
} }
if (mReadEndpoint == null || mWriteEndpoint == null) { return len;
throw new IOException("Could not get read&write endpoints."); }
}
} @Override
public void closeInt() {
private int sendAcmControlMessage(int request, int value, byte[] buf) throws IOException { try {
int len = mConnection.controlTransfer( mConnection.releaseInterface(mControlInterface);
USB_RT_ACM, request, value, mControlIndex, buf, buf != null ? buf.length : 0, 5000); mConnection.releaseInterface(mDataInterface);
if(len < 0) { } catch(Exception ignored) {}
throw new IOException("controlTransfer failed."); }
}
return len; @Override
} public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
if(baudRate <= 0) {
@Override throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
public void close() throws IOException { }
if (mConnection == null) { if(dataBits < DATABITS_5 || dataBits > DATABITS_8) {
throw new IOException("Already closed"); throw new IllegalArgumentException("Invalid data bits: " + dataBits);
} }
synchronized (this) { byte stopBitsByte;
if (mUsbRequest != null) switch (stopBits) {
mUsbRequest.cancel(); case STOPBITS_1: stopBitsByte = 0; break;
} case STOPBITS_1_5: stopBitsByte = 1; break;
mConnection.close(); case STOPBITS_2: stopBitsByte = 2; break;
mConnection = null; default: throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
} }
@Override byte parityBitesByte;
public int read(byte[] dest, int timeoutMillis) throws IOException { switch (parity) {
final UsbRequest request = new UsbRequest(); case PARITY_NONE: parityBitesByte = 0; break;
try { case PARITY_ODD: parityBitesByte = 1; break;
request.initialize(mConnection, mReadEndpoint); case PARITY_EVEN: parityBitesByte = 2; break;
final ByteBuffer buf = ByteBuffer.wrap(dest); case PARITY_MARK: parityBitesByte = 3; break;
if (!request.queue(buf, dest.length)) { case PARITY_SPACE: parityBitesByte = 4; break;
throw new IOException("Error queueing request."); default: throw new IllegalArgumentException("Invalid parity: " + parity);
} }
mUsbRequest = request; byte[] msg = {
final UsbRequest response = mConnection.requestWait(); (byte) ( baudRate & 0xff),
synchronized (this) { (byte) ((baudRate >> 8 ) & 0xff),
mUsbRequest = null; (byte) ((baudRate >> 16) & 0xff),
} (byte) ((baudRate >> 24) & 0xff),
if (response == null) { stopBitsByte,
throw new IOException("Null response"); parityBitesByte,
} (byte) dataBits};
sendAcmControlMessage(SET_LINE_CODING, 0, msg);
final int nread = buf.position(); }
if (nread > 0) {
//Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length))); @Override
return nread; public boolean getCD() throws IOException {
} else { return false; // TODO
return 0; }
}
} finally { @Override
mUsbRequest = null; public boolean getCTS() throws IOException {
request.close(); return false; // TODO
} }
}
@Override
@Override public boolean getDSR() throws IOException {
public int write(byte[] src, int timeoutMillis) throws IOException { return false; // TODO
// TODO(mikey): Nearly identical to FtdiSerial write. Refactor. }
int offset = 0;
@Override
while (offset < src.length) { public boolean getDTR() throws IOException {
final int writeLength; return mDtr;
final int amtWritten; }
synchronized (mWriteBufferLock) { @Override
final byte[] writeBuffer; public void setDTR(boolean value) throws IOException {
mDtr = value;
writeLength = Math.min(src.length - offset, mWriteBuffer.length); setDtrRts();
if (offset == 0) { }
writeBuffer = src;
} else { @Override
// bulkTransfer does not support offsets, make a copy. public boolean getRI() throws IOException {
System.arraycopy(src, offset, mWriteBuffer, 0, writeLength); return false; // TODO
writeBuffer = mWriteBuffer; }
}
@Override
amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength, public boolean getRTS() throws IOException {
timeoutMillis); return mRts;
} }
if (amtWritten <= 0) {
throw new IOException("Error writing " + writeLength @Override
+ " bytes at offset " + offset + " length=" + src.length); public void setRTS(boolean value) throws IOException {
} mRts = value;
setDtrRts();
Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength); }
offset += amtWritten;
} private void setDtrRts() throws IOException {
return offset; int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0);
} sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
}
@Override
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException { }
byte stopBitsByte;
switch (stopBits) { public static Map<Integer, int[]> getSupportedDevices() {
case STOPBITS_1: stopBitsByte = 0; break; final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
case STOPBITS_1_5: stopBitsByte = 1; break; supportedDevices.put(UsbId.VENDOR_ARDUINO,
case STOPBITS_2: stopBitsByte = 2; break; new int[] {
default: throw new IllegalArgumentException("Bad value for stopBits: " + stopBits); UsbId.ARDUINO_UNO,
} UsbId.ARDUINO_UNO_R3,
UsbId.ARDUINO_MEGA_2560,
byte parityBitesByte; UsbId.ARDUINO_MEGA_2560_R3,
switch (parity) { UsbId.ARDUINO_SERIAL_ADAPTER,
case PARITY_NONE: parityBitesByte = 0; break; UsbId.ARDUINO_SERIAL_ADAPTER_R3,
case PARITY_ODD: parityBitesByte = 1; break; UsbId.ARDUINO_MEGA_ADK,
case PARITY_EVEN: parityBitesByte = 2; break; UsbId.ARDUINO_MEGA_ADK_R3,
case PARITY_MARK: parityBitesByte = 3; break; UsbId.ARDUINO_LEONARDO,
case PARITY_SPACE: parityBitesByte = 4; break; UsbId.ARDUINO_MICRO,
default: throw new IllegalArgumentException("Bad value for parity: " + parity); });
} supportedDevices.put(UsbId.VENDOR_VAN_OOIJEN_TECH,
new int[] {
byte[] msg = { UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL,
(byte) ( baudRate & 0xff), });
(byte) ((baudRate >> 8 ) & 0xff), supportedDevices.put(UsbId.VENDOR_ATMEL,
(byte) ((baudRate >> 16) & 0xff), new int[] {
(byte) ((baudRate >> 24) & 0xff), UsbId.ATMEL_LUFA_CDC_DEMO_APP,
stopBitsByte, });
parityBitesByte, supportedDevices.put(UsbId.VENDOR_LEAFLABS,
(byte) dataBits}; new int[] {
sendAcmControlMessage(SET_LINE_CODING, 0, msg); UsbId.LEAFLABS_MAPLE,
} });
supportedDevices.put(UsbId.VENDOR_ARM,
@Override new int[] {
public boolean getCD() throws IOException { UsbId.ARM_MBED,
return false; // TODO });
} return supportedDevices;
}
@Override
public boolean getCTS() throws IOException { }
return false; // TODO
}
@Override
public boolean getDSR() throws IOException {
return false; // TODO
}
@Override
public boolean getDTR() throws IOException {
return mDtr;
}
@Override
public void setDTR(boolean value) throws IOException {
mDtr = value;
setDtrRts();
}
@Override
public boolean getRI() throws IOException {
return false; // TODO
}
@Override
public boolean getRTS() throws IOException {
return mRts;
}
@Override
public void setRTS(boolean value) throws IOException {
mRts = value;
setDtrRts();
}
private void setDtrRts() throws IOException {
int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0);
sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
}
}
public static Map<Integer, int[]> getSupportedDevices() {
final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
supportedDevices.put(UsbId.VENDOR_ARDUINO,
new int[] {
UsbId.ARDUINO_UNO,
UsbId.ARDUINO_UNO_R3,
UsbId.ARDUINO_MEGA_2560,
UsbId.ARDUINO_MEGA_2560_R3,
UsbId.ARDUINO_SERIAL_ADAPTER,
UsbId.ARDUINO_SERIAL_ADAPTER_R3,
UsbId.ARDUINO_MEGA_ADK,
UsbId.ARDUINO_MEGA_ADK_R3,
UsbId.ARDUINO_LEONARDO,
UsbId.ARDUINO_MICRO,
});
supportedDevices.put(UsbId.VENDOR_VAN_OOIJEN_TECH,
new int[] {
UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL,
});
supportedDevices.put(UsbId.VENDOR_ATMEL,
new int[] {
UsbId.ATMEL_LUFA_CDC_DEMO_APP,
});
supportedDevices.put(UsbId.VENDOR_LEAFLABS,
new int[] {
UsbId.LEAFLABS_MAPLE,
});
supportedDevices.put(UsbId.VENDOR_ARM,
new int[] {
UsbId.ARM_MBED,
});
return supportedDevices;
}
}

View File

@ -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);

View File

@ -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,10 +57,9 @@ 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];
} }
@Override @Override
public String toString() { public String toString() {
return String.format("<%s device_name=%s device_id=%s port_number=%s>", return String.format("<%s device_name=%s device_id=%s port_number=%s>",
@ -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;

View File

@ -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);
} }

View File

@ -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, count);
packetIdx * (maxPacketSize - MODEM_STATUS_HEADER_LENGTH),
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,

View File

@ -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);
} }

View File

@ -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 {
mConnection.releaseInterface(mDevice.getInterface(0));
} finally {
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(mDevice.getInterface(0));
final ByteBuffer buf = ByteBuffer.wrap(dest); } catch(Exception ignored) {}
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 @Override
public int write(byte[] src, int timeoutMillis) throws IOException { public void setParameters(int baudRate, int dataBits, int stopBits, int parity) 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);

View File

@ -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");
} }
} }

View File

@ -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.

View File

@ -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;

View File

@ -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");
} }
} }
} }