fix: 修复已配对的设备还能搜索到的问题

This commit is contained in:
liyi 2025-09-19 10:20:39 +08:00
parent cfde51c063
commit adf1cf3f1c

View File

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