Java Code Examples for android.hardware.usb.UsbDeviceConnection#claimInterface()

The following examples show how to use android.hardware.usb.UsbDeviceConnection#claimInterface() . 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: 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 2
Source File: FtdiSerialDriver.java    From Arduino-Serial-Controller with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 3
Source File: Usb.java    From android-stm32-dfu-programmer with Apache License 2.0 6 votes vote down vote up
public void setDevice(UsbDevice device) {
    mDevice = device;

    // The first interface is the one we want
    mInterface = device.getInterface(0);    // todo check when changing if alternative interface is changing

    if (device != null) {
        UsbDeviceConnection connection = mUsbManager.openDevice(device);
        if (connection != null && connection.claimInterface(mInterface, true)) {
            Log.i(TAG, "open SUCCESS");
            mConnection = connection;

            // get the bcdDevice version
            byte[] rawDescriptor = mConnection.getRawDescriptors();
            mDeviceVersion = rawDescriptor[13] << 8;
            mDeviceVersion |= rawDescriptor[12];

            Log.i("USB", getDeviceInfo(device));
        } else {
            Log.e(TAG, "open FAIL");
            mConnection = null;
        }
    }
}
 
Example 4
Source File: FtdiSerialDriver.java    From PodEmu with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 5
Source File: FtdiSerialDriver.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 6
Source File: FtdiSerialDriver.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 7
Source File: FtdiSerialDriver.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 8
Source File: FtdiSerialDriver.java    From usb-with-serial-port with Apache License 2.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                L.INSTANCE.d("claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 9
Source File: FtdiSerialDriver.java    From OkUSB with Apache License 2.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 10
Source File: MainActivity.java    From astrobee_android with Apache License 2.0 6 votes vote down vote up
protected void setupUsb(UsbDevice device) {
    UsbInterface inf = device.getInterface(0);
    UsbDeviceConnection conn = mUsbManager.openDevice(device);
    if (conn == null) {
        Log.wtf("MainActivity", "unable to open device?");
        return;
    }

    if (!conn.claimInterface(inf, true)) {
        conn.close();
        Log.wtf("MainActivity", "unable to claim interface!");
        return;
    }

    mBlinkDevice = device;
    mBlinkConn = conn;
}
 
Example 11
Source File: FtdiSerialDriver.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 12
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 13
Source File: FtdiSerialDriver.java    From Chorus-RF-Laptimer with MIT License 6 votes vote down vote up
@Override
public void open(UsbDeviceConnection connection) throws IOException {
    if (mConnection != null) {
        throw new IOException("Already open");
    }
    mConnection = connection;

    boolean opened = false;
    try {
        for (int i = 0; i < mDevice.getInterfaceCount(); i++) {
            if (connection.claimInterface(mDevice.getInterface(i), true)) {
                Log.d(TAG, "claimInterface " + i + " SUCCESS");
            } else {
                throw new IOException("Error claiming interface " + i);
            }
        }
        reset();
        opened = true;
    } finally {
        if (!opened) {
            close();
            mConnection = null;
        }
    }
}
 
Example 14
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 15
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 16
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);
       }
}
 
Example 17
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 18
Source File: Trezor.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static Trezor getDevice(final Context context, final TrezorGUICallback guiFn,
                               final Network network) {
    final UsbManager manager = (UsbManager)context.getSystemService(Context.USB_SERVICE);

    for (final UsbDevice device: manager.getDeviceList().values()) {
        // Check if the device is TREZOR (or AvalonWallet or BWALLET)

        final int vendorId = device.getVendorId();
        final int productId = device.getProductId();

        if ((vendorId != 0x534c || productId != 0x0001) &&
            (vendorId != 0x1209 || productId != 0x53c0) &&
            (vendorId != 0x1209 || productId != 0x53c1) &&
            (vendorId != 0x10c4 || productId != 0xea80)) {
            continue;
        }

        Log.i(TAG, "Hardware Wallet device found");
        if (device.getInterfaceCount() < 1) {
            Log.e(TAG, "Wrong interface count");
            continue;
        }

        // Use first interface
        final UsbInterface iface = device.getInterface(0);
        // Try to find read/write endpoints
        UsbEndpoint readEndpoint = null, writeEndpoint = null;

        for (int i = 0; i < iface.getEndpointCount(); ++i) {
            final UsbEndpoint ep = iface.getEndpoint(i);

            if (readEndpoint == null &&
                    ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
                    ep.getAddress() == 0x81) {
                // number = 1 ; dir = USB_DIR_IN
                readEndpoint = ep;
                continue;
            }
            if (writeEndpoint == null &&
                    ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
                    (ep.getAddress() == 0x01 || ep.getAddress() == 0x02)) {
                // number = 1 ; dir = USB_DIR_OUT
                writeEndpoint = ep;
                continue;
            }
            Log.e(TAG, String.format("ep %d", ep.getAddress()));
        }

        if (!isEndpointOK(readEndpoint, "read") || !isEndpointOK(writeEndpoint, "write"))
            continue;

        // Try to open the device
        final UsbDeviceConnection conn = manager.openDevice(device);
        if (conn == null || !conn.claimInterface(iface,  true)) {
            Log.e(TAG, conn == null ? "Could not open connection" : "Could not claim interface");
            continue;
        }

        // All OK - return the class
        return new Trezor(guiFn, device, conn, readEndpoint, writeEndpoint, network);
    }
    return null;
}
 
