getDeviceDetails method

Map<String, dynamic> getDeviceDetails(
  1. int vendorId,
  2. int productId
)

Implementation

Map<String, dynamic> getDeviceDetails(int vendorId, int productId) {
  final deviceHandlePtr =
      _bindings.libusb_open_device_with_vid_pid(nullptr, vendorId, productId);

  if (deviceHandlePtr == nullptr) {
    final errorCode =
        -1; // No hay un código de error directo, usamos un valor genérico
    final errorMessage = "Could not open device (unknown error)";
    log("Error al abrir el dispositivo: $errorMessage (Código: $errorCode)");

    return {
      'error': 'Could not open device',
      'errorCode': errorCode,
      'message': errorMessage
    };
  }

  try {
    final configDescriptor = calloc<Pointer<libusb_config_descriptor>>();

    // Get the active configuration descriptor
    final result = _bindings.libusb_get_active_config_descriptor(
        nullptr, configDescriptor);

    if (result < 0) {
      return {
        'error': 'Could not obtain configuration descriptor',
        'errorCode': result,
        'message':
            _bindings.libusb_error_name(result).cast<Utf8>().toDartString()
      };
    }

    final config = configDescriptor.value;

    // Extract interface and endpoint information
    List<Map<String, dynamic>> interfaces = [];

    // Print available fields for debugging
    log("Available fields in config.ref: ${config.ref.toString()}");

    final numInterfaces = config.ref.bNumInterfaces;
    log("Number of interfaces: $numInterfaces");

    for (int i = 0; i < numInterfaces; i++) {
      final interfaceNumber =
          _bindings.libusb_claim_interface(deviceHandlePtr, i);
      interfaces.add({
        'interfaceNumber': interfaceNumber,
        'endpoints': [],
      });
    }

    // Free resources
    _bindings.libusb_free_config_descriptor(config);

    return {
      'configValue': config.ref.bConfigurationValue,
      'maxPower': config.ref.MaxPower,
      'selfPowered': (config.ref.bmAttributes & 0x40) != 0,
      'remoteWakeup': (config.ref.bmAttributes & 0x20) != 0,
      'numInterfaces': numInterfaces,
      'interfaces': interfaces
    };
  } catch (e) {
    return {
      'error': 'Error obtaining device details',
      'message': e.toString()
    };
  } finally {
    closeDevice(deviceHandlePtr);
  }
}