├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── themes.xml │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── layout │ │ │ │ └── activity_main.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── values-night │ │ │ │ └── themes.xml │ │ │ ├── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ │ └── drawable │ │ │ │ └── ic_launcher_background.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── lgh │ │ │ └── app │ │ │ └── MainActivity.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── lgh │ │ │ └── hetcommonusbserialsdk │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── lgh │ │ └── hetcommonusbserialsdk │ │ └── ExampleInstrumentedTest.java ├── proguard-rules.pro └── build.gradle ├── commonusbserialsdk ├── .gitignore ├── consumer-rules.pro ├── src │ ├── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── lgh │ │ │ └── commonusbserialsdk │ │ │ ├── usb │ │ │ ├── PortType.java │ │ │ ├── IDeviceFilter.java │ │ │ ├── IUsbManager.java │ │ │ ├── CustomUsbPort.java │ │ │ └── UsbManagerUtil.java │ │ │ ├── listen │ │ │ ├── UsbSerialListener.java │ │ │ └── UsbConnectListener.java │ │ │ ├── IUsbSerialSdk.java │ │ │ ├── thread │ │ │ ├── BaseThread.java │ │ │ ├── ReadThread.java │ │ │ └── WriteThread.java │ │ │ ├── utils │ │ │ ├── HexUtil.java │ │ │ └── LogUtil.java │ │ │ └── CommonUsbSerialSdk.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── lgh │ │ │ └── commonusbserialsdk │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── lgh │ │ └── commonusbserialsdk │ │ └── ExampleInstrumentedTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── README.md ├── gradlew.bat └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /commonusbserialsdk/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /commonusbserialsdk/consumer-rules.pro: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':commonusbserialsdk' 2 | include ':app' 3 | rootProject.name = "CommonUsbSerialSdk" -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CommonUsbSerialSdk 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Liuguihong/AndroidUsbSerialSdk/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Nov 22 10:20:43 CST 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip 7 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/usb/PortType.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.usb; 2 | 3 | /** 4 | * 描述:通信类型,USB通信 || USB转串口通信 5 | * 作者:liugh 6 | * 日期:2021/12/28 7 | * 版本:V1.0.0 8 | */ 9 | public enum PortType { 10 | USB, USB_TO_SERIAL 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | .idea 17 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/listen/UsbSerialListener.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.listen; 2 | 3 | /** 4 | * 描述:USB读写数据处理接口 5 | * 作者:liugh 6 | * 日期:2021/11/24 7 | * 版本:V1.0.0 8 | */ 9 | public interface UsbSerialListener { 10 | void onWrite(byte[] bytes); 11 | 12 | void onRead(byte[] bytes); 13 | } 14 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/usb/IDeviceFilter.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.usb; 2 | 3 | import android.hardware.usb.UsbDevice; 4 | 5 | /** 6 | * 描述:判断是否目标设备 7 | * 作者:liugh 8 | * 日期:2021/11/22 9 | * 版本:V1.0.0 10 | */ 11 | public interface IDeviceFilter { 12 | boolean isTargetDevice(UsbDevice usbDevice); 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /app/src/test/java/com/lgh/hetcommonusbserialsdk/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.lgh.hetcommonusbserialsdk; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /commonusbserialsdk/src/test/java/com/lgh/commonusbserialsdk/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/IUsbSerialSdk.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk; 2 | 3 | import android.hardware.usb.UsbDevice; 4 | 5 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 6 | 7 | /** 8 | * 描述:HetCommonUsbSerialSdk实现接口 9 | * 作者:liugh 10 | * 日期:2021/11/22 11 | * 版本:V1.0.0 12 | */ 13 | public interface IUsbSerialSdk { 14 | boolean hasTargetDevice(); 15 | 16 | void checkTargetDevice(); 17 | 18 | void checkDriver(UsbDevice usbDevice); 19 | 20 | void openSerialPort(UsbSerialDriver driver, UsbDevice usbDevice); 21 | 22 | void closeSerialPort(); 23 | 24 | void startThread(); 25 | 26 | void stopThread(); 27 | 28 | void write(byte[] src); 29 | 30 | void release(); 31 | } 32 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/usb/IUsbManager.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.usb; 2 | 3 | import android.hardware.usb.UsbDevice; 4 | import android.hardware.usb.UsbDeviceConnection; 5 | 6 | /** 7 | * 描述:UsbManager实现接口 8 | * 作者:liugh 9 | * 日期:2021/11/22 10 | * 版本:v1.0.0 11 | */ 12 | public interface IUsbManager { 13 | void registerReceiver(); 14 | 15 | void unregisterReceiver(); 16 | 17 | boolean hasPermission(UsbDevice usbDevice); 18 | 19 | void requestPermission(UsbDevice usbDevice); 20 | 21 | void connectDevice(UsbDevice usbDevice); 22 | 23 | void closeDevice(UsbDevice usbDevice); 24 | 25 | UsbDeviceConnection getConnection(UsbDevice usbDevice); 26 | 27 | void checkTargetDevice(); 28 | 29 | boolean hasTargetDevice(); 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /commonusbserialsdk/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/lgh/hetcommonusbserialsdk/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.lgh.hetcommonusbserialsdk; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.clife.hetcommonusbserialsdk", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /commonusbserialsdk/src/androidTest/java/com/lgh/commonusbserialsdk/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.het.commonusbserialsdk.test", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/thread/BaseThread.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.thread; 2 | 3 | import com.lgh.commonusbserialsdk.listen.UsbSerialListener; 4 | import com.hoho.android.usbserial.driver.UsbSerialPort; 5 | 6 | /** 7 | * 描述:数据收发处理线程基类 8 | * 作者:liugh 9 | * 日期:2021/11/23 10 | * 版本:V1.0.0 11 | */ 12 | public abstract class BaseThread { 13 | protected static final int TIMEOUT = 100; 14 | protected static final int CAPACITY = 64; 15 | protected UsbSerialPort mUsbSerialPort; 16 | protected UsbSerialListener mUsbSerialListener; 17 | 18 | public BaseThread(UsbSerialListener listener) { 19 | this.mUsbSerialListener = listener; 20 | } 21 | 22 | public void start(UsbSerialPort usbSerialPort) { 23 | this.mUsbSerialPort = usbSerialPort; 24 | } 25 | 26 | public abstract boolean isStart(); 27 | 28 | public abstract void stop(); 29 | 30 | public abstract void write(byte[] bytes); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true -------------------------------------------------------------------------------- /commonusbserialsdk/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.3" 8 | 9 | defaultConfig { 10 | minSdkVersion 18 11 | targetSdkVersion 30 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | consumerProguardFiles "consumer-rules.pro" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | 26 | compileOptions { 27 | sourceCompatibility JavaVersion.VERSION_1_8 28 | targetCompatibility JavaVersion.VERSION_1_8 29 | } 30 | } 31 | 32 | dependencies { 33 | testImplementation 'junit:junit:4.+' 34 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 35 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 36 | 37 | api 'androidx.annotation:annotation:1.2.0' 38 | api 'com.github.mik3y:usb-serial-for-android:3.4.3' 39 | } -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.3" 8 | 9 | defaultConfig { 10 | applicationId "com.lgh.commonusbserialsdk" 11 | minSdkVersion 18 12 | targetSdkVersion 30 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | } 30 | 31 | dependencies { 32 | testImplementation 'junit:junit:4.+' 33 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 34 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 35 | 36 | implementation 'androidx.appcompat:appcompat:1.2.0' 37 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 38 | implementation 'com.google.android.material:material:1.2.1' 39 | 40 | implementation project(':commonusbserialsdk') 41 | } 42 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/listen/UsbConnectListener.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.listen; 2 | 3 | import android.hardware.usb.UsbDevice; 4 | 5 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 6 | 7 | /** 8 | * 描述:USB连接监听接口 9 | * 作者:liugh 10 | * 日期:2021/11/22 11 | * 版本:v1.0.0 12 | */ 13 | public interface UsbConnectListener { 14 | /** 15 | * 设备插入 16 | * 17 | * @param usbDevice 18 | */ 19 | void onAttached(UsbDevice usbDevice); 20 | 21 | /** 22 | * USB设备授权回调 23 | * 24 | * @param usbDevice 25 | * @param granted 是否授权成功 26 | */ 27 | void onGranted(UsbDevice usbDevice, boolean granted); 28 | 29 | /** 30 | * 设备连接状态 31 | * 32 | * @param usbDevice 33 | * @param connected 34 | */ 35 | void onConnected(UsbDevice usbDevice, boolean connected); 36 | 37 | /** 38 | * 串口驱动检查 39 | * 40 | * @param usbDevice 41 | * @param driver 是否找到相关驱动 42 | */ 43 | void onDriverFound(UsbDevice usbDevice, UsbSerialDriver driver); 44 | 45 | /** 46 | * 串口打开状态 47 | * 48 | * @param usbDevice 49 | * @param success 50 | */ 51 | void onDeviceOpened(UsbDevice usbDevice, boolean success); 52 | 53 | /** 54 | * 设备拔出 55 | * 56 | * @param usbDevice 57 | */ 58 | void onDetached(UsbDevice usbDevice); 59 | } 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [**USB、USB转串口、串口通信的区别与实现**](https://blog.csdn.net/u011630465/article/details/124168432?spm=1001.2014.3001.5501) 2 | 3 | **本库优势:** 4 | 1. 同时满足USB通信和USB转串口通信,免去维护多个SDK烦恼 5 | 2. 超简单的使用方式,超简洁的API 6 | 3. 支持全方位自定义扩展,与业务高度解耦,满足各种场景需求 7 | 4. 无需关注繁琐的USB插拔逻辑 8 | 9 | github地址:[https://github.com/Liuguihong/AndroidUsbSerialSdk](https://github.com/Liuguihong/AndroidUsbSerialSdk) 10 | 11 | #### 1.添加依赖 12 | compile 'com.github.Liuguihong:AndroidUsbSerialSdk:1.0.0' 13 | #### 2.创建CommonUsbSerialSdk对象 14 | ```java 15 | CommonUsbSerialSdk mCommonUsbSerialSdk = new CommonUsbSerialSdk(this); 16 | ``` 17 | #### 3.添加配置(可选) 18 | ```java 19 | mCommonUsbSerialSdk.setBaudRate(115200) // 波特率 20 | .setDataBits(UsbSerialPort.DATABITS_8) // 数据位 21 | .setStopBits(UsbSerialPort.STOPBITS_1) // 停止位 22 | .setParity(UsbSerialPort.PARITY_NONE) // 奇偶校验位 23 | .setForceGrant(true) // 强制授权,授权不成功重复弹出授权弹窗 24 | .setPortType(PortType.USB_TO_SERIAL) // 通信类型,可选择usb通信或者usb转串口通信 25 | ``` 26 | #### 4.设置USB设备过滤条件 27 | ```java 28 | mCommonUsbSerialSdk.setDeviceFilter(new IDeviceFilter() { 29 | @Override 30 | public boolean isTargetDevice(UsbDevice usbDevice) { 31 | return usbDevice != null 32 | && usbDevice.getProductId() == 123 33 | && usbDevice.getVendorId() == 456; 34 | } 35 | }); 36 | ``` 37 | #### 5.设置读写数据回调 38 | ```java 39 | mCommonUsbSerialSdk.setUsbSerialListener(new UsbSerialListener() { // 读写数据回调 40 | @Override 41 | public void onWrite(byte[] bytes) { 42 | 43 | } 44 | 45 | @Override 46 | public void onRead(byte[] bytes) { 47 | 48 | } 49 | }) 50 | ``` 51 | #### 6.通信 52 | ```java 53 | mCommonUsbSerialSdk.write(null); 54 | ``` 55 | #### 参考 56 | [https://github.com/mik3y/usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) 57 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/lgh/app/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.lgh.app; 2 | 3 | import android.os.Bundle; 4 | 5 | import androidx.appcompat.app.AppCompatActivity; 6 | 7 | import com.hoho.android.usbserial.driver.UsbSerialPort; 8 | import com.lgh.commonusbserialsdk.CommonUsbSerialSdk; 9 | import com.lgh.commonusbserialsdk.listen.UsbSerialListener; 10 | import com.lgh.commonusbserialsdk.usb.PortType; 11 | 12 | public class MainActivity extends AppCompatActivity { 13 | private CommonUsbSerialSdk mCommonUsbSerialSdk; 14 | 15 | @Override 16 | protected void onCreate(Bundle savedInstanceState) { 17 | super.onCreate(savedInstanceState); 18 | setContentView(R.layout.activity_main); 19 | mCommonUsbSerialSdk = new CommonUsbSerialSdk(this); 20 | mCommonUsbSerialSdk.setBaudRate(115200) 21 | .setDataBits(UsbSerialPort.DATABITS_8) // 数据位 22 | .setStopBits(UsbSerialPort.STOPBITS_1) // 停止位 23 | .setParity(UsbSerialPort.PARITY_NONE) // 奇偶校验位 24 | .setForceGrant(true) // 强制授权,授权不成功重复弹出授权弹窗 25 | .setPortType(PortType.USB_TO_SERIAL) // 通信类型 26 | .setDeviceFilter(usbDevice -> true) // 设置USB设备过滤条件 27 | .setUsbSerialListener(new UsbSerialListener() { // 读写数据回调 28 | @Override 29 | public void onWrite(byte[] bytes) { 30 | 31 | } 32 | 33 | @Override 34 | public void onRead(byte[] bytes) { 35 | 36 | } 37 | }) 38 | .create(); 39 | 40 | mCommonUsbSerialSdk.checkTargetDevice(); // 检查是否有目标设备 41 | } 42 | 43 | private void write() { 44 | mCommonUsbSerialSdk.write(null); 45 | } 46 | 47 | @Override 48 | protected void onDestroy() { 49 | super.onDestroy(); 50 | mCommonUsbSerialSdk.release(); 51 | } 52 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/thread/ReadThread.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.thread; 2 | 3 | import com.lgh.commonusbserialsdk.listen.UsbSerialListener; 4 | import com.lgh.commonusbserialsdk.utils.HexUtil; 5 | import com.lgh.commonusbserialsdk.utils.LogUtil; 6 | import com.hoho.android.usbserial.driver.UsbSerialPort; 7 | 8 | import java.nio.ByteBuffer; 9 | 10 | /** 11 | * 描述:数据接收线程 12 | * 作者:liugh 13 | * 日期:2021/11/24 14 | * 版本:V1.0.0 15 | */ 16 | public class ReadThread extends BaseThread implements Runnable { 17 | private Thread mReadThread; 18 | private ByteBuffer mReadBuffer; 19 | 20 | public ReadThread(UsbSerialListener listener) { 21 | super(listener); 22 | mReadBuffer = ByteBuffer.allocate(CAPACITY); 23 | } 24 | 25 | @Override 26 | public void start(UsbSerialPort usbSerialPort) { 27 | super.start(usbSerialPort); 28 | if (mReadBuffer == null) { 29 | mReadBuffer = ByteBuffer.allocate(CAPACITY); 30 | } 31 | if (mReadThread == null) { 32 | mReadThread = new Thread(this); 33 | mReadThread.start(); 34 | } 35 | } 36 | 37 | @Override 38 | public boolean isStart() { 39 | return mReadThread != null; 40 | } 41 | 42 | @Override 43 | public void stop() { 44 | if (mReadThread != null) { 45 | mReadThread.interrupt(); 46 | mReadThread = null; 47 | } 48 | if (mReadBuffer != null) { 49 | mReadBuffer.clear(); 50 | mReadBuffer = null; 51 | } 52 | } 53 | 54 | @Override 55 | public void write(byte[] bytes) { 56 | 57 | } 58 | 59 | @Override 60 | public void run() { 61 | while (mReadThread != null 62 | && !mReadThread.isInterrupted() 63 | && mUsbSerialPort != null 64 | && mUsbSerialPort.isOpen()) { 65 | try { 66 | int length = mUsbSerialPort.read(mReadBuffer.array(), TIMEOUT); 67 | if (length > 0) { 68 | byte[] bytes = new byte[length]; 69 | mReadBuffer.get(bytes, 0, length); 70 | LogUtil.i("read-->" + HexUtil.bytesToHex(bytes)); 71 | if (mUsbSerialListener != null) { 72 | mUsbSerialListener.onRead(bytes); 73 | } 74 | mReadBuffer.clear(); 75 | } 76 | } catch (Exception e) { 77 | e.printStackTrace(); 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/usb/CustomUsbPort.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.usb; 2 | 3 | import android.hardware.usb.UsbConstants; 4 | import android.hardware.usb.UsbDevice; 5 | import android.hardware.usb.UsbDeviceConnection; 6 | import android.hardware.usb.UsbEndpoint; 7 | import android.hardware.usb.UsbInterface; 8 | 9 | import com.hoho.android.usbserial.driver.CommonUsbSerialPort; 10 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 11 | 12 | import java.io.IOException; 13 | import java.util.EnumSet; 14 | 15 | /** 16 | * 描述:usb通信端口 17 | * 作者:liugh 18 | * 日期:2021/12/25 19 | * 版本:V1.0.0 20 | */ 21 | public class CustomUsbPort extends CommonUsbSerialPort { 22 | 23 | public CustomUsbPort(UsbDevice device, int portNumber) { 24 | super(device, portNumber); 25 | } 26 | 27 | @Override 28 | protected void openInt(UsbDeviceConnection connection) throws IOException { 29 | for (int i = 0; i < mDevice.getInterfaceCount(); i++) { 30 | UsbInterface usbIface = mDevice.getInterface(i); 31 | if (!mConnection.claimInterface(usbIface, true)) { 32 | throw new IOException("Could not claim data interface"); 33 | } 34 | } 35 | 36 | UsbInterface dataIface = mDevice.getInterface(0); 37 | for (int i = 0; i < dataIface.getEndpointCount(); i++) { 38 | UsbEndpoint endpoint = dataIface.getEndpoint(i); 39 | if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) { 40 | mReadEndpoint = endpoint; 41 | } 42 | if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) { 43 | mWriteEndpoint = endpoint; 44 | } 45 | } 46 | } 47 | 48 | @Override 49 | protected void closeInt() { 50 | try { 51 | for (int i = 0; i < mDevice.getInterfaceCount(); i++) { 52 | mConnection.releaseInterface(mDevice.getInterface(i)); 53 | } 54 | } catch (Exception e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | 59 | @Override 60 | public UsbSerialDriver getDriver() { 61 | return null; 62 | } 63 | 64 | @Override 65 | public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException { 66 | } 67 | 68 | @Override 69 | public EnumSet getControlLines() throws IOException { 70 | return null; 71 | } 72 | 73 | @Override 74 | public EnumSet getSupportedControlLines() throws IOException { 75 | return null; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/thread/WriteThread.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.thread; 2 | 3 | import android.os.Handler; 4 | import android.os.HandlerThread; 5 | import android.os.Message; 6 | 7 | import com.lgh.commonusbserialsdk.listen.UsbSerialListener; 8 | import com.lgh.commonusbserialsdk.utils.HexUtil; 9 | import com.lgh.commonusbserialsdk.utils.LogUtil; 10 | import com.hoho.android.usbserial.driver.UsbSerialPort; 11 | 12 | /** 13 | * 描述:指令下发线程实现类 14 | * 作者:liugh 15 | * 日期:2021/11/23 16 | * 版本:V1.0.0 17 | */ 18 | public class WriteThread extends BaseThread { 19 | private HandlerThread mWriteThread; 20 | private Handler mWriteHandler; 21 | 22 | public WriteThread(UsbSerialListener listener) { 23 | super(listener); 24 | } 25 | 26 | @Override 27 | public void start(UsbSerialPort usbSerialPort) { 28 | super.start(usbSerialPort); 29 | if (mWriteThread == null) { 30 | mWriteThread = new HandlerThread("mWriteThread"); 31 | mWriteThread.start(); 32 | } 33 | if (mWriteHandler == null) { 34 | mWriteHandler = new Handler(mWriteThread.getLooper()) { 35 | @Override 36 | public void handleMessage(Message msg) { 37 | super.handleMessage(msg); 38 | try { 39 | byte[] bytes = (byte[]) msg.obj; 40 | mUsbSerialPort.write(bytes, TIMEOUT); 41 | LogUtil.i("write-->" + HexUtil.bytesToHex(bytes)); 42 | if (mUsbSerialListener != null) { 43 | mUsbSerialListener.onWrite(bytes); 44 | } 45 | } catch (Exception e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | }; 50 | } 51 | } 52 | 53 | @Override 54 | public boolean isStart() { 55 | return mWriteHandler != null && mWriteThread != null; 56 | } 57 | 58 | @Override 59 | public void stop() { 60 | if (mWriteThread != null) { 61 | mWriteThread.quit(); 62 | mWriteThread = null; 63 | } 64 | if (mWriteHandler != null) { 65 | mWriteHandler.removeCallbacksAndMessages(null); 66 | mWriteHandler = null; 67 | } 68 | } 69 | 70 | @Override 71 | public void write(byte[] bytes) { 72 | if (mWriteHandler == null || mWriteThread == null) { 73 | return; 74 | } 75 | Message message = Message.obtain(); 76 | message.obj = bytes; 77 | mWriteHandler.sendMessage(message); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/utils/HexUtil.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.utils; 2 | 3 | import android.text.TextUtils; 4 | 5 | /** 6 | * 描述:数值处理、转换相关工具类 7 | * 作者:liugh 8 | * 日期:2021/11/27 9 | * 版本:V1.0.0 10 | */ 11 | public class HexUtil { 12 | /** 13 | * 计算CRC16校验码 14 | * 15 | * @param bytes 16 | * @return 17 | */ 18 | public static byte[] getCRC16(byte[] bytes) { 19 | String crc16Hex = getCRC16Hex(bytes); 20 | return hexToBytes(crc16Hex); 21 | } 22 | 23 | /** 24 | * 计算CRC16校验码 25 | * 26 | * @param bytes 27 | * @return 28 | */ 29 | public static String getCRC16Hex(byte[] bytes) { 30 | if (bytes == null || bytes.length == 0) { 31 | return ""; 32 | } 33 | 34 | int CRC = 0x0000ffff; 35 | int POLYNOMIAL = 0x0000a001; 36 | 37 | for (int i = 0; i < bytes.length; i++) { 38 | CRC ^= ((int) bytes[i] & 0x000000ff); 39 | for (int j = 0; j < 8; j++) { 40 | if ((CRC & 0x00000001) != 0) { 41 | CRC >>= 1; 42 | CRC ^= POLYNOMIAL; 43 | } else { 44 | CRC >>= 1; 45 | } 46 | } 47 | } 48 | return Integer.toHexString(CRC); 49 | } 50 | 51 | /** 52 | * int转2个字节bytes 53 | * 54 | * @param value 55 | * @return 56 | */ 57 | public static byte[] intToBytes(int value) { 58 | byte[] bytes = new byte[2]; 59 | bytes[0] = (byte) ((value >> 8) & 0xFF); 60 | bytes[1] = (byte) (value & 0xFF); 61 | return bytes; 62 | } 63 | 64 | /** 65 | * 2字节转int 66 | * 67 | * @param b0 68 | * @param b1 69 | * @return 70 | */ 71 | public static int bytes2Int(byte b0, byte b1) { 72 | int result = 0; 73 | result = b0 & 0xff; 74 | result = result << 8 | b1 & 0xff; 75 | return result; 76 | } 77 | 78 | /** 79 | * 字节数组转16进制 80 | * 81 | * @param bytes 需要转换的byte数组 82 | * @return 转换后的Hex字符串 83 | */ 84 | public static String bytesToHex(byte[] bytes) { 85 | if (bytes == null || bytes.length == 0) { 86 | return ""; 87 | } 88 | StringBuffer sb = new StringBuffer(); 89 | for (int i = 0; i < bytes.length; i++) { 90 | String hex = Integer.toHexString(bytes[i] & 0xFF).toUpperCase(); 91 | if (hex.length() < 2) { 92 | sb.append(0); 93 | } 94 | sb.append(hex); 95 | if (i != bytes.length - 1) { 96 | sb.append(" "); 97 | } 98 | } 99 | return sb.toString(); 100 | } 101 | 102 | /** 103 | * 16进制字符串转bytes 104 | * 105 | * @param hex 106 | * @return 107 | */ 108 | public static byte[] hexToBytes(String hex) { 109 | if (TextUtils.isEmpty(hex)) { 110 | return null; 111 | } 112 | hex = hex.length() % 2 != 0 ? "0" + hex : hex; 113 | byte[] bytes = new byte[hex.length() / 2]; 114 | for (int i = 0; i < bytes.length; i++) { 115 | int index = i * 2; 116 | int value = Integer.parseInt(hex.substring(index, index + 2), 16); 117 | bytes[i] = (byte) value; 118 | } 119 | return bytes; 120 | } 121 | 122 | /** 123 | * 去除不可见字符 124 | * 125 | * @param array 126 | * @return 127 | */ 128 | public static String dumpHexString(byte[] array) { 129 | return dumpHexString(array, 0, array.length); 130 | } 131 | 132 | /** 133 | * 去除不可见字符 134 | * 135 | * @param array 136 | * @param offset 137 | * @param length 138 | * @return 139 | */ 140 | public static String dumpHexString(byte[] array, int offset, int length) { 141 | StringBuilder result = new StringBuilder(); 142 | for (int i = offset; i < offset + length; i++) { 143 | if (array[i] >= ' ' && array[i] <= '~') { 144 | result.append(new String(array, i, 1)); 145 | } 146 | } 147 | return result.toString(); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/usb/UsbManagerUtil.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk.usb; 2 | 3 | import android.app.PendingIntent; 4 | import android.content.BroadcastReceiver; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.content.IntentFilter; 8 | import android.hardware.usb.UsbDevice; 9 | import android.hardware.usb.UsbDeviceConnection; 10 | import android.hardware.usb.UsbManager; 11 | 12 | import com.lgh.commonusbserialsdk.listen.UsbConnectListener; 13 | import com.lgh.commonusbserialsdk.utils.LogUtil; 14 | 15 | import java.util.HashMap; 16 | 17 | /** 18 | * 描述:usb插拔监听、连接工具类 19 | * 作者:liugh 20 | * 日期:2021/11/22 21 | * 版本:v1.0.0 22 | */ 23 | public class UsbManagerUtil implements IUsbManager { 24 | private static final String ACTION_USB_DEVICE_PERMISSION = "ACTION_USB_DEVICE_PERMISSION"; 25 | private Context mContext; 26 | private UsbManager mUsbManager; 27 | private USBReceiver mUsbReceiver; 28 | private HashMap mConnectionMap; 29 | private UsbConnectListener mConnectListener; 30 | private IDeviceFilter deviceFilter; 31 | 32 | public UsbManagerUtil(Context context) { 33 | this.mContext = context; 34 | this.mUsbManager = (UsbManager) context.getSystemService(context.USB_SERVICE); 35 | this.mConnectionMap = new HashMap<>(); 36 | } 37 | 38 | /** 39 | * 注册usb插拔监听广播 40 | */ 41 | @Override 42 | public void registerReceiver() { 43 | LogUtil.i("registerReceiver"); 44 | if (mUsbReceiver == null) { 45 | IntentFilter filter = new IntentFilter(); 46 | filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); 47 | filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); 48 | filter.addAction(ACTION_USB_DEVICE_PERMISSION); 49 | mUsbReceiver = new USBReceiver(); 50 | mContext.registerReceiver(mUsbReceiver, filter); 51 | } 52 | } 53 | 54 | /** 55 | * 注销usb插拔监听广播 56 | */ 57 | @Override 58 | public void unregisterReceiver() { 59 | LogUtil.i("unregisterReceiver"); 60 | if (mUsbReceiver != null) { 61 | mContext.unregisterReceiver(mUsbReceiver); 62 | mUsbReceiver = null; 63 | } 64 | if (mConnectionMap != null) { 65 | mConnectionMap.clear(); 66 | mConnectionMap = null; 67 | } 68 | } 69 | 70 | /** 71 | * USB设备权限检查 72 | * 73 | * @param usbDevice 74 | * @return 75 | */ 76 | @Override 77 | public boolean hasPermission(UsbDevice usbDevice) { 78 | LogUtil.i("hasPermission"); 79 | return mUsbManager.hasPermission(usbDevice); 80 | } 81 | 82 | /** 83 | * USB设备授权 84 | * 85 | * @param usbDevice 86 | */ 87 | @Override 88 | public void requestPermission(UsbDevice usbDevice) { 89 | LogUtil.i("requestPermission"); 90 | if (hasPermission(usbDevice)) { 91 | if (mConnectListener != null) { 92 | mConnectListener.onGranted(usbDevice, true); 93 | } 94 | } else { 95 | PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_DEVICE_PERMISSION), 0); 96 | mUsbManager.requestPermission(usbDevice, pendingIntent); 97 | } 98 | } 99 | 100 | /** 101 | * USB设备连接 102 | * 103 | * @param usbDevice 104 | */ 105 | @Override 106 | public void connectDevice(UsbDevice usbDevice) { 107 | LogUtil.i("connectDevice"); 108 | closeDevice(usbDevice); 109 | UsbDeviceConnection connection = mUsbManager.openDevice(usbDevice); 110 | if (connection != null) { 111 | mConnectionMap.put(usbDevice, connection); 112 | } 113 | if (mConnectListener != null) { 114 | mConnectListener.onConnected(usbDevice, connection != null); 115 | } 116 | } 117 | 118 | /** 119 | * 断开USB设备连接 120 | * 121 | * @param usbDevice 122 | */ 123 | @Override 124 | public void closeDevice(UsbDevice usbDevice) { 125 | LogUtil.i("closeDevice"); 126 | UsbDeviceConnection connection = mConnectionMap.get(usbDevice); 127 | if (connection != null) { 128 | connection.close(); 129 | mConnectionMap.remove(connection); 130 | } 131 | } 132 | 133 | /** 134 | * UsbDeviceConnection 135 | * 136 | * @param usbDevice 137 | * @return 138 | */ 139 | @Override 140 | public UsbDeviceConnection getConnection(UsbDevice usbDevice) { 141 | return mConnectionMap.get(usbDevice); 142 | } 143 | 144 | /** 145 | * 查找指定、过滤的设备 146 | */ 147 | @Override 148 | public void checkTargetDevice() { 149 | LogUtil.i("checkDevice"); 150 | UsbDevice usbDevice = getTargetDevice(); 151 | if (usbDevice != null && mConnectListener != null) { 152 | mConnectListener.onAttached(usbDevice); 153 | } 154 | } 155 | 156 | /** 157 | * 是否存在指定USB设备 158 | * 159 | * @return 160 | */ 161 | @Override 162 | public boolean hasTargetDevice() { 163 | return getTargetDevice() != null; 164 | } 165 | 166 | /** 167 | * 获取指定USB设备 168 | * 169 | * @return 170 | */ 171 | public UsbDevice getTargetDevice() { 172 | HashMap deviceMap = mUsbManager.getDeviceList(); 173 | if (deviceMap != null) { 174 | for (UsbDevice usbDevice : deviceMap.values()) { 175 | if (isTargetDevice(usbDevice)) { 176 | LogUtil.i("Find target device"); 177 | return usbDevice; 178 | } 179 | } 180 | } 181 | LogUtil.i("No target device"); 182 | return null; 183 | } 184 | 185 | /** 186 | * 是否目标设备,是相机并且产品id和供应商id跟配置的一致 187 | * 188 | * @param usbDevice 189 | * @return 190 | */ 191 | public boolean isTargetDevice(UsbDevice usbDevice) { 192 | if (deviceFilter != null) { 193 | return deviceFilter.isTargetDevice(usbDevice); 194 | } 195 | return false; 196 | } 197 | 198 | /** 199 | * 设置USB连接监听器 200 | * 201 | * @param listen 202 | */ 203 | public void setUsbConnectListen(UsbConnectListener listen) { 204 | this.mConnectListener = listen; 205 | } 206 | 207 | /** 208 | * 设置设备过滤器 209 | * 210 | * @param deviceFilter 211 | * @return 212 | */ 213 | public UsbManagerUtil setDeviceFilter(IDeviceFilter deviceFilter) { 214 | this.deviceFilter = deviceFilter; 215 | return this; 216 | } 217 | 218 | /** 219 | * usb插拔广播监听类 220 | */ 221 | private class USBReceiver extends BroadcastReceiver { 222 | @Override 223 | public void onReceive(Context context, Intent intent) { 224 | UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); 225 | LogUtil.i("usbDevice-->" + usbDevice); 226 | if (!isTargetDevice(usbDevice) || mConnectListener == null) { 227 | return; 228 | } 229 | 230 | switch (intent.getAction()) { 231 | case UsbManager.ACTION_USB_DEVICE_ATTACHED: 232 | LogUtil.i("onAttached"); 233 | mConnectListener.onAttached(usbDevice); 234 | break; 235 | 236 | case ACTION_USB_DEVICE_PERMISSION: 237 | boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false); 238 | LogUtil.i("onGranted-->" + granted); 239 | mConnectListener.onGranted(usbDevice, granted); 240 | break; 241 | 242 | case UsbManager.ACTION_USB_DEVICE_DETACHED: 243 | LogUtil.i("onDetached"); 244 | mConnectListener.onDetached(usbDevice); 245 | break; 246 | 247 | default: 248 | break; 249 | } 250 | } 251 | } 252 | 253 | } 254 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/utils/LogUtil.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (C) 2017 HET, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.lgh.commonusbserialsdk.utils; 20 | 21 | import android.text.TextUtils; 22 | import android.util.Log; 23 | 24 | /** 25 | *

描述:Log工具,类似android.util.Log。

26 | * tag自动产生,格式: customTagPrefix:className.methodName(L:lineNumber), 27 | * customTagPrefix为空时只输出:className.methodName(L:lineNumber)。 28 | *

29 | * 30 | * @author ~若相惜 31 | * @version v1.0 32 | * @date 2015-8-25 下午1:57:44 33 | */ 34 | public class LogUtil { 35 | 36 | public static String customTagPrefix = "HetCommonUsbSerialSdk"; 37 | 38 | private LogUtil() { 39 | } 40 | 41 | public static boolean allowD = true; 42 | public static boolean allowE = true; 43 | public static boolean allowI = true; 44 | public static boolean allowV = true; 45 | public static boolean allowW = true; 46 | public static boolean allowWtf = true; 47 | 48 | private static String generateTag(StackTraceElement caller) { 49 | String tag = "%s.%s(L:%d)"; 50 | String callerClazzName = caller.getClassName(); 51 | callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1); 52 | tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber()); 53 | tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":" + tag; 54 | return tag; 55 | } 56 | 57 | public static CustomLogger customLogger; 58 | 59 | public interface CustomLogger { 60 | void d(String tag, String content); 61 | 62 | void d(String tag, String content, Throwable tr); 63 | 64 | void e(String tag, String content); 65 | 66 | void e(String tag, String content, Throwable tr); 67 | 68 | void i(String tag, String content); 69 | 70 | void i(String tag, String content, Throwable tr); 71 | 72 | void v(String tag, String content); 73 | 74 | void v(String tag, String content, Throwable tr); 75 | 76 | void w(String tag, String content); 77 | 78 | void w(String tag, String content, Throwable tr); 79 | 80 | void w(String tag, Throwable tr); 81 | 82 | void wtf(String tag, String content); 83 | 84 | void wtf(String tag, String content, Throwable tr); 85 | 86 | void wtf(String tag, Throwable tr); 87 | } 88 | 89 | public static void d(String content) { 90 | if (!allowD) return; 91 | StackTraceElement caller = getCallerStackTraceElement(); 92 | String tag = generateTag(caller); 93 | 94 | if (customLogger != null) { 95 | customLogger.d(tag, content); 96 | } else { 97 | Log.d(tag, content); 98 | } 99 | } 100 | 101 | public static StackTraceElement getCallerStackTraceElement() { 102 | return Thread.currentThread().getStackTrace()[4]; 103 | } 104 | 105 | public static void d(String content, Throwable tr) { 106 | if (!allowD) return; 107 | StackTraceElement caller = getCallerStackTraceElement(); 108 | String tag = generateTag(caller); 109 | 110 | if (customLogger != null) { 111 | customLogger.d(tag, content, tr); 112 | } else { 113 | Log.d(tag, content, tr); 114 | } 115 | } 116 | 117 | public static void e(String content) { 118 | if (!allowE) return; 119 | StackTraceElement caller = getCallerStackTraceElement(); 120 | String tag = generateTag(caller); 121 | 122 | if (customLogger != null) { 123 | customLogger.e(tag, content); 124 | } else { 125 | Log.e(tag, content); 126 | } 127 | } 128 | 129 | public static void e(String content, Throwable tr) { 130 | if (!allowE) return; 131 | StackTraceElement caller = getCallerStackTraceElement(); 132 | String tag = generateTag(caller); 133 | 134 | if (customLogger != null) { 135 | customLogger.e(tag, content, tr); 136 | } else { 137 | Log.e(tag, content, tr); 138 | } 139 | } 140 | 141 | public static void i(String content) { 142 | if (!allowI) return; 143 | StackTraceElement caller = getCallerStackTraceElement(); 144 | String tag = generateTag(caller); 145 | 146 | if (customLogger != null) { 147 | customLogger.i(tag, content); 148 | } else { 149 | Log.i(tag, content); 150 | } 151 | } 152 | 153 | public static void i(String content, Throwable tr) { 154 | if (!allowI) return; 155 | StackTraceElement caller = getCallerStackTraceElement(); 156 | String tag = generateTag(caller); 157 | 158 | if (customLogger != null) { 159 | customLogger.i(tag, content, tr); 160 | } else { 161 | Log.i(tag, content, tr); 162 | } 163 | } 164 | 165 | public static void v(String content) { 166 | if (!allowV) return; 167 | StackTraceElement caller = getCallerStackTraceElement(); 168 | String tag = generateTag(caller); 169 | 170 | if (customLogger != null) { 171 | customLogger.v(tag, content); 172 | } else { 173 | Log.v(tag, content); 174 | } 175 | } 176 | 177 | public static void v(String content, Throwable tr) { 178 | if (!allowV) return; 179 | StackTraceElement caller = getCallerStackTraceElement(); 180 | String tag = generateTag(caller); 181 | 182 | if (customLogger != null) { 183 | customLogger.v(tag, content, tr); 184 | } else { 185 | Log.v(tag, content, tr); 186 | } 187 | } 188 | 189 | public static void w(String content) { 190 | if (!allowW) return; 191 | StackTraceElement caller = getCallerStackTraceElement(); 192 | String tag = generateTag(caller); 193 | 194 | if (customLogger != null) { 195 | customLogger.w(tag, content); 196 | } else { 197 | Log.w(tag, content); 198 | } 199 | } 200 | 201 | public static void w(String content, Throwable tr) { 202 | if (!allowW) return; 203 | StackTraceElement caller = getCallerStackTraceElement(); 204 | String tag = generateTag(caller); 205 | 206 | if (customLogger != null) { 207 | customLogger.w(tag, content, tr); 208 | } else { 209 | Log.w(tag, content, tr); 210 | } 211 | } 212 | 213 | public static void w(Throwable tr) { 214 | if (!allowW) return; 215 | StackTraceElement caller = getCallerStackTraceElement(); 216 | String tag = generateTag(caller); 217 | 218 | if (customLogger != null) { 219 | customLogger.w(tag, tr); 220 | } else { 221 | Log.w(tag, tr); 222 | } 223 | } 224 | 225 | public static void wtf(String content) { 226 | if (!allowWtf) return; 227 | StackTraceElement caller = getCallerStackTraceElement(); 228 | String tag = generateTag(caller); 229 | 230 | if (customLogger != null) { 231 | customLogger.wtf(tag, content); 232 | } else { 233 | Log.wtf(tag, content); 234 | } 235 | } 236 | 237 | public static void wtf(String content, Throwable tr) { 238 | if (!allowWtf) return; 239 | StackTraceElement caller = getCallerStackTraceElement(); 240 | String tag = generateTag(caller); 241 | 242 | if (customLogger != null) { 243 | customLogger.wtf(tag, content, tr); 244 | } else { 245 | Log.wtf(tag, content, tr); 246 | } 247 | } 248 | 249 | public static void wtf(Throwable tr) { 250 | if (!allowWtf) return; 251 | StackTraceElement caller = getCallerStackTraceElement(); 252 | String tag = generateTag(caller); 253 | 254 | if (customLogger != null) { 255 | customLogger.wtf(tag, tr); 256 | } else { 257 | Log.wtf(tag, tr); 258 | } 259 | } 260 | 261 | } 262 | -------------------------------------------------------------------------------- /commonusbserialsdk/src/main/java/com/lgh/commonusbserialsdk/CommonUsbSerialSdk.java: -------------------------------------------------------------------------------- 1 | package com.lgh.commonusbserialsdk; 2 | 3 | import android.content.Context; 4 | import android.hardware.usb.UsbDevice; 5 | 6 | import com.lgh.commonusbserialsdk.listen.UsbConnectListener; 7 | import com.lgh.commonusbserialsdk.listen.UsbSerialListener; 8 | import com.lgh.commonusbserialsdk.thread.BaseThread; 9 | import com.lgh.commonusbserialsdk.thread.ReadThread; 10 | import com.lgh.commonusbserialsdk.thread.WriteThread; 11 | import com.lgh.commonusbserialsdk.usb.UsbManagerUtil; 12 | import com.lgh.commonusbserialsdk.usb.CustomUsbPort; 13 | import com.lgh.commonusbserialsdk.usb.IDeviceFilter; 14 | import com.lgh.commonusbserialsdk.usb.PortType; 15 | import com.lgh.commonusbserialsdk.utils.LogUtil; 16 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 17 | import com.hoho.android.usbserial.driver.UsbSerialPort; 18 | import com.hoho.android.usbserial.driver.UsbSerialProber; 19 | 20 | import java.io.IOException; 21 | 22 | /** 23 | * 描述:HetCommonUsbSerialSdk 24 | * 作者:liugh 25 | * 日期:2021/11/22 26 | * 版本:V1.0.0 27 | */ 28 | public class CommonUsbSerialSdk implements IUsbSerialSdk { 29 | protected UsbManagerUtil mUsbManager; // USB工具类 30 | protected UsbSerialPort mUsbSerialPort; // 串口通信工具类 31 | protected UsbConnectListener mUsbConnectListener; // USB连接监听 32 | protected UsbSerialListener mUsbSerialListener; // 读写数据回调 33 | protected BaseThread mWriteThread; // 数据下发线程 34 | protected BaseThread mReadThread; // 数据接收线程 35 | private int mPort = 0; // 通信端口,一般只有一个 36 | private int mBaudRate = 115200; // 波特率 37 | private int mDataBits = UsbSerialPort.DATABITS_8; // 数据位 38 | private int mStopBits = UsbSerialPort.STOPBITS_1; // 停止位 39 | private int mParity = UsbSerialPort.PARITY_NONE; // 奇偶校验位 40 | private boolean forceGrant; // 是否强制授权,点取消授权会重新弹出授权弹窗,直至授权成功 41 | private PortType mPortType = PortType.USB_TO_SERIAL; // 通信类型 42 | 43 | public CommonUsbSerialSdk(Context context) { 44 | this.mUsbManager = new UsbManagerUtil(context); 45 | } 46 | 47 | public UsbManagerUtil getUsbManager() { 48 | return mUsbManager; 49 | } 50 | 51 | @Override 52 | public boolean hasTargetDevice() { 53 | return mUsbManager.hasTargetDevice(); 54 | } 55 | 56 | /** 57 | * 查找指定设备,适用于没有USB插拔的场景,如连上设备后再进入页面 58 | */ 59 | @Override 60 | public void checkTargetDevice() { 61 | LogUtil.i("checkTargetDevice"); 62 | mUsbManager.registerReceiver(); 63 | mUsbManager.checkTargetDevice(); 64 | } 65 | 66 | /** 67 | * 检查串口驱动 68 | * 69 | * @param usbDevice 70 | */ 71 | public void checkDriver(UsbDevice usbDevice) { 72 | LogUtil.i("checkDriver"); 73 | UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(usbDevice); 74 | if (mUsbConnectListener != null) { 75 | mUsbConnectListener.onDriverFound(usbDevice, driver); 76 | } 77 | } 78 | 79 | /** 80 | * 打开通信端口 81 | * 82 | * @param driver 83 | */ 84 | @Override 85 | public void openSerialPort(UsbSerialDriver driver, UsbDevice usbDevice) { 86 | LogUtil.i("openSerialPort"); 87 | try { 88 | if (mPortType == PortType.USB) { // USB通信,使用USB专用通信端口 89 | mUsbSerialPort = new CustomUsbPort(usbDevice, 0); 90 | } else if (mPortType == PortType.USB_TO_SERIAL) { // USB转串口通信,匹配对应驱动 91 | mUsbSerialPort = driver.getPorts().get(mPort); 92 | } 93 | mUsbSerialPort.open(mUsbManager.getConnection(usbDevice)); 94 | mUsbSerialPort.setParameters(mBaudRate, mDataBits, mStopBits, mParity); 95 | if (mUsbConnectListener != null) { 96 | mUsbConnectListener.onDeviceOpened(usbDevice, true); 97 | } 98 | } catch (Exception e) { 99 | e.printStackTrace(); 100 | if (mUsbConnectListener != null) { 101 | mUsbConnectListener.onDeviceOpened(usbDevice, false); 102 | } 103 | } 104 | } 105 | 106 | /** 107 | * 关闭串口 108 | */ 109 | @Override 110 | public void closeSerialPort() { 111 | LogUtil.i("closeSerialPort"); 112 | try { 113 | if (mUsbSerialPort != null) { 114 | mUsbSerialPort.close(); 115 | mUsbSerialPort = null; 116 | } 117 | } catch (IOException e) { 118 | e.printStackTrace(); 119 | } 120 | stopThread(); 121 | } 122 | 123 | /** 124 | * 启动数据接收线程,写线程在发送第一条指令时再判断启动 125 | */ 126 | @Override 127 | public void startThread() { 128 | if (mReadThread != null && !mReadThread.isStart()) { 129 | LogUtil.i("start read thread"); 130 | mReadThread.start(mUsbSerialPort); 131 | } 132 | if (mWriteThread != null && !mWriteThread.isStart()) { 133 | LogUtil.i("start write thread"); 134 | mWriteThread.start(mUsbSerialPort); 135 | } 136 | } 137 | 138 | /** 139 | * 停止读写线程 140 | */ 141 | @Override 142 | public void stopThread() { 143 | LogUtil.i("stop thread"); 144 | if (mReadThread != null) { 145 | mReadThread.stop(); 146 | } 147 | if (mWriteThread != null) { 148 | mWriteThread.stop(); 149 | } 150 | } 151 | 152 | /** 153 | * 发送指令 154 | * 155 | * @param src 156 | */ 157 | @Override 158 | public void write(byte[] bytes) { 159 | if (mUsbSerialPort == null) { 160 | LogUtil.e("UsbSerialPort can not be null!"); 161 | checkTargetDevice(); 162 | return; 163 | } 164 | if (bytes == null) { 165 | LogUtil.e("bytes can not be null!"); 166 | return; 167 | } 168 | startThread(); 169 | if (mWriteThread != null) { 170 | mWriteThread.write(bytes); 171 | } else { 172 | LogUtil.e("WriteThread can not be null!"); 173 | } 174 | } 175 | 176 | /** 177 | * 关闭串口设备 178 | */ 179 | @Override 180 | public void release() { 181 | LogUtil.i("release"); 182 | closeSerialPort(); 183 | mUsbManager.unregisterReceiver(); 184 | } 185 | 186 | /** 187 | * 设置USB连接监听器 188 | * 189 | * @param listener 190 | * @return 191 | */ 192 | public CommonUsbSerialSdk setUsbConnectListener(UsbConnectListener listener) { 193 | this.mUsbConnectListener = listener; 194 | mUsbManager.setUsbConnectListen(listener); 195 | return this; 196 | } 197 | 198 | /** 199 | * 串口数据收发回调 200 | * 201 | * @param listener 202 | * @return 203 | */ 204 | public CommonUsbSerialSdk setUsbSerialListener(UsbSerialListener listener) { 205 | this.mUsbSerialListener = listener; 206 | return this; 207 | } 208 | 209 | /** 210 | * 设置数据下发线程,不设置则使用默认 211 | * 212 | * @param writeThread 213 | * @return 214 | */ 215 | public CommonUsbSerialSdk setWriteThread(BaseThread writeThread) { 216 | this.mWriteThread = writeThread; 217 | return this; 218 | } 219 | 220 | /** 221 | * 设置数据接收线程,不设置则使用默认 222 | * 223 | * @param readThread 224 | * @return 225 | */ 226 | public CommonUsbSerialSdk setReadThread(BaseThread readThread) { 227 | this.mReadThread = readThread; 228 | return this; 229 | } 230 | 231 | /** 232 | * 设备过滤 233 | * 234 | * @param filter 235 | * @return 236 | */ 237 | public CommonUsbSerialSdk setDeviceFilter(IDeviceFilter filter) { 238 | mUsbManager.setDeviceFilter(filter); 239 | return this; 240 | } 241 | 242 | /** 243 | * 通信端口,一般只有一个 244 | * 245 | * @param port 246 | * @return 247 | */ 248 | public CommonUsbSerialSdk setPort(int port) { 249 | this.mPort = port; 250 | return this; 251 | } 252 | 253 | /** 254 | * 波特率 255 | * 256 | * @param baudRate 257 | * @return 258 | */ 259 | public CommonUsbSerialSdk setBaudRate(int baudRate) { 260 | this.mBaudRate = baudRate; 261 | return this; 262 | } 263 | 264 | /** 265 | * 数据位 266 | * 267 | * @param dataBits 268 | * @return 269 | */ 270 | public CommonUsbSerialSdk setDataBits(int dataBits) { 271 | this.mDataBits = dataBits; 272 | return this; 273 | } 274 | 275 | /** 276 | * 停止位 277 | * 278 | * @param stopBits 279 | * @return 280 | */ 281 | public CommonUsbSerialSdk setStopBits(int stopBits) { 282 | this.mStopBits = stopBits; 283 | return this; 284 | } 285 | 286 | /** 287 | * 奇偶检验位 288 | * 289 | * @param parity 290 | * @return 291 | */ 292 | public CommonUsbSerialSdk setParity(@UsbSerialPort.Parity int parity) { 293 | this.mParity = parity; 294 | return this; 295 | } 296 | 297 | /** 298 | * 是否强制授权 299 | * 300 | * @param forceGrant 301 | * @return 302 | */ 303 | public CommonUsbSerialSdk setForceGrant(boolean forceGrant) { 304 | this.forceGrant = forceGrant; 305 | return this; 306 | } 307 | 308 | /** 309 | * 设置通信类型,USB通信或者USB转串口通信 310 | * 311 | * @param portType 312 | * @return 313 | */ 314 | public CommonUsbSerialSdk setPortType(PortType portType) { 315 | this.mPortType = portType; 316 | return this; 317 | } 318 | 319 | /** 320 | * 非必需,调用该方法即使用默认流程,不调用则需自己处理相关流程 321 | * 322 | * @return 323 | */ 324 | public CommonUsbSerialSdk create() { 325 | if (mUsbConnectListener == null) { 326 | mUsbConnectListener = getDefaultUsbConnectListener(); 327 | mUsbManager.setUsbConnectListen(mUsbConnectListener); 328 | } 329 | if (mWriteThread == null) { 330 | mWriteThread = new WriteThread(mUsbSerialListener); 331 | } 332 | if (mReadThread == null) { 333 | mReadThread = new ReadThread(mUsbSerialListener); 334 | } 335 | return this; 336 | } 337 | 338 | /** 339 | * 默认listener,默认使用通用连接流程 340 | * 341 | * @return 342 | */ 343 | protected UsbConnectListener getDefaultUsbConnectListener() { 344 | return new DefaultUsbConnectListener(); 345 | } 346 | 347 | /** 348 | * 默认listener,默认使用通用连接流程 349 | * 1.查找设备 2.授权 3.连接 4.检查驱动 5.打开串口 6.开启数据接收线程 350 | */ 351 | protected class DefaultUsbConnectListener implements UsbConnectListener { 352 | @Override 353 | public void onAttached(UsbDevice usbDevice) { 354 | mUsbManager.requestPermission(usbDevice); 355 | } 356 | 357 | @Override 358 | public void onGranted(UsbDevice usbDevice, boolean granted) { 359 | if (granted) { 360 | mUsbManager.connectDevice(usbDevice); 361 | } else { 362 | if (forceGrant) { 363 | mUsbManager.requestPermission(usbDevice); 364 | } 365 | } 366 | } 367 | 368 | @Override 369 | public void onConnected(UsbDevice usbDevice, boolean connected) { 370 | if (connected) { 371 | if (mPortType == PortType.USB) { // USB通信,连接成功直接打开串口,不需要驱动 372 | openSerialPort(null, usbDevice); 373 | } else if (mPortType == PortType.USB_TO_SERIAL) { // USB转串口通信,连接成功检查驱动 374 | checkDriver(usbDevice); 375 | } 376 | } 377 | } 378 | 379 | @Override 380 | public void onDriverFound(UsbDevice usbDevice, UsbSerialDriver driver) { 381 | if (driver != null) { 382 | openSerialPort(driver, usbDevice); 383 | } 384 | } 385 | 386 | @Override 387 | public void onDeviceOpened(UsbDevice usbDevice, boolean success) { 388 | } 389 | 390 | @Override 391 | public void onDetached(UsbDevice usbDevice) { 392 | closeSerialPort(); 393 | } 394 | } 395 | 396 | } 397 | --------------------------------------------------------------------------------