【问题标题】:Flutter connecting to multiple BLE devices SynchronouslyFlutter 同步连接多个 BLE 设备
【发布时间】:2019-05-09 02:16:04
【问题描述】:

我正在通过 flutterBlue 库使用 Flutter 开发蓝牙低功耗应用程序,我们可能会在其中同时连接到多个外围设备。 如果我单独连接到多个外围设备并同时向所有外围设备发送命令,我就能够连接到它们。 对于状态管理,我的 BluetoothHelper 是我的 ScopedModel 的模型。

class BluetoothHelper extends Model {

  bool isProcessing = false; 
  int val = 0;

  FlutterBlue flutterBlue = FlutterBlue.instance; //bluetooth library instance

  StreamSubscription scanSubscription;
  Map<DeviceIdentifier, ScanResult> scanResults = new Map();

  /// State
  StreamSubscription stateSubscription;
  BluetoothState state = BluetoothState.unknown;

  /// Device
  List<BluetoothDevice> devicesList = new List(); //todo

  bool get isConnected => (deviceList.size != 0);
  StreamSubscription deviceConnection;
  StreamSubscription deviceStateSubscription;
  List<BluetoothService> services = new List();
  Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
  BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;

  Future startScan(String uuid) async {
    isProcessing = true;
    if (val == 0) {
      Future.delayed(Duration(milliseconds: 25), () => scanAndConnect(uuid));
      val++;
    } else {
      Future.delayed(Duration(seconds: 4), () => scanAndConnect(uuid));
    }
  }

  scanAndConnect(String uuid){
    scanSubscription =
        flutterBlue.scan(timeout: const Duration(seconds: 120), withServices: [
          //new Guid('FB755D40-8DE5-481E-A369-21C0B3F39664')]
        ]).listen((scanResult) {
          if (scanResult.device.id.toString() == uuid) {
            scanResults[scanResult.device.id] = scanResult;

            print("found! Attempting to connect" + scanResult.device.id.toString());
            device = scanResult.device;

            //connect(device);
            connect(device);
          }
        }, onDone: stopScan);
  }

  Future connect(BluetoothDevice d) {

    deviceConnection = flutterBlue.connect(d).listen(
          null,
        );

    deviceStateSubscription = d.onStateChanged().listen((s) {
      if (s == BluetoothDeviceState.connected) {
        stopScan();
        d.discoverServices().then((s) {
          print("connected to ${device.id.toString()}");
          services = s;
          services.forEach((service) {
            var characteristics = service.characteristics;
            for (BluetoothCharacteristic c in characteristics) {
              if (c.uuid.toString() == '') {//we look for the uuid we want to write to
                String handshakeValue ; //value is initiliazed here in code
                List<int> bytes = utf8.encode(handshakeValue);
                d.writeCharacteristic(c, bytes,
                    type: CharacteristicWriteType.withResponse);
                     devicesList.add(d);
              }
            }
          });
        });
      }
    });

  }
}

我正在尝试循环抛出所有外围唯一标识符 (UID),然后让它们以编程方式一个接一个地连接。

这不是很好。它总是会连接到最后一个外围设备。似乎flutterblue实例一次只能扫描一个uid,如果它收到另一个请求,它会立即丢弃最后一个请求并移动到新的请求。

我将相同的逻辑应用于单个外设逻辑的连接,我会立即点击一个外设和第二个外设,然后它会连接到第二个。 (在连接过程发生时,我目前没有阻止 UI 或任何东西) 我需要等到第一个外围设备连接后才能移动到下一个外围设备。

上面的代码是我获得外围设备的唯一方法,但是这段代码存在很大的问题。它目前只能连接到 2 个设备。它使用延迟而不是回调来实现连接,方法是在移动到第二个外围设备之前为扫描和连接提供足够的时间。

我的第一个直觉是将 startScan 和 connect 方法转换为异步方法,但这并不像我希望的那样工作。

{等待连接(设备); } => 给出“内置标识符“等待”不能用作类型。我可能只是错误地设置了异步。

我环顾四周寻找替代品,发现了 Completers 和 Isolates。我不确定这可能有多相关。

用户界面:

我为封装在作用域模型后代中的按钮的 ontap 设置了以下方法。这将可靠地加载带有一些 uid 的 peripheralUIDs 列表,然后一个接一个地连接到它们。

connectAllPeripherals(BluetoothHelper model, List<String> peripheralUIDs) {
    for(var uuid in peripheralUIDs) { //list of strings containing the uuids for the peripherals I want to connect to
      model.startScan(uuid);
    }
}

【问题讨论】:

    标签: asynchronous dart async-await flutter bluetooth-lowenergy


    【解决方案1】:

    不知道这一点是否仍然是一个问题。

    假设您的问题尚未得到解决。我认为您遇到的问题是尝试在 Flutter 中维护连接(而不是仅仅连接多个设备并让 Flutter_Blue/硬件管理连接)。

    我已经很高兴地将它连接到多个设备;在您设置了维护多个设备属性列表的实例之后。

    即我制作了一个 ble-device 类,其中包含以下各项:

    StreamSubscription deviceConnection;
    StreamSubscription deviceStateSubscription;
    List<BluetoothService> services = new List();
    Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
    BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;
    

    使用从上面的类初始化的新对象为每个连接的设备维护一个 LinkedHashMap 效果很好。

    除此之外——Flutter_Blue 一次只允许 1 个并发请求调用(例如读取特征),但您可以很容易地将它们堆叠起来

     await
    

    通过上述方法,我可以在几毫秒内轮询多个设备。

    不知道这是否有帮助 - 但如果运气好的话,也会遇到我的问题的人会遇到这个问题并节省一些时间。

    【讨论】:

    • 因此保持多个设备连接不是问题。我只保留设备列表并向它们发送命令效果很好!问题是以编程方式一个接一个地连接。为什么这是一个问题,因为我试图等待一个返回未来但未来应该来自流中的方法(关于如何解决这个问题的任何想法,因为这仍然会有所帮助?)但我现在可以连接通过使用队列来连接任意数量的设备,并且效果很好。
    • 我猜你试图连接到相当多的设备? (在保持连接时连接到 6 个左右应该不是问题 - 您应该只需要以编程方式连接/断开非常大的数字)。您能否进一步解释未来的问题 - 它仍然源自您上面提到的“{await connect(device); } =>”问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多