flutter 蓝牙ble(blue tooth),同时连接多台/多个设备

写这篇文章的初衷

上一篇文章介绍了如何开发一个蓝牙app,(https://www.jianshu.com/p/969871112806),
但局限于只能连接一台蓝牙设备,想同时连接着多台蓝牙设备,就没法实现

于是就有了写作本文的动力,-------->解决同时连接多台蓝牙设备!!!

选择第三方库

flutter_blue 适合于单台的蓝牙设备,使用起来简单
flutter_reactive_ble 适合于单台的蓝牙设备,多台蓝牙设备也可以用
flutter_ble_lib 适合于单台的蓝牙设备,多台蓝牙设备也可以用,可以在模拟器上进行调试蓝牙

感觉后2个第三方库都可以使用,本人先入为主使用了flutter_reactive_ble,所以本文以flutter_reactive_ble为基础进行介绍

先声明4个全局变量,后面会用到

  StreamSubscription? _streamSubscription;
  StreamSubscription? _connectionStreamSubscription;
  final flutterReactiveBle = FlutterReactiveBle();
  List deviceList = [];

开始扫描

 _streamSubscription = flutterReactiveBle.scanForDevices(
        withServices: [Uuid.parse("0000fff0-0000-1000-XXXX-XXXXXXXXXXX")],
        scanMode: ScanMode.lowLatency).listen((device) {
      //code for handling results,返回的是可以扫描到的设备
      deviceList.add(device);
    }, onError: (e) {
      print("onError = $e");
    });

如果扫描过程,不使用过滤条件,withServices这个参数可以给个空数组

 _streamSubscription = flutterReactiveBle.scanForDevices(
        withServices: [],
        scanMode: ScanMode.lowLatency).listen((device) {
      //code for handling results,返回的是可以扫描到的设备
    deviceList.add(device);
    }, onError: (e) {
      print("onError = $e");
    });

停止扫描如下

_streamSubscription?.cancel();

连接设备

    for (int i = 0; i < deviceList.length; i++) {
      DiscoveredDevice device = deviceList[i];
      _connectionStreamSubscription = flutterReactiveBle
          .connectToDevice(
        id: device.id,
        servicesWithCharacteristicsToDiscover: {
          // Uuid.parse("fff0"): [
          //   Uuid.parse("fff1"),
          //   Uuid.parse("fff2"),
          //   Uuid.parse("fff3"),
          //   Uuid.parse("fff4"),
          //   Uuid.parse("fff5")
          // ]
        },
        connectionTimeout: const Duration(seconds: 3),
      )
          .listen((connectionState) {
        if (connectionState.connectionState ==
            DeviceConnectionState.connected) {
          print(" connectionState=${connectionState.deviceId}");

           _discoverServices(deviceId);
        }
        // Handle connection state updates
      }, onError: (Object error) {
        print("error1 =$error");
        // Handle a possible error
      });
    }

断开设备,
每连接成功一个设备后,就会产生一个_connectionStreamSubscription,对应设备的断开,就用对应的StreamSubscription去断开, 可以用一个HashMap,去记录连接成功的设备StreamSubscription的对应关系

_connectionStreamSubscription.cancel();

去扫描服务,并过滤服务,扫描结果服务里面是包含有特征的数组,如: serviceId:[fff0,fff1,fff2,fff3,...]

_discoverServices(String deivceId) {
List serviceList =
          await flutterReactiveBle.discoverServices(deviceId);
      print("services=$serviceList");
      for (int i = 0; i < serviceList.length; i++) {
        DiscoveredService discoveredService = serviceList[i];
        if (discoveredService.serviceId == Uuid.parse("fff0")) {
          if (discoveredService.characteristicIds.length < 4) {
            print("长度不够用");
          }

    }
  }
}

去监听上报来的数据,参数来自前面扫描到的结果serviceId--服务ID, characteristicId--特征ID,deviceId--设备ID

 final characteristic = QualifiedCharacteristic(
        serviceId: serviceId,
        characteristicId: characteristicId,
        deviceId: deviceId);
    print("characteristic = $characteristic");

    flutterReactiveBle.subscribeToCharacteristic(characteristic).listen((data) {
      // code to handle incoming data
      print("deviceId =${discoveredDevice.id}---上报来的数据data = $data");

}, onError: (dynamic error) {
      // code to handle errors
    });

监听这个地方,就知道当前是哪个设备上报的数据!

后面就是各位看官根据自己的需求去做逻辑处理啦。

print("deviceId =${discoveredDevice.id}---上报来的数据data = $data");

对设备设置命令,发送请求(写操作),list为整形数据,要写的数据

// write
        final writeCharacteristic = QualifiedCharacteristic(
            serviceId: discoveredService.serviceId,
            characteristicId: discoveredService.characteristicIds[2],
            deviceId: widget.device.id);
        await flutterReactiveBle
            .writeCharacteristicWithResponse(writeCharacteristic, value: list);

读取设备的信息(读操作)

// read
        final characteristic = QualifiedCharacteristic(
            serviceId: discoveredService.serviceId,
            characteristicId: discoveredService.characteristicIds[1],
            deviceId: widget.device.id);
        final response =
            await flutterReactiveBle.readCharacteristic(characteristic);
        print("response=$response");
最终的成果
22.gif

结尾

flutter 多台蓝牙设备同时连接的分享就到这里喽,小伴们,觉得有点用的话,或者已经看到这里面来的请点个赞吧~~ 后续分享更多有关flutter的文章。如果有疑问的话,请在下方留言~

补充

过一段时间后,我在项目把这个蓝牙库用起来了,基本能满足日常需求.效果如下:

666.gif

你可能感兴趣的:(flutter 蓝牙ble(blue tooth),同时连接多台/多个设备)