【问题标题】:flutter_reactive_ble - how to check if device is connected before subscribingflutter_reactive_ble - 如何在订阅前检查设备是否已连接
【发布时间】:2021-07-28 12:18:52
【问题描述】:

我正在使用这个插件来尝试开发一个使用蓝牙模块的应用程序。

GitHub https://github.com/PhilipsHue/flutter_reactive_ble/

我正在尝试修改源代码中包含的示例,以便 设备列表的 onTap 将连接和订阅Characteristic

但是,connectToDevice() 方法似乎被声明为流,

在方法调用之前加上 "await" 并不符合我的标准(在连接的设备上,然后 subscribeToCharacteristic)

我如何做到这一点?

我目前在 device_list.dart 中的内容

(device) => ListTile(
    title: Text(device.name),
    subtitle: Text("${device.id}\nRSSI: ${device.rssi}"),
    leading: const BluetoothIcon(),
    onTap: () async {
        widget.stopScan();
        await widget.deviceConn.connect(device.id);
        //call to subscribeToCharacteristic(characteristic);
    });

【问题讨论】:

标签: flutter dart async-await bluetooth-lowenergy


【解决方案1】:

await 仅在方法返回未来的情况下有效。您应该收听流,当流发出 connected 状态时,您将执行订阅调用。例如:

_ble.connectToDevice(id: deviceId).listen(
      (update) {
        if(update.connectionState == DeviceConnectionState.connected){
       // execute subscribe
        }
      },

【讨论】:

  • 嗨@remonh87,听完后,得到数据如何停止听?但保持连接而不断开连接?
  • 是的,当您停止收听连接流时,设备会断开连接。
  • 我可以使用 subscribeStream?.cancel() 停止收听吗?
  • 我对 subscribe 的使用很困惑,在示例应用程序中,该应用程序仅直接从 connect>subscribe>get response 使用它,但是,如果我想像 connect > subscribe > un 那样使用它怎么办从 1 个应用页面订阅,然后移动到其他页面,重新订阅,同时保持连接?
猜你喜欢
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
相关资源
最近更新 更多