React Native-有办法在外围模式下使用蓝牙吗



我正在离线开发ReactNative中的应用程序。其中一个功能是使用蓝牙将(应用程序正在收集的(数据与使用同一应用程序的其他设备同步。

我开始用react native ble管理器库开发这个任务,我可以从设备A连接到设备B,但我不知道如何监听设备B中的传入连接。我需要知道这一点才能显示特定的视图。

有人能帮我吗?我使用的是正确的库吗?

谢谢!

注意:这个答案仅适用于iOS,因为react原生外设尚未实现Android支持

对于这个项目,不能只使用react本机ble管理器。图书馆在其自述中表示,它是基于cordova插件中心的,该中心只能充当中心。对于BLE连接,您需要一个中央和一个外围设备。

看看react原生外设。它允许你充当外设,用一些数据创建一个特征,将其添加到服务中并注册,以便其他设备可以找到它

import Peripheral, { Service, Characteristic } from 'react-native-peripheral'
Peripheral.onStateChanged(state => {
// wait until Bluetooth is ready
if (state === 'poweredOn') {
// first, define a characteristic with a value
const ch = new Characteristic({
uuid: '...',
value: '...', // Base64-encoded string
properties: ['read', 'write'],
permissions: ['readable', 'writeable'],
})
// add the characteristic to a service
const service = new Service({
uuid: '...',
characteristics: [ch],
})
// register GATT services that your device provides
Peripheral.addService(service).then(() => {
// start advertising to make your device discoverable
Peripheral.startAdvertising({
name: 'My BLE device',
serviceUuids: ['...'],
})
})
}
})

有一节是关于动态值的,它们解释了如何使用onReadRequestonWriteRequest回调来侦听外围设备上的读写操作,甚至在每个读请求时返回动态值:

new Characteristic({
uuid: '...',
properties: ['read', 'write'],
permissions: ['readable', 'writeable'],
onReadRequest: async (offset?: number) => {
const value = '...' // calculate the value
return value // you can also return a promise
},
onWriteRequest: async (value: string, offset?: number) => {
// store or do something with the value
this.value = value
},
})

最新更新