android.hardware.usb.UsbInterface Java Examples

The following examples show how to use android.hardware.usb.UsbInterface. 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: UsbHidDevice.java    From UsbHid with MIT License 7 votes vote down vote up
public static UsbHidDevice[] enumerate(Context context, int vid, int pid) throws Exception {
    UsbManager usbManager = (UsbManager) context.getApplicationContext().getSystemService(Context.USB_SERVICE);
    if (usbManager == null) {
        throw new Exception("no usb service");
    }

    Map<String, UsbDevice> devices = usbManager.getDeviceList();
    List<UsbHidDevice> usbHidDevices = new ArrayList<>();
    for (UsbDevice device : devices.values()) {
        if ((vid == 0 || device.getVendorId() == vid) && (pid == 0 || device.getProductId() == pid)) {
            for (int i = 0; i < device.getInterfaceCount(); i++) {
                UsbInterface usbInterface = device.getInterface(i);
                if (usbInterface.getInterfaceClass() == INTERFACE_CLASS_HID) {
                    UsbHidDevice hidDevice = new UsbHidDevice(device, usbInterface, usbManager);
                    usbHidDevices.add(hidDevice);
                }
            }
        }
    }
    return usbHidDevices.toArray(new UsbHidDevice[usbHidDevices.size()]);
}
 
Example #2
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 #3
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 #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: 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 #7
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 #8
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 #9
Source File: UsbIpService.java    From USBIPServerForAndroid with GNU General Public License v3.0 6 votes vote down vote up
public static void dumpInterfaces(UsbDevice dev) {
	for (int i = 0; i < dev.getInterfaceCount(); i++) {
		System.out.printf("%d - Iface %d (%02x/%02x/%02x)\n",
				i, dev.getInterface(i).getId(),
				dev.getInterface(i).getInterfaceClass(),
				dev.getInterface(i).getInterfaceSubclass(),
				dev.getInterface(i).getInterfaceProtocol());
		
		UsbInterface iface = dev.getInterface(i);
		for (int j = 0; j < iface.getEndpointCount(); j++) {
			System.out.printf("\t%d - Endpoint %d (%x/%x)\n",
					j, iface.getEndpoint(j).getEndpointNumber(),
					iface.getEndpoint(j).getAddress(),
					iface.getEndpoint(j).getAttributes());
		}
	}
}
 
Example #10
Source File: UsbHelper.java    From sample-usbenum with Apache License 2.0 6 votes vote down vote up
/**
 * Enumerate the endpoints and interfaces on the connected device.
 *
 * @param device Device to query.
 * @return String description of the device configuration.
 */
public static String readDevice(UsbDevice device) {
    StringBuilder sb = new StringBuilder();
    sb.append("Device Name: " + device.getDeviceName() + "\n");
    sb.append(String.format(
            "Device Class: %s -> Subclass: 0x%02x -> Protocol: 0x%02x\n",
            nameForClass(device.getDeviceClass()),
            device.getDeviceSubclass(), device.getDeviceProtocol()));

    for (int i = 0; i < device.getInterfaceCount(); i++) {
        UsbInterface intf = device.getInterface(i);
        sb.append(String.format(Locale.US,
                "-- Interface %d Class: %s -> Subclass: 0x%02x -> Protocol: 0x%02x\n",
                intf.getId(),
                nameForClass(intf.getInterfaceClass()),
                intf.getInterfaceSubclass(),
                intf.getInterfaceProtocol()));

        sb.append(String.format(Locale.US, "   -- Endpoint Count: %d\n",
                intf.getEndpointCount()));
    }

    return sb.toString();
}
 
Example #11
Source File: CarlifeUtil.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
public boolean isUsbStorageDevice(Context context) {
    UsbManager mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    if (null == mUsbManager) {
        LogUtil.e(TAG, "There is no devices");
        return false;
    } else {
        LogUtil.v(TAG, "Usb Devices: " + String.valueOf(mUsbManager.toString()));
    }
    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
        UsbDevice device = deviceIterator.next();
        if (STORAGE_INTERFACE_CONUT == device.getInterfaceCount()) {
            UsbInterface usbInter = device.getInterface(STORAGE_INTERFACE_ID);
            if ((STORAGE_INTERFACE_CLASS == usbInter.getInterfaceClass())
                    && (STORAGE_INTERFACE_SUBCLASS == usbInter.getInterfaceSubclass())
                    && (STORAGE_INTERFACE_PROTOCOL == usbInter.getInterfaceProtocol())) {
                LogUtil.e(TAG, "This is mass storage 1");
                return true;
            }
        }
    }

    return false;
}
 
