【问题标题】:How to Write Characteristics to Bluetooth Low Energy Device Without Paring Every Time?如何在不每次配对的情况下将特征写入低功耗蓝牙设备?
【发布时间】:2019-06-26 15:33:35
【问题描述】:

我正在使用 site 中的以下代码通过我的 asp.net MVC Web 应用程序的浏览器配对并连接到蓝牙低功耗打印机。

navigator.bluetooth.requestDevice({
  filters: [{ services: [0xffe5] }]
})
  .then(function(device) {
    // Step 2: Connect to it
    return device.gatt.connect();
  })
  .then(function(server) {
    // Step 3: Get the Service
    return server.getPrimaryService(0xffe5);
  })
  .then(function(service) {
    // Step 4: get the Characteristic
    return service.getCharacteristic(0xffe9);
  })
  .then(function(characteristic) {
    // Step 5: Write to the characteristic
    var data = new Uint8Array([0xbb, 0x25, 0x05, 0x44]);
    return characteristic.writeValue(data);
  })
  .catch(function(error) {
     // And of course: error handling!
     console.error('Connection failed!', error);
});

此代码完美运行,但我不明白如何将“配对”、“连接”、“获取服务”和“写入服务”与特性的实际编写解耦。理想情况下,我想配对、连接、获得服务和特性一次。然后不断地写值,这样我就可以打印多个东西,而不必每次都出现配对提示。我见过的每个示例都以 .then 格式而不是独立的格式将它们捆绑在一起。

基本上如何解耦:

navigator.bluetooth.requestDevice({
  filters: [{ services: [0xffe5] }]
})
  .then(function(device) {
    // Step 2: Connect to it
    return device.gatt.connect();
  })
  .then(function(server) {
    // Step 3: Get the Service
    return server.getPrimaryService(0xffe5);
  })
  .then(function(service) {
    // Step 4: get the Characteristic
    return service.getCharacteristic(0xffe9);
  })
});

从这里:

  .then(function(characteristic) {
    // Step 5: Write to the characteristic
    var data = new Uint8Array([0xbb, 0x25, 0x05, 0x44]);
    return characteristic.writeValue(data);
  })
});

谢谢。这是我第一次体验 BTLE,如果这是一个愚蠢的问题,我很抱歉,但我有点挣扎。

【问题讨论】:

    标签: asp.net asp.net-mvc model-view-controller bluetooth bluetooth-lowenergy


    【解决方案1】:

    我在 Angular 应用程序中所做的是使用 async/await 模式并将响应对象分配给一个全局变量,如下所示:

    this.bluetoothDevice = await navigator.bluetooth.requestDevice({acceptAllDevices: true});
    

    然后我使用另一个变量来管理连接:

    this.serverConnected = await this.connect(this.bluetoothDevice.gatt);
    

    最后,我在我的类中的单独方法中使用这些变量来管理断开连接:

    onDisconnectButtonClick() {
        if (!this.bluetoothDevice) {
          return;
        }
        console.log('Disconnecting from Bluetooth Device...');
        if (this.bluetoothDevice.gatt.connected) {
          this.bluetoothDevice.gatt.disconnect();
        } else {
          console.log('> Bluetooth Device is already disconnected');
          this.deviceInfo = 'You have been disconnected.'
        }
      }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2015-06-25
      • 1970-01-01
      • 2013-11-17
      • 2013-12-21
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多