mirror of
https://github.com/mik3y/usb-serial-for-android
synced 2025-06-07 16:06:10 +00:00
Compare commits
31 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
c608aadc59 | ||
|
06faad5622 | ||
|
52042f8c3e | ||
|
068fe80c07 | ||
|
e1018ab31c | ||
|
026355f61e | ||
|
150174573c | ||
|
9911e141a7 | ||
|
2673407f1d | ||
|
8584fe4cb8 | ||
|
0b5950c991 | ||
|
9f93e192ca | ||
|
f5380975ce | ||
|
0a32c3f9e3 | ||
|
88ca3f57c4 | ||
|
843792001f | ||
|
275590027b | ||
|
b6e1833270 | ||
|
b794092c81 | ||
|
b1362416f0 | ||
|
0c0275675f | ||
|
cab862599d | ||
|
2fbceb6cc7 | ||
|
a4ee5c2158 | ||
|
9bc3834eff | ||
|
28506a9bf9 | ||
|
8b9ad7efdf | ||
|
1245293888 | ||
|
26a2f9363e | ||
|
83646d6955 | ||
|
573c7e41ca |
3
.idea/.gitignore
generated
vendored
3
.idea/.gitignore
generated
vendored
@ -3,4 +3,7 @@ codeStyles
|
||||
libraries
|
||||
workspace.xml
|
||||
androidTestResultsUserPreferences.xml
|
||||
appInsightsSettings.xml
|
||||
deploymentTargetDropDown.xml
|
||||
deploymentTargetSelector.xml
|
||||
other.xml
|
||||
|
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"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="17" />
|
||||
<bytecodeTargetLevel target="21" />
|
||||
</component>
|
||||
</project>
|
13
.idea/misc.xml
generated
13
.idea/misc.xml
generated
@ -1,3 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="NullableNotNullManager">
|
||||
@ -5,7 +6,7 @@
|
||||
<option name="myDefaultNotNull" value="androidx.annotation.NonNull" />
|
||||
<option name="myNullables">
|
||||
<value>
|
||||
<list size="15">
|
||||
<list size="18">
|
||||
<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="2" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" />
|
||||
@ -21,12 +22,15 @@
|
||||
<item index="12" class="java.lang.String" itemvalue="org.eclipse.jdt.annotation.Nullable" />
|
||||
<item index="13" class="java.lang.String" itemvalue="io.reactivex.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="16" class="java.lang.String" itemvalue="jakarta.annotation.Nullable" />
|
||||
<item index="17" class="java.lang.String" itemvalue="org.jspecify.annotations.Nullable" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
<option name="myNotNulls">
|
||||
<value>
|
||||
<list size="14">
|
||||
<list size="17">
|
||||
<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="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
|
||||
@ -41,11 +45,14 @@
|
||||
<item index="11" class="java.lang.String" itemvalue="org.eclipse.jdt.annotation.NonNull" />
|
||||
<item index="12" class="java.lang.String" itemvalue="io.reactivex.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="15" class="java.lang.String" itemvalue="org.jspecify.nullness.NonNull" />
|
||||
<item index="16" class="java.lang.String" itemvalue="org.jspecify.annotations.NonNull" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" 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" />
|
||||
</component>
|
||||
<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>
|
32
README.md
32
README.md
@ -45,7 +45,7 @@ If using gradle kotlin use line
|
||||
Add library to dependencies
|
||||
```gradle
|
||||
dependencies {
|
||||
implementation 'com.github.mik3y:usb-serial-for-android:3.7.0'
|
||||
implementation 'com.github.mik3y:usb-serial-for-android:3.9.0'
|
||||
}
|
||||
```
|
||||
|
||||
@ -115,9 +115,10 @@ For a simple example, see
|
||||
[UsbSerialExamples](https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialExamples)
|
||||
folder in this project.
|
||||
|
||||
For a more complete example with background service to stay connected while
|
||||
the app is not visible or rotating, see separate github project
|
||||
[SimpleUsbTerminal](https://github.com/kai-morich/SimpleUsbTerminal).
|
||||
See separate github project [SimpleUsbTerminal](https://github.com/kai-morich/SimpleUsbTerminal)
|
||||
for a more complete example with:
|
||||
* Background service to stay connected while the app is not visible or rotating
|
||||
* Flow control
|
||||
|
||||
## Probing for Unrecognized Devices
|
||||
|
||||
@ -144,8 +145,8 @@ UsbSerialProber prober = new UsbSerialProber(customTable);
|
||||
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,
|
||||
so custom probers are typically not required any more for CDC devices.
|
||||
*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/ACM devices.
|
||||
|
||||
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
|
||||
@ -153,22 +154,23 @@ a compatible UsbDevice.
|
||||
|
||||
## 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
|
||||
* Prolific PL2303
|
||||
* Silabs CP2102, CP210*
|
||||
* Qinheng CH340, CH341A, CH9102
|
||||
* Qinheng CH340, CH341A
|
||||
|
||||
devices implementing the CDC/ACM protocol like
|
||||
* Arduino using ATmega32U4
|
||||
* Digispark using V-USB software USB
|
||||
* BBC micro:bit using ARM mbed DAPLink firmware
|
||||
* ...
|
||||
|
||||
and some device specific drivers:
|
||||
some other device specific drivers
|
||||
* GsmModem devices, e.g. for Unisoc based Fibocom GSM modems
|
||||
* 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
|
||||
|
||||
For common problems, see the [FAQ](https://github.com/mik3y/usb-serial-for-android/wiki/FAQ) wiki page.
|
||||
|
@ -6,7 +6,7 @@ buildscript {
|
||||
google()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.0.2'
|
||||
classpath 'com.android.tools.build:gradle:8.9.1'
|
||||
}
|
||||
}
|
||||
|
||||
|
5
codecov.yml
Normal file
5
codecov.yml
Normal file
@ -0,0 +1,5 @@
|
||||
codecov:
|
||||
max_report_age: off
|
||||
require_ci_to_pass: no
|
||||
notify:
|
||||
wait_for_ci: no
|
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
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
|
||||
|
@ -3,7 +3,7 @@ plugins {
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion 33
|
||||
compileSdkVersion 35
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
@ -12,7 +12,7 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 17
|
||||
targetSdkVersion 33
|
||||
targetSdkVersion 35
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
|
||||
missingDimensionStrategy 'device', 'anyDevice'
|
||||
@ -28,6 +28,6 @@ android {
|
||||
|
||||
dependencies {
|
||||
implementation project(':usbSerialForAndroid')
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||
implementation 'com.google.android.material:material:1.9.0'
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1' // later versions have minsdk 21
|
||||
implementation 'com.google.android.material:material:1.11.0' // later versions have minsdk 19
|
||||
}
|
||||
|
@ -28,6 +28,7 @@ import android.widget.ToggleButton;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import com.hoho.android.usbserial.driver.UsbSerialDriver;
|
||||
@ -89,12 +90,22 @@ public class TerminalFragment extends Fragment implements SerialInputOutputManag
|
||||
withIoManager = getArguments().getBoolean("withIoManager");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
ContextCompat.registerReceiver(getActivity(), broadcastReceiver, new IntentFilter(INTENT_ACTION_GRANT_USB), ContextCompat.RECEIVER_NOT_EXPORTED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
getActivity().unregisterReceiver(broadcastReceiver);
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(INTENT_ACTION_GRANT_USB));
|
||||
|
||||
if(usbPermission == UsbPermission.Unknown || usbPermission == UsbPermission.Granted)
|
||||
if(!connected && (usbPermission == UsbPermission.Unknown || usbPermission == UsbPermission.Granted))
|
||||
mainLooper.post(this::connect);
|
||||
}
|
||||
|
||||
@ -104,7 +115,6 @@ public class TerminalFragment extends Fragment implements SerialInputOutputManag
|
||||
status("disconnected");
|
||||
disconnect();
|
||||
}
|
||||
getActivity().unregisterReceiver(broadcastReceiver);
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
@ -204,7 +214,7 @@ public class TerminalFragment extends Fragment implements SerialInputOutputManag
|
||||
status("connection failed: no driver for device");
|
||||
return;
|
||||
}
|
||||
if(driver.getPorts().size() < portNum) {
|
||||
if(portNum >= driver.getPorts().size()) {
|
||||
status("connection failed: not enough ports at device");
|
||||
return;
|
||||
}
|
||||
@ -213,7 +223,9 @@ public class TerminalFragment extends Fragment implements SerialInputOutputManag
|
||||
if(usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(driver.getDevice())) {
|
||||
usbPermission = UsbPermission.Requested;
|
||||
int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_MUTABLE : 0;
|
||||
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(INTENT_ACTION_GRANT_USB), flags);
|
||||
Intent intent = new Intent(INTENT_ACTION_GRANT_USB);
|
||||
intent.setPackage(getActivity().getPackageName());
|
||||
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, flags);
|
||||
usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
|
||||
return;
|
||||
}
|
||||
|
@ -4,16 +4,16 @@ plugins {
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion 33
|
||||
compileSdkVersion 35
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 17
|
||||
targetSdkVersion 33
|
||||
targetSdkVersion 35
|
||||
consumerProguardFiles 'proguard-rules.pro'
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
testInstrumentationRunnerArguments = [ // Raspi Windows LinuxVM ...
|
||||
'rfc2217_server_host': '192.168.0.145',
|
||||
'rfc2217_server_host': '192.168.0.78',
|
||||
'rfc2217_server_nonstandard_baudrates': 'true', // true false false
|
||||
]
|
||||
}
|
||||
@ -31,13 +31,14 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "androidx.annotation:annotation:1.5.0"
|
||||
implementation "androidx.annotation:annotation:1.9.1"
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
testImplementation 'org.mockito:mockito-core:5.4.0'
|
||||
androidTestImplementation 'androidx.test:core:1.5.0'
|
||||
androidTestImplementation 'androidx.test:runner:1.5.2'
|
||||
androidTestImplementation 'commons-net:commons-net:3.9.0'
|
||||
androidTestImplementation 'org.apache.commons:commons-lang3:3.12.0'
|
||||
testImplementation 'org.mockito:mockito-core:5.15.2'
|
||||
androidTestImplementation 'androidx.appcompat:appcompat:1.6.1' // later versions have minsdk 21
|
||||
androidTestImplementation 'androidx.test:core:1.5.0' // later versions have minsdk 19
|
||||
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'
|
||||
}
|
||||
|
||||
// gradle task: publishToMavenLocal
|
||||
@ -50,7 +51,7 @@ project.afterEvaluate {
|
||||
// values used for local maven repo, jitpack uses github release:
|
||||
groupId 'com.github.mik3y'
|
||||
artifactId 'usb-serial-for-android'
|
||||
version '3.5.2beta'
|
||||
version '3.8.0beta'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,13 +2,13 @@
|
||||
apply plugin: 'jacoco'
|
||||
|
||||
android {
|
||||
flavorDimensions 'device'
|
||||
flavorDimensions += 'device'
|
||||
productFlavors {
|
||||
anyDevice {
|
||||
// Used as fallback in usbSerialExample/build.gradle -> missingDimensionStrategy, but not for coverage report
|
||||
dimension 'device'
|
||||
}
|
||||
arduino {
|
||||
mcp2221 {
|
||||
dimension 'device'
|
||||
testInstrumentationRunnerArguments = ['test_device_driver': 'CdcAcm']
|
||||
}
|
||||
@ -18,7 +18,7 @@ android {
|
||||
}
|
||||
cp2102 { // and cp2105 first port
|
||||
dimension 'device'
|
||||
testInstrumentationRunnerArguments = ['test_device_driver': 'Cp21xx']
|
||||
testInstrumentationRunnerArguments = ['test_device_driver': 'Cp21xx', 'test_device_port': '0']
|
||||
}
|
||||
cp2105 { // second port
|
||||
dimension 'device'
|
||||
@ -26,7 +26,7 @@ android {
|
||||
}
|
||||
ft232 { // and ft2232 first port
|
||||
dimension 'device'
|
||||
testInstrumentationRunnerArguments = ['test_device_driver': 'Ftdi']
|
||||
testInstrumentationRunnerArguments = ['test_device_driver': 'Ftdi', 'test_device_port': '0']
|
||||
}
|
||||
ft2232 { // second port
|
||||
dimension 'device'
|
||||
|
@ -40,11 +40,12 @@ import com.hoho.android.usbserial.util.TelnetWrapper;
|
||||
import com.hoho.android.usbserial.util.TestBuffer;
|
||||
import com.hoho.android.usbserial.util.UsbWrapper;
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort.ControlLine;
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort.FlowControl;
|
||||
import com.hoho.android.usbserial.util.XonXoffFilter;
|
||||
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
@ -66,13 +67,13 @@ import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.anyOf;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
@ -81,7 +82,10 @@ import static org.junit.Assert.fail;
|
||||
public class DeviceTest {
|
||||
private final static String TAG = DeviceTest.class.getSimpleName();
|
||||
|
||||
enum FlowControl_OutputLineLocked { FALSE, ON_BUFFER_FULL, TRUE }
|
||||
|
||||
// testInstrumentationRunnerArguments configuration
|
||||
|
||||
private static String rfc2217_server_host;
|
||||
private static int rfc2217_server_port = 2217;
|
||||
private static boolean rfc2217_server_nonstandard_baudrates;
|
||||
@ -105,7 +109,7 @@ public class DeviceTest {
|
||||
rfc2217_server_host = InstrumentationRegistry.getArguments().getString("rfc2217_server_host");
|
||||
rfc2217_server_nonstandard_baudrates = Boolean.valueOf(InstrumentationRegistry.getArguments().getString("rfc2217_server_nonstandard_baudrates"));
|
||||
test_device_driver = InstrumentationRegistry.getArguments().getString("test_device_driver");
|
||||
test_device_port = Integer.valueOf(InstrumentationRegistry.getArguments().getString("test_device_port","0"));
|
||||
test_device_port = Integer.valueOf(InstrumentationRegistry.getArguments().getString("test_device_port","-1"));
|
||||
|
||||
// postpone parts of fixture setup to first test, because exceptions are not reported for @BeforeClass
|
||||
// and test terminates with misleading 'Empty test suite'
|
||||
@ -130,12 +134,16 @@ public class DeviceTest {
|
||||
String driverName = usbSerialDriver.getClass().getSimpleName();
|
||||
assertEquals(test_device_driver+"SerialDriver", driverName);
|
||||
}
|
||||
if (test_device_port == -1) {
|
||||
test_device_port = usbSerialDriver.getPorts().size() - 1;
|
||||
} else {
|
||||
assertTrue( usbSerialDriver.getPorts().size() > test_device_port);
|
||||
}
|
||||
usb = new UsbWrapper(context, usbSerialDriver, test_device_port);
|
||||
usb.setUp();
|
||||
|
||||
Log.i(TAG, "Using USB device "+ usb.serialPort.toString()+" driver="+usb.serialDriver.getClass().getSimpleName());
|
||||
telnet.read(-1); // doesn't look related here, but very often after usb permission dialog the first test failed with telnet garbage
|
||||
telnet.read(-1); // doesn't look necessary here, but very often after usb permission dialog the first test failed with telnet garbage
|
||||
}
|
||||
|
||||
@After
|
||||
@ -213,7 +221,8 @@ public class DeviceTest {
|
||||
telnet.write(buf1);
|
||||
data = usb.read(buf1.length, -1, readWait);
|
||||
assertThat(reason, data, equalTo(buf1)); // includes array content in output
|
||||
//assertArrayEquals("net2usb".getBytes(), data); // only includes array length in output
|
||||
if(usb.isCp21xxRestrictedPort && usb.serialPort.getFlowControl() == FlowControl.XON_XOFF)
|
||||
data = telnet.read(); // discard flow control
|
||||
usb.write(buf2);
|
||||
data = telnet.read(buf2.length, readWait);
|
||||
assertThat(reason, data, equalTo(buf2));
|
||||
@ -236,6 +245,12 @@ public class DeviceTest {
|
||||
|
||||
@Test
|
||||
public void openClose() throws Exception {
|
||||
try {
|
||||
usb.serialPort.open(null);
|
||||
fail("null connection error expected");
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
|
||||
usb.open();
|
||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
@ -320,8 +335,10 @@ public class DeviceTest {
|
||||
try {
|
||||
closer.wait = false;
|
||||
usb.serialPort.read(new byte[256], 2000);
|
||||
|
||||
fail("closed expected");
|
||||
} catch(IOException ex) {
|
||||
assertFalse(usb.serialPort.isOpen());
|
||||
assertEquals("Connection closed", ex.getMessage());
|
||||
}
|
||||
th.join();
|
||||
@ -333,6 +350,7 @@ public class DeviceTest {
|
||||
usb.serialPort.read(new byte[256], 0);
|
||||
fail("closed expected");
|
||||
} catch(IOException ex) {
|
||||
assertFalse(usb.serialPort.isOpen());
|
||||
assertEquals("Connection closed", ex.getMessage());
|
||||
}
|
||||
th.join();
|
||||
@ -627,7 +645,13 @@ public class DeviceTest {
|
||||
Thread.sleep(10);
|
||||
usb.write(new byte[]{(byte) 0xff});
|
||||
data = telnet.read(2);
|
||||
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) {
|
||||
if(!usb.isCp21xxRestrictedPort)
|
||||
throw e;
|
||||
@ -700,6 +724,10 @@ public class DeviceTest {
|
||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_ODD);
|
||||
usb.write(_8n1);
|
||||
data = telnet.read(4);
|
||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||
// not supported by MCP2221, other CDC devices might support it
|
||||
assertThat("19200/8N1", data, equalTo(_8n1));
|
||||
} else {
|
||||
assertThat("19200/7O1", data, equalTo(_7o1));
|
||||
|
||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_EVEN);
|
||||
@ -707,11 +735,6 @@ public class DeviceTest {
|
||||
data = telnet.read(4);
|
||||
assertThat("19200/7E1", data, equalTo(_7e1));
|
||||
|
||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||
// not supported by arduino_leonardo_bridge.ino, other devices might support it
|
||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_SPACE);
|
||||
} else {
|
||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
||||
usb.write(_8n1);
|
||||
data = telnet.read(4);
|
||||
@ -740,9 +763,6 @@ public class DeviceTest {
|
||||
data = usb.read(4);
|
||||
assertThat("19200/7E1", data, equalTo(_7e1));
|
||||
|
||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||
// not supported by arduino_leonardo_bridge.ino, other devices might support it
|
||||
} else {
|
||||
telnet.setParameters(19200, 7, 1, UsbSerialPort.PARITY_MARK);
|
||||
telnet.write(_8n1);
|
||||
data = usb.read(4);
|
||||
@ -753,6 +773,9 @@ public class DeviceTest {
|
||||
data = usb.read(4);
|
||||
assertThat("19200/7S1", data, equalTo(_7s1));
|
||||
|
||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||
; // not supported by MCP2221, other CDC devices might support it
|
||||
} else {
|
||||
usb.setParameters(19200, 7, 1, UsbSerialPort.PARITY_ODD);
|
||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.write(_8n1);
|
||||
@ -774,10 +797,6 @@ public class DeviceTest {
|
||||
}
|
||||
}
|
||||
|
||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||
usb.setParameters(19200, 8, UsbSerialPort.STOPBITS_1_5, UsbSerialPort.PARITY_NONE);
|
||||
// software based bridge in arduino_leonardo_bridge.ino is to slow for real test, other devices might support it
|
||||
} else {
|
||||
// shift stopbits into next byte, by using different databits
|
||||
// a - start bit (0)
|
||||
// o - stop bit (1)
|
||||
@ -791,6 +810,10 @@ public class DeviceTest {
|
||||
telnet.setParameters(19200, 6, 1, UsbSerialPort.PARITY_NONE);
|
||||
usb.write(new byte[]{(byte)0x41, (byte)0xf1});
|
||||
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}));
|
||||
|
||||
// out 8N2: addddddd dooaddddddddoo
|
||||
@ -814,7 +837,6 @@ public class DeviceTest {
|
||||
} catch(UnsupportedOperationException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@ -860,13 +882,11 @@ public class DeviceTest {
|
||||
usb.serialPort.getReadEndpoint().getMaxPacketSize());
|
||||
|
||||
int baudRate = 300;
|
||||
if(usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() > 1)
|
||||
if(usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialPort.getPortNumber() > 0)
|
||||
baudRate = 2400;
|
||||
usb.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.setParameters(baudRate, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
int purgeTimeout = 250;
|
||||
if(usb.serialDriver instanceof CdcAcmSerialDriver)
|
||||
purgeTimeout = 500;
|
||||
purgeWriteBuffer(purgeTimeout);
|
||||
|
||||
// determine write buffer size
|
||||
@ -1037,18 +1057,17 @@ public class DeviceTest {
|
||||
|
||||
@Test
|
||||
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
|
||||
//
|
||||
// for buffer > packet size, but not multiple of packet size, the same issue happens, but typically
|
||||
// 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;
|
||||
boolean purge = true;
|
||||
|
||||
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.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
@ -1056,16 +1075,18 @@ public class DeviceTest {
|
||||
|
||||
telnet.write("1aaa".getBytes());
|
||||
data = usb.read(4);
|
||||
Assert.assertThat(data, equalTo("1aaa".getBytes()));
|
||||
telnet.write(new byte[16]);
|
||||
assertThat(data, equalTo("1aaa".getBytes()));
|
||||
|
||||
telnet.write(new byte[len]);
|
||||
try {
|
||||
data = usb.read(16);
|
||||
data = usb.read(len);
|
||||
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 1)
|
||||
Assert.assertNotEquals(0, data.length); // can be shorter or full length
|
||||
else if (usb.serialDriver instanceof ProlificSerialDriver)
|
||||
Assert.assertTrue("expected > 0 and < 16 byte, got " + data.length, data.length > 0 && data.length < 16);
|
||||
assertNotEquals(0, data.length); // can be shorter or full length
|
||||
else if (usb.serialDriver instanceof CdcAcmSerialDriver ||
|
||||
usb.serialDriver instanceof ProlificSerialDriver)
|
||||
assertTrue("expected > 0 and < "+len+" byte, got " + data.length, data.length > 0 && data.length < len);
|
||||
else // ftdi, ch340, cp2105
|
||||
Assert.assertEquals(0, data.length);
|
||||
assertEquals(0, data.length);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
if (purge) {
|
||||
@ -1102,18 +1123,19 @@ public class DeviceTest {
|
||||
|
||||
telnet.write("2aaa".getBytes());
|
||||
data = usb.read(4, 8);
|
||||
Assert.assertThat(data, equalTo("2aaa".getBytes()));
|
||||
telnet.write(new byte[16]);
|
||||
data = usb.read(16, 8);
|
||||
assertThat(data, equalTo("2aaa".getBytes()));
|
||||
telnet.write(new byte[len]);
|
||||
data = usb.read(len, len/2);
|
||||
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 1)
|
||||
Assert.assertNotEquals(0, data.length); // can be shorter or full length
|
||||
else if (usb.serialDriver instanceof ProlificSerialDriver)
|
||||
Assert.assertTrue("sporadic issue! expected > 0 and < 16 byte, got " + data.length, data.length > 0 && data.length < 16);
|
||||
assertNotEquals(0, data.length); // can be shorter or full length
|
||||
else if (usb.serialDriver instanceof CdcAcmSerialDriver ||
|
||||
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
|
||||
Assert.assertEquals(0, data.length);
|
||||
assertEquals(0, data.length);
|
||||
telnet.write("2ccc".getBytes());
|
||||
data = usb.read(4);
|
||||
// Assert.assertThat(data, equalTo("1ccc".getBytes())); // unpredictable here. typically '2ccc' but sometimes '' or byte[16]
|
||||
// assertThat(data, equalTo("1ccc".getBytes())); // unpredictable here. typically '2ccc' but sometimes '' or byte[16]
|
||||
if(data.length != 4) {
|
||||
if (purge) {
|
||||
usb.serialPort.purgeHwBuffers(true, true);
|
||||
@ -1128,8 +1150,6 @@ public class DeviceTest {
|
||||
@Test
|
||||
// provoke data loss, when data is not read fast enough
|
||||
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.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
@ -1202,8 +1222,6 @@ public class DeviceTest {
|
||||
if(usb.serialDriver instanceof Ch34xSerialDriver)
|
||||
baudrate = 38400;
|
||||
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.ioManager.setReadTimeout(readTimeout);
|
||||
@ -1252,16 +1270,10 @@ public class DeviceTest {
|
||||
|
||||
@Test
|
||||
public void writeSpeed() throws Exception {
|
||||
// see logcat for performance results
|
||||
//
|
||||
// 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
|
||||
// see logcat for performance results, speed is near physical limit at 11.5k
|
||||
usb.open();
|
||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
boolean longlines = !(usb.serialDriver instanceof CdcAcmSerialDriver);
|
||||
|
||||
int linenr = 0;
|
||||
String line="";
|
||||
@ -1274,10 +1286,7 @@ public class DeviceTest {
|
||||
for(int seconds=1; seconds<=5; seconds++) {
|
||||
next += 1000;
|
||||
while (System.currentTimeMillis() < next) {
|
||||
if(longlines)
|
||||
line = String.format("%060d,", linenr++);
|
||||
else
|
||||
line = String.format("%07d,", linenr++);
|
||||
usb.write(line.getBytes());
|
||||
expected.append(line);
|
||||
data.append(new String(telnet.read(0)));
|
||||
@ -1407,19 +1416,16 @@ public class DeviceTest {
|
||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
|
||||
assertEquals(SerialInputOutputManager.State.STOPPED, usb.ioManager.getState());
|
||||
usb.ioManager.start();
|
||||
usb.waitForIoManagerStarted();
|
||||
assertTrue("iomanager thread", usb.hasIoManagerThread());
|
||||
assertEquals(SerialInputOutputManager.State.RUNNING, usb.ioManager.getState());
|
||||
assertTrue("iomanager thread", usb.hasIoManagerThreads());
|
||||
try {
|
||||
usb.ioManager.start();
|
||||
fail("already running error expected");
|
||||
} catch (IllegalStateException ignored) {
|
||||
}
|
||||
try {
|
||||
usb.ioManager.run();
|
||||
fail("already running error expected");
|
||||
} catch (IllegalStateException ignored) {
|
||||
}
|
||||
try {
|
||||
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
|
||||
fail("setThreadPriority IllegalStateException expected");
|
||||
@ -1444,23 +1450,12 @@ public class DeviceTest {
|
||||
telnet.write(new byte[1]); // now uses 8 byte buffer
|
||||
usb.read(3);
|
||||
|
||||
// writebuffer resize
|
||||
// small writebuffer
|
||||
try {
|
||||
usb.ioManager.writeAsync(new byte[8192]);
|
||||
fail("expected BufferOverflowException");
|
||||
} 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
|
||||
usb.ioManager.setReadBufferSize(8);
|
||||
Log.d(TAG, "setReadBufferSize(8)");
|
||||
@ -1472,57 +1467,42 @@ public class DeviceTest {
|
||||
telnet.write("d".getBytes());
|
||||
assertThat(usb.read(1), equalTo("d".getBytes()));
|
||||
|
||||
SerialInputOutputManager ioManager = usb.ioManager;
|
||||
assertEquals(SerialInputOutputManager.State.RUNNING, usb.ioManager.getState());
|
||||
usb.close();
|
||||
for (int i = 0; i < 100 && usb.hasIoManagerThread(); i++) {
|
||||
for (int i = 0; i < 100 && usb.hasIoManagerThreads(); i++) {
|
||||
Thread.sleep(1);
|
||||
}
|
||||
assertFalse("iomanager thread", usb.hasIoManagerThread());
|
||||
SerialInputOutputManager.DEBUG = false;
|
||||
assertFalse("iomanager threads", usb.hasIoManagerThreads());
|
||||
assertNull(usb.ioManager);
|
||||
assertEquals(SerialInputOutputManager.State.STOPPED, ioManager.getState());
|
||||
|
||||
// legacy start
|
||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_START)); // creates new IoManager
|
||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
usb.ioManager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
|
||||
Executors.newSingleThreadExecutor().submit(usb.ioManager);
|
||||
usb.waitForIoManagerStarted();
|
||||
try {
|
||||
usb.ioManager.start();
|
||||
fail("already running error expected");
|
||||
} catch (IllegalStateException ignored) {
|
||||
usb.open();
|
||||
ioManager = usb.ioManager;
|
||||
assertEquals(SerialInputOutputManager.State.RUNNING, usb.ioManager.getState());
|
||||
usb.serialPort.close(); // stop before ioManager
|
||||
for (int i = 0; i < 100 && usb.hasIoManagerThreads(); i++) {
|
||||
Thread.sleep(1);
|
||||
}
|
||||
assertFalse("iomanager threads", usb.hasIoManagerThreads());
|
||||
assertEquals(SerialInputOutputManager.State.STOPPED, usb.ioManager.getState());
|
||||
|
||||
SerialInputOutputManager.DEBUG = false;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeAsync() throws Exception {
|
||||
byte[] data, buf = new byte[]{1};
|
||||
|
||||
// w/o timeout: write delayed until something is read
|
||||
// write immediately, without waiting for read
|
||||
usb.open();
|
||||
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(1);
|
||||
assertEquals(0, data.length);
|
||||
telnet.write(buf);
|
||||
data = usb.read(1);
|
||||
assertEquals(1, data.length);
|
||||
data = telnet.read(2);
|
||||
assertEquals(2, data.length);
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -1566,7 +1546,7 @@ public class DeviceTest {
|
||||
telnet.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
|
||||
int longTimeout = 1000;
|
||||
int shortTimeout = 10;
|
||||
int shortTimeout = 20;
|
||||
time = System.currentTimeMillis();
|
||||
len = usb.serialPort.read(readBuf, shortTimeout);
|
||||
assertEquals(0, len);
|
||||
@ -1587,7 +1567,6 @@ public class DeviceTest {
|
||||
}
|
||||
Log.i(TAG, "average time per read " + (System.currentTimeMillis()-time)/i + " msec");
|
||||
|
||||
if(!(usb.serialDriver instanceof CdcAcmSerialDriver)) {
|
||||
int diffLen;
|
||||
usb.close();
|
||||
// no issue with high transfer rate and long read timeout
|
||||
@ -1615,7 +1594,6 @@ public class DeviceTest {
|
||||
// got 00231,0000232,0000234,0000235,0000236,00
|
||||
// expected 00231,0000232,0000233,0000234,0000235,00
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongDriver() throws Exception {
|
||||
@ -1658,7 +1636,7 @@ public class DeviceTest {
|
||||
}
|
||||
}
|
||||
// FTDI only recovers from Cp21xx control commands with power toggle, so skip this combination!
|
||||
if(!(usb.serialDriver instanceof Cp21xxSerialDriver | usb.serialDriver instanceof FtdiSerialDriver)) {
|
||||
if(!(usb.serialDriver instanceof Cp21xxSerialDriver || usb.serialDriver instanceof FtdiSerialDriver)) {
|
||||
UsbDeviceConnection wrongDeviceConnection = usbManager.openDevice(usb.serialDriver.getDevice());
|
||||
UsbSerialDriver wrongSerialDriver = new Cp21xxSerialDriver(usb.serialDriver.getDevice());
|
||||
UsbSerialPort wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||
@ -1676,7 +1654,8 @@ public class DeviceTest {
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
if(!(usb.serialDriver instanceof FtdiSerialDriver)) {
|
||||
// CP2105 does not recover from FTDI commands
|
||||
if(!((usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() == 2) || usb.serialDriver instanceof FtdiSerialDriver)) {
|
||||
UsbDeviceConnection wrongDeviceConnection = usbManager.openDevice(usb.serialDriver.getDevice());
|
||||
UsbSerialDriver wrongSerialDriver = new FtdiSerialDriver(usb.serialDriver.getDevice());
|
||||
UsbSerialPort wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||
@ -1717,8 +1696,9 @@ public class DeviceTest {
|
||||
wrongSerialPort.open(wrongDeviceConnection);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
assertEquals(usb.serialDriver.getDevice(), wrongSerialDriver.getDevice());
|
||||
assertEquals(wrongSerialDriver, wrongSerialPort.getDriver());
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setParameters(9200, 8, 1, 0));
|
||||
assertEquals(EnumSet.noneOf(ControlLine.class), wrongSerialPort.getSupportedControlLines());
|
||||
try {
|
||||
wrongSerialPort.close();
|
||||
} catch (IOException ignored) {
|
||||
@ -1732,8 +1712,9 @@ public class DeviceTest {
|
||||
wrongSerialPort.open(wrongDeviceConnection);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
assertEquals(usb.serialDriver.getDevice(), wrongSerialDriver.getDevice());
|
||||
assertEquals(wrongSerialDriver, wrongSerialPort.getDriver());
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setParameters(9200, 8, 1, 0));
|
||||
assertEquals(EnumSet.noneOf(ControlLine.class), wrongSerialPort.getSupportedControlLines());
|
||||
try {
|
||||
wrongSerialPort.close();
|
||||
} catch (IOException ignored) {
|
||||
@ -1816,11 +1797,6 @@ public class DeviceTest {
|
||||
assertThat(usb.getControlLine(usb.serialPort::getCD), equalTo(inputLineFalse));
|
||||
assertThat(usb.getControlLine(usb.serialPort::getRI), equalTo(usb.inputLinesOnlyRtsCts ? Boolean.FALSE : inputLineTrue));
|
||||
telnet.write(data);
|
||||
if(usb.serialDriver instanceof CdcAcmSerialDriver)
|
||||
// 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);
|
||||
assertThat(Arrays.toString(data), telnet.read(4), equalTo(data));
|
||||
@ -1959,24 +1935,387 @@ 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
|
||||
public void flowControlXonXoff() throws Exception {
|
||||
final byte[] off_on = new byte[]{'x',CommonUsbSerialPort.CHAR_XOFF,'y',CommonUsbSerialPort.CHAR_XON,'z'};
|
||||
final byte[] off_on_filtered = "xyz".getBytes();
|
||||
final XonXoffFilter filter;
|
||||
|
||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_IOMANAGER_THREAD, UsbWrapper.OpenCloseFlags.NO_CONTROL_LINE_INIT));
|
||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
if(!usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF)) {
|
||||
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);
|
||||
}
|
||||
if (usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE) &&
|
||||
usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF)) {
|
||||
fail("only one of both XON_XOFF variants allowed");
|
||||
}
|
||||
if (usb.serialPort.getSupportedFlowControl().contains(FlowControl.XON_XOFF_INLINE)) {
|
||||
filter = new XonXoffFilter();
|
||||
usb.serialPort.setFlowControl(FlowControl.XON_XOFF_INLINE);
|
||||
assertEquals(FlowControl.XON_XOFF_INLINE, usb.serialPort.getFlowControl());
|
||||
assertTrue(filter.getXON());
|
||||
assertThat(filter.filter(off_on), equalTo(off_on_filtered));
|
||||
assertTrue(filter.getXON());
|
||||
assertThat(filter.filter(new byte[]{CommonUsbSerialPort.CHAR_XOFF}), equalTo(new byte[]{}));
|
||||
assertFalse(filter.getXON());
|
||||
assertThat(filter.filter(new byte[]{CommonUsbSerialPort.CHAR_XON}), equalTo(new byte[]{}));
|
||||
assertTrue(filter.getXON());
|
||||
} else {
|
||||
filter = null;
|
||||
usb.serialPort.setFlowControl(FlowControl.XON_XOFF);
|
||||
assertEquals(FlowControl.XON_XOFF, usb.serialPort.getFlowControl());
|
||||
assertTrue(usb.serialPort.getXON());
|
||||
}
|
||||
|
||||
class TelnetXonXoff {
|
||||
void write(boolean on) throws Exception {
|
||||
byte[] data;
|
||||
int i;
|
||||
if (on) telnet.write(new byte[]{CommonUsbSerialPort.CHAR_XON});
|
||||
else telnet.write(new byte[]{CommonUsbSerialPort.CHAR_XOFF});
|
||||
if (filter != null) {
|
||||
data = usb.read(1);
|
||||
assertEquals(1, data.length);
|
||||
data = filter.filter(data);
|
||||
assertEquals(on, filter.getXON());
|
||||
assertEquals(0, data.length);
|
||||
} else {
|
||||
for(i = 0; i < 20; i++) {
|
||||
if (!usb.serialPort.getXON()) break;
|
||||
Thread.sleep(10);
|
||||
}
|
||||
data = usb.read(-1, 0, 10);
|
||||
assertEquals(0, data.length);
|
||||
assertEquals(on, usb.serialPort.getXON());
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
TelnetXonXoff telnetXonXoff = new TelnetXonXoff();
|
||||
|
||||
byte[] data;
|
||||
int i;
|
||||
int bufferSize;
|
||||
|
||||
try {
|
||||
// fast off + on
|
||||
telnet.write(off_on);
|
||||
data = usb.read();
|
||||
if (filter != null) {
|
||||
assertThat(data, equalTo(off_on));
|
||||
assertTrue(filter.getXON());
|
||||
} else {
|
||||
assertThat(data, equalTo(off_on_filtered));
|
||||
assertTrue(usb.serialPort.getXON());
|
||||
}
|
||||
doReadWrite("");
|
||||
|
||||
// USB write disabled -> send buffer full -> USB write -> SerialTimeoutException
|
||||
telnetXonXoff.write(false);
|
||||
bufferSize = usb.writeBufferSize;
|
||||
if (usb.serialDriver instanceof Cp21xxSerialDriver && usb.serialDriver.getPorts().size() > 1 && usb.serialPort.getPortNumber() == 0)
|
||||
bufferSize -= 64;
|
||||
byte[] wbuf = new byte[bufferSize];
|
||||
usb.write(wbuf);
|
||||
data = telnet.read(-1, 100);
|
||||
assertEquals(0, data.length);
|
||||
try {
|
||||
usb.write(new byte[1]);
|
||||
fail("write error expected when buffer full");
|
||||
} catch (SerialTimeoutException ignored) {
|
||||
}
|
||||
telnetXonXoff.write(true);
|
||||
usb.write(new byte[]{1});
|
||||
data = telnet.read(wbuf.length + 1);
|
||||
assertEquals(wbuf.length + 1, data.length);
|
||||
doReadWrite("");
|
||||
|
||||
// no USB read -> receive buffer full -> XOFF -> USB read -> XON
|
||||
bufferSize = usb.readBufferSize;
|
||||
telnet.write(new byte[bufferSize]);
|
||||
data = telnet.read(1);
|
||||
assertThat(data, equalTo(new byte[]{UsbSerialPort.CHAR_XOFF}));
|
||||
data = usb.read(bufferSize, 2*bufferSize);
|
||||
assertEquals(bufferSize, data.length);
|
||||
data = telnet.read(1);
|
||||
if(usb.isCp21xxRestrictedPort && data.length > 1)
|
||||
data = new byte[]{data[data.length-1]};
|
||||
assertThat(data, equalTo(new byte[]{UsbSerialPort.CHAR_XON}));
|
||||
doReadWrite("");
|
||||
|
||||
// retaining XOFF state over mode change is device specific
|
||||
telnetXonXoff.write(false);
|
||||
usb.serialPort.setFlowControl(FlowControl.NONE);
|
||||
usb.serialPort.setFlowControl(filter != null ? FlowControl.XON_XOFF_INLINE : FlowControl.XON_XOFF);
|
||||
if (usb.serialDriver instanceof ProlificSerialDriver) { // only PL3032 retains XOFF state
|
||||
usb.write(new byte[1]);
|
||||
data = telnet.read(1, 100);
|
||||
assertEquals(0, data.length);
|
||||
telnetXonXoff.write(true);
|
||||
data = telnet.read(1, 100);
|
||||
assertEquals(1, data.length);
|
||||
}
|
||||
doReadWrite("");
|
||||
|
||||
// mode retained over close, retaining XOFF state is device specific
|
||||
telnetXonXoff.write(false);
|
||||
usb.close(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));
|
||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
if (filter != null) {
|
||||
assertEquals(FlowControl.XON_XOFF_INLINE, usb.serialPort.getFlowControl());
|
||||
} else {
|
||||
assertEquals(FlowControl.XON_XOFF, usb.serialPort.getFlowControl());
|
||||
for (i = 0; i < 20; i++) {
|
||||
if (usb.serialPort.getXON()) break;
|
||||
Thread.sleep(10);
|
||||
}
|
||||
assertTrue(usb.serialPort.getXON());
|
||||
}
|
||||
if (usb.serialDriver instanceof ProlificSerialDriver) { // only PL3032 retains XOFF state
|
||||
usb.write(new byte[1]);
|
||||
data = telnet.read(1, 100);
|
||||
assertEquals(0, data.length);
|
||||
telnetXonXoff.write(true);
|
||||
data = telnet.read(1, 100);
|
||||
assertEquals(1, data.length);
|
||||
}
|
||||
doReadWrite("");
|
||||
|
||||
} finally {
|
||||
telnet.write(new byte[]{CommonUsbSerialPort.CHAR_XON});
|
||||
if (filter != null) {
|
||||
usb.read(1);
|
||||
}
|
||||
usb.write(new byte[]{CommonUsbSerialPort.CHAR_XON});
|
||||
telnet.read(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flowControlRtsCts() throws Exception {
|
||||
flowControlHw(FlowControl.RTS_CTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flowControlDtrDsr() throws Exception {
|
||||
flowControlHw(FlowControl.DTR_DSR);
|
||||
}
|
||||
|
||||
private void flowControlHw(FlowControl flowControl) throws Exception {
|
||||
byte[] buf = new byte[]{0x30, 0x31, 0x32};
|
||||
byte[] buf64 = new byte[64];
|
||||
byte[] data;
|
||||
int i;
|
||||
|
||||
int controlLineWait = 3; // msec
|
||||
boolean outputLineReadable = false; // getControlLines returns configured value
|
||||
FlowControl_OutputLineLocked outputLineLocked = FlowControl_OutputLineLocked.FALSE;
|
||||
boolean outputLineSet = false;
|
||||
if(usb.serialDriver instanceof ProlificSerialDriver) {
|
||||
outputLineSet = true; // line set to 'true' on setFlowControl
|
||||
outputLineLocked = FlowControl_OutputLineLocked.TRUE; // setRts/Dtr has no effect
|
||||
}
|
||||
if(usb.serialDriver instanceof Cp21xxSerialDriver) {
|
||||
outputLineSet = true;
|
||||
outputLineLocked = FlowControl_OutputLineLocked.ON_BUFFER_FULL;
|
||||
outputLineReadable = true; // getControlLines returns actual value
|
||||
}
|
||||
if(usb.serialDriver instanceof FtdiSerialDriver) {
|
||||
outputLineLocked = FlowControl_OutputLineLocked.ON_BUFFER_FULL;
|
||||
}
|
||||
|
||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_CONTROL_LINE_INIT, UsbWrapper.OpenCloseFlags.NO_IOMANAGER_THREAD));
|
||||
telnet.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
usb.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
|
||||
// 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]
|
||||
usb.serialPort.setFlowControl(flowControl);
|
||||
assertEquals(flowControl, usb.serialPort.getFlowControl());
|
||||
if (!usb.inputLinesConnected)
|
||||
Assume.assumeTrue("flow control lines not connected", false);
|
||||
|
||||
// test output line state by reading corresponding input line
|
||||
boolean m = flowControl == FlowControl.RTS_CTS;
|
||||
Thread.sleep(controlLineWait); // required by pl2303
|
||||
if(outputLineSet) { // was not set before enabling flow control at [1]
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR)); // actual value
|
||||
assertFalse(m ? usb.serialPort.getRTS() : usb.serialPort.getDTR()); // configured value
|
||||
if(outputLineReadable) {
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.RTS : ControlLine.DTR)); // actual value
|
||||
} else {
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.RTS : ControlLine.DTR)); // configured value
|
||||
}
|
||||
} else {
|
||||
assertTrue(usb.serialPort.getControlLines().contains(ControlLine.RI));
|
||||
}
|
||||
if(m) usb.serialPort.setRTS(true); else usb.serialPort.setDTR(true);
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
if(m) usb.serialPort.setRTS(false); else usb.serialPort.setDTR(false);
|
||||
if(outputLineLocked == FlowControl_OutputLineLocked.TRUE) {
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
} else {
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
}
|
||||
|
||||
// read & write
|
||||
usb.serialPort.setFlowControl(m ? FlowControl.RTS_CTS : FlowControl.DTR_DSR);
|
||||
if(!outputLineSet) {
|
||||
if (m) usb.serialPort.setRTS(true); else usb.serialPort.setDTR(true);
|
||||
}
|
||||
telnet.write(buf);
|
||||
data = usb.read(buf.length, -1, 100);
|
||||
assertThat(data, equalTo(buf));
|
||||
usb.write(buf);
|
||||
data = telnet.read(buf.length, 100);
|
||||
assertThat(data, equalTo(buf));
|
||||
|
||||
// write disabled + continued
|
||||
if(m) usb.serialPort.setDTR(true); else usb.serialPort.setRTS(true);
|
||||
Thread.sleep(controlLineWait);
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
telnet.write(buf);
|
||||
data = usb.read(buf.length, -1, 100);
|
||||
assertThat(data, equalTo(buf));
|
||||
usb.write(buf);
|
||||
data = telnet.read(buf.length, 200); // stopped
|
||||
assertThat(data, equalTo(new byte[0]));
|
||||
|
||||
if(m) usb.serialPort.setDTR(false); else usb.serialPort.setRTS(false);
|
||||
Thread.sleep(controlLineWait);
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
data = telnet.read(buf.length, 100); // continued
|
||||
assertThat(data, equalTo(buf));
|
||||
|
||||
// write disabled -> buffer full -> SerialTimeoutException
|
||||
if(m) usb.serialPort.setDTR(true); else usb.serialPort.setRTS(true);
|
||||
Thread.sleep(controlLineWait);
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
usb.write(buf64);
|
||||
data = telnet.read(buf64.length, 200);
|
||||
assertThat(data, equalTo(new byte[0]));
|
||||
try {
|
||||
for (i = 0; i < 80; i++) {
|
||||
usb.write(buf64);
|
||||
}
|
||||
fail("write error expected when buffer full");
|
||||
} catch(SerialTimeoutException ignored) {
|
||||
}
|
||||
|
||||
long t1 = System.currentTimeMillis();
|
||||
try {
|
||||
usb.serialPort.write(buf64, 200);
|
||||
fail("write error expected when buffer full");
|
||||
} catch(SerialTimeoutException ignored) {
|
||||
long t2 = System.currentTimeMillis();
|
||||
assertTrue("expected IOException after 200msec timeout, got "+(t2-t1)+"msec", t2-t1 >= 200);
|
||||
}
|
||||
|
||||
// continue write
|
||||
if(m) usb.serialPort.setDTR(false); else usb.serialPort.setRTS(false);
|
||||
Thread.sleep(controlLineWait);
|
||||
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
data = telnet.read(buf64.length, 200);
|
||||
Thread.sleep(100); // 64 bytes are free again after 4.4ms
|
||||
usb.write(buf64);
|
||||
|
||||
// no read -> buffer full -> RTS/DTR off
|
||||
class NoRead {
|
||||
void run() throws Exception {
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
int i;
|
||||
for (i = 0; i < 120 && usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR); i++) {
|
||||
telnet.write(buf64);
|
||||
Thread.sleep(controlLineWait);
|
||||
}
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
|
||||
byte[] data = usb.read(-1, i*64, 100);
|
||||
Thread.sleep(controlLineWait);
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
}
|
||||
}
|
||||
|
||||
new NoRead().run();
|
||||
|
||||
// no read -> buffer full -> RTS/DTR off -> output line locked
|
||||
if(outputLineLocked != FlowControl_OutputLineLocked.TRUE) {
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
for(i = 0; i < 120 && usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR); i++) {
|
||||
telnet.write(buf64);
|
||||
Thread.sleep(controlLineWait);
|
||||
}
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
if(m) usb.serialPort.setRTS(true); else usb.serialPort.setDTR(true);
|
||||
Thread.sleep(controlLineWait);
|
||||
if(outputLineLocked == FlowControl_OutputLineLocked.ON_BUFFER_FULL)
|
||||
assertFalse(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
else
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
data = usb.read(-1, i*64, 100);
|
||||
}
|
||||
|
||||
// mode retained over close
|
||||
assertEquals(flowControl, usb.serialPort.getFlowControl());
|
||||
if(m) usb.serialPort.setRTS(true); else usb.serialPort.setDTR(true);
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
usb.close(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_CONTROL_LINE_INIT));
|
||||
usb.open(EnumSet.of(UsbWrapper.OpenCloseFlags.NO_CONTROL_LINE_INIT, UsbWrapper.OpenCloseFlags.NO_IOMANAGER_THREAD));
|
||||
assertEquals(flowControl, usb.serialPort.getFlowControl());
|
||||
assertTrue(m ? usb.serialPort.getRTS() : usb.serialPort.getDTR());
|
||||
assertTrue(usb.serialPort.getControlLines().contains(m ? ControlLine.CTS : ControlLine.DSR));
|
||||
new NoRead().run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBreak() throws Exception {
|
||||
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);
|
||||
usb.setParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
|
||||
doReadWrite("");
|
||||
usb.serialPort.setBreak(true);
|
||||
Thread.sleep(100);
|
||||
usb.serialPort.setBreak(false);
|
||||
// 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
|
||||
// 0 byte on Linux, see https://man7.org/linux/man-pages/man3/termios.3.html -> BRKINT
|
||||
byte[] data = telnet.read(1);
|
||||
if (usb.serialDriver instanceof CdcAcmSerialDriver) {
|
||||
// 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[]{0x26})); // send the last byte again?
|
||||
if(usb.isCp21xxRestrictedPort) {
|
||||
assertThat("<break>", data, equalTo(new byte[]{0x55})); // send the last byte again?
|
||||
} else {
|
||||
assertThat("<break>", data, equalTo(new byte[]{0}));
|
||||
}
|
||||
@ -2082,7 +2421,9 @@ public class DeviceTest {
|
||||
public void commonMethods() throws Exception {
|
||||
String s;
|
||||
assertNotNull(usb.serialPort.getDriver());
|
||||
assertEquals(usb.serialDriver, usb.serialPort.getDriver());
|
||||
assertNotNull(usb.serialPort.getDevice());
|
||||
assertEquals(usb.serialDriver.getDevice(), usb.serialPort.getDevice());
|
||||
assertEquals(test_device_port, usb.serialPort.getPortNumber());
|
||||
s = usb.serialDriver.toString();
|
||||
assertNotEquals(0, s.length());
|
||||
@ -2113,6 +2454,31 @@ public class DeviceTest {
|
||||
usb.serialPort.read(buffer, UsbWrapper.USB_READ_WAIT);
|
||||
fail("read buffer to small expected");
|
||||
} catch(IllegalArgumentException ignored) {}
|
||||
try {
|
||||
byte[] buffer = new byte[1];
|
||||
usb.serialPort.read(buffer, 0, UsbWrapper.USB_READ_WAIT);
|
||||
fail("read length to small expected");
|
||||
} catch(IllegalArgumentException ignored) {}
|
||||
|
||||
// use driver that does not override base class
|
||||
UsbSerialDriver wrongSerialDriver = new ChromeCcdSerialDriver(usb.serialDriver.getDevice());
|
||||
UsbSerialPort wrongSerialPort = wrongSerialDriver.getPorts().get(0);
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getCD);
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getCTS);
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getDSR);
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getDTR);
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setDTR(true));
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getRI);
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getRTS);
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setRTS(true));
|
||||
assertEquals(EnumSet.noneOf(ControlLine.class), wrongSerialPort.getSupportedControlLines());
|
||||
assertThrows(UnsupportedOperationException.class, wrongSerialPort::getControlLines);
|
||||
assertEquals(EnumSet.of(FlowControl.NONE), wrongSerialPort.getSupportedFlowControl());
|
||||
assertEquals(FlowControl.NONE, wrongSerialPort.getFlowControl());
|
||||
wrongSerialPort.setFlowControl(FlowControl.NONE);
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setFlowControl(FlowControl.RTS_CTS));
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.purgeHwBuffers(true, true));
|
||||
assertThrows(UnsupportedOperationException.class, () -> wrongSerialPort.setBreak(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -18,6 +18,7 @@ import com.hoho.android.usbserial.driver.CommonUsbSerialPort;
|
||||
import com.hoho.android.usbserial.driver.Cp21xxSerialDriver;
|
||||
import com.hoho.android.usbserial.driver.FtdiSerialDriver;
|
||||
import com.hoho.android.usbserial.driver.ProlificSerialDriver;
|
||||
import com.hoho.android.usbserial.driver.ProlificSerialPortWrapper;
|
||||
import com.hoho.android.usbserial.driver.UsbId;
|
||||
import com.hoho.android.usbserial.driver.UsbSerialDriver;
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort;
|
||||
@ -32,6 +33,8 @@ import java.util.concurrent.Callable;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
|
||||
public final static int USB_READ_WAIT = 500;
|
||||
@ -62,6 +65,7 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
public boolean inputLinesOnlyRtsCts;
|
||||
public int writePacketSize = -1;
|
||||
public int writeBufferSize = -1;
|
||||
public int readBufferSize = -1;
|
||||
|
||||
public UsbWrapper(Context context, UsbSerialDriver serialDriver, int devicePort) {
|
||||
this.context = context;
|
||||
@ -86,9 +90,11 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
}
|
||||
};
|
||||
int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_MUTABLE : 0;
|
||||
PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent("com.android.example.USB_PERMISSION"), flags);
|
||||
Intent intent = new Intent("com.android.example.USB_PERMISSION");
|
||||
intent.setPackage(context.getPackageName());
|
||||
PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, intent, flags);
|
||||
IntentFilter filter = new IntentFilter("com.android.example.USB_PERMISSION");
|
||||
context.registerReceiver(usbReceiver, filter);
|
||||
ContextCompat.registerReceiver(context, usbReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
|
||||
usbManager.requestPermission(serialDriver.getDevice(), permissionIntent);
|
||||
for(int i=0; i<5000; i++) {
|
||||
if(granted[0] != null) break;
|
||||
@ -143,10 +149,18 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
case 2: writePacketSize = 512; writeBufferSize = 4096; break;
|
||||
case 4: writePacketSize = 512; writeBufferSize = 2048; break;
|
||||
}
|
||||
if(serialDriver.getDevice().getProductId() == UsbId.FTDI_FT231X)
|
||||
writeBufferSize = 512;
|
||||
} else if (serialDriver instanceof CdcAcmSerialDriver) {
|
||||
writePacketSize = 64; writeBufferSize = 128;
|
||||
writePacketSize = 16; writeBufferSize = 32; // MCP2221 values, other devices might be different
|
||||
}
|
||||
|
||||
readBufferSize = writeBufferSize;
|
||||
if (serialDriver instanceof Cp21xxSerialDriver && serialDriver.getPorts().size() == 2) {
|
||||
readBufferSize = 256;
|
||||
} else if (serialDriver instanceof FtdiSerialDriver && serialDriver.getPorts().size() == 1 && serialDriver.getDevice().getProductId() != UsbId.FTDI_FT231X) {
|
||||
readBufferSize = 256;
|
||||
} // PL2303 HXN checked in open()
|
||||
}
|
||||
|
||||
public void tearDown() {
|
||||
@ -175,6 +189,8 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
if(!flags.contains(OpenCloseFlags.NO_CONTROL_LINE_INIT)) {
|
||||
serialPort.setDTR(false);
|
||||
serialPort.setRTS(false);
|
||||
if (serialPort.getFlowControl() != UsbSerialPort.FlowControl.NONE)
|
||||
serialPort.setFlowControl(UsbSerialPort.FlowControl.NONE);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
@ -224,6 +240,10 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
readBuffer.clear();
|
||||
}
|
||||
readError = null;
|
||||
|
||||
if (serialDriver instanceof ProlificSerialDriver && ProlificSerialPortWrapper.isDeviceTypeHxn(serialPort)) {
|
||||
readBufferSize = 768;
|
||||
}
|
||||
}
|
||||
|
||||
public void waitForIoManagerStarted() throws IOException {
|
||||
@ -238,12 +258,15 @@ public class UsbWrapper implements SerialInputOutputManager.Listener {
|
||||
throw new IOException("IoManager not started");
|
||||
}
|
||||
|
||||
public boolean hasIoManagerThread() {
|
||||
public boolean hasIoManagerThreads() {
|
||||
int c = 0;
|
||||
for (Thread thread : Thread.getAllStackTraces().keySet()) {
|
||||
if (thread.getName().equals(SerialInputOutputManager.class.getSimpleName()))
|
||||
return true;
|
||||
if (thread.getName().equals(SerialInputOutputManager.class.getSimpleName() + "_read"))
|
||||
c += 1;
|
||||
if (thread.getName().equals(SerialInputOutputManager.class.getSimpleName() + "_write"))
|
||||
c += 1;
|
||||
}
|
||||
return false;
|
||||
return c == 2;
|
||||
}
|
||||
|
||||
// wait full time
|
||||
|
@ -79,11 +79,6 @@ public class ChromeCcdSerialDriver implements UsbSerialDriver{
|
||||
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
|
||||
return EnumSet.noneOf(ControlLine.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<Integer, int[]> getSupportedDevices() {
|
||||
|
@ -10,6 +10,7 @@ import android.hardware.usb.UsbDevice;
|
||||
import android.hardware.usb.UsbDeviceConnection;
|
||||
import android.hardware.usb.UsbEndpoint;
|
||||
import android.hardware.usb.UsbRequest;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hoho.android.usbserial.util.MonotonicClock;
|
||||
@ -28,16 +29,17 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
public static boolean DEBUG = false;
|
||||
|
||||
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 int mPortNumber;
|
||||
|
||||
// non-null when open()
|
||||
protected UsbDeviceConnection mConnection = null;
|
||||
protected UsbDeviceConnection mConnection;
|
||||
protected UsbEndpoint mReadEndpoint;
|
||||
protected UsbEndpoint mWriteEndpoint;
|
||||
protected UsbRequest mUsbRequest;
|
||||
protected FlowControl mFlowControl = FlowControl.NONE;
|
||||
|
||||
/**
|
||||
* Internal write buffer.
|
||||
@ -117,6 +119,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
throw new IllegalArgumentException("Connection is null");
|
||||
}
|
||||
mConnection = connection;
|
||||
boolean ok = false;
|
||||
try {
|
||||
openInt();
|
||||
if (mReadEndpoint == null || mWriteEndpoint == null) {
|
||||
@ -124,11 +127,13 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
}
|
||||
mUsbRequest = new UsbRequest();
|
||||
mUsbRequest.initialize(mConnection, mReadEndpoint);
|
||||
} catch(Exception e) {
|
||||
ok = true;
|
||||
} finally {
|
||||
if (!ok) {
|
||||
try {
|
||||
close();
|
||||
} catch(Exception ignored) {}
|
||||
throw e;
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -139,10 +144,11 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
if (mConnection == null) {
|
||||
throw new IOException("Already closed");
|
||||
}
|
||||
try {
|
||||
mUsbRequest.cancel();
|
||||
} catch(Exception ignored) {}
|
||||
UsbRequest usbRequest = mUsbRequest;
|
||||
mUsbRequest = null;
|
||||
try {
|
||||
usbRequest.cancel();
|
||||
} catch(Exception ignored) {}
|
||||
try {
|
||||
closeInt();
|
||||
} catch(Exception ignored) {}
|
||||
@ -157,28 +163,40 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
/**
|
||||
* use simple USB request supported by all devices to test if connection is still valid
|
||||
*/
|
||||
protected void testConnection() throws IOException {
|
||||
if(mConnection == null || mUsbRequest == null) {
|
||||
protected void testConnection(boolean full) throws IOException {
|
||||
testConnection(full, "USB get_status request failed");
|
||||
}
|
||||
|
||||
protected void testConnection(boolean full, String msg) throws IOException {
|
||||
if(mUsbRequest == null) {
|
||||
throw new IOException("Connection closed");
|
||||
}
|
||||
if(!full) {
|
||||
return;
|
||||
}
|
||||
byte[] buf = new byte[2];
|
||||
int len = mConnection.controlTransfer(0x80 /*DEVICE*/, 0 /*GET_STATUS*/, 0, 0, buf, buf.length, 200);
|
||||
if(len < 0)
|
||||
throw new IOException("USB get_status request failed");
|
||||
throw new IOException(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(final byte[] dest, final int timeout) throws IOException {
|
||||
return read(dest, timeout, true);
|
||||
if(dest.length == 0) {
|
||||
throw new IllegalArgumentException("Read buffer too small");
|
||||
}
|
||||
return read(dest, dest.length, timeout);
|
||||
}
|
||||
|
||||
protected int read(final byte[] dest, final int timeout, boolean testConnection) throws IOException {
|
||||
if(mConnection == null || mUsbRequest == null) {
|
||||
throw new IOException("Connection closed");
|
||||
}
|
||||
if(dest.length <= 0) {
|
||||
throw new IllegalArgumentException("Read buffer to small");
|
||||
@Override
|
||||
public int read(final byte[] dest, final int length, final int timeout) throws IOException {return read(dest, length, timeout, true);}
|
||||
|
||||
protected int read(final byte[] dest, int length, final int timeout, boolean testConnection) throws IOException {
|
||||
testConnection(false);
|
||||
if(length <= 0) {
|
||||
throw new IllegalArgumentException("Read length too small");
|
||||
}
|
||||
length = Math.min(length, dest.length);
|
||||
final int nread;
|
||||
if (timeout != 0) {
|
||||
// bulkTransfer will cause data loss with short timeout + high baud rates + continuous transfer
|
||||
@ -190,16 +208,16 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
// /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
|
||||
long endTime = testConnection ? MonotonicClock.millis() + timeout : 0;
|
||||
int readMax = Math.min(dest.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);
|
||||
// Android error propagation is improvable:
|
||||
// nread == -1 can be: timeout, connection lost, buffer to small, ???
|
||||
if(nread == -1 && testConnection && MonotonicClock.millis() < endTime)
|
||||
testConnection();
|
||||
if(nread == -1 && testConnection)
|
||||
testConnection(MonotonicClock.millis() < endTime);
|
||||
|
||||
} else {
|
||||
final ByteBuffer buf = ByteBuffer.wrap(dest);
|
||||
if (!mUsbRequest.queue(buf, dest.length)) {
|
||||
final ByteBuffer buf = ByteBuffer.wrap(dest, 0, length);
|
||||
if (!mUsbRequest.queue(buf, length)) {
|
||||
throw new IOException("Queueing USB request failed");
|
||||
}
|
||||
final UsbRequest response = mConnection.requestWait();
|
||||
@ -210,21 +228,23 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
// Android error propagation is improvable:
|
||||
// response != null & nread == 0 can be: connection lost, buffer to small, ???
|
||||
if(nread == 0) {
|
||||
testConnection();
|
||||
testConnection(true);
|
||||
}
|
||||
}
|
||||
return Math.max(nread, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(final byte[] src, final int timeout) throws IOException {
|
||||
int offset = 0;
|
||||
final long endTime = (timeout == 0) ? 0 : (MonotonicClock.millis() + timeout);
|
||||
public void write(byte[] src, int timeout) throws IOException {write(src, src.length, timeout);}
|
||||
|
||||
if(mConnection == null) {
|
||||
throw new IOException("Connection closed");
|
||||
}
|
||||
while (offset < src.length) {
|
||||
@Override
|
||||
public void write(final byte[] src, int length, final int timeout) throws IOException {
|
||||
int offset = 0;
|
||||
long startTime = MonotonicClock.millis();
|
||||
length = Math.min(length, src.length);
|
||||
|
||||
testConnection(false);
|
||||
while (offset < length) {
|
||||
int requestTimeout;
|
||||
final int requestLength;
|
||||
final int actualLength;
|
||||
@ -235,7 +255,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
if (mWriteBuffer == null) {
|
||||
mWriteBuffer = new byte[mWriteEndpoint.getMaxPacketSize()];
|
||||
}
|
||||
requestLength = Math.min(src.length - offset, mWriteBuffer.length);
|
||||
requestLength = Math.min(length - offset, mWriteBuffer.length);
|
||||
if (offset == 0) {
|
||||
writeBuffer = src;
|
||||
} else {
|
||||
@ -246,7 +266,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
if (timeout == 0 || offset == 0) {
|
||||
requestTimeout = timeout;
|
||||
} else {
|
||||
requestTimeout = (int)(endTime - MonotonicClock.millis());
|
||||
requestTimeout = (int)(startTime + timeout - MonotonicClock.millis());
|
||||
if(requestTimeout == 0)
|
||||
requestTimeout = -1;
|
||||
}
|
||||
@ -256,16 +276,19 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
actualLength = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, requestLength, requestTimeout);
|
||||
}
|
||||
}
|
||||
long elapsed = MonotonicClock.millis() - startTime;
|
||||
if (DEBUG) {
|
||||
Log.d(TAG, "Wrote " + actualLength + "/" + requestLength + " offset " + offset + "/" + src.length + " timeout " + requestTimeout);
|
||||
Log.d(TAG, "Wrote " + actualLength + "/" + requestLength + " offset " + offset + "/" + length + " time " + elapsed + "/" + requestTimeout);
|
||||
}
|
||||
if (actualLength <= 0) {
|
||||
if (timeout != 0 && MonotonicClock.millis() >= endTime) {
|
||||
SerialTimeoutException ex = new SerialTimeoutException("Error writing " + requestLength + " bytes at offset " + offset + " of total " + src.length + ", rc=" + actualLength);
|
||||
ex.bytesTransferred = offset;
|
||||
throw ex;
|
||||
String msg = "Error writing " + requestLength + " bytes at offset " + offset + " of total " + src.length + " after " + elapsed + "msec, rc=" + actualLength;
|
||||
if (timeout != 0) {
|
||||
// could be buffer full because: writing to fast, stopped by flow control
|
||||
testConnection(elapsed < timeout, msg);
|
||||
throw new SerialTimeoutException(msg, offset);
|
||||
} else {
|
||||
throw new IOException("Error writing " + requestLength + " bytes at offset " + offset + " of total " + src.length);
|
||||
throw new IOException(msg);
|
||||
|
||||
}
|
||||
}
|
||||
offset += actualLength;
|
||||
@ -274,7 +297,7 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
return mConnection != null;
|
||||
return mUsbRequest != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -308,13 +331,26 @@ public abstract class CommonUsbSerialPort implements UsbSerialPort {
|
||||
public EnumSet<ControlLine> getControlLines() throws IOException { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Override
|
||||
public abstract EnumSet<ControlLine> getSupportedControlLines() throws IOException;
|
||||
public EnumSet<ControlLine> getSupportedControlLines() throws IOException { return EnumSet.noneOf(ControlLine.class); }
|
||||
|
||||
@Override
|
||||
public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
|
||||
public void setFlowControl(FlowControl flowcontrol) throws IOException {
|
||||
if (flowcontrol != FlowControl.NONE)
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FlowControl getFlowControl() { return mFlowControl; }
|
||||
|
||||
@Override
|
||||
public EnumSet<FlowControl> getSupportedFlowControl() { return EnumSet.of(FlowControl.NONE); }
|
||||
|
||||
@Override
|
||||
public boolean getXON() throws IOException { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Override
|
||||
public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Override
|
||||
public void setBreak(boolean value) throws IOException { throw new UnsupportedOperationException(); }
|
||||
|
||||
|
@ -60,9 +60,14 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
private static final int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03;
|
||||
private static final int SILABSER_SET_BREAK_REQUEST_CODE = 0x05;
|
||||
private static final int SILABSER_SET_MHS_REQUEST_CODE = 0x07;
|
||||
private static final int SILABSER_SET_BAUDRATE = 0x1E;
|
||||
private static final int SILABSER_FLUSH_REQUEST_CODE = 0x12;
|
||||
private static final int SILABSER_GET_MDMSTS_REQUEST_CODE = 0x08;
|
||||
private static final int SILABSER_SET_XON_REQUEST_CODE = 0x09;
|
||||
private static final int SILABSER_SET_XOFF_REQUEST_CODE = 0x0A;
|
||||
private static final int SILABSER_GET_COMM_STATUS_REQUEST_CODE = 0x10;
|
||||
private static final int SILABSER_FLUSH_REQUEST_CODE = 0x12;
|
||||
private static final int SILABSER_SET_FLOW_REQUEST_CODE = 0x13;
|
||||
private static final int SILABSER_SET_CHARS_REQUEST_CODE = 0x19;
|
||||
private static final int SILABSER_SET_BAUDRATE_REQUEST_CODE = 0x1E;
|
||||
|
||||
private static final int FLUSH_READ_CODE = 0x0a;
|
||||
private static final int FLUSH_WRITE_CODE = 0x05;
|
||||
@ -84,6 +89,8 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
/*
|
||||
* SILABSER_GET_MDMSTS_REQUEST_CODE
|
||||
*/
|
||||
private static final int STATUS_DTR = 0x01;
|
||||
private static final int STATUS_RTS = 0x02;
|
||||
private static final int STATUS_CTS = 0x10;
|
||||
private static final int STATUS_DSR = 0x20;
|
||||
private static final int STATUS_RI = 0x40;
|
||||
@ -118,7 +125,7 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
byte[] buffer = new byte[1];
|
||||
int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, SILABSER_GET_MDMSTS_REQUEST_CODE, 0,
|
||||
mPortNumber, buffer, buffer.length, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (result != 1) {
|
||||
if (result != buffer.length) {
|
||||
throw new IOException("Control transfer failed: " + SILABSER_GET_MDMSTS_REQUEST_CODE + " / " + 0 + " -> " + result);
|
||||
}
|
||||
return buffer[0];
|
||||
@ -147,6 +154,7 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
|
||||
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
|
||||
setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, (dtr ? DTR_ENABLE : DTR_DISABLE) | (rts ? RTS_ENABLE : RTS_DISABLE));
|
||||
setFlowControl(mFlowControl);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -166,7 +174,7 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
(byte) ((baudRate >> 16) & 0xff),
|
||||
(byte) ((baudRate >> 24) & 0xff)
|
||||
};
|
||||
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
|
||||
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE_REQUEST_CODE,
|
||||
0, mPortNumber, data, 4, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (ret < 0) {
|
||||
throw new IOException("Error setting baud rate");
|
||||
@ -289,9 +297,11 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
public EnumSet<ControlLine> getControlLines() throws IOException {
|
||||
byte status = getStatus();
|
||||
EnumSet<ControlLine> set = EnumSet.noneOf(ControlLine.class);
|
||||
if(rts) set.add(ControlLine.RTS);
|
||||
//if(rts) set.add(ControlLine.RTS); // configured value
|
||||
if((status & STATUS_RTS) != 0) set.add(ControlLine.RTS); // actual value
|
||||
if((status & STATUS_CTS) != 0) set.add(ControlLine.CTS);
|
||||
if(dtr) set.add(ControlLine.DTR);
|
||||
//if(dtr) set.add(ControlLine.DTR); // configured value
|
||||
if((status & STATUS_DTR) != 0) set.add(ControlLine.DTR); // actual value
|
||||
if((status & STATUS_DSR) != 0) set.add(ControlLine.DSR);
|
||||
if((status & STATUS_CD) != 0) set.add(ControlLine.CD);
|
||||
if((status & STATUS_RI) != 0) set.add(ControlLine.RI);
|
||||
@ -303,6 +313,73 @@ public class Cp21xxSerialDriver implements UsbSerialDriver {
|
||||
return EnumSet.allOf(ControlLine.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getXON() throws IOException {
|
||||
byte[] buffer = new byte[0x13];
|
||||
int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, SILABSER_GET_COMM_STATUS_REQUEST_CODE, 0,
|
||||
mPortNumber, buffer, buffer.length, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (result != buffer.length) {
|
||||
throw new IOException("Control transfer failed: " + SILABSER_GET_COMM_STATUS_REQUEST_CODE + " -> " + result);
|
||||
}
|
||||
return (buffer[4] & 8) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* emulate external XON/OFF
|
||||
* @throws IOException
|
||||
*/
|
||||
public void setXON(boolean value) throws IOException {
|
||||
setConfigSingle(value ? SILABSER_SET_XON_REQUEST_CODE : SILABSER_SET_XOFF_REQUEST_CODE, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFlowControl(FlowControl flowControl) throws IOException {
|
||||
byte[] data = new byte[16];
|
||||
if(flowControl == FlowControl.RTS_CTS) {
|
||||
data[4] |= 0b1000_0000; // RTS
|
||||
data[0] |= 0b0000_1000; // CTS
|
||||
} else {
|
||||
if(rts)
|
||||
data[4] |= 0b0100_0000;
|
||||
}
|
||||
if(flowControl == FlowControl.DTR_DSR) {
|
||||
data[0] |= 0b0000_0010; // DTR
|
||||
data[0] |= 0b0001_0000; // DSR
|
||||
} else {
|
||||
if(dtr)
|
||||
data[0] |= 0b0000_0001;
|
||||
}
|
||||
if(flowControl == FlowControl.XON_XOFF) {
|
||||
byte[] chars = new byte[]{0, 0, 0, 0, CHAR_XON, CHAR_XOFF};
|
||||
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_CHARS_REQUEST_CODE,
|
||||
0, mPortNumber, chars, chars.length, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (ret != chars.length) {
|
||||
throw new IOException("Error setting XON/XOFF chars");
|
||||
}
|
||||
data[4] |= 0b0000_0011;
|
||||
data[7] |= 0b1000_0000;
|
||||
data[8] = (byte)128;
|
||||
data[12] = (byte)128;
|
||||
}
|
||||
if(flowControl == FlowControl.XON_XOFF_INLINE) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_FLOW_REQUEST_CODE,
|
||||
0, mPortNumber, data, data.length, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (ret != data.length) {
|
||||
throw new IOException("Error setting flow control");
|
||||
}
|
||||
if(flowControl == FlowControl.XON_XOFF) {
|
||||
setXON(true);
|
||||
}
|
||||
mFlowControl = flowControl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumSet<FlowControl> getSupportedFlowControl() {
|
||||
return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS, FlowControl.DTR_DSR, FlowControl.XON_XOFF);
|
||||
}
|
||||
|
||||
@Override
|
||||
// note: only working on some devices, on other devices ignored w/o error
|
||||
public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
|
||||
|
@ -64,6 +64,7 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
||||
|
||||
private static final int RESET_REQUEST = 0;
|
||||
private static final int MODEM_CONTROL_REQUEST = 1;
|
||||
private static final int SET_FLOW_CONTROL_REQUEST = 2;
|
||||
private static final int SET_BAUD_RATE_REQUEST = 3;
|
||||
private static final int SET_DATA_REQUEST = 4;
|
||||
private static final int GET_MODEM_STATUS_REQUEST = 5;
|
||||
@ -120,6 +121,7 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
||||
if (result != 0) {
|
||||
throw new IOException("Init RTS,DTR failed: result=" + result);
|
||||
}
|
||||
setFlowControl(mFlowControl);
|
||||
|
||||
// mDevice.getVersion() would require API 23
|
||||
byte[] rawDescriptors = mConnection.getRawDescriptors();
|
||||
@ -139,24 +141,37 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(final byte[] dest, final int timeout) throws IOException {
|
||||
public int read(final byte[] dest, final int timeout) throws IOException
|
||||
{
|
||||
if(dest.length <= READ_HEADER_LENGTH) {
|
||||
throw new IllegalArgumentException("Read buffer to small");
|
||||
throw new IllegalArgumentException("Read buffer too small");
|
||||
// could allocate larger buffer, including space for 2 header bytes, but this would
|
||||
// result in buffers not being 64 byte aligned any more, causing data loss at continuous
|
||||
// data transfer at high baud rates when buffers are fully filled.
|
||||
}
|
||||
return read(dest, dest.length, timeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(final byte[] dest, int length, final int timeout) throws IOException {
|
||||
if(length <= READ_HEADER_LENGTH) {
|
||||
throw new IllegalArgumentException("Read length too small");
|
||||
// could allocate larger buffer, including space for 2 header bytes, but this would
|
||||
// result in buffers not being 64 byte aligned any more, causing data loss at continuous
|
||||
// data transfer at high baud rates when buffers are fully filled.
|
||||
}
|
||||
length = Math.min(length, dest.length);
|
||||
int nread;
|
||||
if (timeout != 0) {
|
||||
long endTime = MonotonicClock.millis() + timeout;
|
||||
do {
|
||||
nread = super.read(dest, Math.max(1, (int)(endTime - MonotonicClock.millis())), false);
|
||||
nread = super.read(dest, length, Math.max(1, (int)(endTime - MonotonicClock.millis())), false);
|
||||
} while (nread == READ_HEADER_LENGTH && MonotonicClock.millis() < endTime);
|
||||
if(nread <= 0 && MonotonicClock.millis() < endTime)
|
||||
testConnection();
|
||||
if(nread <= 0)
|
||||
testConnection(MonotonicClock.millis() < endTime);
|
||||
} else {
|
||||
do {
|
||||
nread = super.read(dest, timeout);
|
||||
nread = super.read(dest, length, timeout);
|
||||
} while (nread == READ_HEADER_LENGTH);
|
||||
}
|
||||
return readFilter(dest, nread);
|
||||
@ -290,7 +305,7 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
||||
byte[] data = new byte[2];
|
||||
int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, GET_MODEM_STATUS_REQUEST,
|
||||
0, mPortNumber+1, data, data.length, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (result != 2) {
|
||||
if (result != data.length) {
|
||||
throw new IOException("Get modem status failed: result=" + result);
|
||||
}
|
||||
return data[0];
|
||||
@ -364,6 +379,38 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
||||
return EnumSet.allOf(ControlLine.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFlowControl(FlowControl flowControl) throws IOException {
|
||||
int value = 0;
|
||||
int index = mPortNumber+1;
|
||||
switch (flowControl) {
|
||||
case NONE:
|
||||
break;
|
||||
case RTS_CTS:
|
||||
index |= 0x100;
|
||||
break;
|
||||
case DTR_DSR:
|
||||
index |= 0x200;
|
||||
break;
|
||||
case XON_XOFF_INLINE:
|
||||
value = CHAR_XON + (CHAR_XOFF << 8);
|
||||
index |= 0x400;
|
||||
break;
|
||||
default:
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_FLOW_CONTROL_REQUEST,
|
||||
value, index, null, 0, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (result != 0)
|
||||
throw new IOException("Set flow control failed: result=" + result);
|
||||
mFlowControl = flowControl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumSet<FlowControl> getSupportedFlowControl() {
|
||||
return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS, FlowControl.DTR_DSR, FlowControl.XON_XOFF_INLINE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
|
||||
if (purgeWriteBuffers) {
|
||||
@ -406,7 +453,7 @@ public class FtdiSerialDriver implements UsbSerialDriver {
|
||||
byte[] data = new byte[1];
|
||||
int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, GET_LATENCY_TIMER_REQUEST,
|
||||
0, mPortNumber+1, data, data.length, USB_WRITE_TIMEOUT_MILLIS);
|
||||
if (result != 1) {
|
||||
if (result != data.length) {
|
||||
throw new IOException("Get latency timer failed: result=" + result);
|
||||
}
|
||||
return data[0];
|
||||
|
@ -89,10 +89,6 @@ public class GsmModemSerialDriver implements UsbSerialDriver{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumSet<ControlLine> getSupportedControlLines() throws IOException {
|
||||
return EnumSet.noneOf(ControlLine.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<Integer, int[]> getSupportedDevices() {
|
||||
|
@ -122,7 +122,7 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
private volatile Thread mReadStatusThread = null;
|
||||
private final Object mReadStatusThreadLock = new Object();
|
||||
private boolean mStopReadStatusThread = false;
|
||||
private IOException mReadStatusException = null;
|
||||
private Exception mReadStatusException = null;
|
||||
|
||||
|
||||
public ProlificSerialPort(UsbDevice device, int portNumber) {
|
||||
@ -201,12 +201,12 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
|
||||
private void readStatusThreadFunction() {
|
||||
try {
|
||||
while (!mStopReadStatusThread) {
|
||||
byte[] buffer = new byte[STATUS_BUFFER_SIZE];
|
||||
while (!mStopReadStatusThread) {
|
||||
long endTime = MonotonicClock.millis() + 500;
|
||||
int readBytesCount = mConnection.bulkTransfer(mInterruptEndpoint, buffer, STATUS_BUFFER_SIZE, 500);
|
||||
if(readBytesCount == -1 && MonotonicClock.millis() < endTime)
|
||||
testConnection();
|
||||
if(readBytesCount == -1)
|
||||
testConnection(MonotonicClock.millis() < endTime);
|
||||
if (readBytesCount > 0) {
|
||||
if (readBytesCount != STATUS_BUFFER_SIZE) {
|
||||
throw new IOException("Invalid status notification, expected " + STATUS_BUFFER_SIZE + " bytes, got " + readBytesCount);
|
||||
@ -217,7 +217,8 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
} catch (Exception e) {
|
||||
if (isOpen())
|
||||
mReadStatusException = e;
|
||||
}
|
||||
//Log.d(TAG, "end control line status thread " + mStopReadStatusThread + " " + (mReadStatusException == null ? "-" : mReadStatusException.getMessage()));
|
||||
@ -249,8 +250,8 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
}
|
||||
}
|
||||
|
||||
/* throw and clear an exception which occured in the status read thread */
|
||||
IOException readStatusException = mReadStatusException;
|
||||
/* throw and clear an exception which occurred in the status read thread */
|
||||
Exception readStatusException = mReadStatusException;
|
||||
if (mReadStatusException != null) {
|
||||
mReadStatusException = null;
|
||||
throw new IOException(readStatusException);
|
||||
@ -314,6 +315,7 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
resetDevice();
|
||||
doBlackMagic();
|
||||
setControlLines(mControlLinesValue);
|
||||
setFlowControl(mFlowControl);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -525,7 +527,6 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
setControlLines(newControlLinesValue);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public EnumSet<ControlLine> getControlLines() throws IOException {
|
||||
int status = getStatus();
|
||||
@ -544,6 +545,39 @@ public class ProlificSerialDriver implements UsbSerialDriver {
|
||||
return EnumSet.allOf(ControlLine.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFlowControl(FlowControl flowControl) throws IOException {
|
||||
// vendorOut values from https://www.mail-archive.com/linux-usb@vger.kernel.org/msg110968.html
|
||||
switch (flowControl) {
|
||||
case NONE:
|
||||
if (mDeviceType == DeviceType.DEVICE_TYPE_HXN)
|
||||
vendorOut(0x0a, 0xff, null);
|
||||
else
|
||||
vendorOut(0, 0, null);
|
||||
break;
|
||||
case RTS_CTS:
|
||||
if (mDeviceType == DeviceType.DEVICE_TYPE_HXN)
|
||||
vendorOut(0x0a, 0xfa, null);
|
||||
else
|
||||
vendorOut(0, 0x61, null);
|
||||
break;
|
||||
case XON_XOFF_INLINE:
|
||||
if (mDeviceType == DeviceType.DEVICE_TYPE_HXN)
|
||||
vendorOut(0x0a, 0xee, null);
|
||||
else
|
||||
vendorOut(0, 0xc1, null);
|
||||
break;
|
||||
default:
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
mFlowControl = flowControl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumSet<FlowControl> getSupportedFlowControl() {
|
||||
return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS, FlowControl.XON_XOFF_INLINE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
|
||||
if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) {
|
||||
|
@ -9,7 +9,8 @@ import java.io.InterruptedIOException;
|
||||
* {@see InterruptedIOException#bytesTransferred} may contain bytes transferred
|
||||
*/
|
||||
public class SerialTimeoutException extends InterruptedIOException {
|
||||
public SerialTimeoutException(String s) {
|
||||
public SerialTimeoutException(String s, int bytesTransferred) {
|
||||
super(s);
|
||||
this.bytesTransferred = bytesTransferred;
|
||||
}
|
||||
}
|
||||
|
@ -60,6 +60,15 @@ public interface UsbSerialPort extends Closeable {
|
||||
/** Values for get[Supported]ControlLines() */
|
||||
enum ControlLine { RTS, CTS, DTR, DSR, CD, RI }
|
||||
|
||||
/** Values for (set|get|getSupported)FlowControl() */
|
||||
enum FlowControl { NONE, RTS_CTS, DTR_DSR, XON_XOFF, XON_XOFF_INLINE }
|
||||
|
||||
/** XON character used with flow control XON/XOFF */
|
||||
char CHAR_XON = 17;
|
||||
/** XOFF character used with flow control XON/XOFF */
|
||||
char CHAR_XOFF = 19;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the driver used by this port.
|
||||
*/
|
||||
@ -122,6 +131,17 @@ public interface UsbSerialPort extends Closeable {
|
||||
*/
|
||||
int read(final byte[] dest, final int timeout) throws IOException;
|
||||
|
||||
/**
|
||||
* Reads bytes with specified length into the destination buffer.
|
||||
*
|
||||
* @param dest the destination byte buffer
|
||||
* @param length the maximum length of the data to read
|
||||
* @param timeout the timeout for reading in milliseconds, 0 is infinite
|
||||
* @return the actual number of bytes read
|
||||
* @throws IOException if an error occurred during reading
|
||||
*/
|
||||
int read(final byte[] dest, int length, final int timeout) throws IOException;
|
||||
|
||||
/**
|
||||
* Writes as many bytes as possible from the source buffer.
|
||||
*
|
||||
@ -133,6 +153,18 @@ public interface UsbSerialPort extends Closeable {
|
||||
*/
|
||||
void write(final byte[] src, final int timeout) throws IOException;
|
||||
|
||||
/**
|
||||
* Writes bytes with specified length from the source buffer.
|
||||
*
|
||||
* @param src the source byte buffer
|
||||
* @param length the length of the data to write
|
||||
* @param timeout the timeout for writing in milliseconds, 0 is infinite
|
||||
* @throws SerialTimeoutException if timeout reached before sending all data.
|
||||
* ex.bytesTransferred may contain bytes transferred
|
||||
* @throws IOException if an error occurred during writing
|
||||
*/
|
||||
void write(final byte[] src, int length, final int timeout) throws IOException;
|
||||
|
||||
/**
|
||||
* Sets various serial port parameters.
|
||||
*
|
||||
@ -143,7 +175,7 @@ public interface UsbSerialPort extends Closeable {
|
||||
* @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
|
||||
* {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or {@link #PARITY_SPACE}.
|
||||
* @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;
|
||||
|
||||
@ -225,6 +257,7 @@ public interface UsbSerialPort extends Closeable {
|
||||
*
|
||||
* @return EnumSet.contains(...) is {@code true} if set, else {@code false}
|
||||
* @throws IOException if an error occurred during reading
|
||||
* @throws UnsupportedOperationException if not supported
|
||||
*/
|
||||
EnumSet<ControlLine> getControlLines() throws IOException;
|
||||
|
||||
@ -236,6 +269,36 @@ public interface UsbSerialPort extends Closeable {
|
||||
*/
|
||||
EnumSet<ControlLine> getSupportedControlLines() throws IOException;
|
||||
|
||||
/**
|
||||
* Set flow control mode, if supported
|
||||
* @param flowControl @FlowControl
|
||||
* @throws IOException if an error occurred during writing
|
||||
* @throws UnsupportedOperationException if not supported
|
||||
*/
|
||||
void setFlowControl(FlowControl flowControl) throws IOException;
|
||||
|
||||
/**
|
||||
* Get flow control mode.
|
||||
* @return FlowControl
|
||||
*/
|
||||
FlowControl getFlowControl();
|
||||
|
||||
/**
|
||||
* Get supported flow control modes
|
||||
* @return EnumSet.contains(...) is {@code true} if supported, else {@code false}
|
||||
*/
|
||||
EnumSet<FlowControl> getSupportedFlowControl();
|
||||
|
||||
/**
|
||||
* If flow control = XON_XOFF, indicates that send is enabled by XON.
|
||||
* Devices supporting flow control = XON_XOFF_INLINE return CHAR_XON/CHAR_XOFF in read() data.
|
||||
*
|
||||
* @return the current state
|
||||
* @throws IOException if an error occurred during reading
|
||||
* @throws UnsupportedOperationException if not supported
|
||||
*/
|
||||
boolean getXON() throws IOException;
|
||||
|
||||
/**
|
||||
* Purge non-transmitted output data and / or non-read input data.
|
||||
*
|
||||
|
@ -27,6 +27,9 @@ public class HexDump {
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
|
||||
};
|
||||
|
||||
private HexDump() {
|
||||
}
|
||||
|
||||
public static String dumpHexString(byte[] array) {
|
||||
return dumpHexString(array, 0, array.length);
|
||||
}
|
||||
|
@ -13,16 +13,19 @@ import com.hoho.android.usbserial.driver.UsbSerialPort;
|
||||
|
||||
import java.io.IOException;
|
||||
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)
|
||||
*/
|
||||
public class SerialInputOutputManager implements Runnable {
|
||||
public class SerialInputOutputManager {
|
||||
|
||||
public enum State {
|
||||
STOPPED,
|
||||
STARTING,
|
||||
RUNNING,
|
||||
STOPPING
|
||||
}
|
||||
@ -32,9 +35,6 @@ public class SerialInputOutputManager implements Runnable {
|
||||
private static final String TAG = SerialInputOutputManager.class.getSimpleName();
|
||||
private static final int BUFSIZ = 4096;
|
||||
|
||||
/**
|
||||
* default read timeout is infinite, to avoid data loss with bulkTransfer API
|
||||
*/
|
||||
private int mReadTimeout = 0;
|
||||
private int mWriteTimeout = 0;
|
||||
|
||||
@ -45,7 +45,8 @@ public class SerialInputOutputManager implements Runnable {
|
||||
private ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
|
||||
|
||||
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 final UsbSerialPort mSerialPort;
|
||||
|
||||
@ -56,7 +57,7 @@ public class SerialInputOutputManager implements Runnable {
|
||||
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);
|
||||
}
|
||||
@ -86,8 +87,9 @@ public class SerialInputOutputManager implements Runnable {
|
||||
* @param threadPriority see {@link Process#setThreadPriority(int)}
|
||||
* */
|
||||
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");
|
||||
}
|
||||
mThreadPriority = threadPriority;
|
||||
}
|
||||
|
||||
@ -96,7 +98,7 @@ public class SerialInputOutputManager implements Runnable {
|
||||
*/
|
||||
public void setReadTimeout(int timeout) {
|
||||
// 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");
|
||||
mReadTimeout = timeout;
|
||||
}
|
||||
@ -144,79 +146,152 @@ public class SerialInputOutputManager implements Runnable {
|
||||
}
|
||||
|
||||
/**
|
||||
* when using writeAsync, it is recommended to use readTimeout != 0,
|
||||
* else the write will be delayed until read data is available
|
||||
* write data asynchronously
|
||||
*/
|
||||
public void writeAsync(byte[] data) {
|
||||
synchronized (mWriteBufferLock) {
|
||||
mWriteBuffer.put(data);
|
||||
mWriteBufferLock.notifyAll(); // Notify waiting threads
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* start SerialInputOutputManager in separate thread
|
||||
* start SerialInputOutputManager in separate threads
|
||||
*/
|
||||
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");
|
||||
new Thread(this, this.getClass().getSimpleName()).start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* stop SerialInputOutputManager thread
|
||||
* stop SerialInputOutputManager threads
|
||||
*
|
||||
* when using readTimeout == 0 (default), additionally use usbSerialPort.close() to
|
||||
* interrupt blocking read
|
||||
*/
|
||||
public synchronized void stop() {
|
||||
if (getState() == State.RUNNING) {
|
||||
public void stop() {
|
||||
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");
|
||||
mState = State.STOPPING;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized State getState() {
|
||||
return mState;
|
||||
public State getState() {
|
||||
return mState.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Continuously services the read and write buffers until {@link #stop()} is
|
||||
* called, or until a driver exception is raised.
|
||||
* @return true if the thread is still running
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
if (getState() != State.STOPPED) {
|
||||
throw new IllegalStateException("Already running");
|
||||
private boolean isStillRunning() {
|
||||
State state = mState.get();
|
||||
return ((state == State.RUNNING) || (state == State.STARTING))
|
||||
&& !Thread.currentThread().isInterrupted();
|
||||
}
|
||||
mState = State.RUNNING;
|
||||
}
|
||||
Log.i(TAG, "Running ...");
|
||||
try {
|
||||
if(mThreadPriority != Process.THREAD_PRIORITY_DEFAULT)
|
||||
Process.setThreadPriority(mThreadPriority);
|
||||
while (true) {
|
||||
if (getState() != State.RUNNING) {
|
||||
Log.i(TAG, "Stopping mState=" + getState());
|
||||
break;
|
||||
}
|
||||
step();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
|
||||
final Listener listener = getListener();
|
||||
|
||||
/**
|
||||
* Notify listener of an error
|
||||
*
|
||||
* @param e the exception
|
||||
*/
|
||||
private void notifyErrorListener(Throwable e) {
|
||||
Listener listener = getListener();
|
||||
if (listener != null) {
|
||||
listener.onRunError(e);
|
||||
}
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
mState = State.STOPPED;
|
||||
Log.i(TAG, "Stopped");
|
||||
try {
|
||||
listener.onRunError(e instanceof Exception ? (Exception) e : new Exception(e));
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "Exception in onRunError: " + t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
byte[] buffer;
|
||||
synchronized (mReadBufferLock) {
|
||||
@ -234,21 +309,26 @@ public class SerialInputOutputManager implements Runnable {
|
||||
listener.onNewData(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void stepWrite() throws IOException, InterruptedException {
|
||||
// Handle outgoing data.
|
||||
buffer = null;
|
||||
byte[] buffer = null;
|
||||
synchronized (mWriteBufferLock) {
|
||||
len = mWriteBuffer.position();
|
||||
int len = mWriteBuffer.position();
|
||||
if (len > 0) {
|
||||
buffer = new byte[len];
|
||||
mWriteBuffer.rewind();
|
||||
mWriteBuffer.get(buffer, 0, len);
|
||||
mWriteBuffer.clear();
|
||||
mWriteBufferLock.notifyAll(); // Notify writeAsync that there is space in the buffer
|
||||
} else {
|
||||
mWriteBufferLock.wait();
|
||||
}
|
||||
}
|
||||
if (buffer != null) {
|
||||
if (DEBUG) {
|
||||
Log.d(TAG, "Writing data len=" + len);
|
||||
Log.d(TAG, "Writing data len=" + buffer.length);
|
||||
}
|
||||
mSerialPort.write(buffer, mWriteTimeout);
|
||||
}
|
||||
|
@ -6,6 +6,9 @@ import java.util.ArrayList;
|
||||
|
||||
public class UsbUtils {
|
||||
|
||||
private UsbUtils() {
|
||||
}
|
||||
|
||||
public static ArrayList<byte[]> getDescriptors(UsbDeviceConnection connection) {
|
||||
ArrayList<byte[]> descriptors = new ArrayList<>();
|
||||
byte[] rawDescriptors = connection.getRawDescriptors();
|
||||
|
@ -0,0 +1,47 @@
|
||||
package com.hoho.android.usbserial.util;
|
||||
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Some devices return XON and XOFF characters inline in read() data.
|
||||
* Other devices return XON / XOFF condition thru getXOFF() method.
|
||||
*/
|
||||
|
||||
public class XonXoffFilter {
|
||||
private boolean xon = true;
|
||||
|
||||
public XonXoffFilter() {
|
||||
}
|
||||
|
||||
public boolean getXON() {
|
||||
return xon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter XON/XOFF from read() data and remember
|
||||
*
|
||||
* @param data unfiltered data
|
||||
* @return filtered data
|
||||
*/
|
||||
public byte[] filter(byte[] data) {
|
||||
int found = 0;
|
||||
for (int i=0; i<data.length; i++) {
|
||||
if (data[i] == UsbSerialPort.CHAR_XON || data[i] == UsbSerialPort.CHAR_XOFF)
|
||||
found++;
|
||||
}
|
||||
if(found == 0)
|
||||
return data;
|
||||
byte[] filtered = new byte[data.length - found];
|
||||
for (int i=0, j=0; i<data.length; i++) {
|
||||
if (data[i] == UsbSerialPort.CHAR_XON)
|
||||
xon = true;
|
||||
else if(data[i] == UsbSerialPort.CHAR_XOFF)
|
||||
xon = false;
|
||||
else
|
||||
filtered[j++] = data[i];
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
}
|
@ -17,6 +17,11 @@ public class Log {
|
||||
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) {
|
||||
System.out.println("ERROR: " + tag + ": " + msg);
|
||||
return 0;
|
||||
|
@ -0,0 +1,44 @@
|
||||
package com.hoho.android.usbserial.util;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.security.InvalidParameterException;
|
||||
|
||||
public class HexDumpText {
|
||||
|
||||
@Test
|
||||
public void toByteArray() throws Exception {
|
||||
assertThat(HexDump.toByteArray((byte)0x4a), equalTo(new byte[]{ 0x4A}));
|
||||
assertThat(HexDump.toByteArray((short)0x4a5b), equalTo(new byte[]{ 0x4A, 0x5B}));
|
||||
assertThat(HexDump.toByteArray((int)0x4a5b6c7d), equalTo(new byte[]{ 0x4A, 0x5B, 0x6C, 0x7D}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toHexString() throws Exception {
|
||||
assertEquals("4A", HexDump.toHexString((byte)0x4a));
|
||||
assertEquals("4A 5B", HexDump.toHexString((short)0x4a5b));
|
||||
assertEquals("4A 5B 6C 7D", HexDump.toHexString((int)0x4a5b6c7d));
|
||||
assertEquals("4A 5B 6C 7D", HexDump.toHexString(new byte[]{ 0x4A, 0x5B, 0x6C, 0x7D}));
|
||||
assertEquals("5B 6C", HexDump.toHexString(new byte[]{ 0x4A, 0x5B, 0x6C, 0x7D}, 1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dumpHexString() throws Exception {
|
||||
assertEquals("10 31 32 33 34 35 36 37 .1234567\n18 39 .9", HexDump.dumpHexString(new byte[]{ 0x10, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x18, 0x39}));
|
||||
assertEquals("31 32 12", HexDump.dumpHexString(new byte[]{ 0x30, 0x31, 0x32, 0x33}, 1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toByte() throws Exception {
|
||||
assertThat(HexDump.hexStringToByteArray("4a 5B-6c\n7d"), equalTo(new byte[]{ 0x4A, 0x5B, 0x6C, 0x7D}));
|
||||
assertThrows(InvalidParameterException.class, () -> HexDump.hexStringToByteArray("3 "));
|
||||
assertThrows(InvalidParameterException.class, () -> HexDump.hexStringToByteArray("3z"));
|
||||
assertThrows(InvalidParameterException.class, () -> HexDump.hexStringToByteArray("3Z"));
|
||||
}
|
||||
|
||||
}
|
@ -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