connect method

Future<bool> connect(
  1. Printer device, {
  2. Duration? connectionTimeout,
  3. @Deprecated('Use connectionTimeout instead.') Duration? connectionStabilizationDelay,
})

Connect to a printer device

device The printer device to connect to. connectionTimeout How long to wait for a BLE or network printer to connect. Defaults to BleConfig.connectionTimeout for BLE and 5 seconds for network.

Implementation

Future<bool> connect(
  Printer device, {
  Duration? connectionTimeout,
  @Deprecated('Use connectionTimeout instead.')
  Duration? connectionStabilizationDelay,
}) async {
  if (_usesSystemQueue(device) ||
      device.connectionType == ConnectionType.USB) {
    if (Platform.isWindows) {
      // The spooler opens the port per job; there is nothing to connect.
      return _windowsQueueReady(device);
    } else {
      return FlutterThermalPrinterPlatform.instance.connect(device);
    }
  } else if (device.connectionType == ConnectionType.NETWORK) {
    final result = await _networkClient(
      device,
    )?.connect(timeout: connectionTimeout ?? connectionStabilizationDelay);
    return result == NetworkPrintResult.success;
  } else if (device.connectionType == ConnectionType.BLE) {
    try {
      if (device.address == null) {
        log('Device address is null');
        return false;
      }
      final address = device.address!;
      _ensureBleConnectionListener(address, fallbackName: device.name);

      final isConnected = await _isBleDeviceConnected(address);
      if (isConnected) {
        _updateBleConnectionState(address, true, fallbackName: device.name);
        log('Device ${device.name} is already connected');
        return true;
      }
      log('Connecting to BLE device ${device.name} at $address');
      // stopScan() cancels the listener that would have cleared this.
      _bleWriteTargets.remove(address);
      // Completes once connected; throws on failure or timeout.
      await device.connect(
        timeout:
            connectionTimeout ??
            connectionStabilizationDelay ??
            bleConfig.connectionTimeout,
      );
      _updateBleConnectionState(address, true, fallbackName: device.name);
      return true;
    } catch (e) {
      log('Failed to connect to BLE device: $e');
      return false;
    }
  }
  return false;
}