Search code examples
react-nativebluetooth-lowenergyreact-native-ble-plx

How to know when monitorCharacteristic is done with react native ble plx?


I use react-native-ble-plx in my project to communicante with my tool, and I'm trying to monitor one of its characteristics.

The result is rather long so the monitoringCharacteristic function is looping until it has send me everything, but I don't know how to be sure that the loop is done.

Here is my monitoring function :

const scanMyDevice = async (device) => {

    const serviceUUID = '569a1-****'
    const writeUUID = '569a2-****'
    const readUUID = '569a2-****'

    await device.discoverAllServicesAndCharacteristics()
    await device.characteristicsForService(serviceUUID)

    await device.writeCharacteristicWithResponseForService(serviceUUID, writeUUID, 'IzEwCg==')

    var tempTrame = ''

    const subscription = device.monitorCharacteristicForService(serviceUUID, readUUID, (error, a) => {

      if (error) {
        console.log(error)
        console.log(error.message)
      }
      else {
        tempTrame = tempTrame + base64.decode(a.value)
        setTrameResult(tempTrame)
        console.log('// INSIDE ///', tempTrame)
      }
    }, 'idMonitor')

    return () => {
      subscription.remove();
    }

    console.log('DONE')
  }

In my code, 'DONE' is going to be printed before 'INSIDE trame'.

I tried to put console.log('DONE') inside the return, but then it was never printed. I tried to put .then( console.log('DONE')) just before return but it sent me an error saying that it has nothing to do here...

Can someone help me please ?


Solution

  • Finally I went around the problem by defining an ending pattern to the info I wanted to send/read via BLE, and then I wrote a loop to continue reading while the ending pattern was not encountered:

    let tempTrame = tempTrame + base64.decode(a.value)
    let finalTrame = ''
    
    // check if my variable has the end symbols (to be sure that I have all the information) and if it is the first time I get this information
    if (tempTrame.includes('#109F')) {
    
        stop = true
    
        // suppress end symbols
        tempTrame = tempTrame.replace(endTrame, '')
        finalTrame = tempTrame
    }
    console.log(finalTrame)