diff --git a/lib/blue/blue_manage.dart b/lib/blue/blue_manage.dart index 398171f6..94fdad02 100755 --- a/lib/blue/blue_manage.dart +++ b/lib/blue/blue_manage.dart @@ -16,8 +16,7 @@ import 'io_type.dart'; import 'reciver_data.dart'; //连接状态回调 -typedef ConnectStateCallBack = Function( - BluetoothConnectionState connectionState); +typedef ConnectStateCallBack = Function(BluetoothConnectionState connectionState); typedef ScanDevicesCallBack = Function(List); class BlueManage { @@ -62,8 +61,7 @@ class BlueManage { ScanResult? scanResult; // 监听蓝牙连接状态 - BluetoothConnectionState? bluetoothConnectionState = - BluetoothConnectionState.disconnected; + BluetoothConnectionState? bluetoothConnectionState = BluetoothConnectionState.disconnected; BluetoothAdapterState? _adapterState = BluetoothAdapterState.on; StreamSubscription? _adapterStateStateSubscription; @@ -103,7 +101,7 @@ class BlueManage { // 先取消之前的订阅,避免重复监听 _mtuSubscription?.cancel(); _mtuSubscription = null; - + _mtuSubscription = bluetoothConnectDevice!.mtu.listen((int value) { _mtuSize = value - 3; AppLog.log('设备MTU变化 - 原始值:$value 计算后MTU:$_mtuSize 设备:${bluetoothConnectDevice?.remoteId.str}'); @@ -111,8 +109,7 @@ class BlueManage { } void _initAdapterStateStateSubscription() { - _adapterStateStateSubscription ??= - FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) { + _adapterStateStateSubscription ??= FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) { AppLog.log('蓝牙状态:$state'); _adapterState = state; }); @@ -122,18 +119,15 @@ class BlueManage { _connectionStateSubscription?.cancel(); _connectionStateSubscription = null; - _connectionStateSubscription = bluetoothConnectDevice!.connectionState - .listen((BluetoothConnectionState state) async { + _connectionStateSubscription = + bluetoothConnectDevice!.connectionState.listen((BluetoothConnectionState state) async { bluetoothConnectionState = state; AppLog.log('蓝牙连接回调状态:$state'); }); } void _initSendStreamSubscription() { - _sendStreamSubscription ??= EventBusManager() - .eventBus! - .on() - .listen((EventSendModel model) { + _sendStreamSubscription ??= EventBusManager().eventBus!.on().listen((EventSendModel model) { AppLog.log('eventBus接收发送数据:${model}'); if (model.sendChannel == DataChannel.ble) { FlutterBluePlus.isSupported.then((bool isAvailable) async { @@ -158,8 +152,7 @@ class BlueManage { } /// 开始指定设备名称的扫描蓝牙设备 - Future startScanSingle(String deviceName, int timeout, - ScanDevicesCallBack scanDevicesCallBack) async { + Future startScanSingle(String deviceName, int timeout, ScanDevicesCallBack scanDevicesCallBack) async { final DateTime start = DateTime.now(); FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { @@ -167,9 +160,7 @@ class BlueManage { if (_adapterState == BluetoothAdapterState.on) { try { BuglyTool.uploadException( - message: '开始指定设备名称的扫描蓝牙设备', - detail: '调用方法是:startScanSingle 指定设备名称是:$deviceName', - upload: false); + message: '开始指定设备名称的扫描蓝牙设备', detail: '调用方法是:startScanSingle 指定设备名称是:$deviceName', upload: false); //android 扫描比较慢,取样只要 3 分之一 final int divisor = Platform.isAndroid ? 3 : 1; FlutterBluePlus.startScan( @@ -181,12 +172,9 @@ class BlueManage { final StreamSubscription> subscription = FlutterBluePlus.scanResults.listen((List results) { final bool isExit = results.any((ScanResult element) => - (element.device.platformName == deviceName) || - (element.advertisementData.advName == deviceName)); - final int milliseconds = DateTime.now().millisecondsSinceEpoch - - start.millisecondsSinceEpoch; - AppLog.log( - '扫描到的设备数:${results.length} 是否查找到 $isExit 以查找$milliseconds毫秒'); + (element.device.platformName == deviceName) || (element.advertisementData.advName == deviceName)); + final int milliseconds = DateTime.now().millisecondsSinceEpoch - start.millisecondsSinceEpoch; + AppLog.log('扫描到的设备数:${results.length} 是否查找到 $isExit 以查找$milliseconds毫秒'); BuglyTool.uploadException( message: '指定设备名称的扫描蓝牙设备 监听扫描结果', detail: @@ -202,20 +190,15 @@ class BlueManage { } final isMatch = _isMatch( - scanResult.advertisementData.serviceUuids - .map((e) => e.uuid) - .toList(), + scanResult.advertisementData.serviceUuids.map((e) => e.uuid).toList(), isSingle: true, ); if (isMatch && (scanResult.rssi >= -100)) { // 查询id相同的元素 - final int knownDeviceIndex = scanDevices.indexWhere( - (ScanResult 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; @@ -224,8 +207,7 @@ class BlueManage { } BuglyTool.uploadException( message: '遍历扫描到的结果跟缓存的结果对比,如果有最新的就更新缓存', - detail: - 'startScanSingle deviceName:$deviceName 查询到的结果scanResult:$scanResult', + detail: 'startScanSingle deviceName:$deviceName 查询到的结果scanResult:$scanResult', upload: false); } } @@ -234,9 +216,7 @@ class BlueManage { } }, onError: (e) { BuglyTool.uploadException( - message: '指定设备名称的扫描蓝牙设备 监听扫描结果失败', - detail: '打印失败问题 e:${e.toString()}', - upload: false); + message: '指定设备名称的扫描蓝牙设备 监听扫描结果失败', detail: '打印失败问题 e:${e.toString()}', upload: false); AppLog.log('扫描失败:$e'); }); FlutterBluePlus.cancelWhenScanComplete(subscription); @@ -245,9 +225,7 @@ class BlueManage { subscription.cancel(); } catch (e) { BuglyTool.uploadException( - message: '指定设备名称的扫描蓝牙设备 内部逻辑整形失败', - detail: 'tartScanSingle内部逻辑整形失败 e:${e.toString()}', - upload: false); + message: '指定设备名称的扫描蓝牙设备 内部逻辑整形失败', detail: 'tartScanSingle内部逻辑整形失败 e:${e.toString()}', upload: false); AppLog.log('扫描失败'); } } else { @@ -264,8 +242,7 @@ class BlueManage { } /// 开始扫描蓝牙设备 - Future startScan(int timeout, DeviceType deviceType, - ScanDevicesCallBack scanDevicesCallBack, + Future startScan(int timeout, DeviceType deviceType, ScanDevicesCallBack scanDevicesCallBack, {List? idList}) async { FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { @@ -285,21 +262,16 @@ class BlueManage { } final isMatch = _isMatch( - scanResult.advertisementData.serviceUuids - .map((e) => e.uuid) - .toList(), + scanResult.advertisementData.serviceUuids.map((e) => e.uuid).toList(), deviceType: deviceType, isSingle: false, ); // 判断名字为空的直接剔除 if (isMatch && (scanResult.rssi >= -100)) { // 查询id相同的元素 - final int knownDeviceIndex = scanDevices.indexWhere( - (ScanResult 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; @@ -333,10 +305,8 @@ class BlueManage { } /// 判断是否包含指定的uuid - bool _isMatch(List serviceUuids, - {DeviceType deviceType = DeviceType.blue, required bool isSingle}) { - final List prefixes = - getDeviceType(deviceType).map((e) => e.toLowerCase()).toList(); + bool _isMatch(List serviceUuids, {DeviceType deviceType = DeviceType.blue, required bool isSingle}) { + final List prefixes = getDeviceType(deviceType).map((e) => e.toLowerCase()).toList(); for (String uuid in serviceUuids) { final String cleanUuid = uuid.toLowerCase(); if (cleanUuid.length == 8) { @@ -367,8 +337,7 @@ class BlueManage { } else { // 判断配对状态(带横杠UUID的第31、32位,从1开始计数) if (cleanUuid.length >= 32) { - String pairStatus = - cleanUuid.substring(30, 32); // 第31、32位(从1开始计数) + String pairStatus = cleanUuid.substring(30, 32); // 第31、32位(从1开始计数) // 00=未配对,01=已配对 if (pairStatus == '00') { return true; // 未配对才返回true @@ -386,12 +355,11 @@ class BlueManage { // 判断是否有新事件 bool hasNewEvent = (byte1 == 1); - // 返回是否未配对(原逻辑) - if (isPaired) { - return true; // 已配对返回false + if (!isPaired) { + return true; // 未配对返回true } else { - return false; // 未配对返回true + return false; // 配对返回false } } // 已配对(01)不返回true,继续判断下一个uuid @@ -408,8 +376,7 @@ class BlueManage { } else { // 判断配对状态(带横杠UUID的第31、32位,从1开始计数) if (cleanUuid.length >= 32) { - String pairStatus = - cleanUuid.substring(30, 32); // 第31、32位(从1开始计数) + String pairStatus = cleanUuid.substring(30, 32); // 第31、32位(从1开始计数) // 00=未配对,01=已配对 if (pairStatus == '00') { return true; // 未配对才返回true @@ -427,8 +394,7 @@ class BlueManage { } /// 调用发送数据 List senderData, - Future blueSendData( - String deviceName, ConnectStateCallBack stateCallBack, + Future blueSendData(String deviceName, ConnectStateCallBack stateCallBack, {bool isAddEquipment = false}) async { FlutterBluePlus.isSupported.then((bool isAvailable) async { if (isAvailable) { @@ -438,8 +404,7 @@ class BlueManage { if (bluetoothConnectionState != BluetoothConnectionState.connected) { BuglyTool.uploadException( message: '点击按钮 蓝牙未连接 下一步扫描连接蓝牙', - detail: - 'blueSendData 蓝牙连接状态 bluetoothConnectionState:$bluetoothConnectionState deviceName:$deviceName', + detail: 'blueSendData 蓝牙连接状态 bluetoothConnectionState:$bluetoothConnectionState deviceName:$deviceName', upload: false); _connect(deviceName, (BluetoothConnectionState state) { stateCallBack(bluetoothConnectionState!); @@ -455,8 +420,7 @@ class BlueManage { } else { BuglyTool.uploadException( message: '点击按钮 蓝牙未打开', - detail: - 'blueSendData 蓝牙未打开--_adapterState:${BluetoothAdapterState.on} deviceName:$deviceName', + detail: 'blueSendData 蓝牙未打开--_adapterState:${BluetoothAdapterState.on} deviceName:$deviceName', upload: false); try { stateCallBack(BluetoothConnectionState.disconnected); @@ -465,16 +429,13 @@ class BlueManage { AppLog.log('蓝牙打开失败'); BuglyTool.uploadException( message: '点击按钮 蓝牙未打开 然后蓝牙打开失败', - detail: - 'blueSendData 蓝牙打开失败--_adapterState:${BluetoothAdapterState.on} deviceName:$deviceName', + detail: 'blueSendData 蓝牙打开失败--_adapterState:${BluetoothAdapterState.on} deviceName:$deviceName', upload: false); } } } else { BuglyTool.uploadException( - message: '点击按钮 蓝牙状态不可用', - detail: 'blueSendData 蓝牙状态不可用--isAvailable:$isAvailable', - upload: false); + message: '点击按钮 蓝牙状态不可用', detail: 'blueSendData 蓝牙状态不可用--isAvailable:$isAvailable', upload: false); stateCallBack(BluetoothConnectionState.disconnected); AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作'); } @@ -482,8 +443,7 @@ class BlueManage { } /// 连接 - Future _connect( - String deviceName, ConnectStateCallBack connectStateCallBack, + Future _connect(String deviceName, ConnectStateCallBack connectStateCallBack, {bool isAddEquipment = false}) async { connectDeviceName = deviceName; // 当前已扫描到的缓存设备 @@ -491,16 +451,12 @@ class BlueManage { // 是否有缓存设备 true是有缓存设备 final bool isExistDevice = isExistScanDevices(connectDeviceName); // 是否是当前设备 - final bool isCurrentDevice = - CommonDataManage().currentKeyInfo.lockName == deviceName; + final bool isCurrentDevice = CommonDataManage().currentKeyInfo.lockName == deviceName; // mac地址 final String? mac = CommonDataManage().currentKeyInfo.mac; AppLog.log('开始连接 是否存在缓存:$isExistDevice 是否是当前设备:$isCurrentDevice mac:$mac'); - if (GetPlatform.isAndroid && - !isExistDevice && - isCurrentDevice && - mac != null) { + if (GetPlatform.isAndroid && !isExistDevice && isCurrentDevice && mac != null) { // 当是安卓设备 且不存在缓存设备 且是当前设备 且mac地址不为空 BuglyTool.uploadException( message: '开始连接 当是安卓设备 且不存在缓存设备 且是当前设备 且mac地址不为空 上传记录当前方法是:_connect', @@ -512,22 +468,17 @@ class BlueManage { try { if (!needScanSingle) { BuglyTool.uploadException( - message: - '开始连接 当是安卓设备 且不存在缓存设备 且是当前设备 且mac地址不为空 上传记录当前方法是:_connect', + message: '开始连接 当是安卓设备 且不存在缓存设备 且是当前设备 且mac地址不为空 上传记录当前方法是:_connect', detail: '调用方法doNotSearchBLE,直接连接,needScanSingle:$needScanSingle', upload: false); - await doNotSearchBLE(mac, connectStateCallBack, - isAddEquipment: isAddEquipment); + await doNotSearchBLE(mac, connectStateCallBack, isAddEquipment: isAddEquipment); } else { BuglyTool.uploadException( - message: - '开始连接 当是安卓设备 且不存在缓存设备 且是当前设备 且mac地址不为空 上传记录当前方法是:_connect', - detail: - '调用方法startScanSingle,执行扫描函数,needScanSingle:$needScanSingle', + message: '开始连接 当是安卓设备 且不存在缓存设备 且是当前设备 且mac地址不为空 上传记录当前方法是:_connect', + detail: '调用方法startScanSingle,执行扫描函数,needScanSingle:$needScanSingle', upload: false); startScanSingle(deviceName, 15, (List scanDevices) { - _connectDevice(scanDevices, deviceName, connectStateCallBack, - isAddEquipment: isAddEquipment); + _connectDevice(scanDevices, deviceName, connectStateCallBack, isAddEquipment: isAddEquipment); }); } } catch (e) { @@ -536,8 +487,7 @@ class BlueManage { detail: '调用方法doNotSearchBLE发生异常,执行扫描函数 startScanSingle,异常信息:$e', upload: false); startScanSingle(deviceName, 15, (List scanDevices) { - _connectDevice(scanDevices, deviceName, connectStateCallBack, - isAddEquipment: isAddEquipment); + _connectDevice(scanDevices, deviceName, connectStateCallBack, isAddEquipment: isAddEquipment); }); } // @@ -554,16 +504,13 @@ class BlueManage { } else if (isAddEquipment == false && isExistDevice == false) { // 取消缓存直接使用,存在配对场景设备信息会更变 BuglyTool.uploadException( - message: - '取消缓存直接使用,存在配对场景设备信息会更变 然后开始指定设备名称的扫描蓝牙设备 上传记录当前方法是:_connect', - detail: - '符合条件(isAddEquipment == false && isExistDevice == false) 下一步调用startScanSingle', + message: '取消缓存直接使用,存在配对场景设备信息会更变 然后开始指定设备名称的扫描蓝牙设备 上传记录当前方法是:_connect', + detail: '符合条件(isAddEquipment == false && isExistDevice == false) 下一步调用startScanSingle', upload: false); // AppLog.log('无存在设备需要扫描 deviceName:$deviceName isAddEquipment:$isAddEquipment'); startScanSingle(deviceName, 15, (List scanDevices) { - _connectDevice(scanDevices, deviceName, connectStateCallBack, - isAddEquipment: isAddEquipment); + _connectDevice(scanDevices, deviceName, connectStateCallBack, isAddEquipment: isAddEquipment); }); } else { BuglyTool.uploadException( @@ -572,16 +519,14 @@ class BlueManage { '走这个方法是有缓存或者添加设备的时候以及不符合(GetPlatform.isAndroid && !isExistDevice && isCurrentDevice && mac != null) deviceName:$deviceName 直接调用_connectDevice', upload: false); // AppLog.log('安卓或者iOS 存在设备不需要扫描 deviceName:$deviceName isAddEquipment:$isAddEquipment'); - _connectDevice(devicesList, deviceName, connectStateCallBack, - isAddEquipment: isAddEquipment); + _connectDevice(devicesList, deviceName, connectStateCallBack, isAddEquipment: isAddEquipment); } } //查找缓存里面是否有设备 bool isExistScanDevices(String connectDeviceName) { final bool isExistDevice = scanDevices.any((ScanResult element) => - element.device.platformName == connectDeviceName || - element.advertisementData.advName == connectDeviceName); + element.device.platformName == connectDeviceName || element.advertisementData.advName == connectDeviceName); return isExistDevice; } @@ -595,17 +540,15 @@ class BlueManage { // 判断数组列表里面是否有这个设备 // AppLog.log("devicesList:$devicesList"); - final int knownDeviceIndex = devicesList.indexWhere((ScanResult d) => - (d.device.platformName == deviceName) || - (d.advertisementData.advName == deviceName)); + final int knownDeviceIndex = devicesList.indexWhere( + (ScanResult d) => (d.device.platformName == deviceName) || (d.advertisementData.advName == deviceName)); ScanResult? scanResult; //使用局部变量防止出现缓存 if (knownDeviceIndex >= 0) { // 存在的时候赋值 - connectDeviceMacAddress = - devicesList[knownDeviceIndex].advertisementData.advName.isNotEmpty - ? devicesList[knownDeviceIndex].advertisementData.advName - : devicesList[knownDeviceIndex].device.platformName; + connectDeviceMacAddress = devicesList[knownDeviceIndex].advertisementData.advName.isNotEmpty + ? devicesList[knownDeviceIndex].advertisementData.advName + : devicesList[knownDeviceIndex].device.platformName; bluetoothConnectDevice = devicesList[knownDeviceIndex].device; scanResult = devicesList[knownDeviceIndex]; @@ -616,10 +559,8 @@ class BlueManage { } if (scanResult == null || connectDeviceMacAddress.isEmpty) { BuglyTool.uploadException( - message: - '扫描结果scanResult == null || connectDeviceMacAddress.isEmpty不往下执行 return 上传记录当前方法是:_connectDevice', - detail: - 'scanResult:$scanResult connectDeviceMacAddress:$connectDeviceMacAddress', + message: '扫描结果scanResult == null || connectDeviceMacAddress.isEmpty不往下执行 return 上传记录当前方法是:_connectDevice', + detail: 'scanResult:$scanResult connectDeviceMacAddress:$connectDeviceMacAddress', upload: false); return; } @@ -653,8 +594,7 @@ class BlueManage { BuglyTool.uploadException( message: '提示该锁已被重置, 回调断开连接, 清除缓存,上传记录当前方法是:_connectDevice', - detail: - 'isReconnect:$isReconnect serviceUuids:${scanResult.advertisementData.serviceUuids[0].toString()}', + detail: 'isReconnect:$isReconnect serviceUuids:${scanResult.advertisementData.serviceUuids[0].toString()}', upload: false); } return; @@ -686,8 +626,7 @@ class BlueManage { BuglyTool.uploadException( message: '提示该锁已被重置, 回调断开连接, 清除缓存,上传记录当前方法是:_connectDevice', - detail: - 'isReconnect:$isReconnect serviceUuids:${scanResult.advertisementData.serviceUuids[0].toString()}', + detail: 'isReconnect:$isReconnect serviceUuids:${scanResult.advertisementData.serviceUuids[0].toString()}', upload: false); } return; @@ -704,13 +643,11 @@ class BlueManage { } //直接给蓝牙设备写入 - Future doNotSearchBLE( - String masAdds, ConnectStateCallBack connectStateCallBack, + Future doNotSearchBLE(String masAdds, ConnectStateCallBack connectStateCallBack, {bool isAddEquipment = false}) async { await FlutterBluePlus.stopScan(); - if (bluetoothConnectDevice == null || - bluetoothConnectDevice?.remoteId.str != masAdds) { + if (bluetoothConnectDevice == null || bluetoothConnectDevice?.remoteId.str != masAdds) { bluetoothConnectDevice = BluetoothDevice.fromId(masAdds); _initGetMtuSubscription(); _initListenConnectionState(); @@ -721,18 +658,15 @@ class BlueManage { } else { BuglyTool.uploadException( message: '直接给蓝牙设备写入 上传记录当前方法是:doNotSearchBLE', - detail: - '直接给蓝牙设备写入 用传入的bluetoothConnectDevice:${bluetoothConnectDevice.toString()}连接 masAdds:$masAdds', + detail: '直接给蓝牙设备写入 用传入的bluetoothConnectDevice:${bluetoothConnectDevice.toString()}连接 masAdds:$masAdds', upload: false); } //尝试连接设备 - await bluetoothDeviceConnect(bluetoothConnectDevice!, connectStateCallBack, - isAddEquipment: isAddEquipment); + await bluetoothDeviceConnect(bluetoothConnectDevice!, connectStateCallBack, isAddEquipment: isAddEquipment); } //设备连接 - Future bluetoothDeviceConnect(BluetoothDevice bluetoothConnectDevice, - ConnectStateCallBack connectStateCallBack, + Future bluetoothDeviceConnect(BluetoothDevice bluetoothConnectDevice, ConnectStateCallBack connectStateCallBack, {bool isAddEquipment = false}) async { // 重连三次 const int maxAttempts = 3; @@ -754,8 +688,7 @@ class BlueManage { AppLog.log('$maxAttempts次后尝试连接失败'); BuglyTool.uploadException( message: '连接三次超时断开连接 回调断开连接 上传记录当前方法是:bluetoothDeviceConnect', - detail: - 'bluetoothDeviceConnect:${bluetoothConnectDevice.toString()} $maxAttempts次后尝试连接失败', + detail: 'bluetoothDeviceConnect:${bluetoothConnectDevice.toString()} $maxAttempts次后尝试连接失败', upload: false); needScanSingle = true; connectStateCallBack(BluetoothConnectionState.disconnected); @@ -764,22 +697,18 @@ class BlueManage { if (bluetoothConnectionState == BluetoothConnectionState.connected) { try { needScanSingle = false; - final List services = - await bluetoothConnectDevice.discoverServices(); + final List services = await bluetoothConnectDevice.discoverServices(); //循环判断服务 for (final BluetoothService service in services) { if (service.uuid == _serviceIdConnect) { - for (final BluetoothCharacteristic characteristic - in service.characteristics) { - if (characteristic.characteristicUuid == - _characteristicIdSubscription) { + for (final BluetoothCharacteristic characteristic in service.characteristics) { + if (characteristic.characteristicUuid == _characteristicIdSubscription) { _subScribeToCharacteristic(characteristic); bluetoothConnectionState = BluetoothConnectionState.connected; connectStateCallBack(bluetoothConnectionState!); BuglyTool.uploadException( message: '订阅成功 上传记录当前方法是:bluetoothDeviceConnect', - detail: - '发现服务,连接成功,订阅数据 bluetoothDeviceConnect:${bluetoothConnectDevice.toString()} ', + detail: '发现服务,连接成功,订阅数据 bluetoothDeviceConnect:${bluetoothConnectDevice.toString()} ', upload: false); } else { BuglyTool.uploadException( @@ -801,22 +730,18 @@ class BlueManage { needScanSingle = true; bluetoothConnectionState = BluetoothConnectionState.disconnected; connectStateCallBack(bluetoothConnectionState!); - AppLog.log( - '发现设备时失败 e:$e bluetoothConnectionState:$bluetoothConnectionState'); + AppLog.log('发现设备时失败 e:$e bluetoothConnectionState:$bluetoothConnectionState'); BuglyTool.uploadException( message: '发现服务时失败', - detail: - '发现服务时报错原因e:$e bluetoothDeviceConnect:${bluetoothConnectDevice.toString()}', + detail: '发现服务时报错原因e:$e bluetoothDeviceConnect:${bluetoothConnectDevice.toString()}', upload: false); rethrow; } } } - Future _subScribeToCharacteristic( - BluetoothCharacteristic characteristic) async { - final StreamSubscription> subscription = - characteristic.onValueReceived.listen((List data) { + Future _subScribeToCharacteristic(BluetoothCharacteristic characteristic) async { + final StreamSubscription> subscription = characteristic.onValueReceived.listen((List data) { AppLog.log('订阅获取的数据: $data '); if (data == lastTimeData || data.isEmpty) { return; @@ -864,10 +789,7 @@ class BlueManage { return false; } //239, 1, 238, 2, 是数据包头 - if ((data[0] == 0xEF) && - (data[1] == 0x01) && - (data[2] == 0xEE) && - (data[3] == 0x02)) { + if ((data[0] == 0xEF) && (data[1] == 0x01) && (data[2] == 0xEE) && (data[3] == 0x02)) { return true; } else { return false; @@ -876,12 +798,10 @@ class BlueManage { /// 写入蓝牙特征值,并等待响应 Future writeCharacteristicWithResponse(List value) async { - final List services = - await bluetoothConnectDevice!.discoverServices(); + final List services = await bluetoothConnectDevice!.discoverServices(); for (final BluetoothService service in services) { if (service.uuid == _serviceIdConnect) { - for (final BluetoothCharacteristic characteristic - in service.characteristics) { + for (final BluetoothCharacteristic characteristic in service.characteristics) { if (characteristic.characteristicUuid == _characteristicIdWrite) { try { // 添加重试机制 @@ -900,27 +820,22 @@ class BlueManage { while (!packetSent && retryCount < maxRetries) { try { if (characteristic.properties.writeWithoutResponse) { - await characteristic.write(subData[i], - withoutResponse: true); + await characteristic.write(subData[i], withoutResponse: true); } else if (characteristic.properties.write) { await characteristic.write(subData[i]); } else { // 特性不支持写入 - throw Exception( - 'This characteristic does not support writing.'); + throw Exception('This characteristic does not support writing.'); } // 如果到这里没有异常,则包发送成功 packetSent = true; } catch (e) { - if (e.toString().contains('UNKNOWN_GATT_ERROR (133)') && - retryCount < maxRetries - 1) { + if (e.toString().contains('UNKNOWN_GATT_ERROR (133)') && retryCount < maxRetries - 1) { // GATT错误133,尝试重试 retryCount++; - AppLog.log( - '蓝牙写入失败(GATT 133),数据包 ${i + 1}/${subData.length} 正在重试 $retryCount/$maxRetries...'); - await Future.delayed( - Duration(milliseconds: retryDelayMs)); + AppLog.log('蓝牙写入失败(GATT 133),数据包 ${i + 1}/${subData.length} 正在重试 $retryCount/$maxRetries...'); + await Future.delayed(Duration(milliseconds: retryDelayMs)); continue; } else { // 其他错误或已达到最大重试次数,抛出异常 @@ -931,8 +846,7 @@ class BlueManage { } if (!packetSent) { - throw Exception( - '蓝牙写入失败,数据包 ${i + 1}/${subData.length} 已达到最大重试次数'); + throw Exception('蓝牙写入失败,数据包 ${i + 1}/${subData.length} 已达到最大重试次数'); } } @@ -964,12 +878,12 @@ class BlueManage { Future disconnect() async { try { connectDeviceMacAddress = ''; - + // 清理MTU监听 _mtuSubscription?.cancel(); _mtuSubscription = null; _mtuSize = 20; // 重置MTU为默认值 - + if (bluetoothConnectionState == BluetoothConnectionState.connected) { //加快蓝牙断连 await bluetoothConnectDevice!.disconnect(timeout: 3); @@ -1006,7 +920,7 @@ class BlueManage { _mtuSubscription?.cancel(); _adapterStateStateSubscription?.cancel(); _connectionStateSubscription?.cancel(); - + // 重置状态 _mtuSize = 20; connectDeviceName = '';