Android USB通信-实现lsusb
Usb分为host模式和guest模式。顾名思义:Guest为客人,host为主人,当然这里是第一人称。一般情况下usb是处于guest模式。
现在的Android也支持了host模式,Android为 host 外接usb设备。在Android的api中guest模式称为Accessory,不过意思是一样的。我这里以host模式为重点,实现一下以前只能在C层实现的USB通信。
Android源码中提供了AdbTest和MissileLauncher两个USB通信的例子,位于development/samples/USB中。(表格来自:http://www.usb.org/developers/defined_class)
AdbTest是打印从Android设备log的应用程序,需要另外一个Android设备连接到该设备上。(补张图:开发板连接小米手机)
This program serves as an example of the following USB host features:
- Matching devices based on interface class, subclass and protocol (see device_filter.xml)
- Asynchronous IO on bulk endpoints
MissileLauncher是一个控制USB连接的模拟火箭的程序,关于USB的知识点有:
This program serves as an example of the following USB host features:
- filtering for multiple devices based on vendor and product IDs (see device_filter.xml)
- Sending control requests on endpoint zero that contain data
- Receiving packets on an interrupt endpoint using a thread that calls
UsbRequest.queue and UsbDeviceConnection.requestWait()
编写USB程序无需考虑底层如何实现的,直接根据USB协议来编码就好,这是何等的享受。以前一直纠结于Android中没有libusb如何是好,现在这个顾虑被打消了,可以安安心心编写USB通话的代码了。
从UsbDevice中解析出lsusb命令所显示的信息
private UsbManager mManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// check for existing devices
for (UsbDevice device : mManager.getDeviceList().values()) {
lsusb(device);
}
}
/**
* get lsusb 信息
* @param device
*/
private static void lsusb(UsbDevice device) {
if(device == null)
return;
String deviceName = device.getDeviceName();
String[] deviceNameArray = deviceName.split("/");
toLsusbString(
deviceNameArray[deviceNameArray.length - 2],
deviceNameArray[deviceNameArray.length - 1],
String.format("%04x", device.getVendorId()),
String.format("%04x", device.getProductId()),
"see:www.linux-usb.org/usb.ids"); // 由于Android系统中没有带usb.ids,这里也只要给出一个网址。
}
private static String toLsusbString(String bus, String device,
String idVendor, String idProduct, String other) {
// Bus 002 Device 002: ID 192f:0416 Avago Technologies, Pte.
String str = "Bus " + bus + " Device " + device + ": ID " + idVendor
+ ":" + idProduct + " " + other;
Log.i(LOG_TAG, str);
return str;
}
输出截图:
<完>