From 43f76371744704cbb39253279f773fe633d0c4e0 Mon Sep 17 00:00:00 2001 From: wolfplus Date: Wed, 18 Jun 2025 12:05:38 +0100 Subject: [PATCH] add --- .../home/controllers/home_controller.dart | 190 ++++++---------- lib/modules/home/views/home_view.dart | 209 +----------------- .../controllers/pairing_controller.dart | 2 +- 3 files changed, 73 insertions(+), 328 deletions(-) diff --git a/lib/modules/home/controllers/home_controller.dart b/lib/modules/home/controllers/home_controller.dart index 4616d5c49..650083239 100644 --- a/lib/modules/home/controllers/home_controller.dart +++ b/lib/modules/home/controllers/home_controller.dart @@ -16,20 +16,16 @@ enum ConnectionStatus { /// 主页控制器,管理设备连接状态和信息展示 class HomeController extends GetxController { + static const String _tag = 'HomeCtrl'; static HomeController get to => Get.find(); // 连接状态相关 - final _connectionStatus = ConnectionStatus.disconnected.obs; - final _connectionErrorMsg = ''.obs; - final _bluetoothState = 'unknown'.obs; - + final _isFullyConnected = false.obs; + // Getter方法 - ConnectionStatus get connectionStatus => _connectionStatus.value; - String get connectionErrorMsg => _connectionErrorMsg.value; - String get bluetoothState => _bluetoothState.value; + bool get isFullyConnected => _isFullyConnected.value; BluetoothDevice? get currentDevice => _bluetoothManager.currentDevice; Rx get deviceInfo => _bleManager.deviceInfo; - bool get isConnected => currentDevice != null; // 设备详细信息的getter,从deviceInfo获取数据 final leftEarBattery = 0.obs; @@ -60,8 +56,8 @@ class HomeController extends GetxController { // 监听和订阅 Worker? _deviceInfoWorker; - Worker? _bluetoothStateWorker; - Worker? _deviceWorker; + Worker? _classicBluetoothWorker; + Worker? _bleConnectionWorker; // 蓝牙服务 final _bluetoothManager = Get.find(); @@ -75,112 +71,49 @@ class HomeController extends GetxController { @override void onClose() { _deviceInfoWorker?.dispose(); - _bluetoothStateWorker?.dispose(); - _deviceWorker?.dispose(); + _classicBluetoothWorker?.dispose(); + _bleConnectionWorker?.dispose(); super.onClose(); } - /// 使用缓存的蓝牙设备信息初始化 + /// 初始化 void _initWithCachedInfo() { - // 使用蓝牙服务中的当前状态 - _bluetoothState.value = _bluetoothManager.bluetoothState; - - // 根据当前设备状态设置连接状态 - if (currentDevice != null) { - _connectionStatus.value = ConnectionStatus.connected; - _connectionErrorMsg.value = ''; - updateDeviceInfo(_bleManager.deviceInfo.value); - Logger.info('主页加载缓存设备信息: ${currentDevice!.name}'); - } else { - _connectionStatus.value = ConnectionStatus.disconnected; - if (_bluetoothState.value == 'off') { - _connectionErrorMsg.value = '蓝牙未开启'; - } else { - _connectionErrorMsg.value = '未连接到设备'; - } - } - - // 设置监听器监听蓝牙服务状态变化 + // 设置监听器 _setupStateListeners(); - - // 在初始化时自动触发一次刷新设备连接状态 - refreshDeviceConnection(); + + // 延迟检查初始连接状态,确保监听器已经设置 + Future.delayed(const Duration(milliseconds: 100), () { + _checkConnectionStatus(); + }); } /// 设置状态监听器 void _setupStateListeners() { - // 设备信息监听 - 设备信息更新时自动触发UI更新 + // 设备信息监听 _deviceInfoWorker = ever(_bleManager.deviceInfo, (DeviceInfo? info) { - Logger.info('设备信息监听'); if (info != null) { - Logger.info('主页更新设备信息: ${info.toString()}'); + Logger.d(_tag, '更新设备信息: ${info.toString()}'); updateDeviceInfo(info); - } else { - Logger.info('主页清空设备信息'); } - update(); }); - // 蓝牙状态监听 - _bluetoothStateWorker = - ever(_bluetoothManager.bluetoothState.obs, (String state) { - _bluetoothState.value = state; - - // 如果蓝牙关闭,更新错误信息 - if (state == 'off') { - _connectionErrorMsg.value = '蓝牙未开启'; - _connectionStatus.value = ConnectionStatus.disconnected; - } - - update(); + // 经典蓝牙连接监听 + _classicBluetoothWorker = ever(_bluetoothManager.currentDeviceRx, (BluetoothDevice? device) { + Logger.d(_tag, '经典蓝牙: ${device != null ? "已连接" : "已断开"}'); + _checkConnectionStatus(); }); - - // 设备连接状态监听 - 直接监听设备变化 - _deviceWorker = - ever(_bluetoothManager.currentDeviceRx, (BluetoothDevice? device) { - if (device != null) { - // 设备已连接 - if (_connectionStatus.value != ConnectionStatus.connected) { - _connectionStatus.value = ConnectionStatus.connected; - _connectionErrorMsg.value = ''; - Logger.info('主页检测到设备已连接: ${device.name}'); - } - } else if (_connectionStatus.value == ConnectionStatus.connected) { - // 设备已断开 - _connectionStatus.value = ConnectionStatus.disconnected; - _connectionErrorMsg.value = '设备已断开连接'; - - Logger.info('主页检测到设备已断开连接'); - } - - update(); + + // BLE连接监听 + _bleConnectionWorker = ever(_bleManager.connectionStateRx, (int state) { + Logger.d(_tag, 'BLE状态变化: $state (${state == 2 ? "已连接" : "未连接"})'); + _checkConnectionStatus(); }); } /// 刷新设备连接状态 - /// 注意:此方法不会主动刷新设备,只更新UI状态 Future refreshDeviceConnection() async { - // 更新当前状态以反映UI变化 - bool hasDevice = currentDevice != null; - - if (hasDevice) { - _connectionStatus.value = ConnectionStatus.connected; - _connectionErrorMsg.value = ''; - await _bleManager.fetchDeviceInfo(); - - Logger.info('使用缓存设备信息: ${currentDevice!.name}'); - } else { - if (_bluetoothState.value == 'off') { - _connectionErrorMsg.value = '蓝牙未开启'; - } else { - _connectionErrorMsg.value = '未连接到设备'; - } - _connectionStatus.value = ConnectionStatus.disconnected; - } - - // 刷新UI - update(); + _checkConnectionStatus(); } // 导航和功能方法 @@ -201,41 +134,56 @@ class HomeController extends GetxController { } // UI辅助方法 + + /// 检查连接状态 + void _checkConnectionStatus() { + // 直接检查,不使用延迟 + bool hasClassicBluetooth = currentDevice != null; + bool hasBleConnection = _bleManager.connectionState == 2; // 直接检查状态值,2 = connected + + Logger.d(_tag, '连接状态检查: 经典蓝牙=$hasClassicBluetooth, BLE=$hasBleConnection (状态值=${_bleManager.connectionState})'); + + bool wasConnected = _isFullyConnected.value; + bool isNowConnected = hasClassicBluetooth && hasBleConnection; + + // 只有状态真正改变时才更新 + if (_isFullyConnected.value != isNowConnected) { + // 先更新状态 + _isFullyConnected.value = isNowConnected; + Logger.d(_tag, '连接状态变更: ${wasConnected ? "已连接" : "未连接"} -> ${isNowConnected ? "已连接" : "未连接"}'); + + // 强制触发响应式更新 + _isFullyConnected.refresh(); + + // 如果从未连接变为连接,主动获取耳机信息 + if (!wasConnected && isNowConnected) { + Logger.d(_tag, '设备连接成功,获取耳机信息'); + _bleManager.fetchDeviceInfo(); + } + + // 延迟一帧后再次刷新,确保UI更新 + Future.delayed(Duration.zero, () { + update(); + }); + } + + // 总是调用update确保UI刷新 + update(); + } /// 获取连接状态对应的颜色 Color getConnectionStatusColor() { - switch (_connectionStatus.value) { - case ConnectionStatus.connected: - return Colors.green; - case ConnectionStatus.connecting: - return Colors.amber; - case ConnectionStatus.failed: - return Colors.red; - case ConnectionStatus.disconnected: - default: - return Colors.grey; - } + return _isFullyConnected.value ? Colors.green : Colors.grey; } /// 获取连接状态对应的文本 String getConnectionStatusText() { - if (bluetoothState == 'off') { - return 'bluetoothOff'.tr; - } - - switch (_connectionStatus.value) { - case ConnectionStatus.connected: - return 'connected'.tr; - case ConnectionStatus.connecting: - return 'connecting'.tr; - case ConnectionStatus.failed: - return 'connectionFailure'.tr; - case ConnectionStatus.disconnected: - default: - return 'unconnected'.tr; - } + return _isFullyConnected.value ? 'connected'.tr : 'unconnected'.tr; } + /// 判断是否应该显示设备信息(即使未完全连接) + bool get shouldShowDeviceInfo => currentDevice != null; + /// 获取设备名称 String getDeviceName() { return currentDevice?.name ?? 'unknownEquipment'.tr; @@ -243,7 +191,7 @@ class HomeController extends GetxController { /// 获取信号强度(模拟数据) String getSignalStrength() { - if (!isConnected) { + if (!_isFullyConnected.value) { return 'zeroSignal'.tr; } diff --git a/lib/modules/home/views/home_view.dart b/lib/modules/home/views/home_view.dart index be4cef42d..8cc809fda 100644 --- a/lib/modules/home/views/home_view.dart +++ b/lib/modules/home/views/home_view.dart @@ -5,8 +5,6 @@ import '../controllers/home_controller.dart'; import '../../../routes/app_pages.dart'; import '../../../routes/app_routes.dart'; import '../../../core/widgets/common_bottom_nav.dart'; -// 导入枚举 -import '../controllers/home_controller.dart' show ConnectionStatus; // 呼吸灯动画组件 class AnimatedPulsing extends StatefulWidget { @@ -226,18 +224,9 @@ class HomeView extends GetView { // 设备信息 SizedBox(height: 12.h), Obx(() { - // 如果连接失败且有错误信息,显示错误提示 - if (controller.connectionStatus == ConnectionStatus.failed && - controller.connectionErrorMsg.isNotEmpty) { - return _buildConnectionErrorSection(isDarkMode); //错误提示 - } - - // 如果正在连接中,显示连接中提示 - if (controller.connectionStatus == ConnectionStatus.connecting) { - return _buildConnectingIndicator(); //连接中提示 - } + // 移除连接失败和连接中的状态判断,直接根据是否完全连接来判断 - return controller.isConnected + return controller.isFullyConnected ? _buildConnectedDeviceInfo(isDarkMode) //已连接设备信息 : _buildDisconnectedInfo(isDarkMode); //未连接提示 }), @@ -245,7 +234,7 @@ class HomeView extends GetView { // 连接按钮(仅在未连接时显示) SizedBox(height: 12.h), Obx(() { - if (controller.connectionStatus == ConnectionStatus.disconnected) { + if (!controller.isFullyConnected) { return _buildConnectButton(); } else { return const SizedBox(); @@ -332,95 +321,7 @@ class HomeView extends GetView { } // 连接错误部分 - Widget _buildConnectionErrorSection(bool isDarkMode) { - return Column( - children: [ - Container( - padding: EdgeInsets.all(12.w), - decoration: BoxDecoration( - color: - isDarkMode ? Colors.red[900]!.withOpacity(0.2) : Colors.red[50], - borderRadius: BorderRadius.circular(12.r), - border: Border.all( - color: isDarkMode ? Colors.red[800]! : Colors.red[200]!, - ), - ), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Icon( - Icons.error_outline, - color: Colors.red, - size: 18.sp, - ), - SizedBox(width: 8.w), - Expanded( - child: Text( - controller.connectionErrorMsg, - style: TextStyle( - fontSize: 12.sp, - height: 1.4, - color: isDarkMode ? Colors.red[300] : Colors.red[800], - ), - ), - ), - ], - ), - ), - SizedBox(height: 12.h), - // 连接按钮 - ElevatedButton( - onPressed: controller.rescanDevices, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.blue, - foregroundColor: Colors.white, - minimumSize: Size(double.infinity, 40.h), - elevation: 2, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10.r), - ), - ), - child: Text( - 'reconnect'.tr, // 重新连接 - style: TextStyle( - fontSize: 14.sp, - fontWeight: FontWeight.w500, - ), - ), - ), - ], - ); - } - // 连接中指示器 - Widget _buildConnectingIndicator() { - return Container( - padding: EdgeInsets.symmetric(vertical: 20.h), - child: Center( - child: Column( - children: [ - SizedBox( - width: 30.w, - height: 30.w, - child: CircularProgressIndicator( - strokeWidth: 2.5.w, - valueColor: AlwaysStoppedAnimation(Colors.blue), - ), - ), - SizedBox(height: 12.h), - Text( - 'connectingDevice'.tr, - style: TextStyle( - fontSize: 13.sp, - color: Colors.blue, - fontWeight: FontWeight.w500, - ), - ), - ], - ), - ), - ); - } // 已连接设备信息(新增设备名称 + 信号强度 + 电池信息) Widget _buildConnectedDeviceInfo(bool isDarkMode) { @@ -608,110 +509,6 @@ class HomeView extends GetView { } // 设备详情卡片 - Widget _buildDeviceDetailsCard(bool isDarkMode) { - return Container( - padding: EdgeInsets.all(12.w), - decoration: BoxDecoration( - color: isDarkMode ? Colors.grey[900] : Colors.grey[50], - borderRadius: BorderRadius.circular(12.r), - border: Border.all( - color: isDarkMode ? Colors.grey[800]! : Colors.grey[200]!, - width: 1, - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // 设备ID - _buildInfoRow( - icon: Icons.perm_device_info, - label: 'deviceId'.tr, - value: controller.getDeviceId(), - isDarkMode: isDarkMode, - ), - SizedBox(height: 8.h), - - // 固件版本 - _buildInfoRow( - icon: Icons.info_outline, - label: 'firmwareVersion'.tr, - value: controller.firmwareVersion.value, - isDarkMode: isDarkMode, - ), - - // 连接状态标签 - // SizedBox(height: 10.h), - // Container( - // padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), - // decoration: BoxDecoration( - // color: controller.getConnectionStatusColor().withOpacity(0.1), - // borderRadius: BorderRadius.circular(6.r), - // border: Border.all( - // color: controller.getConnectionStatusColor().withOpacity(0.3), - // width: 1, - // ), - // ), - // child: Row( - // mainAxisSize: MainAxisSize.min, - // children: [ - // Icon( - // Icons.check_circle_outline, - // size: 12.sp, - // color: controller.getConnectionStatusColor(), - // ), - // SizedBox(width: 4.w), - // Text( - // controller.getConnectionStatusText(), - // style: TextStyle( - // fontSize: 11.sp, - // color: controller.getConnectionStatusColor(), - // fontWeight: FontWeight.w500, - // ), - // ), - // ], - // ), - // ), - ], - ), - ); - } - - // 信息行 - Widget _buildInfoRow({ - required IconData icon, - required String label, - required String value, - required bool isDarkMode, - }) { - return Row( - children: [ - Icon( - icon, - size: 14.sp, - color: isDarkMode ? Colors.grey[400] : Colors.grey[600], - ), - SizedBox(width: 6.w), - Text( - '$label: ', - style: TextStyle( - fontSize: 11.sp, - color: isDarkMode ? Colors.grey[400] : Colors.grey[600], - ), - ), - Expanded( - child: Text( - value.isEmpty ? 'unknown'.tr : value, - style: TextStyle( - fontSize: 11.sp, - fontWeight: FontWeight.w500, - color: isDarkMode ? Colors.grey[300] : Colors.grey[700], - ), - overflow: TextOverflow.ellipsis, - ), - ), - ], - ); - } // 未连接信息 Widget _buildDisconnectedInfo(bool isDarkMode) { diff --git a/lib/modules/pairing/controllers/pairing_controller.dart b/lib/modules/pairing/controllers/pairing_controller.dart index e8fd9945e..ed7484c52 100644 --- a/lib/modules/pairing/controllers/pairing_controller.dart +++ b/lib/modules/pairing/controllers/pairing_controller.dart @@ -37,7 +37,7 @@ class PairingController extends GetxController { PairingState get state => _state.value; // ==================== 手动模式控制 ==================== - final isManualMode = true.obs; + final isManualMode = false.obs; final isReadyToStart = false.obs; // ==================== 状态数据 ====================