Exemple #1
0
  /**
   * findDevice - finds and returns the device that is lasted connected, and matches both the vendor
   * and product id (please use enums provided in MindStormDevice for parameters)
   *
   * @param vendorId - vendor id for USB device
   * @param productId - product id for USB device
   * @return
   */
  private static Device findDevice(short vendorId, short productId) {
    // Read the USB device list
    DeviceList list = new DeviceList();
    Context context = new Context();
    LibUsb.init(context);
    int result = LibUsb.getDeviceList(context, list);
    if (result < 0) throw new LibUsbException("Unable to get device list", result);

    try {
      // Iterate over all devices and scan for the right one
      for (Device device : list) {
        DeviceDescriptor descriptor = new DeviceDescriptor();
        result = LibUsb.getDeviceDescriptor(device, descriptor);
        if (result != LibUsb.SUCCESS)
          throw new LibUsbException("Unable to read device descriptor", result);
        if (descriptor.idVendor() == vendorId && descriptor.idProduct() == productId) return device;
      }
    } finally {
      // Ensure the allocated device list is freed
      LibUsb.freeDeviceList(list, true);
    }

    // Device not found
    return null;
  }