所以我尝试用一些代码测试蓝牙连接。每当我尝试扫描蓝牙设备时,我没有弹出窗口来允许它,所以它一直在等待。我知道代码工作,因为我们是在组中工作,它在我的合作伙伴的MacOS电脑上工作,但在我的Windows上不工作。我主要希望它扫描带有BLE的ESP。我已经启用了"实验性的网络平台功能“和”使用新的权限后端网络蓝牙“标志,并确保我的Chrome更新,并确保蓝牙扫描和设备的权限启用。
console.log("Init");
document.getElementById("scan").onclick = scan;
navigator.bluetooth.addEventListener("advertisementreceived", (event) => {
console.log("Advertisement", event);
});
async function scanDevices() {
const devices = await navigator.bluetooth.getDevices();
console.log(devices);
}
async function scan() {
console.log("Scanning...");
let options = {
acceptAllAdvertisements: true,
};
try {
log("Requesting Bluetooth Scan with options: " + JSON.stringify(options));
const scan = await navigator.bluetooth.requestLEScan(options);
log("Scan started with:");
log(" acceptAllAdvertisements: " + scan.acceptAllAdvertisements);
log(" active: " + scan.active);
log(" keepRepeatedDevices: " + scan.keepRepeatedDevices);
log(" filters: " + JSON.stringify(scan.filters));
navigator.bluetooth.addEventListener("advertisementreceived", (event) => {
log("Advertisement received.");
log(" Device Name: " + event.device.name);
log(" Device ID: " + event.device.id);
log(" RSSI: " + event.rssi);
log(" TX Power: " + event.txPower);
log(" UUIDs: " + event.uuids);
event.manufacturerData.forEach((valueDataView, key) => {
logDataView("Manufacturer", key, valueDataView);
});
event.serviceData.forEach((valueDataView, key) => {
logDataView("Service", key, valueDataView);
});
});
setTimeout(stopScan, 10000);
function stopScan() {
console.log("Scan result", scan);
log("Stopping scan...");
scan.stop();
log("Stopped. scan.active = " + scan.active);
}
} catch (error) {
log("Argh! " + error);
}
}
function log(c) {
console.log(c);
}
1条答案
按热度按时间i7uaboj41#
使用requestDevice弹出选择器UI。