Example #12
Source File: CarlifeUtil.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
public boolean isUsbStorageDevice(UsbDevice device) {
    if( device == null ) {
        LogUtil.e(TAG, "this device is null");
        return false;
    }

    if (STORAGE_INTERFACE_CONUT == device.getInterfaceCount()) {
        UsbInterface usbInter = device.getInterface(STORAGE_INTERFACE_ID);
        if ((STORAGE_INTERFACE_CLASS == usbInter.getInterfaceClass())
                && (STORAGE_INTERFACE_SUBCLASS == usbInter.getInterfaceSubclass())
                && (STORAGE_INTERFACE_PROTOCOL == usbInter.getInterfaceProtocol())) {
            LogUtil.e(TAG, "this device is mass storage 2");
            return true;
        }
    }

    return false;
}
 
Example #13
Source File: USBMonitor.java    From AndroidUSBCamera with Apache License 2.0 6 votes vote down vote up
/**
 * get interface
 * @param interface_id
 * @param altsetting
 * @return
 * @throws IllegalStateException
 */
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting) throws IllegalStateException {
	checkConnection();
	SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
	if (intfs == null) {
		intfs = new SparseArray<UsbInterface>();
		mInterfaces.put(interface_id, intfs);
	}
	UsbInterface intf = intfs.get(altsetting);
	if (intf == null) {
		final UsbDevice device = mWeakDevice.get();
		final int n = device.getInterfaceCount();
		for (int i = 0; i < n; i++) {
			final UsbInterface temp = device.getInterface(i);
			if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
				intf = temp;
				break;
			}
		}
		if (intf != null) {
			intfs.append(altsetting, intf);
		}
	}
	return intf;
}
 
Example #14
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 #15
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 #16
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 #17
Source File: USBMonitor.java    From UVCCameraZxing with Apache License 2.0 6 votes vote down vote up
/**
 * open specific interface
 * @param interfaceIndex
 * @return
 */
public synchronized UsbInterface open(final int interfaceIndex) {
	if (DEBUG) Log.i(TAG, "UsbControlBlock#open:" + interfaceIndex);
	final UsbDevice device = mWeakDevice.get();
	UsbInterface intf = null;
	intf = mInterfaces.get(interfaceIndex);
	if (intf == null) {
		intf = device.getInterface(interfaceIndex);
		if (intf != null) {
			synchronized (mInterfaces) {
				mInterfaces.append(interfaceIndex, intf);
			}
		}
	}
	return intf;
}
 
Example #18
Source File: USBMonitor.java    From UVCCameraZxing with Apache License 2.0 6 votes vote down vote up
/**
 * close specified interface. USB device itself still keep open.
 */
public synchronized void close() {
	if (DEBUG) Log.i(TAG, "UsbControlBlock#close:");

	if (mConnection != null) {
		final int n = mInterfaces.size();
		int key;
		UsbInterface intf;
		for (int i = 0; i < n; i++) {
			key = mInterfaces.keyAt(i);
			intf = mInterfaces.get(key);
			mConnection.releaseInterface(intf);
		}
		mConnection.close();
		mConnection = null;
		final USBMonitor monitor = mWeakMonitor.get();
		if (monitor != null) {
			if (monitor.mOnDeviceConnectListener != null) {
				final UsbDevice device = mWeakDevice.get();
				monitor.mOnDeviceConnectListener.onDisconnect(device, this);
			}
			monitor.mCtrlBlocks.remove(getDevice());
		}
	}
}
 
