felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.78k stars 581 forks source link

Not writing data to Arduino #338

Open chiffacff opened 2 years ago

chiffacff commented 2 years ago

Hello. I try use this code in Cordova project as plugin. The Arduino-device detected ok, but it not send any to serial port.

My code:

package com.my.mobileapp.plugins;

import static androidx.core.content.ContextCompat.getSystemService;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MySerailReader extends CordovaPlugin {

    public static final String TAG = "Chrome";

    private UsbDevice device;
    private UsbManager usbManager;
    private UsbDeviceConnection connection;
    private UsbSerialDevice serial;

    public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
    public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";

    public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        usbManager = (UsbManager) cordova.getActivity().getSystemService(Context.USB_SERVICE);

        findSerialPortDevice();

        connection = usbManager.openDevice(device);

        serial = UsbSerialDevice.createUsbSerialDevice(device, connection);

        serial.open();
        serial.setBaudRate(115200);
        serial.setDataBits(UsbSerialInterface.DATA_BITS_8);
        serial.setParity(UsbSerialInterface.PARITY_NONE);
        serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
        serial.setStopBits(1);

        serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);

        Intent intent = new Intent(ACTION_USB_READY);
        cordova.getActivity().getApplicationContext().sendBroadcast(intent);

        try {
            serial.write("test".getBytes());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        executeGlobalJavascript("test('END OK!');");

        return true;
    }

    private void executeGlobalJavascript(final String jsString){

        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:" + jsString);
            }
        });
    }

    private void findSerialPortDevice() {
        // This snippet will try to open the first encountered usb device connected, excluding usb root hubs
        HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
        if (!usbDevices.isEmpty()) {

            // first, dump the hashmap for diagnostic purposes
            for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
                device = entry.getValue();
                Log.d(TAG, String.format("USBDevice.HashMap (vid:pid) (%X:%X)-%b class:%X:%X name:%s",
                        device.getVendorId(), device.getProductId(),
                        UsbSerialDevice.isSupported(device),
                        device.getDeviceClass(), device.getDeviceSubclass(),
                        device.getDeviceName()));
            }

            for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
                device = entry.getValue();
                int deviceVID = device.getVendorId();
                int devicePID = device.getProductId();

               if (UsbSerialDevice.isSupported(device)) {
                    // There is a supported device connected - request permission to access it.
                    requestUserPermission();
                    break;
                } else {
                    connection = null;
                    device = null;
                }
            }
            if (device==null) {
                // There are no USB devices connected (but usb host were listed). Send an intent to MainActivity.
                Log.d("Chrome", "No USB");
                executeGlobalJavascript("test('No USB');");

            }
        } else {
            Log.d(TAG, "findSerialPortDevice() usbManager returned empty device list." );
            // There is no USB devices connected. Send an intent to MainActivity
            Log.d("Chrome", "Empty dev list");
            executeGlobalJavascript("test('Empty dev list');");
        }
    }

    private void requestUserPermission() {
        Log.d(TAG, String.format("requestUserPermission(%X:%X)", device.getVendorId(), device.getProductId() ) );
        PendingIntent mPendingIntent = PendingIntent.getBroadcast(cordova.getActivity().getApplicationContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
        usbManager.requestPermission(device, mPendingIntent);
    }

}

Arduino blink when get any data in serial port, I test in Serial Monitoring from Arduino IDE and sscom3.2 - work fine

function "test" in my html call alert, then I get "END OK!" but nothing on Arduino side... Can you help please, what I do wrong? Thanks!