├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── 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
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── layout
│ │ │ └── activity_main.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── me
│ │ └── f1reking
│ │ └── android_serialport
│ │ └── MainActivity.java
├── proguard-rules.pro
└── build.gradle
├── serialportlib
├── consumer-rules.pro
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ └── values
│ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ └── me
│ │ │ └── f1reking
│ │ │ └── serialportlib
│ │ │ ├── listener
│ │ │ ├── Status.java
│ │ │ ├── ISerialPortDataListener.java
│ │ │ └── IOpenSerialPortListener.java
│ │ │ ├── entity
│ │ │ ├── STOPB.java
│ │ │ ├── PARITY.java
│ │ │ ├── FLOWCON.java
│ │ │ ├── DATAB.java
│ │ │ ├── BAUDRATE.java
│ │ │ ├── Driver.java
│ │ │ └── Device.java
│ │ │ ├── util
│ │ │ └── ByteUtils.java
│ │ │ ├── SerialPortReceivedThread.java
│ │ │ ├── SerialPortFinder.java
│ │ │ └── SerialPortHelper.java
│ │ └── jni
│ │ ├── SerialPort.h
│ │ ├── termios.h
│ │ └── SerialPort.c
├── build.gradle
├── proguard-rules.pro
└── CMakeLists.txt
├── 3.webp
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── jitpack.gradle
├── gradle.properties
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/serialportlib/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/serialportlib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/3.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/3.webp
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':serialportlib'
2 | rootProject.name='Android-SerialPort'
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/serialportlib/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SerialPortLib
3 |
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/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/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/serialportlib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeekBugs/Android-SerialPort/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/GeekBugs/Android-SerialPort/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/GeekBugs/Android-SerialPort/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Apr 19 16:13:52 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 |
--------------------------------------------------------------------------------
/jitpack.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.github.dcendents.android-maven'
2 |
3 | group = 'com.github.f1reking'
4 |
5 | tasks.withType(JavaCompile) {
6 | options.encoding = "UTF-8"
7 | }
8 |
9 | task sourcesJar(type: Jar) {
10 | from android.sourceSets.main.java.srcDirs
11 | classifier = 'sources'
12 | }
13 |
14 | task javadoc(type: Javadoc) {
15 | failOnError false
16 | source = android.sourceSets.main.java.sourceFiles
17 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
18 | classpath += configurations.compile
19 | }
20 |
21 |
22 | task javadocJar(type: Jar, dependsOn: javadoc) {
23 | classifier = 'javadoc'
24 | from javadoc.destinationDir
25 | }
26 |
27 | artifacts {
28 | archives sourcesJar
29 | archives javadocJar
30 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | Android-SerialPort
19 |
20 |
--------------------------------------------------------------------------------
/serialportlib/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 29
5 | buildToolsVersion "29.0.2"
6 |
7 | defaultConfig {
8 | minSdkVersion 16
9 | targetSdkVersion 29
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | consumerProguardFiles 'consumer-rules.pro'
14 | }
15 |
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | externalNativeBuild {
24 | cmake {
25 | path "CMakeLists.txt"
26 | }
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 |
33 | }
34 | apply from: '../jitpack.gradle'
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/serialportlib/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/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | #008577
20 | #00574B
21 | #D81B60
22 |
23 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/listener/Status.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.listener;
17 |
18 | /**
19 | * @author HuangYH
20 | * @date 2019/12/2 18:17
21 | * @Description
22 | */
23 | public enum Status {
24 |
25 | NO_READ_WRITE_PERMISSION,
26 | OPEN_FAIL
27 | }
28 |
--------------------------------------------------------------------------------
/serialportlib/src/main/jni/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_com_android_serialport_SerialPort
6 | #define _Included_com_android_serialport_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_me_f1reking_serialportlib_SerialPortHelper_nativeOpen
16 | (JNIEnv *, jclass, jstring, jint, jint, jint, jint, jint, jint);
17 |
18 | /*
19 | * Class: android_serialport_api_SerialPort
20 | * Method: close
21 | * Signature: ()V
22 | */
23 | JNIEXPORT void JNICALL Java_me_f1reking_serialportlib_SerialPortHelper_nativeClose
24 | (JNIEnv *, jobject);
25 |
26 | #ifdef __cplusplus
27 | }
28 | #endif
29 | #endif
30 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/listener/ISerialPortDataListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.listener;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/11/1 10:58
21 | * @Description 串口消息监听
22 | */
23 | public interface ISerialPortDataListener {
24 |
25 | void onDataReceived(byte[] bytes);
26 |
27 | void onDataSend(byte[] bytes);
28 | }
29 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/listener/IOpenSerialPortListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.listener;
17 |
18 | import java.io.File;
19 |
20 | /**
21 | * @author F1ReKing
22 | * @date 2019/11/1 10:49
23 | * @Description 串口打开状态监听
24 | */
25 | public interface IOpenSerialPortListener {
26 |
27 | void onSuccess(File device);
28 |
29 | void onFail(File device, Status status);
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/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 |
21 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/STOPB.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/10/31 18:04
21 | * @Description 串口停止位定义
22 | */
23 | public enum STOPB {
24 |
25 | /**
26 | * 1位停止位
27 | */
28 | B1(1),
29 |
30 | /**
31 | * 2位停止位
32 | */
33 | B2(2);
34 |
35 | int stopBit;
36 |
37 | STOPB(int stopBit) {
38 | this.stopBit = stopBit;
39 | }
40 |
41 | public int getStopBit() {
42 | return this.stopBit;
43 | }
44 |
45 | public static int getStopBit(STOPB stopb) {
46 | return stopb.getStopBit();
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/PARITY.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/10/31 18:05
21 | * @Description 串口校验位定义
22 | */
23 | public enum PARITY {
24 |
25 | /**
26 | * 无奇偶校验
27 | */
28 | NONE(0),
29 | /**
30 | * 奇校验
31 | */
32 | ODD(1),
33 | /**
34 | * 偶校验
35 | */
36 | EVEN(2);
37 |
38 | int parity;
39 |
40 | PARITY(int parity) {
41 | this.parity = parity;
42 | }
43 |
44 | public int getParity() {
45 | return this.parity;
46 | }
47 |
48 | public static int getParity(PARITY parity) {
49 | return parity.getParity();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/FLOWCON.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/10/31 18:06
21 | * @Description 串口流控定义
22 | */
23 | public enum FLOWCON {
24 |
25 | /**
26 | * 不使用流控
27 | */
28 | NONE(0),
29 | /**
30 | * 硬件流控
31 | */
32 | HARD(1),
33 | /**
34 | * 软件流控
35 | */
36 | SOFT(2);
37 |
38 | int flowCon;
39 |
40 | FLOWCON(int flowCon) {
41 | this.flowCon = flowCon;
42 | }
43 |
44 | public int getFlowCon() {
45 | return this.flowCon;
46 | }
47 |
48 | public static int getFlowCon(FLOWCON flowcon) {
49 | return flowcon.getFlowCon();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/DATAB.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/10/31 18:05
21 | * @Description 串口数据位定义
22 | */
23 | public enum DATAB {
24 |
25 | /**
26 | * 5位数据位
27 | */
28 | CS5(5),
29 | /**
30 | * 6位数据位
31 | */
32 | CS6(6),
33 | /**
34 | * 7位数据位
35 | */
36 | CS7(7),
37 | /**
38 | * 8位数据位
39 | */
40 | CS8(8);
41 |
42 | int dataBit;
43 |
44 | DATAB(int dataBit) {
45 | this.dataBit = dataBit;
46 | }
47 |
48 | public int getDataBit() {
49 | return this.dataBit;
50 | }
51 |
52 | public static int getDataBit(DATAB datab) {
53 | return datab.getDataBit();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | apply plugin: 'com.android.application'
18 |
19 | android {
20 | compileSdkVersion 29
21 | buildToolsVersion "29.0.2"
22 | defaultConfig {
23 | applicationId "me.f1reking.android_serialport"
24 | minSdkVersion 16
25 | targetSdkVersion 29
26 | versionCode 1
27 | versionName "1.0"
28 | }
29 | buildTypes {
30 | release {
31 | minifyEnabled false
32 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
33 | }
34 | }
35 | }
36 |
37 | dependencies {
38 | implementation fileTree(dir: 'libs', include: ['*.jar'])
39 | implementation 'androidx.appcompat:appcompat:1.1.0'
40 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
41 | // implementation 'com.github.F1ReKing:Android-SerialPort:1.3.3'
42 | implementation project(path: ':serialportlib')
43 | }
44 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/util/ByteUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.util;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/11/1 14:08
21 | * @Description
22 | */
23 | public class ByteUtils {
24 |
25 | public static int isOdd(int num) {
26 | return num & 0x1;
27 | }
28 |
29 | public static int HexToInt(String inHex) {
30 | return Integer.parseInt(inHex, 16);
31 | }
32 |
33 | public static byte HexToByte(String inHex) {
34 | return (byte) Integer.parseInt(inHex, 16);
35 | }
36 |
37 | public static byte[] hexToByteArr(String hex) {
38 | int hexLen = hex.length();
39 | byte[] result;
40 | if (isOdd(hexLen) == 1) {
41 | hexLen++;
42 | result = new byte[hexLen / 2];
43 | hex = "0" + hex;
44 | } else {
45 | result = new byte[hexLen / 2];
46 | }
47 | int j = 0;
48 | for (int i = 0; i < hexLen; i += 2) {
49 | result[j] = HexToByte(hex.substring(i, i + 2));
50 | j++;
51 | }
52 | return result;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/serialportlib/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # For more information about using CMake with Android Studio, read the
2 | # documentation: https://d.android.com/studio/projects/add-native-code.html
3 |
4 | # Sets the minimum version of CMake required to build the native library.
5 |
6 | cmake_minimum_required(VERSION 3.4.1)
7 |
8 | # Creates and names a library, sets it as either STATIC
9 | # or SHARED, and provides the relative paths to its source code.
10 | # You can define multiple libraries, and CMake builds them for you.
11 | # Gradle automatically packages shared libraries with your APK.
12 |
13 | #set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/jniLibs/${ANDROID_ABI})
14 |
15 | add_library( # Sets the name of the library.
16 | serialport
17 |
18 | # Sets the library as a shared library.
19 | SHARED
20 |
21 | # Provides a relative path to your source file(s).
22 | src/main/jni/SerialPort.c)
23 |
24 | # Searches for a specified prebuilt library and stores the path as a
25 | # variable. Because CMake includes system libraries in the search path by
26 | # default, you only need to specify the name of the public NDK library
27 | # you want to add. CMake verifies that the library exists before
28 | # completing its build.
29 |
30 | find_library( # Sets the name of the path variable.
31 | log-lib
32 |
33 | # Specifies the name of the NDK library that
34 | # you want CMake to locate.
35 | log)
36 |
37 | # Specifies libraries CMake should link to your target library. You
38 | # can link multiple libraries, such as libraries you define in this
39 | # build script, prebuilt third-party libraries, or system libraries.
40 |
41 | target_link_libraries( # Specifies the target library.
42 | serialport
43 |
44 | # Links the target library to the log library
45 | # included in the NDK.
46 | ${log-lib})
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/BAUDRATE.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | /**
19 | * @author F1ReKing
20 | * @date 2019/10/31 18:03
21 | * @Description 串口波特率定义
22 | */
23 | public enum BAUDRATE {
24 |
25 | B0(0),
26 | B50(50),
27 | B75(75),
28 | B110(110),
29 | B134(134),
30 | B150(150),
31 | B200(200),
32 | B300(300),
33 | B600(600),
34 | B1200(1200),
35 | B1800(1800),
36 | B2400(2400),
37 | B4800(4800),
38 | B9600(9600),
39 | B19200(19200),
40 | B38400(38400),
41 | B57600(57600),
42 | B115200(115200),
43 | B230400(230400),
44 | B460800(460800),
45 | B500000(500000),
46 | B576000(576000),
47 | B921600(921600),
48 | B1000000(1000000),
49 | B1152000(1152000),
50 | B1500000(1500000),
51 | B2000000(2000000),
52 | B2500000(2500000),
53 | B3000000(3000000),
54 | B3500000(3500000),
55 | B4000000(4000000);
56 |
57 | int baudrate;
58 |
59 | BAUDRATE(int baudrate) {
60 | this.baudrate = baudrate;
61 | }
62 |
63 | int getBaudrate() {
64 | return this.baudrate;
65 | }
66 |
67 | public static int getBaudrate(BAUDRATE baudrate) {
68 | return baudrate.getBaudrate();
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
25 |
26 |
30 |
31 |
37 |
38 |
44 |
45 |
51 |
52 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/Driver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | import android.util.Log;
19 | import java.io.File;
20 | import java.util.ArrayList;
21 |
22 | /**
23 | * @author F1ReKing
24 | * @date 2019/10/31 18:45
25 | * @Description
26 | */
27 | public class Driver {
28 |
29 | private static final String TAG = Driver.class.getSimpleName();
30 |
31 | private String driverName;
32 | private String deviceRoot;
33 |
34 | public Driver(String driverName, String deviceRoot) {
35 | this.driverName = driverName;
36 | this.deviceRoot = deviceRoot;
37 | }
38 |
39 | public ArrayList getDevices() {
40 | ArrayList devices = new ArrayList<>();
41 | File dev = new File("/dev");
42 |
43 | if (!dev.exists()) {
44 | Log.i(TAG, "getDevices: " + dev.getAbsolutePath() + " no found");
45 | return devices;
46 | }
47 | if (!dev.canRead()) {
48 | Log.i(TAG, "getDevices: " + dev.getAbsolutePath() + " no read permissions");
49 | return devices;
50 | }
51 |
52 | File[] files = dev.listFiles();
53 |
54 | int i;
55 | for (i = 0; i < files.length; i++) {
56 | if (files[i].getAbsolutePath().startsWith(deviceRoot)) {
57 | Log.d(TAG, "Found new device: " + files[i]);
58 | devices.add(files[i]);
59 | }
60 | }
61 | return devices;
62 | }
63 |
64 | public String getName() {
65 | return driverName;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/SerialPortReceivedThread.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 |
21 | /**
22 | * @author F1ReKing
23 | * @date 2019/11/1 11:43
24 | * @Description
25 | */
26 | public abstract class SerialPortReceivedThread extends Thread {
27 |
28 | private static final String TAG = SerialPortReceivedThread.class.getSimpleName();
29 |
30 | private InputStream mInputStream;
31 | private byte[] mReceivedBuffer;
32 |
33 | public SerialPortReceivedThread(InputStream inputStream) {
34 | mInputStream = inputStream;
35 | mReceivedBuffer = new byte[1024];
36 | }
37 |
38 | @Override
39 | public void run() {
40 | super.run();
41 | while (!isInterrupted()) {
42 | try {
43 | if (null == mInputStream) {
44 | return;
45 | }
46 | int size = mInputStream.read(mReceivedBuffer);
47 | if (0 >= size) {
48 | return;
49 | }
50 | byte[] receivedBytes = new byte[size];
51 | System.arraycopy(mReceivedBuffer, 0, receivedBytes, 0, size);
52 | onDataReceived(receivedBytes);
53 | } catch (IOException e) {
54 | e.printStackTrace();
55 | }
56 | }
57 | }
58 |
59 | public abstract void onDataReceived(byte[] bytes);
60 |
61 | /**
62 | * 释放
63 | */
64 | public void release() {
65 | interrupt();
66 |
67 | if (null != mInputStream) {
68 | try {
69 | mInputStream.close();
70 | } catch (IOException e) {
71 | e.printStackTrace();
72 | }
73 | mInputStream = null;
74 | }
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/entity/Device.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib.entity;
17 |
18 | import android.os.Parcel;
19 | import android.os.Parcelable;
20 | import java.io.File;
21 |
22 | /**
23 | * @author F1ReKing
24 | * @date 2019/10/31 18:47
25 | * @Description
26 | */
27 | public class Device implements Parcelable {
28 |
29 | private String name;
30 | private String root;
31 | private File file;
32 |
33 | public Device(String name, String root, File file) {
34 | this.name = name;
35 | this.root = root;
36 | this.file = file;
37 | }
38 |
39 | public String getName() {
40 | return name;
41 | }
42 |
43 | public void setName(String name) {
44 | this.name = name;
45 | }
46 |
47 | public String getRoot() {
48 | return root;
49 | }
50 |
51 | public void setRoot(String root) {
52 | this.root = root;
53 | }
54 |
55 | public File getFile() {
56 | return file;
57 | }
58 |
59 | public void setFile(File file) {
60 | this.file = file;
61 | }
62 |
63 | @Override
64 | public int describeContents() { return 0; }
65 |
66 | @Override
67 | public void writeToParcel(Parcel dest, int flags) {
68 | dest.writeString(this.name);
69 | dest.writeString(this.root);
70 | dest.writeSerializable(this.file);
71 | }
72 |
73 | protected Device(Parcel in) {
74 | this.name = in.readString();
75 | this.root = in.readString();
76 | this.file = (File) in.readSerializable();
77 | }
78 |
79 | public static final Creator CREATOR = new Creator() {
80 | @Override
81 | public Device createFromParcel(Parcel source) {return new Device(source);}
82 |
83 | @Override
84 | public Device[] newArray(int size) {return new Device[size];}
85 | };
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
24 |
29 |
30 |
36 |
39 |
42 |
43 |
44 |
45 |
51 |
52 |
--------------------------------------------------------------------------------
/serialportlib/src/main/jni/termios.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2008 The Android Open Source Project
3 | * All rights reserved.
4 | *
5 | * Redistribution and use in source and binary forms, with or without
6 | * modification, are permitted provided that the following conditions
7 | * are met:
8 | * * Redistributions of source code must retain the above copyright
9 | * notice, this list of conditions and the following disclaimer.
10 | * * Redistributions in binary form must reproduce the above copyright
11 | * notice, this list of conditions and the following disclaimer in
12 | * the documentation and/or other materials provided with the
13 | * distribution.
14 | *
15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 | * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 | * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 | * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 | * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 | * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 | * SUCH DAMAGE.
27 | */
28 | #ifndef _TERMIOS_H_
29 | #define _TERMIOS_H_
30 |
31 | #include
32 | #include
33 | #include
34 | #include
35 | #include
36 |
37 | __BEGIN_DECLS
38 |
39 | /* Redefine these to match their ioctl number */
40 | #undef TCSANOW
41 | #define TCSANOW TCSETS
42 |
43 | #undef TCSADRAIN
44 | #define TCSADRAIN TCSETSW
45 |
46 | #undef TCSAFLUSH
47 | #define TCSAFLUSH TCSETSF
48 |
49 | static __inline__ int tcgetattr(int fd, struct termios *s)
50 | {
51 | return ioctl(fd, TCGETS, s);
52 | }
53 |
54 | static __inline__ int tcsetattr(int fd, int __opt, const struct termios *s)
55 | {
56 | return ioctl(fd, __opt, (void *)s);
57 | }
58 |
59 | static __inline__ int tcflow(int fd, int action)
60 | {
61 | return ioctl(fd, TCXONC, (void *)(intptr_t)action);
62 | }
63 |
64 | static __inline__ int tcflush(int fd, int __queue)
65 | {
66 | return ioctl(fd, TCFLSH, (void *)(intptr_t)__queue);
67 | }
68 |
69 | static __inline__ pid_t tcgetsid(int fd)
70 | {
71 | pid_t _pid;
72 | return ioctl(fd, TIOCGSID, &_pid) ? (pid_t)-1 : _pid;
73 | }
74 |
75 | static __inline__ int tcsendbreak(int fd, int __duration)
76 | {
77 | return ioctl(fd, TCSBRKP, (void *)(uintptr_t)__duration);
78 | }
79 |
80 | static __inline__ speed_t cfgetospeed(const struct termios *s)
81 | {
82 | return (speed_t)(s->c_cflag & CBAUD);
83 | }
84 |
85 | static __inline__ int cfsetospeed(struct termios *s, speed_t speed)
86 | {
87 | s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
88 | return 0;
89 | }
90 |
91 | static __inline__ speed_t cfgetispeed(const struct termios *s)
92 | {
93 | return (speed_t)(s->c_cflag & CBAUD);
94 | }
95 |
96 | static __inline__ int cfsetispeed(struct termios *s, speed_t speed)
97 | {
98 | s->c_cflag = (s->c_cflag & ~CBAUD) | (speed & CBAUD);
99 | return 0;
100 | }
101 |
102 | static __inline__ void cfmakeraw(struct termios *s)
103 | {
104 | s->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
105 | s->c_oflag &= ~OPOST;
106 | s->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
107 | s->c_cflag &= ~(CSIZE|PARENB);
108 | s->c_cflag |= CS8;
109 | }
110 |
111 | __END_DECLS
112 |
113 | #endif /* _TERMIOS_H_ */
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android-SerialPort
2 | 此项目移植于谷歌官方串口库[android-serialport-api](https://code.google.com/archive/p/android-serialport-api/),但该项目仅支持串口名称及波特率,所以在项目的基础上添加支持数据位、数据位、停止位、流控等配置。
3 |
4 | [](https://jitpack.io/#F1ReKing/Android-SerialPort)
5 | [](https://github.com/F1ReKing/Android-SerialPort/blob/master/LICENSE)
6 |
7 | ## 下载
8 |
9 |
10 | 酷安:[https://www.coolapk.com/apk/251882](https://www.coolapk.com/apk/251882)
11 |
12 | 
13 |
14 | ## 引入
15 |
16 | **Step 1.** Add the JitPack repository to your build file
17 |
18 | Add it in your root build.gradle at the end of repositories:
19 |
20 |
21 | allprojects {
22 | repositories {
23 | ...
24 | maven { url 'https://jitpack.io' }
25 | }
26 | }
27 |
28 |
29 | **Step 2.** Add the dependency
30 |
31 |
32 | dependencies {
33 | implementation 'com.github.F1ReKing:Android-SerialPort:1.5.1'
34 | }
35 |
36 |
37 | ## 使用
38 |
39 | ### 1. 查询串口列表
40 |
41 | ```java
42 | SerialPortHelper#getAllDevices();
43 | // 查询串口设备地址列表
44 | SerialPortHelper#getAllDeicesPath();
45 | ```
46 |
47 | ### 2. 配置串口参数
48 |
49 | ```java
50 | SerialPortHelper#Builder(String port, int baudRate).build(); //支持配置串口号,波特率(默认值115200)
51 | setStopBits(int stopBits); // 支持设置停止位 默认值为2
52 | setDataBits(int dataBits); // 支持设置数据位 默认值为8
53 | setParity(int parity); // 支持设置检验位 默认值为0
54 | setFlowCon(int flowCon); // 支持设置流控 默认值为0
55 | setFlags(int flags); // 支持设置标志 默认值为0,O_RDWR 读写方式打开
56 | ```
57 |
58 | ### 3. 打开串口
59 |
60 | ```java
61 | SerialPortHelper#open();
62 | ```
63 |
64 | ### 4. 关闭串口
65 |
66 | ```java
67 | SerialPortHelper#close();
68 | ```
69 |
70 | ### 4. 发送数据
71 |
72 | ```java
73 | SerialPortHelper#sendBytes(byte[] bytes); // 支持发送byte[]
74 | SerialPortHelper#sendHex(String hex); // 支持发送Hex
75 | SerialPortHelper#sendTxt(String txt); // 支持发送ASCII码
76 | ```
77 |
78 | ### 5. 接收数据
79 |
80 | ```java
81 | public interface ISerialPortDataListener {
82 | // 接收数据回调
83 | void onDataReceived(byte[] bytes);
84 | // 发送数据回调
85 | void onDataSend(byte[] bytes);
86 | }
87 | ```
88 |
89 | ### 6. 回调
90 |
91 | ```java
92 | // 串口打开状态监听
93 | void setIOpenSerialPortListener(IOpenSerialPortListener IOpenSerialPortListener);
94 |
95 | // 串口消息监听
96 | void setISerialPortDataListener(ISerialPortDataListener ISerialPortDataListener);
97 | ```
98 | ### 7. proguard-rules
99 | ```
100 | -keep class me.f1reking.serialportlib.** {*;}
101 | ```
102 |
103 | ## 版本更新记录
104 |
105 | ### 1.1
106 |
107 | - 优化api
108 | - 支持设置可选参数,并配置默认值
109 |
110 | ### 1.0
111 |
112 | - 基础功能、支持设置串口号、波特率、数据位、校验位、停止位、流控等配置
113 | - 支持发送、接收数据
114 |
115 | ## License
116 | ```
117 | Copyright 2019 F1ReKing.
118 |
119 | Licensed under the Apache License, Version 2.0 (the "License");
120 | you may not use this file except in compliance with the License.
121 | You may obtain a copy of the License at
122 |
123 | http://www.apache.org/licenses/LICENSE-2.0
124 |
125 | Unless required by applicable law or agreed to in writing, software
126 | distributed under the License is distributed on an "AS IS" BASIS,
127 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
128 | See the License for the specific language governing permissions and
129 | limitations under the License.
130 | ```
131 |
132 |
133 | ## Stargazers over time
134 |
135 | [](https://starchart.cc/GeekBugs/Android-SerialPort)
136 |
137 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/SerialPortFinder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib;
17 |
18 | import android.util.Log;
19 | import java.io.File;
20 | import java.io.FileReader;
21 | import java.io.IOException;
22 | import java.io.LineNumberReader;
23 | import java.util.ArrayList;
24 | import java.util.Iterator;
25 | import java.util.List;
26 | import java.util.Vector;
27 | import me.f1reking.serialportlib.entity.Device;
28 | import me.f1reking.serialportlib.entity.Driver;
29 |
30 | /**
31 | * @author F1ReKing
32 | * @date 2019/10/31 18:41
33 | * @Description
34 | */
35 | public class SerialPortFinder {
36 |
37 | private static final String TAG = SerialPortFinder.class.getSimpleName();
38 | private static final String DRIVERS_PATH = "/proc/tty/drivers";
39 | private static final String SERIAL_FIELD = "serial";
40 |
41 | public SerialPortFinder() {
42 | File file = new File(DRIVERS_PATH);
43 | boolean b = file.canRead();
44 | Log.i(TAG, "SerialPortFinder: file.canRead() = " + b);
45 | }
46 |
47 | /**
48 | * get Drivers
49 | *
50 | * @return Drivers
51 | * @throws IOException IOException
52 | */
53 | private ArrayList getDrivers() throws IOException {
54 | ArrayList drivers = new ArrayList<>();
55 | LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(DRIVERS_PATH));
56 | String readLine;
57 | while ((readLine = lineNumberReader.readLine()) != null) {
58 | String driverName = readLine.substring(0, 0x15).trim();
59 | String[] fields = readLine.split(" +");
60 | if ((fields.length >= 5) && (fields[fields.length - 1].equals(SERIAL_FIELD))) {
61 | Log.d(TAG, "Found new driver " + driverName + " on " + fields[fields.length - 4]);
62 | drivers.add(new Driver(driverName, fields[fields.length - 4]));
63 | }
64 | }
65 | return drivers;
66 | }
67 |
68 | /**
69 | * Use {@link #getAllDevices()} instead.
70 | *
71 | * @return serialPort
72 | */
73 | @Deprecated
74 | public ArrayList getDevices() {
75 | return (ArrayList) getAllDevices();
76 | }
77 |
78 | /**
79 | * get serialPort devices
80 | *
81 | * @return serialPort
82 | */
83 | public List getAllDevices() {
84 | List devices = new ArrayList<>();
85 | try {
86 | List drivers = getDrivers();
87 | for (Driver driver : drivers) {
88 | String driverName = driver.getName();
89 | List driverDevices = driver.getDevices();
90 | for (File file : driverDevices) {
91 | String devicesName = file.getName();
92 | devices.add(new Device(devicesName, driverName, file));
93 | }
94 | }
95 | } catch (IOException e) {
96 | e.printStackTrace();
97 | }
98 | return devices;
99 | }
100 |
101 | /**
102 | * get serialPort devices path
103 | *
104 | * @return serialPort path
105 | */
106 | public String[] getAllDeicesPath() {
107 | Vector paths = new Vector<>();
108 | Iterator drivers;
109 | try {
110 | drivers = getDrivers().iterator();
111 | while (drivers.hasNext()) {
112 | Driver driver = drivers.next();
113 | Iterator files = driver.getDevices().iterator();
114 | while (files.hasNext()) {
115 | String devicesPaths = files.next().getAbsolutePath();
116 | paths.add(devicesPaths);
117 | }
118 | }
119 | } catch (IOException e) {
120 | e.printStackTrace();
121 | }
122 | return paths.toArray(new String[paths.size()]);
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/app/src/main/java/me/f1reking/android_serialport/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 me.f1reking.android_serialport;
18 |
19 | import android.os.Bundle;
20 | import android.util.Log;
21 | import android.view.View;
22 | import android.widget.Button;
23 | import android.widget.EditText;
24 | import android.widget.Toast;
25 | import androidx.appcompat.app.AppCompatActivity;
26 | import me.f1reking.serialportlib.entity.BAUDRATE;
27 | import me.f1reking.serialportlib.entity.DATAB;
28 | import me.f1reking.serialportlib.entity.FLOWCON;
29 | import me.f1reking.serialportlib.entity.PARITY;
30 | import me.f1reking.serialportlib.entity.STOPB;
31 | import java.io.File;
32 | import java.util.Arrays;
33 | import me.f1reking.serialportlib.SerialPortHelper;
34 | import me.f1reking.serialportlib.listener.IOpenSerialPortListener;
35 | import me.f1reking.serialportlib.listener.ISerialPortDataListener;
36 | import me.f1reking.serialportlib.listener.Status;
37 |
38 | /**
39 | * @author F1ReKing
40 | * @date 2019/11/1 09:38
41 | * @Description
42 | */
43 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
44 |
45 | private static final String TAG = MainActivity.class.getSimpleName();
46 |
47 | protected EditText etInput;
48 | protected Button btnSend;
49 | protected Button btnOpen;
50 | protected Button btnClose;
51 |
52 | private SerialPortHelper mSerialPortHelper;
53 |
54 | @Override
55 | protected void onCreate(Bundle savedInstanceState) {
56 | super.onCreate(savedInstanceState);
57 | super.setContentView(R.layout.activity_main);
58 | initView();
59 | }
60 |
61 | @Override
62 | public void onClick(View view) {
63 | if (view.getId() == R.id.btn_send) {
64 | String str = etInput.getText().toString();
65 | if (mSerialPortHelper != null) {
66 | mSerialPortHelper.sendTxt(str);
67 | }
68 | } else if (view.getId() == R.id.btn_open) {
69 | open();
70 | } else if (view.getId() == R.id.btn_close) {
71 | close();
72 | }
73 | }
74 |
75 | private void open() {
76 | if (mSerialPortHelper == null) {
77 | mSerialPortHelper = new SerialPortHelper();
78 | mSerialPortHelper.setPort("/dev/ttyUSB0");
79 | mSerialPortHelper.setBaudRate(120);
80 | mSerialPortHelper.setStopBits(STOPB.getStopBit(STOPB.B2));
81 | mSerialPortHelper.setDataBits(DATAB.getDataBit(DATAB.CS8));
82 | mSerialPortHelper.setParity(PARITY.getParity(PARITY.NONE));
83 | mSerialPortHelper.setFlowCon(FLOWCON.getFlowCon(FLOWCON.NONE));
84 | }
85 | Log.i(TAG, "open: " + Arrays.toString(mSerialPortHelper.getAllDeicesPath()));
86 | mSerialPortHelper.setIOpenSerialPortListener(new IOpenSerialPortListener() {
87 | @Override
88 | public void onSuccess(final File device) {
89 | runOnUiThread(new Runnable() {
90 | @Override
91 | public void run() {
92 | Toast.makeText(MainActivity.this, device.getPath() + " :串口打开成功", Toast.LENGTH_SHORT).show();
93 | }
94 | });
95 | }
96 |
97 | @Override
98 | public void onFail(final File device, final Status status) {
99 | runOnUiThread(new Runnable() {
100 | @Override
101 | public void run() {
102 | switch (status) {
103 | case NO_READ_WRITE_PERMISSION:
104 | Toast.makeText(MainActivity.this, device.getPath() + " :没有读写权限", Toast.LENGTH_SHORT).show();
105 | break;
106 | case OPEN_FAIL:
107 | default:
108 | Toast.makeText(MainActivity.this, device.getPath() + " :串口打开失败", Toast.LENGTH_SHORT).show();
109 | break;
110 | }
111 | }
112 | });
113 | }
114 | });
115 | mSerialPortHelper.setISerialPortDataListener(new ISerialPortDataListener() {
116 | @Override
117 | public void onDataReceived(byte[] bytes) {
118 | Log.i(TAG, "onDataReceived: " + Arrays.toString(bytes));
119 | }
120 |
121 | @Override
122 | public void onDataSend(byte[] bytes) {
123 | Log.i(TAG, "onDataSend: " + Arrays.toString(bytes));
124 | }
125 | });
126 | Log.i(TAG, "open: " + mSerialPortHelper.open());
127 | }
128 |
129 | private void close() {
130 | if (mSerialPortHelper != null) {
131 | mSerialPortHelper.close();
132 | }
133 | }
134 |
135 | private void initView() {
136 | etInput = (EditText) findViewById(R.id.et_input);
137 | btnSend = (Button) findViewById(R.id.btn_send);
138 | btnSend.setOnClickListener(MainActivity.this);
139 | btnOpen = (Button) findViewById(R.id.btn_open);
140 | btnOpen.setOnClickListener(MainActivity.this);
141 | btnClose = (Button) findViewById(R.id.btn_close);
142 | btnClose.setOnClickListener(MainActivity.this);
143 |
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/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 |
17 |
18 |
24 |
27 |
32 |
37 |
42 |
47 |
52 |
57 |
62 |
67 |
72 |
77 |
82 |
87 |
92 |
97 |
102 |
107 |
112 |
117 |
122 |
127 |
132 |
137 |
142 |
147 |
152 |
157 |
162 |
167 |
172 |
177 |
182 |
187 |
188 |
--------------------------------------------------------------------------------
/serialportlib/src/main/jni/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 |
29 | static const char *TAG = "serial_port";
30 | #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
31 | #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
32 | #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
33 |
34 | static speed_t getBaudrate(jint baudrate) {
35 | switch (baudrate) {
36 | case 0:
37 | return B0;
38 | case 50:
39 | return B50;
40 | case 75:
41 | return B75;
42 | case 110:
43 | return B110;
44 | case 134:
45 | return B134;
46 | case 150:
47 | return B150;
48 | case 200:
49 | return B200;
50 | case 300:
51 | return B300;
52 | case 600:
53 | return B600;
54 | case 1200:
55 | return B1200;
56 | case 1800:
57 | return B1800;
58 | case 2400:
59 | return B2400;
60 | case 4800:
61 | return B4800;
62 | case 9600:
63 | return B9600;
64 | case 19200:
65 | return B19200;
66 | case 38400:
67 | return B38400;
68 | case 57600:
69 | return B57600;
70 | case 115200:
71 | return B115200;
72 | case 230400:
73 | return B230400;
74 | case 460800:
75 | return B460800;
76 | case 500000:
77 | return B500000;
78 | case 576000:
79 | return B576000;
80 | case 921600:
81 | return B921600;
82 | case 1000000:
83 | return B1000000;
84 | case 1152000:
85 | return B1152000;
86 | case 1500000:
87 | return B1500000;
88 | case 2000000:
89 | return B2000000;
90 | case 2500000:
91 | return B2500000;
92 | case 3000000:
93 | return B3000000;
94 | case 3500000:
95 | return B3500000;
96 | case 4000000:
97 | return B4000000;
98 | default:
99 | return -1;
100 | }
101 | }
102 |
103 | /*
104 | * Class: com_android_serialport_SerialPort
105 | * Method: open
106 | * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
107 | */
108 | JNIEXPORT jobject JNICALL Java_me_f1reking_serialportlib_SerialPortHelper_nativeOpen
109 | (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint stopBits, jint dataBits,
110 | jint parity, jint flowCon, jint flags) {
111 | int fd;
112 | speed_t speed;
113 | jobject mFileDescriptor;
114 |
115 | /* Check arguments */
116 | {
117 | speed = getBaudrate(baudrate);
118 | if (speed == -1) {
119 | /* TODO: throw an exception */
120 | LOGE("Invalid baudrate");
121 | return NULL;
122 | }
123 | }
124 |
125 | /* Opening device */
126 | {
127 | jboolean iscopy;
128 | const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
129 | LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);
130 | fd = open(path_utf, O_RDWR | flags);
131 | LOGD("open() fd = %d", fd);
132 | (*env)->ReleaseStringUTFChars(env, path, path_utf);
133 | if (fd == -1) {
134 | /* Throw an exception */
135 | LOGE("Cannot open port");
136 | /* TODO: throw an exception */
137 | return NULL;
138 | }
139 | }
140 |
141 | /* Configure device */
142 | {
143 | struct termios cfg;
144 | LOGD("Configuring serial port");
145 | if (tcgetattr(fd, &cfg)) {
146 | LOGE("tcgetattr() failed");
147 | close(fd);
148 | /* TODO: throw an exception */
149 | return NULL;
150 | }
151 |
152 | cfmakeraw(&cfg);
153 | cfsetispeed(&cfg, speed);
154 | cfsetospeed(&cfg, speed);
155 |
156 | cfg.c_cflag &= ~CSIZE;
157 | switch (dataBits) {
158 | case 5:
159 | cfg.c_cflag |= CS5; //Use 5-bit data bits
160 | break;
161 | case 6:
162 | cfg.c_cflag |= CS6; //Use 6-bit data bits
163 | break;
164 | case 7:
165 | cfg.c_cflag |= CS7; //Use 7-bit data bits
166 | break;
167 | case 8:
168 | cfg.c_cflag |= CS8; //Use 8-bit data bits
169 | break;
170 | default:
171 | cfg.c_cflag |= CS8;
172 | break;
173 | }
174 |
175 | switch (parity) {
176 | case 0:
177 | cfg.c_cflag &= ~PARENB; // None parity
178 | break;
179 | case 1:
180 | cfg.c_cflag |= (PARODD | PARENB); // Odd parity
181 | break;
182 | case 2:
183 | cfg.c_iflag &= ~(IGNPAR | PARMRK); // Even parity
184 | cfg.c_iflag |= INPCK;
185 | cfg.c_cflag |= PARENB;
186 | cfg.c_cflag &= ~PARODD;
187 | break;
188 | default:
189 | cfg.c_cflag &= ~PARENB;
190 | break;
191 | }
192 |
193 | switch (stopBits) {
194 | case 1:
195 | cfg.c_cflag &= ~CSTOPB; // 1 bit stop bit
196 | break;
197 | case 2:
198 | cfg.c_cflag |= CSTOPB; // 2 bit stop bit
199 | break;
200 | default:
201 | break;
202 | }
203 |
204 | // hardware flow control
205 | switch (flowCon) {
206 | case 0:
207 | cfg.c_cflag &= ~CRTSCTS; // None flow control
208 | break;
209 | case 1:
210 | cfg.c_cflag |= CRTSCTS; // Hardware flow control
211 | break;
212 | case 2:
213 | cfg.c_cflag |= IXON | IXOFF | IXANY; // Software flow control
214 | break;
215 | default:
216 | cfg.c_cflag &= ~CRTSCTS;
217 | break;
218 | }
219 |
220 |
221 | if (tcsetattr(fd, TCSANOW, &cfg)) {
222 | LOGE("tcsetattr() failed");
223 | close(fd);
224 | /* TODO: throw an exception */
225 | return NULL;
226 | }
227 | }
228 |
229 | /* Create a corresponding file descriptor */
230 | {
231 | jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
232 | jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "", "()V");
233 | jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
234 | mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
235 | (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint) fd);
236 | }
237 |
238 | return mFileDescriptor;
239 | }
240 |
241 | /*
242 | * Class: com_android_serialport_SerialPort
243 | * Method: close
244 | * Signature: ()V
245 | */
246 | JNIEXPORT void JNICALL Java_me_f1reking_serialportlib_SerialPortHelper_nativeClose
247 | (JNIEnv *env, jobject thiz) {
248 | jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
249 | jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");
250 |
251 | jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFD", "Ljava/io/FileDescriptor;");
252 | jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");
253 |
254 | jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
255 | jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);
256 |
257 | LOGD("close(fd = %d)", descriptor);
258 | close(descriptor);
259 | }
260 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/serialportlib/src/main/java/me/f1reking/serialportlib/SerialPortHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 F1ReKing.
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 | package me.f1reking.serialportlib;
17 |
18 | import android.os.Handler;
19 | import android.os.HandlerThread;
20 | import android.os.Message;
21 | import android.util.Log;
22 | import me.f1reking.serialportlib.entity.BAUDRATE;
23 | import me.f1reking.serialportlib.entity.DATAB;
24 | import me.f1reking.serialportlib.entity.Device;
25 | import me.f1reking.serialportlib.entity.FLOWCON;
26 | import me.f1reking.serialportlib.entity.PARITY;
27 | import me.f1reking.serialportlib.entity.STOPB;
28 | import java.io.File;
29 | import java.io.FileDescriptor;
30 | import java.io.FileInputStream;
31 | import java.io.FileOutputStream;
32 | import java.io.IOException;
33 | import java.util.List;
34 | import me.f1reking.serialportlib.listener.IOpenSerialPortListener;
35 | import me.f1reking.serialportlib.listener.ISerialPortDataListener;
36 | import me.f1reking.serialportlib.listener.Status;
37 | import me.f1reking.serialportlib.util.ByteUtils;
38 |
39 | /**
40 | * @author F1ReKing
41 | * @date 2019/11/1 09:38
42 | * @Description
43 | */
44 | public class SerialPortHelper {
45 |
46 | private static final String TAG = SerialPortHelper.class.getSimpleName();
47 |
48 | static {
49 | System.loadLibrary("serialport");
50 | }
51 |
52 | private IOpenSerialPortListener mIOpenSerialPortListener;
53 | private ISerialPortDataListener mISerialPortDataListener;
54 | private HandlerThread mSendingHandlerThread;
55 | private Handler mSendingHandler;
56 | private SerialPortReceivedThread mSerialPortReceivedThread;
57 | private SerialPortFinder mSerialPortFinder;
58 |
59 | private FileDescriptor mFD;
60 | private FileInputStream mFileInputStream;
61 | private FileOutputStream mFileOutputStream;
62 |
63 | private static String mPort = "/dev/ttyUSB0"; //串口设置默认值
64 | private static int mBaudRate = 115200; //波特率默认值
65 | private static int mStopBits = 2; //停止位默认值
66 | private static int mDataBits = 8; //数据位默认值
67 | private static int mParity = 0; //校验位默认值
68 | private static int mFlowCon = 0; //流控默认值
69 | private static int mFlags = 0;
70 | private boolean isOpen = false; //是否打开串口标志
71 |
72 | /**
73 | * 获得所有串口设备的地址
74 | *
75 | * @return 所有串口设备的地址
76 | */
77 | public String[] getAllDeicesPath() {
78 | if (mSerialPortFinder == null) {
79 | mSerialPortFinder = new SerialPortFinder();
80 | }
81 | return mSerialPortFinder.getAllDeicesPath();
82 | }
83 |
84 | /**
85 | * 获取所有串口设备
86 | *
87 | * @return 所有串口设备
88 | */
89 | public List getAllDevices() {
90 | if (mSerialPortFinder == null) {
91 | mSerialPortFinder = new SerialPortFinder();
92 | }
93 | return mSerialPortFinder.getAllDevices();
94 | }
95 |
96 | /**
97 | * 打开串口
98 | *
99 | * @return 串口打开状态 true:打开 false:打开失败
100 | */
101 | public boolean open() {
102 | return openSerialPort(new File(mPort), mBaudRate, mStopBits, mDataBits, mParity, mFlowCon, mFlags);
103 | }
104 |
105 | /**
106 | * 关闭串口
107 | */
108 | public void close() {
109 | closeSerialPort();
110 | }
111 |
112 | /**
113 | * 串口状态
114 | * @return true:打开 false:关闭
115 | */
116 | public boolean isOpen() {
117 | return isOpen;
118 | }
119 |
120 | public boolean setPort(String port) {
121 | if (isOpen) {
122 | return false;
123 | }
124 | mPort = port;
125 | return true;
126 | }
127 |
128 | public String getPort() {
129 | return mPort;
130 | }
131 |
132 | public boolean setBaudRate(int baudRate) {
133 | if (isOpen) {
134 | return false;
135 | }
136 | mBaudRate = baudRate;
137 | return true;
138 | }
139 |
140 | public int getBaudRate() {
141 | return mBaudRate;
142 | }
143 |
144 | public boolean setDataBits(int dataBits) {
145 | if (isOpen) {
146 | return false;
147 | }
148 | mDataBits = dataBits;
149 | return true;
150 | }
151 |
152 | public int getDataBits() {
153 | return mDataBits;
154 | }
155 |
156 | public boolean setStopBits(int stopBits) {
157 | if (isOpen) {
158 | return false;
159 | }
160 | mStopBits = stopBits;
161 | return true;
162 | }
163 |
164 | public int getStopBits() {
165 | return mStopBits;
166 | }
167 |
168 | public boolean setParity(int parity) {
169 | if (isOpen) {
170 | return false;
171 | }
172 | mParity = parity;
173 | return true;
174 | }
175 |
176 | public int getParity() {
177 | return mParity;
178 | }
179 |
180 | public boolean setFlowCon(int flowCon) {
181 | if (isOpen) {
182 | return false;
183 | }
184 | mFlowCon = flowCon;
185 | return true;
186 | }
187 |
188 | public int getFlowCon() {
189 | return mFlowCon;
190 | }
191 |
192 | public boolean setFlags(int flags) {
193 | if (isOpen) {
194 | return false;
195 | }
196 | mFlags = flags;
197 | return true;
198 | }
199 |
200 | public int getFlags() {
201 | return mFlags;
202 | }
203 |
204 | public static class Builder {
205 |
206 | public Builder(String port, int baudRate) {
207 | mPort = port;
208 | mBaudRate = baudRate;
209 | }
210 |
211 | public Builder setStopBits(int stopBits) {
212 | mStopBits = stopBits;
213 | return this;
214 | }
215 |
216 | public Builder setDataBits(int dataBits) {
217 | mDataBits = dataBits;
218 | return this;
219 | }
220 |
221 | public Builder setParity(int parity) {
222 | mParity = parity;
223 | return this;
224 | }
225 |
226 | public Builder setFlowCon(int flowCon) {
227 | mFlowCon = flowCon;
228 | return this;
229 | }
230 |
231 | public Builder setFlags(int flags) {
232 | mFlags = flags;
233 | return this;
234 | }
235 |
236 | public SerialPortHelper build() {
237 | return new SerialPortHelper();
238 | }
239 |
240 | }
241 |
242 | /**
243 | * 发送数据
244 | *
245 | * @param bytes 发送的字节
246 | * @return 发送状态 true:发送成功 false:发送失败
247 | */
248 | public boolean sendBytes(byte[] bytes) {
249 | if (null != mSendingHandler) {
250 | Message message = Message.obtain();
251 | message.obj = bytes;
252 | return mSendingHandler.sendMessage(message);
253 | }
254 | return false;
255 | }
256 |
257 | /**
258 | * 发送Hex
259 | *
260 | * @param hex 16进制文本
261 | */
262 | public void sendHex(String hex) {
263 | byte[] hexArray = ByteUtils.hexToByteArr(hex);
264 | sendBytes(hexArray);
265 | }
266 |
267 | /**
268 | * 发送文本
269 | *
270 | * @param txt 文本
271 | */
272 | public void sendTxt(String txt) {
273 | byte[] txtArray = txt.getBytes();
274 | sendBytes(txtArray);
275 | }
276 |
277 |
278 |
279 | /**
280 | * 设置串口打开的监听
281 | *
282 | * @param iOpenSerialPortListener 监听
283 | */
284 | public void setIOpenSerialPortListener(IOpenSerialPortListener iOpenSerialPortListener) {
285 | mIOpenSerialPortListener = iOpenSerialPortListener;
286 | }
287 |
288 | /**
289 | * 设置串口数据收发的监听
290 | *
291 | * @param iSerialPortDataListener 监听
292 | */
293 | public void setISerialPortDataListener(ISerialPortDataListener iSerialPortDataListener) {
294 | mISerialPortDataListener = iSerialPortDataListener;
295 | }
296 |
297 | /**
298 | * 打开串口
299 | *
300 | * @param device 串口设备的绝对路径
301 | * @param baudRate {@link BAUDRATE} 波特率
302 | * @param stopBits {@link STOPB} 停止位
303 | * @param dataBits {@link DATAB} 数据位
304 | * @param parity {@link PARITY} 校验位
305 | * @param flowCon {@link FLOWCON} 流控
306 | * @param flags O_RDWR 读写方式打开 | O_NOCTTY 不允许进程管理串口 | O_NDELAY 非阻塞
307 | * @return 打开状态
308 | */
309 | private boolean openSerialPort(File device, int baudRate, int stopBits, int dataBits, int parity, int flowCon, int flags) {
310 | isOpen = openSafe(device, baudRate, stopBits, dataBits, parity, flowCon, flags);
311 | return isOpen;
312 | }
313 |
314 | /**
315 | * 关闭串口
316 | */
317 | private void closeSerialPort() {
318 | stopSendThread();
319 | stopReceivedThread();
320 | closeSafe();
321 | isOpen = false;
322 | }
323 |
324 | /**
325 | * 开启发送消息线程
326 | */
327 | private void startSendThread() {
328 | mSendingHandlerThread = new HandlerThread("mSendingHandlerThread");
329 | mSendingHandlerThread.start();
330 |
331 | mSendingHandler = new Handler(mSendingHandlerThread.getLooper()) {
332 | @Override
333 | public void handleMessage(Message msg) {
334 | byte[] sendBytes = (byte[]) msg.obj;
335 | if (null != mFileOutputStream && null != sendBytes && sendBytes.length > 0) {
336 | try {
337 | mFileOutputStream.write(sendBytes);
338 | if (null != mISerialPortDataListener) {
339 | mISerialPortDataListener.onDataSend(sendBytes);
340 | }
341 | } catch (IOException e) {
342 | e.printStackTrace();
343 | }
344 | }
345 | }
346 | };
347 | }
348 |
349 | /**
350 | * 停止发送消息线程
351 | */
352 | private void stopSendThread() {
353 | mSendingHandler = null;
354 | if (null != mSendingHandlerThread) {
355 | mSendingHandlerThread.interrupt();
356 | mSendingHandlerThread.quit();
357 | mSendingHandlerThread = null;
358 | }
359 | }
360 |
361 | /**
362 | * 开启接收消息的线程
363 | */
364 | private void startReceivedThread() {
365 | mSerialPortReceivedThread = new SerialPortReceivedThread(mFileInputStream) {
366 | @Override
367 | public void onDataReceived(byte[] bytes) {
368 | if (null != mISerialPortDataListener) {
369 | mISerialPortDataListener.onDataReceived(bytes);
370 | }
371 | }
372 | };
373 | mSerialPortReceivedThread.start();
374 | }
375 |
376 | /**
377 | * 停止接收消息的线程
378 | */
379 | private void stopReceivedThread() {
380 | if (null != mSerialPortReceivedThread) {
381 | mSerialPortReceivedThread.release();
382 | }
383 | }
384 |
385 | private boolean openSafe(File device, int baudRate, int stopBits, int dataBits, int parity, int flowCon, int flags) {
386 | Log.i(TAG, String.format("SerialPort: %s: %d,%d,%d,%d,%d,%d", device.getPath(), baudRate, stopBits, dataBits, parity, flowCon, flags));
387 | if (!device.canRead() || !device.canWrite()) {
388 | boolean chmod777 = chmod777(device);
389 | if (!chmod777) {
390 | Log.e(TAG, device.getPath() + " : 没有读写权限");
391 | if (null != mIOpenSerialPortListener) {
392 | mIOpenSerialPortListener.onFail(device, Status.NO_READ_WRITE_PERMISSION);
393 | }
394 | return false;
395 | }
396 | }
397 | try {
398 | mFD = nativeOpen(device.getAbsolutePath(), baudRate, stopBits, dataBits, parity, flowCon, flags);
399 | mFileInputStream = new FileInputStream(mFD);
400 | mFileOutputStream = new FileOutputStream(mFD);
401 | startSendThread();
402 | startReceivedThread();
403 | if (null != mIOpenSerialPortListener) {
404 | mIOpenSerialPortListener.onSuccess(device);
405 | }
406 | Log.i(TAG, device.getPath() + " : 串口已经打开");
407 | return true;
408 | } catch (Exception e) {
409 | e.printStackTrace();
410 | if (null != mIOpenSerialPortListener) {
411 | mIOpenSerialPortListener.onFail(device, Status.OPEN_FAIL);
412 | }
413 | }
414 | return false;
415 | }
416 |
417 | private void closeSafe() {
418 | if (null != mFD) {
419 | nativeClose();
420 | mFD = null;
421 | }
422 | if (null != mFileInputStream) {
423 | try {
424 | mFileInputStream.close();
425 | } catch (IOException e) {
426 | e.printStackTrace();
427 | }
428 | mFileInputStream = null;
429 | }
430 |
431 | if (null != mFileOutputStream) {
432 | try {
433 | mFileOutputStream.close();
434 | } catch (IOException e) {
435 | e.printStackTrace();
436 | }
437 | mFileOutputStream = null;
438 | }
439 | }
440 |
441 | /**
442 | * 检查文件权限
443 | *
444 | * @param device 文件
445 | * @return 权限修改是否成功
446 | */
447 | private boolean chmod777(File device) {
448 | if (null == device || !device.exists()) {
449 | return false;
450 | }
451 | try {
452 | Process su = Runtime.getRuntime().exec("/system/bin/su");
453 | String cmd = "chmod 777" + device.getAbsolutePath() + "\n" + "exit\n";
454 | su.getOutputStream().write(cmd.getBytes());
455 | if (0 == su.waitFor() && device.canRead() && device.canWrite() && device.canExecute()) {
456 | return true;
457 | }
458 | } catch (IOException | InterruptedException e) {
459 | e.printStackTrace();
460 |
461 | }
462 | return false;
463 | }
464 |
465 | /**
466 | * 打开串口
467 | *
468 | * @param path 串口设备的绝对路径
469 | * @param baudRate {@link BAUDRATE} 波特率
470 | * @param stopBits {@link STOPB} 停止位
471 | * @param dataBits {@link DATAB} 数据位
472 | * @param parity {@link PARITY} 校验位
473 | * @param flowCon {@link FLOWCON} 流控
474 | * @param flags O_RDWR 读写方式打开 | O_NOCTTY 不允许进程管理串口 | O_NDELAY 非阻塞
475 | *
476 | */
477 | private static native FileDescriptor nativeOpen(String path, int baudRate, int stopBits, int dataBits, int parity, int flowCon, int flags);
478 |
479 | /**
480 | * 关闭串口
481 | */
482 | public native void nativeClose();
483 |
484 | }
485 |
--------------------------------------------------------------------------------