下面列出了怎么用android.hardware.usb.UsbDeviceConnection的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@Before
public void setUp()
{
System.setProperty("dexmaker.dexcache",
getInstrumentation().getTargetContext().getCacheDir().getPath());
mockedUsbFacade = Mockito.mock(UsbFacade.class);
Mockito.when(mockedUsbFacade.openDevice()).thenReturn(true);
Mockito.when(mockedUsbFacade.reset()).thenReturn(true);
Mockito.when(mockedUsbFacade.getMaxLun()).thenReturn(1);
Mockito.doNothing().when(mockedUsbFacade).setCallback(Mockito.any(UsbFacadeInterface.class));
Mockito.doNothing().when(mockedUsbFacade).sendCommand(Mockito.any(byte[].class));
Mockito.doNothing().when(mockedUsbFacade).sendData(Mockito.any(byte[].class));
Mockito.doNothing().when(mockedUsbFacade).requestCsw();
Mockito.doNothing().when(mockedUsbFacade).requestData(Mockito.anyInt());
Mockito.doNothing().when(mockedUsbFacade).close();
UsbDeviceConnection mConnection = Mockito.mock(UsbDeviceConnection.class);
UsbDevice mDevice = Mockito.mock(UsbDevice.class);
comm = new BulkOnlyCommunicator(mDevice, mConnection);
comm.injectUsbFacade(mockedUsbFacade);
}
@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;
}
}
}
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);
}
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;
}
@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;
}
}
}
/**
* USB機器情報(ベンダー名・製品名・バージョン・シリアル等)を取得する
* @param manager
* @param device
* @param out
* @return
*/
@SuppressLint("NewApi")
public static UsbDeviceInfo getDeviceInfo(
@NonNull final UsbManager manager,
@Nullable final UsbDevice device, @Nullable final UsbDeviceInfo out) {
final UsbDeviceConnection connection
= (device != null && manager.hasPermission(device))
? manager.openDevice(device) : null;
try {
return getDeviceInfo(connection, device, out);
} finally {
if (connection != null) {
connection.close();
}
}
}
public static int doControlTransfer(UsbDeviceConnection devConn, int requestType,
int request, int value, int index, byte[] buff, int length, int interval) {
// Mask out possible sign expansions
requestType &= 0xFF;
request &= 0xFF;
value &= 0xFFFF;
index &= 0xFFFF;
length &= 0xFFFF;
System.out.printf("SETUP: %x %x %x %x %x\n",
requestType, request, value, index, length);
int res = devConn.controlTransfer(requestType, request, value,
index, buff, length, interval);
if (res < 0) {
res = -Errno.getErrno();
if (res != -110) {
// Don't print for ETIMEDOUT
System.err.println("Control Xfer failed: "+res);
}
}
return res;
}
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;
}
}
}
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 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];
}
public PtpUsbConnection(UsbDeviceConnection connection, UsbEndpoint bulkIn, UsbEndpoint bulkOut, int vendorId,
int productId) {
this.connection = connection;
this.bulkIn = bulkIn;
this.bulkOut = bulkOut;
this.vendorId = vendorId;
this.productId = productId;
}
@Override
public void open(UsbDeviceConnection connection) throws IOException {
if (mConnection != null) {
throw new IOException("Already open");
}
mConnection = connection;
boolean opened = false;
try {
if (1 == mDevice.getInterfaceCount()) {
Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
openSingleInterface();
} else {
Log.d(TAG,"trying default interface logic");
openInterface();
}
if (mEnableAsyncReads) {
Log.d(TAG, "Async reads enabled");
} else {
Log.d(TAG, "Async reads disabled.");
}
opened = true;
} finally {
if (!opened) {
mConnection = null;
// just to be on the save side
mControlEndpoint = null;
mReadEndpoint = null;
mWriteEndpoint = null;
}
}
}
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);
}
public static boolean isEndpointHalted(UsbDeviceConnection devConn, UsbEndpoint endpoint) {
byte[] statusBuffer = new byte[2];
int res = XferUtils.doControlTransfer(devConn, GET_STATUS_REQUEST_TYPE,
GET_STATUS_REQUEST,
0,
endpoint != null ? endpoint.getAddress() : 0,
statusBuffer, statusBuffer.length, 0);
if (res != statusBuffer.length) {
return false;
}
return (statusBuffer[0] & 1) != 0;
}
public static UsbDeviceDescriptor readDeviceDescriptor(UsbDeviceConnection devConn) {
byte[] descriptorBuffer = new byte[UsbDeviceDescriptor.DESCRIPTOR_SIZE];
int res = XferUtils.doControlTransfer(devConn, GET_DESCRIPTOR_REQUEST_TYPE,
GET_DESCRIPTOR_REQUEST,
(DEVICE_DESCRIPTOR_TYPE << 8) | 0x00, // Devices only have 1 descriptor
0, descriptorBuffer, descriptorBuffer.length, 0);
if (res != UsbDeviceDescriptor.DESCRIPTOR_SIZE) {
return null;
}
return new UsbDeviceDescriptor(descriptorBuffer);
}
private void performUsbPermissionCallback(final UsbDevice device) {
if (mUsbHandler.getLooper().getThread() != Thread.currentThread()) {
mUsbHandler.post(new Runnable() {
@Override
public void run() {
performUsbPermissionCallback(device);
}
});
return;
}
if (mPicoflexx != null) {
Log.d(TAG, "Already have a picoflexx");
return;
}
UsbDeviceConnection conn = mUsbManager.openDevice(device);
Log.i(TAG, "USB Device: " + device.getDeviceName() + ", fd: " + conn.getFileDescriptor());
if (!openPicoflexx(conn.getFileDescriptor())) {
Log.e(TAG, "error initializing the picoflexx");
mUiHandler.obtainMessage(WHAT_STATE, STATE_ERROR, R.string.error_initializing)
.sendToTarget();
conn.close();
return;
}
mConn = conn;
mPicoflexx = device;
final int width = getMaxWidth();
final int height = getMaxHeight();
mCloud.setWidth(width);
mCloud.setHeight(height);
mCloud.setRowStep(width * 12);
mUiHandler.obtainMessage(WHAT_STATE, STATE_IDLE, -1).sendToTarget();
}
@Override
public void open(UsbDeviceConnection connection) throws IOException {
if (mConnection != null) {
throw new IOException("Already open");
}
mConnection = connection;
boolean opened = false;
try {
if (1 == mDevice.getInterfaceCount()) {
Log.d(TAG,"device might be castrated ACM device, trying single interface logic");
openSingleInterface();
} else {
Log.d(TAG,"trying default interface logic");
openInterface();
}
if (mEnableAsyncReads) {
Log.d(TAG, "Async reads enabled");
} else {
Log.d(TAG, "Async reads disabled.");
}
opened = true;
} finally {
if (!opened) {
mConnection = null;
// just to be on the save side
mControlEndpoint = null;
mReadEndpoint = null;
mWriteEndpoint = null;
}
}
}
private Trezor(final TrezorGUICallback guiFn, final UsbDevice device,
final UsbDeviceConnection conn,
final UsbEndpoint readEndpoint, final UsbEndpoint writeEndpoint,
final Network network) {
mGuiFn = guiFn;
mVendorId = device.getVendorId();
mConn = conn;
mReadEndpoint = readEndpoint;
mWriteEndpoint = writeEndpoint;
mSerial = mConn.getSerial();
mNetwork = network;
mNetworkParameters = network.getNetworkParameters();
}
@Override
public void open(UsbDeviceConnection connection) throws IOException {
if (mConnection != null) {
throw new IOException("Already open");
}
mConnection = connection;
boolean opened = false;
try {
if (1 == mDevice.getInterfaceCount()) {
Log.d(TAG, "device might be castrated ACM device, trying single interface logic");
openSingleInterface();
} else {
Log.d(TAG, "trying default interface logic");
openInterface();
}
if (mEnableAsyncReads) {
Log.d(TAG, "Async reads enabled");
} else {
Log.d(TAG, "Async reads disabled.");
}
opened = true;
} finally {
if (!opened) {
mConnection = null;
// just to be on the save side
mControlEndpoint = null;
mReadEndpoint = null;
mWriteEndpoint = null;
}
}
}
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;
}
public PtpUsbConnection(UsbDeviceConnection connection, UsbEndpoint bulkIn, UsbEndpoint bulkOut, int vendorId,
int productId) {
this.connection = connection;
this.bulkIn = bulkIn;
this.bulkOut = bulkOut;
this.vendorId = vendorId;
this.productId = productId;
}
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];
}
static synchronized MtpDevice openMTP(final UsbDevice device) {
if (device == null) {
return null;
}
final UsbManager usbManager = (UsbManager) xdrip.getAppContext().getSystemService(Context.USB_SERVICE);
if (usbManager == null) {
Log.d(TAG, "usbmanager is null in openMTP");
return null;
}
final MtpDevice mtpDevice = new MtpDevice(device);
final UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(device);
try {
if (!mtpDevice.open(usbDeviceConnection)) {
return null;
}
} catch (Exception e) {
JoH.static_toast_long("Exception opening USB: " + e);
return null;
}
return mtpDevice;
}
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);
}
}
public CP2102SerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
{
super(device, connection);
rtsCtsEnabled = false;
dtrDsrEnabled = false;
ctsState = true;
dsrState = true;
mInterface = device.getInterface(iface >= 0 ? iface : 0);
}
/**
* Resumed activity handler
* @see org.apache.cordova.CordovaPlugin#onResume(boolean)
*/
@Override
public void onResume(boolean multitasking) {
Log.d(TAG, "Resumed, driver=" + driver);
if (sleepOnPause) {
if (driver == null) {
Log.d(TAG, "No serial device to resume.");
}
else {
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection != null) {
// get first port and open it
port = driver.getPorts().get(0);
try {
port.open(connection);
port.setParameters(baudRate, dataBits, stopBits, parity);
if (setDTR) port.setDTR(true);
if (setRTS) port.setRTS(true);
}
catch (IOException e) {
// deal with error
Log.d(TAG, e.getMessage());
}
Log.d(TAG, "Serial port opened!");
}
else {
Log.d(TAG, "Cannot connect to the device!");
}
Log.d(TAG, "Serial device: " + driver.getClass().getSimpleName());
}
onDeviceStateChange();
}
}
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();
}
public SCSICommunicator(UsbDevice mDevice, UsbDeviceConnection mConnection)
{
this.communicator = new BulkOnlyCommunicator(mDevice, mConnection);
this.buffer = new SCSICommandBuffer();
this.commandHandler = new SCSICommandHandler();
this.commandHandler.start();
}
public UsbSerialDevice(UsbDevice device, UsbDeviceConnection connection)
{
this.device = device;
this.connection = connection;
this.asyncMode = true;
serialBuffer = new SerialBuffer(mr1Version);
}