import 'package:app_settings/app_settings.dart'; import 'package:get/get.dart'; import 'dart:async'; import 'package:permission_handler/permission_handler.dart'; import '../../../routes/app_routes.dart'; import '../../../core/utils/logger.dart'; import 'dart:io'; import '../../../data/services/bluetooth_manager.dart'; import 'package:classic_bluetooth/classic_bluetooth.dart' show BluetoothDevice; import '../../../data/services/ble_manager.dart'; import 'package:ble_service/ble_service.dart'; /// 配对控制器,负责检查蓝牙权限、状态,并处理配对流程 class PairingController extends GetxController { static PairingController get to => Get.find(); // 需要设备 final bool needdeivice = false; // 状态标志 final isLoading = false.obs; // 权限是否已授予 final _hasPermissions = false.obs; bool get hasPermissions => _hasPermissions.value; // 蓝牙状态 final _bluetoothState = 'unknown'.obs; String get bluetoothState => _bluetoothState.value; bool get isBluetoothOn => _bluetoothState.value == 'on'; // 状态描述(用于UI显示) final statusDescription = 'initializing'.tr.obs; // 按钮文本 final actionButtonText = '去系统设置'.obs; // 是否正在跳转到主页 bool _isNavigatingToHome = false; // 是否正在执行Companion关联流程 bool _isAssociating = false; // 是否用户拒绝了关联 final _userRejectedAssociation = false.obs; bool get userRejectedAssociation => _userRejectedAssociation.value; // 当前连接设备信息 BluetoothDevice? get currentDevice => _bluetoothService.currentDevice; // 是否已连接设备 bool get isDeviceConnected => currentDevice != null; // 是否已完成Companion关联 final _companionAssociated = false.obs; bool get isCompanionAssociated => _companionAssociated.value; // 服务状态监听 Worker? _bluetoothStateWorker; Worker? _deviceWorker; // 蓝牙服务 final _bluetoothService = Get.find(); // BLE服务 final _bleService = BleService(); @override void onInit() { super.onInit(); _initialize(); } @override void onClose() { _bluetoothStateWorker?.dispose(); _deviceWorker?.dispose(); super.onClose(); } /// 初始化流程 Future _initialize() async { try { isLoading.value = true; statusDescription.value = 'checkingPermissions'.tr; // 检查并请求权限 if (!await _checkAndRequestPermissions()) { statusDescription.value = 'permissionDenied'.tr; actionButtonText.value = '去系统设置'; return; } // 设置服务状态监听 _setupServiceListeners(); // 检查蓝牙状态并刷新设备 await _checkBluetoothAndRefresh(); } catch (e) { Logger.error('初始化配对控制器失败: $e'); statusDescription.value = 'initializationFailure'.tr; } finally { isLoading.value = false; _updateStatusDescription(); } } /// 检查蓝牙状态并刷新设备 Future _checkBluetoothAndRefresh() async { statusDescription.value = 'checkingBluetoothStatus'.tr; final isEnabled = await _bluetoothService.isBluetoothEnabled(); _bluetoothState.value = isEnabled ? 'on' : 'off'; if (!isEnabled) { statusDescription.value = 'bluetoothTurnedOff'.tr; actionButtonText.value = '去系统设置'; return; } // 刷新连接设备并检查配对状态 statusDescription.value = 'searchingDevice'.tr; await _bluetoothService.refreshDeviceConnection(); // 设备连接时检查配对状态 if (isDeviceConnected) { await _checkDevicePairingStatus(); } } /// 检查设备配对状态 Future _checkDevicePairingStatus() async { // 只在Android平台且设备已连接时执行 if (!Platform.isAndroid || !isDeviceConnected) return; try { final isSupported = await _bleService.isCompanionSupported(); if (!isSupported) { Logger.info('设备不支持Companion功能'); _companionAssociated.value = true; // 不支持则视为已配对 _userRejectedAssociation.value = false; // 重置拒绝状态 return; } final pairedMac = await _bleService.getPairedMacAddress(); if (pairedMac == null) { // 没有配对记录,需要开始配对 Logger.info('无配对记录,需要开始设备配对'); return; } Logger.info('发现已关联的Companion设备: $pairedMac'); // 检查当前连接设备与已保存的设备是否一致 if (currentDevice!.address != pairedMac) { // MAC地址不匹配 Logger.warning('当前连接的设备与已配对的DeepSound设备不符'); statusDescription.value = 'pleaseConnectPairedDevice'.tr; return; } // 判断设备名称是否符合要求 if (!_isValidDeviceName(currentDevice!.name)) { statusDescription.value = 'pleaseConnectDeepSoundDevice'.tr; return; } // 设备匹配且合规,标记为已配对 Logger.info('当前设备与已配对设备匹配'); _companionAssociated.value = true; _userRejectedAssociation.value = false; // 重置拒绝状态 await _bleService.registerBackgroundScan(); _autoNavigateToHome(); } catch (e) { Logger.error('检查设备配对状态失败: $e'); } } /// 检查设备名称是否合规 bool _isValidDeviceName(String deviceName) { return deviceName.contains("DeapSound"); } /// 检查并请求必要的蓝牙权限 Future _checkAndRequestPermissions() async { Map statuses; List permissionsToRequest = []; if (Platform.isAndroid) { permissionsToRequest.add(Permission.locationWhenInUse); // permissionsToRequest.add(Permission.microphone); if (await _getAndroidSdkVersion() >= 31) { permissionsToRequest.add(Permission.bluetoothScan); permissionsToRequest.add(Permission.bluetoothConnect); } } else if (Platform.isIOS) { permissionsToRequest.add(Permission.bluetooth); } statuses = await permissionsToRequest.request(); bool allGranted = true; statuses.forEach((permission, status) { if (!status.isGranted) { allGranted = false; Logger.warning('权限 ${permission.toString()} 未被授予: $status'); } }); _hasPermissions.value = allGranted; return allGranted; } // 辅助方法获取Android SDK版本 Future _getAndroidSdkVersion() async { if (Platform.isAndroid) { return 31; // 假设运行在需要新权限的设备上 } return 0; } /// 设置服务状态监听 void _setupServiceListeners() { // 监听蓝牙状态变化 _bluetoothStateWorker = ever(_bluetoothService.bluetoothState.obs, (String state) { _bluetoothState.value = state; _updateStatusDescription(); }); // 监听设备连接状态变化 _deviceWorker = ever(_bluetoothService.currentDeviceRx, (BluetoothDevice? device) { if (device != null && !_isNavigatingToHome) { Logger.info('配对页面发现设备已连接: ${device.name}'); _handleDeviceConnected(); } _updateStatusDescription(); }); if (needdeivice) { _handleDeviceConnected(); } } /// 处理设备连接成功事件 Future _handleDeviceConnected() async { if (!isDeviceConnected || _isNavigatingToHome) return; // 检查配对状态,决定下一步操作 await _checkDevicePairingStatus(); // 如果还未配对且设备合规,启动配对流程 if (!_companionAssociated.value && _isValidDeviceName(currentDevice!.name)) { _startCompanionAssociation(); } } /// 更新状态描述 void _updateStatusDescription() { if (_userRejectedAssociation.value) { // 用户拒绝关联时的提示 - 这是最高优先级 statusDescription.value = '关联后才能使用全部功能'; actionButtonText.value = '关联DeapSound耳机'; return; } if (!hasPermissions) { statusDescription.value = 'permissionDenied'.tr; actionButtonText.value = '去系统设置'; return; } if (bluetoothState == 'off') { statusDescription.value = 'bluetoothTurnedOff'.tr; actionButtonText.value = '去系统设置'; return; } if (isDeviceConnected) { if (Platform.isAndroid && !isCompanionAssociated && _isAssociating) { statusDescription.value = '${'associatingDevice'.tr} ${currentDevice!.name}'; } else { statusDescription.value = '${'connectedDevice'.tr} ${currentDevice!.name}'; } return; } if (isLoading.value) { statusDescription.value = 'searchingDevice'.tr; return; } statusDescription.value = 'notFound'.tr; } /// 启动Companion设备关联流程 Future _startCompanionAssociation() async { // 如果不是Android平台,已跳转,已完成关联或正在进行关联,直接返回 if (!Platform.isAndroid || _isNavigatingToHome || _companionAssociated.value || _isAssociating || !isDeviceConnected) { return; } // 重置拒绝状态 _userRejectedAssociation.value = false; // 设置关联状态标志 _isAssociating = true; _updateStatusDescription(); try { // 检查是否支持Companion功能 final isSupported = await _bleService.isCompanionSupported(); if (!isSupported) { Logger.info('设备不支持Companion功能,跳过关联'); _companionAssociated.value = true; _autoNavigateToHome(); return; } // 检查设备名称是否符合要求 if (!_isValidDeviceName(currentDevice!.name)) { statusDescription.value = 'pleaseConnectDeepSoundDevice'.tr; _isAssociating = false; return; } Logger.info('开始Companion设备关联流程, 设备MAC: ${currentDevice!.address}'); var success = await _bleService.startDeviceAssociation( deviceNamePattern: currentDevice!.name, macAddress: currentDevice!.address, ); _isAssociating = false; if (success) { Logger.info('Companion设备关联成功'); _companionAssociated.value = true; _userRejectedAssociation.value = false; // 注册后台扫描,确保应用被杀死后仍能被唤醒 await _bleService.registerBackgroundScan( macAddress: currentDevice!.address); // 关联成功后跳转 _autoNavigateToHome(); } else { Logger.error('Companion设备关联失败或被用户拒绝'); // 关联失败 - 用户拒绝关联 _userRejectedAssociation.value = true; // 确保UI状态更新 _updateStatusDescription(); } } catch (e) { Logger.error('Companion设备关联过程发生错误: $e'); _isAssociating = false; _userRejectedAssociation.value = true; _updateStatusDescription(); } } /// 自动跳转到主页 Future _autoNavigateToHome() async { if (needdeivice && (_isNavigatingToHome || !isDeviceConnected)) return; // 启动BLE后台服务 await _startAgentService(); _isNavigatingToHome = true; Logger.info('已找到连接的设备 ${currentDevice!.name},自动跳转到主页'); Future.delayed(const Duration(milliseconds: 500), () { Get.offAllNamed(Routes.home); }); } /// 启动BLE后台服务 Future _startAgentService() async { try { if (needdeivice && !isDeviceConnected) return; final result = await BleManager.to.startAgentService(); Logger.info(result ? 'BLE后台服务启动成功' : 'BLE后台服务启动失败'); } catch (e) { Logger.error('启动BLE后台服务发生错误: $e'); } } /// 停止BLE后台服务 Future _stopAgentService() async { try { final result = await BleManager.to.stopAgentService(); Logger.info(result ? 'BLE后台服务停止成功' : 'BLE后台服务停止失败'); } catch (e) { Logger.error('停止BLE后台服务发生错误: $e'); } } /// 处理按钮点击 void handleActionButtonTap() { if (userRejectedAssociation) { // 用户拒绝关联后,点击按钮重新开始关联 restartAssociation(); } else if (!hasPermissions || !isBluetoothOn) { // 权限未授予或蓝牙关闭时,打开系统设置 openBluetoothSettings(); } } /// 打开系统蓝牙设置 void openBluetoothSettings() { try { if (!hasPermissions) { openAppSettings(); } else if (Platform.isAndroid && !isBluetoothOn) { AppSettings.openAppSettings(type: AppSettingsType.bluetooth); } else if (Platform.isIOS) { openAppSettings(); } else { AppSettings.openAppSettings(type: AppSettingsType.bluetooth); } } catch (e) { Logger.error('打开设置失败: $e'); } } /// 打开应用设置 Future openAppSettings() async { await AppSettings.openAppSettings(); } /// 重新开始关联 void restartAssociation() { if (isDeviceConnected && !isCompanionAssociated) { _startCompanionAssociation(); } } /// 跳过连接 void skipConnecting() async { // 启动BLE后台服务 await _startAgentService(); _isNavigatingToHome = true; Get.offAllNamed(Routes.home); } }