public boolean commitControl(int request) { if (request == UvcConstants.SET_CUR) { if (mDeviceConnection.controlTransfer( UvcConstants.CLASS_REQUEST_OUT, request, UvcConstants.COMMIT_CONTROL, UvcConstants.VIDEO_STREAMING_INTERFACE, streamingControls, streamingControls.length, 0) > -1) { return true; } else return false; } else { if (mDeviceConnection.controlTransfer( UvcConstants.CLASS_REQUEST_IN, request, UvcConstants.COMMIT_CONTROL, UvcConstants.VIDEO_STREAMING_INTERFACE, streamingControls, streamingControls.length, 0) > -1) { return true; } else return false; } }
@Override public synchronized void write(byte[] buffer, int offset, int count) throws IOException { if (count > (buffer.length - offset)) { throw new IOException("Count is too big"); } while (count > 0) { if (offset == 0) { // This is an optimization: when the offset is 0, we can pass the original // buffer and avoid a copy. offset = connection_.bulkTransfer(ep_, buffer, count, TRANSFER_TIMEOUT_MILLIS); if (offset < 0) { throw new IOException("Couldn't write to USB"); } count -= offset; } else { // We cannot write directly from the buffer, since the API won't let us use a // non-0 offset. // So we have to use an intermediate buffer and copy. int copied = Math.min(count, buffer_.length); System.arraycopy(buffer, offset, buffer_, 0, copied); int written = connection_.bulkTransfer(ep_, buffer_, copied, TRANSFER_TIMEOUT_MILLIS); if (written < 0) { throw new IOException("Couldn't write to USB"); } offset += written; count -= written; } } }
public void setDevice(UsbManager usbManager, UsbDevice usbDevice) { // Log.d(TAG, "setDevice " + usbDevice); device = usbDevice; if (device != null) { usbDeviceDump(usbDevice); UsbInterface controlInterface = device.getInterface(1); endpoint = controlInterface.getEndpoint(0); UsbDeviceConnection connection = usbManager.openDevice(device); if (connection != null && connection.claimInterface(controlInterface, true)) { controlConnection = connection; serial = UsbSerialDevice.createUsbSerialDevice(device, controlConnection); boolean t = serial.open(); Log.d("Set DEVICE : ", "" + t); serial.setBaudRate(9600); serial.setParity(UsbSerialInterface.PARITY_NONE); serial.setStopBits(UsbSerialInterface.STOP_BITS_1); serial.setDataBits(UsbSerialInterface.DATA_BITS_8); } else { Log.e(TAG, "open connection FAIL"); controlConnection = null; } } }
/* (non-Javadoc) * @see net.smartrover.skyrover2.roverlib.IUsbLink#sendBulkTransfer(byte[], byte[]) */ public int sendBulkTransfer(byte[] data, byte[] receiveData) { int returnCode = -1; if (mConnection != null) { mConnection.bulkTransfer(mEpOut, data, data.length, TRANSFER_TIMEOUT); returnCode = mConnection.bulkTransfer(mEpIn, receiveData, receiveData.length, TRANSFER_TIMEOUT); } return returnCode; }
int waitForUSBPermission() { UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); if (usbListener == null) return -1; while (!usbListener.permissionGranted()) { SystemClock.sleep(100); } UsbDevice depthCamera = usbListener.getDevice(); UsbDeviceConnection con = manager.openDevice(depthCamera); return con.getFileDescriptor(); }
private void setDevice(UsbDevice device) { usbInterfaceFound = null; endpointOut = null; endpointIn = null; for (int i = 0; i < device.getInterfaceCount(); i++) { UsbInterface usbif = device.getInterface(i); UsbEndpoint tOut = null; UsbEndpoint tIn = null; int tEndpointCnt = usbif.getEndpointCount(); if (tEndpointCnt >= 2) { for (int j = 0; j < tEndpointCnt; j++) { if (usbif.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT) { tOut = usbif.getEndpoint(j); } else if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN) { tIn = usbif.getEndpoint(j); } } } if (tOut != null && tIn != null) { // This interface have both USB_DIR_OUT // and USB_DIR_IN of USB_ENDPOINT_XFER_BULK usbInterfaceFound = usbif; endpointOut = tOut; endpointIn = tIn; } } } if (usbInterfaceFound == null) { return; } deviceFound = device; if (device != null) { UsbDeviceConnection connection = usbManager.openDevice(device); if (connection != null && connection.claimInterface(usbInterfaceFound, true)) { usbDeviceConnection = connection; Thread thread = new Thread(this); thread.start(); } else { usbDeviceConnection = null; } } }
@Override public synchronized int read(byte[] buffer, int offset, int length) throws IOException { if (offset == 0) { return connection_.bulkTransfer(ep_, buffer, length, TRANSFER_TIMEOUT_MILLIS); } // We have to go through an intermediate buffer and copy, since the API won't let us // write to a non-0 // offset. int readAmount = connection_.bulkTransfer( ep_, buffer_, Math.min(length, buffer_.length), TRANSFER_TIMEOUT_MILLIS); System.arraycopy(buffer_, 0, buffer, offset, readAmount); return readAmount; }
/* (non-Javadoc) * @see net.smartrover.skyrover2.roverlib.IUsbLink#releaseInterface() */ public void releaseInterface() { if (mConnection != null && mIntf != null) { mConnection.releaseInterface(mIntf); mConnection = null; mIntf = null; } }
@Override public void run() { ByteBuffer buffer = ByteBuffer.allocate(1); UsbRequest request = new UsbRequest(); request.initialize(usbDeviceConnection, endpointIn); while (true) { request.queue(buffer, 1); if (usbDeviceConnection.requestWait() == request) { byte rxCmd = buffer.get(0); if (rxCmd != 0) { muestra = "" + rxCmd; temperatura = (int) rxCmd; } try { Thread.sleep(1000); } catch (InterruptedException e) { } } else { break; } } }
/** * デバイスの利用開始。 * * @return null=正常、null以外=エラーメッセージ */ public String onStart(UsbDevice device) { Log.d(TAG, "onStart:" + device); if (!device.equals(usbDevice)) { return "No device attach."; } if (!usbManager.hasPermission(usbDevice)) { return "No device permission."; } usbConnection = usbManager.openDevice(usbDevice); // TODO:インターフェースの検出は端折ってます。 UsbInterface usbIf = usbDevice.getInterface(INTERFACE_INDEX); // EndPointの検索。分かってる場合は直接取り出しても良い。 for (int i = 0; i < usbIf.getEndpointCount(); i++) { UsbEndpoint ep = usbIf.getEndpoint(i); Log.d(TAG, "tye=" + ep.getType()); if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) { if (ep.getDirection() == UsbConstants.USB_DIR_IN) { endpointIn = ep; } else if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { endpointOut = ep; } } } if (endpointIn == null || endpointOut == null) { Log.e(TAG, "Device has not IN/OUT Endpoint."); return "Device has not IN/OUT Endpoint."; } // デバイスの確保 usbConnection.claimInterface(usbIf, true); isReady = true; return null; }
@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; } } }
/* (non-Javadoc) * @see net.smartrover.skyrover2.roverlib.IUsbLink#sendControlTransfer(int, int, int, int, byte[]) */ public int sendControlTransfer(int requestType, int request, int value, int index, byte[] data) { if (mConnection != null) { int dataLength = (data == null) ? 0 : data.length; return mConnection.controlTransfer( requestType, request, value, index, data, dataLength, TRANSFER_TIMEOUT); } return -1; }
private void sendCommand(int control) { synchronized (this) { if (usbDeviceConnection != null) { byte[] message = new byte[1]; message[0] = (byte) control; usbDeviceConnection.bulkTransfer(endpointOut, message, message.length, 0); } } }
/** Closes connections, releases resources, cleans up variables */ private void destroy() { /* Release the interface that was previously claimed and close * the connection. */ connection.releaseInterface(intf); connection.close(); /* Clear up all of the locals */ device = null; manager = null; handler = null; toggleLEDCount = 0; lastButtonState = false; buttonStatusInitialized = false; closeRequested = false; connection = null; intf = null; }
/** * デバイスの切断通知 * * @return */ public String onDetach(UsbDevice device) { Log.d(TAG, "onDetach:" + device); if (!device.equals(usbDevice)) { Log.d(TAG, "onDetach: Other device."); return "Other device"; } if (usbConnection != null) { UsbInterface usbIf = usbDevice.getInterface(INTERFACE_INDEX); usbConnection.releaseInterface(usbIf); usbConnection.close(); } usbConnection = null; usbDevice = null; isReady = false; return null; }
public void sendCommand(int command, int channel, int value) { Log.d(TAG, "sendCommand(" + command + ", " + channel + ", " + value + ")"); if (device == null) { Log.e(TAG, "sendCommand(): device is NULL!"); return; } controlConnection.controlTransfer(0x40, command, value, channel, null, 0, 5000); }
// Sets the current USB device and interface private boolean setAdbInterface(UsbDevice device, UsbInterface intf) { if (mDeviceConnection != null) { if (mInterface != null) { mDeviceConnection.releaseInterface(mInterface); mInterface = null; } mDeviceConnection.close(); mDevice = null; mDeviceConnection = null; } if (device != null && intf != null) { UsbDeviceConnection connection = mManager.openDevice(device); if (connection != null) { log("open succeeded"); if (connection.claimInterface(intf, false)) { log("claim interface succeeded"); mDevice = device; mDeviceConnection = connection; mInterface = intf; mAdbDevice = new AdbDevice(this, mDeviceConnection, intf); log("call start"); mAdbDevice.start(); return true; } else { log("claim interface failed"); connection.close(); } } else { log("open failed"); } } if (mDeviceConnection == null && mAdbDevice != null) { mAdbDevice.stop(); mAdbDevice = null; } return false; }
/** * Initialize the USB device. Determines endpoints and prepares communication. * * @throws IOException if the device cannot be opened */ private void initDevice() throws IOException { 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"); } }
public boolean startStreaming() { if (mDeviceConnection.controlTransfer( UvcConstants.STANDARD_REQUEST_OUT, UvcConstants.SET_INTERFACE, UvcConstants.OPERATIONAL, UvcConstants.VIDEO_STREAMING_INTERFACE, null, 0, 0) > -1) { return true; } else { return false; } }
/** * Constructor - creates connection to device and launches the thread that runs the actual demo. * * @param context Context requesting to run the demo. * @param device The USB device to attach to. * @param handler The Handler where demo Messages should be sent. */ DemoCustomHID(Context context, UsbDevice device, Handler handler) { /* Save the device and handler information for later use. */ this.device = device; this.handler = handler; /* Get the USB manager from the requesting context */ this.manager = (UsbManager) context.getSystemService(Context.USB_SERVICE); /* * Get the required interface from the USB device. In this case * we are hard coding the interface number to 0. In a dynamic example * the code could scan through the interfaces to find the right * interface. In this case since we know the exact device we are connecting * to, we can hard code it. */ intf = device.getInterface(0); /* Open a connection to the USB device */ connection = manager.openDevice(device); if (connection == null) { return; } /* Claim the required interface to gain access to it */ if (connection.claimInterface(intf, true) == true) { thread = new Thread(this); thread.start(); connected = true; } else { /* if the interface claim failed, we should close the * connection and exit. */ connection.close(); } }
public ZBResult readEP1(int numBytes) { if (usbDeviceConnection == null) return null; ZBResult rdo = new ZBResult(); rdo.setStatus(ZBResultStatus.TRANSFER_OK); UsbRequest request = new UsbRequest(); request.initialize(usbDeviceConnection, endpointInt); ByteBuffer buffer = ByteBuffer.allocate(numBytes); request.queue(buffer, numBytes); usbDeviceConnection.requestWait(); rdo.setLength(numBytes); rdo.data = buffer.array(); for (int i = 0; i < numBytes; i++) Log.d("USB" + i, rdo.data[i] + ""); return rdo; }
public boolean isHearbeatOk() { if (usbDeviceConnection == null) return false; byte[] buffer = {1}; // USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN usbDeviceConnection.controlTransfer( UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_ENDPOINT_XFER_CONTROL | UsbConstants.USB_DIR_IN, 130, 1, 0, buffer, 1, 1000); return buffer[0] == 2; }
public int getScanMode() { byte[] mode = new byte[1]; if (mDeviceConnection.controlTransfer( UvcConstants.CLASS_REQUEST_IN, UvcConstants.GET_CUR, UvcConstants.SCANNING_MODE_CONTROL, UvcConstants.CAMERA_SENSOR, mode, mode.length, 0) > -1) { return 1; } else { return 0; } }
public int getErrorCode() { byte[] code = new byte[1]; if (mDeviceConnection.controlTransfer( UvcConstants.CLASS_REQUEST_IN, UvcConstants.GET_CUR, UvcConstants.STREAM_ERROR_CODE_CONTROL, UvcConstants.VIDEO_STREAMING_INTERFACE, code, code.length, 0) > -1) { return (int) code[0]; } else { return -1; } }
public ZBResult send(byte[] buffer) { if (usbDeviceConnection == null) return null; // USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT int realNumBytes = usbDeviceConnection.controlTransfer( UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_ENDPOINT_XFER_CONTROL | UsbConstants.USB_DIR_OUT, 132, 0, 0, buffer, buffer.length, 1000); ZBResult rdo = new ZBResult(); rdo.setLength(realNumBytes); rdo.data = new byte[realNumBytes]; for (int i = 0; i < realNumBytes; i++) rdo.data[i] = buffer[i]; if (realNumBytes < 0) rdo.setStatus(ZBResultStatus.TRANSFER_ERROR); else rdo.setStatus(ZBResultStatus.TRANSFER_OK); return rdo; }
@Override public void open(UsbDeviceConnection connection) throws IOException { if (mConnection != null) { throw new IOException("Already open"); } UsbInterface usbInterface = mDevice.getInterface(0); if (!connection.claimInterface(usbInterface, true)) { throw new IOException("Error claiming Prolific interface 0"); } mConnection = connection; boolean opened = false; try { for (int i = 0; i < usbInterface.getEndpointCount(); ++i) { UsbEndpoint currentEndpoint = usbInterface.getEndpoint(i); switch (currentEndpoint.getAddress()) { case READ_ENDPOINT: mReadEndpoint = currentEndpoint; break; case WRITE_ENDPOINT: mWriteEndpoint = currentEndpoint; break; case INTERRUPT_ENDPOINT: mInterruptEndpoint = currentEndpoint; break; } } if (mDevice.getDeviceClass() == 0x02) { mDeviceType = DEVICE_TYPE_0; } else { try { Method getRawDescriptorsMethod = mConnection.getClass().getMethod("getRawDescriptors"); byte[] rawDescriptors = (byte[]) getRawDescriptorsMethod.invoke(mConnection); byte maxPacketSize0 = rawDescriptors[7]; if (maxPacketSize0 == 64) { mDeviceType = DEVICE_TYPE_HX; } else if ((mDevice.getDeviceClass() == 0x00) || (mDevice.getDeviceClass() == 0xff)) { mDeviceType = DEVICE_TYPE_1; } else { Log.w(TAG, "Could not detect PL2303 subtype, " + "Assuming that it is a HX device"); mDeviceType = DEVICE_TYPE_HX; } } catch (NoSuchMethodException e) { Log.w( TAG, "Method UsbDeviceConnection.getRawDescriptors, " + "required for PL2303 subtype detection, not " + "available! Assuming that it is a HX device"); mDeviceType = DEVICE_TYPE_HX; } catch (Exception e) { Log.e( TAG, "An unexpected exception occured while trying " + "to detect PL2303 subtype", e); } } setControlLines(mControlLinesValue); resetDevice(); doBlackMagic(); opened = true; } finally { if (!opened) { mConnection = null; connection.releaseInterface(usbInterface); } } }
/** The man thread for the demo */ @Override public void run() { /* Get the OUT endpoint. It is the second endpoint in the interface */ UsbEndpoint endpointOUT = intf.getEndpoint(1); /* Get the IN endpoint. It is the first endpoint in the interface */ UsbEndpoint endpointIN = intf.getEndpoint(0); /* Create the packets that we are going to send to the attached USB * device. */ byte[] getPushButtonStatusPacket = new byte[] {(byte) 0x81}; byte[] toggleLEDsPacket = new byte[] {(byte) 0x80}; byte[] getPotentiometerRequest = new byte[] {(byte) 0x37}; byte[] getPotentiometerResults = new byte[64]; byte[] getPushButtonStatusResults = new byte[64]; int potentiometerLastResults = Integer.MAX_VALUE; int result = 0; boolean needToToggleLEDs = false; while (true) { /* If the connection was closed, destroy the connections and variables * and exit this thread. */ if (wasCloseRequested() == true) { destroy(); return; } /* Sleep the thread for a while */ try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } /* Send the request to get the push button status */ do { result = connection.bulkTransfer( endpointOUT, getPushButtonStatusPacket, getPushButtonStatusPacket.length, 1000); } while ((result < 0) && (wasCloseRequested() == false)); /* Read the push button status */ do { result = connection.bulkTransfer( endpointIN, getPushButtonStatusResults, getPushButtonStatusResults.length, 1000); } while ((result < 0) && (wasCloseRequested() == false)); /* If there was data successfully read,... */ if (result > 0) { /* convert the byte data to a boolean representing the current button state */ boolean currentButtonState = (getPushButtonStatusResults[1] == CUSTOM_HID_DEMO_BUTTON_PRESSED) ? true : false; /* We only need to send a message to the GUI if the current button state is different than * the old button state. */ if ((currentButtonState != lastButtonState) || (buttonStatusInitialized == false)) { lastButtonState = currentButtonState; handler.obtainMessage(0, new MessageButton(lastButtonState)).sendToTarget(); } } /* Check to see if we need to toggle the LEDs. We are synchronizing on * The toggleLEDCount object here to insure that the user isn't changing * the value as we are checking it. */ synchronized (toggleLEDCount) { if (toggleLEDCount > 0) { needToToggleLEDs = true; toggleLEDCount--; } } /* If we need to toggle the LEDs, send out the toggle LED command */ if (needToToggleLEDs == true) { do { result = connection.bulkTransfer(endpointOUT, toggleLEDsPacket, toggleLEDsPacket.length, 1000); } while ((result < 0) && (wasCloseRequested() == false)); needToToggleLEDs = false; } /* Send the request to read the Potentiometer */ do { result = connection.bulkTransfer( endpointOUT, getPotentiometerRequest, getPotentiometerRequest.length, 1000); } while ((result < 0) && (wasCloseRequested() == false)); /* Read the results of that request */ do { result = connection.bulkTransfer( endpointIN, getPotentiometerResults, getPotentiometerResults.length, 1000); } while ((result < 0) && (wasCloseRequested() == false)); /* Convert the resulting data to an int */ byte[] potentiometerBuffer = new byte[] {0, 0, 0, 0}; potentiometerBuffer[0] = getPotentiometerResults[1]; potentiometerBuffer[1] = getPotentiometerResults[2]; ByteBuffer buf = ByteBuffer.wrap(potentiometerBuffer); buf.order(ByteOrder.LITTLE_ENDIAN); int potentiometerResults = buf.getInt(); /* If the new results are different from the previous results, then send * a message to the specified handler containing the new data. */ // handler.obtainMessage(0,new MessagePotentiometer((potentiometerResults * // 100)/0x3FF)).sendToTarget(); // potentiometerLastResults = potentiometerResults; } }
/* (non-Javadoc) * @see net.smartrover.skyrover2.roverlib.IUsbLink#getFirmwareVersion() */ public float getFirmwareVersion() { byte[] rawDescs = mConnection.getRawDescriptors(); return Float.parseFloat( Integer.toHexString(rawDescs[13]) + "." + Integer.toHexString(rawDescs[12])); }
/* (non-Javadoc) * @see net.smartrover.skyrover2.roverlib.IUsbLink#getSerialNumber() */ public String getSerialNumber() { return mConnection.getSerial(); }
public void run() { Log("USB Thread started"); UsbEndpoint readEp = null; UsbDeviceConnection usbConnection = null; UsbInterface Intf = null; UsbInterface Intf0 = null; UsbEndpoint readEp0 = null; UsbEndpoint writeEp0 = null; byte[] readbuffer = new byte[64]; Log("Entering Read loop"); interfaceclaimed = false; while (!_shouldstop) { if (_usbDevice == null) { Log("No device. Open device and Recheck in 1 sec..."); interfaceclaimed = false; FindDevice(); Sleep(10000); continue; } if (!interfaceclaimed) { Log("Read loop Aquiring Interface 0 and Endpoint 1"); Intf = _usbDevice.getInterface(1); readEp = Intf.getEndpoint(0); Log("Read loop Aquiring Interface 0 and Endpoint 0"); Intf0 = _usbDevice.getInterface(0); readEp0 = Intf0.getEndpoint(0); writeEp0 = Intf0.getEndpoint(1); if (!_usbManager.getDeviceList().containsKey(_deviceName)) { Log("Failed to connect to the device. Retrying to acquire it."); FindDevice(); if (!_usbManager.getDeviceList().containsKey(_deviceName)) { Log("No device. Recheking in 10 sec..."); _connectionHandler.onDeviceNotFound(); Sleep(10000); continue; } } try { usbConnection = _usbManager.openDevice(_usbDevice); if (usbConnection == null) { Log( "Cannot start reader because the user didn't gave me permissions or the device is not present. Retrying in 2 sec..."); _connectionHandler.onUSBPermissionError(); Sleep(2000); continue; } Log("USB loop claiming interface"); // Claim and lock the interface in the android system. if (usbConnection.claimInterface(Intf, true) && usbConnection.claimInterface(Intf0, true)) { Log("USB loop Interface claimed successful"); interfaceclaimed = true; _connectionHandler.onUSBDeviceClaimed(); } } catch (SecurityException e) { Log( "Cannot start reader because the user didn't gave me permissions. Retrying in 2 sec..."); interfaceclaimed = false; Sleep(2000); continue; } } /* int filed = readConnection.getFileDescriptor(); int epaddress = readEp.getAddress(); TeensyDeviceUsbNativeHelper nativehelper = new TeensyDeviceUsbNativeHelper(filed,64,epaddress); nativehelper.beginUrbReadLoop(); byte[] buffer2 = new byte[64]; nativehelper.readUrb(1000, buffer2); //_receivedQueue.add(buffer2); Log(String.format("Message received of lengths %s and content: %s", 64, composeString(buffer2))); */ synchronized (_writelocker) { // Queue a USBRequest to USB if any data is in queue if (_writeQueue.size() > 0) { byte[] writebuffer = _writeQueue.poll(); Log(String.format("Writing to USB: %s", CAN_Frame.bytesToHexString(writebuffer))); // Log("USB loop sending bulk write request"); if (usbConnection.bulkTransfer(writeEp0, writebuffer, 64, 100) < 0) { // failed to transfer Log("USB loop sending bulk write request FAILED"); } // else Log("USB loop sending bulk write request SUCCEEDED"); } } synchronized (_locker) { // Log("Read loop Waiting for requst to complete"); if (usbConnection.bulkTransfer(readEp0, readbuffer, 64, 100) >= 0) { byte[] readbuffertrimmed = new byte[readbuffer[0]]; System.arraycopy(readbuffer, 0, readbuffertrimmed, 0, readbuffer[0]); _receivedQueue.add(readbuffertrimmed); Log(String.format("Message received: %s", CAN_Frame.bytesToHexString(readbuffer))); _connectionHandler.onUSBRecieve(); } } // Sleep for 10 ms to pause, so other thread can write data or anything. // As both read and write data methods lock each other - they cannot be run in parallel. // Looks like Android is not so smart in planning the threads, so we need to give it a // small time // to switch the thread context. // Sleep(10); } if (usbConnection != null) { usbConnection.releaseInterface(Intf); usbConnection.releaseInterface(Intf0); interfaceclaimed = false; usbConnection.close(); _connectionHandler.onUsbStopped(); Log("USB Thread ENDED!"); } }