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

如何使用 Flutter 和 flutter_blue 在 MI Band 4 中读取步数?

如何解决如何使用 Flutter 和 flutter_blue 在 MI Band 4 中读取步数?

我正在 Flutter 中开发一个应用程序,它可以从 MI 4 Band 读取数据(特别是步数)并将其传递给我的 Flutter 应用程序。到目前为止,我能够连接设备并显示服务列表。但是,我无法找到步数数据。我该怎么做?

我正在使用的完整代码......

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:Flutter/material.dart';
import 'package:Flutter/services.dart';
import 'package:Flutter_bluetooth_serial/Flutter_bluetooth_serial.dart' as flbs;
import 'package:Flutter_blue/Flutter_blue.dart';
import 'package:toast/toast.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter  BLE Demo',theme: ThemeData(
        primarySwatch: Colors.blue,),home: MyHomePage(title: 'Flutter BLE Home Page'),);
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key,this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FlutterBlue FlutterBlue = FlutterBlue.instance;
  flbs.FlutterBluetoothSerial bluetooth = flbs.FlutterBluetoothSerial.instance;
  flbs.BluetoothConnection bleConn;
  List<BluetoothDevice> devices = [];

  List<BluetoothService> services = [];
  BluetoothService myImportantService;
  List<BluetoothCharacteristic> characteristics = [];
  BluetoothCharacteristic myImportantCharacteristic;

  int counter = 10;

  @override
  void initState() {
    super.initState();
    bluetooth.requestEnable();
    discover();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void discover() async {
    List<ScanResult> res = await FlutterBlue.startScan(
      timeout: Duration(seconds: 2),allowDuplicates: false,scanMode: ScanMode.balanced,);
    if ((await FlutterBlue.connectedDevices).isNotEmpty) {
      await FlutterBlue.connectedDevices.then(
        (value) => value.first.disconnect().then(
              (value) => Toast.show("BLE disconnected",context),);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
            OutlinedButton(
              onpressed: () async {
                devices.clear();
                Timer.periodic(Duration(seconds: 1),(t) {
                  setState(() {
                    if (counter > 0) {
                      counter--;
                    } else {
                      counter = 10;
                      t.cancel();
                    }
                  });
                });

                List<ScanResult> res = await FlutterBlue.startScan(
                  timeout: Duration(seconds: 10),);

                print(await FlutterBlue.connectedDevices);

                res.forEach((element) {
                  print(element.device);
                  devices.add(element.device);
                });

                // try {
                //   await bluetooth.getBondedDevices().then((value) {
                //     setState(() {
                //       devices = value;
                //     });
                //   });
                // } on PlatformException {
                //   print("Can't connect");
                // }
              },child: Text(
                'Start Scannig Devices',Text(
              "$counter",Text(
              'Available Devices:',Expanded(
              child: ListView.builder(
                shrinkWrap: true,itemCount: devices.length,itemBuilder: (context,index) => InkWell(
                  onTap: () async {
                    // try {
                    //   if (bleConn == null) {
                    //     bleConn = await BluetoothConnection.toAddress(
                    //         devices[index].address);
                    //     setState(() {});

                    //     if (bleConn.isConnected) {
                    //       var data = await bleConn.output.allSent;
                    //       // bleConn.input.forEach((element) {
                    //       //   print(element.first.toString());
                    //       // });
                    //       Toast.show(
                    //         'BLE Connected. \nData incoming: ${data.toString()}',//         context,//         duration: 10,//       );
                    //       // Toast.show("BLE Connected",context);
                    //     }
                    //   } else {
                    //     bleConn.finish();
                    //     bleConn = null;
                    //     setState(() {});
                    //     Toast.show("BLE disconnected",context,duration: 4);
                    //   }
                    // } on PlatformException {
                    //   Toast.show(
                    //       "Cannot connect due to: Platform Exception",//       duration: 4);
                    // }
                    await devices[index].connect(autoConnect: false).then(
                          (value) => Toast.show("BLE Connected",);

                    services = await devices[index].discoverServices();
                    for (BluetoothService s in services) {
                      //Would recommend to convert all to lowercase if comparing.
                      print(s.uuid);
                    }
                    print(await services[2].characteristics[0].read());
                    print(String.fromCharCodes(
                        await services[2].characteristics[0].read()));
                    // for (BluetoothService s in services) {
                    //   //Would recommend to convert all to lowercase if comparing.
                    //   print(s.uuid);
                    //   if (s.uuid.toString().toLowerCase() ==
                    //       "00002a53-0000-1000-8000-00805f9b34fb") {
                    //     myImportantService = s;
                    //     print(myImportantService.uuid);
                    //     characteristics = myImportantService.characteristics;
                    //     for (BluetoothCharacteristic c in characteristics) {
                    //       //Would recommend to convert all to lowercase if comparing.
                    //       // if(c.uuid.toString().toLowerCase() == CHaraCTERISTIC_UUID)
                    //       //   myImportantCharacteristic = c;
                    //       print(c);
                    //     }
                    //   }
                    // }
                  },onLongPress: () async {
                    // try {

                    // } catch (e) {
                    //   Toast.show(
                    //       "Cannot disconnect due to: ${e.toString()}",context);
                    // }
                    await devices[index].disconnect().then(
                          (value) => Toast.show("BLE disconnected",);
                  },child: Text(
                    "${devices[index].name}",style: Theme.of(context).textTheme.headline4,],);
  }
}

Flutter 中使用的依赖项

dependencies:
  Flutter:
    sdk: Flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  Flutter_blue: ^0.8.0
  Flutter_bluetooth_serial: ^0.2.2
  Flutter_reactive_ble: ^3.1.0
  toast: ^0.1.5

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