From 23f0a19fb87dc2c3f4d87164ed9eb610051fbcce Mon Sep 17 00:00:00 2001 From: anfe <448468458@qq.com> Date: Mon, 20 May 2024 16:37:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E6=B7=BB=E5=8A=A0=E8=93=9D=E7=89=99=20deb?= =?UTF-8?q?ug=20=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/blue/blue_manage.dart | 160 +++++++++++++++++++------------------- 1 file changed, 82 insertions(+), 78 deletions(-) diff --git a/lib/blue/blue_manage.dart b/lib/blue/blue_manage.dart index 223fe584..73a9bdab 100755 --- a/lib/blue/blue_manage.dart +++ b/lib/blue/blue_manage.dart @@ -1,13 +1,9 @@ import 'dart:async'; import 'dart:io'; -import 'package:app_settings/app_settings.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:get/get.dart'; import 'package:star_lock/app_settings/app_settings.dart'; -import 'package:star_lock/tools/showTipView.dart'; -import 'package:star_lock/widget/permission/permission_dialog.dart'; -import 'package:url_launcher/url_launcher.dart'; import 'io_tool/io_model.dart'; import 'io_tool/io_tool.dart'; @@ -21,19 +17,19 @@ typedef ConnectStateCallBack = Function( typedef ScanDevicesCallBack = Function(List); class BlueManage { - final List scanDevices = []; + final List scanDevices = []; // 用来写入的服务id - final Guid _serviceIdConnect = Guid("fff0"); + final Guid _serviceIdConnect = Guid('fff0'); // 用来写入的服务id final Guid _serviceIdWrite = Guid('0000FFF0-0000-1000-8000-00805F9B34FB'); // 用来订阅的特征id - final Guid _characteristicIdSubscription = Guid("fff1"); + final Guid _characteristicIdSubscription = Guid('fff1'); // 用来写入的特征id - final Guid _characteristicIdWrite = Guid("fff2"); + final Guid _characteristicIdWrite = Guid('fff2'); // 监听发送事件 StreamSubscription? _sendStreamSubscription; @@ -50,10 +46,10 @@ class BlueManage { int? _mtuSize = 20; // 当前连接设备的名字 - String connectDeviceName = ""; + String connectDeviceName = ''; // 当前连接设备的mac地址 - String connectDeviceMacAddress = ""; + String connectDeviceMacAddress = ''; // 当前连接的设备 BluetoothDevice? bluetoothConnectDevice; @@ -93,7 +89,7 @@ class BlueManage { } void _initGetMtuSubscription() { - _mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((value) { + _mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((int value) { _mtuSize = value - 3; AppLog.log('_mtuSizeValue:$value mtuSize:$_mtuSize'); }); @@ -101,7 +97,7 @@ class BlueManage { void _initAdapterStateStateSubscription() { _adapterStateStateSubscription ??= - FlutterBluePlus.adapterState.listen((state) { + FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) { _adapterState = state; }); } @@ -149,8 +145,8 @@ class BlueManage { _connectionStateSubscription?.cancel(); _connectionStateSubscription = null; - _connectionStateSubscription = - bluetoothConnectDevice!.connectionState.listen((state) async { + _connectionStateSubscription = bluetoothConnectDevice!.connectionState + .listen((BluetoothConnectionState state) async { bluetoothConnectionState = state; // AppLog.log("蓝牙连接状态:$state"); }); @@ -162,18 +158,18 @@ class BlueManage { .on() .listen((EventSendModel model) { if (model.sendChannel == DataChannel.ble) { - FlutterBluePlus.isSupported.then((isAvailable) async { + FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { if (_adapterState == BluetoothAdapterState.on) { // 蓝牙已开启,可以进行蓝牙操作 writeCharacteristicWithResponse(model.data); } else { try {} catch (e) { - AppLog.log("蓝牙打开失败"); + AppLog.log('蓝牙打开失败'); } } } else { - AppLog.log("写入数据 蓝牙不可用,不能进行蓝牙操作"); + AppLog.log('写入数据 蓝牙不可用,不能进行蓝牙操作'); } }); } @@ -183,31 +179,33 @@ class BlueManage { /// 开始指定设备名称的扫描蓝牙设备 Future startScanSingle(String deviceName, int timeout, ScanDevicesCallBack scanDevicesCallBack) async { - FlutterBluePlus.isSupported.then((isAvailable) async { + FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { if (_adapterState == BluetoothAdapterState.on) { try { FlutterBluePlus.startScan(timeout: Duration(seconds: timeout)); - Completer completer = Completer(); - var subscription = FlutterBluePlus.scanResults.listen((results) { - // AppLog.log("startScanSingle扫描到的设备:$results"); - bool isExit = results.any((element) => + final Completer completer = Completer(); + final StreamSubscription> subscription = + FlutterBluePlus.scanResults.listen((List results) { + final bool isExit = results.any((ScanResult element) => (element.device.platformName == deviceName) || (element.advertisementData.advName == deviceName)); + AppLog.log('扫描到的设备数:${results.length} 是否查找到 $isExit'); if (isExit) { - for (var scanResult in results) { + for (final ScanResult scanResult in results) { if (((scanResult.advertisementData.serviceUuids.isNotEmpty ? scanResult.advertisementData.serviceUuids[0] - : "") + : '') .toString() - .contains("758824")) && + .contains('758824')) && (scanResult.rssi >= -100)) { // 查询id相同的元素 - final knownDeviceIndex = scanDevices.indexWhere((d) => - (d.device.platformName == - scanResult.device.platformName) || - (d.advertisementData.advName == - scanResult.advertisementData.advName)); + final int knownDeviceIndex = scanDevices.indexWhere( + (ScanResult d) => + (d.device.platformName == + scanResult.device.platformName) || + (d.advertisementData.advName == + scanResult.advertisementData.advName)); // 不存在的时候返回-1 if (knownDeviceIndex >= 0) { scanDevices[knownDeviceIndex] = scanResult; @@ -220,7 +218,7 @@ class BlueManage { } }, onError: (e) { AppLog.log( - "扫描失败:$e", + '扫描失败:$e', ); }); FlutterBluePlus.cancelWhenScanComplete(subscription); @@ -228,7 +226,7 @@ class BlueManage { scanDevicesCallBack(scanDevices); subscription.cancel(); } catch (e) { - AppLog.log("扫描失败"); + AppLog.log('扫描失败'); } } else { try { @@ -236,11 +234,11 @@ class BlueManage { await FlutterBluePlus.turnOn(); } } catch (e) { - AppLog.log("蓝牙打开失败"); + AppLog.log('蓝牙打开失败'); } } } else { - AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作"); + AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作'); } }); } @@ -248,15 +246,16 @@ class BlueManage { /// 开始扫描蓝牙设备 Future startScan(int timeout, ScanDevicesCallBack scanDevicesCallBack, {List? idList}) async { - FlutterBluePlus.isSupported.then((isAvailable) async { + FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { if (_adapterState == BluetoothAdapterState.on) { try { FlutterBluePlus.startScan(timeout: Duration(seconds: timeout)); - var subscription = FlutterBluePlus.scanResults.listen((results) { + final StreamSubscription> subscription = + FlutterBluePlus.scanResults.listen((List results) { scanDevices.clear(); - for (var scanResult in results) { + for (final ScanResult scanResult in results) { // 判断名字为空的直接剔除 // if (scanResult.device.advName.isEmpty) { // return; @@ -266,16 +265,17 @@ class BlueManage { // " rssi:${scanResult.rssi}"); if (((scanResult.advertisementData.serviceUuids.isNotEmpty ? scanResult.advertisementData.serviceUuids[0] - : "") + : '') .toString() - .contains("758824")) && + .contains('758824')) && (scanResult.rssi >= -100)) { // 查询id相同的元素 - final knownDeviceIndex = scanDevices.indexWhere((d) => - (d.device.platformName == - scanResult.device.platformName) || - (d.advertisementData.advName == - scanResult.advertisementData.advName)); + final int knownDeviceIndex = scanDevices.indexWhere( + (ScanResult d) => + (d.device.platformName == + scanResult.device.platformName) || + (d.advertisementData.advName == + scanResult.advertisementData.advName)); // 不存在的时候返回-1 if (knownDeviceIndex >= 0) { scanDevices[knownDeviceIndex] = scanResult; @@ -303,13 +303,13 @@ class BlueManage { // FlutterBluePlus.stopScan(); }, onError: (e) { AppLog.log( - "扫描失败:$e", + '扫描失败:$e', ); }); FlutterBluePlus.cancelWhenScanComplete(subscription); } catch (e) { - AppLog.log("扫描失败"); + AppLog.log('扫描失败'); } } else { try { @@ -317,11 +317,11 @@ class BlueManage { await FlutterBluePlus.turnOn(); } } catch (e) { - AppLog.log("蓝牙打开失败"); + AppLog.log('蓝牙打开失败'); } } } else { - AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作"); + AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作'); } }); } @@ -330,12 +330,13 @@ class BlueManage { Future bludSendData( String deviceName, ConnectStateCallBack stateCallBack, {bool isAddEquipment = false}) async { - FlutterBluePlus.isSupported.then((isAvailable) async { + FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { + AppLog.log('蓝牙状态 系统蓝牙状态:$_adapterState 蓝牙连接状态:$bluetoothConnectionState'); if (_adapterState == BluetoothAdapterState.on) { // 蓝牙已开启,可以进行蓝牙操作 if (bluetoothConnectionState != BluetoothConnectionState.connected) { - _connect(deviceName, (state) { + _connect(deviceName, (BluetoothConnectionState state) { stateCallBack(bluetoothConnectionState!); }, isAddEquipment: isAddEquipment); } else { @@ -346,11 +347,11 @@ class BlueManage { stateCallBack(BluetoothConnectionState.disconnected); openBlue(); } catch (e) { - AppLog.log("蓝牙打开失败"); + AppLog.log('蓝牙打开失败'); } } } else { - AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作"); + AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作'); } }); } @@ -360,9 +361,9 @@ class BlueManage { String deviceName, ConnectStateCallBack connectStateCallBack, {bool isAddEquipment = false}) async { connectDeviceName = deviceName; - List devicesList = scanDevices; + final List devicesList = scanDevices; - bool isExistDevice = scanDevices.any((element) => + final bool isExistDevice = scanDevices.any((ScanResult element) => element.device.platformName == connectDeviceName || element.advertisementData.advName == connectDeviceName); @@ -383,7 +384,7 @@ class BlueManage { {bool isAddEquipment = false}) async { // 判断数组列表里面是否有这个设备 // AppLog.log("devicesList:$devicesList"); - final knownDeviceIndex = devicesList.indexWhere((d) => + final int knownDeviceIndex = devicesList.indexWhere((ScanResult d) => (d.device.platformName == deviceName) || (d.advertisementData.advName == deviceName)); @@ -412,15 +413,15 @@ class BlueManage { // AppLog.log("调用了停止扫描的方法"); await stopScan(); - if ((scanResult.advertisementData.serviceUuids[0].toString()[31] == "0") && + if ((scanResult.advertisementData.serviceUuids[0].toString()[31] == '0') && isAddEquipment == false) { connectStateCallBack(BluetoothConnectionState.disconnected); - EasyLoading.showToast("该锁已被重置".tr, duration: 2000.milliseconds); + EasyLoading.showToast('该锁已被重置'.tr, duration: 2000.milliseconds); return; } // 重连三次 - int maxAttempts = 3; + final int maxAttempts = 3; int attempt = 0; while (attempt < maxAttempts) { try { @@ -443,14 +444,16 @@ class BlueManage { // await bluetoothConnectDevice!.connect(); if (bluetoothConnectionState == BluetoothConnectionState.connected) { try { - bluetoothConnectDevice!.discoverServices().then((services) { - for (BluetoothService service in services) { + bluetoothConnectDevice! + .discoverServices() + .then((List services) { + for (final BluetoothService service in services) { // AppLog.log("11111service.remoteId:${service.remoteId}" // " service.uuid:${service.uuid}" // " service.characteristics:${service.characteristics}" // " service.includedServices:${service.includedServices}"); if (service.uuid == _serviceIdConnect) { - for (BluetoothCharacteristic characteristic + for (final BluetoothCharacteristic characteristic in service.characteristics) { // Get.log("22222characteristic.remoteId:${characteristic.remoteId}" // " characteristic.uuid:${characteristic.uuid}" @@ -478,14 +481,15 @@ class BlueManage { } // 听上报来的数据,参数来自前面扫描到的结果 - var allData = []; + List allData = []; // 保存上一次的数据,用来判断是否收到重复的数据 - var lastTimeData = []; + List lastTimeData = []; int? dataLen; _subScribeToCharacteristic(BluetoothCharacteristic characteristic) async { - final subscription = characteristic.onValueReceived.listen((data) { + final StreamSubscription> subscription = + characteristic.onValueReceived.listen((List data) { // AppLog.log("订阅获取的数据:$data"); if (data == lastTimeData || data.isEmpty) { return; @@ -580,15 +584,15 @@ class BlueManage { // 写入 Future writeCharacteristicWithResponse(List value) async { - List services = + final List services = await bluetoothConnectDevice!.discoverServices(); - for (BluetoothService service in services) { + for (final BluetoothService service in services) { // AppLog.log("33333 service.remoteId:${service.remoteId}" // " service.uuid:${service.uuid}\n\n" // " service.characteristics:${service.characteristics}\n\n" // " service.includedServices:${service.includedServices}"); if (service.uuid == _serviceIdConnect) { - for (BluetoothCharacteristic characteristic + for (final BluetoothCharacteristic characteristic in service.characteristics) { // AppLog.log("44444 characteristic.remoteId:${characteristic.remoteId}" // " characteristic.uuid:${characteristic.uuid}\n\n" @@ -598,8 +602,8 @@ class BlueManage { // .characteristicUuid}"); if (characteristic.characteristicUuid == _characteristicIdWrite) { try { - List valueList = value; - List subData = splitList(valueList, _mtuSize!); + final List valueList = value; + final List subData = splitList(valueList, _mtuSize!); // AppLog.log('writeCharacteristicWithResponse _mtuSize:$_mtuSize 得到的分割数据:$subData'); for (int i = 0; i < subData.length; i++) { if (characteristic.properties.writeWithoutResponse) { @@ -660,15 +664,15 @@ class BlueManage { // 写入 Future writeNull() async { - List services = + final List services = await bluetoothConnectDevice!.discoverServices(); - for (BluetoothService service in services) { + for (final BluetoothService service in services) { if (service.uuid == _serviceIdConnect) { - for (BluetoothCharacteristic characteristic + for (final BluetoothCharacteristic characteristic in service.characteristics) { if (characteristic.characteristicUuid == _characteristicIdWrite) { try { - List valueList = [1]; + final List valueList = [1]; AppLog.log('APP写入 writeNull '); await characteristic.write(valueList); } on Exception catch (e, s) { @@ -713,7 +717,7 @@ class BlueManage { try { await FlutterBluePlus.stopScan(); } catch (e) { - AppLog.log("停止扫描失败"); + AppLog.log('停止扫描失败'); } } @@ -721,17 +725,17 @@ class BlueManage { Future disconnect() async { try { // if(bluetoothConnectDevice != null && bluetoothConnectDevice!.connectionState == BluetoothConnectionState.connected){ - connectDeviceMacAddress = ""; + connectDeviceMacAddress = ''; if (bluetoothConnectionState == BluetoothConnectionState.connected) { // await writeNull(); // await Future.delayed(const Duration(milliseconds: 1000)); //加快蓝牙断连 await bluetoothConnectDevice!.disconnect(timeout: 2); - AppLog.log("断开连接成功"); + AppLog.log('断开连接成功'); } // } } on Exception catch (e, _) { - AppLog.log("断开连接失败: $e"); + AppLog.log('断开连接失败: $e'); } finally { bluetoothConnectionState = BluetoothConnectionState.disconnected; } @@ -742,7 +746,7 @@ class BlueManage { await FlutterBluePlus.turnOn(); } if (Platform.isIOS) { - EasyLoading.showToast("请开启蓝牙".tr, duration: 2000.milliseconds); + EasyLoading.showToast('请开启蓝牙'.tr, duration: 2000.milliseconds); } }