예제 #1
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;
    }
  }
예제 #2
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;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
      getFragmentManager()
          .beginTransaction()
          .add(R.id.container, new PlaceholderFragment())
          .commit();
    }
    //
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    //
    filterAttached_and_Detached = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    filterAttached_and_Detached.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filterAttached_and_Detached.addAction(ACTION_USB_PERMISSION);
    //
    registerReceiver(mUsbReceiver, filterAttached_and_Detached);
    //

    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
    Log.d("1", deviceList.size() + " USB device(s) found");
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      Log.d("1", "" + device);
    }
  }
예제 #4
0
  private void findSerialPortDevice() {
    // This snippet will try to open the first encountered usb device connected, excluding usb root
    // hubs
    HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
    if (!usbDevices.isEmpty()) {
      boolean keep = true;
      for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
        device = entry.getValue();
        int deviceVID = device.getVendorId();
        int devicePID = device.getProductId();

        if (deviceVID != 0x1d6b
            && (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
          // There is a device connected to our Android device. Try to open it as a Serial Port.
          requestUserPermission();
          keep = false;
        } else {
          connection = null;
          device = null;
        }

        if (!keep) break;
      }
      if (!keep) {
        // There is no USB devices connected (but usb host were listed). Send an intent to
        // MainActivity.
        Intent intent = new Intent(ACTION_NO_USB);
        sendBroadcast(intent);
      }
    } else {
      // There is no USB devices connected. Send an intent to MainActivity
      Intent intent = new Intent(ACTION_NO_USB);
      sendBroadcast(intent);
    }
  }
예제 #5
0
 public UsbConnector(Context context) {
   UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
   HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
   Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
   Log.d(TAG, "===>UsbConnector");
   while (deviceIterator.hasNext()) {
     UsbDevice device = deviceIterator.next();
     Log.d(
         TAG,
         "device="
             + device.getDeviceName()
             + ","
             + device.getDeviceSubclass()
             + ","
             + device.getDeviceProtocol());
     Log.d(TAG, "ifs=" + device.getInterfaceCount() + "," + device.getInterface(0).toString());
     Log.d(TAG, "end=" + device.getInterface(0).getEndpoint(0).toString());
     Log.d(
         TAG,
         "class="
             + device.getDeviceClass()
             + ", pid="
             + device.getProductId()
             + ",vid="
             + device.getVendorId());
     // your code
   }
 }
예제 #6
0
  private UsbDevice findDevice() {
    HashMap<String, UsbDevice> devList = mUsbManager.getDeviceList();

    for (UsbDevice dev : devList.values()) {
      Log.d(
          TAG,
          "Dev: "
              + dev
              + " "
              + dev.hashCode()
              + " "
              + dev.getVendorId()
              + " "
              + dev.getProductId()
              + " "
              + dev.getDeviceId()
              + " "
              + dev.getDeviceName());

      if (isCSCID(dev)) {
        return dev;
      }
    }
    return null;
  }
 /**
  * Iterate over all attached USB devices and look for Crazyradio. If Crazyradio is found, request
  * permission.
  */
 private static UsbDevice searchForCrazyradio(Context context, UsbManager usbManager) {
   UsbDevice device = null;
   HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
   // Iterate over USB devices
   for (Entry<String, UsbDevice> e : deviceList.entrySet()) {
     Log.i(
         LOG_TAG,
         "String: "
             + e.getKey()
             + " "
             + e.getValue().getVendorId()
             + " "
             + e.getValue().getProductId());
     if (isCrazyradio(e.getValue())) {
       device = e.getValue();
       break; // stop after first matching device is found
     }
   }
   if (device != null && !usbManager.hasPermission(device)) {
     Log.d(LOG_TAG, "Request permission");
     mPermissionIntent =
         PendingIntent.getBroadcast(
             context, 0, new Intent(context.getPackageName() + ".USB_PERMISSION"), 0);
     usbManager.requestPermission(device, mPermissionIntent);
   } else if (device != null && usbManager.hasPermission(device)) {
     Log.d(LOG_TAG, "Has permission");
   } else {
     Log.d(LOG_TAG, "device == null");
   }
   return device;
 }
