├── src ├── test │ ├── java │ │ ├── .gitkeep │ │ ├── test │ │ │ └── R.java │ │ └── io │ │ │ └── inventit │ │ │ └── processing │ │ │ └── android │ │ │ └── serial │ │ │ └── UsbSerialCommunicatorTest.java │ └── resources │ │ └── robolectric │ │ ├── res │ │ └── values │ │ │ └── strings.xml │ │ └── AndroidManifest.xml └── main │ ├── resources │ └── .gitkeep │ ├── examples │ └── PulseSensor11574 │ │ ├── res │ │ └── xml │ │ │ └── device_filter.xml │ │ └── AndroidManifest.xml │ ├── java │ └── io │ │ └── inventit │ │ └── processing │ │ └── android │ │ └── serial │ │ ├── Config.java │ │ ├── SerialCommunicatorFacory.java │ │ ├── SerialInputOutputManager.java │ │ ├── Serial.java │ │ ├── UsbSerialCommunicator.java │ │ ├── SerialCommunicator.java │ │ └── AbstractAndroidSerialCommunicator.java │ └── assembly │ └── distribution.xml ├── images └── Galaxy_J_Screenshot.jpg ├── .gitignore ├── libs ├── com │ └── hoho │ │ └── usb-serial-for-android │ │ ├── b96f9ca │ │ ├── usb-serial-for-android-b96f9ca.jar │ │ └── usb-serial-for-android-b96f9ca.pom │ │ └── usb-serial-for-android-template.pom ├── processing │ └── android-core │ │ └── android-mode-0252 │ │ ├── android-core-android-mode-0252.jar │ │ └── android-core-android-mode-0252.pom ├── slf4j-android.license.txt ├── android-core.license.txt └── usb-serial-for-android.license.txt ├── update_libs.sh ├── library.properties ├── pom.xml └── README.md /src/test/java/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/Galaxy_J_Screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventit/processing-android-serial/HEAD/images/Galaxy_J_Screenshot.jpg -------------------------------------------------------------------------------- /src/test/resources/robolectric/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | tmp 3 | .idea 4 | *.iml 5 | libs/com/hoho/usb-serial-for-android/ccc8e8d 6 | libs/com/hoho/usb-serial-for-android/b96f9ca 7 | -------------------------------------------------------------------------------- /libs/com/hoho/usb-serial-for-android/b96f9ca/usb-serial-for-android-b96f9ca.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventit/processing-android-serial/HEAD/libs/com/hoho/usb-serial-for-android/b96f9ca/usb-serial-for-android-b96f9ca.jar -------------------------------------------------------------------------------- /libs/processing/android-core/android-mode-0252/android-core-android-mode-0252.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inventit/processing-android-serial/HEAD/libs/processing/android-core/android-mode-0252/android-core-android-mode-0252.jar -------------------------------------------------------------------------------- /src/test/java/test/R.java: -------------------------------------------------------------------------------- 1 | package test; 2 | /* AUTO-GENERATED FILE. DO NOT MODIFY. 3 | * 4 | * This class was automatically generated by the 5 | * aapt tool from the resource data it found. It 6 | * should not be modified by hand. 7 | */ 8 | 9 | 10 | 11 | public final class R { 12 | public static final class attr { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /libs/processing/android-core/android-mode-0252/android-core-android-mode-0252.pom: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | processing 4 | android-core 5 | android-mode-0252 6 | https://github.com/processing/processing-android 7 | Processing Android Core 8 | 9 | -------------------------------------------------------------------------------- /libs/com/hoho/usb-serial-for-android/b96f9ca/usb-serial-for-android-b96f9ca.pom: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.hoho 4 | usb-serial-for-android 5 | b96f9ca 6 | https://code.google.com/p/usb-serial-for-android/ 7 | GNU Lesser GPL 8 | USB Serial Driver for Android 9 | 10 | -------------------------------------------------------------------------------- /libs/com/hoho/usb-serial-for-android/usb-serial-for-android-template.pom: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.hoho 4 | usb-serial-for-android 5 | %LIB_VERSION% 6 | https://code.google.com/p/usb-serial-for-android/ 7 | GNU Lesser GPL 8 | USB Serial Driver for Android 9 | 10 | -------------------------------------------------------------------------------- /src/test/resources/robolectric/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/examples/PulseSensor11574/res/xml/device_filter.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/main/examples/PulseSensor11574/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/Config.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | /** 7 | * 8 | * @author dbaba@yourinventit.com 9 | * 10 | */ 11 | final class Config { 12 | 13 | private static boolean debugEnabled = false; 14 | 15 | private static long waitOnException = 5000; 16 | 17 | /** 18 | * @return the debugEnabled 19 | */ 20 | public static boolean isDebugEnabled() { 21 | return debugEnabled; 22 | } 23 | 24 | /** 25 | * @param debugEnabled 26 | * the debugEnabled to set 27 | */ 28 | public static void setDebugEnabled(boolean debugEnabled) { 29 | Config.debugEnabled = debugEnabled; 30 | } 31 | 32 | /** 33 | * @return the waitOnException 34 | */ 35 | public static long getWaitOnException() { 36 | return waitOnException; 37 | } 38 | 39 | /** 40 | * @param waitOnException 41 | * the waitOnException to set 42 | */ 43 | public static void setWaitOnException(long waitOnException) { 44 | Config.waitOnException = waitOnException; 45 | } 46 | 47 | private Config() { 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /update_libs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | LIB_VERSION="b96f9ca" 4 | LIB_ZIP_URL="https://github.com/mik3y/usb-serial-for-android/archive/b96f9ca7a25f44e997e1b5cb5746eb8082716168.zip" 5 | LIB_PATH="./libs/com/hoho/usb-serial-for-android" 6 | 7 | # Use android command to install the following dependencies 8 | # Required Tools: 9 | # - Android SDK Build-tools: 19.1 10 | # - Android SDK Build-tools: 22.0.1 11 | # Required SDK Platforms: 12 | # - SDK Platform: 22 13 | # - SDK Platform: 19 14 | 15 | cd ${LIB_PATH} 16 | mkdir ${LIB_VERSION} 17 | cd ${LIB_VERSION} 18 | rm -fr usb-serial-for-android-* 19 | curl -L -o ${LIB_VERSION}.zip ${LIB_ZIP_URL} 20 | unzip ${LIB_VERSION}.zip 21 | cd usb-serial-for-android-* 22 | ./gradlew build 23 | cp -f usbSerialForAndroid/build/outputs/aar/usbSerialForAndroid-release.aar \ 24 | ../usb-serial-for-android-${LIB_VERSION}.aar 25 | cp -f ../../usb-serial-for-android-template.pom ../usb-serial-for-android-${LIB_VERSION}.pom 26 | sed -i -e "s/%LIB_VERSION%/${LIB_VERSION//\//\\/}/g" ../usb-serial-for-android-${LIB_VERSION}.pom 27 | cd .. 28 | jar xf usb-serial-for-android-${LIB_VERSION}.aar classes.jar 29 | mv classes.jar usb-serial-for-android-${LIB_VERSION}.jar 30 | -------------------------------------------------------------------------------- /libs/slf4j-android.license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2004-2013 QOS.ch 2 | All rights reserved. 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/main/assembly/distribution.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | distribution 8 | 9 | 10 | 11 | zip 12 | 13 | 14 | true 15 | 16 | 17 | 18 | README.md 19 | / 20 | false 21 | 22 | 23 | library.properties 24 | / 25 | false 26 | 27 | 28 | target/AndroidSerial.jar 29 | /library 30 | false 31 | 32 | 33 | libs/usb-serial-for-android.license.txt 34 | /library 35 | false 36 | 37 | 38 | libs/slf4j-android.license.txt 39 | /library 40 | false 41 | 42 | 43 | 44 | 45 | false 46 | library 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/SerialCommunicatorFacory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | import android.os.Build; 7 | import processing.core.PApplet; 8 | import processing.data.JSONObject; 9 | 10 | /** 11 | * 12 | * @author dbaba@yourinventit.com 13 | * 14 | */ 15 | public final class SerialCommunicatorFacory { 16 | 17 | /** 18 | * Singleton Instance 19 | */ 20 | private static final SerialCommunicatorFacory INSTANCE = new SerialCommunicatorFacory(); 21 | 22 | static { 23 | verifyVersion(); 24 | } 25 | 26 | /** 27 | * @return the instance 28 | */ 29 | public static SerialCommunicatorFacory getInstance() { 30 | return INSTANCE; 31 | } 32 | 33 | /** 34 | * Suppress instantiation. 35 | */ 36 | private SerialCommunicatorFacory() { 37 | } 38 | 39 | /** 40 | * Configures the serial library. 41 | * 42 | * @param json 43 | */ 44 | public void configure(String json) { 45 | configure(JSONObject.parse(json)); 46 | } 47 | 48 | /** 49 | * Configures the serial library. 50 | * 51 | * @param jsonObject 52 | */ 53 | public void configure(JSONObject jsonObject) { 54 | Config.setDebugEnabled(jsonObject.getBoolean("debug")); 55 | } 56 | 57 | /** 58 | * Returns a {@link SerialCommunicator} instance specified by the type. 59 | * 60 | * @param parent 61 | * @param type 62 | * @return 63 | */ 64 | public SerialCommunicator create(PApplet parent, String type) { 65 | if ("usb".equalsIgnoreCase(type)) { 66 | return new UsbSerialCommunicator(parent); 67 | } else { 68 | throw new UnsupportedOperationException(type + " is not supported."); 69 | } 70 | } 71 | 72 | /** 73 | * Unfortunately, this library uses USB Host API set introduced since 74 | * Android 3.1. 75 | */ 76 | static void verifyVersion() { 77 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) { 78 | throw new UnsupportedOperationException( 79 | "Your device doesn't support USB Host API. Use Android 3.1 or later."); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | # UTF-8 supported. 2 | 3 | # The name of your library as you want it formatted 4 | name = Android Serial Library for Processing 5 | 6 | # List of authors. Links can be provided using the syntax [author name](url) 7 | authorList = [Daisuke Baba](https://github.com/dbaba) 8 | 9 | # A web page for your library, NOT a direct link to where to download it 10 | url = https://github.com/inventit/processing-android-serial 11 | 12 | # The category of your library, must be one (or many) of the following: 13 | # "3D" "Animation" "Compilations" "Data" 14 | # "Fabrication" "Geometry" "GUI" "Hardware" 15 | # "I/O" "Language" "Math" "Simulation" 16 | # "Sound" "Utilities" "Typography" "Video & Vision" 17 | # 18 | # If a value other than those listed is used, your library will listed as "Other." 19 | category = I/O 20 | 21 | # A short sentence (or fragment) to summarize the library's function. This will be 22 | # shown from inside the PDE when the library is being installed. Avoid repeating 23 | # the name of your library here. Also, avoid saying anything redundant like 24 | # mentioning that its a library. This should start with a capitalized letter, and 25 | # end with a period. 26 | sentence = Android Serial Library 27 | 28 | # Additional information suitable for the Processing website. The value of 29 | # 'sentence' always will be prepended, so you should start by writing the 30 | # second sentence here. If your library only works on certain operating systems, 31 | # mention it here. 32 | paragraph = This library works on Android 5.0 or later. 33 | 34 | # Links in the 'sentence' and 'paragraph' attributes can be inserted using the 35 | # same syntax as for authors. That is, [here is a link to Processing](http://processing.org/) 36 | 37 | 38 | # A version number that increments once with each release. This 39 | # is used to compare different versions of the same library, and 40 | # check if an update is available. You should think of it as a 41 | # counter, counting the total number of releases you've had. 42 | version = 3 43 | 44 | # The version as the user will see it. If blank, the version attribute will be used here 45 | prettyVersion = 0.2.0 46 | -------------------------------------------------------------------------------- /src/test/java/io/inventit/processing/android/serial/UsbSerialCommunicatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | import static org.junit.Assert.assertNotNull; 8 | import static org.junit.Assert.assertNull; 9 | import static org.mockito.Mockito.mock; 10 | import static org.mockito.Mockito.when; 11 | 12 | import android.app.Activity; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | 17 | import org.robolectric.RobolectricTestRunner; 18 | import org.robolectric.annotation.Config; 19 | 20 | import processing.core.PApplet; 21 | import android.content.Context; 22 | import android.hardware.usb.UsbDevice; 23 | import android.hardware.usb.UsbDeviceConnection; 24 | import android.hardware.usb.UsbManager; 25 | 26 | import com.hoho.android.usbserial.driver.UsbId; 27 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 28 | import com.hoho.android.usbserial.driver.UsbSerialProber; 29 | 30 | import java.util.Collections; 31 | import java.util.HashMap; 32 | 33 | /** 34 | * 35 | * @author dbaba@yourinventit.com 36 | * 37 | */ 38 | @Config(manifest = "src/test/resources/robolectric/AndroidManifest.xml") 39 | @RunWith(RobolectricTestRunner.class) 40 | public class UsbSerialCommunicatorTest { 41 | 42 | private UsbSerialCommunicator communicator; 43 | 44 | private final PApplet pApplet = mock(PApplet.class); 45 | private final Activity activity = mock(Activity.class); 46 | private final Context context = mock(Context.class); 47 | private final UsbDevice usbDevice = mock(UsbDevice.class); 48 | private final UsbManager usbManager = mock(UsbManager.class); 49 | private final UsbDeviceConnection usbDeviceConnection = mock(UsbDeviceConnection.class); 50 | 51 | @Before 52 | public void setUp() throws Exception { 53 | when(pApplet.getActivity()).thenReturn(activity); 54 | when(activity.getApplicationContext()).thenReturn(context); 55 | when(context.getSystemService(Context.USB_SERVICE)).thenReturn( 56 | usbManager); 57 | communicator = new UsbSerialCommunicator(pApplet); 58 | } 59 | 60 | /** 61 | * Regression Test 62 | */ 63 | @Test 64 | public void test_getDevice_ok1() { 65 | when(usbManager.getDeviceList()).thenReturn(new HashMap(Collections.singletonMap("port", usbDevice))); 66 | when(usbDevice.getVendorId()).thenReturn(UsbId.VENDOR_ARDUINO); 67 | when(usbDevice.getProductId()).thenReturn(UsbId.ARDUINO_LEONARDO); 68 | when(usbManager.openDevice(usbDevice)).thenReturn(usbDeviceConnection); 69 | final String[] portNames = communicator.list(); 70 | assertNotNull(portNames); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/SerialInputOutputManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | import android.hardware.usb.UsbRequest; 7 | import android.util.Log; 8 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 9 | import com.hoho.android.usbserial.driver.UsbSerialPort; 10 | 11 | import java.io.IOException; 12 | import java.nio.ByteBuffer; 13 | 14 | /** 15 | * Utility class which services a {@link UsbSerialDriver} in its {@link #run()} 16 | * method. 17 | * 18 | * Applied a patch reported at 19 | * https://code.google.com/p/usb-serial-for-android/issues/detail?id=5 by 20 | * dbaba@yourinventit.com 21 | * 22 | * @author mike wakerly (opensource@hoho.com) 23 | */ 24 | class SerialInputOutputManager implements Runnable { 25 | 26 | private static final String TAG = SerialInputOutputManager.class 27 | .getSimpleName(); 28 | 29 | private static final int READ_WAIT_MILLIS = 200; 30 | private static final int BUFSIZ = 4096; 31 | 32 | private final UsbSerialPort mDriver; 33 | 34 | private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ); 35 | 36 | // Synchronized by 'mWriteBuffer' 37 | private final ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ); 38 | 39 | private enum State { 40 | STOPPED, RUNNING, STOPPING 41 | } 42 | 43 | // Synchronized by 'this' 44 | private State mState = State.STOPPED; 45 | 46 | // Synchronized by 'this' 47 | private Listener mListener; 48 | 49 | public interface Listener { 50 | /** 51 | * Called when new incoming data is available. 52 | */ 53 | public void onNewData(byte[] data); 54 | 55 | /** 56 | * Called when {@link SerialInputOutputManager#run()} aborts due to an 57 | * error. 58 | * @return true if transition to stop state 59 | */ 60 | public boolean onRunError(Exception e); 61 | } 62 | 63 | /** 64 | * Creates a new instance with no listener. 65 | */ 66 | public SerialInputOutputManager(UsbSerialPort driver) { 67 | this(driver, null); 68 | } 69 | 70 | /** 71 | * Creates a new instance with the provided listener. 72 | */ 73 | public SerialInputOutputManager(UsbSerialPort driver, Listener listener) { 74 | mDriver = driver; 75 | mListener = listener; 76 | } 77 | 78 | public synchronized void setListener(Listener listener) { 79 | mListener = listener; 80 | } 81 | 82 | public synchronized Listener getListener() { 83 | return mListener; 84 | } 85 | 86 | public void writeAsync(byte[] data) { 87 | synchronized (mWriteBuffer) { 88 | mWriteBuffer.put(data); 89 | } 90 | } 91 | 92 | public synchronized void stop() { 93 | if (getState() == State.RUNNING) { 94 | Log.i(TAG, "Stop requested"); 95 | mState = State.STOPPING; 96 | } 97 | } 98 | 99 | private synchronized State getState() { 100 | return mState; 101 | } 102 | 103 | /** 104 | * Continuously services the read and write buffers until {@link #stop()} is 105 | * called, or until a driver exception is raised. 106 | * 107 | * NOTE(mikey): Uses inefficient read/write-with-timeout. TODO(mikey): Read 108 | * asynchronously with {@link UsbRequest#queue(ByteBuffer, int)} 109 | */ 110 | public void run() { 111 | synchronized (this) { 112 | if (getState() != State.STOPPED) { 113 | throw new IllegalStateException("Already running."); 114 | } 115 | mState = State.RUNNING; 116 | } 117 | 118 | Log.i(TAG, "Running .."); 119 | while (true) { 120 | try { 121 | if (getState() != State.RUNNING) { 122 | Log.i(TAG, "Stopping mState=" + getState()); 123 | break; 124 | } 125 | step(); 126 | } catch (Exception e) { 127 | Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e); 128 | final Listener listener = getListener(); 129 | if (listener != null) { 130 | if (listener.onRunError(e) == false) { 131 | continue; 132 | } 133 | } 134 | break; 135 | } 136 | } 137 | synchronized (this) { 138 | mState = State.STOPPED; 139 | Log.i(TAG, "Stopped."); 140 | } 141 | } 142 | 143 | private void step() throws IOException { 144 | // Handle incoming data. 145 | int len = mDriver.read(mReadBuffer.array(), READ_WAIT_MILLIS); 146 | if (len > 0) { 147 | if (Config.isDebugEnabled()) { 148 | Log.d(TAG, "Read data len=" + len); 149 | } 150 | final Listener listener = getListener(); 151 | if (listener != null) { 152 | final byte[] data = new byte[len]; 153 | mReadBuffer.get(data, 0, len); 154 | listener.onNewData(data); 155 | } 156 | mReadBuffer.clear(); 157 | } 158 | 159 | // Handle outgoing data. 160 | byte[] outBuff = null; 161 | synchronized (mWriteBuffer) { 162 | if (mWriteBuffer.position() > 0) { 163 | len = mWriteBuffer.position(); 164 | outBuff = new byte[len]; 165 | mWriteBuffer.rewind(); 166 | mWriteBuffer.get(outBuff, 0, len); 167 | mWriteBuffer.clear(); 168 | } 169 | } 170 | if (outBuff != null) { 171 | if (Config.isDebugEnabled()) { 172 | Log.d(TAG, "Writing data len=" + len); 173 | } 174 | mDriver.write(outBuff, READ_WAIT_MILLIS); 175 | } 176 | } 177 | 178 | } 179 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | io.inventit.processing.android.serial 6 | processing-android-serial 7 | 0.2.0 8 | AndroidSerial 9 | 10 | Inventit Inc. 11 | http://www.yourinventit.com/ 12 | 13 | https://github.com/inventit/processing-android-serial 14 | 15 | scm:git:git@github.com:inventit/processing-android-serial.git 16 | git@github.com:inventit/processing-android-serial.git 17 | scm:git:git@github.com:inventit/processing-android-serial.git 18 | 19 | jar 20 | 21 | 22 | false 23 | SharedLibrariesRepository 24 | Shared Libraries Repository 25 | file://${basedir}/target 26 | default 27 | 28 | 29 | 30 | 31 | ProjectLocalLibrariesRepository 32 | Project Local Libraries Repository 33 | file://${basedir}/libs 34 | default 35 | 36 | 37 | 38 | 39 | processing 40 | android-core 41 | android-mode-0252 42 | provided 43 | 44 | 45 | com.google.android 46 | android 47 | 4.0.1.2 48 | provided 49 | 50 | 51 | commons-logging 52 | commons-logging 53 | 54 | 55 | httpclient 56 | org.apache.httpcomponents 57 | 58 | 59 | json 60 | org.json 61 | 62 | 63 | 64 | 65 | org.slf4j 66 | slf4j-android 67 | 1.6.1-RC1 68 | compile 69 | 70 | 71 | com.hoho 72 | usb-serial-for-android 73 | b96f9ca 74 | compile 75 | 76 | 77 | org.json 78 | json 79 | 20090211 80 | provided 81 | 82 | 83 | org.robolectric 84 | robolectric 85 | 3.0 86 | test 87 | 88 | 89 | org.mockito 90 | mockito-core 91 | 1.9.5 92 | test 93 | 94 | 95 | org.apache.httpcomponents 96 | httpclient 97 | 4.2.5 98 | test 99 | 100 | 101 | junit 102 | junit 103 | 4.8.2 104 | test 105 | 106 | 107 | 108 | AndroidSerial 109 | 110 | 111 | maven-jar-plugin 112 | 113 | 114 | false 115 | 116 | 117 | 118 | 119 | maven-compiler-plugin 120 | 2.3.2 121 | 122 | UTF-8 123 | 1.5 124 | 1.5 125 | 126 | 127 | 128 | org.codehaus.mojo 129 | buildnumber-maven-plugin 130 | 1.0-beta-4 131 | 132 | 133 | none 134 | 135 | 136 | 137 | 138 | org.apache.maven.plugins 139 | maven-source-plugin 140 | 2.1.2 141 | 142 | 143 | compile 144 | 145 | jar 146 | 147 | 148 | 149 | 150 | 151 | org.apache.maven.plugins 152 | maven-javadoc-plugin 153 | 2.8.1 154 | 155 | -Xdoclint:none 156 | 157 | 158 | 159 | package 160 | 161 | jar 162 | 163 | 164 | 165 | 166 | 167 | maven-assembly-plugin 168 | 2.4 169 | 170 | 171 | src/main/assembly/distribution.xml 172 | 173 | 174 | 175 | 176 | make-assembly 177 | package 178 | 179 | single 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/Serial.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | import processing.core.PApplet; 7 | 8 | /** 9 | * This class is used for retaining the compatibility with 10 | * processing.serial.Serial class. 11 | * 12 | * The difference between processing.serial.Serial is the static method 13 | * `list()`, where this class takes a {@link PApplet} instance as a parameter 14 | * whereas processing.serial.Serial doesn't. 15 | * 16 | * @author dbaba@yourinventit.com 17 | * 18 | */ 19 | public class Serial { 20 | 21 | private static final String DEFAULT_TYPE = "usb"; 22 | 23 | /** 24 | * The delegate object 25 | */ 26 | private final SerialCommunicator delegate; 27 | 28 | /** 29 | * Non public constructor 30 | */ 31 | protected Serial() { 32 | this.delegate = null; 33 | } 34 | 35 | /** 36 | * 37 | * @param type 38 | * @param parent 39 | */ 40 | public Serial(String type, PApplet parent) { 41 | this.delegate = SerialCommunicatorFacory.getInstance().create(parent, 42 | type); 43 | } 44 | 45 | /** 46 | * 47 | * @param parent 48 | */ 49 | public Serial(PApplet parent) { 50 | this(DEFAULT_TYPE, parent); 51 | this.delegate.start(null); 52 | } 53 | 54 | /** 55 | * 56 | * @param parent 57 | * @param portIdentifier 58 | */ 59 | public Serial(PApplet parent, String portIdentifier) { 60 | this(DEFAULT_TYPE, parent); 61 | this.delegate.start(portIdentifier); 62 | } 63 | 64 | /** 65 | * 66 | * @param parent 67 | * @param portIdentifier 68 | * @param baudrate 69 | */ 70 | public Serial(PApplet parent, String portIdentifier, int baudrate) { 71 | this(DEFAULT_TYPE, parent); 72 | this.delegate.start(portIdentifier, baudrate); 73 | } 74 | 75 | /** 76 | * 77 | * @param parent 78 | * @param portIdentifier 79 | * @param baudrate 80 | * @param parity 81 | * @param dataBits 82 | * @param stopBits 83 | */ 84 | public Serial(PApplet parent, String portIdentifier, int baudrate, 85 | char parity, int dataBits, float stopBits) { 86 | this(DEFAULT_TYPE, parent); 87 | this.delegate.start(portIdentifier, baudrate, parity, dataBits, 88 | stopBits); 89 | } 90 | 91 | /** 92 | * @param portIdentifier 93 | * @see SerialCommunicator#start(java.lang.String) 94 | */ 95 | public void start(String portIdentifier) { 96 | delegate.start(portIdentifier); 97 | } 98 | 99 | /** 100 | * @param portIdentifier 101 | * @param baudrate 102 | * @see SerialCommunicator#start(java.lang.String, 103 | * int) 104 | */ 105 | public void start(String portIdentifier, int baudrate) { 106 | delegate.start(portIdentifier, baudrate); 107 | } 108 | 109 | /** 110 | * @param portIdentifier 111 | * @param baudrate 112 | * @param parity 113 | * @param dataBits 114 | * @param stopBits 115 | * @see SerialCommunicator#start(java.lang.String, 116 | * int, char, int, float) 117 | */ 118 | public void start(String portIdentifier, int baudrate, char parity, 119 | int dataBits, float stopBits) { 120 | delegate.start(portIdentifier, baudrate, parity, dataBits, stopBits); 121 | } 122 | 123 | /** 124 | * 125 | * @see SerialCommunicator#stop() 126 | */ 127 | public void stop() { 128 | delegate.stop(); 129 | } 130 | 131 | /** 132 | * @param count 133 | * @see SerialCommunicator#buffer(int) 134 | */ 135 | public void buffer(int count) { 136 | delegate.buffer(count); 137 | } 138 | 139 | /** 140 | * @param what 141 | * @see SerialCommunicator#bufferUntil(int) 142 | */ 143 | public void bufferUntil(int what) { 144 | delegate.bufferUntil(what); 145 | } 146 | 147 | /** 148 | * @return 149 | * @see SerialCommunicator#available() 150 | */ 151 | public int available() { 152 | return delegate.available(); 153 | } 154 | 155 | /** 156 | * 157 | * @see SerialCommunicator#clear() 158 | */ 159 | public void clear() { 160 | delegate.clear(); 161 | } 162 | 163 | /** 164 | * @return 165 | * @see SerialCommunicator#read() 166 | */ 167 | public int read() { 168 | return delegate.read(); 169 | } 170 | 171 | public char readChar() { 172 | return delegate.readChar(); 173 | } 174 | 175 | public int last() { 176 | return delegate.last(); 177 | } 178 | 179 | public char lastChar() { 180 | return delegate.lastChar(); 181 | } 182 | 183 | /** 184 | * @return 185 | * @see SerialCommunicator#readBytes() 186 | */ 187 | public byte[] readBytes() { 188 | return delegate.readBytes(); 189 | } 190 | 191 | /** 192 | * @param byteBuffer 193 | * @return 194 | * @see SerialCommunicator#readBytes(byte[]) 195 | */ 196 | public int readBytes(byte[] byteBuffer) { 197 | return delegate.readBytes(byteBuffer); 198 | } 199 | 200 | /** 201 | * @param interesting 202 | * @return 203 | * @see SerialCommunicator#readBytesUntil(int) 204 | */ 205 | public byte[] readBytesUntil(int interesting) { 206 | return delegate.readBytesUntil(interesting); 207 | } 208 | 209 | /** 210 | * @param interesting 211 | * @param byteBuffer 212 | * @return 213 | * @see SerialCommunicator#readBytesUntil(int, 214 | * byte[]) 215 | */ 216 | public int readBytesUntil(int interesting, byte[] byteBuffer) { 217 | return delegate.readBytesUntil(interesting, byteBuffer); 218 | } 219 | 220 | /** 221 | * @return 222 | * @see SerialCommunicator#readString() 223 | */ 224 | public String readString() { 225 | return delegate.readString(); 226 | } 227 | 228 | /** 229 | * @param interesting 230 | * @return 231 | * @see SerialCommunicator#readStringUntil(int) 232 | */ 233 | public String readStringUntil(int interesting) { 234 | return delegate.readStringUntil(interesting); 235 | } 236 | 237 | /** 238 | * @param what 239 | * @see SerialCommunicator#write(int) 240 | */ 241 | public void write(int what) { 242 | delegate.write(what); 243 | } 244 | 245 | /** 246 | * @param what 247 | * @see SerialCommunicator#write(byte[]) 248 | */ 249 | public void write(byte[] what) { 250 | delegate.write(what); 251 | } 252 | 253 | /** 254 | * @param what 255 | * @see SerialCommunicator#write(java.lang.String) 256 | */ 257 | public void write(String what) { 258 | delegate.write(what); 259 | } 260 | 261 | /** 262 | * @return 263 | * @see SerialCommunicator#list() 264 | */ 265 | public String[] list() { 266 | return delegate.list(); 267 | } 268 | 269 | /** 270 | * 271 | * @param parent 272 | * @return 273 | */ 274 | public static String[] list(PApplet parent) { 275 | final Serial serial = new Serial(parent); 276 | try { 277 | return serial.list(); 278 | } finally { 279 | serial.stop(); 280 | } 281 | } 282 | 283 | } 284 | -------------------------------------------------------------------------------- /libs/android-core.license.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. -------------------------------------------------------------------------------- /libs/usb-serial-for-android.license.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AndroidSerial for Processing 2 | 3 | [![GitHub release](https://img.shields.io/github/release/inventit/processing-android-serial.svg)](https://github.com/inventit/processing-android-serial/releases/latest) 4 | [![master Build Status](https://travis-ci.org/inventit/processing-android-serial.svg?branch=master)](https://travis-ci.org/inventit/processing-android-serial/) 5 | [![License MIT](https://img.shields.io/github/license/inventit/processing-android-serial.svg)](http://opensource.org/licenses/MIT) 6 | 7 | This is a Processing-for-Android library offering the serial communication. 8 | 9 | This library works on Android 5.0 or later since it uses Android USB Host API. 10 | 11 | This library also includes [usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) containing FTDI serial driver and USB CDC/ACM serial driver working on Android. Since the project creates only AAR file by default, there is a shell script, `update_libs.sh`, to extract a jar file from the built AAR file. Use the script when you require the other revision of the project binary. 12 | 13 | Note that this version is alpha release. 14 | 15 | ## How to use 16 | 17 | Build the source code (see below) or download a binary from [the release page](https://github.com/inventit/processing-android-serial/releases). 18 | 19 | Unzip `AndroidSerial-distribution.zip` and copy all files including `AndroidSerial` directory to your `libraries` folder (e.g. `~/Documents/Processing/libraries`). 20 | 21 | If you already install the older version of `AndroidSerial` library, remove it prior to copying the new one. 22 | 23 | The usage of the library is almost same as [processing.serial.Serial](http://processing.org/reference/libraries/serial/Serial.html) library. 24 | 25 | The difference between processing.serial.Serial and this is a static method `list()`. 26 | 27 | The following code does NOT work on the AndroidSerial library. 28 | 29 | println(Serial.list()); // processing.serial library 30 | 31 | But this does work, 32 | 33 | println(Serial.list(this)); 34 | 35 | Other methods in processing.serial.Serial class should work without any changes. 36 | 37 | ## Example 38 | 39 | You can get a working example from the [sparkfun's pulse sensor SEN-11574](https://www.sparkfun.com/products/11574). 40 | 41 | 1. Install Android SDK Platform 23 or higher as well as Android SDK Tools and Android SDK Platform-tools or later (I tried Android SDK Platform 23/24, SDK Platform Tools 24.0.3, SDK Tools 25.2.2, and Processing 3.2.1) 42 | 1. Install Android mode on your Processing environment 43 | 1. Install this library (Unzip `AndroidSerial-distribution.zip` and copy all files including `AndroidSerial` directory to your `libraries` folder (e.g. `~/Documents/Processing/libraries`)) 44 | 1. Go to the [page](https://www.sparkfun.com/products/11574) 45 | 1. Download the Processing sketch from `Documents` section 46 | 1. Open the downloaded Processing sketch (not Arduino) 47 | 1. On the Processing IDE, choose `Sketch` -> `Import Library` -> `Android Serial Library for Processing` (This will insert `import io.inventit.processing.android.serial.*;`) 48 | 1. Modify the code as below (see [here](https://github.com/WorldFamousElectronics/PulseSensor_Amped_Processing_Visualizer/blob/pr/1/PulseSensorAmpd_Processing_1dot1/PulseSensorAmpd_Processing_1dot1.pde) for the source code available at the sparkfun site) 49 | 50 | L9: // import processing.serial.*; // comment out 51 | L57: println(Serial.list()); // print a list of available serial ports 52 | | (add `this`) 53 | v 54 | L57: println(Serial.list(this)); // print a list of available serial ports 55 | 56 | L61: port = new Serial(this, Serial.list()[0], 115200); // make sure Arduino is talking serial at this baud rate 57 | | (add `this`) 58 | v 59 | L61: port = new Serial(this, Serial.list(this)[0], 115200); // make sure Arduino is talking serial at this baud rate 60 | 61 | 1. Please make sure that you need to check and modify the index of `Serial.list(this)` at the line 62 in order to specify the valid port name 62 | 1. Create `res/xml` directories under the opened sketch directory (e.g. `~/Documents/Processing/PulseSensorAmpd_Processing_1dot1`) 63 | 1. Copy `examples/PulseSensor11574/res/xml/device_fileter.xml` to the created directory (e.g. `~/Documents/Processing/PulseSensorAmpd_Processing_1dot1/res/xml`) 64 | 1. Copy `examples/PulseSensor11574/AndroidManifest.xml` to the opened sketch directory (e.g. `~/Documents/Processing/PulseSensorAmpd_Processing_1dot1`) 65 | 1. Connect your Android device to your computer and Run the code 66 | 1. The application may report `Unexpected error` on your Android screen but you can ignore it (tap `OK`) 67 | 1. Disconnect the Android device from the computer and connect your FTDI device or Arduino to the Android device with USB cable 68 | 1. Android asks you to choose an application to launch, then choose your application (e.g. `PulseSensorAmpd_Processing_1dot1`) 69 | 1. Finally, you will see the same screen as your computer! 70 | 71 | ** Screenshot on Galaxy J ** 72 | 73 | ![Galaxy J Screenshot](images/Galaxy_J_Screenshot.jpg) 74 | 75 | ## How to build 76 | 77 | You can build the project source code though you can download the built binary from [our SourceForge project page](https://sourceforge.net/projects/procandser/). 78 | 79 | Prior to building the project, you need to install the following software: 80 | 81 | 1. JDK 6+ (Any JDK will be available) 82 | 1. [Apache Maven](http://maven.apache.org/) (Choose the latest one if possible) 83 | 1. [Gradle](https://gradle.org) is required if you run `update_libs.sh`, which downloads and builds the other revision of `usb-serial-for-android` source code than `b96f9ca` 84 | 85 | Then run the following command under the root of the project: 86 | 87 | mvn clean deploy 88 | 89 | And you can find the artifact file named `AndroidSerial-distribution.zip` at `target` directory. 90 | 91 | ## Directory Structure 92 | The directory structure of this application is as follows: 93 | 94 | |-- images 95 | |-- libs 96 | | |-- processing 97 | | | `-- android-core 98 | | | `-- android-mode-0252 99 | | `-- com 100 | | `-- hoho 101 | | `-- usb-serial-for-android 102 | | `-- b96f9ca 103 | |-- src 104 | | |-- main 105 | | | |-- assembly 106 | | | |-- examples 107 | | | | `-- PulseSensor11574 (X) 108 | | | | | `-- res 109 | | | | | `-- xml 110 | | | |-- java 111 | | | `-- resources 112 | | `-- test 113 | | |-- java 114 | | `-- resources 115 | 116 | (X) is a working example for Sparkfun's Pulse Sensor SEN-11574 117 | 118 | ## Source Code License 119 | 120 | All program source codes are available under the MIT style License. 121 | 122 | Copyright (c) 2016 Inventit Inc. 123 | 124 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 125 | 126 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 127 | 128 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 129 | 130 | ## Dependencies 131 | 132 | * [usb-serial-for-android](https://code.google.com/p/usb-serial-for-android/) ... LGPL, USB serial driver for Android 133 | * [Processing Core](http://wiki.processing.org/w/FAQ#Is_Processing_Open_Source.3F_How_.27bout_some_code.3F) ... LGPL, Processing core library 134 | * [Android](http://source.android.com/source/licenses.html) ... ASL 2.0, Android API Library 135 | * [SLFJ Android](http://www.slf4j.org/android/) ... MIT, Logging framework 136 | * [Robolectric](https://github.com/robolectric/robolectric/) ... Android testing library (TEST USE ONLY) 137 | * [Mockito](https://code.google.com/p/mockito/) ... Mock testing library (TEST USE ONLY) 138 | 139 | ## Change History 140 | 141 | 0.2.0 : September 23, 2016 142 | 143 | * Rename package to `io.inventit.processing.android.serial` 144 | * Processing 3.2 support 145 | * Use the latest version of [usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) 146 | * Android Mode 0252 support 147 | 148 | 0.1.0-alpha : February 29, 2016 149 | 150 | * Processing 3 support and Processing 2 is no longer supported 151 | 152 | 0.0.2-alpha : June 20, 2013 153 | 154 | * Fixes an [issue](https://github.com/inventit/processing-android-serial/issues/1) where [Arduino Due](http://arduino.cc/en/Main/arduinoBoardDue) cannot be detected by [usb-serial-for-android](https://code.google.com/p/usb-serial-for-android/) library. Now all Arduino devices are accepted (but not sure they all work properly. [Give us your feedback](https://github.com/inventit/processing-android-serial/issues)) 155 | * Adds unit testing libraries, [Robolectric](https://github.com/robolectric/robolectric/) and [Mockito](https://code.google.com/p/mockito/) 156 | * The release binary has been moved to [our SourceForge project page](https://sourceforge.net/projects/procandser/) 157 | 158 | 0.0.1-alpha : June 10, 2013 159 | 160 | * Initial 161 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/UsbSerialCommunicator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | import android.app.AlertDialog; 7 | import android.content.Context; 8 | import android.content.DialogInterface; 9 | import android.hardware.usb.UsbDevice; 10 | import android.hardware.usb.UsbDeviceConnection; 11 | import android.hardware.usb.UsbManager; 12 | import com.hoho.android.usbserial.driver.UsbSerialDriver; 13 | import com.hoho.android.usbserial.driver.UsbSerialPort; 14 | import com.hoho.android.usbserial.driver.UsbSerialProber; 15 | import io.inventit.processing.android.serial.SerialInputOutputManager.Listener; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import processing.core.PApplet; 19 | 20 | import java.io.IOException; 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | import java.util.concurrent.ExecutorService; 24 | import java.util.concurrent.Executors; 25 | 26 | /** 27 | * Serial class implementation with USB serial. 28 | * 29 | * @author dbaba@yourinventit.com 30 | * 31 | */ 32 | class UsbSerialCommunicator extends AbstractAndroidSerialCommunicator implements 33 | Listener { 34 | 35 | /** 36 | * {@link Logger} 37 | */ 38 | private static final Logger LOGGER = LoggerFactory 39 | .getLogger(UsbSerialCommunicator.class); 40 | 41 | /** 42 | * {@link UsbManager} 43 | */ 44 | private final UsbManager usbManager; 45 | 46 | /** 47 | * {@link UsbSerialPort} 48 | */ 49 | private UsbSerialPort usbSerialDriver; 50 | 51 | /** 52 | * {@link UsbDeviceConnection} 53 | */ 54 | private UsbDeviceConnection usbDeviceConnection; 55 | 56 | /** 57 | * {@link ExecutorService} 58 | */ 59 | private final ExecutorService serialInputOutputExecutor = Executors 60 | .newSingleThreadExecutor(); 61 | 62 | /** 63 | * {@link SerialInputOutputManager} 64 | */ 65 | private SerialInputOutputManager serialInputOutputManager; 66 | 67 | /** 68 | * @param parent 69 | */ 70 | public UsbSerialCommunicator(PApplet parent) { 71 | super(parent); 72 | this.usbManager = (UsbManager) getApplicatoinContext() 73 | .getSystemService(Context.USB_SERVICE); 74 | } 75 | 76 | /** 77 | * 78 | * @param deviceName 79 | * @return 80 | */ 81 | protected UsbSerialDriver findUsbSerialDriver(String deviceName) { 82 | if (deviceName == null || deviceName.length() == 0) { 83 | final List drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager); 84 | if (drivers == null || drivers.isEmpty()) { 85 | return null; 86 | } 87 | return drivers.get(0); 88 | } 89 | for (final UsbDevice usbDevice : usbManager.getDeviceList() 90 | .values()) { 91 | final UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(usbDevice); 92 | if (driver != null 93 | && deviceName 94 | .equals(driver.getDevice().getDeviceName())) { 95 | return driver; 96 | } 97 | } 98 | return null; 99 | } 100 | 101 | /** 102 | * {@inheritDoc} 103 | * 104 | * @see AbstractAndroidSerialCommunicator#doStart(java.lang.String, 105 | * int, char, int, float) 106 | */ 107 | @Override 108 | protected void doStart(final String portIdentifier, int baudrate, char parity, 109 | int dataBits, float stopBits) { 110 | // TODO Supporting parity, dataBits and stopBits parameters. v101 doesn't support them. 111 | LOGGER.info("parity, dataBits and stopBits are not supported yet."); 112 | if (inquireUsbSerialDriver(portIdentifier, baudrate) == false) { 113 | // failed to start 114 | LOGGER.error("Failed to start as this app failed to retrieve a serial driver: port={}", portIdentifier); 115 | final boolean[] waiting = { true }; 116 | getParent().getActivity().runOnUiThread(new Runnable() { 117 | public void run() { 118 | new AlertDialog.Builder(getParent().getActivity()) 119 | .setTitle("Processing-Android USB Serial ERROR") 120 | .setMessage("Port: " + portIdentifier + "\n" + 121 | "Check the following items:\n" + 122 | "1. Make sure AndroidManifest.xml contains tag for android.hardware.usb.host\n" + 123 | "2. USB Serial is connected to the device\n") 124 | .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 125 | public void onClick(DialogInterface dialog, int which) { 126 | waiting[0] = false; 127 | } 128 | }) 129 | .setIcon(android.R.drawable.ic_dialog_alert) 130 | .show(); 131 | } 132 | }); 133 | while (waiting[0]) { 134 | try { 135 | Thread.sleep(100); 136 | } catch (InterruptedException ignored) { 137 | } 138 | } 139 | getParent().getActivity().finish(); 140 | } 141 | } 142 | 143 | /** 144 | * Inquires a USB serial driver and returns if any driver is detected. 145 | * 146 | * @param deviceName null for wildcard 147 | * @return true if a USB serial driver is found and is ready. 148 | */ 149 | protected boolean inquireUsbSerialDriver(String deviceName, int baudRate) { 150 | if (this.usbSerialDriver != null) { 151 | return true; 152 | } 153 | UsbSerialDriver usbSerialDriver = findUsbSerialDriver(deviceName); 154 | try { 155 | stopSerialInputOutputManager(); 156 | if (usbSerialDriver != null) { 157 | this.usbDeviceConnection = this.usbManager.openDevice(usbSerialDriver.getDevice()); 158 | final UsbSerialPort port = usbSerialDriver.getPorts().get(0); 159 | port.open(this.usbDeviceConnection); 160 | port.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); 161 | } 162 | 163 | } catch (IOException exception) { 164 | usbSerialDriver = null; 165 | 166 | } finally { 167 | if (usbSerialDriver != null) { 168 | this.usbSerialDriver = usbSerialDriver.getPorts().get(0); 169 | } 170 | startSerialInputOutputManager(); 171 | } 172 | return usbSerialDriver != null; 173 | } 174 | 175 | /** 176 | * setup {@link SerialInputOutputManager} 177 | */ 178 | private void startSerialInputOutputManager() { 179 | if (usbSerialDriver != null) { 180 | serialInputOutputManager = new SerialInputOutputManager( 181 | usbSerialDriver); 182 | serialInputOutputManager.setListener(this); 183 | // Serial I/O is performed in another thread. 184 | serialInputOutputExecutor.submit(serialInputOutputManager); 185 | } 186 | } 187 | 188 | /** 189 | * {@link SerialInputOutputManager#stop()} 190 | */ 191 | private void stopSerialInputOutputManager() { 192 | if (serialInputOutputManager != null) { 193 | serialInputOutputManager.stop(); 194 | serialInputOutputManager = null; 195 | } 196 | } 197 | 198 | /** 199 | * @return the serialInputOutputManager 200 | */ 201 | protected SerialInputOutputManager getSerialInputOutputManager() { 202 | if (serialInputOutputManager == null) { 203 | throw new IllegalStateException( 204 | "The serial connection is already closed."); 205 | } 206 | return serialInputOutputManager; 207 | } 208 | 209 | /** 210 | * {@inheritDoc} 211 | * 212 | * @see AbstractAndroidSerialCommunicator#doStop() 213 | */ 214 | @Override 215 | protected void doStop() { 216 | stopSerialInputOutputManager(); 217 | if (usbSerialDriver != null) { 218 | try { 219 | usbDeviceConnection.close(); 220 | } finally { 221 | usbSerialDriver = null; 222 | usbDeviceConnection = null; 223 | } 224 | } 225 | } 226 | 227 | /** 228 | * {@inheritDoc} 229 | * 230 | * @see SerialInputOutputManager.Listener#onNewData(byte[]) 231 | */ 232 | public void onNewData(byte[] data) { 233 | sendBuffer(data); 234 | } 235 | 236 | /** 237 | * {@inheritDoc} 238 | * 239 | * @see SerialInputOutputManager.Listener#onRunError(java.lang.Exception) 240 | */ 241 | public boolean onRunError(Exception e) { 242 | if (e instanceof IOException) { 243 | final String message = e.getMessage(); 244 | if (message != null && 245 | (message.indexOf("Error queueing request.") >= 0 || message.indexOf("Null response") >= 0)) { 246 | LOGGER.warn("USB read error: [{}]", message); 247 | try { 248 | Thread.sleep(10); 249 | } catch (InterruptedException ignored) { 250 | } 251 | return false; // continue 252 | } 253 | } 254 | LOGGER.warn("Exception detected. Restart SerialInputOutputManager.", e); 255 | doStop(); 256 | try { 257 | Thread.sleep(Config.getWaitOnException()); 258 | } catch (InterruptedException ignored) { 259 | } 260 | doStart(getPortIdentifier(), getBaudrate(), getParity(), getDataBits(), 261 | getStopBits()); 262 | return true; // stop 263 | } 264 | 265 | /** 266 | * {@inheritDoc} 267 | * 268 | * @see SerialCommunicator#list() 269 | */ 270 | @Override 271 | public String[] list() { 272 | final List names = new ArrayList(); 273 | for (final UsbDevice usbDevice : usbManager.getDeviceList() 274 | .values()) { 275 | final UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(usbDevice); 276 | if (driver != null) { 277 | names.add(driver.getDevice().getDeviceName()); 278 | } 279 | } 280 | return names.toArray(new String[names.size()]); 281 | } 282 | 283 | /** 284 | * {@inheritDoc} 285 | * 286 | * @see SerialCommunicator#write(byte[]) 287 | */ 288 | @Override 289 | public void write(byte[] what) { 290 | getSerialInputOutputManager().writeAsync(what); 291 | } 292 | 293 | /** 294 | * {@inheritDoc} 295 | * 296 | * @see SerialCommunicator#write(int) 297 | */ 298 | @Override 299 | public void write(int what) { 300 | write(new byte[] { (byte) what }); 301 | } 302 | 303 | /** 304 | * {@inheritDoc} 305 | * 306 | * @see SerialCommunicator#write(java.lang.String) 307 | */ 308 | @Override 309 | public void write(String what) { 310 | write(what.getBytes()); 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/SerialCommunicator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | /** 7 | * This interface represents a serial port and encapsulates its implementation. 8 | * 9 | * The declared methods are almost same as Serial class from 10 | * Processing API. 11 | * 12 | * In order to instantiate this class, you must invoke 13 | * {@link SerialCommunicatorFacory#create(processing.core.PApplet, String)}. 14 | * 15 | * Use {@link SerialCommunicator#start(String, int, char, int, float)} to set 16 | * a port identifier, baurdrate, etc. 17 | * 18 | * You can get a list of available port identifiers by {@link SerialCommunicator#list()}. 19 | * 20 | * @author dbaba@yourinventit.com 21 | * 22 | */ 23 | public interface SerialCommunicator { 24 | 25 | /** 26 | * Starts the serial communication. 27 | * 28 | * From Serial 31 | * 32 | * @param portIdentifier 33 | * name of the port 34 | */ 35 | void start(String portIdentifier); 36 | 37 | /** 38 | * Starts the serial communication. 39 | * 40 | * From Serial 43 | * 44 | * @param portIdentifier 45 | * name of the port 46 | * @param baudrate 47 | * 9600 is the default 48 | */ 49 | void start(String portIdentifier, int baudrate); 50 | 51 | /** 52 | * Starts the serial communication. This method will be invoked automatically by the constructor. 53 | * 54 | * From Serial 57 | * 58 | * @param portIdentifier 59 | * name of the port 60 | * @param baudrate 61 | * 9600 is the default 62 | * @param parity 63 | * 'N' for none, 'E' for even, 'O' for odd ('N' is the default) 64 | * @param dataBits 65 | * 8 is the default 66 | * @param stopBits 67 | * 1.0, 1.5, or 2.0 (1.0 is the default) 68 | */ 69 | void start(String portIdentifier, int baudrate, char parity, int dataBits, 70 | float stopBits); 71 | 72 | /** 73 | * Stops data communication on this port. Use to shut the connection when 74 | * you're finished with the Serial. 75 | * 76 | * From Serial.stop() 79 | */ 80 | void stop(); 81 | 82 | /** 83 | * Sets the number of bytes to buffer before calling serialEvent(). 84 | * 85 | * From Serial.buffer() 88 | * 89 | * @param count 90 | * number of bytes to buffer 91 | */ 92 | void buffer(int count); 93 | 94 | /** 95 | * Sets a specific byte to buffer until before calling serialEvent(). 96 | * 97 | * From Serial.bufferUntil() 100 | * 101 | * @param what 102 | * the value to buffer until 103 | */ 104 | void bufferUntil(int what); 105 | 106 | /** 107 | * Returns the number of bytes available. 108 | * 109 | * From Serial.available() 112 | * 113 | * @return 114 | */ 115 | int available(); 116 | 117 | /** 118 | * Empty the buffer, removes all the data stored there. 119 | * 120 | * From Serial.clear() 123 | */ 124 | void clear(); 125 | 126 | /** 127 | * Returns a numeric value between 0 and 255 for the next byte that's 128 | * waiting in the buffer. 129 | * 130 | * Returns -1 if there is no byte, although this should be avoided by first 131 | * checking available() to see if data is available. 132 | * 133 | * From Serial.read() 136 | * 137 | * @return 138 | */ 139 | int read(); 140 | 141 | /** 142 | * Returns the next byte in the buffer as a char. Returns -1 or 0xffff if nothing is there. 143 | * 144 | * From Serial.readChar() 147 | * 148 | * @return 149 | */ 150 | char readChar(); 151 | 152 | /** 153 | * Returns last byte received. 154 | * 155 | * Returns -1 if there is no byte, although this should be avoided by first 156 | * checking available() to see if data is available. 157 | * 158 | * From Serial.last() 161 | * 162 | * @return 163 | */ 164 | int last(); 165 | 166 | /** 167 | * Returns the last byte received as a char. 168 | * 169 | * Returns -1 if there is no byte, although this should be avoided by first 170 | * checking available() to see if data is available. 171 | * 172 | * From Serial.lastChar() 175 | * 176 | * @return 177 | */ 178 | char lastChar(); 179 | 180 | /** 181 | * Reads a group of bytes from the buffer. The version with no parameters 182 | * returns a byte array of all data in the buffer. This is not efficient, 183 | * but is easy to use. 184 | * 185 | * From Serial.readBytes() 188 | * 189 | * @return 190 | */ 191 | byte[] readBytes(); 192 | 193 | /** 194 | * The version with the byteBuffer parameter is more memory and time 195 | * efficient. It grabs the data in the buffer and puts it into the byte 196 | * array passed in and returns an int value for the number of bytes read. If 197 | * more bytes are available than can fit into the byteBuffer, only those 198 | * that fit are read. 199 | * 200 | * From Serial.readBytes() 203 | * 204 | * @param byteBuffer 205 | * @return 206 | */ 207 | int readBytes(byte[] byteBuffer); 208 | 209 | /** 210 | * Reads from the port into a buffer of bytes up to and including a 211 | * particular character. If the character isn't in the buffer, 'null' is 212 | * returned. The version with without the byteBuffer parameter returns a 213 | * byte array of all data up to and including the interesting byte. This is 214 | * not efficient, but is easy to use. 215 | * 216 | * From Serial.readBytesUntil() 219 | * 220 | * @param interesting 221 | * character designated to mark the end of the data 222 | * @return 223 | */ 224 | byte[] readBytesUntil(int interesting); 225 | 226 | /** 227 | * The version with the byteBuffer parameter is more memory and time 228 | * efficient. It grabs the data in the buffer and puts it into the byte 229 | * array passed in and returns an int value for the number of bytes read. If 230 | * the byte buffer is not large enough, -1 is returned and an error is 231 | * printed to the message area. If nothing is in the buffer, 0 is returned. 232 | * 233 | * From Serial.readBytesUntil() 236 | * 237 | * @param interesting 238 | * character designated to mark the end of the data 239 | * @param byteBuffer 240 | * passed in byte array to be altered 241 | * @return 242 | */ 243 | int readBytesUntil(int interesting, byte[] byteBuffer); 244 | 245 | /** 246 | * Returns all the data from the buffer as a String. This method assumes the 247 | * incoming characters are ASCII. If you want to transfer Unicode data, 248 | * first convert the String to a byte stream in the representation of your 249 | * choice (i.e. UTF8 or two-byte Unicode data), and send it as a byte array. 250 | * 251 | * From Serial.readString() 254 | * 255 | * @return 256 | */ 257 | String readString(); 258 | 259 | /** 260 | * Combination of readBytesUntil() and readString(). Returns null if it 261 | * doesn't find what you're looking for. 262 | * 263 | * From Serial.readStringUntil() 266 | * 267 | * @param interesting 268 | * character designated to mark the end of the data 269 | * @return 270 | */ 271 | String readStringUntil(int interesting); 272 | 273 | /** 274 | * Writes bytes, chars, ints, bytes[], Strings to the serial port 275 | * 276 | * From Serial.write() 279 | * 280 | * @param what 281 | * data to write 282 | */ 283 | void write(int what); 284 | 285 | /** 286 | * Writes bytes, chars, ints, bytes[], Strings to the serial port 287 | * 288 | * From Serial.write() 291 | * 292 | * @param what 293 | * data to write 294 | */ 295 | void write(byte[] what); 296 | 297 | /** 298 | * Writes bytes, chars, ints, bytes[], Strings to the serial port 299 | * 300 | * From Serial.write() 303 | * 304 | * @param what 305 | * data to write 306 | */ 307 | void write(String what); 308 | 309 | /** 310 | * Gets a list of all available serial ports. Use println() to write the 311 | * information to the text window. 312 | * 313 | * From Serial.list() 316 | * 317 | * @return 318 | */ 319 | String[] list(); 320 | } 321 | -------------------------------------------------------------------------------- /src/main/java/io/inventit/processing/android/serial/AbstractAndroidSerialCommunicator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 InventIt Inc. 3 | */ 4 | package io.inventit.processing.android.serial; 5 | 6 | import android.content.Context; 7 | import com.hoho.android.usbserial.util.HexDump; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import processing.core.PApplet; 11 | 12 | import java.io.*; 13 | import java.lang.reflect.InvocationTargetException; 14 | import java.lang.reflect.Method; 15 | 16 | /** 17 | * 18 | * @author dbaba@yourinventit.com 19 | * 20 | */ 21 | abstract class AbstractAndroidSerialCommunicator extends Serial implements 22 | SerialCommunicator { 23 | 24 | /** 25 | * {@link Logger} 26 | */ 27 | private static final Logger LOGGER = LoggerFactory 28 | .getLogger(AbstractAndroidSerialCommunicator.class); 29 | 30 | /** 31 | * {@link PApplet} 32 | */ 33 | private final PApplet parent; 34 | 35 | /** 36 | * {@link Context} 37 | */ 38 | private final Context applicatoinContext; 39 | 40 | /** 41 | * "serialEvent(Serial)" method in the parent. 42 | */ 43 | private final Method serialEventMethod; 44 | 45 | /** 46 | * {@link InputStream} 47 | */ 48 | private InputStream readBufferInputStream; 49 | 50 | /** 51 | * {@link PipedOutputStream} 52 | */ 53 | private PipedOutputStream readBufferOutputStream; 54 | 55 | /** 56 | * Buffer 57 | */ 58 | private byte[] buffer = null; 59 | 60 | /** 61 | * Current buffer size 62 | */ 63 | private int currentBufferCount = 0; 64 | 65 | /** 66 | * Buffering byte data delimiter 67 | */ 68 | private int bufferDelimieter = Integer.MIN_VALUE; 69 | 70 | private String portIdentifier; 71 | 72 | private int baudrate; 73 | 74 | private char parity; 75 | 76 | private int dataBits; 77 | 78 | private float stopBits; 79 | 80 | private int last; 81 | 82 | /** 83 | * 84 | * @param parent 85 | */ 86 | public AbstractAndroidSerialCommunicator(PApplet parent) { 87 | this.parent = parent; 88 | this.applicatoinContext = parent.getActivity().getApplicationContext(); 89 | this.serialEventMethod = resolveSerialEventMethod(parent); 90 | } 91 | 92 | /** 93 | * Finds "serialEvent(Serial)" method from the parent. 94 | * 95 | * @param parent 96 | * @return 97 | */ 98 | static Method resolveSerialEventMethod(PApplet parent) { 99 | for (Method method : parent.getClass().getMethods()) { 100 | if ("serialEvent".equals(method.getName())) { 101 | final Class[] paramTypes = method.getParameterTypes(); 102 | if (paramTypes != null 103 | && paramTypes.length == 1 104 | && (SerialCommunicator.class 105 | .isAssignableFrom(paramTypes[0]) || Serial.class 106 | .isAssignableFrom(paramTypes[0]))) { 107 | return method; 108 | } 109 | } 110 | } 111 | LOGGER.info("serialEvent(Serial) is missing in the parent."); 112 | return null; 113 | } 114 | 115 | /** 116 | * @return the serialEventMethod 117 | */ 118 | private Method getSerialEventMethod() { 119 | return serialEventMethod; 120 | } 121 | 122 | /** 123 | * Invoked when a serial event occurs from the subclass. 124 | */ 125 | protected void serialEvent() { 126 | if (getSerialEventMethod() == null) { 127 | return; 128 | } 129 | try { 130 | getSerialEventMethod().invoke(parent, this); 131 | } catch (IllegalAccessException unexpected) { 132 | throw new IllegalStateException(unexpected); 133 | } catch (InvocationTargetException unexpected) { 134 | throw new IllegalStateException(unexpected); 135 | } 136 | } 137 | 138 | /** 139 | * @return the parent 140 | */ 141 | protected PApplet getParent() { 142 | return parent; 143 | } 144 | 145 | /** 146 | * @return the applicatoinContext 147 | */ 148 | protected Context getApplicatoinContext() { 149 | return applicatoinContext; 150 | } 151 | 152 | /** 153 | * @return the bufferDelimieter 154 | */ 155 | protected int getBufferDelimieter() { 156 | return bufferDelimieter; 157 | } 158 | 159 | /** 160 | * @return the portIdentifier 161 | */ 162 | protected String getPortIdentifier() { 163 | return portIdentifier; 164 | } 165 | 166 | /** 167 | * @return the baudrate 168 | */ 169 | protected int getBaudrate() { 170 | return baudrate; 171 | } 172 | 173 | /** 174 | * @return the parity 175 | */ 176 | protected char getParity() { 177 | return parity; 178 | } 179 | 180 | /** 181 | * @return the dataBits 182 | */ 183 | protected int getDataBits() { 184 | return dataBits; 185 | } 186 | 187 | /** 188 | * @return the stopBits 189 | */ 190 | protected float getStopBits() { 191 | return stopBits; 192 | } 193 | 194 | /** 195 | * {@inheritDoc} 196 | * 197 | * @see SerialCommunicator#buffer(int) 198 | */ 199 | @Override 200 | public void buffer(int count) { 201 | if (count < 1) { 202 | this.buffer = null; 203 | } else { 204 | this.buffer = new byte[count]; 205 | } 206 | this.currentBufferCount = 0; 207 | this.bufferDelimieter = Integer.MIN_VALUE; 208 | } 209 | 210 | /** 211 | * {@inheritDoc} 212 | * 213 | * @see SerialCommunicator#bufferUntil(int) 214 | */ 215 | @Override 216 | public void bufferUntil(int what) { 217 | this.bufferDelimieter = what; 218 | this.buffer = null; 219 | this.currentBufferCount = 0; 220 | } 221 | 222 | /** 223 | * Sends the data into the buffer. 224 | * 225 | * @param data 226 | */ 227 | protected void sendBuffer(byte[] data) { 228 | if (this.buffer != null) { 229 | int dataLength = data.length; 230 | int offset = this.currentBufferCount; 231 | while (true) { 232 | final int bufferLength = this.buffer.length - offset; 233 | if (dataLength < bufferLength) { 234 | System.arraycopy(data, 0, this.buffer, offset, dataLength); 235 | offset += dataLength; 236 | break; 237 | 238 | } else { 239 | System.arraycopy(data, 0, this.buffer, offset, bufferLength); 240 | doSendBuffer(this.buffer.clone()); 241 | offset = 0; 242 | if (dataLength == bufferLength) { 243 | break; 244 | } 245 | } 246 | } 247 | this.currentBufferCount = offset; 248 | 249 | } else if (this.bufferDelimieter > 0) { 250 | final int delim = this.bufferDelimieter; 251 | try { 252 | for (int i = 0; i < data.length; i++) { 253 | this.readBufferOutputStream.write(data[i]); 254 | if (data[i] == delim) { 255 | serialEvent(); 256 | } 257 | } 258 | } catch (IOException e) { 259 | throw new IllegalStateException(e); 260 | } 261 | 262 | } else { 263 | doSendBuffer(data); 264 | } 265 | } 266 | 267 | /** 268 | * 269 | * @param data 270 | */ 271 | protected void doSendBuffer(byte[] data) { 272 | if (readBufferOutputStream == null) { 273 | LOGGER.info("[doSendBuffer] Skipped data =>{}", 274 | HexDump.dumpHexString(data)); 275 | return; 276 | } 277 | try { 278 | this.readBufferOutputStream.write(data); 279 | serialEvent(); 280 | } catch (IOException e) { 281 | throw new IllegalStateException(e); 282 | } 283 | } 284 | 285 | /** 286 | * {@inheritDoc} 287 | * 288 | * @see SerialCommunicator#start(java.lang.String) 289 | */ 290 | @Override 291 | public void start(String portIdentifier) { 292 | start(portIdentifier, 9600); 293 | } 294 | 295 | /** 296 | * {@inheritDoc} 297 | * 298 | * @see SerialCommunicator#start(java.lang.String, 299 | * int) 300 | */ 301 | @Override 302 | public void start(String portIdentifier, int baudrate) { 303 | start(portIdentifier, baudrate, 'N', 8, 1.0f); 304 | } 305 | 306 | /** 307 | * {@inheritDoc} 308 | * 309 | * @see SerialCommunicator#start(java.lang.String, 310 | * int, char, int, float) 311 | */ 312 | @Override 313 | public final void start(String portIdentifier, int baudrate, char parity, 314 | int dataBits, float stopBits) { 315 | final PipedInputStream pipedInputStream = new PipedInputStream(); 316 | this.readBufferInputStream = pipedInputStream; 317 | try { 318 | this.readBufferOutputStream = new PipedOutputStream( 319 | pipedInputStream); 320 | } catch (IOException exception) { 321 | throw new IllegalStateException(exception); 322 | } 323 | this.portIdentifier = portIdentifier; 324 | this.baudrate = baudrate; 325 | this.parity = parity; 326 | this.dataBits = dataBits; 327 | this.stopBits = stopBits; 328 | doStart(portIdentifier, baudrate, parity, dataBits, stopBits); 329 | } 330 | 331 | /** 332 | * 333 | * @param portIdentifier 334 | * @param baudrate 335 | * @param parity 336 | * @param dataBits 337 | * @param stopBits 338 | */ 339 | protected abstract void doStart(String portIdentifier, int baudrate, 340 | char parity, int dataBits, float stopBits); 341 | 342 | /** 343 | * {@inheritDoc} 344 | * 345 | * @see SerialCommunicator#stop() 346 | */ 347 | @Override 348 | public final void stop() { 349 | try { 350 | doStop(); 351 | } finally { 352 | if (readBufferOutputStream != null) { 353 | try { 354 | readBufferOutputStream.close(); 355 | } catch (IOException ignored) { 356 | } 357 | readBufferOutputStream = null; 358 | } 359 | if (readBufferInputStream != null) { 360 | try { 361 | readBufferInputStream.close(); 362 | } catch (IOException ignored) { 363 | } 364 | readBufferOutputStream = null; 365 | } 366 | } 367 | } 368 | 369 | /** 370 | * 371 | */ 372 | protected abstract void doStop(); 373 | 374 | /** 375 | * {@inheritDoc} 376 | * 377 | * @see SerialCommunicator#available() 378 | */ 379 | @Override 380 | public int available() { 381 | try { 382 | return this.readBufferInputStream.available(); 383 | } catch (IOException e) { 384 | throw new IllegalStateException(e); 385 | } 386 | } 387 | 388 | /** 389 | * {@inheritDoc} 390 | * 391 | * @see SerialCommunicator#clear() 392 | */ 393 | @Override 394 | public synchronized void clear() { 395 | try { 396 | this.readBufferOutputStream.flush(); 397 | } catch (IOException e) { 398 | throw new IllegalStateException(e); 399 | } 400 | readBytes(); 401 | if (this.buffer != null) { 402 | this.currentBufferCount = 0; 403 | } 404 | } 405 | 406 | /** 407 | * {@inheritDoc} 408 | * 409 | * @see SerialCommunicator#read() 410 | */ 411 | @Override 412 | public synchronized int read() { 413 | try { 414 | final int b = this.readBufferInputStream.read(); 415 | this.last = b; 416 | return b; 417 | } catch (IOException e) { 418 | throw new IllegalStateException(e); 419 | } 420 | } 421 | 422 | public char readChar() { 423 | return (char) this.read(); 424 | } 425 | 426 | public int last() { 427 | return this.last; 428 | } 429 | 430 | public char lastChar() { 431 | return (char) this.last; 432 | } 433 | 434 | /** 435 | * {@inheritDoc} 436 | * 437 | * @see SerialCommunicator#readBytes() 438 | */ 439 | @Override 440 | public synchronized byte[] readBytes() { 441 | final ByteArrayOutputStream out = new ByteArrayOutputStream(); 442 | int readByte = -1; 443 | final byte[] buff = new byte[1024]; 444 | try { 445 | if (this.readBufferInputStream.available() > 0) { 446 | while ((readByte = this.readBufferInputStream.read(buff)) >= 0) { 447 | out.write(buff, 0, readByte); 448 | if (this.readBufferInputStream.available() < 1) { 449 | break; 450 | } 451 | } 452 | return out.toByteArray(); 453 | } else { 454 | return null; 455 | } 456 | } catch (IOException e) { 457 | throw new IllegalStateException(e); 458 | } 459 | } 460 | 461 | /** 462 | * {@inheritDoc} 463 | * 464 | * @see SerialCommunicator#readBytes(byte[]) 465 | */ 466 | @Override 467 | public synchronized int readBytes(byte[] byteBuffer) { 468 | try { 469 | return this.readBufferInputStream.read(byteBuffer); 470 | } catch (IOException e) { 471 | throw new IllegalStateException(e); 472 | } 473 | } 474 | 475 | /** 476 | * {@inheritDoc} 477 | * 478 | * @see SerialCommunicator#readBytesUntil(int) 479 | */ 480 | @Override 481 | public synchronized byte[] readBytesUntil(int interesting) { 482 | final ByteArrayOutputStream out = new ByteArrayOutputStream(); 483 | int readByte = -1; 484 | if (available() > 0) { 485 | while ((readByte = read()) >= 0) { 486 | out.write(readByte); 487 | if (readByte == interesting) { 488 | return out.toByteArray(); 489 | } else if (available() < 1) { 490 | break; 491 | } 492 | } 493 | } 494 | return null; 495 | } 496 | 497 | /** 498 | * {@inheritDoc} 499 | * 500 | * @see SerialCommunicator#readBytesUntil(int, 501 | * byte[]) 502 | */ 503 | @Override 504 | public synchronized int readBytesUntil(int interesting, byte[] byteBuffer) { 505 | int readByte = -1; 506 | for (int i = 0; i < byteBuffer.length; i++) { 507 | readByte = read(); 508 | if (readByte < 0) { 509 | break; 510 | } 511 | byteBuffer[i] = (byte) readByte; 512 | if (readByte == interesting) { 513 | return i + 1; 514 | } 515 | } 516 | LOGGER.error("Insufficient byteBuffer size ({}).", byteBuffer.length); 517 | return -1; 518 | } 519 | 520 | /** 521 | * {@inheritDoc} 522 | * 523 | * @see SerialCommunicator#readString() 524 | */ 525 | @Override 526 | public String readString() { 527 | return new String(readBytes()); 528 | } 529 | 530 | /** 531 | * {@inheritDoc} 532 | * 533 | * @see SerialCommunicator#readStringUntil(int) 534 | */ 535 | @Override 536 | public String readStringUntil(int interesting) { 537 | final byte[] readBytes = readBytesUntil(interesting); 538 | if (readBytes != null) { 539 | return new String(readBytes); 540 | } 541 | return null; 542 | } 543 | } 544 | --------------------------------------------------------------------------------