下面列出了怎么用android.hardware.usb.UsbConstants的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Write single feature report
* @param buffer blob size of FEATURE_RPT_SIZE
*/
private void writeFeatureReport(byte[] buffer) throws IOException {
int bytesSentPackage = connection.controlTransfer(
UsbConstants.USB_DIR_OUT | TYPE_CLASS | RECIPIENT_INTERFACE,
HID_SET_REPORT, REPORT_TYPE_FEATURE << 8,
hidInterface.getId(),
buffer,
buffer.length, TIMEOUT);
if (bytesSentPackage < 0) {
throw new IOException("Can't write the data");
}
if (bytesSentPackage < FEATURE_RPT_SIZE) {
throw new IOException("Some of the data was not sent");
}
}
@Override
public @NonNull
Iso7816Connection openIso7816Connection() throws IOException {
UsbInterface ccidInterface = getInterface(UsbConstants.USB_CLASS_CSCID);
if (ccidInterface == null) {
throw new IOException("No CCID interface found!");
}
Pair<UsbEndpoint, UsbEndpoint> endpointPair = findEndpoints(ccidInterface, UsbConstants.USB_ENDPOINT_XFER_BULK);
if (endpointPair.first == null || endpointPair.second == null) {
throw new IOException("Unable to find endpoints!");
}
UsbDeviceConnection connection = openConnection();
if (connection == null) {
throw new IOException("exception in UsbManager.openDevice");
}
if (!connection.claimInterface(ccidInterface, true)) {
connection.close();
throw new IOException("Interface couldn't be claimed");
}
return new UsbIso7816Connection(connection, ccidInterface, endpointPair.first, endpointPair.second);
}
/**
* Creates and starts session for communication with yubikey using HID interface
* @return session for communication with yubikey (supported over USB only)
* @throws IOException if Keyboard HID interface or endpoints are not found
*/
public @NonNull
UsbHidConnection openHidKeyboardConnection() throws IOException {
UsbInterface hidInterface = getInterface(UsbConstants.USB_CLASS_HID);
if (hidInterface == null) {
throw new IOException("No HID interface found");
}
if (hidInterface.getInterfaceSubclass() != UsbConstants.USB_INTERFACE_SUBCLASS_BOOT) {
throw new IOException("No expected HID interface");
}
UsbDeviceConnection connection = openConnection();
if (connection == null) {
throw new IOException("exception in UsbManager.openDevice");
}
if (!connection.claimInterface(hidInterface, true)) {
connection.close();
throw new IOException("Interface couldn't be claimed");
}
return new UsbHidConnection(connection, hidInterface);
}
/**
* Gets bulkin and bulkout endpoints of specified interface
* @param usbInterface interface of usb device
* @return the pair of endpoints: in and out
*/
private Pair<UsbEndpoint, UsbEndpoint> findEndpoints(UsbInterface usbInterface, int type) {
UsbEndpoint endpointIn = null;
UsbEndpoint endpointOut = null;
for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
UsbEndpoint endpoint = usbInterface.getEndpoint(i);
if (endpoint.getType() == type) {
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
endpointIn = endpoint;
} else {
endpointOut = endpoint;
}
}
}
return new Pair<>(endpointIn, endpointOut);
}
private UsbHidDevice(UsbDevice usbDevice, UsbInterface usbInterface, UsbManager usbManager) {
mUsbDevice = usbDevice;
mUsbInterface = usbInterface;
mUsbManager= usbManager;
for (int i = 0; i < mUsbInterface.getEndpointCount(); i++) {
UsbEndpoint endpoint = mUsbInterface.getEndpoint(i);
int dir = endpoint.getDirection();
int type = endpoint.getType();
if (mInUsbEndpoint == null && dir == UsbConstants.USB_DIR_IN && type == UsbConstants.USB_ENDPOINT_XFER_INT) {
mInUsbEndpoint = endpoint;
}
if (mOutUsbEndpoint == null && dir == UsbConstants.USB_DIR_OUT && type == UsbConstants.USB_ENDPOINT_XFER_INT) {
mOutUsbEndpoint = endpoint;
}
}
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) throws IOException {
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) throw new IOException("Device not connected");
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
for (int i = 0; i < dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
} else {
out = tmpEndpoint;
}
}
connection.claimInterface(dongleInterface, true);
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out);
}
/**
* Request a device access permission if there is a MIDI interface in the device.
*
* @param device a USB device
*/
private void requestDevicePermissionIfNecessary(UsbDevice device) {
for (UsbDevice d : mRequestedDevices) {
if (d.getDeviceId() == device.getDeviceId()) {
// It is already requested.
return;
}
}
for (int i = 0; i < device.getInterfaceCount(); ++i) {
UsbInterface iface = device.getInterface(i);
if (iface.getInterfaceClass() == UsbConstants.USB_CLASS_AUDIO
&& iface.getInterfaceSubclass() == UsbMidiDeviceAndroid.MIDI_SUBCLASS) {
// There is at least one interface supporting MIDI.
mUsbManager.requestPermission(device,
PendingIntent.getBroadcast(ContextUtils.getApplicationContext(), 0,
new Intent(ACTION_USB_PERMISSION), 0));
mRequestedDevices.add(device);
break;
}
}
}
/**
* Returns the string descriptor bytes for the given index
* @param index index of the descriptor
* @return the string descriptor bytes for the given index.
*/
@CalledByNative
byte[] getStringDescriptor(int index) {
if (mConnection == null) {
return new byte[0];
}
byte[] buffer = new byte[255];
int type = UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_STANDARD;
int request = REQUEST_GET_DESCRIPTOR;
int value = (STRING_DESCRIPTOR_TYPE << 8) | index;
int read = mConnection.controlTransfer(type, request, value, 0, buffer, buffer.length, 0);
if (read < 0) {
return new byte[0];
}
return Arrays.copyOf(buffer, read);
}
@Override
protected void openInt(UsbDeviceConnection connection) throws IOException {
for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
UsbInterface usbIface = mDevice.getInterface(i);
if (!mConnection.claimInterface(usbIface, true)) {
throw new IOException("Could not claim data interface");
}
}
UsbInterface dataIface = mDevice.getInterface(mDevice.getInterfaceCount() - 1);
for (int i = 0; i < dataIface.getEndpointCount(); i++) {
UsbEndpoint ep = dataIface.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
mReadEndpoint = ep;
} else {
mWriteEndpoint = ep;
}
}
}
initialize();
setBaudRate(DEFAULT_BAUD_RATE);
}
public CdcAcmSerialDriver(UsbDevice device) {
mDevice = device;
mPorts = new ArrayList<>();
int controlInterfaceCount = 0;
int dataInterfaceCount = 0;
for( int i = 0; i < device.getInterfaceCount(); i++) {
if(device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_COMM)
controlInterfaceCount++;
if(device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA)
dataInterfaceCount++;
}
for( int port = 0; port < Math.min(controlInterfaceCount, dataInterfaceCount); port++) {
mPorts.add(new CdcAcmSerialPort(mDevice, port));
}
if(mPorts.size() == 0) {
mPorts.add(new CdcAcmSerialPort(mDevice, -1));
}
}
private void openSingleInterface() throws IOException {
// the following code is inspired by the cdc-acm driver in the linux kernel
mControlIndex = 0;
mControlInterface = mDevice.getInterface(0);
mDataInterface = mDevice.getInterface(0);
if (!mConnection.claimInterface(mControlInterface, true)) {
throw new IOException("Could not claim shared control/data interface");
}
for (int i = 0; i < mControlInterface.getEndpointCount(); ++i) {
UsbEndpoint ep = mControlInterface.getEndpoint(i);
if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) {
mControlEndpoint = ep;
} else if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
mReadEndpoint = ep;
} else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) {
mWriteEndpoint = ep;
}
}
if (mControlEndpoint == null) {
throw new IOException("No control endpoint");
}
}
@Override
protected void openInt(UsbDeviceConnection connection) throws IOException {
mIsRestrictedPort = mDevice.getInterfaceCount() == 2 && mPortNumber == 1;
if(mPortNumber >= mDevice.getInterfaceCount()) {
throw new IOException("Unknown port number");
}
UsbInterface dataIface = mDevice.getInterface(mPortNumber);
if (!mConnection.claimInterface(dataIface, true)) {
throw new IOException("Could not claim interface " + mPortNumber);
}
for (int i = 0; i < dataIface.getEndpointCount(); i++) {
UsbEndpoint ep = dataIface.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
mReadEndpoint = ep;
} else {
mWriteEndpoint = ep;
}
}
}
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
// setConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
// setParameters(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY);
}
/**
* Read single feature report
* @return blob size of FEATURE_RPT_SIZE
* @throws IOException
*/
private byte[] readFeatureReport() throws IOException {
byte[] bufferRead = new byte[FEATURE_RPT_SIZE];
int bytesRead = connection.controlTransfer(UsbConstants.USB_DIR_IN | TYPE_CLASS | RECIPIENT_INTERFACE, HID_GET_REPORT,
REPORT_TYPE_FEATURE << 8, hidInterface.getId(), bufferRead, bufferRead.length, TIMEOUT);
if (bytesRead < 0) {
throw new IOException("Can't read the data");
}
if (bytesRead < FEATURE_RPT_SIZE) {
throw new IOException("Size of blob is smaller than expected");
}
return bufferRead;
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
return null;
}
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE) || (device.getProductId() == PID_NANOX));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
public static String nameForClass(int classType) {
switch (classType) {
case UsbConstants.USB_CLASS_APP_SPEC:
return String.format("Application Specific 0x%02x", classType);
case UsbConstants.USB_CLASS_AUDIO:
return "Audio";
case UsbConstants.USB_CLASS_CDC_DATA:
return "CDC Control";
case UsbConstants.USB_CLASS_COMM:
return "Communications";
case UsbConstants.USB_CLASS_CONTENT_SEC:
return "Content Security";
case UsbConstants.USB_CLASS_CSCID:
return "Content Smart Card";
case UsbConstants.USB_CLASS_HID:
return "Human Interface Device";
case UsbConstants.USB_CLASS_HUB:
return "Hub";
case UsbConstants.USB_CLASS_MASS_STORAGE:
return "Mass Storage";
case UsbConstants.USB_CLASS_MISC:
return "Wireless Miscellaneous";
case UsbConstants.USB_CLASS_PER_INTERFACE:
return "(Defined Per Interface)";
case UsbConstants.USB_CLASS_PHYSICA:
return "Physical";
case UsbConstants.USB_CLASS_PRINTER:
return "Printer";
case UsbConstants.USB_CLASS_STILL_IMAGE:
return "Still Image";
case UsbConstants.USB_CLASS_VENDOR_SPEC:
return String.format("Vendor Specific 0x%02x", classType);
case UsbConstants.USB_CLASS_VIDEO:
return "Video";
case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
return "Wireless Controller";
default:
return String.format("0x%02x", classType);
}
}
public static String nameForEndpointType(int type) {
switch (type) {
case UsbConstants.USB_ENDPOINT_XFER_BULK:
return "Bulk";
case UsbConstants.USB_ENDPOINT_XFER_CONTROL:
return "Control";
case UsbConstants.USB_ENDPOINT_XFER_INT:
return "Interrupt";
case UsbConstants.USB_ENDPOINT_XFER_ISOC:
return "Isochronous";
default:
return "Unknown Type";
}
}
public static String nameForDirection(int direction) {
switch (direction) {
case UsbConstants.USB_DIR_IN:
return "IN";
case UsbConstants.USB_DIR_OUT:
return "OUT";
default:
return "Unknown Direction";
}
}
private static String nameForClass(UsbDevice usbDevice) {
int classType = usbDevice.getDeviceClass();
switch (classType) {
case UsbConstants.USB_CLASS_AUDIO:
return "Audio";
case UsbConstants.USB_CLASS_CDC_DATA:
return "CDC Control";
case UsbConstants.USB_CLASS_COMM:
return "Communications";
case UsbConstants.USB_CLASS_CONTENT_SEC:
return "Content Security";
case UsbConstants.USB_CLASS_CSCID:
return "Content Smart Card";
case UsbConstants.USB_CLASS_HID:
return "Human Interface Device";
case UsbConstants.USB_CLASS_HUB:
return "Hub";
case UsbConstants.USB_CLASS_MASS_STORAGE:
return "Mass Storage";
case UsbConstants.USB_CLASS_MISC:
return "Wireless Miscellaneous";
case UsbConstants.USB_CLASS_PHYSICA:
return "Physical";
case UsbConstants.USB_CLASS_PRINTER:
return "Printer";
case UsbConstants.USB_CLASS_STILL_IMAGE:
return "Still Image";
case UsbConstants.USB_CLASS_VENDOR_SPEC:
return String.format("Vendor Specific 0x%02x", classType);
case UsbConstants.USB_CLASS_VIDEO:
return "Video";
case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
return "Wireless Controller";
default:
return "";
}
}
private static String nameForClass(UsbDevice usbDevice) {
int classType = usbDevice.getDeviceClass();
switch (classType) {
case UsbConstants.USB_CLASS_AUDIO:
return "Audio";
case UsbConstants.USB_CLASS_CDC_DATA:
return "CDC Control";
case UsbConstants.USB_CLASS_COMM:
return "Communications";
case UsbConstants.USB_CLASS_CONTENT_SEC:
return "Content Security";
case UsbConstants.USB_CLASS_CSCID:
return "Content Smart Card";
case UsbConstants.USB_CLASS_HID:
return "Human Interface Device";
case UsbConstants.USB_CLASS_HUB:
return "Hub";
case UsbConstants.USB_CLASS_MASS_STORAGE:
return "Mass Storage";
case UsbConstants.USB_CLASS_MISC:
return "Wireless Miscellaneous";
case UsbConstants.USB_CLASS_PHYSICA:
return "Physical";
case UsbConstants.USB_CLASS_PRINTER:
return "Printer";
case UsbConstants.USB_CLASS_STILL_IMAGE:
return "Still Image";
case UsbConstants.USB_CLASS_VENDOR_SPEC:
return String.format("Vendor Specific 0x%02x", classType);
case UsbConstants.USB_CLASS_VIDEO:
return "Video";
case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
return "Wireless Controller";
default:
return "";
}
}
private static String nameForClass(UsbDevice usbDevice) {
int classType = usbDevice.getDeviceClass();
switch (classType) {
case UsbConstants.USB_CLASS_AUDIO:
return "Audio";
case UsbConstants.USB_CLASS_CDC_DATA:
return "CDC Control";
case UsbConstants.USB_CLASS_COMM:
return "Communications";
case UsbConstants.USB_CLASS_CONTENT_SEC:
return "Content Security";
case UsbConstants.USB_CLASS_CSCID:
return "Content Smart Card";
case UsbConstants.USB_CLASS_HID:
return "Human Interface Device";
case UsbConstants.USB_CLASS_HUB:
return "Hub";
case UsbConstants.USB_CLASS_MASS_STORAGE:
return "Mass Storage";
case UsbConstants.USB_CLASS_MISC:
return "Wireless Miscellaneous";
case UsbConstants.USB_CLASS_PHYSICA:
return "Physical";
case UsbConstants.USB_CLASS_PRINTER:
return "Printer";
case UsbConstants.USB_CLASS_STILL_IMAGE:
return "Still Image";
case UsbConstants.USB_CLASS_VENDOR_SPEC:
return String.format("Vendor Specific 0x%02x", classType);
case UsbConstants.USB_CLASS_VIDEO:
return "Video";
case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
return "Wireless Controller";
default:
return "";
}
}
public int controlTransferIn(int request, int value, int index, byte[] buffer) {
if (mUsbDeviceConnection == null) {
return -1;
}
return mUsbDeviceConnection.controlTransfer(UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_VENDOR, request,
value, index, buffer, buffer == null ? 0 : buffer.length, TIME_OUT);
}
public int controlTransferOut(int request, int value, int index, byte[] buffer) {
if (mUsbDeviceConnection == null) {
return -1;
}
return mUsbDeviceConnection.controlTransfer(UsbConstants.USB_DIR_OUT | UsbConstants.USB_TYPE_VENDOR, request,
value, index, buffer, buffer == null ? 0 : buffer.length, TIME_OUT);
}
void onColorChanged() {
final int red = mRed.getValue();
final int green = mGreen.getValue();
final int blue = mBlue.getValue();
mImageView.setBackgroundColor(Color.argb(255, red, green, blue));
if (mBlinkDevice != null) {
mUsbHandler.post(new Runnable() {
@Override
public void run() {
byte[] bytes = {0x01, 0x63, (byte) (red & 0xFF), (byte) (green & 0xFF), (byte) (blue & 0xFF), 0, 0, 0, 0};
mBlinkConn.controlTransfer(
UsbConstants.USB_TYPE_CLASS | UsbConstants.USB_DIR_OUT,
0x09, 1, 0, bytes, 9, 0);
}
});
}
// Publish new color over ROS
synchronized (mPublisherLock) {
if (mColorPublisher == null)
return;
std_msgs.ColorRGBA msg = mColorPublisher.newMessage();
msg.setA(255.0f);
msg.setR(red);
msg.setG(green);
msg.setB(blue);
mColorPublisher.publish(msg);
}
}
void onColorChanged() {
final int red = mRed.getValue();
final int green = mGreen.getValue();
final int blue = mBlue.getValue();
mImageView.setBackgroundColor(Color.argb(255, red, green, blue));
if (mBlinkDevice != null) {
mUsbHandler.post(new Runnable() {
@Override
public void run() {
byte[] bytes = {0x01, 0x63, (byte) (red & 0xFF), (byte) (green & 0xFF), (byte) (blue & 0xFF), 0, 0, 0, 0};
mBlinkConn.controlTransfer(
UsbConstants.USB_TYPE_CLASS | UsbConstants.USB_DIR_OUT,
0x09, 1, 0, bytes, 9, 0);
}
});
}
// Publish new color over ROS
synchronized (mPublisherLock) {
if (mColorPublisher == null)
return;
std_msgs.ColorRGBA msg = mColorPublisher.newMessage();
msg.setA(255.0f);
msg.setR(red);
msg.setG(green);
msg.setB(blue);
mColorPublisher.publish(msg);
}
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
return null;
}
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
/**
* Constructs a UsbMidiDeviceAndroid.
* @param manager
* @param device The USB device which this object is assocated with.
*/
UsbMidiDeviceAndroid(UsbManager manager, UsbDevice device) {
mConnection = manager.openDevice(device);
mEndpointMap = new SparseArray<UsbEndpoint>();
mRequestMap = new HashMap<UsbEndpoint, UsbRequest>();
mHandler = new Handler();
mUsbDevice = device;
mIsClosed = false;
mHasInputThread = false;
mNativePointer = 0;
for (int i = 0; i < device.getInterfaceCount(); ++i) {
UsbInterface iface = device.getInterface(i);
if (iface.getInterfaceClass() != UsbConstants.USB_CLASS_AUDIO
|| iface.getInterfaceSubclass() != MIDI_SUBCLASS) {
continue;
}
mConnection.claimInterface(iface, true);
for (int j = 0; j < iface.getEndpointCount(); ++j) {
UsbEndpoint endpoint = iface.getEndpoint(j);
if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
mEndpointMap.put(endpoint.getEndpointNumber(), endpoint);
}
}
}
// Start listening for input endpoints.
// This function will create and run a thread if there is USB-MIDI endpoints in the
// device. Note that because UsbMidiDevice is shared among all tabs and the thread
// will be terminated when the device is disconnected, at most one thread can be created
// for each connected USB-MIDI device.
startListen(device);
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
public static int doBulkTransfer(UsbDeviceConnection devConn, UsbEndpoint endpoint, byte[] buff, int timeout) {
int bytesTransferred = 0;
while (bytesTransferred < buff.length) {
byte[] remainingBuffer = new byte[buff.length - bytesTransferred];
if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
// Copy input data into the new buffer
System.arraycopy(buff, bytesTransferred, remainingBuffer, 0, remainingBuffer.length);
}
int res = devConn.bulkTransfer(endpoint, remainingBuffer,
remainingBuffer.length, timeout);
if (res < 0) {
// Failed transfer terminates the bulk transfer
res = -Errno.getErrno();
if (res != -110) {
// Don't print for ETIMEDOUT
System.err.println("Bulk Xfer failed: "+res);
}
return res;
}
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
// Copy output data into the original buffer
System.arraycopy(remainingBuffer, 0, buff, bytesTransferred, res);
}
bytesTransferred += res;
if (res < endpoint.getMaxPacketSize()) {
// A packet less than the maximum size for this endpoint
// indicates the transfer has ended
break;
}
}
return bytesTransferred;
}
private void initUsb(int bulkResponse)
{
mConnection = Mockito.mock(UsbDeviceConnection.class);
mDevice = Mockito.mock(UsbDevice.class);
// UsbInterface Mass storage device, Must be injected using a setter.
ifaceMocked = Mockito.mock(UsbInterface.class);
Mockito.when(ifaceMocked.getInterfaceClass()).thenReturn(UsbConstants.USB_CLASS_MASS_STORAGE);
Mockito.when(ifaceMocked.getInterfaceSubclass()).thenReturn(0x06);
Mockito.when(ifaceMocked.getInterfaceProtocol()).thenReturn(0x50);
Mockito.when(ifaceMocked.getEndpointCount()).thenReturn(0);
// UsbEndpoints IN,OUT. Must be injected using a setter
mockedInEndpoint = Mockito.mock(UsbEndpoint.class);
mockedOutEndpoint = Mockito.mock(UsbEndpoint.class);
// UsbDeviceConnection mocked methods
Mockito.when(mConnection.claimInterface(ifaceMocked, true)).thenReturn(true);
Mockito.when(mConnection.bulkTransfer(Mockito.any(UsbEndpoint.class), Mockito.any(byte[].class) ,Mockito.anyInt(), Mockito.anyInt())).thenReturn(bulkResponse);
// UsbDevice mocked methods
Mockito.when(mDevice.getInterfaceCount()).thenReturn(1);
// Initialize and inject dependencies
usbFacade = new UsbFacade(mDevice, mConnection);
usbFacade.setCallback(mCallback);
usbFacade.injectInterface(ifaceMocked);
usbFacade.injectInEndpoint(mockedInEndpoint);
usbFacade.injectOutEndpoint(mockedOutEndpoint);
}
private boolean openCH34X()
{
if(connection.claimInterface(mInterface, true))
{
Log.i(CLASS_ID, "Interface succesfully claimed");
}else
{
Log.i(CLASS_ID, "Interface could not be claimed");
return false;
}
// Assign endpoints
int numberEndpoints = mInterface.getEndpointCount();
for(int i=0;i<=numberEndpoints-1;i++)
{
UsbEndpoint endpoint = mInterface.getEndpoint(i);
if(endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK
&& endpoint.getDirection() == UsbConstants.USB_DIR_IN)
{
inEndpoint = endpoint;
}else if(endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK
&& endpoint.getDirection() == UsbConstants.USB_DIR_OUT)
{
outEndpoint = endpoint;
}
}
return init() == 0;
}