connect method

Future<bool> connect()

Implementation

Future<bool> connect() async {
  final completer = Completer<bool>();
  late StreamSubscription subscription;

  final connectedDevices = await _blue.connectedDevices;
  _log('already connected devices $connectedDevices');

  final device = connectedDevices.firstWhereOrNull((element) => element.name == advertisingName);
  bool deviceFound = false;
  if (device == null) {
    // Listen to scan results
    subscription = _blue.scanResults.listen((results) async {
      _log('scan results $results');
      final wantedDevice = results.firstWhereOrNull((element) => element.device.name == advertisingName);
      _log('wantedDevice $wantedDevice');
      if (wantedDevice != null) {
        deviceFound = true;
        try {
          // Stop scanning
          _blue.stopScan();
          subscription.cancel();
          await wantedDevice.device.connect(autoConnect: false, timeout: Duration(seconds: 4));
          _services = await wantedDevice.device.discoverServices();
          await _wifiResponse?.setNotifyValue(true);
          if (completer.isCompleted) {
            _log('search already completed, ignored connected device');
          } else {
            this._connectedDevice = wantedDevice.device;
            completer.complete(true);
            _log('device found $wantedDevice');
          }
        } catch(err) {
          if (completer.isCompleted) {
            _log('search already completed, ignoring error $err');
          } else {
            completer.completeError(err);
          }
        }
      }
    });
    _log('startScan');

    // Start scanning
    if (await _blue.isScanning.first) {
      await _blue.stopScan();
    }

    await _blue.startScan(timeout: Duration(seconds: 4)).catchError((err) {
      completer.completeError(err);
    });

    if (!completer.isCompleted && !deviceFound) {
      subscription.cancel();
      completer.completeError(NoDeviceException());
    }
  } else {
    final state = await device.state.firstWhere((element) => element == BluetoothDeviceState.connected, orElse: (() => BluetoothDeviceState.disconnected));
    if (state == BluetoothDeviceState.disconnected) {
      await device.connect(autoConnect: false, timeout: Duration(seconds: 4));
    }

    _services = await device.discoverServices();
    await _wifiResponse?.setNotifyValue(true);
    completer.complete(true);
  }
  return completer.future;
}