簡體   English   中英

顫振同步連接到多個BLE設備

[英]Flutter connecting to multiple BLE devices Synchronously

我正在使用flutter通過flutterBlue庫在藍牙低功耗應用程序上工作,在該庫中,我們可能同時連接到多個外圍設備。 如果我分別連接到多個外圍設備並同時向所有外圍設備發送命令,則可以連接到多個外圍設備。 對於狀態管理,我的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轉換並將連接方法轉換為異步方法,但這並不是我希望的那樣。

{等待連接(設備); } =>給出“不能將內置標識符“ await”用作類型。我可能只是錯誤地設置了異步。

我到處尋找替代品,並且遇到了完成者和孤立者。 我不確定這可能有多重要。

使用者介面:

我為包裝在范圍模型后代中的按鈕的ontap設置了以下方法。 這將可靠地加載一些uid,然后一個接一個地將其連接。

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);
    }
}

不知道這是否仍然是一個問題。

假設您的問題此后沒有得到解決。 我認為您遇到的問題是嘗試維護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

通過以上操作,我可以在幾毫秒內輪詢多個設備。

不知道這是否有幫助-但如果運氣好的話,遇到我的問題的人也可以解決這個問題並節省一些時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM