美文网首页程序员
Android之USB数据通信

Android之USB数据通信

作者: aiBarry | 来源:发表于2019-10-09 18:08 被阅读0次

一.USB串口通信步骤:

  1. 连接USB设备

  2. 获取USB设备的权限

  3. 打开设备openDevice(UsbDevice device)

  4. 获取UsbInterface

  5. 通过claimInterface(UsbInterface,true)找到设备接口

  6. 获取USB传出节点口(UsbEndpoint),即Host

  7. 进行交互

二.Android开发中USB串口通信开发主要涉及到以下几个类及相应的方法:

1 ,UsbManager:负责管理USB设备的类,你可以在相应代码中通过以下方法获得

//获取UsbManager实例方法

UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

该类提供的主要方法有:

  1. getDeviceList()

获得设备列表,返回的是一个HashMap.;

  1. hasPermission(UsbDevice device)

判断你的应用程序是否有接入此USB设备的权限,如果有则返回真,否则返回false.

  1. openDevice(UsbDevice device)

打开USB设备,以便向此USB设备发送和接受数据,返回一个关于此USB设备的连接。

  1. requestPermission(UsbDevice device, PendingIntent pi)

向USB设备请求临时的接入权限。

2,UsbDevice:一个USB设备对象,每个设备一般包括一个接口,也可能有多个,每个接口又包含节点用来与此设备传输数据。主要方法有:

  1. getDeviceClass()

返回此USB设备的类别,用一个整型来表示。

  1. getDeviceId()

返回唯一标识此设备的ID号,也用一个整型来表示。

  1. getDeviceName()

返回此设备的名称,用一个字符串来表示。

  1. getDeviceProtocol()

返回此设备的协议类别,用一个整型来表示。

  1. getDeviceSubclass()

返回此设备的子类别,用一个整型来表示。

  1. getVendorId()

返回生产商ID

  1. getProductId()

返回产品ID

  1. getInterfaceCount()

返回此设备的接口数量

  1. getInterface(int index)

得到此设备的一个接口,返回一个UsbInterface。

3,UsbInterface:代表USB设备的一个接口(物理接口),UsbInterface本身是一个类,此类的主要方法有以下:

  1. getId()

得到给接口的id号。

  1. getInterfaceClass()

得到该接口的类别。

  1. getInterfaceSubclass()

得到该接口的子类。

  1. getInterfaceProtocol()

得到该接口的协议类别。

  1. getEndpointCount()

获得关于此接口的节点数量。

  1. getEndpoint(int index)

对于指定的index获得此接口的一个节点,返回一个UsbEndpoint.

4, UsbEndpoint:代表一个接口的某个节点的类。该类主要方法:

  1. getAddress()

获得此节点的地址

  1. getAttributes()

获得此节点的属性

  1. getDirection()

获得此节点的数据传输方向

5 ,UsbDeviceConnection:代表USB连接的一个类。用此连接可以想USB设备发送和接收数据,主要方法有:

1)bulkTransfer(UsbEndpoint endpoint, byte[] buffer, int length, int timeout)

通过给定的endpoint来进行大量的数据传输,传输的方向取决于该节点的方向,buffer是要发送或接收的字节数组,length是该字节数组的长度。传输成功则返回所传输的字节数组的长度,失败则返回负数。

2)controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)

该方法通过0节点向此设备传输数据,传输的方向取决于请求的类别,如果requestType为USB_DIR_OUT则为写数据,USB_DIR_IN, 则为读数据

以上介绍资料主要来自博文: http://www.osedu.net/article/linux/2014-04-16/678.html

—-示例代码——

public class UsbTestActivity extends Activity implements View.OnClickListener {

//设备列表

private HashMap<String, UsbDevice> deviceList;

//从设备读数据

private Button read_btn;

//给设备写数据(发指令)

private Button write_btn;

//USB管理器:负责管理USB设备的类

private UsbManager manager;

//找到的USB设备

private UsbDevice mUsbDevice;

//代表USB设备的一个接口

private UsbInterface mInterface;

private UsbDeviceConnection mDeviceConnection;

//代表一个接口的某个节点的类:写数据节点

private UsbEndpoint usbEpOut;

//代表一个接口的某个节点的类:读数据节点

private UsbEndpoint usbEpIn;

//要发送信息字节

private byte[] sendbytes;

//接收到的信息字节

private byte[] receiveytes;

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_usb);

    initUsbData();

    initViews();

}

