[英]bleManager.startDeviceScan not working on iOS react-native-ble-plx
我正在尝试使用 react-native-ble-plx 将网关与 React 本机应用程序配对。 下面的源代码在 Android 中工作正常,而在 iOS 中,bleManager.startDeviceScan() 没有被触发。 这一步之后没有任何反应。
任何帮助深表感谢!
源代码:
const connectBLE = () => {
const subscription = bleManager.onStateChange(async (state) => {
if (state === 'PoweredOn') {
subscription.remove();
scanAndConnect();
}
};
}
const scanAndConnect = () => {
bleManager.startDeviceScan(null, null, async (error, device) => {
if (error) {
showToast(error, 'error');
console.log('Handle error - scanning will be stopped automatically');
return;
}
console.log('Devices');
console.log(device.name);
// Check if it is a device you are looking for based on device name
if (device.name === "BLE_0006") {
// Stop scanning as we have found the device.
bleManager.stopDeviceScan();
// Establish Device connection.
device
.connect()
.then((deviceData) => {
/** Show Toast on Device disconnect */
bleManager.onDeviceDisconnected(
deviceData.id,
(connectionError, connectionData) => {
if (connectionError) {
console.log(connectionError);
}
console.log('Device is disconnected');
console.log(connectionData);
},
);
/** Discover All Services and Characteristics */
return device.discoverAllServicesAndCharacteristics();
})
.then(async (deviceObject) => {
console.log('deviceObject');
console.log(deviceObject);
/** Subscribe for the Readable service */
device.monitorCharacteristicForService(
Enum.bleConnectionInfo.customServiceUUID,
Enum.bleConnectionInfo.readCharacteristicUUID,
(error, characteristic) => {
if (error) {
console.log('Error in monitorCharacteristicForService');
console.log(error.message);
return;
}
console.log(characteristic.uuid, characteristic.value);
]);
},
);
})
.catch((error) => {
console.warn(error);
showToast(error, 'error');
});
}
});
}
这可能对某人有帮助!
通过将 bleManager() 初始化移到功能组件之外,该问题已得到解决。
@Aarthi 我不明白你的解决方案,我做到了。
const bleManager = new BleManager();
export default class BluetoothController {
static scanDevices(continuousScan: boolean, deviceId: string) {
this.scanEvent();
if (!isScanning || !continuousScan) {
log.info("scanDevices");
isScanning = true;
bleManager.startDeviceScan(
deviceId ? [deviceId] : null,
{allowDuplicates: true, scanMode: ScanMode.Balanced},
(error, bleDevice) => {
isScanning = false;
if (error) {
log.info("scan error, restarting", error);
return;
}
let advertisement = bleDevice.name === "myDevice"
? this.decodeDacAdvertisement(bleDevice)
: null;
if (advertisement) {
blueToothEventManager.emit("MyDeviceEvent", advertisement);
}
}
);
}
}
}
但是,我有问题,有时在 Android 中没有调用回调 bleManager.startDeviceScan(...,..., callback)。 你有什么主意吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.