Example #19
Source File: DeviceFilter.java    From libcommon with Apache License 2.0 6 votes vote down vote up
private boolean interfaceMatches(@NonNull final UsbDevice device) {
	// if device doesn't match, check the interfaces
	final int count = device.getInterfaceCount();
	for (int i = 0; i < count; i++) {
		final UsbInterface intf = device.getInterface(i);
		if (matches(
			intf.getInterfaceClass(),
			intf.getInterfaceSubclass(),
			intf.getInterfaceProtocol())) {

			return true;
		}
		if (interfaceMatches(
			intf.getInterfaceClass(),
			intf.getInterfaceSubclass(),
			intf.getInterfaceProtocol())) {

			return true;
		}
	}
	return false;
}
 
Example #20
Source File: WaltUsbConnection.java    From walt with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnect() {
    // Serial mode only
    // TODO: find the interface and endpoint indexes no matter what mode it is
    int ifIdx = 1;
    int epInIdx = 1;
    int epOutIdx = 0;

    UsbInterface iface = usbDevice.getInterface(ifIdx);

    if (usbConnection.claimInterface(iface, true)) {
        logger.log("Interface claimed successfully\n");
    } else {
        logger.log("ERROR - can't claim interface\n");
        return;
    }

    endpointIn = iface.getEndpoint(epInIdx);
    endpointOut = iface.getEndpoint(epOutIdx);

    super.onConnect();
}
 
Example #21
Source File: USBMonitor.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * get interface
 * @param interface_id
 * @param altsetting
 * @return
 * @throws IllegalStateException
 */
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting) throws IllegalStateException {
	checkConnection();
	SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
	if (intfs == null) {
		intfs = new SparseArray<UsbInterface>();
		mInterfaces.put(interface_id, intfs);
	}
	UsbInterface intf = intfs.get(altsetting);
	if (intf == null) {
		final UsbDevice device = mWeakDevice.get();
		final int n = device.getInterfaceCount();
		for (int i = 0; i < n; i++) {
			final UsbInterface temp = device.getInterface(i);
			if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
				intf = temp;
				break;
			}
		}
		if (intf != null) {
			intfs.append(altsetting, intf);
		}
	}
	return intf;
}
 
Example #22
Source File: BTChipTransportAndroidWinUSB.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public BTChipTransportAndroidWinUSB(UsbDeviceConnection connection, UsbInterface dongleInterface, UsbEndpoint in, UsbEndpoint out, int timeout) {
	this.connection = connection;
	this.dongleInterface = dongleInterface;
	this.in = in;
	this.out = out;
	this.timeout = timeout;
	transferBuffer = new byte[260];
}
 
Example #23
Source File: BTChipTransportAndroidHID.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public BTChipTransportAndroidHID(UsbDeviceConnection connection, UsbInterface dongleInterface, UsbEndpoint in, UsbEndpoint out, int timeout, boolean ledger) {
	this.connection = connection;
	this.dongleInterface = dongleInterface;
	this.in = in;
	this.out = out;
	this.ledger = ledger;
	// Compatibility with old prototypes, to be removed
	if (!this.ledger) {
		this.ledger = (in.getEndpointNumber() != out.getEndpointNumber());
	}
	this.timeout = timeout;
	transferBuffer = new byte[HID_BUFFER_SIZE];
}
 
Example #24
Source File: Usb.java    From android-stm32-dfu-programmer with Apache License 2.0 5 votes vote down vote up
public String getDeviceInfo(UsbDevice device) {
    if (device == null)
        return "No device found.";

    StringBuilder sb = new StringBuilder();
    sb.append("Model: " + device.getDeviceName() + "\n");
    sb.append("ID: " + device.getDeviceId() + " (0x" + Integer.toHexString(device.getDeviceId()) + ")" + "\n");
    sb.append("Class: " + device.getDeviceClass() + "\n");
    sb.append("Subclass: " + device.getDeviceSubclass() + "\n");
    sb.append("Protocol: " + device.getDeviceProtocol() + "\n");
    sb.append("Vendor ID " + device.getVendorId() + " (0x" + Integer.toHexString(device.getVendorId()) + ")" + "\n");
    sb.append("Product ID: " + device.getProductId() + " (0x" + Integer.toHexString(device.getProductId()) + ")" + "\n");
    sb.append("Device Ver: 0x" + Integer.toHexString(mDeviceVersion) + "\n");
    sb.append("Interface count: " + device.getInterfaceCount() + "\n");

    for (int i = 0; i < device.getInterfaceCount(); i++) {

        UsbInterface usbInterface = device.getInterface(i);

        sb.append("Interface: " + usbInterface.toString() + "\n");
        sb.append("Endpoint Count: " + usbInterface.getEndpointCount() + "\n");

        for (int j = 0; j < usbInterface.getEndpointCount(); j++) {

            UsbEndpoint ep = usbInterface.getEndpoint(j);

            sb.append("Endpoint: " + ep.toString() + "\n");
        }
    }

    return sb.toString();
}
 
