android串口通信-rs232

初始化usb对象以及权限申请

 		UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        UsbDevice device = null;
        for (UsbDevice d : usbManager.getDeviceList().values()) {
            device = d;
        }
        UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
        if (driver == null) {
            driver = CustomProber.getCustomProber().probeDevice(device);
        }
        UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
        if (usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(driver.getDevice())) {
            usbPermission = UsbPermission.Requested;
            PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
            usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
            return;
        }
        if (usbConnection == null) {
            if (!usbManager.hasPermission(driver.getDevice()))
                Log.i(TAG, "connection failed: permission denied");
            else
                Log.i(TAG, "connection failed: open failed");
            return;
        }

串口线程

public class GasThread implements Runnable{
    private static final String TAG = GasThread.class.getSimpleName();
    private GasCallback mGasCallback;
    private int mReadTimeout = 0;
    private static final int WRITE_WAIT_MILLIS = 2000;
    private UsbSerialPort mSerialPort;
    private State mState = State.STOPPED;
    private int index=0;
    byte[] outData=null;
    private final Object mReadBufferLock = new Object();
    private static final int BUFSIZ = 4096;
    private ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
    public enum State {
        STOPPED,
        RUNNING,
        STOPPING
    }

    public GasThread(GasCallback gasCallback, UsbSerialDriver driver, UsbDeviceConnection usbConnection) {
        mGasCallback=gasCallback;
        mSerialPort=driver.getPorts().get(2);
        try {
            mSerialPort.open(usbConnection);
            mSerialPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        } catch (Exception e) {
            Log.d(TAG,"connection failed: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        synchronized (this) {
            if (getState() != State.STOPPED) {
                throw new IllegalStateException("Already running");
            }
            mState = State.RUNNING;
        }
        try {
            while (true) {
                if (getState() != State.RUNNING) {
                    Log.i(TAG, "Stopping mState=" + getState());
                    break;
                }
                step();
            }
        } catch (Exception e) {
            Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
            if (mGasCallback != null) {
                mGasCallback.onGasError(e);
            }
        } finally {
            synchronized (this) {
                mState = State.STOPPED;
                Log.i(TAG, "Stopped");
            }
        }
    }

    public  synchronized State getState() {
        return mState;
    }

    private synchronized void step() throws IOException {
        byte[] buffer = null;
        synchronized (mReadBufferLock) {
            buffer = mReadBuffer.array();
        }
        int len = mSerialPort.read(buffer, mReadTimeout);
        if (len > 0) {
            if (index==0){
                outData=new byte[24];
            }
            //Log.d(TAG, "Read data len=" + len);
            if (mGasCallback != null) {
                try {
                    System.arraycopy(buffer, 0, outData, index, len);
                    index=index+len;
                }catch (ArrayIndexOutOfBoundsException e){
                    System.arraycopy(buffer, 0, outData, index-1, len);
                    index=index-1+len;
                }
                if (index==24){
                    mGasCallback.onGasRecv(outData);
                    outData=null;
                    index=0;
                }
            }
        }
    }

    public synchronized void stop() {
        if (getState() == State.RUNNING) {
            Log.i(TAG, "Stop requested");
            mState = State.STOPPING;
        }
    }

    public void send(String str){
        byte[] data=hexToByteArray(str);
        try {
            mSerialPort.write(data, WRITE_WAIT_MILLIS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void toSleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你丶快乐吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值