0

我在我的项目中使用 react-native-ble-plx 来与我的工具进行通信,并且我正在尝试监视它的一个特征。

结果相当长,因此 monitoringCharacteristic 函数一直在循环,直到它向我发送所有内容,但我不知道如何确保循环完成。

这是我的监控功能:

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')
  }

在我的代码中,“DONE”将在“INSIDE Trame”之前打印。

我试图把它放进console.log('DONE')return,但它从来没有被打印出来。.then( console.log('DONE'))我之前试图放,return但它给我发了一个错误,说它与这里无关......

有人能帮助我吗 ?

4

1 回答 1

1

最后我通过为我想通过BLE发送/读取的信息定义一个结束模式来解决这个问题,然后我写了一个循环来继续阅读,而没有遇到结束模式:

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)
于 2022-02-14T11:17:31.893 回答