flutter 蓝牙搜索 读数据 写入数据 02

214 阅读1分钟
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';

class BlueTooth extends StatefulWidget {
  final Map arguments;
   const BlueTooth({Key? key,required this.arguments}) : super(key: key);

  @override
  State<BlueTooth> createState() => _BlueToothState();
}

class _BlueToothState extends State<BlueTooth> {

  //设备对象
  late final BluetoothDevice device;
  //状态
  late String? deviceStat="connecting...";
  //连接状态
  StreamSubscription<BluetoothDeviceState>? _stateSubscription;

  //获取到读写的特征值 对象
  late BluetoothCharacteristic _bluetoothCharacteristic;

  //接收过来的数据对象
 late String? dataString='';

  late Timer time;

  @override
  void initState() {
    // TODO: implement initState
    this.device=widget.arguments['device'];
    //连接蓝牙
    this.device.connect();
    //监听蓝牙连接状态
    _stateSubscription= device.state.listen((state){
      if(BluetoothDeviceState.connected==state){
         setState(() {
           deviceStat="蓝颜连接成功";
         });
         this.discoverServices();
      }else if(BluetoothDeviceState.connecting==state){
        setState(() {
          deviceStat="connecting...";
        });
      }else if(BluetoothDeviceState.disconnected==state){
        setState(() {
          deviceStat="disconnected";
        });
      }

    });
    super.initState();
  }

  //获取蓝牙的服务
  discoverServices() async{
    List<BluetoothService> services = await this.device.discoverServices();
    services.forEach((service) {
          print('----------------');
          print('----------------${service}');
      // print(service);
      // do something with service
    });
    /**
     *
     * 可以读的 sercice  id
     * **/
    BluetoothService  uuidService=services.firstWhere((device)=>device.uuid==Guid('0000ffe0-0000-1000-8000-00805f9b34fb'));
    //拿到特征值
     List characteristics=  uuidService.characteristics;
     for(BluetoothCharacteristic c in characteristics) {
       //特征值里面的 serviceUuid== 获取能写入的uuid uuidService
      if(c.serviceUuid.toString()==uuidService.uuid.toString()){
      //  setState(() {
          _bluetoothCharacteristic=c;
      //  });

          // 两种 读的方式 通知的   uuid
            getCallback(); //一种
          //每隔5秒拿一次数据
          //  读的uuid
          // time=  Timer.periodic(const Duration(seconds: 2), (t) async{ //二种
          //   try {
          //     List<int> value = await c.read();
          //     print("》》》》》》描述符值: $value");
          //   } catch (e) {
          //     print("读取描述符失败: $e");
          //   }
          // });



      }


      //每隔5秒拿一次数据 两种 读的方式

      // List<int> value = await c.read();
      // print(value);
    }

  }

  //读取蓝牙模块传过来的信息
   getCallback() async{
     await _bluetoothCharacteristic.setNotifyValue(true);
     _bluetoothCharacteristic.value.listen((value) {
       if(value==null){
         print("数据为空---------------");
         return;
       }
       print("读取到的值>${value}");
       parseData(value);
     //  print(String.fromCharCodes(value));
       // do something with new value
     });
   }

  void parseData(List<int> data) {
    // 在这里使用刚才定义的解析逻辑
    try {
      String text = utf8.decode(data);
      setState(() {
        dataString=text;
      });
      print('解析为字符串: $text');
    } catch (e) {
      print('字符串解析失败: $e');
    }
  }




  @override
  void dispose() {
    // TODO: implement dispose
    device.disconnect();
    _stateSubscription?.cancel();
    time.cancel();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
             appBar: AppBar(
                title:Text(""),
             ),
          body:Column(
            children: [
              Text("蓝牙详情==${device.id}"),
              Text("蓝牙连接==$deviceStat"),
              Text("读蓝牙的数据==${dataString}"),
              
              ElevatedButton(onPressed: ()async{
                await _bluetoothCharacteristic.write([49, 50, 51]);
              }, child: Text("发送数据给蓝牙"))
            ],
          ),
    );
  }
}