You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

269 lines
7.8 KiB

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 'package:classic_bluetooth/classic_bluetooth.dart';
/// 配对控制器,负责检查蓝牙权限、状态,并处理配对流程
class PairingController extends GetxController {
static PairingController get to => Get.find();
// 状态标志
final isLoading = false.obs;
// 权限是否已授予
final _hasPermissions = false.obs;
bool get hasPermissions => _hasPermissions.value;
// 蓝牙状态
final _bluetoothState = 'unknown'.obs;
String get bluetoothState => _bluetoothState.value;
// 状态描述(用于UI显示)
final statusDescription = 'initializing'.tr.obs;
// 是否正在跳转到主页
bool _isNavigatingToHome = false;
// 当前连接设备
final Rx<BluetoothDevice?> _currentDevice = Rx<BluetoothDevice?>(null);
BluetoothDevice? get currentDevice => _currentDevice.value;
// 蓝牙事件订阅
StreamSubscription<BluetoothEvent>? _bluetoothSubscription;
@override
void onInit() {
super.onInit();
_initialize();
}
@override
void onClose() {
_bluetoothSubscription?.cancel();
super.onClose();
}
/// 初始化流程
Future<void> _initialize() async {
try {
isLoading.value = true;
statusDescription.value = 'checkingPermissions'.tr;
// 检查并请求权限
if (!await _checkAndRequestPermissions()) {
statusDescription.value = 'permissionDenied'.tr;
return;
}
// 监听蓝牙状态变化
_setupBluetoothListener();
// 检查蓝牙状态
statusDescription.value = 'checkingBluetoothStatus'.tr;
final isEnabled = await ClassicBluetooth.isBluetoothEnabled();
_bluetoothState.value = isEnabled ? 'on' : 'off';
if (!isEnabled) {
statusDescription.value = 'bluetoothTurnedOff'.tr;
return;
}
// 刷新已连接设备
statusDescription.value = 'searchingDevice'.tr;
await refreshConnectedDevices();
} catch (e) {
Logger.error('初始化配对控制器失败: $e');
statusDescription.value = 'initializationFailure'.tr;
} finally {
isLoading.value = false;
_updateStatusDescription();
}
}
/// 检查并请求必要的蓝牙权限
Future<bool> _checkAndRequestPermissions() async {
Map<Permission, PermissionStatus> statuses;
List<Permission> permissionsToRequest = [];
if (Platform.isAndroid) {
// Android 12+ (SDK 31+) 需要 SCAN 和 CONNECT
// Android 6+ (SDK 23+) 需要 LOCATION
permissionsToRequest.add(Permission.locationWhenInUse); // 基本定位权限
// Android 12及以上版本才需要请求蓝牙扫描和连接权限
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<int> _getAndroidSdkVersion() async {
if (Platform.isAndroid) {
// 这里需要原生代码支持来获取确切的SDK版本,
// 或者使用 device_info_plus 插件
// 暂时返回一个较高值以触发新权限请求
return 31; // 假设运行在需要新权限的设备上
}
return 0;
}
/// 设置蓝牙状态监听
void _setupBluetoothListener() {
_bluetoothSubscription?.cancel();
try {
_bluetoothSubscription = ClassicBluetooth.events.listen(
(event) {
if (event.type == 'stateChanged' && event.state != null) {
_bluetoothState.value = event.state!;
_updateStatusDescription();
// 如果蓝牙关闭,清除设备
if (event.state == 'off') {
_currentDevice.value = null;
}
} else if (event.type == 'deviceConnected' && event.device != null) {
// 直接从事件中获取设备信息
final newDevice = event.device!;
// 更新当前设备
_currentDevice.value = newDevice;
_updateStatusDescription();
// 设备连接时自动跳转到主页
_autoNavigateToHome();
} else if (event.type == 'deviceDisconnected' && event.device != null) {
// 直接从事件中获取设备信息
final disconnectedDevice = event.device!;
// 如果断开的是当前设备,清除当前设备
if (_currentDevice.value?.address == disconnectedDevice.address) {
_currentDevice.value = null;
}
_updateStatusDescription();
}
},
onError: (error) {
Logger.error('蓝牙事件流错误: $error');
},
);
} catch (e) {
Logger.error('设置蓝牙事件监听器失败: $e');
}
}
/// 更新状态描述
void _updateStatusDescription() {
if (!hasPermissions) {
statusDescription.value = 'permissionDenied'.tr;
return;
}
if (bluetoothState == 'off') {
statusDescription.value = 'bluetoothTurnedOff'.tr;
return;
}
if (currentDevice != null) {
statusDescription.value = '${'connectedDevice'.tr} ${currentDevice!.name}';
return;
}
if (isLoading.value) {
statusDescription.value = 'searchingDevice'.tr;
return;
}
statusDescription.value = 'notFound'.tr;
}
/// 刷新已连接设备
Future<void> refreshConnectedDevices() async {
if (!hasPermissions) {
statusDescription.value = 'permissionDenied'.tr;
return;
}
try {
isLoading.value = true;
statusDescription.value = 'searchingDevice'.tr;
// 获取已连接的蓝牙设备
final devices = await ClassicBluetooth.getConnectedDevices();
// 如果有设备则设置为当前设备
if (devices.isNotEmpty) {
_currentDevice.value = devices.first;
_autoNavigateToHome();
} else {
_currentDevice.value = null;
}
} catch (e) {
Logger.error('刷新设备失败: $e');
statusDescription.value = 'failedRefreshDevice'.tr;
} finally {
isLoading.value = false;
_updateStatusDescription();
}
}
/// 自动跳转到主页
void _autoNavigateToHome() {
if (_isNavigatingToHome || currentDevice == null) return;
_isNavigatingToHome = true;
Logger.info('已找到连接的设备 ${currentDevice?.name},自动跳转到主页');
Future.delayed(const Duration(milliseconds: 500), () {
Get.offAllNamed(Routes.home);
});
}
/// 打开系统蓝牙设置
void openBluetoothSettings() {
try {
if (!hasPermissions) {
openAppSettings();
} else if (Platform.isAndroid && bluetoothState == 'off') {
AppSettings.openAppSettings(type: AppSettingsType.bluetooth);
} else if (Platform.isIOS) {
openAppSettings();
} else {
AppSettings.openAppSettings(type: AppSettingsType.bluetooth);
}
} catch (e) {
Logger.error('打开设置失败: $e');
}
}
/// 打开应用设置
Future<void> openAppSettings() async {
await AppSettings.openAppSettings();
}
/// 跳过连接
void skipConnecting() {
_isNavigatingToHome = true;
Get.offAllNamed(Routes.home);
}
}