question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Wait for successful pairing

See original GitHub issue
  • I am running the latest version
  • I checked the documentation and found no answer

Hi Guys, I posted this on github as well f y i, hope someone can give me some insight!

I’m new to bluetooth and to react native as well and I’ve encountered a problem that I’ve spent days on but I haven’t gotten anywhere.

I’m developing an app using the react-native-ble-plx library, but I encountered the same issue using react-native-ble-manager. I’ve been given a requirement that we need to have security level 3 with numeric comparison and in one of the first screens in the app the user should scan a QR code on the printer which gives the bluetooth library scanner the name it should look for so the user shouldn’t have to see any other devices.

This works fine but the problem is when the pairing starts, the app should wait until pairing has been completed before going to the next screen but I haven’t seen any way to do this. So what happens is that as soon as the device is connected and services are retrieved, the next then-function gets triggered even if the user aborted the pairing because technically I guess the connection is still active because its waiting for the pairing to complete. I’ve marked out what I mean in a code example.

So summarize, is there a way to wait for a successful pairing before allowing the user to the next stage? They’ll be potentially changing to many different devices all on the same day so I can’t really count on them just having to successfully pair just once and it’ll be fine. Thanks!

bleManager.startDeviceScan(
        null,
        {scanMode: ScanMode.LowLatency},
        (err, device) => {
          if (err) {
            setLoading(false);
            return;
          }

          if (device && device.name === printer.printerName) {
            bleManager.stopDeviceScan();
            device
              .connect({timeout: 10000})
              .then((d) => {
                return d.discoverAllServicesAndCharacteristics();
              })
              .then((d) => {
                //THIS SHOULD ONLY HAPPEN IF PAIRING WAS COMPLETED
                dispatch({
                  type: 'SET_PRINTER',
                  payload: {
                    printerId: d.id,
                    printerName: printer.printerName,
                    isBluetooth: printer.isBluetooth,
                    printerNetworkId: printer.id,
                  },
                });

                setLoading(false);

                navigation.canGoBack()
                  ? navigation.goBack()
                  : navigation.navigate(patientRoute);
              })
              .catch((error) => {
                console.log(error);
                setLoading(false);
              });

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:5

github_iconTop GitHub Comments

1reaction
Fivefoldcommented, Sep 29, 2021

I had the same problem of needing to wait until manager.startDeviceScan() was done with scanning and connection.

The solution is to wrap the manager.startDeviceScan() function in a promise and resolve that promise within device.connect().

Here’s an adaption of the official intro code:

export async function scanAndConnect() {
    let promise = new Promise((resolve, reject) => {
    manager.startDeviceScan(null, null, (error, device) => {
        if (error) {
        // Handle error (scanning will be stopped automatically)
        reject(error);
        }

        if (device.name === 'TI BLE Sensor Tag' || device.name === 'SensorTag') {
        // Stop scanning as it's not necessary if you are scanning for one device.
        manager.stopDeviceScan();

        // Proceed with connection.
        device
            .connect()
            .then((device) => {
            return device.discoverAllServicesAndCharacteristics();
            })
            .then((device) => {
            // Do work on device with services and characteristics
            console.log(
                `[INFO] BLE device connected! name: ${device.name}, id: ${device.id}`
            );
            resolve(true);
            })
            .catch((error) => {
            // Handle errors
            reject(error);
            });
        }
    });
    });

    let result = await promise;
    return result;
}

This returns true once the connection is finished. Of course you can return other things with resolve() too.

You can then call this function in some other part of your application:

scanAndConnect().then((res) => {
    // logic that should be executed after successful connection
    res
        ? console.log("[INFO] connection successful")
        : console.log("[INFO] connection failed");
});

Some more info on using Promises.

0reactions
stale[bot]commented, Jun 16, 2021

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

react native - How can I wait for a successful bluetooth pairing?
This works fine but the problem is when the pairing starts, the app should wait until pairing has been completed before going to...
Read more >
Pairing & Developing Rapport - I Love ABA!
You will know pairing has been successful when the child is consistently coming toward you, or approaching, and not walking away from you,...
Read more >
Pairing - KidsAbility
During pairing, allow your child free access to items or activities that your child loves, but ensure these reinforcing items are only available...
Read more >
How to Fix Bluetooth Pairing Problems - Techlicious
If your device is new, it will often be in pairing mode when you first turn it on. A good indicator that a...
Read more >
Pairing in ABA Therapy - SOAR Behavior Services
Pairing can be seen as unproductive play by parents and therapists alike, but while they might be waiting for the “real” learning to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found