From 1d0366414cf20da9e18c36d7fdbe1de334243449 Mon Sep 17 00:00:00 2001 From: liyi Date: Thu, 4 Sep 2025 17:01:56 +0800 Subject: [PATCH] =?UTF-8?q?fix:=E8=B0=83=E6=95=B4mtu=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/app.dart | 2 +- lib/blue/blue_manage.dart | 45 ++++++++++++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/lib/app.dart b/lib/app.dart index bc3b4bff..c6185a9a 100755 --- a/lib/app.dart +++ b/lib/app.dart @@ -144,7 +144,7 @@ class _MyAppState extends State with WidgetsBindingObserver, BaseWidget { break; case AppLifecycleState.paused: // AppLog.log('App--->进入后台'); - BlueManage().disconnect(); + BlueManage.instance.disconnect(); break; case AppLifecycleState.resumed: // AppLog.log('App--->进入前台'); diff --git a/lib/blue/blue_manage.dart b/lib/blue/blue_manage.dart index b49f20a8..398171f6 100755 --- a/lib/blue/blue_manage.dart +++ b/lib/blue/blue_manage.dart @@ -85,6 +85,12 @@ class BlueManage { return _manager; } + // 提供全局单例访问入口 + static BlueManage get instance { + _manager ??= BlueManage._init(); + return _manager!; + } + BlueManage? get manager => shareManager(); void _initBlue() { @@ -94,9 +100,13 @@ class BlueManage { } void _initGetMtuSubscription() { - _mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((int value) { + // 先取消之前的订阅,避免重复监听 + _mtuSubscription?.cancel(); + _mtuSubscription = null; + + _mtuSubscription = bluetoothConnectDevice!.mtu.listen((int value) { _mtuSize = value - 3; - AppLog.log('_mtuSizeValue:$value mtuSize:$_mtuSize'); + AppLog.log('设备MTU变化 - 原始值:$value 计算后MTU:$_mtuSize 设备:${bluetoothConnectDevice?.remoteId.str}'); }); } @@ -954,6 +964,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); @@ -975,10 +991,29 @@ class BlueManage { } } + // 获取当前MTU信息,用于调试 + String getMtuDebugInfo() { + return 'MTU Debug Info:\n' + '- Current MTU Size: $_mtuSize\n' + '- Connected Device: ${bluetoothConnectDevice?.remoteId.str ?? "None"}\n' + '- Device Name: $connectDeviceName\n' + '- Connection State: $bluetoothConnectionState\n' + '- MTU Subscription Active: ${_mtuSubscription != null}'; + } + void disposed() { _sendStreamSubscription?.cancel(); - _mtuSubscription!.cancel(); - _adapterStateStateSubscription!.cancel(); - _connectionStateSubscription!.cancel(); + _mtuSubscription?.cancel(); + _adapterStateStateSubscription?.cancel(); + _connectionStateSubscription?.cancel(); + + // 重置状态 + _mtuSize = 20; + connectDeviceName = ''; + connectDeviceMacAddress = ''; + bluetoothConnectDevice = null; + scanDevices.clear(); + allData.clear(); + lastTimeData.clear(); } }