fix:优化开锁逻辑,减少搜索设备,减少循环发送请求,注释无用log

This commit is contained in:
anfe 2024-04-09 15:49:58 +08:00
parent a1a0ce76dc
commit 09ba3d51af

View File

@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:io';
import 'package:flutter_easyloading/flutter_easyloading.dart';
// import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
@ -20,15 +21,19 @@ class BlueManage {
// id
final Guid _serviceIdConnect = Guid("fff0");
// id
final Guid _serviceIdWrite = Guid('0000FFF0-0000-1000-8000-00805F9B34FB');
// id
final Guid _characteristicIdSubscription = Guid("fff1");
// id
final Guid _characteristicIdWrite = Guid("fff2");
//
StreamSubscription<EventSendModel>? _sendStreamSubscription;
//
// StreamSubscription? _scanSubscription;
//
@ -42,12 +47,16 @@ class BlueManage {
//
String connectDeviceName = "";
// mac地址
String connectDeviceMacAddress = "";
//
BluetoothDevice? bluetoothConnectDevice;
//
ScanResult? scanResult;
//
BluetoothConnectionState? bluetoothConnectionState = BluetoothConnectionState.disconnected;
@ -55,6 +64,7 @@ class BlueManage {
StreamSubscription<BluetoothAdapterState>? _adapterStateStateSubscription;
static BlueManage? _manager;
BlueManage._init() {
_initBlue();
}
@ -66,6 +76,7 @@ class BlueManage {
}
factory BlueManage() => shareManager()!;
BlueManage? get manager => shareManager();
void _initBlue() {
@ -163,6 +174,64 @@ class BlueManage {
});
}
///
Future<void> startScanSingle(String deviceName, int timeout, ScanDevicesCallBack scanDevicesCallBack) async {
FlutterBluePlus.isSupported.then((isAvailable) async {
if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) {
try {
FlutterBluePlus.startScan(timeout: Duration(seconds: timeout));
Completer<dynamic> completer = Completer<dynamic>();
var subscription = FlutterBluePlus.scanResults.listen((results) {
bool isExit = results.any((element) => element.device.platformName == deviceName);
if (isExit) {
for (var scanResult in results) {
if (((scanResult.advertisementData.serviceUuids.isNotEmpty
? scanResult.advertisementData.serviceUuids[0]
: "")
.toString()
.contains("758824")) &&
(scanResult.rssi >= -100)) {
// id相同的元素
final knownDeviceIndex = scanDevices
.indexWhere((d) => d.advertisementData.advName == scanResult.advertisementData.advName);
// -1
if (knownDeviceIndex >= 0) {
scanDevices[knownDeviceIndex] = scanResult;
} else {
scanDevices.add(scanResult);
}
}
}
completer.complete();
}
}, onError: (e) {
Get.log(
"Scan Error:$e",
);
});
FlutterBluePlus.cancelWhenScanComplete(subscription);
await completer.future;
scanDevicesCallBack(scanDevices);
subscription.cancel();
} catch (e) {
Get.log("扫描失败");
}
} else {
try {
if (Platform.isAndroid) {
await FlutterBluePlus.turnOn();
}
} catch (e) {
Get.log("Error Turning On:");
}
}
} else {
Get.log("开始扫描 蓝牙不可用,不能进行蓝牙操作");
}
});
}
///
Future<void> startScan(int timeout, ScanDevicesCallBack scanDevicesCallBack, {List<Guid>? idList}) async {
FlutterBluePlus.isSupported.then((isAvailable) async {
@ -181,9 +250,15 @@ class BlueManage {
// Get.log("scanResult.device.advName:${scanResult.device.advName}"
// " scanResult.advertisementData.serviceUuids:${scanResult.advertisementData.serviceUuids}"
// " rssi:${scanResult.rssi}");
if (((scanResult.advertisementData.serviceUuids.isNotEmpty ? scanResult.advertisementData.serviceUuids[0] : "").toString().contains("758824")) && (scanResult.rssi >= -100)) {
if (((scanResult.advertisementData.serviceUuids.isNotEmpty
? scanResult.advertisementData.serviceUuids[0]
: "")
.toString()
.contains("758824")) &&
(scanResult.rssi >= -100)) {
// id相同的元素
final knownDeviceIndex = scanDevices.indexWhere((d) => d.advertisementData.advName == scanResult.advertisementData.advName);
final knownDeviceIndex = scanDevices
.indexWhere((d) => d.advertisementData.advName == scanResult.advertisementData.advName);
// -1
if (knownDeviceIndex >= 0) {
scanDevices[knownDeviceIndex] = scanResult;
@ -196,7 +271,9 @@ class BlueManage {
// EventBusManager().eventBusFir(scanDevices);
// FlutterBluePlus.stopScan();
}, onError: (e) {
Get.log("Scan Error:$e", );
Get.log(
"Scan Error:$e",
);
});
FlutterBluePlus.cancelWhenScanComplete(subscription);
@ -211,7 +288,8 @@ class BlueManage {
} catch (e) {
Get.log("Error Turning On:");
}
};
}
;
} else {
Get.log("开始扫描 蓝牙不可用,不能进行蓝牙操作");
}
@ -219,7 +297,8 @@ class BlueManage {
}
///
Future<void> bludSendData(String deviceName, ConnectStateCallBack stateCallBack, {bool isAddEquipment = false}) async {
Future<void> bludSendData(String deviceName, ConnectStateCallBack stateCallBack,
{bool isAddEquipment = false}) async {
FlutterBluePlus.isSupported.then((isAvailable) async {
if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) {
@ -244,7 +323,8 @@ class BlueManage {
} catch (e) {
Get.log("Error Turning On:");
}
};
}
;
} else {
Get.log("开始扫描 蓝牙不可用,不能进行蓝牙操作");
}
@ -252,11 +332,14 @@ class BlueManage {
}
///
Future<void> _connect(String deviceName, ConnectStateCallBack connectStateCallBack, {bool isAddEquipment = false}) async {
Future<void> _connect(String deviceName, ConnectStateCallBack connectStateCallBack,
{bool isAddEquipment = false}) async {
connectDeviceName = deviceName;
List<ScanResult> devicesList = scanDevices;
if(isAddEquipment == false){
startScan(10, (List<ScanResult> scanDevices){
//
bool isExistDevice = scanDevices.any((element) => element.device.platformName == connectDeviceName);
if (isAddEquipment == false && isExistDevice == false) {
startScanSingle(deviceName, 10, (List<ScanResult> scanDevices) {
Get.log("扫描到的设备:$scanDevices");
devicesList = scanDevices;
_connectDevice(devicesList, deviceName, connectStateCallBack, isAddEquipment: isAddEquipment);
@ -266,7 +349,9 @@ class BlueManage {
}
}
Future<void> _connectDevice( List<ScanResult> devicesList, String deviceName, ConnectStateCallBack connectStateCallBack, {bool isAddEquipment = false}) async {
Future<void> _connectDevice(
List<ScanResult> devicesList, String deviceName, ConnectStateCallBack connectStateCallBack,
{bool isAddEquipment = false}) async {
//
Get.log("devicesList:$devicesList");
final knownDeviceIndex = devicesList.indexWhere((d) => d.advertisementData.advName == deviceName);
@ -292,7 +377,7 @@ class BlueManage {
await stopScan();
if ((scanResult!.advertisementData.serviceUuids[0].toString()[31] == "0") && isAddEquipment == false) {
connectStateCallBack(BluetoothConnectionState.disconnected!);
connectStateCallBack(BluetoothConnectionState.disconnected);
EasyLoading.showToast("该锁已被重置", duration: 2000.milliseconds);
return;
}
@ -315,7 +400,7 @@ class BlueManage {
if (attempt >= maxAttempts) {
Get.log('Failed to connect after $maxAttempts attempts.');
connectStateCallBack(BluetoothConnectionState.disconnected!);
connectStateCallBack(BluetoothConnectionState.disconnected);
}
// await bluetoothConnectDevice!.connect();
@ -323,7 +408,7 @@ class BlueManage {
if (bluetoothConnectionState == BluetoothConnectionState.connected) {
try {
bluetoothConnectDevice!.discoverServices().then((services) {
Get.log("333333333");
// Get.log("333333333");
for (BluetoothService service in services) {
// Get.log("11111service.remoteId:${service.remoteId}"
// " service.uuid:${service.uuid}"
@ -336,7 +421,7 @@ class BlueManage {
// " characteristic.secondaryServiceUuid:${characteristic.secondaryServiceUuid}"
// " characteristic.characteristicUuid:${characteristic.characteristicUuid}");
if (characteristic.characteristicUuid == _characteristicIdSubscription) {
Get.log("44444444");
// Get.log("44444444");
_subScribeToCharacteristic(characteristic);
Get.log('Discovering services finished');
bluetoothConnectionState = BluetoothConnectionState.connected;
@ -358,9 +443,11 @@ class BlueManage {
// ,
var allData = <int>[];
//
var lastTimeData = <int>[];
int? dataLen;
_subScribeToCharacteristic(BluetoothCharacteristic characteristic) async {
final subscription = characteristic.onValueReceived.listen((data) {
Get.log("启动对特性的通知。当特性的值发生变化时,设备会发送一个通知");
@ -463,8 +550,7 @@ class BlueManage {
// " service.characteristics:${service.characteristics}\n\n"
// " service.includedServices:${service.includedServices}");
if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic in service
.characteristics) {
for (BluetoothCharacteristic characteristic in service.characteristics) {
// print("44444 characteristic.remoteId:${characteristic.remoteId}"
// " characteristic.uuid:${characteristic.uuid}\n\n"
// " characteristic.secondaryServiceUuid:${characteristic
@ -475,13 +561,11 @@ class BlueManage {
try {
List<int> valueList = value;
List subData = splitList(valueList, _mtuSize!);
Get.log(
'writeCharacteristicWithResponse 得到的分割数据:$subData');
Get.log('writeCharacteristicWithResponse 得到的分割数据:$subData');
for (int i = 0; i < subData.length; i++) {
await characteristic.write(subData[i]).then((value) async {
await Future.delayed(const Duration(milliseconds: 1)).then((
value) async {
await Future.delayed(const Duration(milliseconds: 1)).then((value) async {
Get.log('分包发送成功了');
});
});