getDevice method

Pointer<libusb_device>? getDevice(
  1. int vendorId,
  2. int productId
)

Implementation

Pointer<libusb_device>? getDevice(int vendorId, int productId) {
  final deviceListPtr = calloc<Pointer<Pointer<libusb_device>>>();
  final ctxPtr = calloc<Pointer<libusb_context>>();

  if (_bindings.libusb_init(ctxPtr) < 0) {
    log("Error inicializando libusb");
    return null;
  }

  int deviceCount =
      _bindings.libusb_get_device_list(ctxPtr.value, deviceListPtr);
  if (deviceCount < 0) {
    log("Could not get device list");
    return null;
  }

  for (int i = 0; i < deviceCount; i++) {
    final device = deviceListPtr.value[i];
    final descriptor = calloc<libusb_device_descriptor>();

    if (_bindings.libusb_get_device_descriptor(device, descriptor) == 0) {
      if (descriptor.ref.idVendor == vendorId &&
          descriptor.ref.idProduct == productId) {
        log("USB device found -> vendorId: $vendorId - productId: $productId");
        calloc.free(descriptor);
        return device; // 🔹 Retornar el dispositivo, no solo el handle
      }
    }
    calloc.free(descriptor);
  }

  _bindings.libusb_free_device_list(deviceListPtr.value, 1);
  return null;
}