@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;
        }
      }
    }
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;
  }
  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;
      }
    }
  }
  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;
      }
    }
  }
  // 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");
    }
  }
  /**
   * 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 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!");
          }
        }
    @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);
        }
      }
    }