微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Flutter 中将字节列表转换为整数值

如何解决在 Flutter 中将字节列表转换为整数值

我无法从我从 ESP32 即 BLE 设备获得的值中删除括号。我想在心率小部件中显示不带括号的值,但我很难解决这个问题。请帮助我找到它的解决方案。来自设备的数据被转换为字符串格式

BLE 代码

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key key,this.device}) : super(key: key);
  final BluetoothDevice device;
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  // BLE
  final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
  final String CHaraCTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
  bool isReady;
  Stream<List<int>> stream;
  List<int> lastValue;
  List<double> traceDust = List();

  connectToDevice() async {

    // await widget.device.connect();
    print("connected");
    discoverServices();
  }

  discoverServices() async {

    List<BluetoothService> services = await widget.device.discoverServices();
    services.forEach((service) {
      if (service.uuid.toString() == SERVICE_UUID) {
        service.characteristics.forEach((characteristic) {
          if (characteristic.uuid.toString() == CHaraCTERISTIC_UUID) {
            characteristic.setNotifyValue(!characteristic.isnotifying);
            stream = characteristic.value;
            print(stream);
            lastValue = characteristic.lastValue;
            print(lastValue);

            setState(() {
              isReady = true;
            });
          }
        });
      }
    });
  }

心率小部件代码

Container(
                              padding: EdgeInsets.symmetric(vertical: 20),alignment: Alignment.center,//width: double.infinity,child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,children: [
                                  StreamBuilder<List<int>>(
                                    stream: stream,initialData: lastValue,builder: (BuildContext context,AsyncSnapshot<List<int>> snapshot) {
                                      if (snapshot.hasError)
                                        return Text('Error: ${snapshot.error}',style: TextStyle(
                                            fontFamily: 'SF Pro display',fontSize: 19,color: const Color(0xffffffff),fontWeight: FontWeight.w500,height: 1.4736842105263157,),);

                                      if (snapshot.connectionState ==
                                          ConnectionState.active) {
                                        var currentValue = snapshot.data.toString();
                                        //traceDust.add(double.tryParse(currentValue) ?? 0);
                                        return Text('$currentValue',);
                                      } else {
                                        return Text('Check the stream',);
                                      }
                                    },SizedBox(
                                    height: 5,Text(
                                    'Heart Rate',style: TextStyle(
                                      fontFamily: 'SF Pro display',color: Colors.white.withOpacity(0.7),height: 1.2777777777777777,textHeightBehavior: TextHeightBehavior(
                                        applyHeightToFirstAscent: false),textAlign: TextAlign.left,],)

我得到这样的值(如上图所示的心率):

enter image description here

解决方法

如果这确实是您接收的数据格式并且只是想对其进行不同的格式化,请尝试一些字符串操作,例如:

final currentValue = '[33]';
  
print(currentValue.substring(1,currentValue.length-1)); // 33
,

您没有在问题中说明您期望什么价值。我会假设它是 33,尽管对于心率读数来说这似乎很低。

我希望数据是一个字节列表,因此您需要将其转换为整数值。

import 'dart:typed_data';

void main() {
  var value =  Uint8List.fromList([33]);
  print("stream.value: ${value}"); // stream.value: [33]
  var hr = ByteData.sublistView(value,1);
  print("Heart rate: ${hr.getUint8(0)}"); // Heart rate: 33
}

似乎 BLE 设备没有遵循蓝牙标准来发送心率测量值,详情请见以下文档:

  • 心率服务 (HRS)
  • 关贸总协定规范补充 (GSS)

两者都位于:https://www.bluetooth.com/specifications/specs/

如果这样做,那么它可以使用 16-bit UUID Numbers Document 中的 UUID 并使用现有的代码示例,例如 https://webbluetoothcg.github.io/demos/heart-rate-sensor/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。