├── .gitignore
├── .idea
├── codeStyles
│ └── Project.xml
├── gradle.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── misc.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── androidusbserialport
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── nianlun
│ │ └── androidusbserialport
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── nianlun
│ │ │ └── androidusbserialport
│ │ │ ├── AndroidSerialFragment.java
│ │ │ ├── MainActivity.java
│ │ │ ├── SplashActivity.java
│ │ │ ├── UsbSerialPortFragment.java
│ │ │ └── adapter
│ │ │ ├── SerialPortAdapter.java
│ │ │ └── UsbSerialPortAdapter.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── bg_btn_selector.xml
│ │ ├── bg_white_stroke.xml
│ │ ├── ic_launcher_background.xml
│ │ ├── ic_serial.png
│ │ ├── shape_btn_normal.xml
│ │ └── shape_btn_press.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── activity_splash.xml
│ │ ├── fragment_android_serial_port.xml
│ │ ├── fragment_usb_serial_port.xml
│ │ ├── layout_controller_serial_port.xml
│ │ ├── layout_device_measure_top.xml
│ │ ├── layout_serial_port_list.xml
│ │ ├── layout_serial_receive_send_test.xml
│ │ ├── recyclerview_serial_port_item.xml
│ │ └── recyclerview_usb_serial_port_item.xml
│ │ ├── menu
│ │ └── menu_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── nianlun
│ └── androidusbserialport
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── libserialport
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── libs
│ ├── armeabi-v7a
│ │ └── libserial_port.so
│ ├── armeabi
│ │ └── libserial_port.so
│ └── x86
│ │ └── libserial_port.so
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ ├── android_serialport_api
│ │ ├── SerialPort.java
│ │ └── SerialPortFinder.java
│ └── com
│ │ └── nianlun
│ │ └── libserialport
│ │ ├── SerialController.java
│ │ ├── UsbBroadcastReceiver.java
│ │ ├── UsbSerialPortController.java
│ │ ├── UsbSerialPortParameters.java
│ │ └── usbdriver
│ │ ├── CdcAcmSerialDriver.java
│ │ ├── Ch34xSerialDriver.java
│ │ ├── CommonUsbSerialPort.java
│ │ ├── Cp21xxSerialDriver.java
│ │ ├── FtdiSerialDriver.java
│ │ ├── HexDump.java
│ │ ├── ProbeTable.java
│ │ ├── ProlificSerialDriver.java
│ │ ├── SerialInputOutputManager.java
│ │ ├── UsbId.java
│ │ ├── UsbSerialDriver.java
│ │ ├── UsbSerialPort.java
│ │ ├── UsbSerialProber.java
│ │ └── UsbSerialRuntimeException.java
│ └── res
│ └── values
│ └── strings.xml
├── settings.gradle
└── tool
└── serial_port_utility_latest.exe
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
15 |
16 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AndroidUSBSerialPort
2 | 安卓串口通信
3 |
4 | 博客文章:
5 |
6 | [Android串口通信(一)](https://www.cnblogs.com/jqnl/p/13633800.html)
7 |
8 | [Android串口通信(二)](https://www.cnblogs.com/jqnl/p/13633814.html)
9 |
10 | tool文件夹中附有PC串口调试工具供使用:serial_port_utility_latest.exe
11 |
12 | 参考库:
13 |
14 | 谷歌官方android-serialport-api库:[https://github.com/cepr/android-serialport-api](https://github.com/cepr/android-serialport-api)
15 |
16 | Usb转串口驱动usb-serial-for-android库:[https://github.com/mik3y/usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android)
17 |
18 | Kolin使用参考库:[https://github.com/HelloHuDi/usbSerialPortTools](https://github.com/HelloHuDi/usbSerialPortTools)
--------------------------------------------------------------------------------
/androidusbserialport/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/androidusbserialport/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion "30.0.2"
6 | defaultConfig {
7 | applicationId "com.nianlun.androidusbserialport"
8 | minSdkVersion 19
9 | targetSdkVersion 30
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation fileTree(dir: 'libs', include: ['*.jar'])
24 | implementation 'androidx.appcompat:appcompat:1.0.2'
25 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
26 | testImplementation 'junit:junit:4.12'
27 | androidTestImplementation 'androidx.test.ext:junit:1.1.0'
28 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
29 |
30 | implementation project(path: ':libserialport')
31 |
32 | implementation 'androidx.recyclerview:recyclerview:1.1.0'
33 | implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.47-androidx'
34 | implementation 'com.qw:soulpermission:1.3.0'
35 | }
36 |
--------------------------------------------------------------------------------
/androidusbserialport/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 |
--------------------------------------------------------------------------------
/androidusbserialport/src/androidTest/java/com/nianlun/androidusbserialport/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.nianlun.androidusbserialport", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/java/com/nianlun/androidusbserialport/AndroidSerialFragment.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport;
2 |
3 | import android.os.Bundle;
4 | import android.view.LayoutInflater;
5 | import android.view.View;
6 | import android.view.ViewGroup;
7 | import android.widget.Button;
8 | import android.widget.CheckBox;
9 | import android.widget.EditText;
10 | import android.widget.LinearLayout;
11 | import android.widget.ScrollView;
12 | import android.widget.Spinner;
13 | import android.widget.TextView;
14 |
15 | import androidx.annotation.NonNull;
16 | import androidx.annotation.Nullable;
17 | import androidx.fragment.app.Fragment;
18 | import androidx.recyclerview.widget.LinearLayoutManager;
19 | import androidx.recyclerview.widget.RecyclerView;
20 |
21 | import com.chad.library.adapter.base.BaseQuickAdapter;
22 | import com.nianlun.androidusbserialport.adapter.SerialPortAdapter;
23 | import com.nianlun.libserialport.SerialController;
24 | import com.nianlun.libserialport.usbdriver.HexDump;
25 |
26 | import java.util.concurrent.ExecutorService;
27 | import java.util.concurrent.Executors;
28 |
29 | public class AndroidSerialFragment extends Fragment implements View.OnClickListener, SerialController.OnSerialListener {
30 |
31 | private ExecutorService execute = Executors.newCachedThreadPool();
32 | private SerialPortAdapter mSerialPortAdapter;
33 | private SerialController mSerialController;
34 | private String mSerialPortPath;
35 |
36 | private Spinner spBaudRate;
37 | private Spinner spData;
38 | private Spinner spStop;
39 | private LinearLayout usbTitle;
40 | private TextView tvParity;
41 | private Spinner spParity;
42 | private Button btnOpenOrClose;
43 | private RecyclerView rvListUsbSerialPort;
44 | private TextView tvSendDataCount;
45 | private TextView tvReceiveDataCount;
46 | private TextView tvLoseDataCount;
47 | private TextView tvAbnormalDataCount;
48 | private TextView tvResult;
49 | private ScrollView svResult;
50 | private EditText etWriteData;
51 | private CheckBox cbHex;
52 | private CheckBox cbHexRev;
53 | private TextView tvReceiveNumber;
54 | private Button btnClear;
55 | private Button btnSend;
56 | private Button btnStartTest;
57 | private Button btnStopTest;
58 | private SendingThread mTestSendingThread;
59 |
60 | @Nullable
61 | @Override
62 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
63 | View view = inflater.inflate(R.layout.fragment_android_serial_port, container, false);
64 | initView(view);
65 | return view;
66 | }
67 |
68 | @Override
69 | public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
70 | super.onViewCreated(view, savedInstanceState);
71 | initData();
72 | initListener();
73 | }
74 |
75 | private void initListener() {
76 | mSerialController.setOnSerialListener(this);
77 | mSerialPortAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
78 | @Override
79 | public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
80 | mSerialPortPath = (String) adapter.getItem(position);
81 | mSerialPortAdapter.setSelectedPosition(position);
82 | }
83 | });
84 | }
85 |
86 | private void initData() {
87 | mSerialController = new SerialController();
88 | mSerialPortAdapter = new SerialPortAdapter(mSerialController.getAllSerialPortPath());
89 | rvListUsbSerialPort.setAdapter(mSerialPortAdapter);
90 | }
91 |
92 | private void initView(View view) {
93 | spBaudRate = (Spinner) view.findViewById(R.id.sp_baud_rate);
94 | spData = (Spinner) view.findViewById(R.id.sp_data);
95 | spStop = (Spinner) view.findViewById(R.id.sp_stop);
96 | usbTitle = (LinearLayout) view.findViewById(R.id.usb_title);
97 | usbTitle.setVisibility(View.GONE);
98 | tvParity = (TextView) view.findViewById(R.id.tv_parity);
99 | spParity = (Spinner) view.findViewById(R.id.sp_parity);
100 | btnOpenOrClose = (Button) view.findViewById(R.id.btn_open_or_close);
101 | rvListUsbSerialPort = (RecyclerView) view.findViewById(R.id.rv_list_usb_serial_port);
102 | rvListUsbSerialPort.setLayoutManager(new LinearLayoutManager(getContext()));
103 | tvSendDataCount = (TextView) view.findViewById(R.id.tv_sendDataCount);
104 | tvReceiveDataCount = (TextView) view.findViewById(R.id.tv_receiveDataCount);
105 | tvLoseDataCount = (TextView) view.findViewById(R.id.tv_loseDataCount);
106 | tvAbnormalDataCount = (TextView) view.findViewById(R.id.tv_abnormalDataCount);
107 | tvResult = (TextView) view.findViewById(R.id.tv_result);
108 | svResult = (ScrollView) view.findViewById(R.id.sv_result);
109 | etWriteData = (EditText) view.findViewById(R.id.et_write_data);
110 | cbHex = (CheckBox) view.findViewById(R.id.cb_hex);
111 | cbHexRev = (CheckBox) view.findViewById(R.id.cb_hex_rev);
112 | tvReceiveNumber = (TextView) view.findViewById(R.id.tv_receive_number);
113 | btnClear = (Button) view.findViewById(R.id.btn_clear);
114 | btnSend = (Button) view.findViewById(R.id.btn_send);
115 | btnStartTest = (Button) view.findViewById(R.id.btn_start_test);
116 | btnStopTest = (Button) view.findViewById(R.id.btn_stop_test);
117 |
118 | btnOpenOrClose.setOnClickListener(this);
119 | btnClear.setOnClickListener(this);
120 | btnSend.setOnClickListener(this);
121 | btnStartTest.setOnClickListener(this);
122 | btnStopTest.setOnClickListener(this);
123 | }
124 |
125 | @Override
126 | public void onClick(View v) {
127 | switch (v.getId()) {
128 | case R.id.btn_open_or_close:
129 | if (mSerialController.isOpened()) {
130 | mSerialController.closeSerialPort();
131 | btnOpenOrClose.setText(R.string.open_port);
132 | } else {
133 | mSerialController.openSerialPort(mSerialPortPath,
134 | Integer.parseInt(spBaudRate.getSelectedItem().toString()),
135 | Integer.parseInt(spParity.getSelectedItem().toString()));
136 | btnOpenOrClose.setText(R.string.close_port);
137 | }
138 | break;
139 | case R.id.btn_clear:
140 | tvResult.setText("");
141 | break;
142 | case R.id.btn_send:
143 | String data = etWriteData.getText().toString().trim();
144 | byte[] bytes;
145 | if (cbHex.isChecked()) {
146 | try {
147 | bytes = HexDump.hexStringToByteArray(data);
148 | } catch (Exception e) {
149 | showData(getResources().getString(R.string.is_not_hex,data));
150 | return;
151 | }
152 | } else {
153 | bytes = data.getBytes();
154 | }
155 | mSerialController.sendSerialPort(bytes);
156 | break;
157 | case R.id.btn_start_test:
158 | mIsTesting = true;
159 | resetTest();
160 | if (mSerialController.isOpened()) {
161 | mTestSendingThread = new SendingThread();
162 | if (!execute.isShutdown()) {
163 | execute.execute(mTestSendingThread);
164 | }
165 | }
166 | break;
167 | case R.id.btn_stop_test:
168 | mIsTesting = false;
169 | mTestSendingThread.interrupt();
170 | break;
171 | default:
172 | break;
173 | }
174 | }
175 |
176 | @Override
177 | public void onReceivedData(byte[] data, int size) {
178 | if (mIsTesting) {
179 | synchronized (mByteReceivedBackSemaphore) {
180 | int i;
181 | for (i = 0; i < size; i++) {
182 | if (data[i] == mValueToSend && (!mByteReceivedBack)) {
183 | mValueToSend++;
184 | mByteReceivedBack = true;
185 | mByteReceivedBackSemaphore.notify();
186 | } else {
187 | mCorrupted++;
188 | }
189 | }
190 | }
191 | } else {
192 | String receivedData = "";
193 | if (cbHexRev.isChecked()) {
194 | try {
195 | receivedData = HexDump.dumpHexString(data, 0, size);
196 | } catch (Exception e) {
197 | showData(getResources().getString(R.string.is_not_hex));
198 | }
199 | } else {
200 | receivedData = new String(data, 0, size);
201 | }
202 | showData(receivedData);
203 | }
204 | }
205 |
206 | @Override
207 | public void onSerialOpenSuccess() {
208 | showData(getResources().getString(R.string.open_port_success));
209 | }
210 |
211 | @Override
212 | public void onSerialOpenException(Exception e) {
213 | showData(getResources().getString(R.string.open_port_fail) + ":" + e.getMessage());
214 | }
215 |
216 | private void showData(String msg) {
217 | tvResult.append(msg + "\n");
218 | }
219 |
220 | private boolean mIsTesting;
221 | private byte mValueToSend;
222 | private boolean mByteReceivedBack;
223 | private final Object mByteReceivedBackSemaphore = new Object();
224 | private int mIncoming = 0;
225 | private int mOutgoing = 0;
226 | private int mLost = 0;
227 | private int mCorrupted = 0;
228 |
229 | private class SendingThread extends Thread {
230 | @Override
231 | public void run() {
232 | while (mIsTesting) {
233 | synchronized (mByteReceivedBackSemaphore) {
234 | mByteReceivedBack = false;
235 | mSerialController.sendSerialPort(new byte[]{mValueToSend});
236 | mOutgoing++;
237 | try {
238 | mByteReceivedBackSemaphore.wait(100);
239 | if (mByteReceivedBack) {
240 | mIncoming++;
241 | } else {
242 | mLost++;
243 | }
244 | getActivity().runOnUiThread(new Runnable() {
245 | @Override
246 | public void run() {
247 | setTestData(mOutgoing, mLost, mIncoming, mCorrupted);
248 | }
249 | });
250 | } catch (Exception e) {
251 | e.printStackTrace();
252 | }
253 | }
254 | }
255 | }
256 | }
257 |
258 | private void setTestData(int mOutgoing, int mLost, int mIncoming, int mCorrupted) {
259 | tvSendDataCount.setText(String.valueOf(mOutgoing));
260 | tvLoseDataCount.setText(String.valueOf(mLost));
261 | tvReceiveDataCount.setText(String.valueOf(mIncoming));
262 | tvAbnormalDataCount.setText(String.valueOf(mCorrupted));
263 | }
264 |
265 | private void resetTest() {
266 | mIncoming = 0;
267 | mOutgoing = 0;
268 | mLost = 0;
269 | mCorrupted = 0;
270 | setTestData(0, 0, 0, 0);
271 | }
272 | }
273 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/java/com/nianlun/androidusbserialport/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport;
2 |
3 | import android.os.Bundle;
4 | import android.view.Menu;
5 | import android.view.MenuItem;
6 | import android.widget.Toast;
7 |
8 | import androidx.annotation.NonNull;
9 | import androidx.appcompat.app.AppCompatActivity;
10 | import androidx.appcompat.widget.Toolbar;
11 | import androidx.fragment.app.Fragment;
12 |
13 | public class MainActivity extends AppCompatActivity {
14 |
15 | private Toolbar toolbar;
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_main);
21 | toolbar = findViewById(R.id.tool_bar_main);
22 | setSupportActionBar(toolbar);
23 | getSupportFragmentManager().beginTransaction().replace(R.id.fl_content_main, new AndroidSerialFragment()).commit();
24 | }
25 |
26 | @Override
27 | public boolean onCreateOptionsMenu(Menu menu) {
28 | getMenuInflater().inflate(R.menu.menu_main, menu);
29 | return true;
30 | }
31 |
32 | @Override
33 | public boolean onOptionsItemSelected(@NonNull MenuItem item) {
34 | Fragment fragment = null;
35 | switch (item.getItemId()) {
36 | case R.id.action_setting1:
37 | fragment = new AndroidSerialFragment();
38 | toolbar.setTitle(R.string.android_serial_port);
39 | break;
40 | case R.id.action_setting2:
41 | fragment = new UsbSerialPortFragment();
42 | toolbar.setTitle(R.string.usb_serial_port);
43 | break;
44 | default:
45 | break;
46 | }
47 | if (fragment != null) {
48 | getSupportFragmentManager().beginTransaction().replace(R.id.fl_content_main, fragment).commit();
49 | }
50 | return true;
51 |
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/java/com/nianlun/androidusbserialport/SplashActivity.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport;
2 |
3 | import androidx.appcompat.app.AppCompatActivity;
4 |
5 | import android.Manifest;
6 | import android.content.Intent;
7 | import android.os.Bundle;
8 | import android.os.CountDownTimer;
9 | import android.view.Window;
10 |
11 | import com.qw.soul.permission.SoulPermission;
12 | import com.qw.soul.permission.bean.Permission;
13 | import com.qw.soul.permission.callbcak.CheckRequestPermissionListener;
14 |
15 | public class SplashActivity extends AppCompatActivity {
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_splash);
21 | requestPermission();
22 | }
23 |
24 | private void requestPermission() {
25 | SoulPermission.getInstance().checkAndRequestPermission(
26 | Manifest.permission.WRITE_EXTERNAL_STORAGE, new CheckRequestPermissionListener() {
27 | @Override
28 | public void onPermissionOk(Permission permission) {
29 | CountDownTimer countDownTimer = new CountDownTimer(3000, 1000) {
30 | @Override
31 | public void onTick(long l) {
32 |
33 | }
34 |
35 | @Override
36 | public void onFinish() {
37 | Intent intent = new Intent(SplashActivity.this, MainActivity.class);
38 | startActivity(intent);
39 | finish();
40 | }
41 | };
42 | countDownTimer.start();
43 | }
44 |
45 | @Override
46 | public void onPermissionDenied(Permission permission) {
47 |
48 | }
49 | }
50 | );
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/java/com/nianlun/androidusbserialport/UsbSerialPortFragment.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport;
2 |
3 | import android.hardware.usb.UsbDevice;
4 | import android.os.Bundle;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.Button;
9 | import android.widget.CheckBox;
10 | import android.widget.EditText;
11 | import android.widget.Spinner;
12 | import android.widget.TextView;
13 |
14 | import androidx.annotation.NonNull;
15 | import androidx.annotation.Nullable;
16 | import androidx.fragment.app.Fragment;
17 | import androidx.recyclerview.widget.LinearLayoutManager;
18 | import androidx.recyclerview.widget.RecyclerView;
19 |
20 | import com.chad.library.adapter.base.BaseQuickAdapter;
21 | import com.nianlun.androidusbserialport.adapter.UsbSerialPortAdapter;
22 | import com.nianlun.libserialport.UsbSerialPortController;
23 | import com.nianlun.libserialport.UsbSerialPortParameters;
24 | import com.nianlun.libserialport.usbdriver.HexDump;
25 | import com.nianlun.libserialport.usbdriver.UsbSerialPort;
26 |
27 | import java.util.List;
28 | import java.util.Locale;
29 |
30 | public class UsbSerialPortFragment extends Fragment implements UsbSerialPortController.OnUsbSerialListener, View.OnClickListener {
31 |
32 | private UsbSerialPort mUsbSerialPort;
33 |
34 | private UsbSerialPortAdapter mUsbSerialPortAdapter;
35 | private UsbSerialPortController mUsbSerialPortController;
36 |
37 | private RecyclerView rvListUsbSerialPort;
38 | private Spinner spBaudRate;
39 | private Spinner spData;
40 | private Spinner spStop;
41 | private Spinner spParity;
42 | private Button btnOpenOrClose;
43 | private TextView tvResult;
44 | private EditText etWriteData;
45 | private CheckBox cbHex;
46 | private CheckBox cbHexRev;
47 | private TextView tvReceiveNumber;
48 | private Button btnClear;
49 | private Button btnSend;
50 | private List mUsbSerialPortList;
51 |
52 |
53 | @Nullable
54 | @Override
55 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
56 | View view = inflater.inflate(R.layout.fragment_usb_serial_port, container, false);
57 | initView(view);
58 | return view;
59 | }
60 |
61 | @Override
62 | public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
63 | super.onViewCreated(view, savedInstanceState);
64 | initData();
65 | initListener();
66 | }
67 |
68 | private void initListener() {
69 | mUsbSerialPortAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
70 | @Override
71 | public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
72 | mUsbSerialPortAdapter.setSelectedPosition(position);
73 | mUsbSerialPort = (UsbSerialPort) adapter.getItem(position);
74 | }
75 | });
76 | }
77 |
78 | private void initData() {
79 | mUsbSerialPortController = new UsbSerialPortController(getContext());
80 | mUsbSerialPortController.setUsbSerialConnectListener(this);
81 | mUsbSerialPortList = mUsbSerialPortController.getAllSerialPort();
82 | mUsbSerialPortAdapter = new UsbSerialPortAdapter(mUsbSerialPortList);
83 | rvListUsbSerialPort.setAdapter(mUsbSerialPortAdapter);
84 | }
85 |
86 | private void initView(View view) {
87 | rvListUsbSerialPort = (RecyclerView) view.findViewById(R.id.rv_list_usb_serial_port);
88 | rvListUsbSerialPort.setLayoutManager(new LinearLayoutManager(getContext()));
89 | spBaudRate = (Spinner) view.findViewById(R.id.sp_baud_rate);
90 | spData = (Spinner) view.findViewById(R.id.sp_data);
91 | spStop = (Spinner) view.findViewById(R.id.sp_stop);
92 | spParity = (Spinner) view.findViewById(R.id.sp_parity);
93 | btnOpenOrClose = (Button) view.findViewById(R.id.btn_open_or_close);
94 | btnOpenOrClose.setOnClickListener(this);
95 | tvResult = (TextView) view.findViewById(R.id.tv_result);
96 | etWriteData = (EditText) view.findViewById(R.id.et_write_data);
97 | cbHex = (CheckBox) view.findViewById(R.id.cb_hex);
98 | cbHexRev = (CheckBox) view.findViewById(R.id.cb_hex_rev);
99 | tvReceiveNumber = (TextView) view.findViewById(R.id.tv_receive_number);
100 | btnClear = (Button) view.findViewById(R.id.btn_clear);
101 | btnClear.setOnClickListener(this);
102 | btnSend = (Button) view.findViewById(R.id.btn_send);
103 | btnSend.setOnClickListener(this);
104 | }
105 |
106 | @Override
107 | public void onUsbDeviceStateChange(int usbDeviceState, UsbDevice usbDevice) {
108 | mUsbSerialPortList = mUsbSerialPortController.getAllSerialPort();
109 | mUsbSerialPortAdapter.setNewData(mUsbSerialPortList);
110 | mUsbSerialPortAdapter.setSelectedPosition(-1);
111 | }
112 |
113 | @Override
114 | public void onSerialOpenSuccess() {
115 | showData(getResources().getString(R.string.open_port_success));
116 | }
117 |
118 | @Override
119 | public void onSerialOpenException(Exception e) {
120 | showData(getResources().getString(R.string.open_port_fail));
121 | }
122 |
123 | @Override
124 | public void onReceivedData(byte[] data) {
125 | String receivedData;
126 | if (cbHexRev.isChecked()) {
127 | receivedData = HexDump.toHexString(data);
128 | } else {
129 | StringBuilder stringBuilder = new StringBuilder();
130 | for (byte b : data) {
131 | stringBuilder.append((int) b).append(" ");
132 | }
133 | receivedData = stringBuilder.toString();
134 | }
135 | showData(receivedData);
136 | tvReceiveNumber.setText(String.format(Locale.US, "%d", data.length));
137 | }
138 |
139 | @Override
140 | public void onSendException(Exception e) {
141 | showData(getResources().getString(R.string.serial_write_fail));
142 | }
143 |
144 | @Override
145 | public void onClick(View v) {
146 | switch (v.getId()) {
147 | case R.id.btn_open_or_close:
148 | if (mUsbSerialPortController.isOpened()) {
149 | mUsbSerialPortController.closeSerialPort();
150 | btnOpenOrClose.setText(R.string.open_port);
151 | } else {
152 | mUsbSerialPortController.openSerialPort(mUsbSerialPort, new UsbSerialPortParameters(
153 | Integer.parseInt(spBaudRate.getSelectedItem().toString()),
154 | Integer.parseInt(spData.getSelectedItem().toString()),
155 | Integer.parseInt(spStop.getSelectedItem().toString()),
156 | Integer.parseInt(spParity.getSelectedItem().toString())));
157 | btnOpenOrClose.setText(R.string.close_port);
158 | }
159 | break;
160 | case R.id.btn_clear:
161 | tvResult.setText("");
162 | break;
163 | case R.id.btn_send:
164 | String command = etWriteData.getText().toString().trim();
165 | boolean isWrite;
166 | if (cbHex.isChecked()) {
167 | isWrite = sendHexData(command);
168 | } else {
169 | isWrite = mUsbSerialPortController.sendSerialPort(command.getBytes());
170 | }
171 | if (isWrite) {
172 | showData(getResources().getString(R.string.serial_write_success));
173 | } else {
174 | showData(getResources().getString(R.string.serial_write_fail));
175 | }
176 | break;
177 | }
178 | }
179 |
180 | private boolean sendHexData(String command) {
181 | // String[] hexs = command.split(" ");
182 | // byte[] bytes = new byte[hexs.length];
183 | // boolean okflag = true;
184 | // int i = 0;
185 | // for (String hex : hexs) {
186 | // try {
187 | // int d = Integer.parseInt(hex, 16);
188 | // if (d > 255) {
189 | // showData(String.format(getResources().getString(R.string.greater_than_ff), hex));
190 | // okflag = false;
191 | // } else {
192 | // bytes[i] = (byte) d;
193 | // }
194 | // } catch (NumberFormatException e) {
195 | // showData(String.format(getResources().getString(R.string.is_not_hex), hex));
196 | // e.printStackTrace();
197 | // okflag = false;
198 | // }
199 | // i++;
200 | // }
201 | command = command.replace(" ", "");
202 | byte[] bytes;
203 | try {
204 | bytes = HexDump.hexStringToByteArray(command);
205 | } catch (Exception e) {
206 | showData(getResources().getString(R.string.is_not_hex, command));
207 | return false;
208 | }
209 | if (bytes.length > 0) {
210 | return mUsbSerialPortController.sendSerialPort(bytes);
211 | }
212 | return false;
213 | }
214 |
215 | private void showData(final String str) {
216 | getActivity().runOnUiThread(new Runnable() {
217 | @Override
218 | public void run() {
219 | tvResult.append(str + "\n");
220 | }
221 | });
222 |
223 | }
224 |
225 | }
226 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/java/com/nianlun/androidusbserialport/adapter/SerialPortAdapter.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport.adapter;
2 |
3 | import android.graphics.Color;
4 | import android.os.Build;
5 |
6 | import androidx.annotation.NonNull;
7 |
8 | import com.chad.library.adapter.base.BaseQuickAdapter;
9 | import com.chad.library.adapter.base.BaseViewHolder;
10 | import com.nianlun.androidusbserialport.R;
11 | import com.nianlun.libserialport.usbdriver.UsbSerialPort;
12 |
13 | import java.util.List;
14 |
15 | import android_serialport_api.SerialPort;
16 | import android_serialport_api.SerialPortFinder;
17 |
18 | public class SerialPortAdapter extends BaseQuickAdapter {
19 |
20 | private int mSelectedPosition = -1;
21 |
22 | public SerialPortAdapter(List data) {
23 | super(R.layout.recyclerview_serial_port_item, data);
24 | }
25 |
26 | @Override
27 | protected void convert(@NonNull BaseViewHolder helper, String item) {
28 | helper.setText(R.id.tv_name_serial_port_item, item);
29 | if (mSelectedPosition == helper.getAdapterPosition()) {
30 | helper.itemView.setBackgroundColor(Color.GREEN);
31 | }else{
32 | helper.itemView.setBackgroundColor(Color.TRANSPARENT);
33 | }
34 | }
35 |
36 | public void setSelectedPosition(int position) {
37 | this.mSelectedPosition = position;
38 | notifyDataSetChanged();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/java/com/nianlun/androidusbserialport/adapter/UsbSerialPortAdapter.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport.adapter;
2 |
3 | import android.graphics.Color;
4 | import android.os.Build;
5 |
6 | import androidx.annotation.NonNull;
7 | import androidx.annotation.RequiresApi;
8 |
9 | import com.chad.library.adapter.base.BaseQuickAdapter;
10 | import com.chad.library.adapter.base.BaseViewHolder;
11 | import com.nianlun.androidusbserialport.R;
12 | import com.nianlun.libserialport.usbdriver.UsbSerialPort;
13 |
14 | import java.util.List;
15 |
16 | public class UsbSerialPortAdapter extends BaseQuickAdapter {
17 |
18 | private int mSelectedPosition = -1;
19 |
20 | public UsbSerialPortAdapter(List data) {
21 | super(R.layout.recyclerview_usb_serial_port_item, data);
22 | }
23 |
24 | @Override
25 | protected void convert(@NonNull BaseViewHolder helper, UsbSerialPort item) {
26 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
27 | helper.setText(R.id.tv_manufacturer_usb_serial_port_item, item.getDriver().getDevice().getManufacturerName());
28 | }
29 | helper.setText(R.id.tv_vendor_usb_serial_port_item, "vendorId:" + item.getDriver().getDevice().getVendorId());
30 | helper.setText(R.id.tv_product_usb_serial_port_item, "productId:" + item.getDriver().getDevice().getProductId() + "");
31 | helper.setText(R.id.tv_name_usb_serial_port_item, "name:" + item.getDriver().getDevice().getDeviceName());
32 |
33 | if (mSelectedPosition == helper.getAdapterPosition()) {
34 | helper.itemView.setBackgroundColor(Color.GREEN);
35 | } else {
36 | helper.itemView.setBackgroundColor(Color.TRANSPARENT);
37 | }
38 | }
39 |
40 | public void setSelectedPosition(int position) {
41 | this.mSelectedPosition = position;
42 | notifyDataSetChanged();
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable/bg_btn_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable/bg_white_stroke.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable/ic_serial.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/drawable/ic_serial.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable/shape_btn_normal.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/drawable/shape_btn_press.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/activity_splash.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
32 |
33 |
37 |
38 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/fragment_android_serial_port.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
15 |
16 |
19 |
20 |
25 |
26 |
32 |
33 |
39 |
40 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/fragment_usb_serial_port.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
15 |
16 |
19 |
20 |
25 |
26 |
32 |
33 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/layout_controller_serial_port.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
13 |
14 |
22 |
23 |
24 |
31 |
32 |
38 |
39 |
43 |
44 |
49 |
50 |
54 |
55 |
59 |
60 |
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/layout_device_measure_top.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
14 |
15 |
21 |
22 |
28 |
29 |
36 |
37 |
44 |
45 |
52 |
53 |
59 |
60 |
61 |
69 |
70 |
76 |
77 |
84 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/layout_serial_port_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
16 |
17 |
22 |
23 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/layout_serial_receive_send_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
22 |
23 |
27 |
28 |
33 |
34 |
38 |
39 |
44 |
45 |
49 |
50 |
55 |
56 |
60 |
61 |
66 |
67 |
68 |
72 |
73 |
80 |
81 |
88 |
89 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/recyclerview_serial_port_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
21 |
22 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/layout/recyclerview_usb_serial_port_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
21 |
22 |
28 |
29 |
35 |
36 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/androidusbserialport/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3A99FC
4 | #0379EF
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 30px
4 | 16px
5 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 安卓串口调试助手
3 | 串口调试
4 | USB转串口调试
5 | 波特率
6 | 数据位
7 | 停止位
8 | 校验
9 | 打开
10 | 串口列表
11 | 串口打开成功
12 | 关闭
13 |
14 | 提供数据截图功能
15 | %s 不是十六进制数
16 | 要发送的十六进制数据为空
17 | 转换编码失败
18 | 请选择设备
19 | 请先打开串口
20 | 清空文本
21 | 数据截图
22 | 发送数据
23 | 数据收发测试
24 | 接收数据
25 | 丢失数据
26 | 异常数据
27 | 开始测试
28 | 停止测试
29 | HEX发送
30 | HEX接收
31 | 准备接收数据
32 | 数据截图保存成功
33 | 数据截图保存失败
34 | RECEIVE COUNT
35 | 字符模式直接输入,如:Hello World,HEX模式用空格分割,如:1E 10 20 F0
36 | 串口打开失败
37 | 写入成功
38 | 写入失败
39 |
40 |
41 |
42 | - 50
43 | - 75
44 | - 110
45 | - 134
46 | - 150
47 | - 200
48 | - 300
49 | - 600
50 | - 1200
51 | - 1800
52 | - 2400
53 | - 4800
54 | - 9600
55 | - 19200
56 | - 38400
57 | - 57600
58 | - 115200
59 | - 230400
60 | - 460800
61 | - 500000
62 | - 576000
63 | - 921600
64 | - 1000000
65 | - 1152000
66 | - 1500000
67 | - 2000000
68 | - 2500000
69 | - 3000000
70 | - 3500000
71 | - 4000000
72 |
73 |
74 | - 8
75 | - 7
76 | - 6
77 | - 5
78 |
79 |
80 | - 1
81 | - 2
82 | - 3
83 |
84 |
85 | - 0
86 | - 1
87 | - 2
88 | - 3
89 | - 4
90 |
91 |
92 |
93 |
94 |
--------------------------------------------------------------------------------
/androidusbserialport/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
12 |
13 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/androidusbserialport/src/test/java/com/nianlun/androidusbserialport/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.androidusbserialport;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | jcenter()
7 |
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.5.2'
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | jcenter()
21 | maven { url "https://jitpack.io" }
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
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 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Sep 01 16:53:28 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.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/libserialport/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/libserialport/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion "30.0.2"
6 |
7 |
8 | defaultConfig {
9 | minSdkVersion 19
10 | targetSdkVersion 30
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 |
22 | sourceSets {
23 | main {
24 | jniLibs.srcDirs = ['libs']
25 | }
26 | }
27 |
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 | }
33 |
--------------------------------------------------------------------------------
/libserialport/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/libserialport/consumer-rules.pro
--------------------------------------------------------------------------------
/libserialport/libs/armeabi-v7a/libserial_port.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/libserialport/libs/armeabi-v7a/libserial_port.so
--------------------------------------------------------------------------------
/libserialport/libs/armeabi/libserial_port.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/libserialport/libs/armeabi/libserial_port.so
--------------------------------------------------------------------------------
/libserialport/libs/x86/libserial_port.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/libserialport/libs/x86/libserial_port.so
--------------------------------------------------------------------------------
/libserialport/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 |
--------------------------------------------------------------------------------
/libserialport/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/android_serialport_api/SerialPort.java:
--------------------------------------------------------------------------------
1 | package android_serialport_api;
2 |
3 | import java.io.File;
4 | import java.io.FileDescriptor;
5 | import java.io.FileInputStream;
6 | import java.io.FileOutputStream;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.io.OutputStream;
10 |
11 | public class SerialPort {
12 |
13 | private FileDescriptor mFd;
14 | private FileInputStream mFileInputStream;
15 | private FileOutputStream mFileOutputStream;
16 |
17 | public SerialPort(File device, int baudRate, int flags) throws SecurityException, IOException {
18 |
19 | mFd = open(device.getAbsolutePath(), baudRate, flags);
20 | if (mFd == null) {
21 | throw new IOException();
22 | }
23 | mFileInputStream = new FileInputStream(mFd);
24 | mFileOutputStream = new FileOutputStream(mFd);
25 | }
26 |
27 | public InputStream getInputStream() {
28 | return mFileInputStream;
29 | }
30 |
31 | public OutputStream getOutputStream() {
32 | return mFileOutputStream;
33 | }
34 |
35 | private native static FileDescriptor open(String path, int baudrate, int flags);
36 |
37 | public native void close();
38 |
39 | static {
40 | System.loadLibrary("serial_port");
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/android_serialport_api/SerialPortFinder.java:
--------------------------------------------------------------------------------
1 | package android_serialport_api;
2 |
3 | import java.io.File;
4 | import java.io.FileReader;
5 | import java.io.IOException;
6 | import java.io.LineNumberReader;
7 | import java.util.Iterator;
8 | import java.util.Vector;
9 |
10 | import android.util.Log;
11 |
12 | public class SerialPortFinder {
13 |
14 | public class Driver {
15 | public Driver(String name, String root) {
16 | mDriverName = name;
17 | mDeviceRoot = root;
18 | }
19 |
20 | private String mDriverName;
21 | private String mDeviceRoot;
22 | Vector mDevices = null;
23 |
24 | Vector getDevices() {
25 | if (mDevices == null) {
26 | mDevices = new Vector<>();
27 | File dev = new File("/dev");
28 | File[] files = dev.listFiles();
29 | if (files == null) {
30 | return mDevices;
31 | }
32 | int i;
33 | for (i = 0; i < files.length; i++) {
34 | if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
35 | Log.d(TAG, "Found new device: " + files[i]);
36 | mDevices.add(files[i]);
37 | }
38 | }
39 | }
40 | return mDevices;
41 | }
42 |
43 | public String getName() {
44 | return mDriverName;
45 | }
46 | }
47 |
48 | private static final String TAG = "SerialPort";
49 |
50 | private Vector mDrivers = null;
51 |
52 | Vector getDrivers() throws IOException {
53 | if (mDrivers == null) {
54 | mDrivers = new Vector();
55 | LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
56 | String l;
57 | while ((l = r.readLine()) != null) {
58 | // Issue 3:
59 | // Since driver name may contain spaces, we do not extract driver name with split()
60 | String drivername = l.substring(0, 0x15).trim();
61 | String[] w = l.split(" +");
62 | if ((w.length >= 5) && (w[w.length - 1].equals("serial"))) {
63 | Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length - 4]);
64 | mDrivers.add(new Driver(drivername, w[w.length - 4]));
65 | }
66 | }
67 | r.close();
68 | }
69 | return mDrivers;
70 | }
71 |
72 | public String[] getAllDevices() {
73 | Vector devices = new Vector();
74 | // Parse each driver
75 | Iterator itdriv;
76 | try {
77 | itdriv = getDrivers().iterator();
78 | while (itdriv.hasNext()) {
79 | Driver driver = itdriv.next();
80 | Iterator itdev = driver.getDevices().iterator();
81 | while (itdev.hasNext()) {
82 | String device = itdev.next().getName();
83 | String value = String.format("%s (%s)", device, driver.getName());
84 | devices.add(value);
85 | }
86 | }
87 | } catch (IOException e) {
88 | e.printStackTrace();
89 | }
90 | return devices.toArray(new String[devices.size()]);
91 | }
92 |
93 | public String[] getAllDevicesPath() {
94 | Vector devices = new Vector();
95 | // Parse each driver
96 | Iterator itdriv;
97 | try {
98 | itdriv = getDrivers().iterator();
99 | while (itdriv.hasNext()) {
100 | Driver driver = itdriv.next();
101 | Iterator itdev = driver.getDevices().iterator();
102 | while (itdev.hasNext()) {
103 | String device = itdev.next().getAbsolutePath();
104 | devices.add(device);
105 | }
106 | }
107 | } catch (IOException e) {
108 | e.printStackTrace();
109 | }
110 | return devices.toArray(new String[devices.size()]);
111 | }
112 | }
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/SerialController.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.libserialport;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.io.InputStream;
6 | import java.io.OutputStream;
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import java.util.List;
10 | import java.util.concurrent.ExecutorService;
11 | import java.util.concurrent.Executors;
12 |
13 | import android_serialport_api.SerialPort;
14 | import android_serialport_api.SerialPortFinder;
15 |
16 |
17 | public class SerialController {
18 |
19 | private ExecutorService mThreadPoolExecutor = Executors.newCachedThreadPool();
20 | private InputStream inputStream;
21 | private OutputStream outputStream;
22 | private boolean isOpened = false;
23 | private OnSerialListener mOnSerialListener;
24 |
25 | /**
26 | * 获取所有串口路径
27 | *
28 | * @return 串口路径集合
29 | */
30 | public List getAllSerialPortPath() {
31 | SerialPortFinder mSerialPortFinder = new SerialPortFinder();
32 | String[] deviceArr = mSerialPortFinder.getAllDevicesPath();
33 | return new ArrayList<>(Arrays.asList(deviceArr));
34 | }
35 |
36 | /**
37 | * 打开串口
38 | *
39 | * @param serialPath 串口地址
40 | * @param baudRate 波特率
41 | * @param flags 标志位
42 | */
43 | public void openSerialPort(String serialPath, int baudRate, int flags) {
44 | try {
45 | SerialPort serialPort = new SerialPort(new File(serialPath), baudRate, flags);
46 | inputStream = serialPort.getInputStream();
47 | outputStream = serialPort.getOutputStream();
48 | isOpened = true;
49 | if (mOnSerialListener != null) {
50 | mOnSerialListener.onSerialOpenSuccess();
51 | }
52 | mThreadPoolExecutor.execute(new ReceiveDataThread());
53 | } catch (Exception e) {
54 | if (mOnSerialListener != null) {
55 | mOnSerialListener.onSerialOpenException(e);
56 | }
57 | }
58 | }
59 |
60 | /**
61 | * 关闭串口
62 | */
63 | public void closeSerialPort() {
64 | try {
65 | if (inputStream != null) {
66 | inputStream.close();
67 | }
68 | if (outputStream != null) {
69 | outputStream.close();
70 | }
71 | isOpened = false;
72 | } catch (IOException e) {
73 | e.printStackTrace();
74 | }
75 | }
76 |
77 | /**
78 | * 发送串口数据
79 | *
80 | * @param bytes 发送数据
81 | */
82 | public void sendSerialPort(byte[] bytes) {
83 | if (!isOpened) {
84 | return;
85 | }
86 | try {
87 | if (outputStream != null) {
88 | outputStream.write(bytes);
89 | outputStream.flush();
90 | }
91 | } catch (IOException e) {
92 | e.printStackTrace();
93 | }
94 | }
95 |
96 | /**
97 | * 返回串口是否开启
98 | *
99 | * @return 是否开启
100 | */
101 | public boolean isOpened() {
102 | return isOpened;
103 | }
104 |
105 | /**
106 | * 串口返回数据内容读取
107 | */
108 | private class ReceiveDataThread extends Thread {
109 | @Override
110 | public void run() {
111 | super.run();
112 | while (isOpened) {
113 | if (inputStream != null) {
114 | byte[] readData = new byte[1024];
115 | try {
116 | int size = inputStream.read(readData);
117 | if (size > 0) {
118 | if (mOnSerialListener != null) {
119 | mOnSerialListener.onReceivedData(readData, size);
120 | }
121 | }
122 |
123 | } catch (Exception e) {
124 | e.printStackTrace();
125 | }
126 | }
127 | }
128 | }
129 | }
130 |
131 | /**
132 | * 设置串口监听
133 | *
134 | * @param onSerialListener 串口监听
135 | */
136 | public void setOnSerialListener(OnSerialListener onSerialListener) {
137 | this.mOnSerialListener = onSerialListener;
138 | }
139 |
140 | /**
141 | * 串口监听
142 | */
143 | public interface OnSerialListener {
144 |
145 | /**
146 | * 串口数据返回
147 | */
148 | void onReceivedData(byte[] data, int size);
149 |
150 | /**
151 | * 串口打开成功
152 | */
153 | void onSerialOpenSuccess();
154 |
155 | /**
156 | * 串口打开异常
157 | */
158 | void onSerialOpenException(Exception e);
159 | }
160 |
161 |
162 | }
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/UsbBroadcastReceiver.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.libserialport;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.IntentFilter;
7 | import android.hardware.usb.UsbDevice;
8 | import android.hardware.usb.UsbManager;
9 |
10 | public class UsbBroadcastReceiver extends BroadcastReceiver {
11 |
12 | public static final String ACTION_USB_PERMISSION = "android.intent.USB_PERMISSION";
13 |
14 | private OnUsbDeviceStateChangeListener mOnUsbDeviceStateChangeListener;
15 |
16 | public void registerReceiver(Context context, OnUsbDeviceStateChangeListener onUsbDeviceStateChangeListener) {
17 | IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
18 | filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
19 | filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
20 | context.registerReceiver(this, filter);
21 | this.mOnUsbDeviceStateChangeListener = onUsbDeviceStateChangeListener;
22 | }
23 |
24 | @Override
25 | public void onReceive(Context context, Intent intent) {
26 | String action = intent.getAction();
27 | UsbDevice mUsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
28 | int usbState = -1;
29 | //Usb串口权限
30 | if (ACTION_USB_PERMISSION.equals(action)) {
31 | usbState = 0;
32 | }
33 | // Usb设备连接
34 | else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
35 | usbState = 1;
36 | }
37 | // Usb设备断开
38 | else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
39 | usbState = 2;
40 | }
41 | if (mOnUsbDeviceStateChangeListener != null) {
42 | mOnUsbDeviceStateChangeListener.onUsbDeviceStateChange(usbState, mUsbDevice);
43 | }
44 | }
45 |
46 | public interface OnUsbDeviceStateChangeListener {
47 | /**
48 | * Usb权限获取
49 | */
50 | int ACTION_PERMISSION_GAINED = 0;
51 | /**
52 | * Usb设备连接
53 | */
54 | int ACTION_DEVICE_ATTACHED = 1;
55 | /**
56 | * Usb设备断开
57 | */
58 | int ACTION_DEVICE_DETACHED = 2;
59 |
60 | void onUsbDeviceStateChange(int usbDeviceState, UsbDevice usbDevice);
61 | }
62 | }
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/UsbSerialPortController.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.libserialport;
2 |
3 | import android.app.PendingIntent;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.hardware.usb.UsbDevice;
7 | import android.hardware.usb.UsbDeviceConnection;
8 | import android.hardware.usb.UsbManager;
9 |
10 | import com.nianlun.libserialport.usbdriver.SerialInputOutputManager;
11 | import com.nianlun.libserialport.usbdriver.UsbSerialDriver;
12 | import com.nianlun.libserialport.usbdriver.UsbSerialPort;
13 | import com.nianlun.libserialport.usbdriver.UsbSerialProber;
14 |
15 | import java.io.IOException;
16 | import java.util.ArrayList;
17 | import java.util.List;
18 | import java.util.concurrent.ExecutorService;
19 | import java.util.concurrent.Executors;
20 |
21 | /**
22 | * @author 几圈年轮
23 | * @email jed.zhu.@qq.com
24 | * description 串口操作类
25 | */
26 | public class UsbSerialPortController implements SerialInputOutputManager.Listener, UsbBroadcastReceiver.OnUsbDeviceStateChangeListener {
27 |
28 | private static final int PORT_WRITE_TIME_OUT_MILLIS = 1000;
29 |
30 | private UsbManager mUsbManager;
31 | private PendingIntent mPermissionIntent;
32 | private SerialInputOutputManager mSerialInputOutputManager;
33 | private OnUsbSerialListener mOnUsbSerialListener;
34 | private boolean isOpened = false;
35 | private UsbSerialPort mUsbSerialPort;
36 | private UsbSerialPortParameters mUsbSerialPortParameters;
37 |
38 | public UsbSerialPortController(Context context) {
39 | mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
40 | mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(UsbBroadcastReceiver.ACTION_USB_PERMISSION), 0);
41 | UsbBroadcastReceiver mBroadcastReceiver = new UsbBroadcastReceiver();
42 | mBroadcastReceiver.registerReceiver(context, this);
43 | }
44 |
45 | /**
46 | * 获取所有USB串口设备
47 | */
48 | public List getAllSerialPort() {
49 | List drivers = UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
50 | List result = new ArrayList<>();
51 | for (UsbSerialDriver driver : drivers) {
52 | List ports = driver.getPorts();
53 | result.addAll(ports);
54 | }
55 | return result;
56 | }
57 |
58 | /**
59 | * 建立串口通信
60 | */
61 | public void openSerialPort(UsbSerialPort usbSerialPort, UsbSerialPortParameters usbSerialPortParameters) {
62 | if (usbSerialPort == null || usbSerialPortParameters == null) {
63 | return;
64 | }
65 | UsbDeviceConnection connection = mUsbManager.openDevice(usbSerialPort.getDriver().getDevice());
66 | this.mUsbSerialPort = usbSerialPort;
67 | this.mUsbSerialPortParameters = usbSerialPortParameters;
68 | if (connection != null) {
69 | try {
70 | usbSerialPort.open(connection);
71 | usbSerialPort.setParameters(usbSerialPortParameters.getBaudRate(), usbSerialPortParameters.getDataBits(), usbSerialPortParameters.getStopBits(), usbSerialPortParameters.getParity());
72 | mSerialInputOutputManager = new SerialInputOutputManager(usbSerialPort, this);
73 | ExecutorService mExecutor = Executors.newSingleThreadExecutor();
74 | mExecutor.submit(mSerialInputOutputManager);
75 | } catch (IOException e) {
76 | if (mOnUsbSerialListener != null) {
77 | mOnUsbSerialListener.onSerialOpenException(e);
78 | }
79 | }
80 | isOpened = true;
81 | if (mOnUsbSerialListener != null) {
82 | mOnUsbSerialListener.onSerialOpenSuccess();
83 | }
84 | } else {
85 | mUsbManager.requestPermission(usbSerialPort.getDriver().getDevice(), mPermissionIntent);
86 | }
87 | }
88 |
89 | /**
90 | * 发送命令到控制卡
91 | */
92 | public boolean sendSerialPort(byte[] commandBytes) {
93 | if (mUsbSerialPort != null && isOpened && commandBytes.length > 0) {
94 | try {
95 | mUsbSerialPort.write(commandBytes, PORT_WRITE_TIME_OUT_MILLIS);
96 | } catch (IOException e) {
97 | return false;
98 | }
99 | return true;
100 | }
101 | return false;
102 | }
103 |
104 | public boolean isOpened() {
105 | return isOpened;
106 | }
107 |
108 | /**
109 | * 关闭串口
110 | */
111 | public void closeSerialPort() {
112 | try {
113 | if (mUsbSerialPort != null) {
114 | mUsbSerialPort.close();
115 | }
116 | } catch (IOException e) {
117 | e.printStackTrace();
118 | }
119 | isOpened = false;
120 | if (mSerialInputOutputManager != null) {
121 | mSerialInputOutputManager.stop();
122 | mSerialInputOutputManager = null;
123 | }
124 | }
125 |
126 | @Override
127 | public void onNewData(byte[] data) {
128 | if (mOnUsbSerialListener != null) {
129 | mOnUsbSerialListener.onReceivedData(data);
130 | }
131 | }
132 |
133 | @Override
134 | public void onRunError(Exception e) {
135 | if (mOnUsbSerialListener != null) {
136 | mOnUsbSerialListener.onSendException(e);
137 | }
138 | }
139 |
140 | public void setUsbSerialConnectListener(OnUsbSerialListener onUsbSerialListener) {
141 | this.mOnUsbSerialListener = onUsbSerialListener;
142 | }
143 |
144 | @Override
145 | public void onUsbDeviceStateChange(int state, UsbDevice usbDevice) {
146 | if (mUsbSerialPort != null && usbDevice.getDeviceId() == mUsbSerialPort.getDriver().getDevice().getDeviceId()) {
147 | if (state == ACTION_PERMISSION_GAINED || state == ACTION_DEVICE_ATTACHED) {
148 | openSerialPort(mUsbSerialPort, mUsbSerialPortParameters);
149 | } else if (state == ACTION_DEVICE_DETACHED) {
150 | closeSerialPort();
151 | }
152 | }
153 | if (mOnUsbSerialListener != null) {
154 | mOnUsbSerialListener.onUsbDeviceStateChange(state, usbDevice);
155 | }
156 | }
157 |
158 | public interface OnUsbSerialListener {
159 |
160 | /**
161 | * 设备连接状态改变
162 | *
163 | * @param usbDeviceState 连接状态
164 | * @param usbDevice USB设备
165 | */
166 | void onUsbDeviceStateChange(int usbDeviceState, UsbDevice usbDevice);
167 |
168 | /**
169 | * 连接成功
170 | */
171 | void onSerialOpenSuccess();
172 |
173 | /**
174 | * 连接异常
175 | *
176 | * @param e 异常
177 | */
178 | void onSerialOpenException(Exception e);
179 |
180 | /**
181 | * 消息发送返回内容
182 | *
183 | * @param data 返回信息
184 | */
185 | void onReceivedData(byte[] data);
186 |
187 | /**
188 | * 消息发送异常
189 | *
190 | * @param e 异常信息
191 | */
192 | void onSendException(Exception e);
193 | }
194 |
195 | }
196 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/UsbSerialPortParameters.java:
--------------------------------------------------------------------------------
1 | package com.nianlun.libserialport;
2 |
3 | public class UsbSerialPortParameters {
4 |
5 | private int baudRate;
6 | private int dataBits;
7 | private int stopBits;
8 | private int parity;
9 |
10 | public UsbSerialPortParameters(int baudRate, int dataBits, int stopBits, int parity) {
11 | this.baudRate = baudRate;
12 | this.dataBits = dataBits;
13 | this.stopBits = stopBits;
14 | this.parity = parity;
15 | }
16 |
17 | public int getBaudRate() {
18 | return baudRate;
19 | }
20 |
21 | public void setBaudRate(int baudRate) {
22 | this.baudRate = baudRate;
23 | }
24 |
25 | public int getDataBits() {
26 | return dataBits;
27 | }
28 |
29 | public void setDataBits(int dataBits) {
30 | this.dataBits = dataBits;
31 | }
32 |
33 | public int getStopBits() {
34 | return stopBits;
35 | }
36 |
37 | public void setStopBits(int stopBits) {
38 | this.stopBits = stopBits;
39 | }
40 |
41 | public int getParity() {
42 | return parity;
43 | }
44 |
45 | public void setParity(int parity) {
46 | this.parity = parity;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/CdcAcmSerialDriver.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbConstants;
25 | import android.hardware.usb.UsbDevice;
26 | import android.hardware.usb.UsbDeviceConnection;
27 | import android.hardware.usb.UsbEndpoint;
28 | import android.hardware.usb.UsbInterface;
29 | import android.hardware.usb.UsbRequest;
30 | import android.os.Build;
31 | import android.util.Log;
32 |
33 | import java.io.IOException;
34 | import java.nio.ByteBuffer;
35 | import java.util.Collections;
36 | import java.util.LinkedHashMap;
37 | import java.util.List;
38 | import java.util.Map;
39 |
40 | /**
41 | * USB CDC/ACM serial driver implementation.
42 | *
43 | * @author mike wakerly (opensource@hoho.com)
44 | * @see Universal
46 | * Serial Bus Class Definitions for Communication Devices, v1.1
47 | */
48 | public class CdcAcmSerialDriver implements UsbSerialDriver {
49 |
50 | private final String TAG = CdcAcmSerialDriver.class.getSimpleName();
51 |
52 | private final UsbDevice mDevice;
53 | private final UsbSerialPort mPort;
54 |
55 | public CdcAcmSerialDriver(UsbDevice device) {
56 | mDevice = device;
57 | mPort = new CdcAcmSerialPort(device, 0);
58 | }
59 |
60 | @Override
61 | public UsbDevice getDevice() {
62 | return mDevice;
63 | }
64 |
65 | @Override
66 | public List getPorts() {
67 | return Collections.singletonList(mPort);
68 | }
69 |
70 | class CdcAcmSerialPort extends CommonUsbSerialPort {
71 |
72 | private final boolean mEnableAsyncReads;
73 | private UsbInterface mControlInterface;
74 | private UsbInterface mDataInterface;
75 |
76 | private UsbEndpoint mControlEndpoint;
77 | private UsbEndpoint mReadEndpoint;
78 | private UsbEndpoint mWriteEndpoint;
79 |
80 | private boolean mRts = false;
81 | private boolean mDtr = false;
82 |
83 | private static final int USB_RECIP_INTERFACE = 0x01;
84 | private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;
85 |
86 | private static final int SET_LINE_CODING = 0x20; // USB CDC 1.1 section 6.2
87 | private static final int GET_LINE_CODING = 0x21;
88 | private static final int SET_CONTROL_LINE_STATE = 0x22;
89 | private static final int SEND_BREAK = 0x23;
90 |
91 | public CdcAcmSerialPort(UsbDevice device, int portNumber) {
92 | super(device, portNumber);
93 | mEnableAsyncReads = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1);
94 | }
95 |
96 | @Override
97 | public UsbSerialDriver getDriver() {
98 | return CdcAcmSerialDriver.this;
99 | }
100 |
101 | @Override
102 | public void open(UsbDeviceConnection connection) throws IOException {
103 | if (mConnection != null) {
104 | throw new IOException("Already open");
105 | }
106 |
107 | mConnection = connection;
108 | boolean opened = false;
109 | try {
110 |
111 | if (1 == mDevice.getInterfaceCount()) {
112 | Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
113 | openSingleInterface();
114 | } else {
115 | Log.d(TAG,"trying default interface logic");
116 | openInterface();
117 | }
118 |
119 | if (mEnableAsyncReads) {
120 | Log.d(TAG, "Async reads enabled");
121 | } else {
122 | Log.d(TAG, "Async reads disabled.");
123 | }
124 |
125 |
126 | opened = true;
127 | } finally {
128 | if (!opened) {
129 | mConnection = null;
130 | // just to be on the save side
131 | mControlEndpoint = null;
132 | mReadEndpoint = null;
133 | mWriteEndpoint = null;
134 | }
135 | }
136 | }
137 |
138 | private void openSingleInterface() throws IOException {
139 | // the following code is inspired by the cdc-acm driver
140 | // in the linux kernel
141 |
142 | mControlInterface = mDevice.getInterface(0);
143 | Log.d(TAG, "Control iface=" + mControlInterface);
144 |
145 | mDataInterface = mDevice.getInterface(0);
146 | Log.d(TAG, "data iface=" + mDataInterface);
147 |
148 | if (!mConnection.claimInterface(mControlInterface, true)) {
149 | throw new IOException("Could not claim shared control/data interface.");
150 | }
151 |
152 | int endCount = mControlInterface.getEndpointCount();
153 |
154 | if (endCount < 3) {
155 | Log.d(TAG,"not enough endpoints - need 3. count=" + mControlInterface.getEndpointCount());
156 | throw new IOException("Insufficient number of endpoints(" + mControlInterface.getEndpointCount() + ")");
157 | }
158 |
159 | // Analyse endpoints for their properties
160 | mControlEndpoint = null;
161 | mReadEndpoint = null;
162 | mWriteEndpoint = null;
163 | for (int i = 0; i < endCount; ++i) {
164 | UsbEndpoint ep = mControlInterface.getEndpoint(i);
165 | if ((ep.getDirection() == UsbConstants.USB_DIR_IN) &&
166 | (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) {
167 | Log.d(TAG,"Found controlling endpoint");
168 | mControlEndpoint = ep;
169 | } else if ((ep.getDirection() == UsbConstants.USB_DIR_IN) &&
170 | (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
171 | Log.d(TAG,"Found reading endpoint");
172 | mReadEndpoint = ep;
173 | } else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) &&
174 | (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
175 | Log.d(TAG,"Found writing endpoint");
176 | mWriteEndpoint = ep;
177 | }
178 |
179 |
180 | if ((mControlEndpoint != null) &&
181 | (mReadEndpoint != null) &&
182 | (mWriteEndpoint != null)) {
183 | Log.d(TAG,"Found all required endpoints");
184 | break;
185 | }
186 | }
187 |
188 | if ((mControlEndpoint == null) ||
189 | (mReadEndpoint == null) ||
190 | (mWriteEndpoint == null)) {
191 | Log.d(TAG,"Could not establish all endpoints");
192 | throw new IOException("Could not establish all endpoints");
193 | }
194 | }
195 |
196 | private void openInterface() throws IOException {
197 | Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
198 |
199 | mControlInterface = mDevice.getInterface(0);
200 | Log.d(TAG, "Control iface=" + mControlInterface);
201 | // class should be USB_CLASS_COMM
202 |
203 | if (!mConnection.claimInterface(mControlInterface, true)) {
204 | throw new IOException("Could not claim control interface.");
205 | }
206 |
207 | mControlEndpoint = mControlInterface.getEndpoint(0);
208 | Log.d(TAG, "Control endpoint direction: " + mControlEndpoint.getDirection());
209 |
210 | Log.d(TAG, "Claiming data interface.");
211 | mDataInterface = mDevice.getInterface(1);
212 | Log.d(TAG, "data iface=" + mDataInterface);
213 | // class should be USB_CLASS_CDC_DATA
214 |
215 | if (!mConnection.claimInterface(mDataInterface, true)) {
216 | throw new IOException("Could not claim data interface.");
217 | }
218 | mReadEndpoint = mDataInterface.getEndpoint(1);
219 | Log.d(TAG, "Read endpoint direction: " + mReadEndpoint.getDirection());
220 | mWriteEndpoint = mDataInterface.getEndpoint(0);
221 | Log.d(TAG, "Write endpoint direction: " + mWriteEndpoint.getDirection());
222 | }
223 |
224 | private int sendAcmControlMessage(int request, int value, byte[] buf) {
225 | return mConnection.controlTransfer(
226 | USB_RT_ACM, request, value, 0, buf, buf != null ? buf.length : 0, 5000);
227 | }
228 |
229 | @Override
230 | public void close() throws IOException {
231 | if (mConnection == null) {
232 | throw new IOException("Already closed");
233 | }
234 | mConnection.close();
235 | mConnection = null;
236 | }
237 |
238 | @Override
239 | public int read(byte[] dest, int timeoutMillis) throws IOException {
240 | if (mEnableAsyncReads) {
241 | final UsbRequest request = new UsbRequest();
242 | try {
243 | request.initialize(mConnection, mReadEndpoint);
244 | final ByteBuffer buf = ByteBuffer.wrap(dest);
245 | if (!request.queue(buf, dest.length)) {
246 | throw new IOException("Error queueing request.");
247 | }
248 |
249 | final UsbRequest response = mConnection.requestWait();
250 | if (response == null) {
251 | throw new IOException("Null response");
252 | }
253 |
254 | final int nread = buf.position();
255 | if (nread > 0) {
256 | //Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
257 | return nread;
258 | } else {
259 | return 0;
260 | }
261 | } finally {
262 | request.close();
263 | }
264 | }
265 |
266 | final int numBytesRead;
267 | synchronized (mReadBufferLock) {
268 | int readAmt = Math.min(dest.length, mReadBuffer.length);
269 | numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt,
270 | timeoutMillis);
271 | if (numBytesRead < 0) {
272 | // This sucks: we get -1 on timeout, not 0 as preferred.
273 | // We *should* use UsbRequest, except it has a bug/api oversight
274 | // where there is no way to determine the number of bytes read
275 | // in response :\ -- http://b.android.com/28023
276 | if (timeoutMillis == Integer.MAX_VALUE) {
277 | // Hack: Special case "~infinite timeout" as an error.
278 | return -1;
279 | }
280 | return 0;
281 | }
282 | System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
283 | }
284 | return numBytesRead;
285 | }
286 |
287 | @Override
288 | public int write(byte[] src, int timeoutMillis) throws IOException {
289 | // TODO(mikey): Nearly identical to FtdiSerial write. Refactor.
290 | int offset = 0;
291 |
292 | while (offset < src.length) {
293 | final int writeLength;
294 | final int amtWritten;
295 |
296 | synchronized (mWriteBufferLock) {
297 | final byte[] writeBuffer;
298 |
299 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
300 | if (offset == 0) {
301 | writeBuffer = src;
302 | } else {
303 | // bulkTransfer does not support offsets, make a copy.
304 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
305 | writeBuffer = mWriteBuffer;
306 | }
307 |
308 | amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
309 | timeoutMillis);
310 | }
311 | if (amtWritten <= 0) {
312 | throw new IOException("Error writing " + writeLength
313 | + " bytes at offset " + offset + " length=" + src.length);
314 | }
315 |
316 | Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
317 | offset += amtWritten;
318 | }
319 | return offset;
320 | }
321 |
322 | @Override
323 | public void setParameters(int baudRate, int dataBits, int stopBits, int parity) {
324 | byte stopBitsByte;
325 | switch (stopBits) {
326 | case STOPBITS_1: stopBitsByte = 0; break;
327 | case STOPBITS_1_5: stopBitsByte = 1; break;
328 | case STOPBITS_2: stopBitsByte = 2; break;
329 | default: throw new IllegalArgumentException("Bad value for stopBits: " + stopBits);
330 | }
331 |
332 | byte parityBitesByte;
333 | switch (parity) {
334 | case PARITY_NONE: parityBitesByte = 0; break;
335 | case PARITY_ODD: parityBitesByte = 1; break;
336 | case PARITY_EVEN: parityBitesByte = 2; break;
337 | case PARITY_MARK: parityBitesByte = 3; break;
338 | case PARITY_SPACE: parityBitesByte = 4; break;
339 | default: throw new IllegalArgumentException("Bad value for parity: " + parity);
340 | }
341 |
342 | byte[] msg = {
343 | (byte) ( baudRate & 0xff),
344 | (byte) ((baudRate >> 8 ) & 0xff),
345 | (byte) ((baudRate >> 16) & 0xff),
346 | (byte) ((baudRate >> 24) & 0xff),
347 | stopBitsByte,
348 | parityBitesByte,
349 | (byte) dataBits};
350 | sendAcmControlMessage(SET_LINE_CODING, 0, msg);
351 | }
352 |
353 | @Override
354 | public boolean getCD() throws IOException {
355 | return false; // TODO
356 | }
357 |
358 | @Override
359 | public boolean getCTS() throws IOException {
360 | return false; // TODO
361 | }
362 |
363 | @Override
364 | public boolean getDSR() throws IOException {
365 | return false; // TODO
366 | }
367 |
368 | @Override
369 | public boolean getDTR() throws IOException {
370 | return mDtr;
371 | }
372 |
373 | @Override
374 | public void setDTR(boolean value) throws IOException {
375 | mDtr = value;
376 | setDtrRts();
377 | }
378 |
379 | @Override
380 | public boolean getRI() throws IOException {
381 | return false; // TODO
382 | }
383 |
384 | @Override
385 | public boolean getRTS() throws IOException {
386 | return mRts;
387 | }
388 |
389 | @Override
390 | public void setRTS(boolean value) throws IOException {
391 | mRts = value;
392 | setDtrRts();
393 | }
394 |
395 | private void setDtrRts() {
396 | int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0);
397 | sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
398 | }
399 |
400 | }
401 |
402 | public static Map getSupportedDevices() {
403 | final Map supportedDevices = new LinkedHashMap();
404 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ARDUINO),
405 | new int[] {
406 | UsbId.ARDUINO_UNO,
407 | UsbId.ARDUINO_UNO_R3,
408 | UsbId.ARDUINO_MEGA_2560,
409 | UsbId.ARDUINO_MEGA_2560_R3,
410 | UsbId.ARDUINO_SERIAL_ADAPTER,
411 | UsbId.ARDUINO_SERIAL_ADAPTER_R3,
412 | UsbId.ARDUINO_MEGA_ADK,
413 | UsbId.ARDUINO_MEGA_ADK_R3,
414 | UsbId.ARDUINO_LEONARDO,
415 | UsbId.ARDUINO_MICRO,
416 | });
417 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_VAN_OOIJEN_TECH),
418 | new int[] {
419 | UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL,
420 | });
421 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ATMEL),
422 | new int[] {
423 | UsbId.ATMEL_LUFA_CDC_DEMO_APP,
424 | });
425 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_LEAFLABS),
426 | new int[] {
427 | UsbId.LEAFLABS_MAPLE,
428 | });
429 | return supportedDevices;
430 | }
431 |
432 | }
433 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/Ch34xSerialDriver.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2014 Andreas Butti
2 | *
3 | * This library is free software; you can redistribute it and/or
4 | * modify it under the terms of the GNU Lesser General Public
5 | * License as published by the Free Software Foundation; either
6 | * version 2.1 of the License, or (at your option) any later version.
7 | *
8 | * This library is distributed in the hope that it will be useful,
9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | * Lesser General Public License for more details.
12 | *
13 | * You should have received a copy of the GNU Lesser General Public
14 | * License along with this library; if not, write to the Free Software
15 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
16 | * USA.
17 | *
18 | * Project home page: https://github.com/mik3y/usb-serial-for-android
19 | */
20 |
21 | package com.nianlun.libserialport.usbdriver;
22 |
23 | import android.hardware.usb.UsbConstants;
24 | import android.hardware.usb.UsbDevice;
25 | import android.hardware.usb.UsbDeviceConnection;
26 | import android.hardware.usb.UsbEndpoint;
27 | import android.hardware.usb.UsbInterface;
28 | import android.util.Log;
29 |
30 | import java.io.IOException;
31 | import java.util.Collections;
32 | import java.util.LinkedHashMap;
33 | import java.util.List;
34 | import java.util.Map;
35 |
36 | /**
37 | * Driver for CH340, maybe also working with CH341, but not tested
38 | * See http://wch-ic.com/product/usb/ch340.asp
39 | *
40 | * @author Andreas Butti
41 | */
42 | public class Ch34xSerialDriver implements UsbSerialDriver {
43 |
44 | private static final String TAG = Ch34xSerialDriver.class.getSimpleName();
45 |
46 | private final UsbDevice mDevice;
47 | private final UsbSerialPort mPort;
48 |
49 | public Ch34xSerialDriver(UsbDevice device) {
50 | mDevice = device;
51 | mPort = new Ch340SerialPort(mDevice, 0);
52 | }
53 |
54 | @Override
55 | public UsbDevice getDevice() {
56 | return mDevice;
57 | }
58 |
59 | @Override
60 | public List getPorts() {
61 | return Collections.singletonList(mPort);
62 | }
63 |
64 | public class Ch340SerialPort extends CommonUsbSerialPort {
65 |
66 | private static final int USB_TIMEOUT_MILLIS = 5000;
67 |
68 | private final int DEFAULT_BAUD_RATE = 9600;
69 |
70 | private boolean dtr = false;
71 | private boolean rts = false;
72 |
73 | private UsbEndpoint mReadEndpoint;
74 | private UsbEndpoint mWriteEndpoint;
75 |
76 | public Ch340SerialPort(UsbDevice device, int portNumber) {
77 | super(device, portNumber);
78 | }
79 |
80 | @Override
81 | public UsbSerialDriver getDriver() {
82 | return Ch34xSerialDriver.this;
83 | }
84 |
85 | @Override
86 | public void open(UsbDeviceConnection connection) throws IOException {
87 | if (mConnection != null) {
88 | throw new IOException("Already opened.");
89 | }
90 |
91 | mConnection = connection;
92 | boolean opened = false;
93 | try {
94 | for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
95 | UsbInterface usbIface = mDevice.getInterface(i);
96 | if (mConnection.claimInterface(usbIface, true)) {
97 | Log.d(TAG, "claimInterface " + i + " SUCCESS");
98 | } else {
99 | Log.d(TAG, "claimInterface " + i + " FAIL");
100 | }
101 | }
102 |
103 | UsbInterface dataIface = mDevice.getInterface(mDevice.getInterfaceCount() - 1);
104 | for (int i = 0; i < dataIface.getEndpointCount(); i++) {
105 | UsbEndpoint ep = dataIface.getEndpoint(i);
106 | if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
107 | if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
108 | mReadEndpoint = ep;
109 | } else {
110 | mWriteEndpoint = ep;
111 | }
112 | }
113 | }
114 |
115 |
116 | initialize();
117 | setBaudRate(DEFAULT_BAUD_RATE);
118 |
119 | opened = true;
120 | } finally {
121 | if (!opened) {
122 | try {
123 | close();
124 | } catch (IOException e) {
125 | // Ignore IOExceptions during close()
126 | }
127 | }
128 | }
129 | }
130 |
131 | @Override
132 | public void close() throws IOException {
133 | if (mConnection == null) {
134 | throw new IOException("Already closed");
135 | }
136 |
137 | // TODO: nothing sended on close, maybe needed?
138 |
139 | try {
140 | mConnection.close();
141 | } finally {
142 | mConnection = null;
143 | }
144 | }
145 |
146 |
147 | @Override
148 | public int read(byte[] dest, int timeoutMillis) throws IOException {
149 | final int numBytesRead;
150 | synchronized (mReadBufferLock) {
151 | int readAmt = Math.min(dest.length, mReadBuffer.length);
152 | numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt,
153 | timeoutMillis);
154 | if (numBytesRead < 0) {
155 | // This sucks: we get -1 on timeout, not 0 as preferred.
156 | // We *should* use UsbRequest, except it has a bug/api oversight
157 | // where there is no way to determine the number of bytes read
158 | // in response :\ -- http://b.android.com/28023
159 | return 0;
160 | }
161 | System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
162 | }
163 | return numBytesRead;
164 | }
165 |
166 | @Override
167 | public int write(byte[] src, int timeoutMillis) throws IOException {
168 | int offset = 0;
169 |
170 | while (offset < src.length) {
171 | final int writeLength;
172 | final int amtWritten;
173 |
174 | synchronized (mWriteBufferLock) {
175 | final byte[] writeBuffer;
176 |
177 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
178 | if (offset == 0) {
179 | writeBuffer = src;
180 | } else {
181 | // bulkTransfer does not support offsets, make a copy.
182 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
183 | writeBuffer = mWriteBuffer;
184 | }
185 |
186 | amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
187 | timeoutMillis);
188 | }
189 | if (amtWritten <= 0) {
190 | throw new IOException("Error writing " + writeLength
191 | + " bytes at offset " + offset + " length=" + src.length);
192 | }
193 |
194 | Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
195 | offset += amtWritten;
196 | }
197 | return offset;
198 | }
199 |
200 | private int controlOut(int request, int value, int index) {
201 | final int REQTYPE_HOST_TO_DEVICE = 0x41;
202 | return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request,
203 | value, index, null, 0, USB_TIMEOUT_MILLIS);
204 | }
205 |
206 |
207 | private int controlIn(int request, int value, int index, byte[] buffer) {
208 | final int REQTYPE_HOST_TO_DEVICE = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_IN;
209 | return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request,
210 | value, index, buffer, buffer.length, USB_TIMEOUT_MILLIS);
211 | }
212 |
213 |
214 | private void checkState(String msg, int request, int value, int[] expected) throws IOException {
215 | byte[] buffer = new byte[expected.length];
216 | int ret = controlIn(request, value, 0, buffer);
217 |
218 | if (ret < 0) {
219 | throw new IOException("Faild send cmd [" + msg + "]");
220 | }
221 |
222 | if (ret != expected.length) {
223 | throw new IOException("Expected " + expected.length + " bytes, but get " + ret + " [" + msg + "]");
224 | }
225 |
226 | for (int i = 0; i < expected.length; i++) {
227 | if (expected[i] == -1) {
228 | continue;
229 | }
230 |
231 | int current = buffer[i] & 0xff;
232 | if (expected[i] != current) {
233 | throw new IOException("Expected 0x" + Integer.toHexString(expected[i]) + " bytes, but get 0x" + Integer.toHexString(current) + " [" + msg + "]");
234 | }
235 | }
236 | }
237 |
238 | private void writeHandshakeByte() throws IOException {
239 | if (controlOut(0xa4, ~((dtr ? 1 << 5 : 0) | (rts ? 1 << 6 : 0)), 0) < 0) {
240 | throw new IOException("Faild to set handshake byte");
241 | }
242 | }
243 |
244 | private void initialize() throws IOException {
245 | checkState("init #1", 0x5f, 0, new int[]{-1 /* 0x27, 0x30 */, 0x00});
246 |
247 | if (controlOut(0xa1, 0, 0) < 0) {
248 | throw new IOException("init failed! #2");
249 | }
250 |
251 | setBaudRate(DEFAULT_BAUD_RATE);
252 |
253 | checkState("init #4", 0x95, 0x2518, new int[]{-1 /* 0x56, c3*/, 0x00});
254 |
255 | if (controlOut(0x9a, 0x2518, 0x0050) < 0) {
256 | throw new IOException("init failed! #5");
257 | }
258 |
259 | checkState("init #6", 0x95, 0x0706, new int[]{0xff, 0xee});
260 |
261 | if (controlOut(0xa1, 0x501f, 0xd90a) < 0) {
262 | throw new IOException("init failed! #7");
263 | }
264 |
265 | setBaudRate(DEFAULT_BAUD_RATE);
266 |
267 | writeHandshakeByte();
268 |
269 | checkState("init #10", 0x95, 0x0706, new int[]{-1/* 0x9f, 0xff*/, 0xee});
270 | }
271 |
272 |
273 | private void setBaudRate(int baudRate) throws IOException {
274 | int[] baud = new int[]{2400, 0xd901, 0x0038, 4800, 0x6402,
275 | 0x001f, 9600, 0xb202, 0x0013, 19200, 0xd902, 0x000d, 38400,
276 | 0x6403, 0x000a, 115200, 0xcc03, 0x0008};
277 |
278 | for (int i = 0; i < baud.length / 3; i++) {
279 | if (baud[i * 3] == baudRate) {
280 | int ret = controlOut(0x9a, 0x1312, baud[i * 3 + 1]);
281 | if (ret < 0) {
282 | throw new IOException("Error setting baud rate. #1");
283 | }
284 | ret = controlOut(0x9a, 0x0f2c, baud[i * 3 + 2]);
285 | if (ret < 0) {
286 | throw new IOException("Error setting baud rate. #1");
287 | }
288 |
289 | return;
290 | }
291 | }
292 |
293 |
294 | throw new IOException("Baud rate " + baudRate + " currently not supported");
295 | }
296 |
297 |
298 | @Override
299 | public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
300 | throws IOException {
301 | setBaudRate(baudRate);
302 |
303 | // TODO databit, stopbit and paraty set not implemented
304 | }
305 |
306 | @Override
307 | public boolean getCD() throws IOException {
308 | return false;
309 | }
310 |
311 | @Override
312 | public boolean getCTS() throws IOException {
313 | return false;
314 | }
315 |
316 | @Override
317 | public boolean getDSR() throws IOException {
318 | return false;
319 | }
320 |
321 | @Override
322 | public boolean getDTR() throws IOException {
323 | return dtr;
324 | }
325 |
326 | @Override
327 | public void setDTR(boolean value) throws IOException {
328 | dtr = value;
329 | writeHandshakeByte();
330 | }
331 |
332 | @Override
333 | public boolean getRI() throws IOException {
334 | return false;
335 | }
336 |
337 | @Override
338 | public boolean getRTS() throws IOException {
339 | return rts;
340 | }
341 |
342 | @Override
343 | public void setRTS(boolean value) throws IOException {
344 | rts = value;
345 | writeHandshakeByte();
346 | }
347 |
348 | @Override
349 | public boolean purgeHwBuffers(boolean purgeReadBuffers, boolean purgeWriteBuffers) throws IOException {
350 | return true;
351 | }
352 |
353 | }
354 |
355 | public static Map getSupportedDevices() {
356 | final Map supportedDevices = new LinkedHashMap();
357 | supportedDevices.put(UsbId.VENDOR_QINHENG, new int[]{
358 | UsbId.QINHENG_HL340
359 | });
360 | return supportedDevices;
361 | }
362 |
363 | }
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/CommonUsbSerialPort.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbDevice;
25 | import android.hardware.usb.UsbDeviceConnection;
26 |
27 | import java.io.IOException;
28 |
29 | /**
30 | * A base class shared by several driver implementations.
31 | *
32 | * @author mike wakerly (opensource@hoho.com)
33 | */
34 | abstract class CommonUsbSerialPort implements UsbSerialPort {
35 |
36 | public static final int DEFAULT_READ_BUFFER_SIZE = 16 * 1024;
37 | public static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
38 |
39 | protected final UsbDevice mDevice;
40 | protected final int mPortNumber;
41 |
42 | // non-null when open()
43 | protected UsbDeviceConnection mConnection = null;
44 |
45 | protected final Object mReadBufferLock = new Object();
46 | protected final Object mWriteBufferLock = new Object();
47 |
48 | /** Internal read buffer. Guarded by {@link #mReadBufferLock}. */
49 | protected byte[] mReadBuffer;
50 |
51 | /** Internal write buffer. Guarded by {@link #mWriteBufferLock}. */
52 | protected byte[] mWriteBuffer;
53 |
54 | public CommonUsbSerialPort(UsbDevice device, int portNumber) {
55 | mDevice = device;
56 | mPortNumber = portNumber;
57 |
58 | mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
59 | mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
60 | }
61 |
62 | @Override
63 | public String toString() {
64 | return String.format("<%s device_name=%s device_id=%s port_number=%s>",
65 | getClass().getSimpleName(), mDevice.getDeviceName(),
66 | mDevice.getDeviceId(), mPortNumber);
67 | }
68 |
69 | /**
70 | * Returns the currently-bound USB device.
71 | *
72 | * @return the device
73 | */
74 | public final UsbDevice getDevice() {
75 | return mDevice;
76 | }
77 |
78 | @Override
79 | public int getPortNumber() {
80 | return mPortNumber;
81 | }
82 |
83 | /**
84 | * Returns the device serial number
85 | * @return serial number
86 | */
87 | @Override
88 | public String getSerial() {
89 | return mConnection.getSerial();
90 | }
91 |
92 | /**
93 | * Sets the size of the internal buffer used to exchange data with the USB
94 | * stack for read operations. Most users should not need to change this.
95 | *
96 | * @param bufferSize the size in bytes
97 | */
98 | public final void setReadBufferSize(int bufferSize) {
99 | synchronized (mReadBufferLock) {
100 | if (bufferSize == mReadBuffer.length) {
101 | return;
102 | }
103 | mReadBuffer = new byte[bufferSize];
104 | }
105 | }
106 |
107 | /**
108 | * Sets the size of the internal buffer used to exchange data with the USB
109 | * stack for write operations. Most users should not need to change this.
110 | *
111 | * @param bufferSize the size in bytes
112 | */
113 | public final void setWriteBufferSize(int bufferSize) {
114 | synchronized (mWriteBufferLock) {
115 | if (bufferSize == mWriteBuffer.length) {
116 | return;
117 | }
118 | mWriteBuffer = new byte[bufferSize];
119 | }
120 | }
121 |
122 | @Override
123 | public abstract void open(UsbDeviceConnection connection) throws IOException;
124 |
125 | @Override
126 | public abstract void close() throws IOException;
127 |
128 | @Override
129 | public abstract int read(final byte[] dest, final int timeoutMillis) throws IOException;
130 |
131 | @Override
132 | public abstract int write(final byte[] src, final int timeoutMillis) throws IOException;
133 |
134 | @Override
135 | public abstract void setParameters(
136 | int baudRate, int dataBits, int stopBits, int parity) throws IOException;
137 |
138 | @Override
139 | public abstract boolean getCD() throws IOException;
140 |
141 | @Override
142 | public abstract boolean getCTS() throws IOException;
143 |
144 | @Override
145 | public abstract boolean getDSR() throws IOException;
146 |
147 | @Override
148 | public abstract boolean getDTR() throws IOException;
149 |
150 | @Override
151 | public abstract void setDTR(boolean value) throws IOException;
152 |
153 | @Override
154 | public abstract boolean getRI() throws IOException;
155 |
156 | @Override
157 | public abstract boolean getRTS() throws IOException;
158 |
159 | @Override
160 | public abstract void setRTS(boolean value) throws IOException;
161 |
162 | @Override
163 | public boolean purgeHwBuffers(boolean flushReadBuffers, boolean flushWriteBuffers) throws IOException {
164 | return !flushReadBuffers && !flushWriteBuffers;
165 | }
166 |
167 | }
168 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/Cp21xxSerialDriver.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbConstants;
25 | import android.hardware.usb.UsbDevice;
26 | import android.hardware.usb.UsbDeviceConnection;
27 | import android.hardware.usb.UsbEndpoint;
28 | import android.hardware.usb.UsbInterface;
29 | import android.util.Log;
30 |
31 | import java.io.IOException;
32 | import java.util.Collections;
33 | import java.util.LinkedHashMap;
34 | import java.util.List;
35 | import java.util.Map;
36 |
37 | public class Cp21xxSerialDriver implements UsbSerialDriver {
38 |
39 | private static final String TAG = Cp21xxSerialDriver.class.getSimpleName();
40 |
41 | private final UsbDevice mDevice;
42 | private final UsbSerialPort mPort;
43 |
44 | public Cp21xxSerialDriver(UsbDevice device) {
45 | mDevice = device;
46 | mPort = new Cp21xxSerialPort(mDevice, 0);
47 | }
48 |
49 | @Override
50 | public UsbDevice getDevice() {
51 | return mDevice;
52 | }
53 |
54 | @Override
55 | public List getPorts() {
56 | return Collections.singletonList(mPort);
57 | }
58 |
59 | public class Cp21xxSerialPort extends CommonUsbSerialPort {
60 |
61 | private static final int DEFAULT_BAUD_RATE = 9600;
62 |
63 | private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
64 |
65 | /*
66 | * Configuration Request Types
67 | */
68 | private static final int REQTYPE_HOST_TO_DEVICE = 0x41;
69 |
70 | /*
71 | * Configuration Request Codes
72 | */
73 | private static final int SILABSER_IFC_ENABLE_REQUEST_CODE = 0x00;
74 | private static final int SILABSER_SET_BAUDDIV_REQUEST_CODE = 0x01;
75 | private static final int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03;
76 | private static final int SILABSER_SET_MHS_REQUEST_CODE = 0x07;
77 | private static final int SILABSER_SET_BAUDRATE = 0x1E;
78 | private static final int SILABSER_FLUSH_REQUEST_CODE = 0x12;
79 |
80 | private static final int FLUSH_READ_CODE = 0x0a;
81 | private static final int FLUSH_WRITE_CODE = 0x05;
82 |
83 | /*
84 | * SILABSER_IFC_ENABLE_REQUEST_CODE
85 | */
86 | private static final int UART_ENABLE = 0x0001;
87 | private static final int UART_DISABLE = 0x0000;
88 |
89 | /*
90 | * SILABSER_SET_BAUDDIV_REQUEST_CODE
91 | */
92 | private static final int BAUD_RATE_GEN_FREQ = 0x384000;
93 |
94 | /*
95 | * SILABSER_SET_MHS_REQUEST_CODE
96 | */
97 | private static final int MCR_DTR = 0x0001;
98 | private static final int MCR_RTS = 0x0002;
99 | private static final int MCR_ALL = 0x0003;
100 |
101 | private static final int CONTROL_WRITE_DTR = 0x0100;
102 | private static final int CONTROL_WRITE_RTS = 0x0200;
103 |
104 | private UsbEndpoint mReadEndpoint;
105 | private UsbEndpoint mWriteEndpoint;
106 |
107 | public Cp21xxSerialPort(UsbDevice device, int portNumber) {
108 | super(device, portNumber);
109 | }
110 |
111 | @Override
112 | public UsbSerialDriver getDriver() {
113 | return Cp21xxSerialDriver.this;
114 | }
115 |
116 | private int setConfigSingle(int request, int value) {
117 | return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value,
118 | 0, null, 0, USB_WRITE_TIMEOUT_MILLIS);
119 | }
120 |
121 | @Override
122 | public void open(UsbDeviceConnection connection) throws IOException {
123 | if (mConnection != null) {
124 | throw new IOException("Already opened.");
125 | }
126 |
127 | mConnection = connection;
128 | boolean opened = false;
129 | try {
130 | for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
131 | UsbInterface usbIface = mDevice.getInterface(i);
132 | if (mConnection.claimInterface(usbIface, true)) {
133 | Log.d(TAG, "claimInterface " + i + " SUCCESS");
134 | } else {
135 | Log.d(TAG, "claimInterface " + i + " FAIL");
136 | }
137 | }
138 |
139 | UsbInterface dataIface = mDevice.getInterface(mDevice.getInterfaceCount() - 1);
140 | for (int i = 0; i < dataIface.getEndpointCount(); i++) {
141 | UsbEndpoint ep = dataIface.getEndpoint(i);
142 | if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
143 | if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
144 | mReadEndpoint = ep;
145 | } else {
146 | mWriteEndpoint = ep;
147 | }
148 | }
149 | }
150 |
151 | setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
152 | setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
153 | setConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
154 | // setParameters(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY);
155 | opened = true;
156 | } finally {
157 | if (!opened) {
158 | try {
159 | close();
160 | } catch (IOException e) {
161 | // Ignore IOExceptions during close()
162 | }
163 | }
164 | }
165 | }
166 |
167 | @Override
168 | public void close() throws IOException {
169 | if (mConnection == null) {
170 | throw new IOException("Already closed");
171 | }
172 | try {
173 | setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE);
174 | mConnection.close();
175 | } finally {
176 | mConnection = null;
177 | }
178 | }
179 |
180 | @Override
181 | public int read(byte[] dest, int timeoutMillis) throws IOException {
182 | final int numBytesRead;
183 | synchronized (mReadBufferLock) {
184 | int readAmt = Math.min(dest.length, mReadBuffer.length);
185 | numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt,
186 | timeoutMillis);
187 | if (numBytesRead < 0) {
188 | // This sucks: we get -1 on timeout, not 0 as preferred.
189 | // We *should* use UsbRequest, except it has a bug/api oversight
190 | // where there is no way to determine the number of bytes read
191 | // in response :\ -- http://b.android.com/28023
192 | return 0;
193 | }
194 | System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
195 | }
196 | return numBytesRead;
197 | }
198 |
199 | @Override
200 | public int write(byte[] src, int timeoutMillis) throws IOException {
201 | int offset = 0;
202 |
203 | while (offset < src.length) {
204 | final int writeLength;
205 | final int amtWritten;
206 |
207 | synchronized (mWriteBufferLock) {
208 | final byte[] writeBuffer;
209 |
210 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
211 | if (offset == 0) {
212 | writeBuffer = src;
213 | } else {
214 | // bulkTransfer does not support offsets, make a copy.
215 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
216 | writeBuffer = mWriteBuffer;
217 | }
218 |
219 | amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
220 | timeoutMillis);
221 | }
222 | if (amtWritten <= 0) {
223 | throw new IOException("Error writing " + writeLength
224 | + " bytes at offset " + offset + " length=" + src.length);
225 | }
226 |
227 | Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
228 | offset += amtWritten;
229 | }
230 | return offset;
231 | }
232 |
233 | private void setBaudRate(int baudRate) throws IOException {
234 | byte[] data = new byte[]{
235 | (byte) (baudRate & 0xff),
236 | (byte) ((baudRate >> 8) & 0xff),
237 | (byte) ((baudRate >> 16) & 0xff),
238 | (byte) ((baudRate >> 24) & 0xff)
239 | };
240 | int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
241 | 0, 0, data, 4, USB_WRITE_TIMEOUT_MILLIS);
242 | if (ret < 0) {
243 | throw new IOException("Error setting baud rate.");
244 | }
245 | }
246 |
247 | @Override
248 | public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
249 | throws IOException {
250 | setBaudRate(baudRate);
251 |
252 | int configDataBits = 0;
253 | switch (dataBits) {
254 | case DATABITS_5:
255 | configDataBits |= 0x0500;
256 | break;
257 | case DATABITS_6:
258 | configDataBits |= 0x0600;
259 | break;
260 | case DATABITS_7:
261 | configDataBits |= 0x0700;
262 | break;
263 | case DATABITS_8:
264 | configDataBits |= 0x0800;
265 | break;
266 | default:
267 | configDataBits |= 0x0800;
268 | break;
269 | }
270 |
271 | switch (parity) {
272 | case PARITY_ODD:
273 | configDataBits |= 0x0010;
274 | break;
275 | case PARITY_EVEN:
276 | configDataBits |= 0x0020;
277 | break;
278 | default:
279 | break;
280 | }
281 |
282 | switch (stopBits) {
283 | case STOPBITS_1:
284 | configDataBits |= 0;
285 | break;
286 | case STOPBITS_2:
287 | configDataBits |= 2;
288 | break;
289 | default:
290 | break;
291 | }
292 | setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
293 | }
294 |
295 | @Override
296 | public boolean getCD() throws IOException {
297 | return false;
298 | }
299 |
300 | @Override
301 | public boolean getCTS() throws IOException {
302 | return false;
303 | }
304 |
305 | @Override
306 | public boolean getDSR() throws IOException {
307 | return false;
308 | }
309 |
310 | @Override
311 | public boolean getDTR() throws IOException {
312 | return true;
313 | }
314 |
315 | @Override
316 | public void setDTR(boolean value) throws IOException {
317 | }
318 |
319 | @Override
320 | public boolean getRI() throws IOException {
321 | return false;
322 | }
323 |
324 | @Override
325 | public boolean getRTS() throws IOException {
326 | return true;
327 | }
328 |
329 | @Override
330 | public void setRTS(boolean value) throws IOException {
331 | }
332 |
333 | @Override
334 | public boolean purgeHwBuffers(boolean purgeReadBuffers,
335 | boolean purgeWriteBuffers) throws IOException {
336 | int value = (purgeReadBuffers ? FLUSH_READ_CODE : 0)
337 | | (purgeWriteBuffers ? FLUSH_WRITE_CODE : 0);
338 |
339 | if (value != 0) {
340 | setConfigSingle(SILABSER_FLUSH_REQUEST_CODE, value);
341 | }
342 |
343 | return true;
344 | }
345 |
346 | }
347 |
348 | public static Map getSupportedDevices() {
349 | final Map supportedDevices = new LinkedHashMap();
350 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_SILABS),
351 | new int[]{
352 | UsbId.SILABS_CP2102,
353 | UsbId.SILABS_CP2105,
354 | UsbId.SILABS_CP2108,
355 | UsbId.SILABS_CP2110
356 | });
357 | return supportedDevices;
358 | }
359 |
360 | }
361 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/HexDump.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2006 The Android Open Source Project
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 com.nianlun.libserialport.usbdriver;
18 |
19 | /**
20 | * Clone of Android's HexDump class, for use in debugging. Cosmetic changes
21 | * only.
22 | */
23 | public class HexDump {
24 | private final static char[] HEX_DIGITS = {
25 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
26 | };
27 |
28 | public static String dumpHexString(byte[] array) {
29 | return dumpHexString(array, 0, array.length);
30 | }
31 |
32 | public static String dumpHexString(byte[] array, int offset, int length) {
33 | StringBuilder result = new StringBuilder();
34 |
35 | byte[] line = new byte[16];
36 | int lineIndex = 0;
37 |
38 | result.append("\n0x");
39 | result.append(toHexString(offset));
40 |
41 | for (int i = offset; i < offset + length; i++) {
42 | if (lineIndex == 16) {
43 | result.append(" ");
44 |
45 | for (int j = 0; j < 16; j++) {
46 | if (line[j] > ' ' && line[j] < '~') {
47 | result.append(new String(line, j, 1));
48 | } else {
49 | result.append(".");
50 | }
51 | }
52 |
53 | result.append("\n0x");
54 | result.append(toHexString(i));
55 | lineIndex = 0;
56 | }
57 |
58 | byte b = array[i];
59 | result.append(" ");
60 | result.append(HEX_DIGITS[(b >>> 4) & 0x0F]);
61 | result.append(HEX_DIGITS[b & 0x0F]);
62 |
63 | line[lineIndex++] = b;
64 | }
65 |
66 | if (lineIndex != 16) {
67 | int count = (16 - lineIndex) * 3;
68 | count++;
69 | for (int i = 0; i < count; i++) {
70 | result.append(" ");
71 | }
72 |
73 | for (int i = 0; i < lineIndex; i++) {
74 | if (line[i] > ' ' && line[i] < '~') {
75 | result.append(new String(line, i, 1));
76 | } else {
77 | result.append(".");
78 | }
79 | }
80 | }
81 |
82 | return result.toString();
83 | }
84 |
85 | public static String toHexString(byte b) {
86 | return toHexString(toByteArray(b));
87 | }
88 |
89 | public static String toHexString(byte[] array) {
90 | return toHexString(array, 0, array.length);
91 | }
92 |
93 | public static String toHexString(byte[] array, int offset, int length) {
94 | char[] buf = new char[length * 2];
95 |
96 | int bufIndex = 0;
97 | for (int i = offset; i < offset + length; i++) {
98 | byte b = array[i];
99 | buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
100 | buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
101 | }
102 |
103 | return new String(buf);
104 | }
105 |
106 | public static String toHexString(int i) {
107 | return toHexString(toByteArray(i));
108 | }
109 |
110 | public static String toHexString(short i) {
111 | return toHexString(toByteArray(i));
112 | }
113 |
114 | public static byte[] toByteArray(byte b) {
115 | byte[] array = new byte[1];
116 | array[0] = b;
117 | return array;
118 | }
119 |
120 | public static byte[] toByteArray(int i) {
121 | byte[] array = new byte[4];
122 |
123 | array[3] = (byte) (i & 0xFF);
124 | array[2] = (byte) ((i >> 8) & 0xFF);
125 | array[1] = (byte) ((i >> 16) & 0xFF);
126 | array[0] = (byte) ((i >> 24) & 0xFF);
127 |
128 | return array;
129 | }
130 |
131 | public static byte[] toByteArray(short i) {
132 | byte[] array = new byte[2];
133 |
134 | array[1] = (byte) (i & 0xFF);
135 | array[0] = (byte) ((i >> 8) & 0xFF);
136 |
137 | return array;
138 | }
139 |
140 | private static int toByte(char c) {
141 | if (c >= '0' && c <= '9') {
142 | return (c - '0');
143 | }
144 | if (c >= 'A' && c <= 'F') {
145 | return (c - 'A' + 10);
146 | }
147 | if (c >= 'a' && c <= 'f') {
148 | return (c - 'a' + 10);
149 | }
150 |
151 | throw new RuntimeException("Invalid hex char '" + c + "'");
152 | }
153 |
154 | public static byte[] hexStringToByteArray(String hexString) {
155 | int length = hexString.length();
156 | byte[] buffer = new byte[length / 2];
157 |
158 | for (int i = 0; i < length; i += 2) {
159 | buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString
160 | .charAt(i + 1)));
161 | }
162 |
163 | return buffer;
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/ProbeTable.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.util.Pair;
25 |
26 | import java.lang.reflect.InvocationTargetException;
27 | import java.lang.reflect.Method;
28 | import java.util.LinkedHashMap;
29 | import java.util.Map;
30 |
31 | /**
32 | * Maps (vendor id, product id) pairs to the corresponding serial driver.
33 | *
34 | * @author mike wakerly (opensource@hoho.com)
35 | */
36 | public class ProbeTable {
37 |
38 | private final Map, Class extends UsbSerialDriver>> mProbeTable =
39 | new LinkedHashMap, Class extends UsbSerialDriver>>();
40 |
41 | /**
42 | * Adds or updates a (vendor, product) pair in the table.
43 | *
44 | * @param vendorId the USB vendor id
45 | * @param productId the USB product id
46 | * @param driverClass the driver class responsible for this pair
47 | * @return {@code this}, for chaining
48 | */
49 | public ProbeTable addProduct(int vendorId, int productId,
50 | Class extends UsbSerialDriver> driverClass) {
51 | mProbeTable.put(Pair.create(vendorId, productId), driverClass);
52 | return this;
53 | }
54 |
55 | /**
56 | * Internal method to add all supported products from
57 | * {@code getSupportedProducts} static method.
58 | *
59 | * @param driverClass
60 | * @return
61 | */
62 | @SuppressWarnings("unchecked")
63 | ProbeTable addDriver(Class extends UsbSerialDriver> driverClass) {
64 | final Method method;
65 |
66 | try {
67 | method = driverClass.getMethod("getSupportedDevices");
68 | } catch (SecurityException e) {
69 | throw new RuntimeException(e);
70 | } catch (NoSuchMethodException e) {
71 | throw new RuntimeException(e);
72 | }
73 |
74 | final Map devices;
75 | try {
76 | devices = (Map) method.invoke(null);
77 | } catch (IllegalArgumentException e) {
78 | throw new RuntimeException(e);
79 | } catch (IllegalAccessException e) {
80 | throw new RuntimeException(e);
81 | } catch (InvocationTargetException e) {
82 | throw new RuntimeException(e);
83 | }
84 |
85 | for (Map.Entry entry : devices.entrySet()) {
86 | final int vendorId = entry.getKey().intValue();
87 | for (int productId : entry.getValue()) {
88 | addProduct(vendorId, productId, driverClass);
89 | }
90 | }
91 |
92 | return this;
93 | }
94 |
95 | /**
96 | * Returns the driver for the given (vendor, product) pair, or {@code null}
97 | * if no match.
98 | *
99 | * @param vendorId the USB vendor id
100 | * @param productId the USB product id
101 | * @return the driver class matching this pair, or {@code null}
102 | */
103 | public Class extends UsbSerialDriver> findDriver(int vendorId, int productId) {
104 | final Pair pair = Pair.create(vendorId, productId);
105 | return mProbeTable.get(pair);
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/ProlificSerialDriver.java:
--------------------------------------------------------------------------------
1 | /* This library is free software; you can redistribute it and/or
2 | * modify it under the terms of the GNU Lesser General Public
3 | * License as published by the Free Software Foundation; either
4 | * version 2.1 of the License, or (at your option) any later version.
5 | *
6 | * This library is distributed in the hope that it will be useful,
7 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
8 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 | * Lesser General Public License for more details.
10 | *
11 | * You should have received a copy of the GNU Lesser General Public
12 | * License along with this library; if not, write to the Free Software
13 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
14 | * USA.
15 | *
16 | * Project home page: https://github.com/mik3y/usb-serial-for-android
17 | */
18 |
19 | /*
20 | * Ported to usb-serial-for-android
21 | * by Felix Hädicke
22 | *
23 | * Based on the pyprolific driver written
24 | * by Emmanuel Blot
25 | * See https://github.com/eblot/pyftdi
26 | */
27 |
28 | package com.nianlun.libserialport.usbdriver;
29 |
30 | import android.hardware.usb.UsbConstants;
31 | import android.hardware.usb.UsbDevice;
32 | import android.hardware.usb.UsbDeviceConnection;
33 | import android.hardware.usb.UsbEndpoint;
34 | import android.hardware.usb.UsbInterface;
35 | import android.util.Log;
36 |
37 | import java.io.IOException;
38 | import java.lang.reflect.Method;
39 | import java.util.Collections;
40 | import java.util.LinkedHashMap;
41 | import java.util.List;
42 | import java.util.Map;
43 |
44 | public class ProlificSerialDriver implements UsbSerialDriver {
45 |
46 | private final String TAG = ProlificSerialDriver.class.getSimpleName();
47 |
48 | private final UsbDevice mDevice;
49 | private final UsbSerialPort mPort;
50 |
51 | public ProlificSerialDriver(UsbDevice device) {
52 | mDevice = device;
53 | mPort = new ProlificSerialPort(mDevice, 0);
54 | }
55 |
56 | @Override
57 | public List getPorts() {
58 | return Collections.singletonList(mPort);
59 | }
60 |
61 | @Override
62 | public UsbDevice getDevice() {
63 | return mDevice;
64 | }
65 |
66 | class ProlificSerialPort extends CommonUsbSerialPort {
67 |
68 | private static final int USB_READ_TIMEOUT_MILLIS = 1000;
69 | private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
70 |
71 | private static final int USB_RECIP_INTERFACE = 0x01;
72 |
73 | private static final int PROLIFIC_VENDOR_READ_REQUEST = 0x01;
74 | private static final int PROLIFIC_VENDOR_WRITE_REQUEST = 0x01;
75 |
76 | private static final int PROLIFIC_VENDOR_OUT_REQTYPE = UsbConstants.USB_DIR_OUT
77 | | UsbConstants.USB_TYPE_VENDOR;
78 |
79 | private static final int PROLIFIC_VENDOR_IN_REQTYPE = UsbConstants.USB_DIR_IN
80 | | UsbConstants.USB_TYPE_VENDOR;
81 |
82 | private static final int PROLIFIC_CTRL_OUT_REQTYPE = UsbConstants.USB_DIR_OUT
83 | | UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;
84 |
85 | private static final int WRITE_ENDPOINT = 0x02;
86 | private static final int READ_ENDPOINT = 0x83;
87 | private static final int INTERRUPT_ENDPOINT = 0x81;
88 |
89 | private static final int FLUSH_RX_REQUEST = 0x08;
90 | private static final int FLUSH_TX_REQUEST = 0x09;
91 |
92 | private static final int SET_LINE_REQUEST = 0x20;
93 | private static final int SET_CONTROL_REQUEST = 0x22;
94 |
95 | private static final int CONTROL_DTR = 0x01;
96 | private static final int CONTROL_RTS = 0x02;
97 |
98 | private static final int STATUS_FLAG_CD = 0x01;
99 | private static final int STATUS_FLAG_DSR = 0x02;
100 | private static final int STATUS_FLAG_RI = 0x08;
101 | private static final int STATUS_FLAG_CTS = 0x80;
102 |
103 | private static final int STATUS_BUFFER_SIZE = 10;
104 | private static final int STATUS_BYTE_IDX = 8;
105 |
106 | private static final int DEVICE_TYPE_HX = 0;
107 | private static final int DEVICE_TYPE_0 = 1;
108 | private static final int DEVICE_TYPE_1 = 2;
109 |
110 | private int mDeviceType = DEVICE_TYPE_HX;
111 |
112 | private UsbEndpoint mReadEndpoint;
113 | private UsbEndpoint mWriteEndpoint;
114 | private UsbEndpoint mInterruptEndpoint;
115 |
116 | private int mControlLinesValue = 0;
117 |
118 | private int mBaudRate = -1, mDataBits = -1, mStopBits = -1, mParity = -1;
119 |
120 | private int mStatus = 0;
121 | private volatile Thread mReadStatusThread = null;
122 | private final Object mReadStatusThreadLock = new Object();
123 | boolean mStopReadStatusThread = false;
124 | private IOException mReadStatusException = null;
125 |
126 |
127 | public ProlificSerialPort(UsbDevice device, int portNumber) {
128 | super(device, portNumber);
129 | }
130 |
131 | @Override
132 | public UsbSerialDriver getDriver() {
133 | return ProlificSerialDriver.this;
134 | }
135 |
136 | private final byte[] inControlTransfer(int requestType, int request,
137 | int value, int index, int length) throws IOException {
138 | byte[] buffer = new byte[length];
139 | int result = mConnection.controlTransfer(requestType, request, value,
140 | index, buffer, length, USB_READ_TIMEOUT_MILLIS);
141 | if (result != length) {
142 | throw new IOException(
143 | String.format("ControlTransfer with value 0x%x failed: %d",
144 | value, result));
145 | }
146 | return buffer;
147 | }
148 |
149 | private final void outControlTransfer(int requestType, int request,
150 | int value, int index, byte[] data) throws IOException {
151 | int length = (data == null) ? 0 : data.length;
152 | int result = mConnection.controlTransfer(requestType, request, value,
153 | index, data, length, USB_WRITE_TIMEOUT_MILLIS);
154 | if (result != length) {
155 | throw new IOException(
156 | String.format("ControlTransfer with value 0x%x failed: %d",
157 | value, result));
158 | }
159 | }
160 |
161 | private final byte[] vendorIn(int value, int index, int length)
162 | throws IOException {
163 | return inControlTransfer(PROLIFIC_VENDOR_IN_REQTYPE,
164 | PROLIFIC_VENDOR_READ_REQUEST, value, index, length);
165 | }
166 |
167 | private final void vendorOut(int value, int index, byte[] data)
168 | throws IOException {
169 | outControlTransfer(PROLIFIC_VENDOR_OUT_REQTYPE,
170 | PROLIFIC_VENDOR_WRITE_REQUEST, value, index, data);
171 | }
172 |
173 | private void resetDevice() throws IOException {
174 | purgeHwBuffers(true, true);
175 | }
176 |
177 | private final void ctrlOut(int request, int value, int index, byte[] data)
178 | throws IOException {
179 | outControlTransfer(PROLIFIC_CTRL_OUT_REQTYPE, request, value, index,
180 | data);
181 | }
182 |
183 | private void doBlackMagic() throws IOException {
184 | vendorIn(0x8484, 0, 1);
185 | vendorOut(0x0404, 0, null);
186 | vendorIn(0x8484, 0, 1);
187 | vendorIn(0x8383, 0, 1);
188 | vendorIn(0x8484, 0, 1);
189 | vendorOut(0x0404, 1, null);
190 | vendorIn(0x8484, 0, 1);
191 | vendorIn(0x8383, 0, 1);
192 | vendorOut(0, 1, null);
193 | vendorOut(1, 0, null);
194 | vendorOut(2, (mDeviceType == DEVICE_TYPE_HX) ? 0x44 : 0x24, null);
195 | }
196 |
197 | private void setControlLines(int newControlLinesValue) throws IOException {
198 | ctrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null);
199 | mControlLinesValue = newControlLinesValue;
200 | }
201 |
202 | private final void readStatusThreadFunction() {
203 | try {
204 | while (!mStopReadStatusThread) {
205 | byte[] buffer = new byte[STATUS_BUFFER_SIZE];
206 | int readBytesCount = mConnection.bulkTransfer(mInterruptEndpoint,
207 | buffer,
208 | STATUS_BUFFER_SIZE,
209 | 500);
210 | if (readBytesCount > 0) {
211 | if (readBytesCount == STATUS_BUFFER_SIZE) {
212 | mStatus = buffer[STATUS_BYTE_IDX] & 0xff;
213 | } else {
214 | throw new IOException(
215 | String.format("Invalid CTS / DSR / CD / RI status buffer received, expected %d bytes, but received %d",
216 | STATUS_BUFFER_SIZE,
217 | readBytesCount));
218 | }
219 | }
220 | }
221 | } catch (IOException e) {
222 | mReadStatusException = e;
223 | }
224 | }
225 |
226 | private final int getStatus() throws IOException {
227 | if ((mReadStatusThread == null) && (mReadStatusException == null)) {
228 | synchronized (mReadStatusThreadLock) {
229 | if (mReadStatusThread == null) {
230 | byte[] buffer = new byte[STATUS_BUFFER_SIZE];
231 | int readBytes = mConnection.bulkTransfer(mInterruptEndpoint,
232 | buffer,
233 | STATUS_BUFFER_SIZE,
234 | 100);
235 | if (readBytes != STATUS_BUFFER_SIZE) {
236 | Log.w(TAG, "Could not read initial CTS / DSR / CD / RI status");
237 | } else {
238 | mStatus = buffer[STATUS_BYTE_IDX] & 0xff;
239 | }
240 |
241 | mReadStatusThread = new Thread(new Runnable() {
242 | @Override
243 | public void run() {
244 | readStatusThreadFunction();
245 | }
246 | });
247 | mReadStatusThread.setDaemon(true);
248 | mReadStatusThread.start();
249 | }
250 | }
251 | }
252 |
253 | /* throw and clear an exception which occured in the status read thread */
254 | IOException readStatusException = mReadStatusException;
255 | if (mReadStatusException != null) {
256 | mReadStatusException = null;
257 | throw readStatusException;
258 | }
259 |
260 | return mStatus;
261 | }
262 |
263 | private final boolean testStatusFlag(int flag) throws IOException {
264 | return ((getStatus() & flag) == flag);
265 | }
266 |
267 | @Override
268 | public void open(UsbDeviceConnection connection) throws IOException {
269 | if (mConnection != null) {
270 | throw new IOException("Already open");
271 | }
272 |
273 | UsbInterface usbInterface = mDevice.getInterface(0);
274 |
275 | if (!connection.claimInterface(usbInterface, true)) {
276 | throw new IOException("Error claiming Prolific interface 0");
277 | }
278 |
279 | mConnection = connection;
280 | boolean opened = false;
281 | try {
282 | for (int i = 0; i < usbInterface.getEndpointCount(); ++i) {
283 | UsbEndpoint currentEndpoint = usbInterface.getEndpoint(i);
284 |
285 | switch (currentEndpoint.getAddress()) {
286 | case READ_ENDPOINT:
287 | mReadEndpoint = currentEndpoint;
288 | break;
289 |
290 | case WRITE_ENDPOINT:
291 | mWriteEndpoint = currentEndpoint;
292 | break;
293 |
294 | case INTERRUPT_ENDPOINT:
295 | mInterruptEndpoint = currentEndpoint;
296 | break;
297 | default:
298 | break;
299 | }
300 | }
301 |
302 | if (mDevice.getDeviceClass() == 0x02) {
303 | mDeviceType = DEVICE_TYPE_0;
304 | } else {
305 | try {
306 | Method getRawDescriptorsMethod
307 | = mConnection.getClass().getMethod("getRawDescriptors");
308 | byte[] rawDescriptors
309 | = (byte[]) getRawDescriptorsMethod.invoke(mConnection);
310 | byte maxPacketSize0 = rawDescriptors[7];
311 | if (maxPacketSize0 == 64) {
312 | mDeviceType = DEVICE_TYPE_HX;
313 | } else if ((mDevice.getDeviceClass() == 0x00)
314 | || (mDevice.getDeviceClass() == 0xff)) {
315 | mDeviceType = DEVICE_TYPE_1;
316 | } else {
317 | Log.w(TAG, "Could not detect PL2303 subtype, "
318 | + "Assuming that it is a HX device");
319 | mDeviceType = DEVICE_TYPE_HX;
320 | }
321 | } catch (NoSuchMethodException e) {
322 | Log.w(TAG, "Method UsbDeviceConnection.getRawDescriptors, "
323 | + "required for PL2303 subtype detection, not "
324 | + "available! Assuming that it is a HX device");
325 | mDeviceType = DEVICE_TYPE_HX;
326 | } catch (Exception e) {
327 | Log.e(TAG, "An unexpected exception occured while trying "
328 | + "to detect PL2303 subtype", e);
329 | }
330 | }
331 |
332 | setControlLines(mControlLinesValue);
333 | resetDevice();
334 |
335 | doBlackMagic();
336 | opened = true;
337 | } finally {
338 | if (!opened) {
339 | mConnection = null;
340 | connection.releaseInterface(usbInterface);
341 | }
342 | }
343 | }
344 |
345 | @Override
346 | public void close() throws IOException {
347 | if (mConnection == null) {
348 | throw new IOException("Already closed");
349 | }
350 | try {
351 | mStopReadStatusThread = true;
352 | synchronized (mReadStatusThreadLock) {
353 | if (mReadStatusThread != null) {
354 | try {
355 | mReadStatusThread.join();
356 | } catch (Exception e) {
357 | Log.w(TAG, "An error occured while waiting for status read thread", e);
358 | }
359 | }
360 | }
361 | resetDevice();
362 | } finally {
363 | try {
364 | mConnection.releaseInterface(mDevice.getInterface(0));
365 | } finally {
366 | mConnection = null;
367 | }
368 | }
369 | }
370 |
371 | @Override
372 | public int read(byte[] dest, int timeoutMillis) throws IOException {
373 | synchronized (mReadBufferLock) {
374 | int readAmt = Math.min(dest.length, mReadBuffer.length);
375 | int numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer,
376 | readAmt, timeoutMillis);
377 | if (numBytesRead < 0) {
378 | return 0;
379 | }
380 | System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
381 | return numBytesRead;
382 | }
383 | }
384 |
385 | @Override
386 | public int write(byte[] src, int timeoutMillis) throws IOException {
387 | int offset = 0;
388 |
389 | while (offset < src.length) {
390 | final int writeLength;
391 | final int amtWritten;
392 |
393 | synchronized (mWriteBufferLock) {
394 | final byte[] writeBuffer;
395 |
396 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
397 | if (offset == 0) {
398 | writeBuffer = src;
399 | } else {
400 | // bulkTransfer does not support offsets, make a copy.
401 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
402 | writeBuffer = mWriteBuffer;
403 | }
404 |
405 | amtWritten = mConnection.bulkTransfer(mWriteEndpoint,
406 | writeBuffer, writeLength, timeoutMillis);
407 | }
408 |
409 | if (amtWritten <= 0) {
410 | throw new IOException("Error writing " + writeLength
411 | + " bytes at offset " + offset + " length="
412 | + src.length);
413 | }
414 |
415 | offset += amtWritten;
416 | }
417 | return offset;
418 | }
419 |
420 | @Override
421 | public void setParameters(int baudRate, int dataBits, int stopBits,
422 | int parity) throws IOException {
423 | if ((mBaudRate == baudRate) && (mDataBits == dataBits)
424 | && (mStopBits == stopBits) && (mParity == parity)) {
425 | // Make sure no action is performed if there is nothing to change
426 | return;
427 | }
428 |
429 | byte[] lineRequestData = new byte[7];
430 |
431 | lineRequestData[0] = (byte) (baudRate & 0xff);
432 | lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff);
433 | lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff);
434 | lineRequestData[3] = (byte) ((baudRate >> 24) & 0xff);
435 |
436 | switch (stopBits) {
437 | case STOPBITS_1:
438 | lineRequestData[4] = 0;
439 | break;
440 |
441 | case STOPBITS_1_5:
442 | lineRequestData[4] = 1;
443 | break;
444 |
445 | case STOPBITS_2:
446 | lineRequestData[4] = 2;
447 | break;
448 |
449 | default:
450 | throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
451 | }
452 |
453 | switch (parity) {
454 | case PARITY_NONE:
455 | lineRequestData[5] = 0;
456 | break;
457 |
458 | case PARITY_ODD:
459 | lineRequestData[5] = 1;
460 | break;
461 |
462 | case PARITY_EVEN:
463 | lineRequestData[5] = 2;
464 | break;
465 |
466 | case PARITY_MARK:
467 | lineRequestData[5] = 3;
468 | break;
469 |
470 | case PARITY_SPACE:
471 | lineRequestData[5] = 4;
472 | break;
473 |
474 | default:
475 | throw new IllegalArgumentException("Unknown parity value: " + parity);
476 | }
477 |
478 | lineRequestData[6] = (byte) dataBits;
479 |
480 | ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);
481 |
482 | resetDevice();
483 |
484 | mBaudRate = baudRate;
485 | mDataBits = dataBits;
486 | mStopBits = stopBits;
487 | mParity = parity;
488 | }
489 |
490 | @Override
491 | public boolean getCD() throws IOException {
492 | return testStatusFlag(STATUS_FLAG_CD);
493 | }
494 |
495 | @Override
496 | public boolean getCTS() throws IOException {
497 | return testStatusFlag(STATUS_FLAG_CTS);
498 | }
499 |
500 | @Override
501 | public boolean getDSR() throws IOException {
502 | return testStatusFlag(STATUS_FLAG_DSR);
503 | }
504 |
505 | @Override
506 | public boolean getDTR() throws IOException {
507 | return ((mControlLinesValue & CONTROL_DTR) == CONTROL_DTR);
508 | }
509 |
510 | @Override
511 | public void setDTR(boolean value) throws IOException {
512 | int newControlLinesValue;
513 | if (value) {
514 | newControlLinesValue = mControlLinesValue | CONTROL_DTR;
515 | } else {
516 | newControlLinesValue = mControlLinesValue & ~CONTROL_DTR;
517 | }
518 | setControlLines(newControlLinesValue);
519 | }
520 |
521 | @Override
522 | public boolean getRI() throws IOException {
523 | return testStatusFlag(STATUS_FLAG_RI);
524 | }
525 |
526 | @Override
527 | public boolean getRTS() throws IOException {
528 | return ((mControlLinesValue & CONTROL_RTS) == CONTROL_RTS);
529 | }
530 |
531 | @Override
532 | public void setRTS(boolean value) throws IOException {
533 | int newControlLinesValue;
534 | if (value) {
535 | newControlLinesValue = mControlLinesValue | CONTROL_RTS;
536 | } else {
537 | newControlLinesValue = mControlLinesValue & ~CONTROL_RTS;
538 | }
539 | setControlLines(newControlLinesValue);
540 | }
541 |
542 | @Override
543 | public boolean purgeHwBuffers(boolean purgeReadBuffers, boolean purgeWriteBuffers) throws IOException {
544 | if (purgeReadBuffers) {
545 | vendorOut(FLUSH_RX_REQUEST, 0, null);
546 | }
547 |
548 | if (purgeWriteBuffers) {
549 | vendorOut(FLUSH_TX_REQUEST, 0, null);
550 | }
551 |
552 | return purgeReadBuffers || purgeWriteBuffers;
553 | }
554 | }
555 |
556 | public static Map getSupportedDevices() {
557 | final Map supportedDevices = new LinkedHashMap();
558 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_PROLIFIC),
559 | new int[]{UsbId.PROLIFIC_PL2303,});
560 | return supportedDevices;
561 | }
562 | }
563 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/SerialInputOutputManager.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbRequest;
25 | import android.util.Log;
26 |
27 | import java.io.IOException;
28 | import java.nio.ByteBuffer;
29 |
30 | /**
31 | * Utility class which services a {@link UsbSerialPort} in its {@link #run()}
32 | * method.
33 | *
34 | * @author mike wakerly (opensource@hoho.com)
35 | */
36 | public class SerialInputOutputManager implements Runnable {
37 |
38 | private static final String TAG = SerialInputOutputManager.class.getSimpleName();
39 | private static final boolean DEBUG = true;
40 |
41 | private static final int READ_WAIT_MILLIS = 200;
42 | private static final int BUFSIZ = 4096;
43 |
44 | private final UsbSerialPort mDriver;
45 |
46 | private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
47 |
48 | // Synchronized by 'mWriteBuffer'
49 | private final ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
50 |
51 | private enum State {
52 | STOPPED,
53 | RUNNING,
54 | STOPPING
55 | }
56 |
57 | // Synchronized by 'this'
58 | private State mState = State.STOPPED;
59 |
60 | // Synchronized by 'this'
61 | private Listener mListener;
62 |
63 | public interface Listener {
64 | /**
65 | * Called when new incoming data is available.
66 | */
67 | public void onNewData(byte[] data);
68 |
69 | /**
70 | * Called when {@link SerialInputOutputManager#run()} aborts due to an
71 | * error.
72 | */
73 | public void onRunError(Exception e);
74 | }
75 |
76 | /**
77 | * Creates a new instance with no listener.
78 | */
79 | public SerialInputOutputManager(UsbSerialPort driver) {
80 | this(driver, null);
81 | }
82 |
83 | /**
84 | * Creates a new instance with the provided listener.
85 | */
86 | public SerialInputOutputManager(UsbSerialPort driver, Listener listener) {
87 | mDriver = driver;
88 | mListener = listener;
89 | }
90 |
91 | public synchronized void setListener(Listener listener) {
92 | mListener = listener;
93 | }
94 |
95 | public synchronized Listener getListener() {
96 | return mListener;
97 | }
98 |
99 | public void writeAsync(byte[] data) {
100 | synchronized (mWriteBuffer) {
101 | mWriteBuffer.put(data);
102 | }
103 | }
104 |
105 | public synchronized void stop() {
106 | if (getState() == State.RUNNING) {
107 | Log.i(TAG, "Stop requested");
108 | mState = State.STOPPING;
109 | }
110 | }
111 |
112 | private synchronized State getState() {
113 | return mState;
114 | }
115 |
116 | /**
117 | * Continuously services the read and write buffers until {@link #stop()} is
118 | * called, or until a driver exception is raised.
119 | *
120 | * NOTE(mikey): Uses inefficient read/write-with-timeout.
121 | * TODO(mikey): Read asynchronously with {@link UsbRequest#queue(ByteBuffer, int)}
122 | */
123 | @Override
124 | public void run() {
125 | synchronized (this) {
126 | if (getState() != State.STOPPED) {
127 | throw new IllegalStateException("Already running.");
128 | }
129 | mState = State.RUNNING;
130 | }
131 |
132 | Log.i(TAG, "Running ..");
133 | try {
134 | while (true) {
135 | if (getState() != State.RUNNING) {
136 | Log.i(TAG, "Stopping mState=" + getState());
137 | break;
138 | }
139 | step();
140 | }
141 | } catch (Exception e) {
142 | Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
143 | final Listener listener = getListener();
144 | if (listener != null) {
145 | listener.onRunError(e);
146 | }
147 | } finally {
148 | synchronized (this) {
149 | mState = State.STOPPED;
150 | Log.i(TAG, "Stopped.");
151 | }
152 | }
153 | }
154 |
155 | private void step() throws IOException {
156 | // Handle incoming data.
157 | int len = mDriver.read(mReadBuffer.array(), READ_WAIT_MILLIS);
158 | if (len > 0) {
159 | if (DEBUG) {
160 | Log.d(TAG, "Read data len=" + len);
161 | }
162 | final Listener listener = getListener();
163 | if (listener != null) {
164 | final byte[] data = new byte[len];
165 | mReadBuffer.get(data, 0, len);
166 | listener.onNewData(data);
167 | }
168 | mReadBuffer.clear();
169 | }
170 |
171 | // Handle outgoing data.
172 | byte[] outBuff = null;
173 | synchronized (mWriteBuffer) {
174 | len = mWriteBuffer.position();
175 | if (len > 0) {
176 | outBuff = new byte[len];
177 | mWriteBuffer.rewind();
178 | mWriteBuffer.get(outBuff, 0, len);
179 | mWriteBuffer.clear();
180 | }
181 | }
182 | if (outBuff != null) {
183 | if (DEBUG) {
184 | Log.d(TAG, "Writing data len=" + len);
185 | }
186 | mDriver.write(outBuff, READ_WAIT_MILLIS);
187 | }
188 | }
189 |
190 | }
191 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/UsbId.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | /**
25 | * Registry of USB vendor/product ID constants.
26 | *
27 | * Culled from various sources; see
28 | * usb.ids for one listing.
29 | *
30 | * @author mike wakerly (opensource@hoho.com)
31 | */
32 | public final class UsbId {
33 |
34 | public static final int VENDOR_FTDI = 0x0403;
35 | public static final int FTDI_FT232R = 0x6001;
36 | public static final int FTDI_FT231X = 0x6015;
37 |
38 | public static final int VENDOR_ATMEL = 0x03EB;
39 | public static final int ATMEL_LUFA_CDC_DEMO_APP = 0x2044;
40 |
41 | public static final int VENDOR_ARDUINO = 0x2341;
42 | public static final int ARDUINO_UNO = 0x0001;
43 | public static final int ARDUINO_MEGA_2560 = 0x0010;
44 | public static final int ARDUINO_SERIAL_ADAPTER = 0x003b;
45 | public static final int ARDUINO_MEGA_ADK = 0x003f;
46 | public static final int ARDUINO_MEGA_2560_R3 = 0x0042;
47 | public static final int ARDUINO_UNO_R3 = 0x0043;
48 | public static final int ARDUINO_MEGA_ADK_R3 = 0x0044;
49 | public static final int ARDUINO_SERIAL_ADAPTER_R3 = 0x0044;
50 | public static final int ARDUINO_LEONARDO = 0x8036;
51 | public static final int ARDUINO_MICRO = 0x8037;
52 |
53 | public static final int VENDOR_VAN_OOIJEN_TECH = 0x16c0;
54 | public static final int VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL = 0x0483;
55 |
56 | public static final int VENDOR_LEAFLABS = 0x1eaf;
57 | public static final int LEAFLABS_MAPLE = 0x0004;
58 |
59 | public static final int VENDOR_SILABS = 0x10c4;
60 | public static final int SILABS_CP2102 = 0xea60;
61 | public static final int SILABS_CP2105 = 0xea70;
62 | public static final int SILABS_CP2108 = 0xea71;
63 | public static final int SILABS_CP2110 = 0xea80;
64 |
65 | public static final int VENDOR_PROLIFIC = 0x067b;
66 | public static final int PROLIFIC_PL2303 = 0x2303;
67 |
68 | public static final int VENDOR_QINHENG = 0x1a86;
69 | public static final int QINHENG_HL340 = 0x7523;
70 |
71 | private UsbId() {
72 | throw new IllegalAccessError("Non-instantiable class.");
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/UsbSerialDriver.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbDevice;
25 |
26 | import java.util.List;
27 |
28 | /**
29 | *
30 | * @author mike wakerly (opensource@hoho.com)
31 | */
32 | public interface UsbSerialDriver {
33 |
34 | /**
35 | * Returns the raw {@link UsbDevice} backing this port.
36 | *
37 | * @return the device
38 | */
39 | public UsbDevice getDevice();
40 |
41 | /**
42 | * Returns all available ports for this device. This list must have at least
43 | * one entry.
44 | *
45 | * @return the ports
46 | */
47 | public List getPorts();
48 | }
49 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/UsbSerialPort.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbDeviceConnection;
25 | import android.hardware.usb.UsbManager;
26 |
27 | import java.io.IOException;
28 |
29 | /**
30 | * Interface for a single serial port.
31 | *
32 | * @author mike wakerly (opensource@hoho.com)
33 | */
34 | public interface UsbSerialPort {
35 |
36 | /** 5 data bits. */
37 | public static final int DATABITS_5 = 5;
38 |
39 | /** 6 data bits. */
40 | public static final int DATABITS_6 = 6;
41 |
42 | /** 7 data bits. */
43 | public static final int DATABITS_7 = 7;
44 |
45 | /** 8 data bits. */
46 | public static final int DATABITS_8 = 8;
47 |
48 | /** No flow control. */
49 | public static final int FLOWCONTROL_NONE = 0;
50 |
51 | /** RTS/CTS input flow control. */
52 | public static final int FLOWCONTROL_RTSCTS_IN = 1;
53 |
54 | /** RTS/CTS output flow control. */
55 | public static final int FLOWCONTROL_RTSCTS_OUT = 2;
56 |
57 | /** XON/XOFF input flow control. */
58 | public static final int FLOWCONTROL_XONXOFF_IN = 4;
59 |
60 | /** XON/XOFF output flow control. */
61 | public static final int FLOWCONTROL_XONXOFF_OUT = 8;
62 |
63 | /** No parity. */
64 | public static final int PARITY_NONE = 0;
65 |
66 | /** Odd parity. */
67 | public static final int PARITY_ODD = 1;
68 |
69 | /** Even parity. */
70 | public static final int PARITY_EVEN = 2;
71 |
72 | /** Mark parity. */
73 | public static final int PARITY_MARK = 3;
74 |
75 | /** Space parity. */
76 | public static final int PARITY_SPACE = 4;
77 |
78 | /** 1 stop bit. */
79 | public static final int STOPBITS_1 = 1;
80 |
81 | /** 1.5 stop bits. */
82 | public static final int STOPBITS_1_5 = 3;
83 |
84 | /** 2 stop bits. */
85 | public static final int STOPBITS_2 = 2;
86 |
87 | public UsbSerialDriver getDriver();
88 |
89 | /**
90 | * Port number within driver.
91 | */
92 | public int getPortNumber();
93 |
94 | /**
95 | * The serial number of the underlying UsbDeviceConnection, or {@code null}.
96 | */
97 | public String getSerial();
98 |
99 | /**
100 | * Opens and initializes the port. Upon success, caller must ensure that
101 | * {@link #close()} is eventually called.
102 | *
103 | * @param connection an open device connection, acquired with
104 | * {@link UsbManager#openDevice(android.hardware.usb.UsbDevice)}
105 | * @throws IOException on error opening or initializing the port.
106 | */
107 | public void open(UsbDeviceConnection connection) throws IOException;
108 |
109 | /**
110 | * Closes the port.
111 | *
112 | * @throws IOException on error closing the port.
113 | */
114 | public void close() throws IOException;
115 |
116 | /**
117 | * Reads as many bytes as possible into the destination buffer.
118 | *
119 | * @param dest the destination byte buffer
120 | * @param timeoutMillis the timeout for reading
121 | * @return the actual number of bytes read
122 | * @throws IOException if an error occurred during reading
123 | */
124 | public int read(final byte[] dest, final int timeoutMillis) throws IOException;
125 |
126 | /**
127 | * Writes as many bytes as possible from the source buffer.
128 | *
129 | * @param src the source byte buffer
130 | * @param timeoutMillis the timeout for writing
131 | * @return the actual number of bytes written
132 | * @throws IOException if an error occurred during writing
133 | */
134 | public int write(final byte[] src, final int timeoutMillis) throws IOException;
135 |
136 | /**
137 | * Sets various serial port parameters.
138 | *
139 | * @param baudRate baud rate as an integer, for example {@code 115200}.
140 | * @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6},
141 | * {@link #DATABITS_7}, or {@link #DATABITS_8}.
142 | * @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or
143 | * {@link #STOPBITS_2}.
144 | * @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD},
145 | * {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or
146 | * {@link #PARITY_SPACE}.
147 | * @throws IOException on error setting the port parameters
148 | */
149 | public void setParameters(
150 | int baudRate, int dataBits, int stopBits, int parity) throws IOException;
151 |
152 | /**
153 | * Gets the CD (Carrier Detect) bit from the underlying UART.
154 | *
155 | * @return the current state, or {@code false} if not supported.
156 | * @throws IOException if an error occurred during reading
157 | */
158 | public boolean getCD() throws IOException;
159 |
160 | /**
161 | * Gets the CTS (Clear To Send) bit from the underlying UART.
162 | *
163 | * @return the current state, or {@code false} if not supported.
164 | * @throws IOException if an error occurred during reading
165 | */
166 | public boolean getCTS() throws IOException;
167 |
168 | /**
169 | * Gets the DSR (Data Set Ready) bit from the underlying UART.
170 | *
171 | * @return the current state, or {@code false} if not supported.
172 | * @throws IOException if an error occurred during reading
173 | */
174 | public boolean getDSR() throws IOException;
175 |
176 | /**
177 | * Gets the DTR (Data Terminal Ready) bit from the underlying UART.
178 | *
179 | * @return the current state, or {@code false} if not supported.
180 | * @throws IOException if an error occurred during reading
181 | */
182 | public boolean getDTR() throws IOException;
183 |
184 | /**
185 | * Sets the DTR (Data Terminal Ready) bit on the underlying UART, if
186 | * supported.
187 | *
188 | * @param value the value to set
189 | * @throws IOException if an error occurred during writing
190 | */
191 | public void setDTR(boolean value) throws IOException;
192 |
193 | /**
194 | * Gets the RI (Ring Indicator) bit from the underlying UART.
195 | *
196 | * @return the current state, or {@code false} if not supported.
197 | * @throws IOException if an error occurred during reading
198 | */
199 | public boolean getRI() throws IOException;
200 |
201 | /**
202 | * Gets the RTS (Request To Send) bit from the underlying UART.
203 | *
204 | * @return the current state, or {@code false} if not supported.
205 | * @throws IOException if an error occurred during reading
206 | */
207 | public boolean getRTS() throws IOException;
208 |
209 | /**
210 | * Sets the RTS (Request To Send) bit on the underlying UART, if
211 | * supported.
212 | *
213 | * @param value the value to set
214 | * @throws IOException if an error occurred during writing
215 | */
216 | public void setRTS(boolean value) throws IOException;
217 |
218 | /**
219 | * Flush non-transmitted output data and / or non-read input data
220 | * @param flushRX {@code true} to flush non-transmitted output data
221 | * @param flushTX {@code true} to flush non-read input data
222 | * @return {@code true} if the operation was successful, or
223 | * {@code false} if the operation is not supported by the driver or device
224 | * @throws IOException if an error occurred during flush
225 | */
226 | public boolean purgeHwBuffers(boolean flushRX, boolean flushTX) throws IOException;
227 |
228 | }
229 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/UsbSerialProber.java:
--------------------------------------------------------------------------------
1 | /* Copyright 2011-2013 Google Inc.
2 | * Copyright 2013 mike wakerly
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | *
19 | * Project home page: https://github.com/mik3y/usb-serial-for-android
20 | */
21 |
22 | package com.nianlun.libserialport.usbdriver;
23 |
24 | import android.hardware.usb.UsbDevice;
25 | import android.hardware.usb.UsbManager;
26 |
27 | import java.lang.reflect.Constructor;
28 | import java.lang.reflect.InvocationTargetException;
29 | import java.util.ArrayList;
30 | import java.util.List;
31 |
32 | /**
33 | *
34 | * @author mike wakerly (opensource@hoho.com)
35 | */
36 | public class UsbSerialProber {
37 |
38 | private final ProbeTable mProbeTable;
39 |
40 | public UsbSerialProber(ProbeTable probeTable) {
41 | mProbeTable = probeTable;
42 | }
43 |
44 | public static UsbSerialProber getDefaultProber() {
45 | return new UsbSerialProber(getDefaultProbeTable());
46 | }
47 |
48 | public static ProbeTable getDefaultProbeTable() {
49 | final ProbeTable probeTable = new ProbeTable();
50 | probeTable.addDriver(CdcAcmSerialDriver.class);
51 | probeTable.addDriver(Cp21xxSerialDriver.class);
52 | probeTable.addDriver(FtdiSerialDriver.class);
53 | probeTable.addDriver(ProlificSerialDriver.class);
54 | probeTable.addDriver(Ch34xSerialDriver.class);
55 | return probeTable;
56 | }
57 |
58 | /**
59 | * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
60 | * from the currently-attached {@link UsbDevice} hierarchy. This method does
61 | * not require permission from the Android USB system, since it does not
62 | * open any of the devices.
63 | *
64 | * @param usbManager
65 | * @return a list, possibly empty, of all compatible drivers
66 | */
67 | public List findAllDrivers(final UsbManager usbManager) {
68 | final List result = new ArrayList();
69 |
70 | for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
71 | final UsbSerialDriver driver = probeDevice(usbDevice);
72 | if (driver != null) {
73 | result.add(driver);
74 | }
75 | }
76 | return result;
77 | }
78 |
79 | /**
80 | * Probes a single device for a compatible driver.
81 | *
82 | * @param usbDevice the usb device to probe
83 | * @return a new {@link UsbSerialDriver} compatible with this device, or
84 | * {@code null} if none available.
85 | */
86 | public UsbSerialDriver probeDevice(final UsbDevice usbDevice) {
87 | final int vendorId = usbDevice.getVendorId();
88 | final int productId = usbDevice.getProductId();
89 |
90 | final Class extends UsbSerialDriver> driverClass =
91 | mProbeTable.findDriver(vendorId, productId);
92 | if (driverClass != null) {
93 | final UsbSerialDriver driver;
94 | try {
95 | final Constructor extends UsbSerialDriver> ctor =
96 | driverClass.getConstructor(UsbDevice.class);
97 | driver = ctor.newInstance(usbDevice);
98 | } catch (NoSuchMethodException e) {
99 | throw new RuntimeException(e);
100 | } catch (IllegalArgumentException e) {
101 | throw new RuntimeException(e);
102 | } catch (InstantiationException e) {
103 | throw new RuntimeException(e);
104 | } catch (IllegalAccessException e) {
105 | throw new RuntimeException(e);
106 | } catch (InvocationTargetException e) {
107 | throw new RuntimeException(e);
108 | }
109 | return driver;
110 | }
111 | return null;
112 | }
113 |
114 | }
115 |
--------------------------------------------------------------------------------
/libserialport/src/main/java/com/nianlun/libserialport/usbdriver/UsbSerialRuntimeException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2011 Google Inc.
3 | *
4 | * This library is free software; you can redistribute it and/or
5 | * modify it under the terms of the GNU Lesser General Public
6 | * License as published by the Free Software Foundation; either
7 | * version 2.1 of the License, or (at your option) any later version.
8 | *
9 | * This library is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | * Lesser General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Lesser General Public
15 | * License along with this library; if not, write to the Free Software
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 | * USA.
18 | */
19 |
20 | package com.nianlun.libserialport.usbdriver;
21 |
22 | /**
23 | * Generic unchecked exception for the usbserial package.
24 | *
25 | * @author mike wakerly (opensource@hoho.com)
26 | */
27 | @SuppressWarnings("serial")
28 | public class UsbSerialRuntimeException extends RuntimeException {
29 |
30 | public UsbSerialRuntimeException() {
31 | super();
32 | }
33 |
34 | public UsbSerialRuntimeException(String detailMessage, Throwable throwable) {
35 | super(detailMessage, throwable);
36 | }
37 |
38 | public UsbSerialRuntimeException(String detailMessage) {
39 | super(detailMessage);
40 | }
41 |
42 | public UsbSerialRuntimeException(Throwable throwable) {
43 | super(throwable);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/libserialport/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | libserialport
3 |
4 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':androidusbserialport', ':libserialport'
2 | rootProject.name='AndroidUSBSerialPort'
3 |
--------------------------------------------------------------------------------
/tool/serial_port_utility_latest.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MickJson/AndroidUSBSerialPort/57bd67beacbabf98c603365bdb628bb2d169fd6d/tool/serial_port_utility_latest.exe
--------------------------------------------------------------------------------