Android USB转串口通信

一、引用

1、Git上最火的USB转串口通信
2、Android之USB转串口通信
3、安卓开发中的USB转串口通讯

二、截图

废话不多说,先上图,micro usb -> usb 连接的测试温度的外设(其实是个测试粮油品质的,还有TPM值等等)


Android USB转串口通信
usb_connect.png

三、流程

1、mainfest中注册监听USB拔插动作并且过滤对应vid,pid的设备。这个是静态的,在下面实例中用的是动态的,具体可以参考引用中的第【2】个。
2、查找所有的USB设备
3、动态注册需要用的USB设备权限
4、连接已注册的USB设备,并设置连接参数
5、设置返回监听,并对话
6、按照不同的协议解析byte[]数据获得对应数据(在此不表)
7、关闭连接等

四、代码

0、配置:git上的案例,把其中usbSerialForAndroid的这个module拿下来,关联到自己的工程上面去

build.gradle-app

dependencies {
    compile project(':usbSerialForAndroid')
}

settings.gradle

include ':app', 'usbSerialForAndroid'

1、动态监听USB拔插动作+USB注册动作

private String USB_PERMISSION = "xxxxxxxxxx.usb.permission";
private PendingIntent mPrtPermissionIntent; //获取外设权限的意图

/**
     * 动态注册usb广播,拔插动作,注册动作
     * */
    private void register(){
        //注册在此service下的receiver的监听的action
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        intentFilter.addAction(USB_PERMISSION);
        registerReceiver(usbReceiver, intentFilter);//注册receiver


        //通知监听外设权限注册状态
        //PendingIntent:连接外设的intent
        //ask permission
        mPrtPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(USB_PERMISSION), 0);
    }

private BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            String action = intent.getAction();

            // USB注册动作
            if (USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if ((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) != null) {
                            // usbDev = (UsbDevice)
                            // intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                            // after request dev permission and granted
                            // pemission , connect printer by usb
                            LogUtil.i("after request dev permission and granted pemission , connect printer by usb.");
                            getUsbInfo(mUsbSerialPort.getDriver().getDevice());
                        } else {
                            LogUtil.e("usb device suddenly disappera.");
                            ToastUtil.showShort(instance,"USB外设意外消失。");
                        }
                    } else {
                        LogUtil.e("usb permission granted fail.");
                        ToastUtil.showShort(instance, "USB权限注册失败。");
                    }
                }
            }
            // USB拔插动作
            else if(UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)
                    || UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)){
                LogUtil.i("USB 插入...");
                search();
            }
        }
    };

2、查询所有USB设备

//查询设备
    private void search(){
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        List<UsbSerialDriver> drivers =
                UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);

        //try get enable printer dev
        if (drivers.size() > 0) {
            usbDevicesList.clear();
            for(UsbSerialDriver driver : drivers){
                usbDevicesList.addAll(driver.getPorts());
            }
            adapter.notifyDataSetChanged();
        }else{
            LogUtil.e("not find device.");
            return;
        }
    }

3、动态注册需要用的USB设备权限(会走到1中的receiver中)

 @Override
            public void onItemClick(View view, int position) {
                mUsbSerialPort = usbDevicesList.get(position);
                RequestNormalPermission(usbManager, mUsbSerialPort.getDriver().getDevice());
            }
   /**
     * 请求权限:一般来说有弹框
     */
    public  void RequestNormalPermission(UsbManager usbManager,UsbDevice device) {
        if (!usbManager.hasPermission(device)) {
            // ask has dev permission,pop dialog
            LogUtil.d("printer dev has no permission,try request it.");
            ToastUtil.showShort(this,"printer dev has no permission,try request it.");
            usbManager.requestPermission(device, mPrtPermissionIntent);// will recall mReceiver
        } else {
            // when dev has granted permission , connect printer by usb
            LogUtil.d("printer dev has granted permission,connect usb.");
            ToastUtil.showShort(this, "USB权限注册成功。");
            getUsbInfo(mUsbSerialPort.getDriver().getDevice());
        }
    }

4、连接已注册的USB设备,并设置连接参数 + 5、设置返回监听,并对话 + 7、关闭连接等

/**
     * 获得授权USB的基本信息
     * 1、USB接口,一般是第一个
     * 2、USB设备的输入输出端
     *
     * */
    private void getUsbInfo(UsbDevice usbDevice){
        StringBuilder sb = new StringBuilder();
        if(Build.VERSION.SDK_INT >= 23){
            sb.append(String.format("VID:%04X  PID:%04X  ManuFN:%s  PN:%s V:%s",
                    usbDevice.getVendorId(),
                    usbDevice.getProductId(),
                    usbDevice.getManufacturerName(),
                    usbDevice.getProductName(),
                    usbDevice.getVersion()
            ));
        }
        else if(Build.VERSION.SDK_INT >= 21){
            sb.append(String.format("VID:%04X  PID:%04X  ManuFN:%s  PN:%s",
                    usbDevice.getVendorId(),
                    usbDevice.getProductId(),
                    usbDevice.getManufacturerName(),
                    usbDevice.getProductName()
            ));
        }
        else{
            sb.append(String.format("VID:%04X  PID:%04X",
                    usbDevice.getVendorId(),
                    usbDevice.getProductId()
                    ));
        }


        tv_usb.setText(sb.toString());

        connect();//连接
    }

