dotintent / FlutterBleLib

Bluetooth Low Energy library for Flutter with support for simulating peripherals
Apache License 2.0
537 stars 197 forks source link

Scanning for devices #595

Open ahoelzemann opened 3 years ago

ahoelzemann commented 3 years ago

Hello everyone,

I wrote the following method to scan for nearby bluetooth devices and connect to an earlier saved device.

  Future<dynamic> start_ble_scan() async {
    Completer completer = new Completer();

    if (_mydevice != null) {
      bool connected = await _mydevice.isConnected();
      print("DeviceState: " + connected.toString());
      if (connected) {
        try {
          await _responseSubscription?.cancel();
          await _characSubscription?.cancel();
          await _condeviceStateSubscription?.cancel();
          await _mydevice.disconnectOrCancelConnection();
          _mydevice = null;
          _currentDeviceConnected = false;
        } catch (e) {
          print("Disconnecting device before new scan process");
        }
      }
    }

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String savedDevice = prefs.getString("Devicename");
    String savedIdentifier = prefs.getString("macnum");
    bool alreadyStoppedScanning = false;

    _bleonSubscription = _activateBleManager
        .startPeripheralScan()
        .timeout(Duration(seconds: 30), onTimeout: (timeout) async {
      if (!alreadyStoppedScanning) {
        await _activateBleManager.stopPeripheralScan();
      }
    }).listen(
      (data) async {
        if ((data.peripheral.name == savedDevice) ||
            (data.peripheral.identifier == savedIdentifier)) {
          if (!alreadyStoppedScanning) {
            alreadyStoppedScanning = true;
            _mydevice = data.peripheral;
            print("Device found: " + _mydevice.toString());
            await _activateBleManager.stopPeripheralScan();
            _bleonSubscription?.cancel();
          } 

        }
      },
      onError: (err) {
        print('Error!: $err');
      },
      cancelOnError: true,
      onDone: () async {
        print("Device found: " + _mydevice.toString());
        completer.complete(true);
      },
    );
    return completer.future;
  }

however, this method doesn't always returns the desired result. Sometimes I jump directly into the timeout which stops the scan immediately and does not connect my device.

Someone has an idea what I'm doing wrong?

thanks and best regards!

bretmh commented 3 years ago

Please create a test project and implement the breaking code. I would try to only show an example of this with FlutterBleLib and no other packages / noisy code.

You have two places where you stop the scan and one place where you disconnect/cancel connections.