Can't stop scanning and connect to device via react native ble manager

1.3k Views Asked by At

React Native application with BLE Manager for interacting with BLE devices.

I am able to scan for devices, by default running for 10 sec.

Expected action, when I find a device & click on Connect Button [on same page, where devices are being scanned], I need to stop scanning further and initiate the Connection.

Issue is, its not responding to the button action during the scanning. Only after scanning is done after given time, connection request is initiated.

Code snippet is given below, when connect button is clicked.

    try {
      console.log('connect....');
      await BleManager.stopScan();
      setIsScanning(false);
      await connectBle(peripheral.id);
      Alert.alert(
        'Alert Title',
        `Successfully Connected to ${peripheral.name}`,
        [
          {
            text: 'OK',
            onPress: () => handleConnected(peripheral),
          },
        ],
      );
      getConnectedPeripherals();
      var newPeripherals1 = newPeripherals.filter(n => n.id !== peripheral.id);
      console.log('newPeripherals1111', newPeripherals1);
      setNewPeripherals(newPeripherals1);
    } catch (error) {
      Alert.alert(
        'Alert Title',
        `Successfully Connected to ${peripheral.name}`,
        [
          {
            text: 'OK',
            onPress: () => {},
            // navigation.navigate('Configuration', {
            //   peripheral: peripheral,
            // }),
          },
        ],
      );
    }
  }```
1

There are 1 best solutions below

0
On

Refer this example:

https://github.com/innoveit/react-native-ble-manager/blob/master/example/App.js

In this example you can get the connect and disconnect the ble devices.