flutter 设置两个BLE特性的通知值

hkmswyz6  于 2023-02-13  发布在  Flutter
关注(0)|答案(1)|浏览(169)

我似乎无法为同一BLE服务中的多个特征设置通知值。调用第二个通知值时,应用程序总是崩溃。
如果我注解掉setNotifyValue中的任何一个特征并重新编译,应用程序将运行良好,并提供传入数据的实时流。

class DeviceScreen extends StatelessWidget {
  const DeviceScreen({Key key, this.device}) : super(key: key);
  final BluetoothDevice device;
  static String CHARACTERISTIC_UUID_BTN =
      "0000ab0a-1212-efde-1523-785fef13d123";
  static String CHARACTERISTIC_UUID_TEMP =
      "0000beef-1212-efde-1523-785fef13d123";

  Widget _myService(List<BluetoothService> services) {
    Stream<List<int>> btn_stream;
    Stream<List<int>> temp_stream;
    services.forEach((service) {
      service.characteristics.forEach((character) {
        if (character.uuid.toString() == CHARACTERISTIC_UUID_BTN) {
          character.setNotifyValue(true);
          btn_stream = character.value;
        }
        if (character.uuid.toString() == CHARACTERISTIC_UUID_TEMP) {
          character.setNotifyValue(true);
          temp_stream = character.value;
        }
      });
    });
    return Container(
        //eric code
        child: StreamBuilder<List<int>>(
      stream: btn_stream,
      builder: (BuildContext context, AsyncSnapshot<List<int>> btn_snapshot) {
        return StreamBuilder(
          stream: temp_stream,
          builder:
              (BuildContext context, AsyncSnapshot<List<int>> temp_snapshot) {
            if (btn_snapshot.hasError)
              return Text('Error : ${btn_snapshot.error}');
            if (temp_snapshot.hasError)
              return Text('Error : ${temp_snapshot.error}');

            if ((btn_snapshot.data != null) && (temp_snapshot.data != null)) {
              if ((btn_snapshot.data.length != 0) &&
                  (temp_snapshot.data.length != 0)) {
                int incoming_counts = btn_snapshot.data[0];
                int incoming_temp = temp_snapshot.data[0];
                return Text(incoming_counts.toString() +
                    " " +
                    incoming_temp.toString());
              } else {
                return Text("Synced! Waiting for input");
                //return Text(btn_snapshot.data.toString() +
                //  " " +
                //  temp_snapshot.data.toString());
              }
            } else {
              return Text("Waiting to sync...");
              //return Text(btn_snapshot.data.toString() +
              //    " " +
              //    temp_snapshot.data.toString());
            }
          },
        );
      },
    ));
  }

我希望"incoming_counts"和"incoming_temp"都能在蓝牙外设有新数据可用时实时更新。然而,当分配流时,第二次调用character. setNotifyValue(true);抛出一个错误:
发生异常,平台异常(平台异常(set_notification_error,写描述符出错,null))

5sxhfpxr

5sxhfpxr1#

运行多个setNotifyValue()的一个变通方法是与await异步运行,如本文issue thread中所述。

await character.setNotifyValue(true);

相关问题