예제 #8
0
 /**
  * Creates a new {@link UsbSerialDriver} instance for all compatible {@link UsbDevice}s found on
  * the bus. If no compatible devices are found, the list will be empty.
  *
  * @param usbManager
  * @return
  */
 public static List<UsbSerialDriver> findAllDevices(final UsbManager usbManager) {
   final List<UsbSerialDriver> result = new ArrayList<UsbSerialDriver>();
   // Log.i("QGC_UsbSerialProber", "Looking for USB devices");
   // For each UsbDevice, call probe() for each prober.
   for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
     // Log.i("QGC_UsbSerialProber", "Probing device: " + usbDevice.getDeviceName() + " mid: " +
     // usbDevice.getVendorId() + " pid: " + usbDevice.getDeviceId());
     result.addAll(probeSingleDevice(usbManager, usbDevice));
   }
   return result;
 }
예제 #9
0
 /**
  * Creates and returns a new {@link UsbSerialDriver} instance for the first compatible {@link
  * UsbDevice} found on the bus. If none are found, returns {@code null}.
  *
  * <p>The order of devices is undefined, therefore if there are multiple devices on the bus, the
  * chosen device may not be predictable (clients should use {@link #findAllDevices(UsbManager)}
  * instead).
  *
  * @param usbManager the {@link UsbManager} to use.
  * @return the first available {@link UsbSerialDriver}, or {@code null} if none are available.
  */
 public static UsbSerialDriver findFirstDevice(final UsbManager usbManager) {
   for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
     for (final UsbSerialProber prober : values()) {
       final List<UsbSerialDriver> probedDevices = prober.probe(usbManager, usbDevice);
       if (!probedDevices.isEmpty()) {
         return probedDevices.get(0);
       }
     }
   }
   return null;
 }
예제 #10
0
 private static UsbDevice findDevice(UsbManager usbManager, int venderId, int productId) {
   HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
   Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
   while (deviceIterator.hasNext()) {
     UsbDevice d = deviceIterator.next();
     Log.d(TAG, "device=" + d);
     if (d.getVendorId() == venderId && d.getProductId() == productId) {
       return d;
     }
   }
   return null;
 }
예제 #11
0
  @Override
  protected void onResume() {
    super.onResume();

    HashMap<String, UsbDevice> deviceList = mManager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      if (device.getProductId() == PID && device.getVendorId() == VID) {
        if (mManager.hasPermission(device)) mManager.requestPermission(device, mPermissionIntent);
        break;
      }
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.adb);
    mLog = (TextView) findViewById(R.id.log);

    mManager = (UsbManager) getSystemService(Context.USB_SERVICE);

    // check for existing devices
    for (UsbDevice device : mManager.getDeviceList().values()) {
      UsbInterface intf = findAdbInterface(device);
      if (setAdbInterface(device, intf)) {
        break;
      }
    }

    // listen for new devices
    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mUsbReceiver, filter);
  }
  // return true if a device is found
  boolean askForUSBPermission() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    // register someone to listen for "permission granted" dialogs
    PendingIntent permissionIntent =
        PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    usbListener = new InfiniTAMUSBPermissionListener();
    registerReceiver(usbListener, filter);

    // get a ist of USB devices
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

    // find the depth camera
    UsbDevice depthCamera = null;
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();

      if ((device.getVendorId() == 0x1d27) && (device.getProductId() == 0x0600)) {
        depthCamera = device;
      }
    }
    if (depthCamera == null) {
      usbListener = null;
      return false;
    }

    if (manager.hasPermission(depthCamera)) {
      usbListener.setDeviceWithPermission(depthCamera);
    } else {
      manager.requestPermission(depthCamera, permissionIntent);
    }

    return true;
  }
예제 #14
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!");
          }
        }