80,351
社区成员
发帖
与我相关
我的任务
分享
//寻找指定USB设备
private void findDevice(){
mUsbManager=(UsbManager) getSystemService(Context.USB_SERVICE);
if(mUsbManager==null){
Toast.makeText(this, "创建USBManager失败", Toast.LENGTH_SHORT).show();
return;
}
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
if(deviceList.isEmpty()){
Toast.makeText(this, "请连接USB设备", Toast.LENGTH_SHORT).show();
}
else{
Iterator<UsbDevice> it = deviceList.values().iterator();
while(it.hasNext()){
UsbDevice device = it.next();
delay(10);
if(device.getVendorId()==VendorID&&device.getProductId()==ProductID){
mUsbDevice=device;
Toast.makeText(this, "找到摄像头", Toast.LENGTH_SHORT).show();
break;
}
}
if(mUsbDevice==null){
Toast.makeText(this, "未找到摄像头,请连接USB设备", Toast.LENGTH_SHORT).show();
}
}
}
//寻找设备接口和输入输出端点
private void findInterfaceAndEndpoint(){
if(mUsbDevice==null){
return;
}
Log.d("接口信息", "接口数:"+mUsbDevice.getInterfaceCount());
mInterface=mUsbDevice.getInterface(0); //经测试该摄像头只有一个借口
if(mInterface==null){
Toast.makeText(this, "未找到接口", Toast.LENGTH_SHORT).show();
return;
}
Log.d("端点信息", "端点数:"+mInterface.getEndpointCount());
for(int i=0;i<mInterface.getEndpointCount();i++){
UsbEndpoint ep = mInterface.getEndpoint(i);
if(ep.getType()==UsbConstants.USB_ENDPOINT_XFER_CONTROL){
epControl=ep;
}
else if(ep.getType()==UsbConstants.USB_ENDPOINT_XFER_BULK){
if(ep.getDirection()==UsbConstants.USB_DIR_OUT){
epOut=ep;
Log.d("输出端点", "index:"+i+" "+"端点号"+ep.getEndpointNumber());
}
if(ep.getDirection()==UsbConstants.USB_DIR_IN){
epIn=ep;
Log.d("输入端点", "index:"+i+" "+"端点号"+ep.getEndpointNumber()+" 包大小"+ep.getMaxPacketSize());
}
}
}
}
//连接设备,获取操作权限
private String connectDevice(){
if(!(epOut==null||epIn==null)){
if(mUsbManager.hasPermission(mUsbDevice)){
mUsbDeviceConnection=mUsbManager.openDevice(mUsbDevice);
if(mUsbDeviceConnection==null){
Toast.makeText(this, "未成功连接设备", Toast.LENGTH_SHORT).show();
return "USB_INIT_FAILURE";
}
if(mUsbDeviceConnection.claimInterface(mInterface, true)){
// Toast.makeText(this, "设备连接成功", Toast.LENGTH_SHORT).show();
int a = mUsbDeviceConnection.controlTransfer(0x40, 0xB2, 0, 0, null, 0, 0);
int b = mUsbDeviceConnection.controlTransfer(0x40, 0xB4, 0, 0, null, 0, 0);
if(a<0||b<0){
Toast.makeText(this, "控制传输失败",Toast.LENGTH_SHORT).show();
return "USB_INIT_FAILURE";
}
}
else{
mUsbDeviceConnection.close();
return "USB_INIT_FAILURE";
}
}
}
return "USB_INIT_SUCCESS";
}
/*//控制传输,设备初始化,清空设备段缓存
private void deviceControlTransfer(){
mUsbDeviceConnection.controlTransfer(0x40, 0xB2, 0, 0, null, 0, 0);
mUsbDeviceConnection.controlTransfer(0x40, 0xB4, 0, 0, null, 0, 0);
}*/
//获取图像数据
private void getUsbData(){
int a = mUsbDeviceConnection.controlTransfer(0x40, 0xB4, 0, 0, null, 0, 0);
int b = mUsbDeviceConnection.controlTransfer(0x40, 0xB5, 0, 0, null, 0, 0);
if(a<0||b<0){
Toast.makeText(this, "控制传输失败", Toast.LENGTH_SHORT).show();
}
int len = mUsbDeviceConnection.bulkTransfer(epIn, buffer,buffer.length, 0);
Log.d("接收数据信息","长度:"+len);
}