@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;
      }
    }
  }
Exemple #2
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
  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) {
    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();
  }
    @Override
    public int read(byte[] dest, int timeoutMillis) throws IOException {
      final UsbEndpoint endpoint = mDevice.getInterface(0).getEndpoint(0);

      if (ENABLE_ASYNC_READS) {
        final int readAmt;
        synchronized (mReadBufferLock) {
          // mReadBuffer is only used for maximum read size.
          readAmt = Math.min(dest.length, mReadBuffer.length);
        }

        final UsbRequest request = new UsbRequest();
        request.initialize(mConnection, endpoint);

        final ByteBuffer buf = ByteBuffer.wrap(dest);
        if (!request.queue(buf, readAmt)) {
          throw new IOException("Error queueing request.");
        }

        final UsbRequest response = mConnection.requestWait();
        if (response == null) {
          throw new IOException("Null response");
        }

        final int payloadBytesRead = buf.position() - MODEM_STATUS_HEADER_LENGTH;
        if (payloadBytesRead > 0) {
          Log.d(TAG, HexDump.dumpHexString(dest, 0, Math.min(32, dest.length)));
          return payloadBytesRead;
        } else {
          return 0;
        }
      } else {
        final int totalBytesRead;

        synchronized (mReadBufferLock) {
          final int readAmt = Math.min(dest.length, mReadBuffer.length);
          totalBytesRead = mConnection.bulkTransfer(endpoint, mReadBuffer, readAmt, timeoutMillis);

          if (totalBytesRead < MODEM_STATUS_HEADER_LENGTH) {
            throw new IOException("Expected at least " + MODEM_STATUS_HEADER_LENGTH + " bytes");
          }

          return filterStatusBytes(mReadBuffer, dest, totalBytesRead, endpoint.getMaxPacketSize());
        }
      }
    }
    @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;
        }
      }
    }
  @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;
  }
  /**
   * 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 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);
        }
      }
    }