const handleReceiveData = async () => {
// Find the connected peripheral you want to receive data from
const connectedPeripheral = Array.from(peripherals.values()).find(
p => p.connected,
);
if (!connectedPeripheral) {
console.log('No connected peripheral found for receiving data');
return;
}
try {
await BleManager.retrieveServices(connectedPeripheral.id).then(
peripheralInfo => {
// Success code
console.log('Peripheral info:', peripheralInfo);
},
);
// Start notification on the characteristic
await BleManager.startNotification(
connectedPeripheral.id,
SERVICE_UUID,
CHARACTERISTIC_UUID,
)
.then(() => {
console.log('Started notification on ' + CHARACTERISTIC_UUID);
})
.catch(error => {
console.error('Notification error', error);
});
// Set up an event listener for when characteristic value updates
bleManagerEmitter.addListener(
'BleManagerDidUpdateValueForCharacteristic',
({value, peripheral, characteristic, service}) => {
// Check if this is the right characteristic
if (
peripheral === connectedPeripheral.id &&
characteristic === CHARACTERISTIC_UUID
) {
// Convert bytes array to string
const dataAsString = value
.map((byte: number) => String.fromCharCode(byte))
.join('');
setReceivedData(dataAsString);
console.log('Received data: ', dataAsString);
}
},
);
} catch (error) {
console.error('Failed to set up data reception', error);
}
};
我收到的所有时间都为错误:LOG Set notification failed for 6e400002-b5a3-f393-e0a9-e50e24dcca9e
我的 ble 设备工作正常。我使用“nRF Connect”应用程序测试了所有内容,这是包含接收到的数据的图片。交叉发布到GitHub上得到回答。在这里交叉发布答案:
在调用 startNotification 之前,我可以通过将 iOS 上已知的 128 位 UUID 压缩为其较短的 16 位版本来成功连接到我的蓝牙设备。
注:此代码仅处理 16 位 UUID。根据 CBUUID 的文档(请参阅其他上下文),完整的解决方案似乎还需要支持 32 位 UUID
function compressUUID(uuid: string): string { // Bluetooth 4.0 specification, Volume 3, Part F, Section 3.2.1 // https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=456433 // Required since react-native-ble-manager needs short UUIDs for notifications on // iOS, so I need to be able to compare them to the full UUIDs known for my devices. // CBUUID (iOS): // https://developer.apple.com/documentation/corebluetooth/cbuuid // Source: https://github.com/innoveit/react-native-ble-manager/blob/f46dd5c303ea0e70a44e299fb1ebabff86da9edd/ios/BleManager.swift#L381-L385 const baseUUID = /0000(....)-0000-1000-8000-00805F9B34FB/; if (baseUUID.test(uuid.toUpperCase())) { return uuid.substring(4, 8); } else { return uuid; } } BleManager.startNotification( "189fd3cb-fb2b-a6a6-b214-246d82f81298", compressUUID("0000aadb-0000-1000-8000-00805f9b34fb"), compressUUID("0000aadc-0000-1000-8000-00805f9b34fb"), )