【发布时间】:2021-12-06 07:30:37
【问题描述】:
我需要使用 Web 蓝牙 API 在 Web 应用程序中从 Leica Disto D2 读取距离测量值。我的目标是最近的 Android 设备,所以 Chrome/三星浏览器 should support it。
【问题讨论】:
标签: android google-chrome bluetooth web-bluetooth
我需要使用 Web 蓝牙 API 在 Web 应用程序中从 Leica Disto D2 读取距离测量值。我的目标是最近的 Android 设备,所以 Chrome/三星浏览器 should support it。
【问题讨论】:
标签: android google-chrome bluetooth web-bluetooth
除非使用 localhost 进行测试,否则通过 HTTPS 提供 HTML。必须从用户手势开始:
<button onclick="discoverDevices()">Discover Devices</button>
连接到我们的蓝牙设备,在距离变化时请求通知,在控制台日志中打印距离。
function discoverDevices() {
console.log("discoverDevices");
var options = {
filters: [{ services: ['3ab10100-f831-4395-b29d-570977d5bf94'] }],
optionalServices: ['0000180a-0000-1000-8000-00805f9b34fb', '0000180f-0000-1000-8000-00805f9b34fb', '3ab10100-f831-4395-b29d-570977d5bf94'],
acceptAllDevices: false
}
const DISTO_DISTANCE = "3ab10101-f831-4395-b29d-570977d5bf94";
const DISTO_DISTANCE_UNIT = "3ab10102-f831-4395-b29d-570977d5bf94";
const DISTO_COMMAND = "3ab10109-f831-4395-b29d-570977d5bf94";
const STATE_RESPONSE = "3ab1010a-f831-4395-b29d-570977d5bf94";
const DS_MODEL_NAME = "3ab1010c-f831-4395-b29d-570977d5bf94";
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('> Name:' + device.name);
console.log('> Id:' + device.id);
console.log(device);
return device.gatt.connect();
})
.then(device => {
device.addEventListener('gattserverdisconnected', onDisconnected);
return device.gatt.connect();
})
.then(server => server.getPrimaryService('3ab10100-f831-4395-b29d-570977d5bf94'))
.then(service => service.getCharacteristic(DISTO_DISTANCE))
.then(characteristic => characteristic.startNotifications())
.then(characteristic => {
characteristic.addEventListener('characteristicvaluechanged',
handleDistanceChanged);
console.log('Notifications have been started.');
})
.catch(error => {
console.log('ERROR: ' + error);
});
function handleDistanceChanged(event) {
const value = event.target.value;
console.log('Got distance: ' + value.getFloat32(0, true));
}
function onDisconnected(event) {
const device = event.target;
console.log(`Device ${device.name} is disconnected.`);
}
}
来源:
【讨论】: