コード例 #1
0
  /**
   * Searches for the device and opens it if successful
   *
   * @return true, if connection was successful
   */
  public boolean FindDevice() {
    _usbManager = (UsbManager) _context.getSystemService(Context.USB_SERVICE);

    HashMap<String, UsbDevice> deviceList = _usbManager.getDeviceList();

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    _usbDevice = null;

    // Iterate all the available devices and find ours.
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      if (device.getProductId() == _productId && device.getVendorId() == _vendorId) {
        _usbDevice = device;
        _deviceName = _usbDevice.getDeviceName();
      }
    }

    if (_usbDevice == null) {
      Log("Cannot find the device. Did you forgot to plug it?");
      Log(String.format("\t I search for VendorId: %s and ProductId: %s", _vendorId, _productId));
      _connectionHandler.onDeviceNotFound();
      return false;
    }

    // Create and intent and request a permission.
    PendingIntent mPermissionIntent =
        PendingIntent.getBroadcast(_context, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    _context.registerReceiver(mUsbReceiver, filter);

    _usbManager.requestPermission(_usbDevice, mPermissionIntent);
    Log("Found the device and requested permission.");
    return true;
  }
コード例 #2
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!");
          }
        }