connect method

Future<bool> connect(
  1. Printer device, {
  2. Duration? connectionStabilizationDelay,
})

Connect to a printer device

device The printer device to connect to. connectionStabilizationDelay Optional delay to wait after connection is established before considering it stable. Defaults to BleConfig.connectionStabilizationDelay.

Implementation

Future<bool> connect(
  Printer device, {
  Duration? connectionStabilizationDelay,
}) async {
  if (device.connectionType == ConnectionType.USB) {
    if (Platform.isWindows) {
      // Windows USB connection - device is already available, no connection needed
      return true;
    } else {
      return FlutterThermalPrinterPlatform.instance.connect(device);
    }
  } else if (device.connectionType == ConnectionType.BLE) {
    try {
      if (device.address == null) {
        log('Device address is null');
        return false;
      }

      final isConnected =
          (await UniversalBle.getConnectionState(device.address!) ==
              BleConnectionState.connected);
      if (isConnected) {
        log('Device ${device.name} is already connected');
        return true;
      }
      final connectionCompleter = Completer<bool>();
      log('Connecting to BLE device ${device.name} at ${device.address}');

      StreamSubscription? subscription;

      try {
        // Listen to global connection changes
        subscription = device.connectionStream.listen((state) {
          log('Connection state changed for device ${device.name}: $state');
          if (state) {
            if (!connectionCompleter.isCompleted) {
              connectionCompleter.complete(true);
            }
          }
        });

        await device.connect();
        final delay = connectionStabilizationDelay ??
            bleConfig.connectionStabilizationDelay;
        return await connectionCompleter.future.timeout(
          delay,
          onTimeout: () {
            log('Connection to device ${device.name} timed out');
            return false;
          },
        );
      } catch (e) {
        log('Error connecting to device: $e');
        return false;
      } finally {
        await subscription?.cancel();
      }
    } catch (e) {
      log('Failed to connect to BLE device: $e');
      return false;
    }
  }
  return false;
}