android.hardware.usb.UsbConstants Java Examples

The following examples show how to use android.hardware.usb.UsbConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Cp21xxSerialDriver.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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);
        }
 
Example #2
Source File: UsbHidDevice.java    From UsbHid with MIT License 6 votes vote down vote up
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;
        }
    }
}
 
Example #3
Source File: UsbSession.java    From yubikit-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #4
Source File: UsbSession.java    From yubikit-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: UsbSession.java    From yubikit-android with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: UsbHidConnection.java    From yubikit-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }

}
 
Example #7
Source File: BTChipTransportAndroidHID.java    From xmrwallet with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: UsbMidiDeviceFactoryAndroid.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example #9
Source File: UsbMidiDeviceAndroid.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #10
Source File: Ch34xSerialDriver.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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);
}
 
Example #11
Source File: CdcAcmSerialDriver.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
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));
    }
}
 
Example #12
Source File: CdcAcmSerialDriver.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
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");
    }
}
 
Example #13
Source File: UsbHelper.java    From sample-usbenum with Apache License 2.0 5 votes vote down vote up
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";
    }
}
 
Example #14
Source File: UsbUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
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 "";
    }
}
 
Example #15
Source File: MainActivity.java    From astrobee_android with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #16
Source File: BTChipTransportAndroid.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
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);
       }
}
 
Example #17
Source File: UsbMidiDeviceAndroid.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: UsbUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
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 "";
    }
}
 
Example #19
Source File: BTChipTransportAndroid.java    From WalletCordova with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
       }
}
 
Example #20
Source File: XferUtils.java    From USBIPServerForAndroid with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: UsbFacadeTest.java    From Pincho-Usb-Mass-Storage-for-Android with MIT License 5 votes vote down vote up
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);
}
 
Example #22
Source File: CH34xSerialDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
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;
}
 
Example #23
Source File: UsbSerialDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
public static boolean isCdcDevice(UsbDevice device)
{
    int iIndex = device.getInterfaceCount();
    for(int i=0;i<=iIndex-1;i++)
    {
        UsbInterface iface = device.getInterface(i);
        if(iface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA)
            return true;
    }
    return false;
}
 
Example #24
Source File: UsbSerialDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
@Override
public void doRun()
{
    UsbRequest request = connection.requestWait();
    if(request != null && request.getEndpoint().getType() == UsbConstants.USB_ENDPOINT_XFER_BULK
            && request.getEndpoint().getDirection() == UsbConstants.USB_DIR_IN)
    {
        byte[] data = serialBuffer.getDataReceived();

        // FTDI devices reserves two first bytes of an IN endpoint with info about
        // modem and Line.
        if(isFTDIDevice())
        {
            ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.checkModemStatus(data); //Check the Modem status
            serialBuffer.clearReadBuffer();

            if(data.length > 2)
            {
                data = FTDISerialDevice.adaptArray(data);
                onReceivedData(data);
            }
        }else
        {
            // Clear buffer, execute the callback
            serialBuffer.clearReadBuffer();
            onReceivedData(data);
        }
        // Queue a new request
        requestIN.queue(serialBuffer.getReadBuffer(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE);
    }
}
 
Example #25
Source File: CP2102SerialDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
private boolean openCP2102()
{
    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
        {
            outEndpoint = endpoint;
        }
    }


    // Default Setup
    if(setControlCommand(CP210x_IFC_ENABLE, CP210x_UART_ENABLE, null) < 0)
        return false;
    setBaudRate(DEFAULT_BAUDRATE);
    if(setControlCommand(CP210x_SET_LINE_CTL, CP210x_LINE_CTL_DEFAULT,null) < 0)
        return false;
    setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
    if(setControlCommand(CP210x_SET_MHS, CP210x_MHS_DEFAULT, null) < 0)
        return false;

    return true;
}
 
Example #26
Source File: CDCSerialDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
private boolean openCDC()
{
    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;
        }
    }

    if(outEndpoint == null || inEndpoint == null)
    {
        Log.i(CLASS_ID, "Interface does not have an IN or OUT interface");
        return false;
    }

    // Default Setup
    setControlCommand(CDC_SET_LINE_CODING, 0, getInitialLineCoding());
    setControlCommand(CDC_SET_CONTROL_LINE_STATE, CDC_CONTROL_LINE_ON, null);

    return true;
}
 
Example #27
Source File: CDCSerialDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
private static int findFirstCDC(UsbDevice device)
{
    int interfaceCount = device.getInterfaceCount();

    for (int iIndex = 0; iIndex < interfaceCount; ++iIndex)
    {
        if (device.getInterface(iIndex).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA)
        {
            return iIndex;
        }
    }

    Log.i(CLASS_ID, "There is no CDC class interface");
    return -1;
}
 
Example #28
Source File: CP2130SpiDevice.java    From UsbSerial with MIT License 5 votes vote down vote up
private boolean openCP2130()
{
    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
        {
            outEndpoint = endpoint;
        }
    }

    return true;
}
 
Example #29
Source File: UsbHidConnection.java    From yubikit-android with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: BTChipTransportAndroid.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
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);
       }
}