connect method

Future<void> connect(
  1. BluetoothDevice device
)

Connect to a BLE device.

Connects to device and discovers its services.

Implementation

Future<void> connect(BluetoothDevice device) async {
  if (state is! BleDeviceScanning) {
    logger.severe("Not in scanning state");
    return;
  }

  await stopScanning();

  if (!(state as BleDeviceScanning).discoveredDevices.contains(device)) {
    logger.severe("Device not found in the list of discovered devices");
    return;
  }

  emit(BleDeviceConnecting(
    device: device,
    connectionState: BluetoothConnectionState.disconnected,
  ));

  /* skip one to avoid the initial connection state (disconnected) to
   * be emitted
   */
  _conStateSubs = device.connectionState.skip(1).listen(
    (event) => _onConnectionUpdate(device, event),
    onError: (e) {
      logger.severe("Error callback called on connectToDevice stream");
      emit(
        BleDeviceFailedToConnect(
          device: device,
          errorMessage: e.toString(),
        ),
      );
    },
  );

  final success = await _tryFbpOperation(
      device, "connecting to device ${device.platformName}", () async {
    await device.connect(timeout: const Duration(seconds: 10));
    if (!device.isConnected) {
      logger.warning("connection failed");
      emit(
        BleDeviceFailedToConnect(
          device: device,
          errorMessage: "Connection failed",
        ),
      );
    } else {
      logger.info("connected to device ${device.platformName}");
    }
    if (Platform.isAndroid) {
      await device.requestConnectionPriority(
          connectionPriorityRequest: ConnectionPriority.high);
    }
  });
  if (success) {
    await discoverServices();
  }
}