uniapp如何同时监听多个蓝牙设备的特征值变化
在uniapp中如何同时监听多个蓝牙设备的特征值变化?我已经能够成功连接单个设备并监听其特征值变化,但当尝试同时连接多个设备时,发现无法同时监听所有设备的特征值更新。请问有没有办法实现同时监听多个蓝牙设备的特征值变化?需要如何设置回调函数或处理多个设备的特征值通知?
2 回复
在uniapp中,使用uni.onBLECharacteristicValueChange监听特征值变化。为多个设备分别建立连接后,每个设备的特征值变化都会触发此回调。在回调中通过deviceId区分不同设备,实现同时监听。
在 UniApp 中,可以通过 H5+ API 或 uni-app 的蓝牙 API 同时监听多个蓝牙设备的特征值变化。以下是实现步骤和示例代码:
实现步骤
- 初始化蓝牙模块:使用
uni.openBluetoothAdapter初始化。 - 发现设备并连接:通过
uni.startBluetoothDevicesDiscovery发现设备,使用uni.createBLEConnection连接目标设备。 - 获取服务与特征值:连接后,通过
uni.getBLEDeviceServices和uni.getBLEDeviceCharacteristics获取设备的服务和特征值。 - 启用特征值通知:对每个设备的特征值调用
uni.notifyBLECharacteristicValueChange启用通知。 - 监听特征值变化:通过
uni.onBLECharacteristicValueChange监听特征值变化,并在回调中处理数据。
示例代码
// 初始化蓝牙
uni.openBluetoothAdapter({
success: () => {
// 开始搜索设备
uni.startBluetoothDevicesDiscovery({
success: () => {
// 假设已知设备 deviceId,实际中需通过 onBluetoothDeviceFound 获取
const deviceIds = ['deviceId1', 'deviceId2']; // 多个设备 ID
deviceIds.forEach(deviceId => {
connectAndListenToDevice(deviceId);
});
}
});
}
});
// 连接设备并监听特征值
function connectAndListenToDevice(deviceId) {
// 连接设备
uni.createBLEConnection({
deviceId,
success: () => {
// 获取服务
uni.getBLEDeviceServices({
deviceId,
success: (res) => {
const serviceId = res.services[0].uuid; // 假设使用第一个服务
// 获取特征值
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (charRes) => {
const characteristic = charRes.characteristics.find(c => c.properties.notify);
if (characteristic) {
// 启用通知
uni.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: characteristic.uuid,
state: true,
success: () => {
console.log(`监听设备 ${deviceId} 特征值成功`);
}
});
}
}
});
}
});
}
});
}
// 统一监听特征值变化
uni.onBLECharacteristicValueChange((res) => {
console.log(`设备 ${res.deviceId} 特征值变化:`, res.value);
// 根据 deviceId 区分设备,处理数据
if (res.deviceId === 'deviceId1') {
// 处理设备1的数据
} else if (res.deviceId === 'deviceId2') {
// 处理设备2的数据
}
});
注意事项
- 设备管理:使用数组或对象存储多个设备的
deviceId,在回调中通过res.deviceId区分来源。 - 错误处理:添加
fail回调处理连接或监听失败情况。 - 性能优化:避免频繁操作蓝牙,按需连接和监听。
- 平台差异:测试 Android 和 iOS 的兼容性,部分 API 可能有平台限制。
通过以上方法,即可在 UniApp 中同时监听多个蓝牙设备的特征值变化。