/**
     * usb设备的连接
     * */
    private void connect(){
        LogUtil.i("usb connect...");
        usbDeviceConnection = null;
        usbDeviceConnection = usbManager.openDevice(mUsbSerialPort.getDriver().getDevice());
        if(usbDeviceConnection == null){
            ll_usb_connect.setVisibility(View.GONE);
            tv_usb.setText(tv_usb.getText().toString() + " 连接失败!!!");
        }else{
            tv_usb.setText(tv_usb.getText().toString() + " 连接成功。");
            ll_usb_connect.setVisibility(View.VISIBLE);
            tv_connect_state.setText("USB通信");
            tv_receive.setText("");
            et_send.setText("01 03 00 01 00 01 D5 CA");

            setConnectionParam();
            onDeviceStateChange();
        }

    }

/**
     * 设置通讯参数
     * */
    private void setConnectionParam(){
        try {
            if(mUsbSerialPort.getDriver().getDevice().getInterfaceCount() > 0){

                mUsbSerialPort.open(usbDeviceConnection);
                mUsbSerialPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

                StringBuilder sb = new StringBuilder();

                sb.append( "\n CD  - Carrier Detect = "+mUsbSerialPort.getCD());
                sb.append( "\n CTS - Clear To Send = "+mUsbSerialPort.getCTS());
                sb.append( "\n DSR - Data Set Ready = "+mUsbSerialPort.getDSR());
                sb.append( "\n DTR - Data Terminal Ready = "+mUsbSerialPort.getDTR());
                sb.append( "\n DSR - Data Set Ready = "+mUsbSerialPort.getDSR());
                sb.append( "\n RI  - Ring Indicator = "+mUsbSerialPort.getRI());
                sb.append( "\n RTS - Request To Send = "+mUsbSerialPort.getRTS());

                tv_connect_state.setText(sb.toString());

                try {
                    mUsbSerialPort.setDTR(true);
                }catch (IOException x){
                    LogUtil.e("IOException DTR: " + x.getMessage());
                }
                try {
                    mUsbSerialPort.setRTS(true);
                }catch (IOException x){
                    LogUtil.e("IOException RTS: " + x.getMessage());
                }
            }
            //无通讯接口
            else{
                tv_connect_state.setText("该USB无通讯接口");
            }



        } catch (IOException e) {
            LogUtil.e("Error setting up device: " + e.getMessage());
            tv_connect_state.setText("Error opening device: " + e.getMessage());
            try {
                mUsbSerialPort.close();
            } catch (IOException e2) {
                // Ignore.
            }
            mUsbSerialPort = null;
            return;
        }

    }


    public boolean sendData(byte[] data) {
        LogUtil.i("sendData:"+Arrays.toString(data));
        if (mSerialIoManager != null) {
            mSerialIoManager.writeAsync(data);
        }
        return false;
    }

    private final SerialInputOutputManager.Listener mListener =
            new SerialInputOutputManager.Listener() {

                @Override
                public void onRunError(Exception e) {
                    LogUtil.d("Runner stopped.");
                }

                @Override
                public void onNewData(final byte[] data) {
                    LogUtil.i("onReceiver data="+Arrays.toString(data));
                    instance.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_receive.setText(HexUtil.bytesToHexString(data));
                        }
                    });
                }
            };


    /**
     * usb设备断开连接
     * */
    private void disconnect(){
        LogUtil.e("usb disconnect...");
        stopIoManager();
        if (mUsbSerialPort != null) {
            try {
                mUsbSerialPort.close();
            } catch (IOException e) {
                // Ignore.
            }
            mUsbSerialPort = null;
        }

        //usbdevice usbmanager
    }


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

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

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




    @Override
    public void onDestroy() {
        unregisterReceiver(usbReceiver);
        usbReceiver = null;
        disconnect();

        super.onDestroy();
    }

五、其他

参数意义

1 载波检测 DCD(Data Carrier Detect)
2 接收数据 RXD(Received Data)
3 发送数据 TXD(Transmit Data)
4 数据终端准备好 DTR(Data Terminal Ready)
5 信号地 SG(Signal Ground)
6 数据准备好 DSR(Data Set Ready)
7 请求发送 RTS(Request To Send)
8 清除发送 CTS(Clear To Send)
9 振铃提示 RI(Ring Indicator)

支持USB芯片种类

1、CDC ACM
2、CH34X
3、CP21XX
4、FTDI
5、Common USB

波特率参数等

这里是写死的,具体得看设备

上一篇:c-使用ASCII值确定A是否为B的置换


下一篇:Android xml数据的读取和写入(sax,pull,dom,xstream,jsoup)