如何连接到iOS设备使用FlutterReactBLE

hm2xizp9  于 2023-06-30  发布在  Flutter
关注(0)|答案(1)|浏览(157)

这是几天我一直在努力建立与iOS设备的BLE连接.一旦扫描成功找到我要查找的设备,就会调用以下代码,并且在android设备上运行良好。

void connect(Bike bike, BuildContext context) {
    String connectionId = ""; //foundDeviceId
    if (Platform.isIOS) {
      connectionId = bike.uuid; //On iOS the device ID is a UUID
    } else {
      connectionId = bike.mac; //On Android it is a MAC address
    }
    currentConnectionStream = bluetoothProvider.flutterReactiveBle
        .connectToDevice(
      id: connectionId,
      connectionTimeout: const Duration(seconds: 15),
    )
        .listen(
      (connectionState) {
        switch (connectionState.connectionState) {
          ...
        }
      },
      onError: (error) {
        cancelConnectionStream();
        log("ble_service error: " + (error as PlatformException).message!);
      },
    );
  }

当尝试连接到iOS设备时,我会收到以下错误日志提示,迫使.listen()函数立即跳转到OnError

Unhandled Exception: PlatformException(invalidMethodCall(method: "disconnectFromDevice", details: Optional("\"deviceID\" is invalid")), invalid "disconnectFromDevice" method call ("deviceID" is invalid), null, null)

我已经尝试设置String connectionId与我的设备UUID的硬编码值,大写和小写,用破折号格式化...但仍然被错误消息卡住。
有人犯过这个错误吗?

slwdgvem

slwdgvem1#

经过几次尝试和错误,我发现为了让connectToDevice()正常工作,您需要从扫描设备时创建的DiscoveredDevice中给予device.id字段。

flutterReactiveBle.scanForDevices().listen((device) {
  ...
  [once device is found, cancel scan stream]
}

flutterReactiveBle.connectToDevice(id: device.id).listen() {
  ...
}

相关问题