├── .gitignore
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── top
│ │ └── maybesix
│ │ └── demo
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── top
│ │ │ └── maybesix
│ │ │ └── demo
│ │ │ └── MainActivity.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.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
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── top
│ └── maybesix
│ └── demo
│ └── ExampleUnitTest.kt
├── build.gradle
├── easyserialport
├── .gitignore
├── CMakeLists.txt
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── cpp
│ ├── SerialPort.c
│ └── SerialPort.h
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ ├── android_serialport_api
│ ├── SerialPort.java
│ └── SerialPortFinder.java
│ └── top
│ └── maybesix
│ └── easyserialport
│ ├── ComPortData.java
│ ├── EasySerialPort.java
│ └── util
│ ├── CrcUtils.java
│ └── HexStringUtils.java
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android-EasySerialPort
2 | 非常好用、非常稳定的Android串口封装
3 | 久经两年多项目考验,一直很稳定
4 | ## 使用说明
5 | 第一步,在gradle(Project)下添加
6 | ```
7 | allprojects {
8 | repositories {
9 | ...
10 | maven { url 'https://www.jitpack.io' }
11 | }
12 | }
13 | ```
14 | 第二步,导入依赖
15 | ```
16 | dependencies {
17 | implementation 'com.github.maybesix:Android-XHLibrary:v1.0.0'
18 | }
19 | ```
20 | 在需要实现Activity或者Service中这样写:
21 |
22 | ```
23 | SerialPortHelper serialPort;
24 | String port = "/dev/ttyHSL1";
25 | int baudRate = 9600;
26 | //串口程序初始化
27 | serialPort = new SerialPortHelper(port, baudRate, this);
28 | //打开串口
29 | serialPort.open();
30 | ```
31 | 串口发送:
32 | ```
33 | //发送十六进制
34 | serialPort.sendHex("A55A0010002096");
35 | //发送文本
36 | serialPort.sendHex("hello world");
37 | ```
38 | 串口接收:实现SerialPortHelper.OnSerialPortReceivedListener接口
39 | ```
40 | public class MainActivity extends AppCompatActivity implements SerialPortHelper.OnSerialPortReceivedListener {
41 | ...
42 | @Override
43 | protected void onCreate(Bundle savedInstanceState) {
44 | super.onCreate(savedInstanceState);
45 | ...
46 | }
47 | ...
48 | @Override
49 | public void onSerialPortDataReceived(ComPortData comPortData) {
50 | //处理接收的串口消息
51 | String s = HexStringUtils.byteArray2HexString(comPortData.getRecData());
52 | Log.i(TAG, "onReceived: " + s);
53 | }
54 | }
55 | ```
56 | 或者可以使用构造者链式调用(kotlin写法)
57 | ```
58 | serialPort = EasySerialPort.Builder()
59 | .setBaudRate(9600)
60 | .setPort("")
61 | .setSatesListener(object : EasySerialPort.OnStatesChangeListener {
62 | /**
63 | * 打开的状态回调
64 | *
65 | * @param isSuccess 是否成功
66 | * @param reason 原因
67 | */
68 | override fun onOpen(isSuccess: Boolean, reason: String) {
69 | Log.i("EasySerialPort", "是否开启成功:$isSuccess,原因:$reason")
70 | Toast.makeText(
71 | applicationContext,
72 | "是否开启成功:$isSuccess,原因:$reason",
73 | Toast.LENGTH_SHORT
74 | ).show()
75 |
76 | }
77 |
78 | /**
79 | * 关闭的状态回调
80 | */
81 | override fun onClose() {
82 | Log.i("EasySerialPort", "已关闭")
83 | Toast.makeText(applicationContext, "已关闭", Toast.LENGTH_SHORT).show()
84 | }
85 | })
86 | .setListener {
87 | //处理接收的串口消息
88 | val s: String = HexStringUtils.byteArray2HexString(it.recData)
89 | Log.i("EasySerialPort", "onReceived: $s,time:${it.recTime}")
90 | textView.text = s
91 | }
92 | .build()
93 | ```
94 | 至此,串口的打开、发送、接收就全部完成了。
95 | ## 串口相关
96 | > 串口操作类 → [SerialPortHelper](https://github.com/maybesix/Android-XHLibrary/blob/master/XHLibrary/src/main/java/top/maybesix/xhlibrary/serialport/SerialPortHelper.java)
97 | ```
98 | isOpen : 是否开启串口
99 | getBaudRate : 获取波特率
100 | setBaudRate : 设置波特率
101 | getPort : 获取串口名称
102 | setPort : 设置串口名称
103 | open : 打开串口
104 | close : 关闭串口
105 | sendHex : 以16进制发送
106 | sendTxtString : 以文本发送
107 | getLoopData : 获取循环发送的数据
108 | setLoopData : 设置循环发送的数据
109 | getDelay : 获取延迟
110 | setDelay : 设置延时(毫秒)
111 | startSend : 开启循环发送
112 | stopSend : 停止循环发送
113 | OnSerialPortReceivedListener : 串口数据接收回调
114 | ```
115 | > 串口数据基类 → [ComPortData](https://github.com/maybesix/Android-XHLibrary/blob/master/XHLibrary/src/main/java/top/maybesix/xhlibrary/serialport/ComPortData.java)
116 | ```
117 | getRecData : 获取串口数据
118 | setRecData : 设置串口数据
119 | getRecTime : 获取接收时间
120 | setRecTime : 设置接受时间
121 | getComPort : 获取串口名称
122 | setComPort : 设置串口名称
123 | ```
124 | ## 串口数据处理相关
125 | > 十六进制转换 → [HexStringUtils](https://github.com/maybesix/Android-XHLibrary/blob/master/XHLibrary/src/main/java/top/maybesix/xhlibrary/util/HexStringUtils.java)
126 | ```
127 | isOdd : 判断是否为奇数
128 | hexString2Int : 16进制字符串转int
129 | hexString2Byte : 16进制字符串转byte
130 | byte2HexString : byte转16进制字符串
131 | byteArray2HexString : byte数组转16进制字符串
132 | hexString2ByteArray : 16进制字符串转byte数组
133 | ```
134 | > CRC校验 → [CrcUtils](https://github.com/maybesix/Android-XHLibrary/blob/master/XHLibrary/src/main/java/top/maybesix/xhlibrary/util/CrcUtils.java)
135 | ```
136 | isPassCRC : 返回是否通过验证
137 | getCrcString : 获取16进制的crc字符串
138 | toHexString : int转16进制字符串
139 | getCrc : 传入bytes,计算得到CRC验证码
140 | hexToByte : 16进制字符串转byte数组
141 | ```
142 |
143 | ## 项目更新内容:
144 | ### v1.1:
145 |
146 | 1. 升级至androidx
147 | 2. 去除不必要的依赖
148 | 3. 支持链式调用配置监听事件、设置端口号、设置波特率
149 | 4. 修改串口接收数据时格式化时间,现在改为时间戳
150 |
151 | ## 如果这个项目对你有帮助,请点个star!
152 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 29
7 | buildToolsVersion "29.0.3"
8 |
9 | defaultConfig {
10 | applicationId "top.maybesix.demo"
11 | minSdkVersion 19
12 | targetSdkVersion 29
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 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
31 | implementation 'androidx.appcompat:appcompat:1.1.0'
32 | implementation 'androidx.core:core-ktx:1.2.0'
33 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
34 | //引入串口库
35 | implementation project(':easyserialport')
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/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
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/top/maybesix/demo/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package top.maybesix.demo
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("top.maybesix.demo", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/top/maybesix/demo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package top.maybesix.demo
2 |
3 | import android.os.Bundle
4 | import android.util.Log
5 | import android.widget.Toast
6 | import androidx.appcompat.app.AppCompatActivity
7 | import kotlinx.android.synthetic.main.activity_main.*
8 | import top.maybesix.easyserialport.EasySerialPort
9 | import top.maybesix.easyserialport.util.HexStringUtils
10 |
11 | class MainActivity : AppCompatActivity() {
12 | private lateinit var serialPort: EasySerialPort
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 | setContentView(R.layout.activity_main)
16 | //初始化
17 | serialPort = EasySerialPort.Builder()
18 | .setBaudRate(9600)
19 | .setPort("")
20 | .setSatesListener(object : EasySerialPort.OnStatesChangeListener {
21 | /**
22 | * 打开的状态回调
23 | *
24 | * @param isSuccess 是否成功
25 | * @param reason 原因
26 | */
27 | override fun onOpen(isSuccess: Boolean, reason: String) {
28 | Log.i("EasySerialPort", "是否开启成功:$isSuccess,原因:$reason")
29 | Toast.makeText(
30 | applicationContext,
31 | "是否开启成功:$isSuccess,原因:$reason",
32 | Toast.LENGTH_SHORT
33 | ).show()
34 |
35 | }
36 |
37 | /**
38 | * 关闭的状态回调
39 | */
40 | override fun onClose() {
41 | Log.i("EasySerialPort", "已关闭")
42 | Toast.makeText(applicationContext, "已关闭", Toast.LENGTH_SHORT).show()
43 | }
44 | })
45 | .setListener {
46 | //处理接收的串口消息
47 | val s: String = HexStringUtils.byteArray2HexString(it.recData)
48 | Log.i("EasySerialPort", "onReceived: $s,time:${it.recTime}")
49 | textView.text = s
50 | }
51 | .build()
52 |
53 | btn_open.setOnClickListener {
54 | serialPort.open()
55 | }
56 | btn_close.setOnClickListener {
57 | serialPort.close()
58 | }
59 | btn_send.setOnClickListener {
60 | if (serialPort.isNotOpen) {
61 | Toast.makeText(applicationContext, "请先开启串口", Toast.LENGTH_SHORT).show()
62 | } else {
63 | Toast.makeText(
64 | applicationContext,
65 | "发送:${et_send.text.toString()}",
66 | Toast.LENGTH_SHORT
67 | ).show()
68 | serialPort.sendTxtString(et_send.text.toString())
69 | }
70 | }
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
12 |
13 |
17 |
18 |
23 |
24 |
32 |
33 |
41 |
42 |
49 |
50 |
55 |
60 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Android-EasySerialPort
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/top/maybesix/demo/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package top.maybesix.demo
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.71'
5 | repositories {
6 | google()
7 | jcenter()
8 |
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:3.6.1'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 |
14 | // NOTE: Do not place your application dependencies here; they belong
15 | // in the individual module build.gradle files
16 | }
17 | }
18 |
19 | allprojects {
20 | repositories {
21 | google()
22 | jcenter()
23 |
24 | }
25 | }
26 |
27 | task clean(type: Delete) {
28 | delete rootProject.buildDir
29 | }
30 |
--------------------------------------------------------------------------------
/easyserialport/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/easyserialport/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Sets the minimum version of CMake required to build the native
2 | # library. You should either keep the default value or only pass a
3 | # value of 3.4.0 or lower.
4 |
5 | cmake_minimum_required(VERSION 3.4.1)
6 |
7 | # Creates and names a library, sets it as either STATIC
8 | # or SHARED, and provides the relative paths to its source code.
9 | # You can define multiple libraries, and CMake builds it for you.
10 | # Gradle automatically packages shared libraries with your APK.
11 |
12 | add_library( # Sets the name of the library.
13 | SerialPort
14 |
15 | # Sets the library as a shared library.
16 | SHARED
17 |
18 | # Provides a relative path to your source file(s).
19 | # Associated headers in the same location as their source
20 | # file are automatically included.
21 | src/main/cpp/SerialPort.c )
22 |
23 | # Searches for a specified prebuilt library and stores the path as a
24 | # variable. Because system libraries are included in the search path by
25 | # default, you only need to specify the name of the public NDK library
26 | # you want to add. CMake verifies that the library exists before
27 | # completing its build.
28 |
29 | find_library( # Sets the name of the path variable.
30 | log-lib
31 |
32 | # Specifies the name of the NDK library that
33 | # you want CMake to locate.
34 | log )
35 |
36 | # Specifies libraries CMake should link to your target library. You
37 | # can link multiple libraries, such as libraries you define in the
38 | # build script, prebuilt third-party libraries, or system libraries.
39 |
40 | target_link_libraries( # Specifies the target library.
41 | SerialPort
42 |
43 | # Links the target library to the log library
44 | # included in the NDK.
45 | ${log-lib} )
46 |
--------------------------------------------------------------------------------
/easyserialport/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 29
5 | buildToolsVersion "29.0.3"
6 |
7 | defaultConfig {
8 | minSdkVersion 19
9 | targetSdkVersion 29
10 | versionCode 2
11 | versionName "1.1"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles 'consumer-rules.pro'
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | }
29 |
--------------------------------------------------------------------------------
/easyserialport/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/easyserialport/consumer-rules.pro
--------------------------------------------------------------------------------
/easyserialport/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
22 |
--------------------------------------------------------------------------------
/easyserialport/src/cpp/SerialPort.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2011 Cedric Priscal
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #include
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 |
25 | #include "SerialPort.h"
26 |
27 | #include "android/log.h"
28 | static const char *TAG="serial_port";
29 | #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
30 | #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
31 | #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
32 |
33 | static speed_t getBaudrate(jint baudrate)
34 | {
35 | switch(baudrate) {
36 | case 0: return B0;
37 | case 50: return B50;
38 | case 75: return B75;
39 | case 110: return B110;
40 | case 134: return B134;
41 | case 150: return B150;
42 | case 200: return B200;
43 | case 300: return B300;
44 | case 600: return B600;
45 | case 1200: return B1200;
46 | case 1800: return B1800;
47 | case 2400: return B2400;
48 | case 4800: return B4800;
49 | case 9600: return B9600;
50 | case 19200: return B19200;
51 | case 38400: return B38400;
52 | case 57600: return B57600;
53 | case 115200: return B115200;
54 | case 230400: return B230400;
55 | case 460800: return B460800;
56 | case 500000: return B500000;
57 | case 576000: return B576000;
58 | case 921600: return B921600;
59 | case 1000000: return B1000000;
60 | case 1152000: return B1152000;
61 | case 1500000: return B1500000;
62 | case 2000000: return B2000000;
63 | case 2500000: return B2500000;
64 | case 3000000: return B3000000;
65 | case 3500000: return B3500000;
66 | case 4000000: return B4000000;
67 | default: return -1;
68 | }
69 | }
70 |
71 | /*
72 | * Class: android_serialport_SerialPort
73 | * Method: open
74 | * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
75 | */
76 | JNIEXPORT jobject JNICALL Java_android_1serialport_1api_SerialPort_open
77 | (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)
78 | {
79 | int fd;
80 | speed_t speed;
81 | jobject mFileDescriptor;
82 |
83 | /* Check arguments */
84 | {
85 | speed = getBaudrate(baudrate);
86 | if (speed == -1) {
87 | /* TODO: throw an exception */
88 | LOGE("Invalid baudrate");
89 | return NULL;
90 | }
91 | }
92 |
93 | /* Opening device */
94 | {
95 | jboolean iscopy;
96 | const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
97 | LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);
98 | fd = open(path_utf, O_RDWR | flags);
99 | LOGD("open() fd = %d", fd);
100 | (*env)->ReleaseStringUTFChars(env, path, path_utf);
101 | if (fd == -1)
102 | {
103 | /* Throw an exception */
104 | LOGE("Cannot open port");
105 | /* TODO: throw an exception */
106 | return NULL;
107 | }
108 | }
109 |
110 | /* Configure device */
111 | {
112 | struct termios cfg;
113 | LOGD("Configuring serial port");
114 | if (tcgetattr(fd, &cfg))
115 | {
116 | LOGE("tcgetattr() failed");
117 | close(fd);
118 | /* TODO: throw an exception */
119 | return NULL;
120 | }
121 |
122 | cfmakeraw(&cfg);
123 | cfsetispeed(&cfg, speed);
124 | cfsetospeed(&cfg, speed);
125 |
126 | //此处设置校验位
127 | //cfg.c_cflag……
128 |
129 | if (tcsetattr(fd, TCSANOW, &cfg))
130 | {
131 | LOGE("tcsetattr() failed");
132 | close(fd);
133 | /* TODO: throw an exception */
134 | return NULL;
135 | }
136 | }
137 |
138 | /* Create a corresponding file descriptor */
139 | {
140 | jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
141 | jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "", "()V");
142 | jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
143 | mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
144 | (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
145 | }
146 |
147 | return mFileDescriptor;
148 | }
149 |
150 | /*
151 | * Class: cedric_serial_SerialPort
152 | * Method: close
153 | * Signature: ()V
154 | */
155 | JNIEXPORT void JNICALL Java_android_1serialport_1api_SerialPort_close
156 | (JNIEnv *env, jobject thiz)
157 | {
158 | jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
159 | jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");
160 |
161 | jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
162 | jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");
163 |
164 | jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
165 | jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);
166 |
167 | LOGD("close(fd = %d)", descriptor);
168 | close(descriptor);
169 | }
170 |
171 |
--------------------------------------------------------------------------------
/easyserialport/src/cpp/SerialPort.h:
--------------------------------------------------------------------------------
1 | /* DO NOT EDIT THIS FILE - it is machine generated */
2 | #include
3 | /* Header for class android_serialport_api_SerialPort */
4 |
5 | #ifndef _Included_android_serialport_api_SerialPort
6 | #define _Included_android_serialport_api_SerialPort
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 | /*
11 | * Class: android_serialport_api_SerialPort
12 | * Method: open
13 | * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
14 | */
15 | JNIEXPORT jobject JNICALL Java_android_1serialport_1api_SerialPort_open
16 | (JNIEnv *, jclass, jstring, jint, jint);
17 |
18 | /*
19 | * Class: android_serialport_api_SerialPort
20 | * Method: close
21 | * Signature: ()V
22 | */
23 | JNIEXPORT void JNICALL Java_android_1serialport_1api_SerialPort_close
24 | (JNIEnv *, jobject);
25 |
26 | #ifdef __cplusplus
27 | }
28 | #endif
29 | #endif
30 |
--------------------------------------------------------------------------------
/easyserialport/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/easyserialport/src/main/java/android_serialport_api/SerialPort.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Cedric Priscal
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package android_serialport_api;
18 |
19 | import android.util.Log;
20 |
21 | import java.io.File;
22 | import java.io.FileDescriptor;
23 | import java.io.FileInputStream;
24 | import java.io.FileOutputStream;
25 | import java.io.IOException;
26 | import java.io.InputStream;
27 | import java.io.OutputStream;
28 |
29 | /**
30 | * @author MaybeSix
31 | */
32 | public class SerialPort {
33 |
34 | private static final String TAG = "SerialPort";
35 |
36 | /**
37 | * Do not remove or rename the field mFd: it is used by native method close();
38 | */
39 | private FileDescriptor mFd;
40 | private FileInputStream mFileInputStream;
41 | private FileOutputStream mFileOutputStream;
42 |
43 | public SerialPort(File device, int baudRate, int flags) throws SecurityException, IOException {
44 |
45 | /* Check access permission */
46 | if (!device.canRead() || !device.canWrite()) {
47 | try {
48 | /* Missing read/write permission, trying to chmod the file */
49 | Process su;
50 | su = Runtime.getRuntime().exec("/system/xbin/su");
51 | String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
52 | + "exit\n";
53 | su.getOutputStream().write(cmd.getBytes());
54 | if ((su.waitFor() != 0) || !device.canRead()
55 | || !device.canWrite()) {
56 | throw new SecurityException();
57 | }
58 | } catch (Exception e) {
59 | e.printStackTrace();
60 | throw new SecurityException();
61 | }
62 | }
63 |
64 | mFd = open(device.getAbsolutePath(), baudRate, flags);
65 | if (mFd == null) {
66 | Log.e(TAG, "native open returns null");
67 | throw new IOException();
68 | }
69 | mFileInputStream = new FileInputStream(mFd);
70 | mFileOutputStream = new FileOutputStream(mFd);
71 | }
72 |
73 | /**
74 | * Getters and setters
75 | */
76 | public InputStream getInputStream() {
77 | return mFileInputStream;
78 | }
79 |
80 | public OutputStream getOutputStream() {
81 | return mFileOutputStream;
82 | }
83 |
84 |
85 | /**
86 | * JNI
87 | */
88 | private native static FileDescriptor open(String path, int baudrate, int flags);
89 | public native void close();
90 | static {
91 | System.loadLibrary("SerialPort");
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/easyserialport/src/main/java/android_serialport_api/SerialPortFinder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Cedric Priscal
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package android_serialport_api;
18 |
19 | import android.util.Log;
20 |
21 | import java.io.File;
22 | import java.io.FileReader;
23 | import java.io.IOException;
24 | import java.io.LineNumberReader;
25 | import java.util.Iterator;
26 | import java.util.Vector;
27 |
28 | /**
29 | * @author MaybeSix
30 | */
31 | public class SerialPortFinder {
32 |
33 | public class Driver {
34 | public Driver(String name, String root) {
35 | mDriverName = name;
36 | mDeviceRoot = root;
37 | }
38 | private String mDriverName;
39 | private String mDeviceRoot;
40 | Vector mDevices = null;
41 | public Vector getDevices() {
42 | if (mDevices == null) {
43 | mDevices = new Vector();
44 | File dev = new File("/dev");
45 | File[] files = dev.listFiles();
46 | int i;
47 | for (i=0; i mDrivers = null;
64 |
65 | Vector getDrivers() throws IOException {
66 | if (mDrivers == null) {
67 | mDrivers = new Vector();
68 | LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
69 | String l;
70 | while((l = r.readLine()) != null) {
71 | // Issue 3:
72 | // Since driver name may contain spaces, we do not extract driver name with split()
73 | String drivername = l.substring(0, 0x15).trim();
74 | String[] w = l.split(" +");
75 | if ((w.length >= 5) && (w[w.length-1].equals("serial"))) {
76 | Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length-4]);
77 | mDrivers.add(new Driver(drivername, w[w.length-4]));
78 | }
79 | }
80 | r.close();
81 | }
82 | return mDrivers;
83 | }
84 |
85 | public String[] getAllDevices() {
86 | Vector devices = new Vector();
87 | // Parse each driver
88 | Iterator itdriv;
89 | try {
90 | itdriv = getDrivers().iterator();
91 | while(itdriv.hasNext()) {
92 | Driver driver = itdriv.next();
93 | Iterator itdev = driver.getDevices().iterator();
94 | while(itdev.hasNext()) {
95 | String device = itdev.next().getName();
96 | String value = String.format("%s (%s)", device, driver.getName());
97 | devices.add(value);
98 | }
99 | }
100 | } catch (IOException e) {
101 | e.printStackTrace();
102 | }
103 | return devices.toArray(new String[devices.size()]);
104 | }
105 |
106 | public String[] getAllDevicesPath() {
107 | Vector devices = new Vector();
108 | // Parse each driver
109 | Iterator itdriv;
110 | try {
111 | itdriv = getDrivers().iterator();
112 | while(itdriv.hasNext()) {
113 | Driver driver = itdriv.next();
114 | Iterator itdev = driver.getDevices().iterator();
115 | while(itdev.hasNext()) {
116 | String device = itdev.next().getAbsolutePath();
117 | devices.add(device);
118 | }
119 | }
120 | } catch (IOException e) {
121 | e.printStackTrace();
122 | }
123 | return devices.toArray(new String[devices.size()]);
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/easyserialport/src/main/java/top/maybesix/easyserialport/ComPortData.java:
--------------------------------------------------------------------------------
1 | package top.maybesix.easyserialport;
2 |
3 | /**
4 | * @author MaybeSix
5 | * @date 2019/3/18
6 | */
7 | public class ComPortData {
8 | private byte[] recData;
9 | private long recTime;
10 | private String comPort;
11 |
12 | ComPortData(String comPort, byte[] buffer, int size) {
13 | this.comPort = comPort;
14 | recData = new byte[size];
15 | System.arraycopy(buffer, 0, recData, 0, size);
16 | recTime = System.currentTimeMillis();
17 | }
18 |
19 | public byte[] getRecData() {
20 | return recData;
21 | }
22 |
23 | public void setRecData(byte[] recData) {
24 | this.recData = recData;
25 | }
26 |
27 | public long getRecTime() {
28 | return recTime;
29 | }
30 |
31 | public void setRecTime(long recTime) {
32 | this.recTime = recTime;
33 | }
34 |
35 | public String getComPort() {
36 | return comPort;
37 | }
38 |
39 | public void setComPort(String comPort) {
40 | this.comPort = comPort;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/easyserialport/src/main/java/top/maybesix/easyserialport/EasySerialPort.java:
--------------------------------------------------------------------------------
1 | package top.maybesix.easyserialport;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.File;
6 | import java.io.IOException;
7 | import java.io.InputStream;
8 | import java.io.OutputStream;
9 | import java.security.InvalidParameterException;
10 |
11 | import android_serialport_api.SerialPort;
12 | import top.maybesix.easyserialport.util.HexStringUtils;
13 |
14 | /**
15 | * @author MaybeSix
16 | */
17 | public class EasySerialPort {
18 | private static final String TAG = "SerialPortHelper";
19 | private SerialPort serialPort;
20 | private OutputStream outputStream;
21 | private InputStream inputStream;
22 | private ReadThread readThread;
23 | private SendThread sendThread;
24 | private boolean openState = false;
25 | private byte[] loopData = new byte[]{0x30};
26 | private int delay = 500;
27 |
28 | /**
29 | * 串口参数
30 | */
31 | private String port;
32 | private int baudRate;
33 | private OnSerialPortReceivedListener onSerialPortReceivedListener;
34 | private OnStatesChangeListener onStatesChangeListener;
35 |
36 |
37 | private EasySerialPort(String port, int baudRate, OnSerialPortReceivedListener listener) {
38 | this.port = port;
39 | this.baudRate = baudRate;
40 | this.onSerialPortReceivedListener = listener;
41 | }
42 |
43 | public static class Builder {
44 | private String port;
45 | private int baudRate = 9600;
46 | private OnSerialPortReceivedListener onSerialPortReceivedListener;
47 | private OnStatesChangeListener onStatesChangeListener;
48 |
49 | public Builder setPort(String port) {
50 | this.port = port;
51 | return this;
52 | }
53 |
54 | public Builder setBaudRate(int baudRate) {
55 | this.baudRate = baudRate;
56 | return this;
57 | }
58 |
59 | public Builder setListener(OnSerialPortReceivedListener onSerialPortReceivedListener) {
60 | this.onSerialPortReceivedListener = onSerialPortReceivedListener;
61 | return this;
62 | }
63 |
64 | public Builder setSatesListener(OnStatesChangeListener onStatesChangeListener) {
65 | this.onStatesChangeListener = onStatesChangeListener;
66 | return this;
67 | }
68 |
69 | public EasySerialPort build() throws Exception {
70 | if (port == null || port.isEmpty()) {
71 | throw new Exception("port is null or empty!");
72 | }
73 | return new EasySerialPort(port, baudRate, onSerialPortReceivedListener);
74 | }
75 | }
76 |
77 | public void setSerialPortReceivedListener(OnSerialPortReceivedListener onSerialPortReceivedListener) {
78 | this.onSerialPortReceivedListener = onSerialPortReceivedListener;
79 | }
80 |
81 | public void setSatesListener(OnStatesChangeListener onStatesChangeListener) {
82 | this.onStatesChangeListener = onStatesChangeListener;
83 | }
84 |
85 | /**
86 | * 是否开启串口
87 | *
88 | * @return
89 | */
90 | public boolean isOpen() {
91 | return openState;
92 | }
93 |
94 | /**
95 | * 是否没有开启串口
96 | *
97 | * @return
98 | */
99 | public boolean isNotOpen() {
100 | return !openState;
101 | }
102 | /**
103 | * 串口打开方法
104 | */
105 | public void open() {
106 | try {
107 | baseOpen();
108 | Log.i(TAG, "打开串口成功!");
109 | onStatesChangeListener.onOpen(true, "");
110 | } catch (SecurityException e) {
111 | Log.e(TAG, "打开串口失败:没有串口读/写权限!");
112 | e.printStackTrace();
113 | onStatesChangeListener.onOpen(false, "没有串口读/写权限!");
114 | } catch (IOException e) {
115 | Log.e(TAG, "打开串口失败:未知错误!");
116 | e.printStackTrace();
117 | onStatesChangeListener.onOpen(false, "未知错误!");
118 | } catch (InvalidParameterException e) {
119 | Log.e(TAG, "打开串口失败:参数错误!");
120 | e.printStackTrace();
121 | onStatesChangeListener.onOpen(false, "参数错误!");
122 | } catch (Exception e) {
123 | Log.e(TAG, "openComPort: 其他错误");
124 | e.printStackTrace();
125 | onStatesChangeListener.onOpen(false, "其他错误!");
126 | }
127 | }
128 |
129 | private void baseOpen() throws SecurityException, IOException, InvalidParameterException {
130 | serialPort = new SerialPort(new File(port), baudRate, 0);
131 | outputStream = serialPort.getOutputStream();
132 | inputStream = serialPort.getInputStream();
133 | readThread = new ReadThread();
134 | readThread.start();
135 | sendThread = new SendThread();
136 | sendThread.setSuspendFlag();
137 | sendThread.start();
138 | openState = true;
139 | }
140 |
141 | /**
142 | * 串口关闭方法
143 | */
144 | public void close() {
145 | if (readThread != null) {
146 | readThread.interrupt();
147 | }
148 | if (serialPort != null) {
149 | serialPort.close();
150 | serialPort = null;
151 | }
152 | openState = false;
153 | onStatesChangeListener.onClose();
154 | }
155 |
156 | /**
157 | * 执行发送程序,若未开启,则会先开启,然后再发送
158 | *
159 | * @param bOutArray
160 | */
161 | private void send(byte[] bOutArray) {
162 | try {
163 | if (openState) {
164 | outputStream.write(bOutArray);
165 | } else {
166 | open();
167 | outputStream.write(bOutArray);
168 | }
169 | } catch (IOException e) {
170 | e.printStackTrace();
171 | }
172 | }
173 |
174 | /**
175 | * 发送十六进制字符串
176 | *
177 | * @param hexString
178 | */
179 | public void sendHex(String hexString) {
180 | byte[] bOutArray = HexStringUtils.hexString2ByteArray(hexString);
181 | send(bOutArray);
182 | }
183 |
184 | /**
185 | * 发送文本
186 | *
187 | * @param txtString
188 | */
189 | public void sendTxtString(String txtString) {
190 | byte[] bOutArray = txtString.getBytes();
191 | send(bOutArray);
192 | }
193 |
194 | private class ReadThread extends Thread {
195 | @Override
196 | public void run() {
197 | super.run();
198 | while (!isInterrupted()) {
199 | try {
200 | if (inputStream == null) {
201 | return;
202 | }
203 | byte[] buffer = new byte[512];
204 | int size = inputStream.read(buffer);
205 | if (size > 0) {
206 | ComPortData comPortData = new ComPortData(port, buffer, size);
207 | onSerialPortReceivedListener.onSerialPortDataReceived(comPortData);
208 | }
209 |
210 | } catch (Throwable e) {
211 | e.printStackTrace();
212 | return;
213 | }
214 | }
215 | }
216 | }
217 |
218 | private class SendThread extends Thread {
219 | /**
220 | * 线程运行标志
221 | */
222 | boolean runFlag = true;
223 |
224 | @Override
225 | public void run() {
226 | super.run();
227 | while (!isInterrupted()) {
228 | synchronized (this) {
229 | while (runFlag) {
230 | try {
231 | wait();
232 | } catch (InterruptedException e) {
233 | e.printStackTrace();
234 | }
235 | }
236 | }
237 | send(getLoopData());
238 | try {
239 | Thread.sleep(delay);
240 | } catch (InterruptedException e) {
241 | e.printStackTrace();
242 | }
243 | }
244 | }
245 |
246 | /**
247 | * 线程暂停
248 | */
249 | private void setSuspendFlag() {
250 | this.runFlag = true;
251 | }
252 |
253 | /**
254 | * 唤醒线程
255 | */
256 | private synchronized void setResume() {
257 | this.runFlag = false;
258 | notify();
259 | }
260 | }
261 |
262 | public int getBaudRate() {
263 | return baudRate;
264 | }
265 |
266 | public boolean setBaudRate(int iBaud) {
267 | if (openState) {
268 | return false;
269 | } else {
270 | baudRate = iBaud;
271 | return true;
272 | }
273 | }
274 |
275 | public boolean setBaudRate(String sBaud) {
276 | int iBaud = Integer.parseInt(sBaud);
277 | return setBaudRate(iBaud);
278 | }
279 |
280 | public String getPort() {
281 | return port;
282 | }
283 |
284 | public boolean setPort(String sPort) {
285 | if (openState) {
286 | return false;
287 | } else {
288 | this.port = sPort;
289 | return true;
290 | }
291 | }
292 |
293 |
294 | public byte[] getLoopData() {
295 | return loopData;
296 | }
297 |
298 | /**
299 | * 设置循环发送的数据
300 | *
301 | * @param loopData byte数据
302 | */
303 | public void setLoopData(byte[] loopData) {
304 | this.loopData = loopData;
305 | }
306 |
307 | /**
308 | * 设置循环发送的数据
309 | *
310 | * @param str 传入的字符串
311 | * @param isHexString 是否为16进制字符串
312 | */
313 | public void setLoopData(String str, boolean isHexString) {
314 | if (isHexString) {
315 | this.loopData = str.getBytes();
316 | } else {
317 | this.loopData = HexStringUtils.hexString2ByteArray(str);
318 | }
319 | }
320 |
321 | /**
322 | * 获取延迟
323 | *
324 | * @return 时间(毫秒)
325 | */
326 | public int getDelay() {
327 | return delay;
328 | }
329 |
330 | /**
331 | * 设置延时(毫秒)
332 | *
333 | * @param delay
334 | */
335 | public void setDelay(int delay) {
336 | this.delay = delay;
337 | }
338 |
339 | /**
340 | * 开启循环发送
341 | */
342 | public void startSend() {
343 | if (sendThread != null) {
344 | sendThread.setResume();
345 | }
346 | }
347 |
348 | /**
349 | * 停止循环发送
350 | */
351 | public void stopSend() {
352 | if (sendThread != null) {
353 | sendThread.setSuspendFlag();
354 | }
355 | }
356 |
357 | /**
358 | * 实现串口数据的接收监听
359 | */
360 | public interface OnSerialPortReceivedListener {
361 | /**
362 | * 串口接收到数据后的回调
363 | *
364 | * @param comPortData 接收到的数据类
365 | */
366 | void onSerialPortDataReceived(ComPortData comPortData);
367 | }
368 |
369 | /**
370 | * 实现串口状态改变
371 | */
372 | public interface OnStatesChangeListener {
373 | /**
374 | * 打开时的回调
375 | *
376 | * @param isSuccess 是否成功
377 | * @param reason 原因
378 | */
379 | void onOpen(boolean isSuccess, String reason);
380 |
381 | /**
382 | * 关闭时的回调
383 | */
384 | void onClose();
385 | }
386 | }
--------------------------------------------------------------------------------
/easyserialport/src/main/java/top/maybesix/easyserialport/util/CrcUtils.java:
--------------------------------------------------------------------------------
1 | package top.maybesix.easyserialport.util;
2 |
3 | /**
4 | * @Author MaybeSix
5 | * @Date 2019/1/13 14:29
6 | * @Version 1.0
7 | * @Description 用于CRC16 CCITT(1024)算法的CRC校验
8 | */
9 | public class CrcUtils {
10 | private static final String TAG = "CrcUtils";
11 |
12 | /**
13 | * 放入完整的bytes数据,返回验证结果
14 | * 例如:{0x5A,0xA5,0xD5,0x01,0x01,0x00,0x00,0x3D,0x44,0x96}
15 | * head:0xA5,0x5A;
16 | * end:0x96;
17 | * bodyAndCrc:0xD5,0x01,0x01,0x00,0x00,0x3D,0x44
18 | * 验证的内容包含:
19 | * 1、验证head是否为:0xA5,0x5A。
20 | * 2、验证end是否为:0x96
21 | * 3、验证getCrc(bodyAndCrc)结果是否为0
22 | * 注:crc验证码有可能高八位和低八位颠倒,所以实际过程中计算两次:
23 | * 一次直接运算,另一次将高低位颠倒过来再运算一次,取或值返回
24 | *
25 | * @param bytes 参与运算的全部串口数据
26 | * @return 结果
27 | */
28 | public static boolean isPassCRC(byte[] bytes) {
29 | int length = bytes.length;
30 | byte[] head = new byte[2];
31 | byte[] end = new byte[1];
32 | byte[] body = new byte[length - 5];
33 | byte valueHead1 = (byte) 0x5A;
34 | byte valueHead2 = (byte) 0xA5;
35 | byte valueEnd = (byte) 0x96;
36 | byte crcLow = bytes[length - 2];
37 | byte crcHigh = bytes[length - 3];
38 | System.arraycopy(bytes, 0, head, 0, 2);
39 | System.arraycopy(bytes, length - 1, end, 0, 1);
40 | System.arraycopy(bytes, 2, body, 0, length - 5);
41 | byte[] bodyAndCrcOne = new byte[body.length + 2];
42 | System.arraycopy(body, 0, bodyAndCrcOne, 0, body.length);
43 | bodyAndCrcOne[body.length] = crcHigh;
44 | bodyAndCrcOne[body.length + 1] = crcLow;
45 | byte[] bodyAndCrcTwo = new byte[body.length + 2];
46 | System.arraycopy(body, 0, bodyAndCrcTwo, 0, body.length);
47 | bodyAndCrcOne[body.length] = crcLow;
48 | bodyAndCrcOne[body.length + 1] = crcHigh;
49 | if (head[0] == valueHead1 && head[1] == valueHead2) {
50 | if (end[0] == valueEnd) {
51 | return getCrc(bodyAndCrcOne) == 0 || getCrc(bodyAndCrcTwo) == 0;
52 | } else {
53 | System.out.println("end校验失败 ");
54 | }
55 | } else {
56 | System.out.println("head校验失败 ");
57 | }
58 | return false;
59 | }
60 |
61 | /**
62 | * 放入完整的hexString数据,返回验证结果
63 | * 例如:"5A A5 D5 01 01 00 00 3D 44 96"
64 | * head:5A A5;
65 | * end:96;
66 | * bodyAndCrc: D5 01 01 00 00 3D 44
67 | * 验证的内容包含:
68 | * 1、验证head是否为:5A A5。
69 | * 2、验证end是否为:96。
70 | * 3、验证getCrc(bodyAndCrc)结果是否为0。
71 | * 注:crc验证码有可能高八位和低八位颠倒,所以实际过程中计算两次:
72 | * 一次直接运算,另一次将高低位颠倒过来再运算一次,取或值返回。
73 | *
74 | * @param hexString 参与运算的全部串口数据
75 | * @return 结果
76 | */
77 | public static boolean isPassCRC(String hexString) {
78 | try {
79 | hexString = hexString.replace(" ", "");
80 | int length = hexString.length();
81 | String head = hexString.substring(0, 4);
82 | String end = hexString.substring(length - 2, length);
83 | String body = hexString.substring(4, length - 6);
84 | String crcHigh = hexString.substring(length - 6, length - 4);
85 | String crcLow = hexString.substring(length - 4, length - 2);
86 | String bodyAndCrcOne = body + crcHigh + crcLow;
87 | String bodyAndCrcTwo = body + crcLow + crcHigh;
88 | String valueHead = "5AA5";
89 | String valueEnd = "96";
90 | if (head.equals(valueHead)) {
91 | if (end.equals(valueEnd)) {
92 | return getCrc(bodyAndCrcOne) == 0 || getCrc(bodyAndCrcTwo) == 0;
93 | } else {
94 | System.out.println("end校验失败 ");
95 | }
96 | } else {
97 | System.out.println("head校验失败 ");
98 | }
99 | } catch (Exception e) {
100 | e.printStackTrace();
101 | return false;
102 | }
103 | return false;
104 | }
105 |
106 | /**
107 | * 获取十六进制的crc字符串
108 | *
109 | * @param hexString String字符串
110 | * @return crc字符串
111 | */
112 | public static String getCrcString(String hexString) {
113 | return toHexString(getCrc(hexString));
114 | }
115 |
116 | /**
117 | * 获取十六进制的crc字符串
118 | *
119 | * @param bytes byte数组
120 | * @return 十六进制crc字符串
121 | */
122 | public static String getCrcString(byte[] bytes) {
123 | return toHexString(getCrc(bytes));
124 | }
125 |
126 | /**
127 | * int转化为十六进制字符串,并且判断十六进制字符串长度是否为4,小于4在高位补零
128 | *
129 | * @param crc 需要转化的int值
130 | * @return 返回十六进制字符串
131 | */
132 | private static String toHexString(int crc) {
133 | String result = Integer.toHexString(crc).toUpperCase();
134 | int length = result.length();
135 | int fixedLength = 4;
136 | if (length != fixedLength) {
137 | for (int i = (fixedLength - length); i > 0; i--) {
138 | result = "0" + result;
139 | }
140 | }
141 | return result;
142 | }
143 |
144 | /**
145 | * 传入bytes,计算得到CRC验证码
146 | *
147 | * @param bytes 参与运算的数组
148 | * @return CRC十六进制字符串的验证码
149 | */
150 | private static int getCrc(byte[] bytes) {
151 | //初始值
152 | int crc = 0xffff;
153 | //公式
154 | int polynomial = 0x1021;
155 | for (byte b : bytes) {
156 | for (int i = 0; i < 8; i++) {
157 | boolean bit = ((b >> (7 - i) & 1) == 1);
158 | boolean c15 = ((crc >> 15 & 1) == 1);
159 | crc <<= 1;
160 | if (c15 ^ bit) {
161 | crc ^= polynomial;
162 | }
163 | }
164 | }
165 | crc &= 0xffff;
166 | return crc;
167 | }
168 |
169 |
170 | /**
171 | * 传入十六进制字符串,计算得到CRC验证码
172 | *
173 | * @param hexString 参与运算的字符串
174 | * @return CRC十六进制字符串的验证码
175 | */
176 | private static int getCrc(String hexString) {
177 | return getCrc(hexToByte(hexString));
178 | }
179 |
180 | /**
181 | * 十六进制字符串转byte数组
182 | * 每两个字符描述一个字节
183 | *
184 | * @param hex 十六进制字符串
185 | * @return 返回byte
186 | */
187 | private static byte[] hexToByte(String hex) {
188 | //去空格
189 | hex = hex.replace(" ", "");
190 | int m = 0, n = 0;
191 | int byteLen = hex.length() / 2;
192 | byte[] ret = new byte[byteLen];
193 | for (int i = 0; i < byteLen; i++) {
194 | m = i * 2 + 1;
195 | n = m + 1;
196 | int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
197 | ret[i] = (byte) intVal;
198 | }
199 | return ret;
200 | }
201 |
202 | }
203 |
--------------------------------------------------------------------------------
/easyserialport/src/main/java/top/maybesix/easyserialport/util/HexStringUtils.java:
--------------------------------------------------------------------------------
1 | package top.maybesix.easyserialport.util;
2 |
3 | /**
4 | * @author MaybeSix
5 | * @date 2019/3/18
6 | */
7 | public class HexStringUtils {
8 | /**
9 | * 判断是否为奇数,位运算,最后一位是1则为奇数,为0是偶数
10 | *
11 | * @param num 传入的int数据
12 | * @return 如果为奇数,返回true;如果为偶数返回false
13 | */
14 | public static boolean isOdd(int num) {
15 | return (num & 0x1) == 1;
16 | }
17 |
18 | /**
19 | * 16进制字符串转int
20 | *
21 | * @param hexString 传入的十六进制字符串
22 | * @return 转换后的结果
23 | */
24 | public static int hexString2Int(String hexString) {
25 | return Integer.parseInt(hexString, 16);
26 | }
27 |
28 | /**
29 | * 16进制字符串转byte
30 | *
31 | * @param hexString 传入的十六进制字符串
32 | * @return 转换后的结果
33 | */
34 | public static byte hexString2Byte(String hexString) {
35 | return (byte) Integer.parseInt(hexString, 16);
36 | }
37 |
38 | /**
39 | * Byte 转 十六进制字符串
40 | *
41 | * @param hexByte 传入的数据
42 | * @return 转换后的结果
43 | */
44 | public static String byte2HexString(Byte hexByte) {
45 | return String.format("%02x", hexByte).toUpperCase();
46 | }
47 |
48 | /**
49 | * 字节数组转hex字符串
50 | *
51 | * @param hexbytearray 传入的数据
52 | * @return 转换后的结果
53 | */
54 | public static String byteArray2HexString(byte[] hexbytearray) {
55 |
56 | return byteArray2HexString(hexbytearray, 0, hexbytearray.length);
57 | }
58 |
59 | /**
60 | * 字节数组转转hex字符串
61 | *
62 | * @param hexbytearray 传入的数据
63 | * @return 转换后的结果
64 | */
65 | public static String byteArray2HexString(byte[] hexbytearray, int beginIndex, int endIndex)//字节数组转转hex字符串,可选长度
66 | {
67 | StringBuilder strBuilder = new StringBuilder();
68 | for (int i = beginIndex; i < endIndex; i++) {
69 | strBuilder.append(byte2HexString(hexbytearray[i]));
70 | }
71 | return strBuilder.toString();
72 | }
73 |
74 | /**
75 | * hex字符串转字节数组
76 | *
77 | * @param hexString 传入的数据
78 | * @return 转换后的结果
79 | */
80 | public static byte[] hexString2ByteArray(String hexString) {
81 | int len = hexString.length();
82 | byte[] result;
83 | if (isOdd(len)) {
84 | //奇数
85 | len++;
86 | result = new byte[(len / 2)];
87 | hexString = "0" + hexString;
88 | } else {
89 | //偶数
90 | result = new byte[(len / 2)];
91 | }
92 | int j = 0;
93 | for (int i = 0; i < len; i += 2) {
94 | result[j] = hexString2Byte(hexString.substring(i, i + 2));
95 | j++;
96 | }
97 | return result;
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/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=-Xmx1536m
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
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maybesix/Android-EasySerialPort/c21e4197dfb91273e677881f0de05af2e0a6e29d/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Mar 30 10:56:02 CST 2020
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-5.6.4-all.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name='Android-EasySerialPort'
2 | include ':app'
3 | include ':easyserialport'
4 |
--------------------------------------------------------------------------------