如何通过网络蓝牙读取激光距离测量值

Mar*_*son 2 android google-chrome bluetooth web-bluetooth

我需要使用 Web 蓝牙 API 在 Web 应用程序中读取 Leica Disto D2 的距离测量值。我的目标是最新的 Android 设备,因此 Chrome/Samsung 浏览器应该支持它

Mar*_*son 5

除非使用本地主机进行测试,否则通过 HTTPS 提供 HTML。必须从用户手势开始:

<button onclick="discoverDevices()">Discover Devices</button>
Run Code Online (Sandbox Code Playgroud)

连接到我们的蓝牙设备,在距离变化时请求通知,在控制台日志中打印距离。

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.`);
  }
}
Run Code Online (Sandbox Code Playgroud)

资料来源: