diff --git a/lib/data/services/ble_manager.dart b/lib/data/services/ble_manager.dart index 4805bb03f..5e11370a7 100644 --- a/lib/data/services/ble_manager.dart +++ b/lib/data/services/ble_manager.dart @@ -6,6 +6,7 @@ import 'package:deep_voice/core/utils/logger.dart'; import 'package:get_storage/get_storage.dart'; import 'dart:convert'; import 'package:agent_service/agent_service.dart'; +import 'bluetooth_manager.dart'; // 重新导出BLE连接状态常量,让外部可以通过BleManager访问 export 'package:ble_service/ble_service.dart' show BleConnectionState; @@ -107,6 +108,10 @@ class BleManager extends GetxService { final BleService _bleService = BleService(); // 经典蓝牙实例 + // 当前连接的设备信息 + String? _currentDeviceAddress; + String? _currentDeviceName; + // BLE连接状态 final _connectionState = BleConnectionState.disconnected.obs; int get connectionState => _connectionState.value; @@ -179,19 +184,8 @@ class BleManager extends GetxService { state == BleConnectionState.error) { Logger.info('BLE设备已断开或发生错误'); _isConnected.value = false; - // 更新设备信息 - _updateDeviceInfoIfNeeded( - batteryLevel: 0, - leftEarBattery: 0, - rightEarBattery: 0, - caseBattery: 0, - leftEarCharging: false, - rightEarCharging: false, - caseCharging: false, - firmwareVersion: '', - firmwareProductId: '', - firmwareProductColor: '', - ); + // 断开连接时不清除设备信息,保留最后的电量信息 + // 只有在需要完全清除设备时才重置信息 } } @@ -408,11 +402,14 @@ class BleManager extends GetxService { else if (deviceInfo.value == null && _isConnected.value && (firmwareVersion != null || batteryLevel != null)) { - // 提示尝试创建设备信息但缺少必要信息 - Logger.warning('尝试更新设备信息,但设备基本信息不存在'); + // 使用保存的设备信息创建新的DeviceInfo对象 + String deviceAddress = _currentDeviceAddress ?? ""; + String deviceName = _currentDeviceName ?? ""; + + Logger.info('创建新的设备信息对象: address=$deviceAddress, name=$deviceName'); deviceInfo.value = DeviceInfo( - address: "", // 应确保从连接信息中获取真实值 - name: "", + address: deviceAddress, + name: deviceName, batteryLevel: batteryLevel ?? 0, leftEarBattery: leftEarBattery ?? 0, rightEarBattery: rightEarBattery ?? 0, @@ -427,35 +424,59 @@ class BleManager extends GetxService { } } + /// 清除设备信息(用于完全断开连接或切换设备时) + void clearDeviceInfo() { + Logger.info('清除设备信息'); + deviceInfo.value = null; + _currentDeviceAddress = null; + _currentDeviceName = null; + } + /// 连接成功后获取设备信息 Future fetchDeviceInfo() async { Logger.info('开始获取BLE设备详细信息'); try { - // 获取电池信息 - final batteryResult = await _bleService.getBatteryInfo(); - if (batteryResult) { - Logger.info('电池信息获取指令已发送'); - } else { + // 确保设备信息对象存在 + if (deviceInfo.value == null && _isConnected.value) { + // 创建初始设备信息对象 + String deviceAddress = _currentDeviceAddress ?? ""; + String deviceName = _currentDeviceName ?? ""; + + Logger.info('初始化设备信息对象: address=$deviceAddress, name=$deviceName'); + deviceInfo.value = DeviceInfo( + address: deviceAddress, + name: deviceName, + batteryLevel: 0, + leftEarBattery: 0, + rightEarBattery: 0, + caseBattery: 0, + leftEarCharging: false, + rightEarCharging: false, + caseCharging: false, + firmwareVersion: '', + firmwareProductId: '', + firmwareProductColor: '', + ); + } + + // 并行获取所有设备信息,不使用延迟 + final results = await Future.wait([ + _bleService.getBatteryInfo(), + _bleService.getDeviceVersion(), + _bleService.getProductId(), + ]); + + Logger.info('设备信息获取结果: 电池=${results[0]}, 版本=${results[1]}, 产品ID=${results[2]}'); + + if (!results[0]) { Logger.warning('电池信息获取指令发送失败'); } - // 添加延迟 - await Future.delayed(const Duration(seconds: 1)); - // 获取设备版本信息 - final versionResult = await _bleService.getDeviceVersion(); - if (versionResult) { - Logger.info('版本信息获取指令已发送'); - } else { + if (!results[1]) { Logger.warning('版本信息获取指令发送失败'); } - // 添加延迟 - await Future.delayed(const Duration(seconds: 1)); - // 获取产品id - final productIdResult = await _bleService.getProductId(); - if (productIdResult) { - Logger.info('产品id获取指令已发送'); - } else { - Logger.warning('产品id获取指令发送失败'); + if (!results[2]) { + Logger.warning('产品ID获取指令发送失败'); } } catch (e) { Logger.error('获取BLE设备信息失败: ${e.toString()}'); @@ -576,6 +597,8 @@ class BleManager extends GetxService { Logger.info('BLE服务停止成功'); _isConnected.value = false; _connectionState.value = BleConnectionState.disconnected; + // 停止服务时清除设备信息 + clearDeviceInfo(); } else { Logger.error('BLE服务停止失败'); } @@ -756,6 +779,15 @@ class BleManager extends GetxService { /// 注册后台扫描 Future registerBackgroundScan({String? macAddress}) async { try { + // 保存设备地址信息 + if (macAddress != null) { + _currentDeviceAddress = macAddress; + // 从蓝牙管理器获取设备名称 + final bluetoothManager = Get.find(); + _currentDeviceName = bluetoothManager.currentDevice?.name ?? ""; + Logger.info('保存设备信息: address=$_currentDeviceAddress, name=$_currentDeviceName'); + } + return await _bleService.registerBackgroundScan(macAddress: macAddress); } catch (e) { Logger.error('注册后台扫描失败: ${e.toString()}'); diff --git a/lib/modules/home/controllers/home_controller.dart b/lib/modules/home/controllers/home_controller.dart index 748d767e6..04c687ba0 100644 --- a/lib/modules/home/controllers/home_controller.dart +++ b/lib/modules/home/controllers/home_controller.dart @@ -103,12 +103,22 @@ class HomeController extends GetxController { _classicBluetoothWorker = ever(_bluetoothManager.currentDeviceRx, (BluetoothDevice? device) { Logger.d(_tag, '经典蓝牙: ${device != null ? "已连接" : "已断开"}'); _checkConnectionStatus(); + // 额外的刷新确保UI更新 + Future.delayed(const Duration(milliseconds: 50), () { + _isFullyConnected.refresh(); + update(); + }); }); // BLE连接监听 _bleConnectionWorker = ever(_bleManager.connectionStateRx, (int state) { Logger.d(_tag, 'BLE状态变化: $state (${state == 2 ? "已连接" : "未连接"})'); _checkConnectionStatus(); + // 额外的刷新确保UI更新 + Future.delayed(const Duration(milliseconds: 50), () { + _isFullyConnected.refresh(); + update(); + }); }); } @@ -165,6 +175,14 @@ class HomeController extends GetxController { // 延迟一帧后再次刷新,确保UI更新 Future.delayed(Duration.zero, () { update(); + // 再次强制刷新响应式变量 + _isFullyConnected.refresh(); + }); + + // 延迟稍长时间再刷新一次,处理某些特殊情况 + Future.delayed(const Duration(milliseconds: 100), () { + update(); + _isFullyConnected.refresh(); }); } @@ -174,12 +192,16 @@ class HomeController extends GetxController { /// 获取连接状态对应的颜色 Color getConnectionStatusColor() { - return _isFullyConnected.value ? Colors.green : Colors.grey; + final isConnected = _isFullyConnected.value; + Logger.d(_tag, 'getConnectionStatusColor called: isConnected=$isConnected'); + return isConnected ? Colors.green : Colors.grey; } /// 获取连接状态对应的文本 String getConnectionStatusText() { - return _isFullyConnected.value ? 'connected'.tr : 'unconnected'.tr; + final isConnected = _isFullyConnected.value; + Logger.d(_tag, 'getConnectionStatusText called: isConnected=$isConnected'); + return isConnected ? 'connected'.tr : 'unconnected'.tr; } /// 判断是否应该显示设备信息(即使未完全连接) diff --git a/lib/modules/home/views/home_view.dart b/lib/modules/home/views/home_view.dart index b5c3653f7..d100d1a6c 100644 --- a/lib/modules/home/views/home_view.dart +++ b/lib/modules/home/views/home_view.dart @@ -203,8 +203,12 @@ class HomeView extends GetView { // 设备状态卡片 Widget _buildDeviceStatusCard(bool isDarkMode) { - return Container( - decoration: BoxDecoration( + return Obx(() { + // 使用连接状态作为key,强制在状态改变时重建widget + final isConnected = controller.isFullyConnectedRx.value; + return Container( + key: ValueKey('device_status_$isConnected'), + decoration: BoxDecoration( color: isDarkMode ? const Color(0xFF1A1A1A) : Colors.white, borderRadius: BorderRadius.circular(16.r), boxShadow: [ @@ -243,7 +247,8 @@ class HomeView extends GetView { }), ], ), - ); + ); + }); } // 设备状态头部