我在蓝牙 RN 应用程序中运行一些异步代码时遇到问题。
我正在尝试创建一个执行以下操作的侦听器函数:连接到设备(使用异步函数),记录我已连接,然后断开与设备的连接(使用异步函数)。
此侦听器功能作为蓝牙低功耗 (ble) 设备扫描功能的参数提供:
// Relevant Function Prototypes --------------------------------------------------
// startDeviceScan() -> This scans for devices and runs a listener function on each
// device it scans.
bleManager.startDeviceScan(
UUIDs: ?Array<UUID>,
options: ?ScanOptions,
listener: (error: ?Error, scannedDevice: ?Device) => void // <- this listener function
)
// connectToDevice() -> This connects to a device scanned by the bleManager in the
// listener function given to startDeviceScan()
bleManager.connectToDevice(
deviceIdentifier: DeviceId,
options: ?ConnectionOptions,
): Promise<Device>
// My code ------------------------------------------------------------------------
// Scans nearby ble devices advertising and runs a listener function that has the
// connection error status and device id as given parameters.
// **This function triggers on a Button onPress
const handleStartScanning = async () => {
try {
bleManager.startDeviceScan(
['00001200-0000-1000-8000-00805f9b34fb'], // the service UUID I am scanning for
{ allowDuplicates: true }, // I allow to duplicates to continuously reconnect to devices
async (error, device) => {
// get services
let services = device.serviceUUIDs // get list of the service UUIDs on device
// make sure services not null and out service UUID is included
if (services && services.includes('00001200-0000-1000-8000-00805f9b34fb')) {
}
}
)
}
我不明白为什么即使我使侦听器函数异步并等待侦听器中的 2 个异步函数调用,日志Connected to Device也不会打印。await bleManager.connectToDevice(device.id)这意味着侦听器永远不会在异步函数调用之后执行
守着星空守着你
相关分类