我是 Web 开发领域的初学者。我想通过网页将 BLE 设备 (NRF52840 DK) 与我的移动设备配对。我测试了一个 Web 蓝牙示例,它在我的 PC 上运行良好,如下图所示:
将我的 PC (Chrome) 与 BLE 设备成功配对
我是通过 VS Code 上流行的扩展 Live Server 完成的。当我尝试使用我的 IP 和端口访问我的手机 (Android) 上的该页面并按下按钮时,什么也没发生。
将我的手机 (Chrome) 与 BLE 设备配对失败
有什么我没有考虑到的吗?
这是 HTML 和 JS 代码:
<!DOCTYPE html>
<html>
<head>
<title>BLE WebApp</title>
</head>
<body>
<form>
<button>Connect with BLE device</button>
</form>
<script>
var deviceName = 'Nordic_HRM'
function isWebBluetoothEnabled() {
if (!navigator.bluetooth) {
console.log('Web Bluetooth API is not available in this browser!')
return false
}
return true
}
function getDeviceInfo() {
let chosenHeartRateService = null;
console.log('Requesting Bluetooth Device...')
navigator.bluetooth.requestDevice({ filters: [{ services: ['heart_rate'] }] })
.then(device => device.gatt.connect())
.then(server => {
console.log("Getting HR Service…")
return server.getPrimaryService('heart_rate');
})
.then(service => {
chosenHeartRateService = service;
return Promise.all([
service.getCharacteristic('heart_rate_measurement')
.then(handleHeartRateMeasurementCharacteristic),
]);
})
}
function handleHeartRateMeasurementCharacteristic(characteristic) {
return characteristic.startNotifications()
.then(char => {
characteristic.addEventListener('characteristicvaluechanged',
onHeartRateChanged);
});
}
function onHeartRateChanged(event) {
const characteristic = event.target;
console.log(parseHeartRate(characteristic.value));
}
function parseHeartRate(data) {
const flags = data.getUint8(0);
const rate16Bits = flags & 0x1;
const result = {};
let index = 1;
if (rate16Bits) {
result.heartRate = data.getUint16(index, /*littleEndian=*/true);
index += 2;
} else {
result.heartRate = data.getUint8(index);
index += 1;
}
const contactDetected = flags & 0x2;
const contactSensorPresent = flags & 0x4;
if (contactSensorPresent) {
result.contactDetected = !!contactDetected;
}
const energyPresent = flags & 0x8;
if (energyPresent) {
result.energyExpended = data.getUint16(index, /*littleEndian=*/true);
index += 2;
}
const rrIntervalPresent = flags & 0x10;
if (rrIntervalPresent) {
const rrIntervals = [];
for (; index + 1 < data.byteLength; index += 2) {
rrIntervals.push(data.getUint16(index, /*littleEndian=*/true));
}
result.rrIntervals = rrIntervals;
}
return result;
}
document.querySelector('form').addEventListener('submit', function(event) {
event.stopPropagation()
event.preventDefault()
if (isWebBluetoothEnabled()) {
getDeviceInfo()
}
})
</script>
</body>
</html>