Example 19
Source File: UsbIpService.java    From USBIPServerForAndroid with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean attachToDevice(Socket s, String busId) {
	UsbDevice dev = getDevice(busId);
	if (dev == null) {
		return false;
	}
	
	if (connections.get(dev.getDeviceId()) != null) {
		// Already attached
		return false;
	}
	
	if (!usbManager.hasPermission(dev)) {
		// Try to get permission from the user
		permission.put(dev.getDeviceId(), null);
		usbManager.requestPermission(dev, usbPermissionIntent);
		synchronized (dev) {
			while (permission.get(dev.getDeviceId()) == null) {
				try {
					dev.wait(1000);
				} catch (InterruptedException e) {
					return false;
				}
			}
		}
		
		// User may have rejected this
		if (!permission.get(dev.getDeviceId())) {
			return false;
		}
	}
	
	UsbDeviceConnection devConn = usbManager.openDevice(dev);
	if (devConn == null) {
		return false;
	}
	
	// Claim all interfaces since we don't know which one the client wants
	for (int i = 0; i < dev.getInterfaceCount(); i++) {
		if (!devConn.claimInterface(dev.getInterface(i), true)) {
			System.err.println("Unabled to claim interface "+dev.getInterface(i).getId());
		}
	}
	
	// Create a context for this attachment
	AttachedDeviceContext context = new AttachedDeviceContext();
	context.devConn = devConn;
	context.device = dev;
	
	// Count all endpoints on all interfaces
	int endpointCount = 0;
	for (int i = 0; i < dev.getInterfaceCount(); i++) {
		endpointCount += dev.getInterface(i).getEndpointCount();
	}
	
	// Use a thread pool with a thread per endpoint
	context.requestPool = new ThreadPoolExecutor(endpointCount, endpointCount,
			Long.MAX_VALUE, TimeUnit.DAYS, 
			new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardPolicy());
	
	// Create the active message set
	context.activeMessages = new HashSet<UsbIpSubmitUrb>();
	
	connections.put(dev.getDeviceId(), context);
	socketMap.put(s, context);
	
	updateNotification();
	return true;
}
 
Example 20
Source File: UsbLinkAndroid.java    From crazyflie-android-client with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Initialize the USB device. Determines endpoints and prepares communication.
 *
 * @param vid
 * @param pid
 * @throws IOException if the device cannot be opened
 * @throws SecurityException
 */
public void initDevice(int vid, int pid) throws IOException, SecurityException {
    mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
    if (mUsbManager == null) {
        throw new IllegalArgumentException("UsbManager == null!");
    }

    List<UsbDevice> usbDevices = findUsbDevices(mUsbManager, (short) vid, (short) pid);
    if (usbDevices.isEmpty() || usbDevices.get(0) == null) {
        throw new IOException("USB device not found. (VID: " + vid + ", PID: " + pid + ")");
    }
    // TODO: Only gets the first USB device that is found
    this.mUsbDevice = usbDevices.get(0);

    //request permissions
    if (mUsbDevice != null && !mUsbManager.hasPermission(mUsbDevice)) {
        Log.d(LOG_TAG, "Request permission");
        mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext.getPackageName()+".USB_PERMISSION"), 0);
        mUsbManager.requestPermission(mUsbDevice, mPermissionIntent);
    } else if (mUsbDevice != null && mUsbManager.hasPermission(mUsbDevice)) {
        Log.d(LOG_TAG, "Has permission");
    } else {
        Log.d(LOG_TAG, "device == null");
        return;
    }

    Log.d(LOG_TAG, "setDevice " + this.mUsbDevice);
    // find interface
    if (this.mUsbDevice.getInterfaceCount() != 1) {
        Log.e(LOG_TAG, "Could not find interface");
        return;
    }
    mIntf = this.mUsbDevice.getInterface(0);
    // device should have two endpoints
    if (mIntf.getEndpointCount() != 2) {
        Log.e(LOG_TAG, "Could not find endpoints");
        return;
    }
    // endpoints should be of type bulk
    UsbEndpoint ep = mIntf.getEndpoint(0);
    if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) {
        Log.e(LOG_TAG, "Endpoint is not of type bulk");
        return;
    }
    // check endpoint direction
    if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
        mEpIn = mIntf.getEndpoint(0);
        mEpOut = mIntf.getEndpoint(1);
    } else {
        mEpIn = mIntf.getEndpoint(1);
        mEpOut = mIntf.getEndpoint(0);
    }

    UsbDeviceConnection connection = mUsbManager.openDevice(mUsbDevice);
    if (connection != null && connection.claimInterface(mIntf, true)) {
        Log.d(LOG_TAG, "open SUCCESS");
        mConnection = connection;
    } else {
        Log.d(LOG_TAG, "open FAIL");
        throw new IOException("could not open usb connection");
    }
}