open method

  1. @override
Future<bool> open(
  1. UsbDevice usbDevice
)
override

Implementation

@override
Future<bool> open(UsbDevice usbDevice) async {
  try {
    final activeDevice = _foundDevices.firstWhere(
      (e) => e.serialNumber == usbDevice.identifier,
      orElse: () => throw Exception('Device not found'),
    );

    await activeDevice.open();

    final configuration = await activeDevice.configuration;
    if (configuration == null) {
      throw Exception('No configuration found');
    }
    await activeDevice.selectConfiguration(configuration.configurationValue);

    final allInterfaces = await activeDevice.interfaces;
    if (allInterfaces.isEmpty) {
      throw Exception('No interfaces found');
    }

    List<USBInterface> eligibleInterfaces = allInterfaces
        .where(
          (e) =>
              !e.claimed &&
              e.alternate.endpoints.any(
                (e) => e.direction == _usbInterfaceDirectionIn,
              ) &&
              e.alternate.endpoints.any(
                (e) => e.direction == _usbInterfaceDirectionOut,
              ),
        )
        .toList(growable: false);

    if (eligibleInterfaces.isEmpty) {
      throw Exception('No eligible interfaces found');
    }

    USBInterface? claimedInterface;
    for (final interface in eligibleInterfaces) {
      if (interface.claimed) continue;

      try {
        await activeDevice.claimInterface(interface.interfaceNumber);
        claimedInterface = interface;
        break;
      } catch (e) {
        debugPrint('Error in claimInterface: $e');
        continue;
        // if (e.toString().contains('SecurityError')) {
        //   continue;
        // } else {
        //   rethrow;
        // }
      }
    }

    if (claimedInterface == null) {
      throw Exception('No eligible interface could be claimed.');
    }

    final endpoints = claimedInterface.alternate.endpoints;
    final inEndpoint = endpoints.firstWhere(
      (e) => e.direction == _usbInterfaceDirectionIn,
      orElse: () => throw Exception(
          'wtf: IN endpoint not found anymore on eligible interface'),
    );
    final outEndpoint = endpoints.firstWhere(
      (e) => e.direction == _usbInterfaceDirectionOut,
      orElse: () => throw Exception(
          'wtf: OUT endpoint not found anymore on eligible interface'),
    );

    _activeDevice = (
      device: activeDevice,
      inEndpointNumber: inEndpoint.endpointNumber,
      outEndpointNumber: outEndpoint.endpointNumber
    );
    return true;
  } catch (e) {
    debugPrint('Error in open: $e');
    return false;
  }
}