private void initUsbData() {

    // 获取USB设备

    manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    //获取到设备列表

    deviceList = manager.getDeviceList();

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

    while (deviceIterator.hasNext()) {

        Log.e("ldm", "vid=" + usb.getVendorId() + "---pid=" + usb.getProductId());

        //if (mVendorID == usb.getVendorId() && mProductID == usb.getProductId()) {//找到指定设备

        mUsbDevice = deviceIterator.next();

        }

        // }

    }

    //获取设备接口

    for (int i = 0; i < mUsbDevice.getInterfaceCount(); ) {

        // 一般来说一个设备都是一个接口,你可以通过getInterfaceCount()查看接口的个数

        // 这个接口上有两个端点,分别对应OUT 和 IN

        UsbInterface usbInterface = mUsbDevice.getInterface(i);

        mInterface = usbInterface;

        break;

    }

    //用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯

    if (mInterface.getEndpoint(1) != null) {

        usbEpOut = mInterface.getEndpoint(1);

    }

    if (mInterface.getEndpoint(0) != null) {

        usbEpIn = mInterface.getEndpoint(0);

    }

    if (mInterface != null) {

        // 判断是否有权限

        if (manager.hasPermission(mUsbDevice)) {

            // 打开设备,获取 UsbDeviceConnection 对象,连接设备,用于后面的通讯

            mDeviceConnection = manager.openDevice(mUsbDevice);

            if (mDeviceConnection == null) {

                return;

            }

            if (mDeviceConnection.claimInterface(mInterface, true)) {

                showTmsg("找到设备接口");

            } else {

                mDeviceConnection.close();

            }

        } else {

            showTmsg("没有权限");

        }

    } else {

        showTmsg("没有找到设备接口!");

    }

}

private void initViews() {

    this.read_btn = (Button) findViewById(R.id.read_btn);

    this.write_btn = (Button) findViewById(R.id.write_btn);

    this.read_btn.setOnClickListener(this);

    this.write_btn.setOnClickListener(this);

}

@Override

public void onClick(View view) {

    switch (view.getId()) {

        case R.id.write_btn:

            sendToUsb("按照规则给设备发指令!");

            break;

        case R.id.read_btn:

            readFromUsb();

            break;

    }

}

private void sendToUsb(String content) {

    sendbytes = content.getBytes();

    int ret = -1;

    // 发送准备命令

    ret = mDeviceConnection.bulkTransfer(usbEpOut, sendbytes, sendbytes.length, 5000);

    showTmsg("指令已经发送!");

    // 接收发送成功信息(相当于读取设备数据)

    receiveytes = new byte[128];  //根据设备实际情况写数据大小

    ret = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 10000);

// result_tv.setText(String.valueOf(ret));

    Toast.makeText(this, String.valueOf(ret), Toast.LENGTH_SHORT).show();

}

private void readFromUsb() {

    //读取数据2

    int outMax = usbEpOut.getMaxPacketSize();

    int inMax = usbEpIn.getMaxPacketSize();

    ByteBuffer byteBuffer = ByteBuffer.allocate(inMax);

    UsbRequest usbRequest = new UsbRequest();

    usbRequest.initialize(mDeviceConnection, usbEpIn);

    usbRequest.queue(byteBuffer, inMax);

    if (mDeviceConnection.requestWait() == usbRequest) {

        byte[] retData = byteBuffer.array();

        try {

            showTmsg("收到数据:" + new String(retData, "UTF-8"));

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

    }

}

//文字提示方法

private void showTmsg(String msg) {

    Toast.makeText(UsbTestActivity.this, msg, Toast.LENGTH_SHORT).show();

}

}

另外要与USB通信,在开发项目的配置上还需要注意:

1,添加相应权限:

<uses-permission android:name="android.permission.HARDWARE_TEST" />

2,AndroidManifest.xml中添加uses-feature过滤所有你设备不支持的应用:

<uses-feature android:name="android.hardware.usb.host" android:required="true"/>

3, SDK必须是12以上的,因为从 Android3.1开始,才正式支持USB Host相应开发。

4,在AndroidManifext.xml中对操作USB对应的Activity配置做修改,添加USB_DEVICE_ATTACHED与:

<activity android:name=".UsbTestActivity">

        <intent-filter>

            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />

        </intent-filter>
        <meta-data

android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"

            android:resource="@xml/device_filter" />

    </activity>

—–@xml/device_filter—–

<?xml version="1.0" encoding="utf-8"?>

<resources>

<!-- 以下内容的 vendor-id、product-id就是USB的vid和pid了,填写自己设备对应的数据->

<usb-device vendor-id="1155" product-id="22352"/>

</resources>

参考CSDN:https://blog.csdn.net/true100/article/details/51791929

相关文章

网友评论

    本文标题:Android之USB数据通信

    本文链接:https://www.haomeiwen.com/subject/bjngpctx.html