Example #25
Source File: U2FTransportAndroidHID.java    From android-u2f-bridge with Apache License 2.0 5 votes vote down vote up
public U2FTransportAndroidHID(UsbDeviceConnection connection, UsbInterface dongleInterface, UsbEndpoint in, UsbEndpoint out, int timeout) {
   this.connection = connection;
   this.dongleInterface = dongleInterface;
   this.in = in;
   this.out = out;
   this.timeout = timeout;
   transferBuffer = new byte[HID_BUFFER_SIZE];
   helper = new U2FHelper();
   random = new Random();
}
 
Example #26
Source File: BootloaderConnection.java    From walt with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnect() {
    int ifIdx = 0;

    UsbInterface iface = usbDevice.getInterface(ifIdx);

    if (usbConnection.claimInterface(iface, true)) {
        logger.log("Interface claimed successfully\n");
    } else {
        logger.log("ERROR - can't claim interface\n");
    }

    super.onConnect();
}
 
Example #27
Source File: USBMonitor.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * デバイスを閉じる
 * Java内でインターフェースをopenして使う時は開いているインターフェースも閉じる
 */
public void close() {
	if (DEBUG) Log.i(TAG, "UsbControlBlock#close:");

	UsbDeviceConnection connection;
	synchronized (this) {
		connection = mConnection;
		mConnection = null;
	}
	if (connection != null) {
		// 2015/01/06 closeしてからonDisconnectを呼び出すように変更
		// openしているinterfaceが有れば閉じる XXX Java側でインターフェースを使う時
		final int n = mInterfaces.size();
		for (int i = 0; i < n; i++) {
			final SparseArray<UsbInterface> intfs = mInterfaces.valueAt(i);
			if (intfs != null) {
				final int m = intfs.size();
				for (int j = 0; j < m; j++) {
					final UsbInterface intf = intfs.valueAt(j);
					connection.releaseInterface(intf);
				}
				intfs.clear();
			}
		}
		mInterfaces.clear();
		connection.close();
		final USBMonitor monitor = getMonitor();
		final UsbDevice device = getDevice();
		if ((monitor != null) && (device != null)) {
			monitor.callOnDisconnect(device, this);
		}
	}
}
 
Example #28
Source File: USBMonitor.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * インターフェースを閉じる
 * @param intf
 * @throws IllegalStateException
 */
public synchronized void releaseInterface(final UsbInterface intf)
	throws IllegalStateException {

	checkConnection();
	final SparseArray<UsbInterface> intfs = mInterfaces.get(intf.getId());
	if (intfs != null) {
		final int index = intfs.indexOfValue(intf);
		intfs.removeAt(index);
		if (intfs.size() == 0) {
			mInterfaces.remove(intf.getId());
		}
	}
	mConnection.releaseInterface(intf);
}
 
Example #29
Source File: BTChipTransportAndroidHID.java    From WalletCordova with GNU Lesser General Public License v2.1 5 votes vote down vote up
public BTChipTransportAndroidHID(UsbDeviceConnection connection, UsbInterface dongleInterface, UsbEndpoint in, UsbEndpoint out, int timeout, boolean ledger) {
	this.connection = connection;
	this.dongleInterface = dongleInterface;
	this.in = in;
	this.out = out;
	this.ledger = ledger;
	// Compatibility with old prototypes, to be removed
	if (!this.ledger) {
		this.ledger = (in.getEndpointNumber() != out.getEndpointNumber());
	}
	this.timeout = timeout;
	transferBuffer = new byte[HID_BUFFER_SIZE];
}
 
Example #30
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);
}