import 'dart:async'; import 'dart:convert'; import 'package:get/get.dart'; import '../../pigeons/core_api.g.dart'; import '../../utils/haptic_feedback_manager.dart'; import '../../utils/log/logger.dart'; import '../constants/enums.dart'; import '../data/models/vpn_message.dart'; class CoreController extends GetxService { final TAG = 'CoreController'; final _state = ConnectionState.disconnected.obs; ConnectionState get state => _state.value; set state(ConnectionState value) => _state.value = value; final _timer = "00:00:00".obs; String get timer => _timer.value; set timer(String value) => _timer.value = value; // 事件流订阅 StreamSubscription? _eventSubscription; @override void onInit() { super.onInit(); _initCheckConnect(); _startListeningToEvents(); } @override void onClose() { super.onClose(); // 取消事件流订阅 _eventSubscription?.cancel(); _eventSubscription = null; } void _initCheckConnect() { CoreApi().isConnected().then((value) { if (value == true) { state = ConnectionState.connected; CoreApi().reconnect(); } else { state = ConnectionState.disconnected; } }); } void handleConnection() { if (state == ConnectionState.disconnected) { // 开始连接 - 轻微震动 state = ConnectionState.connecting; HapticFeedbackManager.connectionStart(); CoreApi().connect(); } else { // 断开连接 state = ConnectionState.disconnecting; CoreApi().disconnect(); } } /// 开始监听来自 Android 的事件 void _startListeningToEvents() { _eventSubscription = onEventChange().listen( _handleEventChange, onError: (error) { log(TAG, '事件流错误: $error'); }, ); } // 处理从原生端接收到的消息 void _handleEventChange(String message) { try { final Map json = jsonDecode(message); final String type = json['type'] ?? ''; switch (type) { case 'vpn_status': _handleVpnStatus(VpnStatusMessage.fromJson(json)); break; case 'timer_update': _handleTimerUpdate(TimerUpdateMessage.fromJson(json)); break; default: log(TAG, '未知消息类型: $type'); } } catch (e) { log(TAG, '解析消息失败: $e'); } } void _handleVpnStatus(VpnStatusMessage message) { log(TAG, 'VPN状态变化: status=${message.status}, message=${message.message}'); // 根据状态码处理不同的VPN状态 switch (message.status) { case 0: // disconnected _onVpnDisconnected(); break; case 1: // connecting _onVpnConnecting(); break; case 2: // connected _onVpnConnected(); break; case 3: // error _onVpnError(message.message); break; case 4: // disconnecting _onVpnDisconnecting(); break; case 403: // permission denied _onVpnPermissionDenied(); break; default: log(TAG, '未知VPN状态: ${message.status}'); } } void _handleTimerUpdate(TimerUpdateMessage message) { log( TAG, '计时更新: time=${message.currentTime}, mode=${message.mode}, running=${message.isRunning}, paused=${message.isPaused}', ); timer = _formatTime(message.currentTime); // 处理计时更新 if (message.isRunning) { if (message.isPaused) { _onTimerPaused(message.currentTime, message.mode); } else { _onTimerRunning(message.currentTime, message.mode); } } else { _onTimerStopped(); } } // VPN状态处理方法 void _onVpnDisconnected() { log(TAG, 'VPN已断开连接'); // 更新UI状态 state = ConnectionState.disconnected; timer = "00:00:00"; HapticFeedbackManager.connectionDisconnected(); } void _onVpnConnecting() { log(TAG, 'VPN正在连接'); // 显示连接中状态 state = ConnectionState.connecting; } void _onVpnConnected() { log(TAG, 'VPN已连接'); // 显示已连接状态 state = ConnectionState.connected; HapticFeedbackManager.connectionSuccess(); } void _onVpnError(String errorMessage) { log(TAG, 'VPN连接错误: $errorMessage'); // 显示错误信息 state = ConnectionState.disconnected; HapticFeedbackManager.connectionDisconnected(); // 可以显示错误提示 Get.snackbar('连接失败', '无法建立连接,请重试'); } void _onVpnDisconnecting() { log(TAG, 'VPN正在断开连接'); // 显示断开连接状态 state = ConnectionState.disconnecting; } void _onVpnPermissionDenied() { log(TAG, 'VPN权限拒绝'); // 显示权限拒绝状态 state = ConnectionState.disconnected; HapticFeedbackManager.connectionDisconnected(); // 可以显示错误提示 Get.snackbar('权限拒绝', '无法建立连接,请重试'); } // 计时器状态处理方法 void _onTimerRunning(int currentTime, int mode) { log( TAG, '计时器运行中: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}', ); } void _onTimerPaused(int currentTime, int mode) { log( TAG, '计时器已暂停: ${_formatTime(currentTime)}, 模式: ${mode == 0 ? "普通计时" : "倒计时"}', ); } void _onTimerStopped() { log(TAG, '计时器已停止'); } // 格式化时间显示 String _formatTime(int timeMs) { final totalSeconds = (timeMs / 1000).abs().round(); final days = totalSeconds ~/ 86400; // 86400 = 24 * 3600 final hours = (totalSeconds % 86400) ~/ 3600; final minutes = (totalSeconds % 3600) ~/ 60; final seconds = totalSeconds % 60; if (days > 0) { return '$days days ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'; } else if (hours > 0) { return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'; } else { return '00:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'; } } }