├── Android
├── ArduinoController
│ ├── AndroidManifest.xml
│ ├── bin
│ │ └── ArduinoController.apk
│ ├── ic_launcher-web.png
│ ├── libs
│ │ └── android-support-v4.jar
│ ├── res
│ │ ├── drawable-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── layout
│ │ │ └── activity_arduino_controller.xml
│ │ ├── values-v11
│ │ │ └── styles.xml
│ │ ├── values-v14
│ │ │ └── styles.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ └── xml
│ │ │ └── device_filter.xml
│ └── src
│ │ └── com
│ │ └── hardcopy
│ │ └── arduinocontroller
│ │ ├── ArduinoControllerActivity.java
│ │ ├── Constants.java
│ │ ├── SerialCommand.java
│ │ └── SerialConnector.java
└── usbSerialForAndroid
│ ├── build.gradle
│ └── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── hoho
│ └── android
│ └── usbserial
│ ├── BuildInfo.java
│ ├── driver
│ ├── CH34xSerialDriver.java
│ ├── CdcAcmSerialDriver.java
│ ├── CommonUsbSerialPort.java
│ ├── Cp21xxSerialDriver.java
│ ├── FtdiSerialDriver.java
│ ├── ProbeTable.java
│ ├── ProlificSerialDriver.java
│ ├── UsbId.java
│ ├── UsbSerialDriver.java
│ ├── UsbSerialPort.java
│ ├── UsbSerialProber.java
│ └── UsbSerialRuntimeException.java
│ └── util
│ ├── HexDump.java
│ └── SerialInputOutputManager.java
├── Arduino
├── alcohol_sensor
│ └── alcohol_sensor.ino
└── non_contact_thermometer
│ └── non_contact_thermometer.ino
├── LICENSE
└── README.md
/Android/ArduinoController/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
10 |
11 |
12 |
13 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/Android/ArduinoController/bin/ArduinoController.apk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/bin/ArduinoController.apk
--------------------------------------------------------------------------------
/Android/ArduinoController/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/ic_launcher-web.png
--------------------------------------------------------------------------------
/Android/ArduinoController/libs/android-support-v4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/libs/android-support-v4.jar
--------------------------------------------------------------------------------
/Android/ArduinoController/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/ArduinoController/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/ArduinoController/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/ArduinoController/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/godstale/Arduino-Serial-Controller/0ef3efbf97668829a24815eb654414ff05134974/Android/ArduinoController/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/ArduinoController/res/layout/activity_arduino_controller.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
14 |
22 |
23 |
24 |
30 |
36 |
37 |
38 |
43 |
50 |
57 |
64 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/values-v11/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/values-v14/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 | 64dp
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 16dp
5 | 16dp
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ArduinoController
5 | Hello world!
6 |
7 | Button1
8 | Button2
9 | Button3
10 | Button4
11 |
12 | No data\n
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Android/ArduinoController/res/xml/device_filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Android/ArduinoController/src/com/hardcopy/arduinocontroller/ArduinoControllerActivity.java:
--------------------------------------------------------------------------------
1 | package com.hardcopy.arduinocontroller;
2 |
3 | import com.hardcopy.arduinocontroller.R;
4 | import com.hardcopy.arduinocontroller.Constants;
5 | import com.hardcopy.arduinocontroller.SerialConnector;
6 |
7 | import android.app.Activity;
8 | import android.content.Context;
9 | import android.os.Bundle;
10 | import android.os.Handler;
11 | import android.os.Message;
12 | import android.text.method.ScrollingMovementMethod;
13 | import android.view.Menu;
14 | import android.view.View;
15 | import android.widget.Button;
16 | import android.widget.TextView;
17 |
18 | public class ArduinoControllerActivity extends Activity implements View.OnClickListener {
19 |
20 | private Context mContext = null;
21 | private ActivityHandler mHandler = null;
22 |
23 | private SerialListener mListener = null;
24 | private SerialConnector mSerialConn = null;
25 |
26 | private TextView mTextLog = null;
27 | private TextView mTextInfo = null;
28 | private Button mButton1;
29 | private Button mButton2;
30 | private Button mButton3;
31 | private Button mButton4;
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 |
37 | // System
38 | mContext = getApplicationContext();
39 |
40 | // Layouts
41 | setContentView(R.layout.activity_arduino_controller);
42 |
43 | mTextLog = (TextView) findViewById(R.id.text_serial);
44 | mTextLog.setMovementMethod(new ScrollingMovementMethod());
45 | mTextInfo = (TextView) findViewById(R.id.text_info);
46 | mTextInfo.setMovementMethod(new ScrollingMovementMethod());
47 | mButton1 = (Button) findViewById(R.id.button_send1);
48 | mButton1.setOnClickListener(this);
49 | mButton2 = (Button) findViewById(R.id.button_send2);
50 | mButton2.setOnClickListener(this);
51 | mButton3 = (Button) findViewById(R.id.button_send3);
52 | mButton3.setOnClickListener(this);
53 | mButton4 = (Button) findViewById(R.id.button_send4);
54 | mButton4.setOnClickListener(this);
55 |
56 | // Initialize
57 | mListener = new SerialListener();
58 | mHandler = new ActivityHandler();
59 |
60 | // Initialize Serial connector and starts Serial monitoring thread.
61 | mSerialConn = new SerialConnector(mContext, mListener, mHandler);
62 | mSerialConn.initialize();
63 | }
64 |
65 | @Override
66 | public boolean onCreateOptionsMenu(Menu menu) {
67 | return true;
68 | }
69 |
70 | @Override
71 | public void onDestroy() {
72 | super.onDestroy();
73 |
74 | mSerialConn.finalize();
75 | }
76 |
77 | @Override
78 | public void onClick(View v) {
79 | switch(v.getId()) {
80 | case R.id.button_send1:
81 | mSerialConn.sendCommand("b1");
82 | break;
83 | case R.id.button_send2:
84 | mSerialConn.sendCommand("b2");
85 | break;
86 | case R.id.button_send3:
87 | mSerialConn.sendCommand("b3");
88 | break;
89 | case R.id.button_send4:
90 | mSerialConn.sendCommand("b4");
91 | break;
92 | default:
93 | break;
94 | }
95 | }
96 |
97 |
98 | public class SerialListener {
99 | public void onReceive(int msg, int arg0, int arg1, String arg2, Object arg3) {
100 | switch(msg) {
101 | case Constants.MSG_DEVICD_INFO:
102 | mTextLog.append(arg2);
103 | break;
104 | case Constants.MSG_DEVICE_COUNT:
105 | mTextLog.append(Integer.toString(arg0) + " device(s) found \n");
106 | break;
107 | case Constants.MSG_READ_DATA_COUNT:
108 | mTextLog.append(Integer.toString(arg0) + " buffer received \n");
109 | break;
110 | case Constants.MSG_READ_DATA:
111 | if(arg3 != null) {
112 | mTextInfo.setText((String)arg3);
113 | mTextLog.append((String)arg3);
114 | mTextLog.append("\n");
115 | }
116 | break;
117 | case Constants.MSG_SERIAL_ERROR:
118 | mTextLog.append(arg2);
119 | break;
120 | case Constants.MSG_FATAL_ERROR_FINISH_APP:
121 | finish();
122 | break;
123 | }
124 | }
125 | }
126 |
127 | public class ActivityHandler extends Handler {
128 | @Override
129 | public void handleMessage(Message msg) {
130 | switch(msg.what) {
131 | case Constants.MSG_DEVICD_INFO:
132 | mTextLog.append((String)msg.obj);
133 | break;
134 | case Constants.MSG_DEVICE_COUNT:
135 | mTextLog.append(Integer.toString(msg.arg1) + " device(s) found \n");
136 | break;
137 | case Constants.MSG_READ_DATA_COUNT:
138 | mTextLog.append(((String)msg.obj) + "\n");
139 | break;
140 | case Constants.MSG_READ_DATA:
141 | if(msg.obj != null) {
142 | mTextInfo.setText((String)msg.obj);
143 | mTextLog.append((String)msg.obj);
144 | mTextLog.append("\n");
145 | }
146 | break;
147 | case Constants.MSG_SERIAL_ERROR:
148 | mTextLog.append((String)msg.obj);
149 | break;
150 | }
151 | }
152 | }
153 |
154 |
155 |
156 | }
157 |
--------------------------------------------------------------------------------
/Android/ArduinoController/src/com/hardcopy/arduinocontroller/Constants.java:
--------------------------------------------------------------------------------
1 | package com.hardcopy.arduinocontroller;
2 |
3 | public class Constants {
4 | public static final int MSG_DEVICE_COUNT = 1;
5 | public static final int MSG_DEVICD_INFO = 11;
6 | public static final int MSG_READ_DATA_COUNT = 21;
7 | public static final int MSG_READ_DATA = 22;
8 | public static final int MSG_SERIAL_ERROR = -1;
9 | public static final int MSG_FATAL_ERROR_FINISH_APP = -2;
10 | }
11 |
--------------------------------------------------------------------------------
/Android/ArduinoController/src/com/hardcopy/arduinocontroller/SerialCommand.java:
--------------------------------------------------------------------------------
1 | package com.hardcopy.arduinocontroller;
2 |
3 | public class SerialCommand {
4 | /**
5 | //---------- buffer structure when received
6 | mDataArray[0] : a
7 | mDataArray[1] : 1
8 | mDataArray[2] : 2
9 | mDataArray[3] : .
10 | mDataArray[4] : 3
11 | mDataArray[5] : 4
12 | ...
13 | mDataArray[n] : z
14 |
15 | ==> converts into float number : 12.34xxxxxx
16 | */
17 |
18 |
19 | public static final int SIZE_IN_BYTE = 20;
20 | public StringBuilder mStringBuffer;
21 |
22 |
23 | public SerialCommand() {
24 | mStringBuffer = new StringBuilder();
25 | }
26 |
27 | public void initialize() {
28 | mStringBuffer = new StringBuilder();
29 | }
30 |
31 | public void addChar(char c) {
32 | if(c < 0x00)
33 | return;
34 | if(c == 'a') {
35 | initialize();
36 | } else {
37 | mStringBuffer.append(c);
38 | }
39 | }
40 |
41 | public String toString() {
42 | return mStringBuffer.length()>0 ? mStringBuffer.toString() : "No data";
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Android/ArduinoController/src/com/hardcopy/arduinocontroller/SerialConnector.java:
--------------------------------------------------------------------------------
1 | package com.hardcopy.arduinocontroller;
2 |
3 | import java.io.IOException;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | import android.content.Context;
8 | import android.hardware.usb.UsbDevice;
9 | import android.hardware.usb.UsbDeviceConnection;
10 | import android.hardware.usb.UsbManager;
11 | import android.os.Handler;
12 | import android.os.Message;
13 | import android.util.Log;
14 |
15 | import com.hardcopy.arduinocontroller.Constants;
16 | import com.hardcopy.arduinocontroller.SerialCommand;
17 | import com.hardcopy.arduinocontroller.ArduinoControllerActivity.SerialListener;
18 | import com.hoho.android.usbserial.driver.UsbSerialDriver;
19 | import com.hoho.android.usbserial.driver.UsbSerialPort;
20 | import com.hoho.android.usbserial.driver.UsbSerialProber;
21 |
22 | public class SerialConnector {
23 | public static final String tag = "SerialConnector";
24 |
25 | private Context mContext;
26 | private SerialListener mListener;
27 | private Handler mHandler;
28 |
29 | private SerialMonitorThread mSerialThread;
30 |
31 | private UsbSerialDriver mDriver;
32 | private UsbSerialPort mPort;
33 |
34 | public static final int TARGET_VENDOR_ID = 9025; // Arduino
35 | public static final int TARGET_VENDOR_ID2 = 1659; // PL2303
36 | public static final int TARGET_VENDOR_ID3 = 1027; // FT232R
37 | public static final int TARGET_VENDOR_ID4 = 6790; // CH340G
38 | public static final int TARGET_VENDOR_ID5 = 4292; // CP210x
39 | public static final int BAUD_RATE = 115200;
40 |
41 |
42 | /*****************************************************
43 | * Constructor, Initialize
44 | ******************************************************/
45 | public SerialConnector(Context c, SerialListener l, Handler h) {
46 | mContext = c;
47 | mListener = l;
48 | mHandler = h;
49 | }
50 |
51 |
52 | public void initialize() {
53 | UsbManager manager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
54 |
55 | List availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
56 | if (availableDrivers.isEmpty()) {
57 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: There is no available device. \n", null);
58 | return;
59 | }
60 |
61 | mDriver = availableDrivers.get(0);
62 | if(mDriver == null) {
63 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Driver is Null \n", null);
64 | return;
65 | }
66 |
67 | // Report to UI
68 | StringBuilder sb = new StringBuilder();
69 | UsbDevice device = mDriver.getDevice();
70 | sb.append(" DName : ").append(device.getDeviceName()).append("\n")
71 | .append(" DID : ").append(device.getDeviceId()).append("\n")
72 | .append(" VID : ").append(device.getVendorId()).append("\n")
73 | .append(" PID : ").append(device.getProductId()).append("\n")
74 | .append(" IF Count : ").append(device.getInterfaceCount()).append("\n");
75 | mListener.onReceive(Constants.MSG_DEVICD_INFO, 0, 0, sb.toString(), null);
76 |
77 | UsbDeviceConnection connection = manager.openDevice(device);
78 | if (connection == null) {
79 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot connect to device. \n", null);
80 | return;
81 | }
82 |
83 | // Read some data! Most have just one port (port 0).
84 | mPort = mDriver.getPorts().get(0);
85 | if(mPort == null) {
86 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot get port. \n", null);
87 | return;
88 | }
89 |
90 | try {
91 | mPort.open(connection);
92 | mPort.setParameters(9600, 8, 1, 0); // baudrate:9600, dataBits:8, stopBits:1, parity:N
93 | // byte buffer[] = new byte[16];
94 | // int numBytesRead = mPort.read(buffer, 1000);
95 | // Log.d(TAG, "Read " + numBytesRead + " bytes.");
96 | } catch (IOException e) {
97 | // Deal with error.
98 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot open port \n" + e.toString() + "\n", null);
99 | } finally {
100 | }
101 |
102 | // Everything is fine. Start serial monitoring thread.
103 | startThread();
104 | } // End of initialize()
105 |
106 | public void finalize() {
107 | try {
108 | mDriver = null;
109 | stopThread();
110 |
111 | mPort.close();
112 | mPort = null;
113 | } catch(Exception ex) {
114 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot finalize serial connector \n" + ex.toString() + "\n", null);
115 | }
116 | }
117 |
118 |
119 |
120 | /*****************************************************
121 | * public methods
122 | ******************************************************/
123 | // send string to remote
124 | public void sendCommand(String cmd) {
125 |
126 | if(mPort != null && cmd != null) {
127 | try {
128 | mPort.write(cmd.getBytes(), cmd.length()); // Send to remote device
129 | }
130 | catch(IOException e) {
131 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Failed in sending command. : IO Exception \n", null);
132 | }
133 | }
134 | }
135 |
136 |
137 | /*****************************************************
138 | * private methods
139 | ******************************************************/
140 | // start thread
141 | private void startThread() {
142 | Log.d(tag, "Start serial monitoring thread");
143 | mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Start serial monitoring thread \n", null);
144 | if(mSerialThread == null) {
145 | mSerialThread = new SerialMonitorThread();
146 | mSerialThread.start();
147 | }
148 | }
149 | // stop thread
150 | private void stopThread() {
151 | if(mSerialThread != null && mSerialThread.isAlive())
152 | mSerialThread.interrupt();
153 | if(mSerialThread != null) {
154 | mSerialThread.setKillSign(true);
155 | mSerialThread = null;
156 | }
157 | }
158 |
159 |
160 |
161 |
162 |
163 | /*****************************************************
164 | * Sub classes, Handler, Listener
165 | ******************************************************/
166 |
167 | public class SerialMonitorThread extends Thread {
168 | // Thread status
169 | private boolean mKillSign = false;
170 | private SerialCommand mCmd = new SerialCommand();
171 |
172 |
173 | private void initializeThread() {
174 | // This code will be executed only once.
175 | }
176 |
177 | private void finalizeThread() {
178 | }
179 |
180 | // stop this thread
181 | public void setKillSign(boolean isTrue) {
182 | mKillSign = isTrue;
183 | }
184 |
185 | /**
186 | * Main loop
187 | **/
188 | @Override
189 | public void run()
190 | {
191 | byte buffer[] = new byte[128];
192 |
193 | while(!Thread.interrupted())
194 | {
195 | if(mPort != null) {
196 | Arrays.fill(buffer, (byte)0x00);
197 |
198 | try {
199 | // Read received buffer
200 | int numBytesRead = mPort.read(buffer, 1000);
201 | if(numBytesRead > 0) {
202 | Log.d(tag, "run : read bytes = " + numBytesRead);
203 |
204 | // Print message length
205 | Message msg = mHandler.obtainMessage(Constants.MSG_READ_DATA_COUNT, numBytesRead, 0,
206 | new String(buffer));
207 | mHandler.sendMessage(msg);
208 |
209 | // Extract data from buffer
210 | for(int i=0; i 0)
223 | }
224 | catch (IOException e) {
225 | Log.d(tag, "IOException - mDriver.read");
226 | Message msg = mHandler.obtainMessage(Constants.MSG_SERIAL_ERROR, 0, 0, "Error # run: " + e.toString() + "\n");
227 | mHandler.sendMessage(msg);
228 | mKillSign = true;
229 | }
230 | }
231 |
232 | try {
233 | Thread.sleep(100);
234 | } catch (InterruptedException e) {
235 | e.printStackTrace();
236 | break;
237 | }
238 |
239 | if(mKillSign)
240 | break;
241 |
242 | } // End of while() loop
243 |
244 | // Finalize
245 | finalizeThread();
246 |
247 | } // End of run()
248 |
249 |
250 | } // End of SerialMonitorThread
251 |
252 | }
253 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'android-library'
2 | apply plugin: 'maven'
3 | apply plugin: 'signing'
4 |
5 | android {
6 | compileSdkVersion 19
7 | buildToolsVersion "19.1"
8 |
9 | defaultConfig {
10 | minSdkVersion 12
11 | targetSdkVersion 19
12 | }
13 |
14 | buildTypes {
15 | release {
16 | runProguard false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
18 | }
19 | }
20 | }
21 |
22 | group = "com.hoho.android"
23 | version = "0.2.0-SNAPSHOT"
24 |
25 | configurations {
26 | archives {
27 | extendsFrom configurations.default
28 | }
29 | }
30 |
31 | signing {
32 | required { has("release") && gradle.taskGraph.hasTask("uploadArchives") }
33 | sign configurations.archives
34 | }
35 |
36 | def getRepositoryUsername() {
37 | return hasProperty('sonatypeUsername') ? sonatypeUsername : ""
38 | }
39 |
40 | def getRepositoryPassword() {
41 | return hasProperty('sonatypePassword') ? sonatypePassword : ""
42 | }
43 |
44 | def isReleaseBuild() {
45 | return version.contains("SNAPSHOT") == false
46 | }
47 |
48 | uploadArchives {
49 | def sonatypeRepositoryUrl
50 | if (isReleaseBuild()) {
51 | println 'RELEASE BUILD'
52 | sonatypeRepositoryUrl = hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL
53 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
54 | } else {
55 | println 'SNAPSHOT BUILD'
56 | sonatypeRepositoryUrl = hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL
57 | : "https://oss.sonatype.org/content/repositories/snapshots/"
58 | }
59 |
60 | configuration = configurations.archives
61 | repositories.mavenDeployer {
62 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
63 |
64 | repository(url: sonatypeRepositoryUrl) {
65 | authentication(userName: getRepositoryUsername(),
66 | password: getRepositoryPassword())
67 | }
68 |
69 | pom.artifactId = 'usb-serial-for-android'
70 | pom.project {
71 | name 'usb-serial-for-android'
72 | packaging 'aar'
73 | description 'USB Serial Driver Library for Android'
74 | url 'https://github.com/mik3y/usb-serial-for-android'
75 |
76 | scm {
77 | url 'scm:git@github.com:mik3y/usb-serial-for-android.git'
78 | connection 'scm:git@github.com:mik3y/usb-serial-for-android.git'
79 | developerConnection 'scm:git@github.com:mik3y/usb-serial-for-android.git'
80 | }
81 |
82 | licenses {
83 | license {
84 | name 'GNU LGPL v2.1'
85 | url 'http://www.gnu.org/licenses/lgpl-2.1.txt'
86 | distribution 'repo'
87 | }
88 | }
89 |
90 | developers {
91 | developer {
92 | id 'mik3y'
93 | name 'mik3y'
94 | email 'opensource@hoho.com'
95 | }
96 | }
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/BuildInfo.java:
--------------------------------------------------------------------------------
1 | package com.hoho.android.usbserial;
2 |
3 | /**
4 | * Static container of information about this library.
5 | */
6 | public final class BuildInfo {
7 |
8 | /**
9 | * The current version of this library. Values are of the form
10 | * "major.minor.micro[-suffix]". A suffix of "-pre" indicates a pre-release
11 | * of the version preceeding it.
12 | */
13 | public static final String VERSION = "0.2.0-pre";
14 |
15 | private BuildInfo() {
16 | throw new IllegalStateException("Non-instantiable class.");
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 | }
364 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 >= 17); // 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 | Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
111 | mControlInterface = mDevice.getInterface(0);
112 | Log.d(TAG, "Control iface=" + mControlInterface);
113 | // class should be USB_CLASS_COMM
114 |
115 | if (!mConnection.claimInterface(mControlInterface, true)) {
116 | throw new IOException("Could not claim control interface.");
117 | }
118 | mControlEndpoint = mControlInterface.getEndpoint(0);
119 | Log.d(TAG, "Control endpoint direction: " + mControlEndpoint.getDirection());
120 |
121 | Log.d(TAG, "Claiming data interface.");
122 | mDataInterface = mDevice.getInterface(1);
123 | Log.d(TAG, "data iface=" + mDataInterface);
124 | // class should be USB_CLASS_CDC_DATA
125 |
126 | if (!mConnection.claimInterface(mDataInterface, true)) {
127 | throw new IOException("Could not claim data interface.");
128 | }
129 | mReadEndpoint = mDataInterface.getEndpoint(1);
130 | Log.d(TAG, "Read endpoint direction: " + mReadEndpoint.getDirection());
131 | mWriteEndpoint = mDataInterface.getEndpoint(0);
132 | Log.d(TAG, "Write endpoint direction: " + mWriteEndpoint.getDirection());
133 | if (mEnableAsyncReads) {
134 | Log.d(TAG, "Async reads enabled");
135 | } else {
136 | Log.d(TAG, "Async reads disabled.");
137 | }
138 | opened = true;
139 | } finally {
140 | if (!opened) {
141 | mConnection = null;
142 | }
143 | }
144 | }
145 |
146 | private int sendAcmControlMessage(int request, int value, byte[] buf) {
147 | return mConnection.controlTransfer(
148 | USB_RT_ACM, request, value, 0, buf, buf != null ? buf.length : 0, 5000);
149 | }
150 |
151 | @Override
152 | public void close() throws IOException {
153 | if (mConnection == null) {
154 | throw new IOException("Already closed");
155 | }
156 | mConnection.close();
157 | mConnection = null;
158 | }
159 |
160 | @Override
161 | public int read(byte[] dest, int timeoutMillis) throws IOException {
162 | if (mEnableAsyncReads) {
163 | final UsbRequest request = new UsbRequest();
164 | try {
165 | request.initialize(mConnection, mReadEndpoint);
166 | final ByteBuffer buf = ByteBuffer.wrap(dest);
167 | if (!request.queue(buf, dest.length)) {
168 | throw new IOException("Error queueing request.");
169 | }
170 |
171 | final UsbRequest response = mConnection.requestWait();
172 | if (response == null) {
173 | throw new IOException("Null response");
174 | }
175 |
176 | final int nread = buf.position();
177 | if (nread > 0) {
178 | //Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
179 | return nread;
180 | } else {
181 | return 0;
182 | }
183 | } finally {
184 | request.close();
185 | }
186 | }
187 |
188 | final int numBytesRead;
189 | synchronized (mReadBufferLock) {
190 | int readAmt = Math.min(dest.length, mReadBuffer.length);
191 | numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt,
192 | timeoutMillis);
193 | if (numBytesRead < 0) {
194 | // This sucks: we get -1 on timeout, not 0 as preferred.
195 | // We *should* use UsbRequest, except it has a bug/api oversight
196 | // where there is no way to determine the number of bytes read
197 | // in response :\ -- http://b.android.com/28023
198 | if (timeoutMillis == Integer.MAX_VALUE) {
199 | // Hack: Special case "~infinite timeout" as an error.
200 | return -1;
201 | }
202 | return 0;
203 | }
204 | System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
205 | }
206 | return numBytesRead;
207 | }
208 |
209 | @Override
210 | public int write(byte[] src, int timeoutMillis) throws IOException {
211 | // TODO(mikey): Nearly identical to FtdiSerial write. Refactor.
212 | int offset = 0;
213 |
214 | while (offset < src.length) {
215 | final int writeLength;
216 | final int amtWritten;
217 |
218 | synchronized (mWriteBufferLock) {
219 | final byte[] writeBuffer;
220 |
221 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
222 | if (offset == 0) {
223 | writeBuffer = src;
224 | } else {
225 | // bulkTransfer does not support offsets, make a copy.
226 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
227 | writeBuffer = mWriteBuffer;
228 | }
229 |
230 | amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength,
231 | timeoutMillis);
232 | }
233 | if (amtWritten <= 0) {
234 | throw new IOException("Error writing " + writeLength
235 | + " bytes at offset " + offset + " length=" + src.length);
236 | }
237 |
238 | Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength);
239 | offset += amtWritten;
240 | }
241 | return offset;
242 | }
243 |
244 | @Override
245 | public void setParameters(int baudRate, int dataBits, int stopBits, int parity) {
246 | byte stopBitsByte;
247 | switch (stopBits) {
248 | case STOPBITS_1: stopBitsByte = 0; break;
249 | case STOPBITS_1_5: stopBitsByte = 1; break;
250 | case STOPBITS_2: stopBitsByte = 2; break;
251 | default: throw new IllegalArgumentException("Bad value for stopBits: " + stopBits);
252 | }
253 |
254 | byte parityBitesByte;
255 | switch (parity) {
256 | case PARITY_NONE: parityBitesByte = 0; break;
257 | case PARITY_ODD: parityBitesByte = 1; break;
258 | case PARITY_EVEN: parityBitesByte = 2; break;
259 | case PARITY_MARK: parityBitesByte = 3; break;
260 | case PARITY_SPACE: parityBitesByte = 4; break;
261 | default: throw new IllegalArgumentException("Bad value for parity: " + parity);
262 | }
263 |
264 | byte[] msg = {
265 | (byte) ( baudRate & 0xff),
266 | (byte) ((baudRate >> 8 ) & 0xff),
267 | (byte) ((baudRate >> 16) & 0xff),
268 | (byte) ((baudRate >> 24) & 0xff),
269 | stopBitsByte,
270 | parityBitesByte,
271 | (byte) dataBits};
272 | sendAcmControlMessage(SET_LINE_CODING, 0, msg);
273 | }
274 |
275 | @Override
276 | public boolean getCD() throws IOException {
277 | return false; // TODO
278 | }
279 |
280 | @Override
281 | public boolean getCTS() throws IOException {
282 | return false; // TODO
283 | }
284 |
285 | @Override
286 | public boolean getDSR() throws IOException {
287 | return false; // TODO
288 | }
289 |
290 | @Override
291 | public boolean getDTR() throws IOException {
292 | return mDtr;
293 | }
294 |
295 | @Override
296 | public void setDTR(boolean value) throws IOException {
297 | mDtr = value;
298 | setDtrRts();
299 | }
300 |
301 | @Override
302 | public boolean getRI() throws IOException {
303 | return false; // TODO
304 | }
305 |
306 | @Override
307 | public boolean getRTS() throws IOException {
308 | return mRts;
309 | }
310 |
311 | @Override
312 | public void setRTS(boolean value) throws IOException {
313 | mRts = value;
314 | setDtrRts();
315 | }
316 |
317 | private void setDtrRts() {
318 | int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0);
319 | sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
320 | }
321 |
322 | }
323 |
324 | public static Map getSupportedDevices() {
325 | final Map supportedDevices = new LinkedHashMap();
326 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ARDUINO),
327 | new int[] {
328 | UsbId.ARDUINO_UNO,
329 | UsbId.ARDUINO_UNO_R3,
330 | UsbId.ARDUINO_MEGA_2560,
331 | UsbId.ARDUINO_MEGA_2560_R3,
332 | UsbId.ARDUINO_SERIAL_ADAPTER,
333 | UsbId.ARDUINO_SERIAL_ADAPTER_R3,
334 | UsbId.ARDUINO_MEGA_ADK,
335 | UsbId.ARDUINO_MEGA_ADK_R3,
336 | UsbId.ARDUINO_LEONARDO,
337 | });
338 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_VAN_OOIJEN_TECH),
339 | new int[] {
340 | UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL,
341 | });
342 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ATMEL),
343 | new int[] {
344 | UsbId.ATMEL_LUFA_CDC_DEMO_APP,
345 | });
346 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_LEAFLABS),
347 | new int[] {
348 | UsbId.LEAFLABS_MAPLE,
349 | });
350 | return supportedDevices;
351 | }
352 |
353 | }
354 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 | }
279 |
280 | switch (stopBits) {
281 | case STOPBITS_1:
282 | configDataBits |= 0;
283 | break;
284 | case STOPBITS_2:
285 | configDataBits |= 2;
286 | break;
287 | }
288 | setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
289 | }
290 |
291 | @Override
292 | public boolean getCD() throws IOException {
293 | return false;
294 | }
295 |
296 | @Override
297 | public boolean getCTS() throws IOException {
298 | return false;
299 | }
300 |
301 | @Override
302 | public boolean getDSR() throws IOException {
303 | return false;
304 | }
305 |
306 | @Override
307 | public boolean getDTR() throws IOException {
308 | return true;
309 | }
310 |
311 | @Override
312 | public void setDTR(boolean value) throws IOException {
313 | }
314 |
315 | @Override
316 | public boolean getRI() throws IOException {
317 | return false;
318 | }
319 |
320 | @Override
321 | public boolean getRTS() throws IOException {
322 | return true;
323 | }
324 |
325 | @Override
326 | public void setRTS(boolean value) throws IOException {
327 | }
328 |
329 | @Override
330 | public boolean purgeHwBuffers(boolean purgeReadBuffers,
331 | boolean purgeWriteBuffers) throws IOException {
332 | int value = (purgeReadBuffers ? FLUSH_READ_CODE : 0)
333 | | (purgeWriteBuffers ? FLUSH_WRITE_CODE : 0);
334 |
335 | if (value != 0) {
336 | setConfigSingle(SILABSER_FLUSH_REQUEST_CODE, value);
337 | }
338 |
339 | return true;
340 | }
341 |
342 | }
343 |
344 | public static Map getSupportedDevices() {
345 | final Map supportedDevices = new LinkedHashMap();
346 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_SILABS),
347 | new int[] {
348 | UsbId.SILABS_CP2102,
349 | UsbId.SILABS_CP2105,
350 | UsbId.SILABS_CP2108,
351 | UsbId.SILABS_CP2110
352 | });
353 | return supportedDevices;
354 | }
355 |
356 | }
357 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.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.hoho.android.usbserial.driver;
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.UsbRequest;
29 | import android.util.Log;
30 |
31 | import com.hoho.android.usbserial.util.HexDump;
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 | * A {@link CommonUsbSerialPort} implementation for a variety of FTDI devices
42 | *
43 | * This driver is based on libftdi, and is
45 | * copyright and subject to the following terms:
46 | *
47 | *
48 | * Copyright (C) 2003 by Intra2net AG
49 | *
50 | * This program is free software; you can redistribute it and/or modify
51 | * it under the terms of the GNU Lesser General Public License
52 | * version 2.1 as published by the Free Software Foundation;
53 | *
54 | * opensource@intra2net.com
55 | * http://www.intra2net.com/en/developer/libftdi
56 | *
57 | *
58 | *
59 | *
60 | * Some FTDI devices have not been tested; see later listing of supported and
61 | * unsupported devices. Devices listed as "supported" support the following
62 | * features:
63 | *
64 | *
Read and write of serial data (see
65 | * {@link CommonUsbSerialPort#read(byte[], int)} and
66 | * {@link CommonUsbSerialPort#write(byte[], int)}.
67 | *
Setting serial line parameters (see
68 | * {@link CommonUsbSerialPort#setParameters(int, int, int, int)}.
69 | *
70 | *
71 | *
72 | * Supported and tested devices:
73 | *
74 | *
{@value DeviceType#TYPE_R}
75 | *
76 | *
77 | *
78 | * Unsupported but possibly working devices (please contact the author with
79 | * feedback or patches):
80 | *
81 | *
{@value DeviceType#TYPE_2232C}
82 | *
{@value DeviceType#TYPE_2232H}
83 | *
{@value DeviceType#TYPE_4232H}
84 | *
{@value DeviceType#TYPE_AM}
85 | *
{@value DeviceType#TYPE_BM}
86 | *
87 | *
88 | *
89 | * @author mike wakerly (opensource@hoho.com)
90 | * @see USB Serial
91 | * for Android project page
92 | * @see FTDI Homepage
93 | * @see libftdi
94 | */
95 | public class FtdiSerialDriver implements UsbSerialDriver {
96 |
97 | private final UsbDevice mDevice;
98 | private final UsbSerialPort mPort;
99 |
100 | /**
101 | * FTDI chip types.
102 | */
103 | private static enum DeviceType {
104 | TYPE_BM, TYPE_AM, TYPE_2232C, TYPE_R, TYPE_2232H, TYPE_4232H;
105 | }
106 |
107 | public FtdiSerialDriver(UsbDevice device) {
108 | mDevice = device;
109 | mPort = new FtdiSerialPort(mDevice, 0);
110 | }
111 | @Override
112 | public UsbDevice getDevice() {
113 | return mDevice;
114 | }
115 |
116 | @Override
117 | public List getPorts() {
118 | return Collections.singletonList(mPort);
119 | }
120 |
121 | private class FtdiSerialPort extends CommonUsbSerialPort {
122 |
123 | public static final int USB_TYPE_STANDARD = 0x00 << 5;
124 | public static final int USB_TYPE_CLASS = 0x00 << 5;
125 | public static final int USB_TYPE_VENDOR = 0x00 << 5;
126 | public static final int USB_TYPE_RESERVED = 0x00 << 5;
127 |
128 | public static final int USB_RECIP_DEVICE = 0x00;
129 | public static final int USB_RECIP_INTERFACE = 0x01;
130 | public static final int USB_RECIP_ENDPOINT = 0x02;
131 | public static final int USB_RECIP_OTHER = 0x03;
132 |
133 | public static final int USB_ENDPOINT_IN = 0x80;
134 | public static final int USB_ENDPOINT_OUT = 0x00;
135 |
136 | public static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
137 | public static final int USB_READ_TIMEOUT_MILLIS = 5000;
138 |
139 | // From ftdi.h
140 | /**
141 | * Reset the port.
142 | */
143 | private static final int SIO_RESET_REQUEST = 0;
144 |
145 | /**
146 | * Set the modem control register.
147 | */
148 | private static final int SIO_MODEM_CTRL_REQUEST = 1;
149 |
150 | /**
151 | * Set flow control register.
152 | */
153 | private static final int SIO_SET_FLOW_CTRL_REQUEST = 2;
154 |
155 | /**
156 | * Set baud rate.
157 | */
158 | private static final int SIO_SET_BAUD_RATE_REQUEST = 3;
159 |
160 | /**
161 | * Set the data characteristics of the port.
162 | */
163 | private static final int SIO_SET_DATA_REQUEST = 4;
164 |
165 | private static final int SIO_RESET_SIO = 0;
166 | private static final int SIO_RESET_PURGE_RX = 1;
167 | private static final int SIO_RESET_PURGE_TX = 2;
168 |
169 | public static final int FTDI_DEVICE_OUT_REQTYPE =
170 | UsbConstants.USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT;
171 |
172 | public static final int FTDI_DEVICE_IN_REQTYPE =
173 | UsbConstants.USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
174 |
175 | /**
176 | * Length of the modem status header, transmitted with every read.
177 | */
178 | private static final int MODEM_STATUS_HEADER_LENGTH = 2;
179 |
180 | private final String TAG = FtdiSerialDriver.class.getSimpleName();
181 |
182 | private DeviceType mType;
183 |
184 | private int mInterface = 0; /* INTERFACE_ANY */
185 |
186 | private int mMaxPacketSize = 64; // TODO(mikey): detect
187 |
188 | /**
189 | * Due to http://b.android.com/28023 , we cannot use UsbRequest async reads
190 | * since it gives no indication of number of bytes read. Set this to
191 | * {@code true} on platforms where it is fixed.
192 | */
193 | private static final boolean ENABLE_ASYNC_READS = false;
194 |
195 | public FtdiSerialPort(UsbDevice device, int portNumber) {
196 | super(device, portNumber);
197 | }
198 |
199 | @Override
200 | public UsbSerialDriver getDriver() {
201 | return FtdiSerialDriver.this;
202 | }
203 |
204 | /**
205 | * Filter FTDI status bytes from buffer
206 | * @param src The source buffer (which contains status bytes)
207 | * @param dest The destination buffer to write the status bytes into (can be src)
208 | * @param totalBytesRead Number of bytes read to src
209 | * @param maxPacketSize The USB endpoint max packet size
210 | * @return The number of payload bytes
211 | */
212 | private final int filterStatusBytes(byte[] src, byte[] dest, int totalBytesRead, int maxPacketSize) {
213 | final int packetsCount = totalBytesRead / maxPacketSize + (totalBytesRead % maxPacketSize == 0 ? 0 : 1);
214 | for (int packetIdx = 0; packetIdx < packetsCount; ++packetIdx) {
215 | final int count = (packetIdx == (packetsCount - 1))
216 | ? (totalBytesRead % maxPacketSize) - MODEM_STATUS_HEADER_LENGTH
217 | : maxPacketSize - MODEM_STATUS_HEADER_LENGTH;
218 | if (count > 0) {
219 | System.arraycopy(src,
220 | packetIdx * maxPacketSize + MODEM_STATUS_HEADER_LENGTH,
221 | dest,
222 | packetIdx * (maxPacketSize - MODEM_STATUS_HEADER_LENGTH),
223 | count);
224 | }
225 | }
226 |
227 | return totalBytesRead - (packetsCount * 2);
228 | }
229 |
230 | public void reset() throws IOException {
231 | int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
232 | SIO_RESET_SIO, 0 /* index */, null, 0, USB_WRITE_TIMEOUT_MILLIS);
233 | if (result != 0) {
234 | throw new IOException("Reset failed: result=" + result);
235 | }
236 |
237 | // TODO(mikey): autodetect.
238 | mType = DeviceType.TYPE_R;
239 | }
240 |
241 | @Override
242 | public void open(UsbDeviceConnection connection) throws IOException {
243 | if (mConnection != null) {
244 | throw new IOException("Already open");
245 | }
246 | mConnection = connection;
247 |
248 | boolean opened = false;
249 | try {
250 | for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
251 | if (connection.claimInterface(mDevice.getInterface(i), true)) {
252 | Log.d(TAG, "claimInterface " + i + " SUCCESS");
253 | } else {
254 | throw new IOException("Error claiming interface " + i);
255 | }
256 | }
257 | reset();
258 | opened = true;
259 | } finally {
260 | if (!opened) {
261 | close();
262 | mConnection = null;
263 | }
264 | }
265 | }
266 |
267 | @Override
268 | public void close() throws IOException {
269 | if (mConnection == null) {
270 | throw new IOException("Already closed");
271 | }
272 | try {
273 | mConnection.close();
274 | } finally {
275 | mConnection = null;
276 | }
277 | }
278 |
279 | @Override
280 | public int read(byte[] dest, int timeoutMillis) throws IOException {
281 | final UsbEndpoint endpoint = mDevice.getInterface(0).getEndpoint(0);
282 |
283 | if (ENABLE_ASYNC_READS) {
284 | final int readAmt;
285 | synchronized (mReadBufferLock) {
286 | // mReadBuffer is only used for maximum read size.
287 | readAmt = Math.min(dest.length, mReadBuffer.length);
288 | }
289 |
290 | final UsbRequest request = new UsbRequest();
291 | request.initialize(mConnection, endpoint);
292 |
293 | final ByteBuffer buf = ByteBuffer.wrap(dest);
294 | if (!request.queue(buf, readAmt)) {
295 | throw new IOException("Error queueing request.");
296 | }
297 |
298 | final UsbRequest response = mConnection.requestWait();
299 | if (response == null) {
300 | throw new IOException("Null response");
301 | }
302 |
303 | final int payloadBytesRead = buf.position() - MODEM_STATUS_HEADER_LENGTH;
304 | if (payloadBytesRead > 0) {
305 | Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
306 | return payloadBytesRead;
307 | } else {
308 | return 0;
309 | }
310 | } else {
311 | final int totalBytesRead;
312 |
313 | synchronized (mReadBufferLock) {
314 | final int readAmt = Math.min(dest.length, mReadBuffer.length);
315 | totalBytesRead = mConnection.bulkTransfer(endpoint, mReadBuffer,
316 | readAmt, timeoutMillis);
317 |
318 | if (totalBytesRead < MODEM_STATUS_HEADER_LENGTH) {
319 | throw new IOException("Expected at least " + MODEM_STATUS_HEADER_LENGTH + " bytes");
320 | }
321 |
322 | return filterStatusBytes(mReadBuffer, dest, totalBytesRead, endpoint.getMaxPacketSize());
323 | }
324 | }
325 | }
326 |
327 | @Override
328 | public int write(byte[] src, int timeoutMillis) throws IOException {
329 | final UsbEndpoint endpoint = mDevice.getInterface(0).getEndpoint(1);
330 | int offset = 0;
331 |
332 | while (offset < src.length) {
333 | final int writeLength;
334 | final int amtWritten;
335 |
336 | synchronized (mWriteBufferLock) {
337 | final byte[] writeBuffer;
338 |
339 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
340 | if (offset == 0) {
341 | writeBuffer = src;
342 | } else {
343 | // bulkTransfer does not support offsets, make a copy.
344 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
345 | writeBuffer = mWriteBuffer;
346 | }
347 |
348 | amtWritten = mConnection.bulkTransfer(endpoint, writeBuffer, writeLength,
349 | timeoutMillis);
350 | }
351 |
352 | if (amtWritten <= 0) {
353 | throw new IOException("Error writing " + writeLength
354 | + " bytes at offset " + offset + " length=" + src.length);
355 | }
356 |
357 | Log.d(TAG, "Wrote amtWritten=" + amtWritten + " attempted=" + writeLength);
358 | offset += amtWritten;
359 | }
360 | return offset;
361 | }
362 |
363 | private int setBaudRate(int baudRate) throws IOException {
364 | long[] vals = convertBaudrate(baudRate);
365 | long actualBaudrate = vals[0];
366 | long index = vals[1];
367 | long value = vals[2];
368 | int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE,
369 | SIO_SET_BAUD_RATE_REQUEST, (int) value, (int) index,
370 | null, 0, USB_WRITE_TIMEOUT_MILLIS);
371 | if (result != 0) {
372 | throw new IOException("Setting baudrate failed: result=" + result);
373 | }
374 | return (int) actualBaudrate;
375 | }
376 |
377 | @Override
378 | public void setParameters(int baudRate, int dataBits, int stopBits, int parity)
379 | throws IOException {
380 | setBaudRate(baudRate);
381 |
382 | int config = dataBits;
383 |
384 | switch (parity) {
385 | case PARITY_NONE:
386 | config |= (0x00 << 8);
387 | break;
388 | case PARITY_ODD:
389 | config |= (0x01 << 8);
390 | break;
391 | case PARITY_EVEN:
392 | config |= (0x02 << 8);
393 | break;
394 | case PARITY_MARK:
395 | config |= (0x03 << 8);
396 | break;
397 | case PARITY_SPACE:
398 | config |= (0x04 << 8);
399 | break;
400 | default:
401 | throw new IllegalArgumentException("Unknown parity value: " + parity);
402 | }
403 |
404 | switch (stopBits) {
405 | case STOPBITS_1:
406 | config |= (0x00 << 11);
407 | break;
408 | case STOPBITS_1_5:
409 | config |= (0x01 << 11);
410 | break;
411 | case STOPBITS_2:
412 | config |= (0x02 << 11);
413 | break;
414 | default:
415 | throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
416 | }
417 |
418 | int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE,
419 | SIO_SET_DATA_REQUEST, config, 0 /* index */,
420 | null, 0, USB_WRITE_TIMEOUT_MILLIS);
421 | if (result != 0) {
422 | throw new IOException("Setting parameters failed: result=" + result);
423 | }
424 | }
425 |
426 | private long[] convertBaudrate(int baudrate) {
427 | // TODO(mikey): Braindead transcription of libfti method. Clean up,
428 | // using more idiomatic Java where possible.
429 | int divisor = 24000000 / baudrate;
430 | int bestDivisor = 0;
431 | int bestBaud = 0;
432 | int bestBaudDiff = 0;
433 | int fracCode[] = {
434 | 0, 3, 2, 4, 1, 5, 6, 7
435 | };
436 |
437 | for (int i = 0; i < 2; i++) {
438 | int tryDivisor = divisor + i;
439 | int baudEstimate;
440 | int baudDiff;
441 |
442 | if (tryDivisor <= 8) {
443 | // Round up to minimum supported divisor
444 | tryDivisor = 8;
445 | } else if (mType != DeviceType.TYPE_AM && tryDivisor < 12) {
446 | // BM doesn't support divisors 9 through 11 inclusive
447 | tryDivisor = 12;
448 | } else if (divisor < 16) {
449 | // AM doesn't support divisors 9 through 15 inclusive
450 | tryDivisor = 16;
451 | } else {
452 | if (mType == DeviceType.TYPE_AM) {
453 | // TODO
454 | } else {
455 | if (tryDivisor > 0x1FFFF) {
456 | // Round down to maximum supported divisor value (for
457 | // BM)
458 | tryDivisor = 0x1FFFF;
459 | }
460 | }
461 | }
462 |
463 | // Get estimated baud rate (to nearest integer)
464 | baudEstimate = (24000000 + (tryDivisor / 2)) / tryDivisor;
465 |
466 | // Get absolute difference from requested baud rate
467 | if (baudEstimate < baudrate) {
468 | baudDiff = baudrate - baudEstimate;
469 | } else {
470 | baudDiff = baudEstimate - baudrate;
471 | }
472 |
473 | if (i == 0 || baudDiff < bestBaudDiff) {
474 | // Closest to requested baud rate so far
475 | bestDivisor = tryDivisor;
476 | bestBaud = baudEstimate;
477 | bestBaudDiff = baudDiff;
478 | if (baudDiff == 0) {
479 | // Spot on! No point trying
480 | break;
481 | }
482 | }
483 | }
484 |
485 | // Encode the best divisor value
486 | long encodedDivisor = (bestDivisor >> 3) | (fracCode[bestDivisor & 7] << 14);
487 | // Deal with special cases for encoded value
488 | if (encodedDivisor == 1) {
489 | encodedDivisor = 0; // 3000000 baud
490 | } else if (encodedDivisor == 0x4001) {
491 | encodedDivisor = 1; // 2000000 baud (BM only)
492 | }
493 |
494 | // Split into "value" and "index" values
495 | long value = encodedDivisor & 0xFFFF;
496 | long index;
497 | if (mType == DeviceType.TYPE_2232C || mType == DeviceType.TYPE_2232H
498 | || mType == DeviceType.TYPE_4232H) {
499 | index = (encodedDivisor >> 8) & 0xffff;
500 | index &= 0xFF00;
501 | index |= 0 /* TODO mIndex */;
502 | } else {
503 | index = (encodedDivisor >> 16) & 0xffff;
504 | }
505 |
506 | // Return the nearest baud rate
507 | return new long[] {
508 | bestBaud, index, value
509 | };
510 | }
511 |
512 | @Override
513 | public boolean getCD() throws IOException {
514 | return false;
515 | }
516 |
517 | @Override
518 | public boolean getCTS() throws IOException {
519 | return false;
520 | }
521 |
522 | @Override
523 | public boolean getDSR() throws IOException {
524 | return false;
525 | }
526 |
527 | @Override
528 | public boolean getDTR() throws IOException {
529 | return false;
530 | }
531 |
532 | @Override
533 | public void setDTR(boolean value) throws IOException {
534 | }
535 |
536 | @Override
537 | public boolean getRI() throws IOException {
538 | return false;
539 | }
540 |
541 | @Override
542 | public boolean getRTS() throws IOException {
543 | return false;
544 | }
545 |
546 | @Override
547 | public void setRTS(boolean value) throws IOException {
548 | }
549 |
550 | @Override
551 | public boolean purgeHwBuffers(boolean purgeReadBuffers, boolean purgeWriteBuffers) throws IOException {
552 | if (purgeReadBuffers) {
553 | int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
554 | SIO_RESET_PURGE_RX, 0 /* index */, null, 0, USB_WRITE_TIMEOUT_MILLIS);
555 | if (result != 0) {
556 | throw new IOException("Flushing RX failed: result=" + result);
557 | }
558 | }
559 |
560 | if (purgeWriteBuffers) {
561 | int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
562 | SIO_RESET_PURGE_TX, 0 /* index */, null, 0, USB_WRITE_TIMEOUT_MILLIS);
563 | if (result != 0) {
564 | throw new IOException("Flushing RX failed: result=" + result);
565 | }
566 | }
567 | return true;
568 | }
569 | }
570 |
571 | public static Map getSupportedDevices() {
572 | final Map supportedDevices = new LinkedHashMap();
573 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_FTDI),
574 | new int[] {
575 | UsbId.FTDI_FT232R,
576 | UsbId.FTDI_FT231X,
577 | });
578 | return supportedDevices;
579 | }
580 |
581 | }
582 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 | }
298 | }
299 |
300 | if (mDevice.getDeviceClass() == 0x02) {
301 | mDeviceType = DEVICE_TYPE_0;
302 | } else {
303 | try {
304 | Method getRawDescriptorsMethod
305 | = mConnection.getClass().getMethod("getRawDescriptors");
306 | byte[] rawDescriptors
307 | = (byte[]) getRawDescriptorsMethod.invoke(mConnection);
308 | byte maxPacketSize0 = rawDescriptors[7];
309 | if (maxPacketSize0 == 64) {
310 | mDeviceType = DEVICE_TYPE_HX;
311 | } else if ((mDevice.getDeviceClass() == 0x00)
312 | || (mDevice.getDeviceClass() == 0xff)) {
313 | mDeviceType = DEVICE_TYPE_1;
314 | } else {
315 | Log.w(TAG, "Could not detect PL2303 subtype, "
316 | + "Assuming that it is a HX device");
317 | mDeviceType = DEVICE_TYPE_HX;
318 | }
319 | } catch (NoSuchMethodException e) {
320 | Log.w(TAG, "Method UsbDeviceConnection.getRawDescriptors, "
321 | + "required for PL2303 subtype detection, not "
322 | + "available! Assuming that it is a HX device");
323 | mDeviceType = DEVICE_TYPE_HX;
324 | } catch (Exception e) {
325 | Log.e(TAG, "An unexpected exception occured while trying "
326 | + "to detect PL2303 subtype", e);
327 | }
328 | }
329 |
330 | setControlLines(mControlLinesValue);
331 | resetDevice();
332 |
333 | doBlackMagic();
334 | opened = true;
335 | } finally {
336 | if (!opened) {
337 | mConnection = null;
338 | connection.releaseInterface(usbInterface);
339 | }
340 | }
341 | }
342 |
343 | @Override
344 | public void close() throws IOException {
345 | if (mConnection == null) {
346 | throw new IOException("Already closed");
347 | }
348 | try {
349 | mStopReadStatusThread = true;
350 | synchronized (mReadStatusThreadLock) {
351 | if (mReadStatusThread != null) {
352 | try {
353 | mReadStatusThread.join();
354 | } catch (Exception e) {
355 | Log.w(TAG, "An error occured while waiting for status read thread", e);
356 | }
357 | }
358 | }
359 | resetDevice();
360 | } finally {
361 | try {
362 | mConnection.releaseInterface(mDevice.getInterface(0));
363 | } finally {
364 | mConnection = null;
365 | }
366 | }
367 | }
368 |
369 | @Override
370 | public int read(byte[] dest, int timeoutMillis) throws IOException {
371 | synchronized (mReadBufferLock) {
372 | int readAmt = Math.min(dest.length, mReadBuffer.length);
373 | int numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer,
374 | readAmt, timeoutMillis);
375 | if (numBytesRead < 0) {
376 | return 0;
377 | }
378 | System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
379 | return numBytesRead;
380 | }
381 | }
382 |
383 | @Override
384 | public int write(byte[] src, int timeoutMillis) throws IOException {
385 | int offset = 0;
386 |
387 | while (offset < src.length) {
388 | final int writeLength;
389 | final int amtWritten;
390 |
391 | synchronized (mWriteBufferLock) {
392 | final byte[] writeBuffer;
393 |
394 | writeLength = Math.min(src.length - offset, mWriteBuffer.length);
395 | if (offset == 0) {
396 | writeBuffer = src;
397 | } else {
398 | // bulkTransfer does not support offsets, make a copy.
399 | System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
400 | writeBuffer = mWriteBuffer;
401 | }
402 |
403 | amtWritten = mConnection.bulkTransfer(mWriteEndpoint,
404 | writeBuffer, writeLength, timeoutMillis);
405 | }
406 |
407 | if (amtWritten <= 0) {
408 | throw new IOException("Error writing " + writeLength
409 | + " bytes at offset " + offset + " length="
410 | + src.length);
411 | }
412 |
413 | offset += amtWritten;
414 | }
415 | return offset;
416 | }
417 |
418 | @Override
419 | public void setParameters(int baudRate, int dataBits, int stopBits,
420 | int parity) throws IOException {
421 | if ((mBaudRate == baudRate) && (mDataBits == dataBits)
422 | && (mStopBits == stopBits) && (mParity == parity)) {
423 | // Make sure no action is performed if there is nothing to change
424 | return;
425 | }
426 |
427 | byte[] lineRequestData = new byte[7];
428 |
429 | lineRequestData[0] = (byte) (baudRate & 0xff);
430 | lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff);
431 | lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff);
432 | lineRequestData[3] = (byte) ((baudRate >> 24) & 0xff);
433 |
434 | switch (stopBits) {
435 | case STOPBITS_1:
436 | lineRequestData[4] = 0;
437 | break;
438 |
439 | case STOPBITS_1_5:
440 | lineRequestData[4] = 1;
441 | break;
442 |
443 | case STOPBITS_2:
444 | lineRequestData[4] = 2;
445 | break;
446 |
447 | default:
448 | throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
449 | }
450 |
451 | switch (parity) {
452 | case PARITY_NONE:
453 | lineRequestData[5] = 0;
454 | break;
455 |
456 | case PARITY_ODD:
457 | lineRequestData[5] = 1;
458 | break;
459 |
460 | case PARITY_MARK:
461 | lineRequestData[5] = 3;
462 | break;
463 |
464 | case PARITY_SPACE:
465 | lineRequestData[5] = 4;
466 | break;
467 |
468 | default:
469 | throw new IllegalArgumentException("Unknown parity value: " + parity);
470 | }
471 |
472 | lineRequestData[6] = (byte) dataBits;
473 |
474 | ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);
475 |
476 | resetDevice();
477 |
478 | mBaudRate = baudRate;
479 | mDataBits = dataBits;
480 | mStopBits = stopBits;
481 | mParity = parity;
482 | }
483 |
484 | @Override
485 | public boolean getCD() throws IOException {
486 | return testStatusFlag(STATUS_FLAG_CD);
487 | }
488 |
489 | @Override
490 | public boolean getCTS() throws IOException {
491 | return testStatusFlag(STATUS_FLAG_CTS);
492 | }
493 |
494 | @Override
495 | public boolean getDSR() throws IOException {
496 | return testStatusFlag(STATUS_FLAG_DSR);
497 | }
498 |
499 | @Override
500 | public boolean getDTR() throws IOException {
501 | return ((mControlLinesValue & CONTROL_DTR) == CONTROL_DTR);
502 | }
503 |
504 | @Override
505 | public void setDTR(boolean value) throws IOException {
506 | int newControlLinesValue;
507 | if (value) {
508 | newControlLinesValue = mControlLinesValue | CONTROL_DTR;
509 | } else {
510 | newControlLinesValue = mControlLinesValue & ~CONTROL_DTR;
511 | }
512 | setControlLines(newControlLinesValue);
513 | }
514 |
515 | @Override
516 | public boolean getRI() throws IOException {
517 | return testStatusFlag(STATUS_FLAG_RI);
518 | }
519 |
520 | @Override
521 | public boolean getRTS() throws IOException {
522 | return ((mControlLinesValue & CONTROL_RTS) == CONTROL_RTS);
523 | }
524 |
525 | @Override
526 | public void setRTS(boolean value) throws IOException {
527 | int newControlLinesValue;
528 | if (value) {
529 | newControlLinesValue = mControlLinesValue | CONTROL_RTS;
530 | } else {
531 | newControlLinesValue = mControlLinesValue & ~CONTROL_RTS;
532 | }
533 | setControlLines(newControlLinesValue);
534 | }
535 |
536 | @Override
537 | public boolean purgeHwBuffers(boolean purgeReadBuffers, boolean purgeWriteBuffers) throws IOException {
538 | if (purgeReadBuffers) {
539 | vendorOut(FLUSH_RX_REQUEST, 0, null);
540 | }
541 |
542 | if (purgeWriteBuffers) {
543 | vendorOut(FLUSH_TX_REQUEST, 0, null);
544 | }
545 |
546 | return purgeReadBuffers || purgeWriteBuffers;
547 | }
548 | }
549 |
550 | public static Map getSupportedDevices() {
551 | final Map supportedDevices = new LinkedHashMap();
552 | supportedDevices.put(Integer.valueOf(UsbId.VENDOR_PROLIFIC),
553 | new int[] { UsbId.PROLIFIC_PL2303, });
554 | return supportedDevices;
555 | }
556 | }
557 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
52 | public static final int VENDOR_VAN_OOIJEN_TECH = 0x16c0;
53 | public static final int VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL = 0x0483;
54 |
55 | public static final int VENDOR_LEAFLABS = 0x1eaf;
56 | public static final int LEAFLABS_MAPLE = 0x0004;
57 |
58 | public static final int VENDOR_SILABS = 0x10c4;
59 | public static final int SILABS_CP2102 = 0xea60;
60 | public static final int SILABS_CP2105 = 0xea70;
61 | public static final int SILABS_CP2108 = 0xea71;
62 | public static final int SILABS_CP2110 = 0xea80;
63 |
64 | public static final int VENDOR_PROLIFIC = 0x067b;
65 | public static final int PROLIFIC_PL2303 = 0x2303;
66 |
67 | public static final int VENDOR_QINHENG = 0x1a86;
68 | public static final int QINHENG_HL340 = 0x7523;
69 |
70 | private UsbId() {
71 | throw new IllegalAccessError("Non-instantiable class.");
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/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.hoho.android.usbserial.driver;
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 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/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.hoho.android.usbserial.util;
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 | if (c >= 'A' && c <= 'F')
144 | return (c - 'A' + 10);
145 | if (c >= 'a' && c <= 'f')
146 | return (c - 'a' + 10);
147 |
148 | throw new RuntimeException("Invalid hex char '" + c + "'");
149 | }
150 |
151 | public static byte[] hexStringToByteArray(String hexString) {
152 | int length = hexString.length();
153 | byte[] buffer = new byte[length / 2];
154 |
155 | for (int i = 0; i < length; i += 2) {
156 | buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString
157 | .charAt(i + 1)));
158 | }
159 |
160 | return buffer;
161 | }
162 | }
163 |
--------------------------------------------------------------------------------
/Android/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/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.hoho.android.usbserial.util;
23 |
24 | import android.hardware.usb.UsbRequest;
25 | import android.util.Log;
26 |
27 | import com.hoho.android.usbserial.driver.UsbSerialPort;
28 |
29 | import java.io.IOException;
30 | import java.nio.ByteBuffer;
31 |
32 | /**
33 | * Utility class which services a {@link UsbSerialPort} in its {@link #run()}
34 | * method.
35 | *
36 | * @author mike wakerly (opensource@hoho.com)
37 | */
38 | public class SerialInputOutputManager implements Runnable {
39 |
40 | private static final String TAG = SerialInputOutputManager.class.getSimpleName();
41 | private static final boolean DEBUG = true;
42 |
43 | private static final int READ_WAIT_MILLIS = 200;
44 | private static final int BUFSIZ = 4096;
45 |
46 | private final UsbSerialPort mDriver;
47 |
48 | private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
49 |
50 | // Synchronized by 'mWriteBuffer'
51 | private final ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
52 |
53 | private enum State {
54 | STOPPED,
55 | RUNNING,
56 | STOPPING
57 | }
58 |
59 | // Synchronized by 'this'
60 | private State mState = State.STOPPED;
61 |
62 | // Synchronized by 'this'
63 | private Listener mListener;
64 |
65 | public interface Listener {
66 | /**
67 | * Called when new incoming data is available.
68 | */
69 | public void onNewData(byte[] data);
70 |
71 | /**
72 | * Called when {@link SerialInputOutputManager#run()} aborts due to an
73 | * error.
74 | */
75 | public void onRunError(Exception e);
76 | }
77 |
78 | /**
79 | * Creates a new instance with no listener.
80 | */
81 | public SerialInputOutputManager(UsbSerialPort driver) {
82 | this(driver, null);
83 | }
84 |
85 | /**
86 | * Creates a new instance with the provided listener.
87 | */
88 | public SerialInputOutputManager(UsbSerialPort driver, Listener listener) {
89 | mDriver = driver;
90 | mListener = listener;
91 | }
92 |
93 | public synchronized void setListener(Listener listener) {
94 | mListener = listener;
95 | }
96 |
97 | public synchronized Listener getListener() {
98 | return mListener;
99 | }
100 |
101 | public void writeAsync(byte[] data) {
102 | synchronized (mWriteBuffer) {
103 | mWriteBuffer.put(data);
104 | }
105 | }
106 |
107 | public synchronized void stop() {
108 | if (getState() == State.RUNNING) {
109 | Log.i(TAG, "Stop requested");
110 | mState = State.STOPPING;
111 | }
112 | }
113 |
114 | private synchronized State getState() {
115 | return mState;
116 | }
117 |
118 | /**
119 | * Continuously services the read and write buffers until {@link #stop()} is
120 | * called, or until a driver exception is raised.
121 | *
122 | * NOTE(mikey): Uses inefficient read/write-with-timeout.
123 | * TODO(mikey): Read asynchronously with {@link UsbRequest#queue(ByteBuffer, int)}
124 | */
125 | @Override
126 | public void run() {
127 | synchronized (this) {
128 | if (getState() != State.STOPPED) {
129 | throw new IllegalStateException("Already running.");
130 | }
131 | mState = State.RUNNING;
132 | }
133 |
134 | Log.i(TAG, "Running ..");
135 | try {
136 | while (true) {
137 | if (getState() != State.RUNNING) {
138 | Log.i(TAG, "Stopping mState=" + getState());
139 | break;
140 | }
141 | step();
142 | }
143 | } catch (Exception e) {
144 | Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
145 | final Listener listener = getListener();
146 | if (listener != null) {
147 | listener.onRunError(e);
148 | }
149 | } finally {
150 | synchronized (this) {
151 | mState = State.STOPPED;
152 | Log.i(TAG, "Stopped.");
153 | }
154 | }
155 | }
156 |
157 | private void step() throws IOException {
158 | // Handle incoming data.
159 | int len = mDriver.read(mReadBuffer.array(), READ_WAIT_MILLIS);
160 | if (len > 0) {
161 | if (DEBUG) Log.d(TAG, "Read data len=" + len);
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 |
--------------------------------------------------------------------------------
/Arduino/alcohol_sensor/alcohol_sensor.ino:
--------------------------------------------------------------------------------
1 | #define COUNT_MAX 10
2 | int index = 0;
3 | float values[COUNT_MAX];
4 |
5 | void setup() {
6 | Serial.begin(9600);
7 |
8 | initialize();
9 | delay(3000);
10 | }
11 |
12 | void loop() {
13 | float vol;
14 | int sensorValue = analogRead(A0); // read data
15 | values[index] = sensorValue;
16 |
17 | // calc average and display value
18 | if(index >= COUNT_MAX - 1) {
19 | float average = calcAverage();
20 | float bac = pow(((-3.757)*pow(10, -7))*average, 2) + 0.0008613*average -0.3919;
21 |
22 | Serial.print("a");
23 | Serial.print(bac, 4);
24 | Serial.print("z");
25 |
26 | index=0;
27 | } else {
28 | index++;
29 | }
30 |
31 | delay(100); // prepare next read
32 | }
33 |
34 | void initialize() {
35 | for(int i=0; i https://www.adafruit.com/products/1748
7 | ----> https://www.adafruit.com/products/1749
8 |
9 | These sensors use I2C to communicate, 2 pins are required to
10 | interface
11 | Adafruit invests time and resources providing this open source code,
12 | please support Adafruit and open-source hardware by purchasing
13 | products from Adafruit!
14 |
15 | Written by Limor Fried/Ladyada for Adafruit Industries.
16 | BSD license, all text above must be included in any redistribution
17 | ****************************************************/
18 |
19 | #include
20 | #include
21 | #include "U8glib.h"
22 |
23 | Adafruit_MLX90614 mlx = Adafruit_MLX90614();
24 |
25 | ///////////////////////////////////////////////////////////////////
26 | //----- OLED instance
27 | // IMPORTANT NOTE: The complete list of supported devices
28 | // with all constructor calls is here: http://code.google.com/p/u8glib/wiki/device
29 | U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0); // I2C / TWI
30 | ///////////////////////////////////////////////////////////////////
31 |
32 | // Remember received data
33 | #define INPUT_BUFFER_LEN 3
34 | char inputBuffer[INPUT_BUFFER_LEN];
35 | // Remember temperature
36 | int iRememberedTemp = 0;
37 |
38 |
39 | void setup() {
40 | Serial.begin(9600);
41 | mlx.begin();
42 | for(int i=0; i 0) {
116 | String strTemp2 = String("");
117 | strTemp2 += iRememberedTemp;
118 | char buff[5];
119 | strTemp2.toCharArray(buff, 5);
120 | buff[2] = 0x27;
121 | buff[3] = 'C';
122 | buff[4] = 0x00;
123 |
124 | u8g.drawStr(3, 40, "Prev: ");
125 | u8g.drawStr(55, 40, buff);
126 | }
127 | } while( u8g.nextPage() );
128 | }
129 |
130 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 2.1, February 1999
3 |
4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc.
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | (This is the first released version of the Lesser GPL. It also counts
10 | as the successor of the GNU Library Public License, version 2, hence
11 | the version number 2.1.)
12 |
13 | Preamble
14 |
15 | The licenses for most software are designed to take away your
16 | freedom to share and change it. By contrast, the GNU General Public
17 | Licenses are intended to guarantee your freedom to share and change
18 | free software--to make sure the software is free for all its users.
19 |
20 | This license, the Lesser General Public License, applies to some
21 | specially designated software packages--typically libraries--of the
22 | Free Software Foundation and other authors who decide to use it. You
23 | can use it too, but we suggest you first think carefully about whether
24 | this license or the ordinary General Public License is the better
25 | strategy to use in any particular case, based on the explanations below.
26 |
27 | When we speak of free software, we are referring to freedom of use,
28 | not price. Our General Public Licenses are designed to make sure that
29 | you have the freedom to distribute copies of free software (and charge
30 | for this service if you wish); that you receive source code or can get
31 | it if you want it; that you can change the software and use pieces of
32 | it in new free programs; and that you are informed that you can do
33 | these things.
34 |
35 | To protect your rights, we need to make restrictions that forbid
36 | distributors to deny you these rights or to ask you to surrender these
37 | rights. These restrictions translate to certain responsibilities for
38 | you if you distribute copies of the library or if you modify it.
39 |
40 | For example, if you distribute copies of the library, whether gratis
41 | or for a fee, you must give the recipients all the rights that we gave
42 | you. You must make sure that they, too, receive or can get the source
43 | code. If you link other code with the library, you must provide
44 | complete object files to the recipients, so that they can relink them
45 | with the library after making changes to the library and recompiling
46 | it. And you must show them these terms so they know their rights.
47 |
48 | We protect your rights with a two-step method: (1) we copyright the
49 | library, and (2) we offer you this license, which gives you legal
50 | permission to copy, distribute and/or modify the library.
51 |
52 | To protect each distributor, we want to make it very clear that
53 | there is no warranty for the free library. Also, if the library is
54 | modified by someone else and passed on, the recipients should know
55 | that what they have is not the original version, so that the original
56 | author's reputation will not be affected by problems that might be
57 | introduced by others.
58 |
59 | Finally, software patents pose a constant threat to the existence of
60 | any free program. We wish to make sure that a company cannot
61 | effectively restrict the users of a free program by obtaining a
62 | restrictive license from a patent holder. Therefore, we insist that
63 | any patent license obtained for a version of the library must be
64 | consistent with the full freedom of use specified in this license.
65 |
66 | Most GNU software, including some libraries, is covered by the
67 | ordinary GNU General Public License. This license, the GNU Lesser
68 | General Public License, applies to certain designated libraries, and
69 | is quite different from the ordinary General Public License. We use
70 | this license for certain libraries in order to permit linking those
71 | libraries into non-free programs.
72 |
73 | When a program is linked with a library, whether statically or using
74 | a shared library, the combination of the two is legally speaking a
75 | combined work, a derivative of the original library. The ordinary
76 | General Public License therefore permits such linking only if the
77 | entire combination fits its criteria of freedom. The Lesser General
78 | Public License permits more lax criteria for linking other code with
79 | the library.
80 |
81 | We call this license the "Lesser" General Public License because it
82 | does Less to protect the user's freedom than the ordinary General
83 | Public License. It also provides other free software developers Less
84 | of an advantage over competing non-free programs. These disadvantages
85 | are the reason we use the ordinary General Public License for many
86 | libraries. However, the Lesser license provides advantages in certain
87 | special circumstances.
88 |
89 | For example, on rare occasions, there may be a special need to
90 | encourage the widest possible use of a certain library, so that it becomes
91 | a de-facto standard. To achieve this, non-free programs must be
92 | allowed to use the library. A more frequent case is that a free
93 | library does the same job as widely used non-free libraries. In this
94 | case, there is little to gain by limiting the free library to free
95 | software only, so we use the Lesser General Public License.
96 |
97 | In other cases, permission to use a particular library in non-free
98 | programs enables a greater number of people to use a large body of
99 | free software. For example, permission to use the GNU C Library in
100 | non-free programs enables many more people to use the whole GNU
101 | operating system, as well as its variant, the GNU/Linux operating
102 | system.
103 |
104 | Although the Lesser General Public License is Less protective of the
105 | users' freedom, it does ensure that the user of a program that is
106 | linked with the Library has the freedom and the wherewithal to run
107 | that program using a modified version of the Library.
108 |
109 | The precise terms and conditions for copying, distribution and
110 | modification follow. Pay close attention to the difference between a
111 | "work based on the library" and a "work that uses the library". The
112 | former contains code derived from the library, whereas the latter must
113 | be combined with the library in order to run.
114 |
115 | GNU LESSER GENERAL PUBLIC LICENSE
116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
117 |
118 | 0. This License Agreement applies to any software library or other
119 | program which contains a notice placed by the copyright holder or
120 | other authorized party saying it may be distributed under the terms of
121 | this Lesser General Public License (also called "this License").
122 | Each licensee is addressed as "you".
123 |
124 | A "library" means a collection of software functions and/or data
125 | prepared so as to be conveniently linked with application programs
126 | (which use some of those functions and data) to form executables.
127 |
128 | The "Library", below, refers to any such software library or work
129 | which has been distributed under these terms. A "work based on the
130 | Library" means either the Library or any derivative work under
131 | copyright law: that is to say, a work containing the Library or a
132 | portion of it, either verbatim or with modifications and/or translated
133 | straightforwardly into another language. (Hereinafter, translation is
134 | included without limitation in the term "modification".)
135 |
136 | "Source code" for a work means the preferred form of the work for
137 | making modifications to it. For a library, complete source code means
138 | all the source code for all modules it contains, plus any associated
139 | interface definition files, plus the scripts used to control compilation
140 | and installation of the library.
141 |
142 | Activities other than copying, distribution and modification are not
143 | covered by this License; they are outside its scope. The act of
144 | running a program using the Library is not restricted, and output from
145 | such a program is covered only if its contents constitute a work based
146 | on the Library (independent of the use of the Library in a tool for
147 | writing it). Whether that is true depends on what the Library does
148 | and what the program that uses the Library does.
149 |
150 | 1. You may copy and distribute verbatim copies of the Library's
151 | complete source code as you receive it, in any medium, provided that
152 | you conspicuously and appropriately publish on each copy an
153 | appropriate copyright notice and disclaimer of warranty; keep intact
154 | all the notices that refer to this License and to the absence of any
155 | warranty; and distribute a copy of this License along with the
156 | Library.
157 |
158 | You may charge a fee for the physical act of transferring a copy,
159 | and you may at your option offer warranty protection in exchange for a
160 | fee.
161 |
162 | 2. You may modify your copy or copies of the Library or any portion
163 | of it, thus forming a work based on the Library, and copy and
164 | distribute such modifications or work under the terms of Section 1
165 | above, provided that you also meet all of these conditions:
166 |
167 | a) The modified work must itself be a software library.
168 |
169 | b) You must cause the files modified to carry prominent notices
170 | stating that you changed the files and the date of any change.
171 |
172 | c) You must cause the whole of the work to be licensed at no
173 | charge to all third parties under the terms of this License.
174 |
175 | d) If a facility in the modified Library refers to a function or a
176 | table of data to be supplied by an application program that uses
177 | the facility, other than as an argument passed when the facility
178 | is invoked, then you must make a good faith effort to ensure that,
179 | in the event an application does not supply such function or
180 | table, the facility still operates, and performs whatever part of
181 | its purpose remains meaningful.
182 |
183 | (For example, a function in a library to compute square roots has
184 | a purpose that is entirely well-defined independent of the
185 | application. Therefore, Subsection 2d requires that any
186 | application-supplied function or table used by this function must
187 | be optional: if the application does not supply it, the square
188 | root function must still compute square roots.)
189 |
190 | These requirements apply to the modified work as a whole. If
191 | identifiable sections of that work are not derived from the Library,
192 | and can be reasonably considered independent and separate works in
193 | themselves, then this License, and its terms, do not apply to those
194 | sections when you distribute them as separate works. But when you
195 | distribute the same sections as part of a whole which is a work based
196 | on the Library, the distribution of the whole must be on the terms of
197 | this License, whose permissions for other licensees extend to the
198 | entire whole, and thus to each and every part regardless of who wrote
199 | it.
200 |
201 | Thus, it is not the intent of this section to claim rights or contest
202 | your rights to work written entirely by you; rather, the intent is to
203 | exercise the right to control the distribution of derivative or
204 | collective works based on the Library.
205 |
206 | In addition, mere aggregation of another work not based on the Library
207 | with the Library (or with a work based on the Library) on a volume of
208 | a storage or distribution medium does not bring the other work under
209 | the scope of this License.
210 |
211 | 3. You may opt to apply the terms of the ordinary GNU General Public
212 | License instead of this License to a given copy of the Library. To do
213 | this, you must alter all the notices that refer to this License, so
214 | that they refer to the ordinary GNU General Public License, version 2,
215 | instead of to this License. (If a newer version than version 2 of the
216 | ordinary GNU General Public License has appeared, then you can specify
217 | that version instead if you wish.) Do not make any other change in
218 | these notices.
219 |
220 | Once this change is made in a given copy, it is irreversible for
221 | that copy, so the ordinary GNU General Public License applies to all
222 | subsequent copies and derivative works made from that copy.
223 |
224 | This option is useful when you wish to copy part of the code of
225 | the Library into a program that is not a library.
226 |
227 | 4. You may copy and distribute the Library (or a portion or
228 | derivative of it, under Section 2) in object code or executable form
229 | under the terms of Sections 1 and 2 above provided that you accompany
230 | it with the complete corresponding machine-readable source code, which
231 | must be distributed under the terms of Sections 1 and 2 above on a
232 | medium customarily used for software interchange.
233 |
234 | If distribution of object code is made by offering access to copy
235 | from a designated place, then offering equivalent access to copy the
236 | source code from the same place satisfies the requirement to
237 | distribute the source code, even though third parties are not
238 | compelled to copy the source along with the object code.
239 |
240 | 5. A program that contains no derivative of any portion of the
241 | Library, but is designed to work with the Library by being compiled or
242 | linked with it, is called a "work that uses the Library". Such a
243 | work, in isolation, is not a derivative work of the Library, and
244 | therefore falls outside the scope of this License.
245 |
246 | However, linking a "work that uses the Library" with the Library
247 | creates an executable that is a derivative of the Library (because it
248 | contains portions of the Library), rather than a "work that uses the
249 | library". The executable is therefore covered by this License.
250 | Section 6 states terms for distribution of such executables.
251 |
252 | When a "work that uses the Library" uses material from a header file
253 | that is part of the Library, the object code for the work may be a
254 | derivative work of the Library even though the source code is not.
255 | Whether this is true is especially significant if the work can be
256 | linked without the Library, or if the work is itself a library. The
257 | threshold for this to be true is not precisely defined by law.
258 |
259 | If such an object file uses only numerical parameters, data
260 | structure layouts and accessors, and small macros and small inline
261 | functions (ten lines or less in length), then the use of the object
262 | file is unrestricted, regardless of whether it is legally a derivative
263 | work. (Executables containing this object code plus portions of the
264 | Library will still fall under Section 6.)
265 |
266 | Otherwise, if the work is a derivative of the Library, you may
267 | distribute the object code for the work under the terms of Section 6.
268 | Any executables containing that work also fall under Section 6,
269 | whether or not they are linked directly with the Library itself.
270 |
271 | 6. As an exception to the Sections above, you may also combine or
272 | link a "work that uses the Library" with the Library to produce a
273 | work containing portions of the Library, and distribute that work
274 | under terms of your choice, provided that the terms permit
275 | modification of the work for the customer's own use and reverse
276 | engineering for debugging such modifications.
277 |
278 | You must give prominent notice with each copy of the work that the
279 | Library is used in it and that the Library and its use are covered by
280 | this License. You must supply a copy of this License. If the work
281 | during execution displays copyright notices, you must include the
282 | copyright notice for the Library among them, as well as a reference
283 | directing the user to the copy of this License. Also, you must do one
284 | of these things:
285 |
286 | a) Accompany the work with the complete corresponding
287 | machine-readable source code for the Library including whatever
288 | changes were used in the work (which must be distributed under
289 | Sections 1 and 2 above); and, if the work is an executable linked
290 | with the Library, with the complete machine-readable "work that
291 | uses the Library", as object code and/or source code, so that the
292 | user can modify the Library and then relink to produce a modified
293 | executable containing the modified Library. (It is understood
294 | that the user who changes the contents of definitions files in the
295 | Library will not necessarily be able to recompile the application
296 | to use the modified definitions.)
297 |
298 | b) Use a suitable shared library mechanism for linking with the
299 | Library. A suitable mechanism is one that (1) uses at run time a
300 | copy of the library already present on the user's computer system,
301 | rather than copying library functions into the executable, and (2)
302 | will operate properly with a modified version of the library, if
303 | the user installs one, as long as the modified version is
304 | interface-compatible with the version that the work was made with.
305 |
306 | c) Accompany the work with a written offer, valid for at
307 | least three years, to give the same user the materials
308 | specified in Subsection 6a, above, for a charge no more
309 | than the cost of performing this distribution.
310 |
311 | d) If distribution of the work is made by offering access to copy
312 | from a designated place, offer equivalent access to copy the above
313 | specified materials from the same place.
314 |
315 | e) Verify that the user has already received a copy of these
316 | materials or that you have already sent this user a copy.
317 |
318 | For an executable, the required form of the "work that uses the
319 | Library" must include any data and utility programs needed for
320 | reproducing the executable from it. However, as a special exception,
321 | the materials to be distributed need not include anything that is
322 | normally distributed (in either source or binary form) with the major
323 | components (compiler, kernel, and so on) of the operating system on
324 | which the executable runs, unless that component itself accompanies
325 | the executable.
326 |
327 | It may happen that this requirement contradicts the license
328 | restrictions of other proprietary libraries that do not normally
329 | accompany the operating system. Such a contradiction means you cannot
330 | use both them and the Library together in an executable that you
331 | distribute.
332 |
333 | 7. You may place library facilities that are a work based on the
334 | Library side-by-side in a single library together with other library
335 | facilities not covered by this License, and distribute such a combined
336 | library, provided that the separate distribution of the work based on
337 | the Library and of the other library facilities is otherwise
338 | permitted, and provided that you do these two things:
339 |
340 | a) Accompany the combined library with a copy of the same work
341 | based on the Library, uncombined with any other library
342 | facilities. This must be distributed under the terms of the
343 | Sections above.
344 |
345 | b) Give prominent notice with the combined library of the fact
346 | that part of it is a work based on the Library, and explaining
347 | where to find the accompanying uncombined form of the same work.
348 |
349 | 8. You may not copy, modify, sublicense, link with, or distribute
350 | the Library except as expressly provided under this License. Any
351 | attempt otherwise to copy, modify, sublicense, link with, or
352 | distribute the Library is void, and will automatically terminate your
353 | rights under this License. However, parties who have received copies,
354 | or rights, from you under this License will not have their licenses
355 | terminated so long as such parties remain in full compliance.
356 |
357 | 9. You are not required to accept this License, since you have not
358 | signed it. However, nothing else grants you permission to modify or
359 | distribute the Library or its derivative works. These actions are
360 | prohibited by law if you do not accept this License. Therefore, by
361 | modifying or distributing the Library (or any work based on the
362 | Library), you indicate your acceptance of this License to do so, and
363 | all its terms and conditions for copying, distributing or modifying
364 | the Library or works based on it.
365 |
366 | 10. Each time you redistribute the Library (or any work based on the
367 | Library), the recipient automatically receives a license from the
368 | original licensor to copy, distribute, link with or modify the Library
369 | subject to these terms and conditions. You may not impose any further
370 | restrictions on the recipients' exercise of the rights granted herein.
371 | You are not responsible for enforcing compliance by third parties with
372 | this License.
373 |
374 | 11. If, as a consequence of a court judgment or allegation of patent
375 | infringement or for any other reason (not limited to patent issues),
376 | conditions are imposed on you (whether by court order, agreement or
377 | otherwise) that contradict the conditions of this License, they do not
378 | excuse you from the conditions of this License. If you cannot
379 | distribute so as to satisfy simultaneously your obligations under this
380 | License and any other pertinent obligations, then as a consequence you
381 | may not distribute the Library at all. For example, if a patent
382 | license would not permit royalty-free redistribution of the Library by
383 | all those who receive copies directly or indirectly through you, then
384 | the only way you could satisfy both it and this License would be to
385 | refrain entirely from distribution of the Library.
386 |
387 | If any portion of this section is held invalid or unenforceable under any
388 | particular circumstance, the balance of the section is intended to apply,
389 | and the section as a whole is intended to apply in other circumstances.
390 |
391 | It is not the purpose of this section to induce you to infringe any
392 | patents or other property right claims or to contest validity of any
393 | such claims; this section has the sole purpose of protecting the
394 | integrity of the free software distribution system which is
395 | implemented by public license practices. Many people have made
396 | generous contributions to the wide range of software distributed
397 | through that system in reliance on consistent application of that
398 | system; it is up to the author/donor to decide if he or she is willing
399 | to distribute software through any other system and a licensee cannot
400 | impose that choice.
401 |
402 | This section is intended to make thoroughly clear what is believed to
403 | be a consequence of the rest of this License.
404 |
405 | 12. If the distribution and/or use of the Library is restricted in
406 | certain countries either by patents or by copyrighted interfaces, the
407 | original copyright holder who places the Library under this License may add
408 | an explicit geographical distribution limitation excluding those countries,
409 | so that distribution is permitted only in or among countries not thus
410 | excluded. In such case, this License incorporates the limitation as if
411 | written in the body of this License.
412 |
413 | 13. The Free Software Foundation may publish revised and/or new
414 | versions of the Lesser General Public License from time to time.
415 | Such new versions will be similar in spirit to the present version,
416 | but may differ in detail to address new problems or concerns.
417 |
418 | Each version is given a distinguishing version number. If the Library
419 | specifies a version number of this License which applies to it and
420 | "any later version", you have the option of following the terms and
421 | conditions either of that version or of any later version published by
422 | the Free Software Foundation. If the Library does not specify a
423 | license version number, you may choose any version ever published by
424 | the Free Software Foundation.
425 |
426 | 14. If you wish to incorporate parts of the Library into other free
427 | programs whose distribution conditions are incompatible with these,
428 | write to the author to ask for permission. For software which is
429 | copyrighted by the Free Software Foundation, write to the Free
430 | Software Foundation; we sometimes make exceptions for this. Our
431 | decision will be guided by the two goals of preserving the free status
432 | of all derivatives of our free software and of promoting the sharing
433 | and reuse of software generally.
434 |
435 | NO WARRANTY
436 |
437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
446 |
447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
456 | DAMAGES.
457 |
458 | END OF TERMS AND CONDITIONS
459 |
460 | How to Apply These Terms to Your New Libraries
461 |
462 | If you develop a new library, and you want it to be of the greatest
463 | possible use to the public, we recommend making it free software that
464 | everyone can redistribute and change. You can do so by permitting
465 | redistribution under these terms (or, alternatively, under the terms of the
466 | ordinary General Public License).
467 |
468 | To apply these terms, attach the following notices to the library. It is
469 | safest to attach them to the start of each source file to most effectively
470 | convey the exclusion of warranty; and each file should have at least the
471 | "copyright" line and a pointer to where the full notice is found.
472 |
473 | {description}
474 | Copyright (C) {year} {fullname}
475 |
476 | This library is free software; you can redistribute it and/or
477 | modify it under the terms of the GNU Lesser General Public
478 | License as published by the Free Software Foundation; either
479 | version 2.1 of the License, or (at your option) any later version.
480 |
481 | This library is distributed in the hope that it will be useful,
482 | but WITHOUT ANY WARRANTY; without even the implied warranty of
483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
484 | Lesser General Public License for more details.
485 |
486 | You should have received a copy of the GNU Lesser General Public
487 | License along with this library; if not, write to the Free Software
488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
489 | USA
490 |
491 | Also add information on how to contact you by electronic and paper mail.
492 |
493 | You should also get your employer (if you work as a programmer) or your
494 | school, if any, to sign a "copyright disclaimer" for the library, if
495 | necessary. Here is a sample; alter the names:
496 |
497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the
498 | library `Frob' (a library for tweaking knobs) written by James Random
499 | Hacker.
500 |
501 | {signature of Ty Coon}, 1 April 1990
502 | Ty Coon, President of Vice
503 |
504 | That's all there is to it!
505 |
506 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Arduino-Serial-Controller
2 | Connect arduino to Android with OTG cable. Arduino serial controller helps you to communicate with arduino.
3 |
4 | This project uses usb-serial-for-android driver. Get details from below 2 repository.
5 | https://github.com/mik3y/usb-serial-for-android
6 | https://github.com/andreasb242/usb-serial-for-android
7 |
8 | To compile with USB-Serial driver, you must import below path to your project as external source link.
9 |
10 |
11 | Arduino-Serial-Controller/Android/usbSerialForAndroid/src/main/java
12 |
--------------------------------------------------------------------------------