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() {
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}');
});
BluetoothService uuidService=services.firstWhere((device)=>device.uuid==Guid('0000ffe0-0000-1000-8000-00805f9b34fb'));
List characteristics= uuidService.characteristics;
for(BluetoothCharacteristic c in characteristics) {
if(c.serviceUuid.toString()==uuidService.uuid.toString()){
_bluetoothCharacteristic=c;
getCallback();
}
}
}
getCallback() async{
await _bluetoothCharacteristic.setNotifyValue(true);
_bluetoothCharacteristic.value.listen((value) {
if(value==null){
print("数据为空---------------");
return;
}
print("读取到的值>${value}");
parseData(value);
});
}
void parseData(List<int> data) {
try {
String text = utf8.decode(data);
setState(() {
dataString=text;
});
print('解析为字符串: $text');
} catch (e) {
print('字符串解析失败: $e');
}
}
@override
void 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("发送数据给蓝牙"))
],
),
);
}
}