From 4f7e5ea8cf78bfcdbb6689f6fcd9c5bd3828074a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20Petra=C5=A1inovi=C4=87?= Date: Thu, 6 Jan 2022 12:43:34 +0100 Subject: [PATCH] Initial commit --- CHANGES.txt | 10 + LICENSE.txt | 21 + README.md | 144 ++++++ device_filter.xml | 35 ++ package.json | 29 ++ plugin.xml | 20 + src/android/SerialUSB.java | 607 ++++++++++++++++++++++++++ src/android/UsbBroadcastReceiver.java | 72 +++ src/android/build.gradle | 11 + www/SerialUSB.js | 90 ++++ 10 files changed, 1039 insertions(+) create mode 100644 CHANGES.txt create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 device_filter.xml create mode 100644 package.json create mode 100644 plugin.xml create mode 100644 src/android/SerialUSB.java create mode 100644 src/android/UsbBroadcastReceiver.java create mode 100644 src/android/build.gradle create mode 100644 www/SerialUSB.js diff --git a/CHANGES.txt b/CHANGES.txt new file mode 100644 index 0000000..3a6a7c2 --- /dev/null +++ b/CHANGES.txt @@ -0,0 +1,10 @@ +-------------------- +cordova-plugin-serialusb +Cordova plugin for Android Serial USB communication (easily connect an Arduino board to an Android device). +-------------------- + +Release 1.0.0, 10.12.2021. + +- Initial release + +-------------------- \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..cab0ab1 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License +Copyright (c) 2021 Miloš Petrašinović PR-DC. https://pr-dc.com +Copyright (c) 2015 Xavier Seignard. http://drangies.fr + +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: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8bea9ad --- /dev/null +++ b/README.md @@ -0,0 +1,144 @@ +## PR-DC cordova-plugin-serialusb + +Cordova plugin for Android Serial USB communication. This plugin makes a connection to the external board trivial, for example, you can connect an Arduino board to an Android device and get power, storage, a high-quality touch interface and many possible ways of connecting with the rest of the world (mobile network, WiFi, Bluetooth...). + +## Requirements +[Apache Cordova](https://cordova.apache.org/)
+ +This library is tested with +**Cordova Android 9.1.0** + +## Installation +From the root folder of your Cordova project, run: +``` +cordova plugin add https://github.com/PR-DC/cordova-plugin-serialusb.git +``` + +## Usage +Thanks to [usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) library, you can communicate with CDC, FTDI, Arduino and other devices. + +Copy `device_filter.xml` document to `www/res/xml`. + +Append the following to the project's `config.xml` document within the Android platform-specific configuration. +```xml + + + + + + + +``` + +Append following preference to project's `config.xml` document. +```xml + +``` + +Now you can proceed with the app code, request permission to use the serial port to the system: +```js +SerialUSB.requestPermission(function success(), function error()); +``` +After permission is granted you can open the serial port: +```js +SerialUSB.open(opts, function success(), function error()); +``` +`opts` is a JSON object with the following properties: + +- baudRate: defaults to 9600 +- dataBits: defaults to 8 +- stopBits: defaults to 1 +- parity: defaults to 0 +- dtr: defaults to false (it may be needed to be true for some Arduino) +- rts: defaults to false (it may be needed to be true for some modules) +- sleepOnPause: defaults to true. If false, the OTG port will remain open when the app goes to the background (or the screen turns off). Otherwise, the port automatically closes and resumes once the app is brought back to the foreground. + +You're now able to read and write: +```js +SerialUSB.write(data, function success(), function error()); +SerialUSB.read(function success(buffer), function error()); +``` +`data` is the string representation to be written to the serial port. +`buffer` is a JavaScript ArrayBuffer containing the data that was just read. + +Apart from using `SerialUSB.write()`, you can also use `SerialUSB.writeHex()` to have an easy way to work with **RS232 protocol** driven hardware from your javascript by using **hex-strings**. + +In a nutshell, `SerialUSB.writeHex('ff')` would write just a single byte where `SerialUSB.write('ff')` would let java write 2 bytes to the serial port. + +Apart from that, `SerialUSB.writeHex()` works the same way as `SerialUSB.write()` does. + +Register a callback that will be invoked when the driver reads incoming data from your serial device. The success callback function will receive an ArrayBuffer filled with the data read from serial: +```js +SerialUSB.registerReadCallback( + function success(data){ + var view = new Uint8Array(data); + console.log(view); + }, + function error(){ + new Error("Failed to register read callback"); + }); +``` + +Register a callback that will be invoked when the device is detached: +```js +SerialUSB.detached( + function(success_message) { + + }, function(err) { + console.log("Device detached!"); + } +); +``` + +And finally, you can also close the port with: +```js +SerialUSB.close(function success(), function error()) +``` + +## Example with Cordova app and Arduino sketch + +An example of connecting Cordova application to Arduino board is available at: https://github.com/PR-DC/PRDC_TestSerialUSB + +## Change log +2021.12: [Miloš Petrašinović](https://github.com/PR-DC): renamed to cordova-plugin-serialusb (SerialUSB as in Arduino) and implemented detached event. + +2018.02: [Dario Cavada](https://github.com/dariocavada): renamed to cordova-plugin-usbserial and refactory internal to follow cordova naming convention. + +2015.10: [Ed. Lafargue](https://github.com/elafargue): Implemented "sleepOnPause" flag in the 'open' options to prevent closing the OTG port when app goes to background. + +2014.08: [Zevero](https://github.com/zevero): Option to find device by VID and PID, that let you use "unrecognized" devices. + +2014.07: [Hendrik Maus](https://github.com/hendrikmaus): Implemented writeHex for working with RS232 protocol, i.e. javascript can now pass "ff", java turns it into a 1 byte array and writes to the serial port - naturally, java, and the existing write method here, would create a 2 byte array from the input string. + +2014.04: [Derek K](https://github.com/etx): Implemented registerReadCallback for evented reading and Android onPause/onResume + +2014.03: [Ed. Lafargue](https://github.com/elafargue): Implemented read(). The success callback returns a Javascript ArrayBuffer which is the best way to handle binary data in Javascript. It is straightforward to convert this to a string if required - a utility function could be implemented in this plugin. + +2013.11: [Xavier Seignard](https://github.com/xseignard): First implementation + +## License +The MIT License + +Copyright (c) 2021 Miloš Petrašinović PR-DC. https://pr-dc.com + +Copyright (c) 2015 Xavier Seignard. http://drangies.fr + +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: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. diff --git a/device_filter.xml b/device_filter.xml new file mode 100644 index 0000000..6e211bc --- /dev/null +++ b/device_filter.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..8e9a535 --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "cordova-plugin-serialusb", + "version": "1.0.0", + "description": "Cordova plugin for Android Serial USB communication", + "cordova": { + "id": "cordova-plugin-serialusb", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "cordova-android" + ], + "author": "Miloš Petrašinović ", + "license": "MIT", + "main": "./www/SerialUSB.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/PR-DC/cordova-plugin-serialusb.git" + }, + "bugs": { + "url": "https://github.com/PR-DC/cordova-plugin-serialusb/issues" + }, + "homepage": "https://github.com/PR-DC/cordova-plugin-serialusb#readme" +} diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..0d5a532 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,20 @@ + + + Serial USB + + + + + + + + + + + + + + + diff --git a/src/android/SerialUSB.java b/src/android/SerialUSB.java new file mode 100644 index 0000000..4f2accc --- /dev/null +++ b/src/android/SerialUSB.java @@ -0,0 +1,607 @@ +/** + * cordova-plugin-serialusb - SerialUSB.java + * Author: Milos Petrasinovic + * PR-DC, Republic of Serbia + * info@pr-dc.com + * -------------------- + */ + +package rs.prdc.serialusb; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import com.hoho.android.usbserial.driver.CdcAcmSerialDriver; +import com.hoho.android.usbserial.driver.Ch34xSerialDriver; +import com.hoho.android.usbserial.driver.Cp21xxSerialDriver; +import com.hoho.android.usbserial.driver.FtdiSerialDriver; +import com.hoho.android.usbserial.driver.ProbeTable; +import com.hoho.android.usbserial.driver.ProlificSerialDriver; +import com.hoho.android.usbserial.driver.UsbSerialDriver; +import com.hoho.android.usbserial.driver.UsbSerialPort; +import com.hoho.android.usbserial.driver.UsbSerialProber; +import com.hoho.android.usbserial.util.SerialInputOutputManager; + +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbDeviceConnection; +import android.hardware.usb.UsbManager; +import android.util.Base64; +import android.util.Log; + + +/** + * Cordova plugin for Android Serial USB communication + * @author Xavier Seignard + * @author Dario Cavada + * @author Milоs Petrasinovic + */ +public class SerialUSB extends CordovaPlugin { + // logging tag + private final String TAG = SerialUSB.class.getSimpleName(); + // actions definitions + private static final String ACTION_REQUEST_PERMISSION = "requestPermission"; + private static final String ACTION_OPEN = "openSerial"; + private static final String ACTION_READ = "readSerial"; + private static final String ACTION_WRITE = "writeSerial"; + private static final String ACTION_WRITE_HEX = "writeSerialHex"; + private static final String ACTION_CLOSE = "closeSerial"; + private static final String ACTION_READ_CALLBACK = "registerReadCallback"; + private static final String ACTION_DETACHED = "detached"; + + // UsbManager instance to deal with permission and opening + private UsbManager manager; + // The current driver that handle the serial port + private UsbSerialDriver driver; + // The serial port that will be used in this plugin + private UsbSerialPort port; + // Read buffer, and read params + private static final int READ_WAIT_MILLIS = 200; + private static final int BUFSIZ = 4096; + private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ); + // Connection info + private int baudRate; + private int dataBits; + private int stopBits; + private int parity; + private boolean setDTR; + private boolean setRTS; + private boolean sleepOnPause; + + // callback that will be used to send back data to the cordova app + private CallbackContext readCallback; + + // I/O manager to handle new incoming serial data + private final ExecutorService mExecutor = Executors.newSingleThreadExecutor(); + private SerialInputOutputManager mSerialIoManager; + private final SerialInputOutputManager.Listener mListener = + new SerialInputOutputManager.Listener() { + @Override + public void onRunError(Exception e) { + Log.d(TAG, "Runner stopped."); + } + @Override + public void onNewData(final byte[] data) { + SerialUSB.this.updateReceivedData(data); + } + }; + + /** + * Overridden execute method + * @param action the string representation of the action to execute + * @param args + * @param callbackContext the cordova {@link CallbackContext} + * @return true if the action exists, false otherwise + * @throws JSONException if the args parsing fails + */ + @Override + public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { + Log.d(TAG, "Action: " + action); + JSONObject arg_object = args.optJSONObject(0); + // request permission + if (ACTION_REQUEST_PERMISSION.equals(action)) { + JSONObject opts = arg_object.has("opts")? arg_object.getJSONObject("opts") : new JSONObject(); + requestPermission(opts, callbackContext); + return true; + } + // open serial port + else if (ACTION_OPEN.equals(action)) { + JSONObject opts = arg_object.has("opts")? arg_object.getJSONObject("opts") : new JSONObject(); + openSerial(opts, callbackContext); + return true; + } + // write to the serial port + else if (ACTION_WRITE.equals(action)) { + String data = arg_object.getString("data"); + writeSerial(data, callbackContext); + return true; + } + // write hex to the serial port + else if (ACTION_WRITE_HEX.equals(action)) { + String data = arg_object.getString("data"); + writeSerialHex(data, callbackContext); + return true; + } + // read on the serial port + else if (ACTION_READ.equals(action)) { + readSerial(callbackContext); + return true; + } + // close the serial port + else if (ACTION_CLOSE.equals(action)) { + closeSerial(callbackContext); + return true; + } + // Register read callback + else if (ACTION_READ_CALLBACK.equals(action)) { + registerReadCallback(callbackContext); + return true; + } + // Receive USB device detach + else if (ACTION_DETACHED.equals(action)) { + detached(callbackContext); + return true; + } + // the action doesn't exist + return false; + } + + /** + * Request permission the the user for the app to use the USB/serial port + * @param callbackContext the cordova {@link CallbackContext} + */ + private void requestPermission(final JSONObject opts, final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + // get UsbManager from Android + manager = (UsbManager) cordova.getActivity().getSystemService(Context.USB_SERVICE); + UsbSerialProber prober; + + if (opts.has("vid") && opts.has("pid")) { + ProbeTable customTable = new ProbeTable(); + Object o_vid = opts.opt("vid"); //can be an integer Number or a hex String + Object o_pid = opts.opt("pid"); //can be an integer Number or a hex String + int vid = o_vid instanceof Number ? ((Number) o_vid).intValue() : Integer.parseInt((String) o_vid,16); + int pid = o_pid instanceof Number ? ((Number) o_pid).intValue() : Integer.parseInt((String) o_pid,16); + String driver = opts.has("driver") ? (String) opts.opt("driver") : "CdcAcmSerialDriver"; + + if (driver.equals("FtdiSerialDriver")) { + customTable.addProduct(vid, pid, FtdiSerialDriver.class); + } + else if (driver.equals("CdcAcmSerialDriver")) { + customTable.addProduct(vid, pid, CdcAcmSerialDriver.class); + } + else if (driver.equals("Cp21xxSerialDriver")) { + customTable.addProduct(vid, pid, Cp21xxSerialDriver.class); + } + else if (driver.equals("ProlificSerialDriver")) { + customTable.addProduct(vid, pid, ProlificSerialDriver.class); + } + else if (driver.equals("Ch34xSerialDriver")) { + customTable.addProduct(vid, pid, Ch34xSerialDriver.class); + } + else { + Log.d(TAG, "Unknown driver!"); + callbackContext.error("Unknown driver!"); + } + + prober = new UsbSerialProber(customTable); + + } + else { + // find all available drivers from attached devices. + prober = UsbSerialProber.getDefaultProber(); + } + + List availableDrivers = prober.findAllDrivers(manager); + + if (!availableDrivers.isEmpty()) { + // get the first one as there is a high chance that there is no more than one usb device attached to your android + driver = availableDrivers.get(0); + UsbDevice device = driver.getDevice(); + // create the intent that will be used to get the permission + PendingIntent pendingIntent = PendingIntent.getBroadcast(cordova.getActivity(), 0, new Intent(UsbBroadcastReceiver.USB_PERMISSION), 0); + // and a filter on the permission we ask + IntentFilter filter = new IntentFilter(); + filter.addAction(UsbBroadcastReceiver.USB_PERMISSION); + // this broadcast receiver will handle the permission results + UsbBroadcastReceiver usbReceiver = new UsbBroadcastReceiver(callbackContext, cordova.getActivity()); + cordova.getActivity().registerReceiver(usbReceiver, filter); + // finally ask for the permission + manager.requestPermission(device, pendingIntent); + } + else { + // no available drivers + Log.d(TAG, "No device found!"); + callbackContext.error("No device found!"); + } + } + }); + } + + /** + * Open the serial port from Cordova + * @param opts a {@link JSONObject} containing the connection paramters + * @param callbackContext the cordova {@link CallbackContext} + */ + private void openSerial(final JSONObject opts, final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + UsbDevice device = driver.getDevice(); + if (device != null) { + UsbDeviceConnection connection = manager.openDevice(device); + if (connection != null) { + // get first port and open it + port = driver.getPorts().get(0); + try { + // get connection params or the default values + baudRate = opts.has("baudRate") ? opts.getInt("baudRate") : 9600; + dataBits = opts.has("dataBits") ? opts.getInt("dataBits") : UsbSerialPort.DATABITS_8; + stopBits = opts.has("stopBits") ? opts.getInt("stopBits") : UsbSerialPort.STOPBITS_1; + parity = opts.has("parity") ? opts.getInt("parity") : UsbSerialPort.PARITY_NONE; + setDTR = opts.has("dtr") && opts.getBoolean("dtr"); + setRTS = opts.has("rts") && opts.getBoolean("rts"); + // Sleep On Pause defaults to true + sleepOnPause = opts.has("sleepOnPause") ? opts.getBoolean("sleepOnPause") : true; + + port.open(connection); + port.setParameters(baudRate, dataBits, stopBits, parity); + if (setDTR) port.setDTR(true); + if (setRTS) port.setRTS(true); + } catch (IOException e) { + // deal with error + Log.d(TAG, e.getMessage()); + callbackContext.error(e.getMessage()); + } catch (JSONException e) { + // deal with error + Log.d(TAG, e.getMessage()); + callbackContext.error(e.getMessage()); + } + + Log.d(TAG, "Serial port opened!"); + callbackContext.success("Serial port opened!"); + } + } + else { + Log.d(TAG, "Cannot connect to the device!"); + callbackContext.error("Cannot connect to the device!"); + } + onDeviceStateChange(); + } + }); + } + + /** + * Write on the serial port + * @param data the {@link String} representation of the data to be written on the port + * @param callbackContext the cordova {@link CallbackContext} + */ + private void writeSerial(final String data, final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + if (port == null) { + callbackContext.error("Writing a closed port."); + } + else { + try { + Log.d(TAG, data); + byte[] buffer = data.getBytes(); + port.write(buffer, 1000); + callbackContext.success(); + } + catch (IOException e) { + // deal with error + Log.d(TAG, e.getMessage()); + callbackContext.error(e.getMessage()); + } + } + } + }); + } + + /** + * Write hex on the serial port + * @param data the {@link String} representation of the data to be written on the port as hexadecimal string + * e.g. "ff55aaeeef000233" + * @param callbackContext the cordova {@link CallbackContext} + */ + private void writeSerialHex(final String data, final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + if (port == null) { + callbackContext.error("Writing a closed port."); + } + else { + try { + Log.d(TAG, data); + byte[] buffer = hexStringToByteArray(data); + port.write(buffer, 1000); + callbackContext.success(); + } + catch (IOException e) { + // deal with error + Log.d(TAG, e.getMessage()); + callbackContext.error(e.getMessage()); + } + } + } + }); + } + + /** + * Convert a given string of hexadecimal numbers + * into a byte[] array where every 2 hex chars get packed into + * a single byte. + * + * E.g. "ffaa55" results in a 3 byte long byte array + * + * @param s + * @return + */ + private byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i+1), 16)); + } + return data; + } + + /** + * Read on the serial port + * @param callbackContext the {@link CallbackContext} + */ + private void readSerial(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + if (port == null) { + callbackContext.error("Reading a closed port."); + } + else { + try { + int len = port.read(mReadBuffer.array(), READ_WAIT_MILLIS); + // Whatever happens, we send an "OK" result, up to the + // receiver to check that len > 0 + PluginResult.Status status = PluginResult.Status.OK; + if (len > 0) { + Log.d(TAG, "Read data len=" + len); + final byte[] data = new byte[len]; + mReadBuffer.get(data, 0, len); + mReadBuffer.clear(); + callbackContext.sendPluginResult(new PluginResult(status,data)); + } + else { + final byte[] data = new byte[0]; + callbackContext.sendPluginResult(new PluginResult(status, data)); + } + } + catch (IOException e) { + // deal with error + Log.d(TAG, e.getMessage()); + callbackContext.error(e.getMessage()); + } + } + } + }); + } + + /** + * Close the serial port + * @param callbackContext the cordova {@link CallbackContext} + */ + private void closeSerial(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + // Make sure we don't die if we try to close an non-existing port! + if (port != null) { + port.close(); + } + port = null; + callbackContext.success(); + } + catch (IOException e) { + // deal with error + Log.d(TAG, e.getMessage()); + callbackContext.error(e.getMessage()); + } + onDeviceStateChange(); + } + }); + } + + + /** + * Stop observing serial connection + */ + private void stopIoManager() { + if (mSerialIoManager != null) { + Log.i(TAG, "Stopping io manager."); + mSerialIoManager.stop(); + mSerialIoManager = null; + } + } + + /** + * Observe serial connection + */ + private void startIoManager() { + if (driver != null) { + Log.i(TAG, "Starting io manager."); + mSerialIoManager = new SerialInputOutputManager(port, mListener); + mExecutor.submit(mSerialIoManager); + } + } + + /** + * Restart the observation of the serial connection + */ + private void onDeviceStateChange() { + stopIoManager(); + startIoManager(); + } + + /** + * Dispatch read data to javascript + * @param data the array of bytes to dispatch + */ + private void updateReceivedData(byte[] data) { + if( readCallback != null ) { + PluginResult result = new PluginResult(PluginResult.Status.OK, data); + result.setKeepCallback(true); + readCallback.sendPluginResult(result); + } + } + + /** + * Register callback for read data + * @param callbackContext the cordova {@link CallbackContext} + */ + private void registerReadCallback(final CallbackContext callbackContext) { + Log.d(TAG, "Registering callback"); + cordova.getThreadPool().execute(new Runnable() { + public void run() { + Log.d(TAG, "Registering Read Callback"); + readCallback = callbackContext; + JSONObject returnObj = new JSONObject(); + addProperty(returnObj, "registerReadCallback", "true"); + // Keep the callback + PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, returnObj); + pluginResult.setKeepCallback(true); + callbackContext.sendPluginResult(pluginResult); + } + }); + } + + /** + * BroadcastReceiver for USB detached + * @param callbackContext the cordova {@link CallbackContext} + */ + private void detached(final CallbackContext callbackContext) { + Log.d(TAG, "Registering callback"); + cordova.getThreadPool().execute(new Runnable() { + public void run() { + IntentFilter filterAttachDetach = new IntentFilter(); + filterAttachDetach.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); + // this broadcast receiver will handle the results + UsbBroadcastReceiver usbReceiver = new UsbBroadcastReceiver(callbackContext, cordova.getActivity()); + cordova.getActivity().registerReceiver(usbReceiver, filterAttachDetach); + } + }); + } + + /** + * Paused activity handler + * @see org.apache.cordova.CordovaPlugin#onPause(boolean) + */ + @Override + public void onPause(boolean multitasking) { + if (sleepOnPause) { + stopIoManager(); + if (port != null) { + try { + port.close(); + } catch (IOException e) { + // Ignore + } + port = null; + } + } + } + + + /** + * Resumed activity handler + * @see org.apache.cordova.CordovaPlugin#onResume(boolean) + */ + @Override + public void onResume(boolean multitasking) { + Log.d(TAG, "Resumed, driver=" + driver); + if (sleepOnPause) { + if (driver == null) { + Log.d(TAG, "No serial device to resume."); + } + else { + UsbDeviceConnection connection = manager.openDevice(driver.getDevice()); + if (connection != null) { + // get first port and open it + port = driver.getPorts().get(0); + try { + port.open(connection); + port.setParameters(baudRate, dataBits, stopBits, parity); + if (setDTR) port.setDTR(true); + if (setRTS) port.setRTS(true); + } + catch (IOException e) { + // deal with error + Log.d(TAG, e.getMessage()); + } + Log.d(TAG, "Serial port opened!"); + } + else { + Log.d(TAG, "Cannot connect to the device!"); + } + Log.d(TAG, "Serial device: " + driver.getClass().getSimpleName()); + } + + onDeviceStateChange(); + } + } + + + /** + * Destroy activity handler + * @see org.apache.cordova.CordovaPlugin#onDestroy() + */ + @Override + public void onDestroy() { + Log.d(TAG, "Destroy, port=" + port); + if(port != null) { + try { + port.close(); + } + catch (IOException e) { + Log.d(TAG, e.getMessage()); + } + } + onDeviceStateChange(); + } + + /** + * Utility method to add some properties to a {@link JSONObject} + * @param obj the json object where to add the new property + * @param key property key + * @param value value of the property + */ + private void addProperty(JSONObject obj, String key, Object value) { + try { + obj.put(key, value); + } + catch (JSONException e){} + } + + /** + * Utility method to add some properties to a {@link JSONObject} + * @param obj the json object where to add the new property + * @param key property key + * @param bytes the array of byte to add as value to the {@link JSONObject} + */ + private void addPropertyBytes(JSONObject obj, String key, byte[] bytes) { + String string = Base64.encodeToString(bytes, Base64.NO_WRAP); + this.addProperty(obj, key, string); + } +} diff --git a/src/android/UsbBroadcastReceiver.java b/src/android/UsbBroadcastReceiver.java new file mode 100644 index 0000000..0fd45a5 --- /dev/null +++ b/src/android/UsbBroadcastReceiver.java @@ -0,0 +1,72 @@ +/** + * cordova-plugin-serialusb - UsbBroadcastReveicer.java + * Author: Milos Petrasinovic + * PR-DC, Republic of Serbia + * info@pr-dc.com + * -------------------- + */ + +package rs.prdc.serialusb; + +import org.apache.cordova.CallbackContext; + +import android.app.Activity; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.hardware.usb.UsbManager; +import android.util.Log; + +/** + * Custom {@link BroadcastReceiver} that can talk through a cordova {@link CallbackContext} + * @author Xavier Seignard + * @author Milоs Petrasinovic + */ +public class UsbBroadcastReceiver extends BroadcastReceiver { + // logging tag + private final String TAG = UsbBroadcastReceiver.class.getSimpleName(); + // usb permission tag name + public static final String USB_PERMISSION = "rs.prdc.serialusb.USB_PERMISSION"; + // cordova callback context to notify the success/error to the cordova app + private CallbackContext callbackContext; + // cordova activity to use it to unregister this broadcast receiver + private Activity activity; + + /** + * Custom broadcast receiver that will handle the cordova callback context + * @param callbackContext + * @param activity + */ + public UsbBroadcastReceiver(CallbackContext callbackContext, Activity activity) { + this.callbackContext = callbackContext; + this.activity = activity; + } + + + /** + * Handle permission answer + * @param context + * @param intent + * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) + */ + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (USB_PERMISSION.equals(action)) { + // deal with the user answer about the permission + if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { + Log.d(TAG, "Permission to connect to the device was accepted!"); + callbackContext.success("Permission to connect to the device was accepted!"); + } + else { + Log.d(TAG, "Permission to connect to the device was denied!"); + callbackContext.error("Permission to connect to the device was denied!"); + } + // unregister the broadcast receiver since it's no longer needed + activity.unregisterReceiver(this); + } else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) { + callbackContext.error("Device disconnected!"); + activity.unregisterReceiver(this); + } + } +} diff --git a/src/android/build.gradle b/src/android/build.gradle new file mode 100644 index 0000000..09dfccd --- /dev/null +++ b/src/android/build.gradle @@ -0,0 +1,11 @@ +android { + compileSdkVersion 30 +} + +repositories { + maven { url "https://jitpack.io" } +} + +dependencies { + implementation 'com.github.mik3y:usb-serial-for-android:3.4.0' +} \ No newline at end of file diff --git a/www/SerialUSB.js b/www/SerialUSB.js new file mode 100644 index 0000000..6d16e7d --- /dev/null +++ b/www/SerialUSB.js @@ -0,0 +1,90 @@ +// cordova-plugin-serialusb - SerialUSB.js +// Author: Milos Petrasinovic +// PR-DC, Republic of Serbia +// info@pr-dc.com +// -------------------- + +var exec = require('cordova/exec'); + +var SerialUSB = { + requestPermission: function(opts, successCallback, errorCallback) { + if (typeof opts === 'function') { // user did not pass opts + errorCallback = successCallback; + successCallback = opts; + opts = {}; + } + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'requestPermission', + [{'opts': opts}] + ); + }, + open: function(opts, successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'openSerial', + [{'opts': opts}] + ); + }, + write: function(data, successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'writeSerial', + [{'data': data}] + ); + }, + writeHex: function(hexString, successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'writeSerialHex', + [{'data': hexString}] + ); + }, + read: function(successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'readSerial', + [] + ); + }, + close: function(successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'closeSerial', + [] + ); + }, + registerReadCallback: function(successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'registerReadCallback', + [] + ); + }, + detached: function (successCallback, errorCallback) { + cordova.exec( + successCallback, + errorCallback, + 'SerialUSB', + 'detached', + [] + ); + } + +}; +module.exports = SerialUSB; +