使用usb-serial set rts高

时间:2017-12-05 11:23:38

标签: java android usbserial

我正在努力实现这个: https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialExamples/src/main/java/src/com/hoho/android/usbserial/examples/SerialConsoleActivity.java

我有一个LED连接到rts和5v引脚通过CH340g。我在Android上的UsbTerminal应用程序上进行了测试,它工作正常但我的应用程序没有检测到任何USB串行设备,当我尝试检查RTS复选框时它崩溃了。

我是编程和Android的新手,也是我第一次使用这些组件的经验,所以任何帮助都会受到赞赏。

这是我的代码:

package com.example.dell.cashregister;

import android.content.Context;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

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.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;


import java.io.IOException;
import java.util.List;
import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends Activity {

private final String TAG = MainActivity.class.getSimpleName();

private static UsbSerialPort sPort = null;

private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private CheckBox chkDTR;
private CheckBox chkRTS;

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) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.this.updateReceivedData(data);
                    }
                });
            }
        };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTitleTextView = (TextView) findViewById(R.id.demoTitle);
    mDumpTextView = (TextView) findViewById(R.id.consoleText);
    mScrollView = (ScrollView) findViewById(R.id.demoScroller);
    chkDTR = (CheckBox) findViewById(R.id.checkBoxDTR);
    chkRTS = (CheckBox) findViewById(R.id.checkBoxRTS);

    chkDTR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setDTR(isChecked);
            }catch (IOException x){}
        }
    });

    chkRTS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setRTS(isChecked);
            }catch (IOException x){}
        }
    });

}


@Override
protected void onPause() {
    super.onPause();
    stopIoManager();
    if (sPort != null) {
        try {
            sPort.close();
        } catch (IOException e) {
            // Ignore.
        }
        sPort = null;
    }
    finish();
}

void showStatus(TextView theTextView, String theLabel, boolean theValue){
    String msg = theLabel + ": " + (theValue ? "enabled" : "disabled") + "\n";
    theTextView.append(msg);
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "Resumed, port=" + sPort);
    if (sPort == null) {
        mTitleTextView.setText("No serial device.");
    } else {
        final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
        if (connection == null) {
            mTitleTextView.setText("Opening device failed");
            return;
        }

        try {
            sPort.open(connection);
            sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            showStatus(mDumpTextView, "CD  - Carrier Detect", sPort.getCD());
            showStatus(mDumpTextView, "CTS - Clear To Send", sPort.getCTS());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "DTR - Data Terminal Ready", sPort.getDTR());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "RI  - Ring Indicator", sPort.getRI());
            showStatus(mDumpTextView, "RTS - Request To Send", sPort.getRTS());

        } catch (IOException e) {
            Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
            mTitleTextView.setText("Error opening device: " + e.getMessage());
            try {
                sPort.close();
            } catch (IOException e2) {
                // Ignore.
            }
            sPort = null;
            return;
        }
        mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName());
    }
    onDeviceStateChange();
}

private void stopIoManager() {
    if (mSerialIoManager != null) {
        Log.i(TAG, "Stopping io manager ..");
        mSerialIoManager.stop();
        mSerialIoManager = null;
    }
}

private void startIoManager() {
    if (sPort != null) {
        Log.i(TAG, "Starting io manager ..");
        mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
        mExecutor.submit(mSerialIoManager);
    }
}

private void onDeviceStateChange() {
    stopIoManager();
    startIoManager();
}

private void updateReceivedData(byte[] data) {
    final String message = "Read " + data.length + " bytes: \n"
            + HexDump.dumpHexString(data) + "\n\n";
    mDumpTextView.append(message);
    mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}

/**
 * Starts the activity, using the supplied driver instance.
 *
 * @param context
 * @param driver
 */
static void show(Context context, UsbSerialPort port) {
    sPort = port;
    final Intent intent = new Intent(context, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    context.startActivity(intent);
}

}

如果需要更改任何内容以便检测我的设备或是否有任何其他问题,请告诉我。

这是logcat:

12-05 16:32:34.677 17322-17322/com.example.dell.cashregister 
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.dell.cashregister, PID: 17322
                                                                           java.lang.NullPointerException: Attempt to invoke interface method 'void com.hoho.android.usbserial.driver.UsbSerialPort.setRTS(boolean)' on a null object reference
                                                                               at com.example.dell.cashregister.MainActivity$3.onCheckedChanged(MainActivity.java:101)
                                                                               at android.widget.CompoundButton.setChecked(CompoundButton.java:161)
                                                                               at android.widget.CompoundButton.toggle(CompoundButton.java:115)
                                                                               at android.widget.CompoundButton.performClick(CompoundButton.java:127)
                                                                               at android.view.View$PerformClick.run(View.java:20755)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5835)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

1 个答案:

答案 0 :(得分:0)

您确定使用static void show(Context context, UsbSerialPort port)方法初始化了活动,并为UsbSerialPort port传递了一个NonNull值吗?从日志中,似乎mPort变量尚未初始化。从查看代码时,只有在调用此方法时才能初始化它。

我的猜测是你试图在不调用此方法的情况下初始化Activity。出于此示例的目的,应仅使用show方法初始化活动(至少是第一次)。

我还看了一下你试图重新创建的例子,并且在那里声明使用静态变量进行端口引用是一种实现这个的hacky方式。对于一个快速的例子它应该没问题,但它可能会在某些情况下崩溃,如果你打算进一步使用它,最好找到一种不同的初始化方法。