mirror of
https://github.com/mik3y/usb-serial-for-android
synced 2025-06-07 16:06:10 +00:00
Compare commits
13 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
c608aadc59 | ||
|
06faad5622 | ||
|
52042f8c3e | ||
|
068fe80c07 | ||
|
e1018ab31c | ||
|
026355f61e | ||
|
150174573c | ||
|
9911e141a7 | ||
|
2673407f1d | ||
|
8584fe4cb8 | ||
|
0b5950c991 | ||
|
9f93e192ca | ||
|
f5380975ce |
6
.idea/AndroidProjectSystem.xml
generated
Normal file
6
.idea/AndroidProjectSystem.xml
generated
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="AndroidProjectSystem">
|
||||||
|
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
|
||||||
|
</component>
|
||||||
|
</project>
|
2
.idea/compiler.xml
generated
2
.idea/compiler.xml
generated
@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="CompilerConfiguration">
|
<component name="CompilerConfiguration">
|
||||||
<bytecodeTargetLevel target="17" />
|
<bytecodeTargetLevel target="21" />
|
||||||
</component>
|
</component>
|
||||||
</project>
|
</project>
|
9
.idea/misc.xml
generated
9
.idea/misc.xml
generated
@ -1,3 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
<component name="NullableNotNullManager">
|
<component name="NullableNotNullManager">
|
||||||
@ -5,7 +6,7 @@
|
|||||||
<option name="myDefaultNotNull" value="androidx.annotation.NonNull" />
|
<option name="myDefaultNotNull" value="androidx.annotation.NonNull" />
|
||||||
<option name="myNullables">
|
<option name="myNullables">
|
||||||
<value>
|
<value>
|
||||||
<list size="17">
|
<list size="18">
|
||||||
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
|
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
|
||||||
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
|
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
|
||||||
<item index="2" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" />
|
<item index="2" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" />
|
||||||
@ -23,12 +24,13 @@
|
|||||||
<item index="14" class="java.lang.String" itemvalue="io.reactivex.rxjava3.annotations.Nullable" />
|
<item index="14" class="java.lang.String" itemvalue="io.reactivex.rxjava3.annotations.Nullable" />
|
||||||
<item index="15" class="java.lang.String" itemvalue="org.jspecify.nullness.Nullable" />
|
<item index="15" class="java.lang.String" itemvalue="org.jspecify.nullness.Nullable" />
|
||||||
<item index="16" class="java.lang.String" itemvalue="jakarta.annotation.Nullable" />
|
<item index="16" class="java.lang.String" itemvalue="jakarta.annotation.Nullable" />
|
||||||
|
<item index="17" class="java.lang.String" itemvalue="org.jspecify.annotations.Nullable" />
|
||||||
</list>
|
</list>
|
||||||
</value>
|
</value>
|
||||||
</option>
|
</option>
|
||||||
<option name="myNotNulls">
|
<option name="myNotNulls">
|
||||||
<value>
|
<value>
|
||||||
<list size="16">
|
<list size="17">
|
||||||
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
|
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
|
||||||
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
|
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
|
||||||
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
|
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
|
||||||
@ -45,11 +47,12 @@
|
|||||||
<item index="13" class="java.lang.String" itemvalue="io.reactivex.rxjava3.annotations.NonNull" />
|
<item index="13" class="java.lang.String" itemvalue="io.reactivex.rxjava3.annotations.NonNull" />
|
||||||
<item index="14" class="java.lang.String" itemvalue="jakarta.annotation.Nonnull" />
|
<item index="14" class="java.lang.String" itemvalue="jakarta.annotation.Nonnull" />
|
||||||
<item index="15" class="java.lang.String" itemvalue="org.jspecify.nullness.NonNull" />
|
<item index="15" class="java.lang.String" itemvalue="org.jspecify.nullness.NonNull" />
|
||||||
|
<item index="16" class="java.lang.String" itemvalue="org.jspecify.annotations.NonNull" />
|
||||||
</list>
|
</list>
|
||||||
</value>
|
</value>
|
||||||
</option>
|
</option>
|
||||||
</component>
|
</component>
|
||||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
|
||||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||||
</component>
|
</component>
|
||||||
<component name="ProjectType">
|
<component name="ProjectType">
|
||||||
|
17
.idea/runConfigurations.xml
generated
Normal file
17
.idea/runConfigurations.xml
generated
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RunConfigurationProducerService">
|
||||||
|
<option name="ignoredProducers">
|
||||||
|
<set>
|
||||||
|
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
|
||||||
|
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
|
||||||
|
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
25
README.md
25
README.md
@ -45,7 +45,7 @@ If using gradle kotlin use line
|
|||||||
Add library to dependencies
|
Add library to dependencies
|
||||||
```gradle
|
```gradle
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'com.github.mik3y:usb-serial-for-android:3.8.0'
|
implementation 'com.github.mik3y:usb-serial-for-android:3.9.0'
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -145,8 +145,8 @@ UsbSerialProber prober = new UsbSerialProber(customTable);
|
|||||||
List<UsbSerialDriver> drivers = prober.findAllDrivers(usbManager);
|
List<UsbSerialDriver> drivers = prober.findAllDrivers(usbManager);
|
||||||
// ...
|
// ...
|
||||||
```
|
```
|
||||||
*Note*: as of v3.5.0 this library detects CDC devices by USB interface types instead of fixed VID+PID,
|
*Note*: as of v3.5.0 this library detects CDC/ACM devices by USB interface types instead of fixed VID+PID,
|
||||||
so custom probers are typically not required any more for CDC devices.
|
so custom probers are typically not required any more for CDC/ACM devices.
|
||||||
|
|
||||||
Of course, nothing requires you to use UsbSerialProber at all: you can
|
Of course, nothing requires you to use UsbSerialProber at all: you can
|
||||||
instantiate driver classes directly if you know what you're doing; just supply
|
instantiate driver classes directly if you know what you're doing; just supply
|
||||||
@ -154,22 +154,23 @@ a compatible UsbDevice.
|
|||||||
|
|
||||||
## Compatible Devices
|
## Compatible Devices
|
||||||
|
|
||||||
This library supports USB to serial converter chips:
|
This library supports USB to serial converter chips with specific drivers
|
||||||
* FTDI FT232R, FT232H, FT2232H, FT4232H, FT230X, FT231X, FT234XD
|
* FTDI FT232R, FT232H, FT2232H, FT4232H, FT230X, FT231X, FT234XD
|
||||||
* Prolific PL2303
|
* Prolific PL2303
|
||||||
* Silabs CP2102, CP210*
|
* Silabs CP2102, CP210*
|
||||||
* Qinheng CH340, CH341A, CH9102
|
* Qinheng CH340, CH341A
|
||||||
|
|
||||||
devices implementing the CDC/ACM protocol like
|
some other device specific drivers
|
||||||
* Arduino using ATmega32U4
|
|
||||||
* Digispark using V-USB software USB
|
|
||||||
* BBC micro:bit using ARM mbed DAPLink firmware
|
|
||||||
* ...
|
|
||||||
|
|
||||||
and some device specific drivers:
|
|
||||||
* GsmModem devices, e.g. for Unisoc based Fibocom GSM modems
|
* GsmModem devices, e.g. for Unisoc based Fibocom GSM modems
|
||||||
* Chrome OS CCD (Closed Case Debugging)
|
* Chrome OS CCD (Closed Case Debugging)
|
||||||
|
|
||||||
|
and devices implementing the generic CDC/ACM protocol like
|
||||||
|
* Qinheng CH9102
|
||||||
|
* Microchip MCP2221
|
||||||
|
* Arduino using ATmega32U4
|
||||||
|
* Digispark using V-USB software USB
|
||||||
|
* ...
|
||||||
|
|
||||||
## Help & Discussion
|
## Help & Discussion
|
||||||
|
|
||||||
For common problems, see the [FAQ](https://github.com/mik3y/usb-serial-for-android/wiki/FAQ) wiki page.
|
For common problems, see the [FAQ](https://github.com/mik3y/usb-serial-for-android/wiki/FAQ) wiki page.
|
||||||
|
@ -6,7 +6,7 @@ buildscript {
|
|||||||
google()
|
google()
|
||||||
}
|
}
|
||||||
dependencies {
|
dependencies {
|
||||||
classpath 'com.android.tools.build:gradle:8.4.0'
|
classpath 'com.android.tools.build:gradle:8.9.1'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
|
||||||
|
@ -3,7 +3,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
compileSdkVersion 34
|
compileSdkVersion 35
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility JavaVersion.VERSION_1_8
|
sourceCompatibility JavaVersion.VERSION_1_8
|
||||||
@ -12,7 +12,7 @@ android {
|
|||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
minSdkVersion 17
|
minSdkVersion 17
|
||||||
targetSdkVersion 34
|
targetSdkVersion 35
|
||||||
vectorDrawables.useSupportLibrary = true
|
vectorDrawables.useSupportLibrary = true
|
||||||
|
|
||||||
missingDimensionStrategy 'device', 'anyDevice'
|
missingDimensionStrategy 'device', 'anyDevice'
|
||||||
@ -28,6 +28,6 @@ android {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation project(':usbSerialForAndroid')
|
implementation project(':usbSerialForAndroid')
|
||||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
implementation 'androidx.appcompat:appcompat:1.6.1' // later versions have minsdk 21
|
||||||
implementation 'com.google.android.material:material:1.11.0'
|
implementation 'com.google.android.material:material:1.11.0' // later versions have minsdk 19
|
||||||
}
|
}
|
||||||
|
@ -214,7 +214,7 @@ public class TerminalFragment extends Fragment implements SerialInputOutputManag
|
|||||||
status("connection failed: no driver for device");
|
status("connection failed: no driver for device");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(driver.getPorts().size() < portNum) {
|
if(portNum >= driver.getPorts().size()) {
|
||||||
status("connection failed: not enough ports at device");
|
status("connection failed: not enough ports at device");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -4,11 +4,11 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
compileSdkVersion 34
|
compileSdkVersion 35
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
minSdkVersion 17
|
minSdkVersion 17
|
||||||
targetSdkVersion 34
|
targetSdkVersion 35
|
||||||
consumerProguardFiles 'proguard-rules.pro'
|
consumerProguardFiles 'proguard-rules.pro'
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
@ -31,12 +31,13 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation "androidx.annotation:annotation:1.8.0"
|
implementation "androidx.annotation:annotation:1.9.1"
|
||||||
testImplementation 'junit:junit:4.13.2'
|
testImplementation 'junit:junit:4.13.2'
|
||||||
testImplementation 'org.mockito:mockito-core:5.12.0'
|
testImplementation 'org.mockito:mockito-core:5.15.2'
|
||||||
androidTestImplementation 'androidx.test:core:1.5.0'
|
androidTestImplementation 'androidx.appcompat:appcompat:1.6.1' // later versions have minsdk 21
|
||||||
androidTestImplementation 'androidx.test:runner:1.5.2'
|
androidTestImplementation 'androidx.test:core:1.5.0' // later versions have minsdk 19
|
||||||
androidTestImplementation 'commons-net:commons-net:3.10.0'
|
androidTestImplementation 'androidx.test:runner:1.5.2' // later versions have minsdk 19
|
||||||
|
androidTestImplementation 'commons-net:commons-net:3.9.0' // later versions fail on old Android devices with missing java.time.Duration class
|
||||||
androidTestImplementation 'org.apache.commons:commons-lang3:3.14.0'
|
androidTestImplementation 'org.apache.commons:commons-lang3:3.14.0'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,7 +8,7 @@ android {
|
|||||||
// Used as fallback in usbSerialExample/build.gradle -> missingDimensionStrategy, but not for coverage report
|
// Used as fallback in usbSerialExample/build.gradle -> missingDimensionStrategy, but not for coverage report
|
||||||
dimension 'device'
|
dimension 'device'
|
||||||
}
|
}
|
||||||
arduino {
|
mcp2221 {
|
||||||
dimension 'device'
|
dimension 'device'
|
||||||
testInstrumentationRunnerArguments = ['test_device_driver': 'CdcAcm']
|
testInstrumentationRunnerArguments = ['test_device_driver': 'CdcAcm']
|
||||||
}
|
}
|
||||||
|
@ -645,7 +645,13 @@ public class DeviceTest {
|
|||||||
Thread.sleep(10);
|
Thread.sleep(10);
|
||||||
usb.write(new byte[]{(byte) 0xff});
|
usb.write(new byte[]{(byte) 0xff});
|
||||||
data = telnet.read(2);
|
data = telnet.read(2);
|
||||||
assertThat("19000/7N1", data, equalTo(new byte[]{(byte) 0x80, (byte) 0xff}));
|
if(usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||||
|
// not supported by MCP2221, other CDC devices might support it
|
||||||
|
assertThat("19000/7N1", data, equalTo(new byte[]{(byte) 0x00, (byte) 0xff}));
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
assertThat("19000/7N1", data, equalTo(new byte[]{(byte) 0x80, (byte) 0xff}));
|
||||||
|
}
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
if(!usb.isCp21xxRestrictedPort)
|
if(!usb.isCp21xxRestrictedPort)
|
||||||
throw e;
|
throw e;
|
||||||
@ -718,18 +724,17 @@ public class DeviceTest {
|
|||||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_ODD);
|
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_ODD);
|
||||||
usb.write(_8n1);
|
usb.write(_8n1);
|
||||||
data = telnet.read(4);
|
data = telnet.read(4);
|
||||||
assertThat("19200/7O1", data, equalTo(_7o1));
|
|
||||||
|
|
||||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_EVEN);
|
|
||||||
usb.write(_8n1);
|
|
||||||
data = telnet.read(4);
|
|
||||||
assertThat("19200/7E1", data, equalTo(_7e1));
|
|
||||||
|
|
||||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||||
// not supported by arduino_leonardo_bridge.ino, other devices might support it
|
// not supported by MCP2221, other CDC devices might support it
|
||||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
assertThat("19200/8N1", data, equalTo(_8n1));
|
||||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_SPACE);
|
|
||||||
} else {
|
} else {
|
||||||
|
assertThat("19200/7O1", data, equalTo(_7o1));
|
||||||
|
|
||||||
|
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_EVEN);
|
||||||
|
usb.write(_8n1);
|
||||||
|
data = telnet.read(4);
|
||||||
|
assertThat("19200/7E1", data, equalTo(_7e1));
|
||||||
|
|
||||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
||||||
usb.write(_8n1);
|
usb.write(_8n1);
|
||||||
data = telnet.read(4);
|
data = telnet.read(4);
|
||||||
@ -758,19 +763,19 @@ public class DeviceTest {
|
|||||||
data = usb.read(4);
|
data = usb.read(4);
|
||||||
assertThat("19200/7E1", data, equalTo(_7e1));
|
assertThat("19200/7E1", data, equalTo(_7e1));
|
||||||
|
|
||||||
|
telnet.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
||||||
|
telnet.write(_8n1);
|
||||||
|
data = usb.read(4);
|
||||||
|
assertThat("19200/7M1", data, equalTo(_7m1));
|
||||||
|
|
||||||
|
telnet.setParameters(19200, 7, 1, UsbSerialPort.PARITY_SPACE);
|
||||||
|
telnet.write(_8n1);
|
||||||
|
data = usb.read(4);
|
||||||
|
assertThat("19200/7S1", data, equalTo(_7s1));
|
||||||
|
|
||||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||||
// not supported by arduino_leonardo_bridge.ino, other devices might support it
|
; // not supported by MCP2221, other CDC devices might support it
|
||||||
} else {
|
} else {
|
||||||
telnet.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
|
||||||
telnet.write(_8n1);
|
|
||||||
data = usb.read(4);
|
|
||||||
assertThat("19200/7M1", data, equalTo(_7m1));
|
|
||||||
|
|
||||||
telnet.setParameters(19200, 7, 1, UsbSerialPort.PARITY_SPACE);
|
|
||||||
telnet.write(_8n1);
|
|
||||||
data = usb.read(4);
|
|
||||||
assertThat("19200/7S1", data, equalTo(_7s1));
|
|
||||||
|
|
||||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_ODD);
|
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_ODD);
|
||||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.write(_8n1);
|
telnet.write(_8n1);
|
||||||
@ -792,45 +797,44 @@ public class DeviceTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
// shift stopbits into next byte, by using different databits
|
||||||
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_1_5, UsbSerialPort.PARITY_NONE);
|
// a - start bit (0)
|
||||||
// software based bridge in arduino_leonardo_bridge.ino is to slow for real test, other devices might support it
|
// o - stop bit (1)
|
||||||
} else {
|
// d - data bit
|
||||||
// shift stopbits into next byte, by using different databits
|
|
||||||
// a - start bit (0)
|
|
||||||
// o - stop bit (1)
|
|
||||||
// d - data bit
|
|
||||||
|
|
||||||
// out 8N2: addddddd doaddddddddo
|
// out 8N2: addddddd doaddddddddo
|
||||||
// 1000001 0 10001111
|
// 1000001 0 10001111
|
||||||
// in 6N1: addddddo addddddo
|
// in 6N1: addddddo addddddo
|
||||||
// 100000 101000
|
// 100000 101000
|
||||||
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usb.write(new byte[]{(byte)0x41, (byte)0xf1});
|
usb.write(new byte[]{(byte)0x41, (byte)0xf1});
|
||||||
data = telnet.read(2);
|
data = telnet.read(2);
|
||||||
|
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||||
|
// MCP2221 slightly slower, looks like 2 stop bits. could be different for other CDC devices
|
||||||
|
assertThat("19200/8N1", data, equalTo(new byte[]{1, 11}));
|
||||||
|
} else
|
||||||
assertThat("19200/8N1", data, equalTo(new byte[]{1, 5}));
|
assertThat("19200/8N1", data, equalTo(new byte[]{1, 5}));
|
||||||
|
|
||||||
// out 8N2: addddddd dooaddddddddoo
|
// out 8N2: addddddd dooaddddddddoo
|
||||||
// 1000001 0 10011111
|
// 1000001 0 10011111
|
||||||
// in 6N1: addddddo addddddo
|
// in 6N1: addddddo addddddo
|
||||||
// 100000 110100
|
// 100000 110100
|
||||||
try {
|
try {
|
||||||
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_2, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_2, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usb.write(new byte[]{(byte) 0x41, (byte) 0xf9});
|
usb.write(new byte[]{(byte) 0x41, (byte) 0xf9});
|
||||||
data = telnet.read(2);
|
data = telnet.read(2);
|
||||||
assertThat("19200/8N1", data, equalTo(new byte[]{1, 11}));
|
assertThat("19200/8N1", data, equalTo(new byte[]{1, 11}));
|
||||||
} catch(UnsupportedOperationException e) {
|
} catch(UnsupportedOperationException e) {
|
||||||
if(!usb.isCp21xxRestrictedPort)
|
if(!usb.isCp21xxRestrictedPort)
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_1_5, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(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(UnsupportedOperationException ignored) {
|
} catch(UnsupportedOperationException ignored) {
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -883,8 +887,6 @@ public class DeviceTest {
|
|||||||
usb.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
int purgeTimeout = 250;
|
int purgeTimeout = 250;
|
||||||
if(usb.serialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
purgeTimeout = 500;
|
|
||||||
purgeWriteBuffer(purgeTimeout);
|
purgeWriteBuffer(purgeTimeout);
|
||||||
|
|
||||||
// determine write buffer size
|
// determine write buffer size
|
||||||
@ -1055,18 +1057,17 @@ public class DeviceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void readBufferSize() throws Exception {
|
public void readBufferSize() throws Exception {
|
||||||
// looks like devices perform USB read with full mReadEndpoint.getMaxPacketSize() size (32, 64, 512)
|
// looks like devices perform USB read with full mReadEndpoint.getMaxPacketSize() size (16, 32, 64, 512)
|
||||||
// if the buffer is smaller than the received result, it is silently lost
|
// if the buffer is smaller than the received result, it is silently lost
|
||||||
//
|
//
|
||||||
// for buffer > packet size, but not multiple of packet size, the same issue happens, but typically
|
// for buffer > packet size, but not multiple of packet size, the same issue happens, but typically
|
||||||
// only the last (partly filled) packet is lost.
|
// only the last (partly filled) packet is lost.
|
||||||
if(usb.serialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
return; // arduino sends each byte individually, so not testable here
|
|
||||||
byte[] data;
|
byte[] data;
|
||||||
boolean purge = true;
|
boolean purge = true;
|
||||||
|
|
||||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START));
|
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START));
|
||||||
usb.ioManager.setReadBufferSize(8);
|
int len = Math.min(16, usb.serialPort.getReadEndpoint().getMaxPacketSize()/2); // 8 for MCP2221, else 16
|
||||||
|
usb.ioManager.setReadBufferSize(len/2);
|
||||||
usb.ioManager.start();
|
usb.ioManager.start();
|
||||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
@ -1075,13 +1076,15 @@ public class DeviceTest {
|
|||||||
telnet.write("1aaa".getBytes());
|
telnet.write("1aaa".getBytes());
|
||||||
data = usb.read(4);
|
data = usb.read(4);
|
||||||
assertThat(data, equalTo("1aaa".getBytes()));
|
assertThat(data, equalTo("1aaa".getBytes()));
|
||||||
telnet.write(new byte[16]);
|
|
||||||
|
telnet.write(new byte[len]);
|
||||||
try {
|
try {
|
||||||
data = usb.read(16);
|
data = usb.read(len);
|
||||||
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 1)
|
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 1)
|
||||||
assertNotEquals(0, data.length); // can be shorter or full length
|
assertNotEquals(0, data.length); // can be shorter or full length
|
||||||
else if (usb.serialDriver instanceof ProlificSerialDriver)
|
else if (usb.serialDriver instanceof CdcAcmSerialDriver ||
|
||||||
assertTrue("expected > 0 and < 16 byte, got " + data.length, data.length > 0 && data.length < 16);
|
usb.serialDriver instanceof ProlificSerialDriver)
|
||||||
|
assertTrue("expected > 0 and < "+len+" byte, got " + data.length, data.length > 0 && data.length < len);
|
||||||
else // ftdi, ch340, cp2105
|
else // ftdi, ch340, cp2105
|
||||||
assertEquals(0, data.length);
|
assertEquals(0, data.length);
|
||||||
} catch (IOException ignored) {
|
} catch (IOException ignored) {
|
||||||
@ -1121,12 +1124,13 @@ public class DeviceTest {
|
|||||||
telnet.write("2aaa".getBytes());
|
telnet.write("2aaa".getBytes());
|
||||||
data = usb.read(4, 8);
|
data = usb.read(4, 8);
|
||||||
assertThat(data, equalTo("2aaa".getBytes()));
|
assertThat(data, equalTo("2aaa".getBytes()));
|
||||||
telnet.write(new byte[16]);
|
telnet.write(new byte[len]);
|
||||||
data = usb.read(16, 8);
|
data = usb.read(len, len/2);
|
||||||
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 1)
|
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 1)
|
||||||
assertNotEquals(0, data.length); // can be shorter or full length
|
assertNotEquals(0, data.length); // can be shorter or full length
|
||||||
else if (usb.serialDriver instanceof ProlificSerialDriver)
|
else if (usb.serialDriver instanceof CdcAcmSerialDriver ||
|
||||||
assertTrue("sporadic issue! expected > 0 and < 16 byte, got " + data.length, data.length > 0 && data.length < 16);
|
usb.serialDriver instanceof ProlificSerialDriver)
|
||||||
|
assertTrue("sporadic issue! expected > 0 and < "+len+" byte, got " + data.length, data.length > 0 && data.length < len);
|
||||||
else // ftdi, ch340, cp2105
|
else // ftdi, ch340, cp2105
|
||||||
assertEquals(0, data.length);
|
assertEquals(0, data.length);
|
||||||
telnet.write("2ccc".getBytes());
|
telnet.write("2ccc".getBytes());
|
||||||
@ -1146,8 +1150,6 @@ public class DeviceTest {
|
|||||||
@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(usb.serialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
telnet.writeDelay = 10; // arduino_leonardo_bridge.ino sends each byte in own USB packet, which is horribly slow
|
|
||||||
usb.open();
|
usb.open();
|
||||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
@ -1220,8 +1222,6 @@ public class DeviceTest {
|
|||||||
if(usb.serialDriver instanceof Ch34xSerialDriver)
|
if(usb.serialDriver instanceof Ch34xSerialDriver)
|
||||||
baudrate = 38400;
|
baudrate = 38400;
|
||||||
int writeAhead = 5*baudrate/10; // write ahead for another 5 second read
|
int writeAhead = 5*baudrate/10; // write ahead for another 5 second read
|
||||||
if(usb.serialDriver instanceof CdcAcmSerialDriver)
|
|
||||||
writeAhead = 50;
|
|
||||||
|
|
||||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START));
|
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START));
|
||||||
usb.ioManager.setReadTimeout(readTimeout);
|
usb.ioManager.setReadTimeout(readTimeout);
|
||||||
@ -1270,16 +1270,10 @@ public class DeviceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void writeSpeed() throws Exception {
|
public void writeSpeed() throws Exception {
|
||||||
// see logcat for performance results
|
// see logcat for performance results, speed is near physical limit at 11.5k
|
||||||
//
|
|
||||||
// CDC arduino_leonardo_bridge.ino has transfer speed ~ 100 byte/sec
|
|
||||||
// all other devices can get near physical limit:
|
|
||||||
// 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
|
|
||||||
usb.open();
|
usb.open();
|
||||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
boolean longlines = !(usb.serialDriver instanceof CdcAcmSerialDriver);
|
|
||||||
|
|
||||||
int linenr = 0;
|
int linenr = 0;
|
||||||
String line="";
|
String line="";
|
||||||
@ -1292,10 +1286,7 @@ public class DeviceTest {
|
|||||||
for(int seconds=1; seconds<=5; seconds++) {
|
for(int seconds=1; seconds<=5; seconds++) {
|
||||||
next += 1000;
|
next += 1000;
|
||||||
while (System.currentTimeMillis() < next) {
|
while (System.currentTimeMillis() < next) {
|
||||||
if(longlines)
|
line = String.format("%060d,", linenr++);
|
||||||
line = String.format("%060d,", linenr++);
|
|
||||||
else
|
|
||||||
line = String.format("%07d,", linenr++);
|
|
||||||
usb.write(line.getBytes());
|
usb.write(line.getBytes());
|
||||||
expected.append(line);
|
expected.append(line);
|
||||||
data.append(new String(telnet.read(0)));
|
data.append(new String(telnet.read(0)));
|
||||||
@ -1425,19 +1416,16 @@ public class DeviceTest {
|
|||||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
|
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
|
||||||
|
assertEquals(SerialInputOutputManager.State.STOPPED, usb.ioManager.getState());
|
||||||
usb.ioManager.start();
|
usb.ioManager.start();
|
||||||
usb.waitForIoManagerStarted();
|
usb.waitForIoManagerStarted();
|
||||||
assertTrue("iomanager thread", usb.hasIoManagerThread());
|
assertEquals(SerialInputOutputManager.State.RUNNING, usb.ioManager.getState());
|
||||||
|
assertTrue("iomanager thread", usb.hasIoManagerThreads());
|
||||||
try {
|
try {
|
||||||
usb.ioManager.start();
|
usb.ioManager.start();
|
||||||
fail("already running error expected");
|
fail("already running error expected");
|
||||||
} catch (IllegalStateException ignored) {
|
} catch (IllegalStateException ignored) {
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
usb.ioManager.run();
|
|
||||||
fail("already running error expected");
|
|
||||||
} catch (IllegalStateException ignored) {
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
|
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
|
||||||
fail("setThreadPriority IllegalStateException expected");
|
fail("setThreadPriority IllegalStateException expected");
|
||||||
@ -1462,23 +1450,12 @@ public class DeviceTest {
|
|||||||
telnet.write(new byte[1]); // now uses 8 byte buffer
|
telnet.write(new byte[1]); // now uses 8 byte buffer
|
||||||
usb.read(3);
|
usb.read(3);
|
||||||
|
|
||||||
// writebuffer resize
|
// small writebuffer
|
||||||
try {
|
try {
|
||||||
usb.ioManager.writeAsync(new byte[8192]);
|
usb.ioManager.writeAsync(new byte[8192]);
|
||||||
fail("expected BufferOverflowException");
|
fail("expected BufferOverflowException");
|
||||||
} catch (BufferOverflowException ignored) {}
|
} catch (BufferOverflowException ignored) {}
|
||||||
|
|
||||||
usb.ioManager.setWriteBufferSize(16);
|
|
||||||
usb.ioManager.writeAsync("1234567890AB".getBytes());
|
|
||||||
try {
|
|
||||||
usb.ioManager.setWriteBufferSize(8);
|
|
||||||
fail("expected BufferOverflowException");
|
|
||||||
} catch (BufferOverflowException ignored) {}
|
|
||||||
usb.ioManager.setWriteBufferSize(24); // pending date copied to new buffer
|
|
||||||
telnet.write("a".getBytes());
|
|
||||||
assertThat(usb.read(1), equalTo("a".getBytes()));
|
|
||||||
assertThat(telnet.read(12), equalTo("1234567890AB".getBytes()));
|
|
||||||
|
|
||||||
// small readbuffer
|
// small readbuffer
|
||||||
usb.ioManager.setReadBufferSize(8);
|
usb.ioManager.setReadBufferSize(8);
|
||||||
Log.d(TAG, "setReadBufferSize(8)");
|
Log.d(TAG, "setReadBufferSize(8)");
|
||||||
@ -1490,74 +1467,42 @@ public class DeviceTest {
|
|||||||
telnet.write("d".getBytes());
|
telnet.write("d".getBytes());
|
||||||
assertThat(usb.read(1), equalTo("d".getBytes()));
|
assertThat(usb.read(1), equalTo("d".getBytes()));
|
||||||
|
|
||||||
|
SerialInputOutputManager ioManager = usb.ioManager;
|
||||||
|
assertEquals(SerialInputOutputManager.State.RUNNING, usb.ioManager.getState());
|
||||||
usb.close();
|
usb.close();
|
||||||
for (int i = 0; i < 100 && usb.hasIoManagerThread(); i++) {
|
for (int i = 0; i < 100 && usb.hasIoManagerThreads(); i++) {
|
||||||
Thread.sleep(1);
|
Thread.sleep(1);
|
||||||
}
|
}
|
||||||
assertFalse("iomanager thread", usb.hasIoManagerThread());
|
assertFalse("iomanager threads", usb.hasIoManagerThreads());
|
||||||
SerialInputOutputManager.DEBUG = false;
|
assertNull(usb.ioManager);
|
||||||
|
assertEquals(SerialInputOutputManager.State.STOPPED, ioManager.getState());
|
||||||
|
|
||||||
// legacy start
|
usb.open();
|
||||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START)); // creates new IoManager
|
ioManager = usb.ioManager;
|
||||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
assertEquals(SerialInputOutputManager.State.RUNNING, usb.ioManager.getState());
|
||||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.serialPort.close(); // stop before ioManager
|
||||||
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
|
for (int i = 0; i < 100 && usb.hasIoManagerThreads(); i++) {
|
||||||
Executors.newSingleThreadExecutor().submit(usb.ioManager);
|
Thread.sleep(1);
|
||||||
usb.waitForIoManagerStarted();
|
|
||||||
try {
|
|
||||||
usb.ioManager.start();
|
|
||||||
fail("already running error expected");
|
|
||||||
} catch (IllegalStateException ignored) {
|
|
||||||
}
|
}
|
||||||
|
assertFalse("iomanager threads", usb.hasIoManagerThreads());
|
||||||
|
assertEquals(SerialInputOutputManager.State.STOPPED, usb.ioManager.getState());
|
||||||
|
|
||||||
|
SerialInputOutputManager.DEBUG = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void writeAsync() throws Exception {
|
public void writeAsync() throws Exception {
|
||||||
byte[] data, buf = new byte[]{1};
|
byte[] data, buf = new byte[]{1};
|
||||||
|
|
||||||
// w/o timeout: write delayed until something is read
|
// write immediately, without waiting for read
|
||||||
usb.open();
|
usb.open();
|
||||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usb.ioManager.writeAsync(buf);
|
usb.ioManager.writeAsync(buf);
|
||||||
usb.ioManager.writeAsync(buf);
|
usb.ioManager.writeAsync(buf);
|
||||||
data = telnet.read(1);
|
|
||||||
assertEquals(0, data.length);
|
|
||||||
telnet.write(buf);
|
|
||||||
data = usb.read(1);
|
|
||||||
assertEquals(1, data.length);
|
|
||||||
data = telnet.read(2);
|
data = telnet.read(2);
|
||||||
assertEquals(2, data.length);
|
assertEquals(2, data.length);
|
||||||
usb.close();
|
usb.close();
|
||||||
|
|
||||||
// with timeout: write after timeout
|
|
||||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START));
|
|
||||||
usb.ioManager.setReadTimeout(100);
|
|
||||||
usb.ioManager.start();
|
|
||||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
|
||||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
|
||||||
usb.ioManager.writeAsync(buf);
|
|
||||||
usb.ioManager.writeAsync(buf);
|
|
||||||
data = telnet.read(2);
|
|
||||||
assertEquals(2, data.length);
|
|
||||||
usb.ioManager.setReadTimeout(200);
|
|
||||||
|
|
||||||
// with internal SerialTimeoutException
|
|
||||||
TestBuffer tbuf = new TestBuffer(usb.writeBufferSize + 2*usb.writePacketSize);
|
|
||||||
byte[] pbuf1 = new byte[tbuf.buf.length - 4];
|
|
||||||
byte[] pbuf2 = new byte[1];
|
|
||||||
System.arraycopy(tbuf.buf, 0,pbuf1, 0, pbuf1.length);
|
|
||||||
usb.ioManager.setWriteTimeout(20); // tbuf len >= 128, needs 133msec @ 9600 baud
|
|
||||||
usb.setParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
|
||||||
telnet.setParameters(9600, 8, 1, UsbSerialPort.PARITY_NONE);
|
|
||||||
usb.ioManager.writeAsync(pbuf1);
|
|
||||||
for(int i = pbuf1.length; i < tbuf.buf.length; i++) {
|
|
||||||
Thread.sleep(20);
|
|
||||||
pbuf2[0] = tbuf.buf[i];
|
|
||||||
usb.ioManager.writeAsync(pbuf2);
|
|
||||||
}
|
|
||||||
while(!tbuf.testRead(telnet.read(-1)))
|
|
||||||
;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -1622,34 +1567,32 @@ public class DeviceTest {
|
|||||||
}
|
}
|
||||||
Log.i(TAG, "average time per read " + (System.currentTimeMillis()-time)/i + " msec");
|
Log.i(TAG, "average time per read " + (System.currentTimeMillis()-time)/i + " msec");
|
||||||
|
|
||||||
if(!(usb.serialDriver instanceof CdcAcmSerialDriver)) {
|
int diffLen;
|
||||||
int diffLen;
|
usb.close();
|
||||||
usb.close();
|
// no issue with high transfer rate and long read timeout
|
||||||
// no issue with high transfer rate and long read timeout
|
diffLen = readSpeedInt(5, -1, longTimeout);
|
||||||
diffLen = readSpeedInt(5, -1, longTimeout);
|
if(usb.serialDriver instanceof Ch34xSerialDriver && diffLen == -1)
|
||||||
if(usb.serialDriver instanceof Ch34xSerialDriver && diffLen == -1)
|
diffLen = 0; // todo: investigate last packet loss
|
||||||
diffLen = 0; // todo: investigate last packet loss
|
assertEquals(0, diffLen);
|
||||||
assertEquals(0, diffLen);
|
usb.close();
|
||||||
usb.close();
|
// date loss with high transfer rate and short read timeout !!!
|
||||||
// date loss with high transfer rate and short read timeout !!!
|
diffLen = readSpeedInt(5, -1, shortTimeout);
|
||||||
diffLen = readSpeedInt(5, -1, shortTimeout);
|
|
||||||
|
|
||||||
assertNotEquals("sporadic issue!", 0, diffLen);
|
assertNotEquals("sporadic issue!", 0, diffLen);
|
||||||
|
|
||||||
// data loss observed with read timeout up to 200 msec, e.g.
|
// data loss observed with read timeout up to 200 msec, e.g.
|
||||||
// difference at 181 len 64
|
// difference at 181 len 64
|
||||||
// got 000020,0000021,0000030,0000031,0000032,0
|
// got 000020,0000021,0000030,0000031,0000032,0
|
||||||
// expected 000020,0000021,0000022,0000023,0000024,0
|
// expected 000020,0000021,0000022,0000023,0000024,0
|
||||||
// difference at 341 len 128
|
// difference at 341 len 128
|
||||||
// got 000048,0000049,0000066,0000067,0000068,0
|
// got 000048,0000049,0000066,0000067,0000068,0
|
||||||
// expected 000048,0000049,0000050,0000051,0000052,0
|
// expected 000048,0000049,0000050,0000051,0000052,0
|
||||||
// difference at 724 len 704
|
// difference at 724 len 704
|
||||||
// got 0000112,0000113,0000202,0000203,0000204,
|
// got 0000112,0000113,0000202,0000203,0000204,
|
||||||
// expected 0000112,0000113,0000114,0000115,0000116,
|
// expected 0000112,0000113,0000114,0000115,0000116,
|
||||||
// difference at 974 len 8
|
// difference at 974 len 8
|
||||||
// got 00231,0000232,0000234,0000235,0000236,00
|
// got 00231,0000232,0000234,0000235,0000236,00
|
||||||
// expected 00231,0000232,0000233,0000234,0000235,00
|
// expected 00231,0000232,0000233,0000234,0000235,00
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -1854,12 +1797,7 @@ public class DeviceTest {
|
|||||||
assertThat(usb.getControlLine(usb.serialPort::getCD), equalTo(inputLineFalse));
|
assertThat(usb.getControlLine(usb.serialPort::getCD), equalTo(inputLineFalse));
|
||||||
assertThat(usb.getControlLine(usb.serialPort::getRI), equalTo(usb.inputLinesOnlyRtsCts ? Boolean.FALSE : inputLineTrue));
|
assertThat(usb.getControlLine(usb.serialPort::getRI), equalTo(usb.inputLinesOnlyRtsCts ? Boolean.FALSE : inputLineTrue));
|
||||||
telnet.write(data);
|
telnet.write(data);
|
||||||
if(usb.serialDriver instanceof CdcAcmSerialDriver)
|
assertThat(Arrays.toString(data), usb.read(4), equalTo(data));
|
||||||
// arduino: control line feedback as serial_state notification is not implemented.
|
|
||||||
// It does not send w/o RTS or DTR, so these control lines can be partly checked here.
|
|
||||||
assertEquals(0, usb.read().length);
|
|
||||||
else
|
|
||||||
assertThat(Arrays.toString(data), usb.read(4), equalTo(data));
|
|
||||||
usb.write(data);
|
usb.write(data);
|
||||||
assertThat(Arrays.toString(data), telnet.read(4), equalTo(data));
|
assertThat(Arrays.toString(data), telnet.read(4), equalTo(data));
|
||||||
|
|
||||||
@ -1997,6 +1935,22 @@ public class DeviceTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void flowControlBase() throws Exception {
|
||||||
|
usb.open();
|
||||||
|
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
assertEquals(FlowControl.NONE, usb.serialPort.getFlowControl());
|
||||||
|
assertTrue(usb.serialPort.getSupportedFlowControl().contains(FlowControl.NONE));
|
||||||
|
for(FlowControl flowControl : FlowControl.values()) {
|
||||||
|
if(usb.serialPort.getSupportedFlowControl().contains(flowControl)) {
|
||||||
|
usb.serialPort.setFlowControl(flowControl);
|
||||||
|
assertEquals(flowControl, usb.serialPort.getFlowControl());
|
||||||
|
} else {
|
||||||
|
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.setFlowControl(flowControl));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void flowControlXonXoff() throws Exception {
|
public void flowControlXonXoff() throws Exception {
|
||||||
final byte[] off_on = new byte[]{'x',CommonUsbSerialPort.CHAR_XOFF,'y',CommonUsbSerialPort.CHAR_XON,'z'};
|
final byte[] off_on = new byte[]{'x',CommonUsbSerialPort.CHAR_XOFF,'y',CommonUsbSerialPort.CHAR_XON,'z'};
|
||||||
@ -2006,12 +1960,11 @@ public class DeviceTest {
|
|||||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_THREAD, UsbWrapper.OpenCloseFlags.NO_CONTROL_LINE_INIT));
|
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_THREAD, UsbWrapper.OpenCloseFlags.NO_CONTROL_LINE_INIT));
|
||||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
assertEquals(FlowControl.NONE, usb.serialPort.getFlowControl());
|
if(!usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF)) {
|
||||||
if (!usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE) &&
|
|
||||||
!usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF)) {
|
|
||||||
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.setFlowControl(FlowControl.XON_XOFF_INLINE));
|
|
||||||
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.setFlowControl(FlowControl.XON_XOFF));
|
|
||||||
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.getXON());
|
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.getXON());
|
||||||
|
}
|
||||||
|
if (!usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE) &&
|
||||||
|
!usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF)) {
|
||||||
Assume.assumeTrue("flow control not supported", false);
|
Assume.assumeTrue("flow control not supported", false);
|
||||||
}
|
}
|
||||||
if (usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE) &&
|
if (usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE) &&
|
||||||
@ -2020,11 +1973,8 @@ public class DeviceTest {
|
|||||||
}
|
}
|
||||||
if (usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE)) {
|
if (usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE)) {
|
||||||
filter = new XonXoffFilter();
|
filter = new XonXoffFilter();
|
||||||
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.setFlowControl(FlowControl.XON_XOFF));
|
|
||||||
usb.serialPort.setFlowControl(FlowControl.XON_XOFF_INLINE);
|
usb.serialPort.setFlowControl(FlowControl.XON_XOFF_INLINE);
|
||||||
assertEquals(FlowControl.XON_XOFF_INLINE, usb.serialPort.getFlowControl());
|
assertEquals(FlowControl.XON_XOFF_INLINE, usb.serialPort.getFlowControl());
|
||||||
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.getXON());
|
|
||||||
|
|
||||||
assertTrue(filter.getXON());
|
assertTrue(filter.getXON());
|
||||||
assertThat(filter.filter(off_on), equalTo(off_on_filtered));
|
assertThat(filter.filter(off_on), equalTo(off_on_filtered));
|
||||||
assertTrue(filter.getXON());
|
assertTrue(filter.getXON());
|
||||||
@ -2034,7 +1984,6 @@ public class DeviceTest {
|
|||||||
assertTrue(filter.getXON());
|
assertTrue(filter.getXON());
|
||||||
} else {
|
} else {
|
||||||
filter = null;
|
filter = null;
|
||||||
assertThrows(UnsupportedOperationException.class, () -> usb.serialPort.setFlowControl(FlowControl.XON_XOFF_INLINE));
|
|
||||||
usb.serialPort.setFlowControl(FlowControl.XON_XOFF);
|
usb.serialPort.setFlowControl(FlowControl.XON_XOFF);
|
||||||
assertEquals(FlowControl.XON_XOFF, usb.serialPort.getFlowControl());
|
assertEquals(FlowControl.XON_XOFF, usb.serialPort.getFlowControl());
|
||||||
assertTrue(usb.serialPort.getXON());
|
assertTrue(usb.serialPort.getXON());
|
||||||
@ -2203,17 +2152,10 @@ public class DeviceTest {
|
|||||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
|
|
||||||
// early exit, if flow control not supported
|
// early exit, if flow control not supported
|
||||||
|
if (!usb.serialPort.getSupportedFlowControl().contains(flowControl))
|
||||||
|
Assume.assumeTrue("flow control not supported", false);
|
||||||
assertEquals(usb.inputLinesConnected ? EnumSet.of(ControlLine.RI) : EnumSet.noneOf(ControlLine.class), usb.serialPort.getControlLines()); // [1]
|
assertEquals(usb.inputLinesConnected ? EnumSet.of(ControlLine.RI) : EnumSet.noneOf(ControlLine.class), usb.serialPort.getControlLines()); // [1]
|
||||||
assertEquals(FlowControl.NONE, usb.serialPort.getFlowControl());
|
usb.serialPort.setFlowControl(flowControl);
|
||||||
try {
|
|
||||||
usb.serialPort.setFlowControl(flowControl);
|
|
||||||
} catch (UnsupportedOperationException ignored) {
|
|
||||||
if (usb.serialPort.getSupportedFlowControl().contains(flowControl)) {
|
|
||||||
assertTrue("flow control support expected", false);
|
|
||||||
} else {
|
|
||||||
Assume.assumeTrue("flow control not supported", false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assertEquals(flowControl, usb.serialPort.getFlowControl());
|
assertEquals(flowControl, usb.serialPort.getFlowControl());
|
||||||
if (!usb.inputLinesConnected)
|
if (!usb.inputLinesConnected)
|
||||||
Assume.assumeTrue("flow control lines not connected", false);
|
Assume.assumeTrue("flow control lines not connected", false);
|
||||||
@ -2354,20 +2296,25 @@ public class DeviceTest {
|
|||||||
@Test
|
@Test
|
||||||
public void setBreak() throws Exception {
|
public void setBreak() throws Exception {
|
||||||
usb.open();
|
usb.open();
|
||||||
|
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||||
|
// not supported by MCP2221, other CDC devices might support it
|
||||||
|
try {
|
||||||
|
usb.serialPort.setBreak(true);
|
||||||
|
fail("setBreak error expected");
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||||
doReadWrite("");
|
doReadWrite("");
|
||||||
usb.serialPort.setBreak(true);
|
|
||||||
Thread.sleep(100);
|
Thread.sleep(100);
|
||||||
usb.serialPort.setBreak(false);
|
usb.serialPort.setBreak(false);
|
||||||
// RFC2217 has SET_CONTROL + REQ_BREAK_STATE request, but this is not supported by pyserial
|
// RFC2217 has SET_CONTROL + REQ_BREAK_STATE request, but this is not supported by pyserial
|
||||||
// as there is no easy notification on <break> condition. By default break is returned as
|
// as there is no easy notification on <break> condition. By default break is returned as
|
||||||
// 0 byte on Linux, see https://man7.org/linux/man-pages/man3/termios.3.html -> BRKINT
|
// 0 byte on Linux, see https://man7.org/linux/man-pages/man3/termios.3.html -> BRKINT
|
||||||
byte[] data = telnet.read(1);
|
byte[] data = telnet.read(1);
|
||||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
if(usb.isCp21xxRestrictedPort) {
|
||||||
// BREAK forwarding not implemented by arduino_leonardo_bridge.ino
|
|
||||||
assertThat("<break>", data, equalTo(new byte[]{}));
|
|
||||||
} else if(usb.isCp21xxRestrictedPort) {
|
|
||||||
assertThat("<break>", data, equalTo(new byte[]{0x55})); // send the last byte again?
|
assertThat("<break>", data, equalTo(new byte[]{0x55})); // send the last byte again?
|
||||||
} else {
|
} else {
|
||||||
assertThat("<break>", data, equalTo(new byte[]{0}));
|
assertThat("<break>", data, equalTo(new byte[]{0}));
|
||||||
@ -2528,7 +2475,8 @@ public class DeviceTest {
|
|||||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getControlLines);
|
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getControlLines);
|
||||||
assertEquals(EnumSet.of(FlowControl.NONE), wrongSerialPort.getSupportedFlowControl());
|
assertEquals(EnumSet.of(FlowControl.NONE), wrongSerialPort.getSupportedFlowControl());
|
||||||
assertEquals(FlowControl.NONE, wrongSerialPort.getFlowControl());
|
assertEquals(FlowControl.NONE, wrongSerialPort.getFlowControl());
|
||||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setFlowControl(FlowControl.NONE));
|
wrongSerialPort.setFlowControl(FlowControl.NONE);
|
||||||
|
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setFlowControl(FlowControl.RTS_CTS));
|
||||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.purgeHwBuffers(true, true));
|
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.purgeHwBuffers(true, true));
|
||||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setBreak(true));
|
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setBreak(true));
|
||||||
}
|
}
|
||||||
|
@ -33,6 +33,8 @@ import java.util.concurrent.Callable;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import androidx.core.content.ContextCompat;
|
||||||
|
|
||||||
public class UsbWrapper implements SerialInputOutputManager.Listener {
|
public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||||
|
|
||||||
public final static int USB_READ_WAIT = 500;
|
public final static int USB_READ_WAIT = 500;
|
||||||
@ -92,7 +94,7 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
|||||||
intent.setPackage(context.getPackageName());
|
intent.setPackage(context.getPackageName());
|
||||||
PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, intent, flags);
|
PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, intent, flags);
|
||||||
IntentFilter filter = new IntentFilter("com.android.example.USB_PERMISSION");
|
IntentFilter filter = new IntentFilter("com.android.example.USB_PERMISSION");
|
||||||
context.registerReceiver(usbReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
|
ContextCompat.registerReceiver(context, usbReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
|
||||||
usbManager.requestPermission(serialDriver.getDevice(), permissionIntent);
|
usbManager.requestPermission(serialDriver.getDevice(), permissionIntent);
|
||||||
for(int i=0; i<5000; i++) {
|
for(int i=0; i<5000; i++) {
|
||||||
if(granted[0] != null) break;
|
if(granted[0] != null) break;
|
||||||
@ -150,7 +152,7 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
|||||||
if(serialDriver.getDevice().getProductId() == UsbId.FTDI_FT231X)
|
if(serialDriver.getDevice().getProductId() == UsbId.FTDI_FT231X)
|
||||||
writeBufferSize = 512;
|
writeBufferSize = 512;
|
||||||
} else if (serialDriver instanceof CdcAcmSerialDriver) {
|
} else if (serialDriver instanceof CdcAcmSerialDriver) {
|
||||||
writePacketSize = 64; writeBufferSize = 128;
|
writePacketSize = 16; writeBufferSize = 32; // MCP2221 values, other devices might be different
|
||||||
}
|
}
|
||||||
|
|
||||||
readBufferSize = writeBufferSize;
|
readBufferSize = writeBufferSize;
|
||||||
@ -256,12 +258,15 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
|||||||
throw new IOException("IoManager not started");
|
throw new IOException("IoManager not started");
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasIoManagerThread() {
|
public boolean hasIoManagerThreads() {
|
||||||
|
int c = 0;
|
||||||
for (Thread thread : Thread.getAllStackTraces().keySet()) {
|
for (Thread thread : Thread.getAllStackTraces().keySet()) {
|
||||||
if (thread.getName().equals(SerialInputOutputManager.class.getSimpleName()))
|
if (thread.getName().equals(SerialInputOutputManager.class.getSimpleName() + "_read"))
|
||||||
return true;
|
c += 1;
|
||||||
|
if (thread.getName().equals(SerialInputOutputManager.class.getSimpleName() + "_write"))
|
||||||
|
c += 1;
|
||||||
}
|
}
|
||||||
return false;
|
return c == 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
// wait full time
|
// wait full time
|
||||||
|
@ -10,13 +10,13 @@ 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.UsbRequest;
|
import android.hardware.usb.UsbRequest;
|
||||||
|
import android.os.Build;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import com.hoho.android.usbserial.util.MonotonicClock;
|
import com.hoho.android.usbserial.util.MonotonicClock;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.security.InvalidParameterException;
|
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -29,7 +29,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
|||||||
public static boolean DEBUG = false;
|
public static boolean DEBUG = false;
|
||||||
|
|
||||||
private static final String TAG = CommonUsbSerialPort.class.getSimpleName();
|
private static final String TAG = CommonUsbSerialPort.class.getSimpleName();
|
||||||
private static final int MAX_READ_SIZE = 16 * 1024; // = old bulkTransfer limit
|
private static final int MAX_READ_SIZE = 16 * 1024; // = old bulkTransfer limit prior to Android 9
|
||||||
|
|
||||||
protected final UsbDevice mDevice;
|
protected final UsbDevice mDevice;
|
||||||
protected final int mPortNumber;
|
protected final int mPortNumber;
|
||||||
@ -208,7 +208,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
|||||||
// /system/lib64/libandroid_runtime.so (android_hardware_UsbDeviceConnection_request_wait(_JNIEnv*, _jobject*, long)+84)
|
// /system/lib64/libandroid_runtime.so (android_hardware_UsbDeviceConnection_request_wait(_JNIEnv*, _jobject*, long)+84)
|
||||||
// data loss / crashes were observed with timeout up to 200 msec
|
// data loss / crashes were observed with timeout up to 200 msec
|
||||||
long endTime = testConnection ? MonotonicClock.millis() + timeout : 0;
|
long endTime = testConnection ? MonotonicClock.millis() + timeout : 0;
|
||||||
int readMax = Math.min(length, MAX_READ_SIZE);
|
int readMax = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) ? length : Math.min(length, MAX_READ_SIZE);
|
||||||
nread = mConnection.bulkTransfer(mReadEndpoint, dest, readMax, timeout);
|
nread = mConnection.bulkTransfer(mReadEndpoint, dest, readMax, timeout);
|
||||||
// Android error propagation is improvable:
|
// Android error propagation is improvable:
|
||||||
// nread == -1 can be: timeout, connection lost, buffer to small, ???
|
// nread == -1 can be: timeout, connection lost, buffer to small, ???
|
||||||
@ -334,7 +334,10 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
|||||||
public EnumSet<ControlLine> getSupportedControlLines() throws IOException { return EnumSet.noneOf(ControlLine.class); }
|
public EnumSet<ControlLine> getSupportedControlLines() throws IOException { return EnumSet.noneOf(ControlLine.class); }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setFlowControl(FlowControl flowcontrol) throws IOException { throw new UnsupportedOperationException(); }
|
public void setFlowControl(FlowControl flowcontrol) throws IOException {
|
||||||
|
if (flowcontrol != FlowControl.NONE)
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public FlowControl getFlowControl() { return mFlowControl; }
|
public FlowControl getFlowControl() { return mFlowControl; }
|
||||||
|
@ -175,7 +175,7 @@ public interface UsbSerialPort extends Closeable {
|
|||||||
* @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
|
* @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
|
||||||
* {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or {@link #PARITY_SPACE}.
|
* {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or {@link #PARITY_SPACE}.
|
||||||
* @throws IOException on error setting the port parameters
|
* @throws IOException on error setting the port parameters
|
||||||
* @throws UnsupportedOperationException if values are not supported by a specific device
|
* @throws UnsupportedOperationException if not supported or values are not supported by a specific device
|
||||||
*/
|
*/
|
||||||
void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException;
|
void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException;
|
||||||
|
|
||||||
@ -257,6 +257,7 @@ public interface UsbSerialPort extends Closeable {
|
|||||||
*
|
*
|
||||||
* @return EnumSet.contains(...) is {@code true} if set, else {@code false}
|
* @return EnumSet.contains(...) is {@code true} if set, else {@code false}
|
||||||
* @throws IOException if an error occurred during reading
|
* @throws IOException if an error occurred during reading
|
||||||
|
* @throws UnsupportedOperationException if not supported
|
||||||
*/
|
*/
|
||||||
EnumSet<ControlLine> getControlLines() throws IOException;
|
EnumSet<ControlLine> getControlLines() throws IOException;
|
||||||
|
|
||||||
|
@ -9,21 +9,23 @@ package com.hoho.android.usbserial.util;
|
|||||||
import android.os.Process;
|
import android.os.Process;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import com.hoho.android.usbserial.driver.SerialTimeoutException;
|
|
||||||
import com.hoho.android.usbserial.driver.UsbSerialPort;
|
import com.hoho.android.usbserial.driver.UsbSerialPort;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility class which services a {@link UsbSerialPort} in its {@link #run()} method.
|
* Utility class which services a {@link UsbSerialPort} in its {@link #runWrite()} ()} and {@link #runRead()} ()} ()} methods.
|
||||||
*
|
*
|
||||||
* @author mike wakerly (opensource@hoho.com)
|
* @author mike wakerly (opensource@hoho.com)
|
||||||
*/
|
*/
|
||||||
public class SerialInputOutputManager implements Runnable {
|
public class SerialInputOutputManager {
|
||||||
|
|
||||||
public enum State {
|
public enum State {
|
||||||
STOPPED,
|
STOPPED,
|
||||||
|
STARTING,
|
||||||
RUNNING,
|
RUNNING,
|
||||||
STOPPING
|
STOPPING
|
||||||
}
|
}
|
||||||
@ -33,9 +35,6 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
private static final String TAG = SerialInputOutputManager.class.getSimpleName();
|
private static final String TAG = SerialInputOutputManager.class.getSimpleName();
|
||||||
private static final int BUFSIZ = 4096;
|
private static final int BUFSIZ = 4096;
|
||||||
|
|
||||||
/**
|
|
||||||
* default read timeout is infinite, to avoid data loss with bulkTransfer API
|
|
||||||
*/
|
|
||||||
private int mReadTimeout = 0;
|
private int mReadTimeout = 0;
|
||||||
private int mWriteTimeout = 0;
|
private int mWriteTimeout = 0;
|
||||||
|
|
||||||
@ -46,7 +45,8 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
private ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
|
private ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
|
||||||
|
|
||||||
private int mThreadPriority = Process.THREAD_PRIORITY_URGENT_AUDIO;
|
private int mThreadPriority = Process.THREAD_PRIORITY_URGENT_AUDIO;
|
||||||
private State mState = State.STOPPED; // Synchronized by 'this'
|
private final AtomicReference<State> mState = new AtomicReference<>(State.STOPPED);
|
||||||
|
private CountDownLatch mStartuplatch = new CountDownLatch(2);
|
||||||
private Listener mListener; // Synchronized by 'this'
|
private Listener mListener; // Synchronized by 'this'
|
||||||
private final UsbSerialPort mSerialPort;
|
private final UsbSerialPort mSerialPort;
|
||||||
|
|
||||||
@ -57,7 +57,7 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
void onNewData(byte[] data);
|
void onNewData(byte[] data);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when {@link SerialInputOutputManager#run()} aborts due to an error.
|
* Called when {@link SerialInputOutputManager#runRead()} ()} or {@link SerialInputOutputManager#runWrite()} ()} ()} aborts due to an error.
|
||||||
*/
|
*/
|
||||||
void onRunError(Exception e);
|
void onRunError(Exception e);
|
||||||
}
|
}
|
||||||
@ -87,8 +87,9 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
* @param threadPriority see {@link Process#setThreadPriority(int)}
|
* @param threadPriority see {@link Process#setThreadPriority(int)}
|
||||||
* */
|
* */
|
||||||
public void setThreadPriority(int threadPriority) {
|
public void setThreadPriority(int threadPriority) {
|
||||||
if (mState != State.STOPPED)
|
if (!mState.compareAndSet(State.STOPPED, State.STOPPED)) {
|
||||||
throw new IllegalStateException("threadPriority only configurable before SerialInputOutputManager is started");
|
throw new IllegalStateException("threadPriority only configurable before SerialInputOutputManager is started");
|
||||||
|
}
|
||||||
mThreadPriority = threadPriority;
|
mThreadPriority = threadPriority;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,7 +98,7 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
*/
|
*/
|
||||||
public void setReadTimeout(int timeout) {
|
public void setReadTimeout(int timeout) {
|
||||||
// when set if already running, read already blocks and the new value will not become effective now
|
// when set if already running, read already blocks and the new value will not become effective now
|
||||||
if(mReadTimeout == 0 && timeout != 0 && mState != State.STOPPED)
|
if(mReadTimeout == 0 && timeout != 0 && mState.get() != State.STOPPED)
|
||||||
throw new IllegalStateException("readTimeout only configurable before SerialInputOutputManager is started");
|
throw new IllegalStateException("readTimeout only configurable before SerialInputOutputManager is started");
|
||||||
mReadTimeout = timeout;
|
mReadTimeout = timeout;
|
||||||
}
|
}
|
||||||
@ -145,83 +146,152 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* when using writeAsync, it is recommended to use readTimeout != 0,
|
* write data asynchronously
|
||||||
* else the write will be delayed until read data is available
|
|
||||||
*/
|
*/
|
||||||
public void writeAsync(byte[] data) {
|
public void writeAsync(byte[] data) {
|
||||||
synchronized (mWriteBufferLock) {
|
synchronized (mWriteBufferLock) {
|
||||||
mWriteBuffer.put(data);
|
mWriteBuffer.put(data);
|
||||||
|
mWriteBufferLock.notifyAll(); // Notify waiting threads
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* start SerialInputOutputManager in separate thread
|
* start SerialInputOutputManager in separate threads
|
||||||
*/
|
*/
|
||||||
public void start() {
|
public void start() {
|
||||||
if(mState != State.STOPPED)
|
if(mState.compareAndSet(State.STOPPED, State.STARTING)) {
|
||||||
|
mStartuplatch = new CountDownLatch(2);
|
||||||
|
new Thread(this::runRead, this.getClass().getSimpleName() + "_read").start();
|
||||||
|
new Thread(this::runWrite, this.getClass().getSimpleName() + "_write").start();
|
||||||
|
try {
|
||||||
|
mStartuplatch.await();
|
||||||
|
mState.set(State.RUNNING);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
throw new IllegalStateException("already started");
|
throw new IllegalStateException("already started");
|
||||||
new Thread(this, this.getClass().getSimpleName()).start();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* stop SerialInputOutputManager thread
|
* stop SerialInputOutputManager threads
|
||||||
*
|
*
|
||||||
* when using readTimeout == 0 (default), additionally use usbSerialPort.close() to
|
* when using readTimeout == 0 (default), additionally use usbSerialPort.close() to
|
||||||
* interrupt blocking read
|
* interrupt blocking read
|
||||||
*/
|
*/
|
||||||
public synchronized void stop() {
|
public void stop() {
|
||||||
if (getState() == State.RUNNING) {
|
if(mState.compareAndSet(State.RUNNING, State.STOPPING)) {
|
||||||
|
synchronized (mWriteBufferLock) {
|
||||||
|
mWriteBufferLock.notifyAll(); // wake up write thread to check the stop condition
|
||||||
|
}
|
||||||
Log.i(TAG, "Stop requested");
|
Log.i(TAG, "Stop requested");
|
||||||
mState = State.STOPPING;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized State getState() {
|
public State getState() {
|
||||||
return mState;
|
return mState.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Continuously services the read and write buffers until {@link #stop()} is
|
* @return true if the thread is still running
|
||||||
* called, or until a driver exception is raised.
|
|
||||||
*/
|
*/
|
||||||
@Override
|
private boolean isStillRunning() {
|
||||||
public void run() {
|
State state = mState.get();
|
||||||
synchronized (this) {
|
return ((state == State.RUNNING) || (state == State.STARTING))
|
||||||
if (getState() != State.STOPPED) {
|
&& !Thread.currentThread().isInterrupted();
|
||||||
throw new IllegalStateException("Already running");
|
}
|
||||||
}
|
|
||||||
mState = State.RUNNING;
|
/**
|
||||||
}
|
* Notify listener of an error
|
||||||
Log.i(TAG, "Running ...");
|
*
|
||||||
try {
|
* @param e the exception
|
||||||
if(mThreadPriority != Process.THREAD_PRIORITY_DEFAULT)
|
*/
|
||||||
Process.setThreadPriority(mThreadPriority);
|
private void notifyErrorListener(Throwable e) {
|
||||||
while (true) {
|
Listener listener = getListener();
|
||||||
if (getState() != State.RUNNING) {
|
if (listener != null) {
|
||||||
Log.i(TAG, "Stopping mState=" + getState());
|
try {
|
||||||
break;
|
listener.onRunError(e instanceof Exception ? (Exception) e : new Exception(e));
|
||||||
}
|
} catch (Throwable t) {
|
||||||
step();
|
Log.w(TAG, "Exception in onRunError: " + t.getMessage(), t);
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
if(mSerialPort.isOpen()) {
|
|
||||||
Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
|
|
||||||
} else {
|
|
||||||
Log.i(TAG, "Socket closed");
|
|
||||||
}
|
|
||||||
final Listener listener = getListener();
|
|
||||||
if (listener != null) {
|
|
||||||
listener.onRunError(e);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
synchronized (this) {
|
|
||||||
mState = State.STOPPED;
|
|
||||||
Log.i(TAG, "Stopped");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void step() throws IOException {
|
/**
|
||||||
|
* Set the thread priority
|
||||||
|
*/
|
||||||
|
private void setThreadPriority() {
|
||||||
|
if (mThreadPriority != Process.THREAD_PRIORITY_DEFAULT) {
|
||||||
|
Process.setThreadPriority(mThreadPriority);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Continuously services the read buffers until {@link #stop()} is called, or until a driver exception is
|
||||||
|
* raised.
|
||||||
|
*/
|
||||||
|
void runRead() {
|
||||||
|
Log.i(TAG, "runRead running ...");
|
||||||
|
try {
|
||||||
|
setThreadPriority();
|
||||||
|
mStartuplatch.countDown();
|
||||||
|
do {
|
||||||
|
stepRead();
|
||||||
|
} while (isStillRunning());
|
||||||
|
Log.i(TAG, "runRead: Stopping mState=" + getState());
|
||||||
|
} catch (Throwable e) {
|
||||||
|
if (Thread.currentThread().isInterrupted()) {
|
||||||
|
Log.w(TAG, "runRead: interrupted");
|
||||||
|
} else if(mSerialPort.isOpen()) {
|
||||||
|
Log.w(TAG, "runRead ending due to exception: " + e.getMessage(), e);
|
||||||
|
} else {
|
||||||
|
Log.i(TAG, "runRead: Socket closed");
|
||||||
|
}
|
||||||
|
notifyErrorListener(e);
|
||||||
|
} finally {
|
||||||
|
if (mState.compareAndSet(State.RUNNING, State.STOPPING)) {
|
||||||
|
synchronized (mWriteBufferLock) {
|
||||||
|
mWriteBufferLock.notifyAll(); // wake up write thread to check the stop condition
|
||||||
|
}
|
||||||
|
} else if (mState.compareAndSet(State.STOPPING, State.STOPPED)) {
|
||||||
|
Log.i(TAG, "runRead: Stopped mState=" + getState());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Continuously services the write buffers until {@link #stop()} is called, or until a driver exception is
|
||||||
|
* raised.
|
||||||
|
*/
|
||||||
|
void runWrite() {
|
||||||
|
Log.i(TAG, "runWrite running ...");
|
||||||
|
try {
|
||||||
|
setThreadPriority();
|
||||||
|
mStartuplatch.countDown();
|
||||||
|
do {
|
||||||
|
stepWrite();
|
||||||
|
} while (isStillRunning());
|
||||||
|
Log.i(TAG, "runWrite: Stopping mState=" + getState());
|
||||||
|
} catch (Throwable e) {
|
||||||
|
if (Thread.currentThread().isInterrupted()) {
|
||||||
|
Log.w(TAG, "runWrite: interrupted");
|
||||||
|
} else if(mSerialPort.isOpen()) {
|
||||||
|
Log.w(TAG, "runWrite ending due to exception: " + e.getMessage(), e);
|
||||||
|
} else {
|
||||||
|
Log.i(TAG, "runWrite: Socket closed");
|
||||||
|
}
|
||||||
|
notifyErrorListener(e);
|
||||||
|
} finally {
|
||||||
|
if (!mState.compareAndSet(State.RUNNING, State.STOPPING)) {
|
||||||
|
if (mState.compareAndSet(State.STOPPING, State.STOPPED)) {
|
||||||
|
Log.i(TAG, "runWrite: Stopped mState=" + getState());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stepRead() throws IOException {
|
||||||
// Handle incoming data.
|
// Handle incoming data.
|
||||||
byte[] buffer;
|
byte[] buffer;
|
||||||
synchronized (mReadBufferLock) {
|
synchronized (mReadBufferLock) {
|
||||||
@ -239,39 +309,28 @@ public class SerialInputOutputManager implements Runnable {
|
|||||||
listener.onNewData(data);
|
listener.onNewData(data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stepWrite() throws IOException, InterruptedException {
|
||||||
// Handle outgoing data.
|
// Handle outgoing data.
|
||||||
buffer = null;
|
byte[] buffer = null;
|
||||||
synchronized (mWriteBufferLock) {
|
synchronized (mWriteBufferLock) {
|
||||||
len = mWriteBuffer.position();
|
int len = mWriteBuffer.position();
|
||||||
if (len > 0) {
|
if (len > 0) {
|
||||||
buffer = new byte[len];
|
buffer = new byte[len];
|
||||||
mWriteBuffer.rewind();
|
mWriteBuffer.rewind();
|
||||||
mWriteBuffer.get(buffer, 0, len);
|
mWriteBuffer.get(buffer, 0, len);
|
||||||
mWriteBuffer.clear();
|
mWriteBuffer.clear();
|
||||||
|
mWriteBufferLock.notifyAll(); // Notify writeAsync that there is space in the buffer
|
||||||
|
} else {
|
||||||
|
mWriteBufferLock.wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (buffer != null) {
|
if (buffer != null) {
|
||||||
if (DEBUG) {
|
if (DEBUG) {
|
||||||
Log.d(TAG, "Writing data len=" + len);
|
Log.d(TAG, "Writing data len=" + buffer.length);
|
||||||
}
|
|
||||||
try {
|
|
||||||
mSerialPort.write(buffer, mWriteTimeout);
|
|
||||||
} catch (SerialTimeoutException ex) {
|
|
||||||
synchronized (mWriteBufferLock) {
|
|
||||||
byte[] buffer2 = null;
|
|
||||||
int len2 = mWriteBuffer.position();
|
|
||||||
if (len2 > 0) {
|
|
||||||
buffer2 = new byte[len2];
|
|
||||||
mWriteBuffer.rewind();
|
|
||||||
mWriteBuffer.get(buffer2, 0, len2);
|
|
||||||
mWriteBuffer.clear();
|
|
||||||
}
|
|
||||||
mWriteBuffer.put(buffer, ex.bytesTransferred, buffer.length - ex.bytesTransferred);
|
|
||||||
if (buffer2 != null)
|
|
||||||
mWriteBuffer.put(buffer2);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
mSerialPort.write(buffer, mWriteTimeout);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,6 +17,11 @@ public class Log {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static int w(String tag, String msg, Throwable tr) {
|
||||||
|
System.out.println("WARN: " + tag + ": " + msg + " / " + tr.getMessage());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
public static int e(String tag, String msg) {
|
public static int e(String tag, String msg) {
|
||||||
System.out.println("ERROR: " + tag + ": " + msg);
|
System.out.println("ERROR: " + tag + ": " + msg);
|
||||||
return 0;
|
return 0;
|
||||||
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.hoho.android.usbserial.util;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import android.hardware.usb.UsbEndpoint;
|
||||||
|
import android.os.Process;
|
||||||
|
|
||||||
|
import com.hoho.android.usbserial.driver.CommonUsbSerialPort;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SerialInputOutputManagerTest {
|
||||||
|
|
||||||
|
|
||||||
|
// catch all Throwables in onNewData() and onRunError()
|
||||||
|
@Test
|
||||||
|
public void throwable() throws Exception {
|
||||||
|
|
||||||
|
class ExceptionListener implements SerialInputOutputManager.Listener {
|
||||||
|
public Exception e;
|
||||||
|
@Override public void onNewData(byte[] data) { throw new RuntimeException("exception1"); }
|
||||||
|
@Override public void onRunError(Exception e) { this.e = e; throw new RuntimeException("exception2"); }
|
||||||
|
}
|
||||||
|
class ErrorListener implements SerialInputOutputManager.Listener {
|
||||||
|
public Exception e;
|
||||||
|
@Override public void onNewData(byte[] data) { throw new UnknownError("error1"); }
|
||||||
|
@Override public void onRunError(Exception e) { this.e = e; throw new UnknownError("error2");}
|
||||||
|
}
|
||||||
|
|
||||||
|
UsbEndpoint readEndpoint = mock(UsbEndpoint.class);
|
||||||
|
when(readEndpoint.getMaxPacketSize()).thenReturn(16);
|
||||||
|
CommonUsbSerialPort port = mock(CommonUsbSerialPort.class);
|
||||||
|
when(port.getReadEndpoint()).thenReturn(readEndpoint);
|
||||||
|
when(port.read(new byte[16], 0)).thenReturn(1);
|
||||||
|
when(port.isOpen()).thenReturn(true);
|
||||||
|
SerialInputOutputManager manager = new SerialInputOutputManager(port);
|
||||||
|
manager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
|
||||||
|
|
||||||
|
ExceptionListener exceptionListener = new ExceptionListener();
|
||||||
|
manager.setListener(exceptionListener);
|
||||||
|
manager.runRead();
|
||||||
|
assertEquals(RuntimeException.class, exceptionListener.e.getClass());
|
||||||
|
assertEquals("exception1", exceptionListener.e.getMessage());
|
||||||
|
|
||||||
|
ErrorListener errorListener = new ErrorListener();
|
||||||
|
manager.setListener(errorListener);
|
||||||
|
manager.runRead();
|
||||||
|
assertEquals(Exception.class, errorListener.e.getClass());
|
||||||
|
assertEquals("java.lang.UnknownError: error1", errorListener.e.getMessage());
|
||||||
|
assertEquals(UnknownError.class, errorListener.e.getCause().getClass());
|
||||||
|
assertEquals("error1", errorListener.e.getCause().getMessage());
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user