connect method

Future<BluetoothDeviceState> connect({
  1. Duration? timeout,
  2. bool autoConnect = true,
})

Establishes a connection to the Bluetooth Device.

Implementation

Future<BluetoothDeviceState> connect({
  Duration? timeout,
  bool autoConnect = true,
}) async {
  var request = protos.ConnectRequest.create()
    ..remoteId = id.toString()
    ..androidAutoConnect = autoConnect;

  // if we have a running connect process, return with the future
  if (_connectCompleter != null) {
    if (!(_connectCompleter!.isCompleted)) {
      return _connectCompleter!.future;
    }
  }

  // if we are connected return with the last state
  if (_lastState != null && _lastState is BluetoothDeviceConnected) {
    return _lastState!;
  }

  // else start a new connect process
  _connectCompleter = Completer<BluetoothDeviceState>();
  // this 2 call shouldn't be necessary so test it without them??
  _connectTimeoutTimer?.cancel();
  _connectTimeoutTimer = null;
  _stateSubscription?.cancel();
  _stateSubscription = null;

  var firsStateArrived = false;
  _stateSubscription = state.listen((state) {
    if (firsStateArrived &&
        (state is BluetoothDeviceConnected ||
            state is BluetoothDeviceDisconnected)) {
      _connectTimeoutTimer?.cancel();
      _stateSubscription!.cancel();
      _stateSubscription = null;
      _connectCompleter!.complete(state);
      _connectCompleter = null;
      return;
    }
    firsStateArrived = true;
  }, onError: (err) {
    _connectTimeoutTimer?.cancel();
    _stateSubscription!.cancel();
    _stateSubscription = null;
    _connectCompleter!.completeError(err);
    _connectCompleter = null;
  });

  if (timeout != null) {
    _connectTimeoutTimer = Timer(timeout, () {
      _stateSubscription?.cancel();
      _connectCompleter!.completeError(TimeoutException('BLE connect'));
      _connectCompleter = null;
    });
  }

  final returnFuture = _connectCompleter!.future;

  await FlutterBlue.instance._channel
      .invokeMethod('connect', request.writeToBuffer());

  return returnFuture;
}