@Override
  public void open() throws IOException {
    Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());

    Log.d(TAG, "Claiming control interface.");
    mControlInterface = mDevice.getInterface(0);
    Log.d(TAG, "Control iface=" + mControlInterface);
    // class should be USB_CLASS_COMM

    if (!mConnection.claimInterface(mControlInterface, true)) {
      throw new IOException("Could not claim control interface.");
    }
    mControlEndpoint = mControlInterface.getEndpoint(0);
    Log.d(TAG, "Control endpoint direction: " + mControlEndpoint.getDirection());

    Log.d(TAG, "Claiming data interface.");
    mDataInterface = mDevice.getInterface(1);
    Log.d(TAG, "data iface=" + mDataInterface);
    // class should be USB_CLASS_CDC_DATA

    if (!mConnection.claimInterface(mDataInterface, true)) {
      throw new IOException("Could not claim data interface.");
    }
    mReadEndpoint = mDataInterface.getEndpoint(1);
    Log.d(TAG, "Read endpoint direction: " + mReadEndpoint.getDirection());
    mWriteEndpoint = mDataInterface.getEndpoint(0);
    Log.d(TAG, "Write endpoint direction: " + mWriteEndpoint.getDirection());
  }
  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;
      }
    }
  }
Esempio n. 3
0
  /**
   * デバイスの利用開始。
   *
   * @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
  protected void initEndpoints() throws IOException {
    UsbInterface usbInterface = mDevice.getInterface(0);

    if (!mConnection.claimInterface(usbInterface, true)) {
      throw new IOException("Error claiming Prolific interface 0");
    }

    for (int i = 0; i < usbInterface.getEndpointCount(); ++i) {
      UsbEndpoint currentEndpoint = usbInterface.getEndpoint(i);

      switch (currentEndpoint.getType()) {
        case UsbConstants.USB_ENDPOINT_XFER_BULK:
          if (currentEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
            mReadEndpoint = currentEndpoint;
          } else {
            mWriteEndpoint = currentEndpoint;
          }
          break;

        case UsbConstants.USB_ENDPOINT_XFER_INT:
          mControlEndpoint = currentEndpoint;
          break;
      }
    }
  }
Esempio n. 5
0
  public ZBCoordinator(Context context, String actionUsbPermission) {
    super();
    UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    UsbDevice device = null;
    while (deviceIterator.hasNext()) {
      UsbDevice devi = deviceIterator.next();
      // TODO Remove hardcoded IDs
      if (devi.getProductId() == 0x05dc && devi.getVendorId() == 0x16c0) device = devi;
      // TODO Make sure this is the ZBCoordinator using RAW Descriptors
    }

    PendingIntent mPermissionIntent =
        PendingIntent.getBroadcast(context, 0, new Intent(actionUsbPermission), 0);

    if (device != null && !manager.hasPermission(device))
      manager.requestPermission(device, mPermissionIntent);

    if (device != null && manager.hasPermission(device)) {
      UsbInterface intf = device.getInterface(0);
      this.endpointInt = intf.getEndpoint(0);
      this.usbDeviceConnection = manager.openDevice(device);
      this.usbDeviceConnection.claimInterface(intf, false);
      this.canUse = true;
    }
  }
  private void setDevice(UsbDevice device) {
    mConnection = mUsbManager.openDevice(device);
    intf = device.getInterface(0);
    UsbEndpoint epOut = null;
    UsbEndpoint epIn = null;
    UsbEndpoint epEv = null;
    // Looking for Bulk Endpoints
    for (int i = 0; i < intf.getEndpointCount(); i++) {
      UsbEndpoint ep = intf.getEndpoint(i);
      if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
        if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
          epOut = ep;
        } else {
          epIn = ep;
        }
      }
      if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
        epEv = ep;
      }
    }
    if (epOut == null || epIn == null || epEv == null) {
      throw new IllegalArgumentException("not all endpoints found");
    }

    mEndpointBulkOut = epOut;
    mEndpointBulkIn = epIn;
    mEndpointIntr = epEv;
    inMaxPS = mEndpointBulkIn.getMaxPacketSize();
  }
Esempio n. 7
0
  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;
      }
    }
  }
Esempio n. 8
0
  public void usbDeviceDump(UsbDevice usbDevice) {
    //		Log.d(TAG, "usbDeviceDump " + usbDevice);

    if (usbDevice == null) {
      Log.e(TAG, "usbDevice is NULL!");
      return;
    }

    int numInterfaces = usbDevice.getInterfaceCount();

    // Log.d(TAG, numInterfaces + " interfaces");
    Log.d(
        TAG,
        "Device found: VendorId="
            + usbDevice.getVendorId()
            + " ProductId="
            + usbDevice.getProductId());

    for (int i = 0; i < numInterfaces; i++) {
      UsbInterface usbInterface = usbDevice.getInterface(i);
      //			Log.d(TAG, "\tInterface(" + i + "): class=" + usbInterface.getInterfaceClass() + "
      // protocol=" + usbInterface.getInterfaceProtocol());

      int numEndpoints = usbInterface.getEndpointCount();
      //			Log.d(TAG, numEndpoints + " endpoints");

      for (int j = 0; j < numEndpoints; j++) {
        UsbEndpoint usbEndpoint = usbInterface.getEndpoint(j);
        //				Log.d(TAG, "\t\tEndpoint(" + j + ")");
      }
    }
  }
    @Override
    public void open(UsbDeviceConnection connection) throws IOException {
      if (mConnection != null) {
        throw new IOException("Already open");
      }

      mConnection = connection;
      boolean opened = false;
      try {
        Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount());
        mControlInterface = mDevice.getInterface(0);
        Log.d(TAG, "Control iface=" + mControlInterface);
        // class should be USB_CLASS_COMM

        if (!mConnection.claimInterface(mControlInterface, true)) {
          throw new IOException("Could not claim control interface.");
        }
        mControlEndpoint = mControlInterface.getEndpoint(0);
        Log.d(TAG, "Control endpoint direction: " + mControlEndpoint.getDirection());

        Log.d(TAG, "Claiming data interface.");
        mDataInterface = mDevice.getInterface(1);
        Log.d(TAG, "data iface=" + mDataInterface);
        // class should be USB_CLASS_CDC_DATA

        if (!mConnection.claimInterface(mDataInterface, true)) {
          throw new IOException("Could not claim data interface.");
        }
        mReadEndpoint = mDataInterface.getEndpoint(1);
        Log.d(TAG, "Read endpoint direction: " + mReadEndpoint.getDirection());
        mWriteEndpoint = mDataInterface.getEndpoint(0);
        Log.d(TAG, "Write endpoint direction: " + mWriteEndpoint.getDirection());
        if (mEnableAsyncReads) {
          Log.d(TAG, "Async reads enabled");
        } else {
          Log.d(TAG, "Async reads disabled.");
        }
        opened = true;
      } finally {
        if (!opened) {
          mConnection = null;
        }
      }
    }
  /**
   * 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");
    }
  }
  @Override
  public boolean open() {

    // Restart the working thread and writeThread if it has been killed before and  get and claim
    // interface
    restartWorkingThread();
    restartWriteThread();

    if (connection.claimInterface(mInterface, true)) {
      Log.i(CLASS_ID, "Interface succesfully claimed");
    } else {
      Log.i(CLASS_ID, "Interface could not be claimed");
      return false;
    }

    // Assign endpoints
    int numberEndpoints = mInterface.getEndpointCount();
    for (int i = 0; i <= numberEndpoints - 1; i++) {
      UsbEndpoint endpoint = mInterface.getEndpoint(i);
      if (endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK
          && endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
        inEndpoint = endpoint;
      } else {
        outEndpoint = endpoint;
      }
    }

    // Default Setup
    if (setControlCommand(XDCVCP_IFC_ENABLE, XDCVCP_UART_ENABLE, null) < 0) return false;
    setBaudRate(DEFAULT_BAUDRATE);
    if (setControlCommand(XDCVCP_SET_LINE_CTL, XDCVCP_LINE_CTL_DEFAULT, null) < 0) return false;
    setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
    if (setControlCommand(XDCVCP_SET_MHS, XDCVCP_MHS_DEFAULT, null) < 0) return false;

    // Initialize UsbRequest
    requestIN = new UsbRequest();
    requestIN.initialize(connection, inEndpoint);

    // Pass references to the threads
    setThreadsParams(requestIN, outEndpoint);

    return true;
  }
Esempio n. 12
0
        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!");
          }
        }
Esempio n. 13
0
  /** 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;

    }
  }
    @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);
        }
      }
    }