diff --git a/assets/languages/en-US.json b/assets/languages/en-US.json index 1fa4f6e4..c2a8e35f 100644 --- a/assets/languages/en-US.json +++ b/assets/languages/en-US.json @@ -336,6 +336,27 @@ }, "remote_control": { + "permission_checking": "Checking…", + "permission_sending": "Requesting…", + "permission_waiting": "Awaiting response…", + "permission_unconfirmed": "Unconfirmed", + "permission_request_failed": "Request unsuccessful", + "permission_invalid_device": "Cannot request control: no target device", + "permission_auth_required": "Your sign-in has expired. Please sign in again.", + "permission_query_invalid": "Invalid permission response. Please retry.", + "permission_query_rejected": "Permission check unsuccessful. Please retry later.", + "permission_query_timeout": "Permission check timed out. Please retry.", + "permission_query_failed": "Permission check failed. Check your network and retry.", + "permission_tcp_disconnected": "Request not sent: TCP is disconnected", + "permission_send_uncertain": "Send error. Delivery is unconfirmed. Please retry later.", + "permission_sent": "Control request sent via TCP. Awaiting a response.", + "permission_already_granted": "You already have control", + "permission_granted": "Control acquired", + "permission_denied": "The control holder denied your request", + "permission_not_granted": "Control request unsuccessful", + "permission_connection_lost": "Connection lost. Request result is unconfirmed.", + "permission_result_timeout": "No control confirmation received yet. Please retry later.", + "permission_handover_pending": "Please handle the current control handover request first", "controlling": "Controlling", "not_controlling": "Not Controlling", "permission_request_title": "Permission Change", @@ -355,6 +376,30 @@ "left_right": "Left/Right", "emergency_stop": "E-Stop", "emergency_stopping": "Stopping", + "emergency_submitting": "Sending", + "emergency_unknown": "Unknown", + "emergency_inactive": "Not stopped", + "emergency_status_unavailable": "No valid e-stop status received for this vehicle. Command unavailable.", + "emergency_already_active": "This vehicle is already in e-stop. No duplicate command sent.", + "emergency_already_released": "This vehicle is not in e-stop. No release command sent.", + "emergency_retry": "Tap to retry", + "emergency_request_sent": "E-stop request submitted. Device action is unconfirmed.", + "emergency_release_sent": "E-stop release requested. Device action is unconfirmed.", + "emergency_request_failed": "Request failed or action unconfirmed. Check the vehicle before retrying.", + "emergency_request_rejected": "Request rejected. The displayed state has not changed. Please retry.", + "emergency_release_action": "Release", + "mower_last_operation": "Last action: {operation}\n(Release to center: no action)", + "mower_operation_on": "On", + "mower_operation_off": "Off", + "mower_operation_none": "None", + "emergency_missing_sn": "No vehicle SN selected. E-stop request was not sent.", + "emergency_confirm_title": "Confirm emergency stop", + "emergency_confirm_message": "Send an emergency-stop request to vehicle {sn}? Confirm to enter the stop state in this app.", + "emergency_release_title": "Confirm e-stop release", + "emergency_release_message": "Request e-stop release for vehicle {sn}? Check that people and the work area are safe before confirming.", + "emergency_cancel": "Cancel", + "emergency_confirm_stop": "Confirm stop", + "emergency_confirm_release": "Confirm release", "perm_unknown_device": "Unknown device", "perm_unknown_platform": "Unknown platform", "permission_request_body": "{platform} is requesting control\n\nDevice ID: {deviceId}\n\nRelease control?", @@ -377,14 +422,15 @@ "view_map": "Map", "emergency_stop": "E-Stop", "emergency_stopping": "Stopping", - "sheet_mower_title": "Mower Lift", - "sheet_mower_hint": "Left: raise · Right: lower · Release: stop", + "sheet_mower_title": "Mower Switch", + "sheet_mower_hint": "Left: on · Right: off · Release to center: no action", "sheet_chassis_title": "Chassis Lift", "sheet_chassis_hint": "Left: up · Right: down · Release: stop", "sheet_fire_title": "Ignition", "sheet_fire_hint": "Left: ignite · Right: extinguish · Center: stop", - "seg_mower_up": "Raise", - "seg_mower_down": "Lower", + "seg_mower_up": "On", + "seg_mower_down": "Off", + "seg_mower_idle": "No action", "seg_chassis_up": "Up", "seg_chassis_down": "Down", "seg_fire_up": "Ignite", @@ -435,6 +481,14 @@ "chassis_height": "Height", "position_quality": "Position Quality", "mower_status": "Mower", + "mower_stopped": "Stopped", + "left_measured_rpm": "Left measured", + "right_measured_rpm": "Right measured", + "left_target_rpm": "Left target", + "right_target_rpm": "Right target", + "status_moving": "Moving", + "status_stopped": "Stopped", + "status_blocked": "Blocked", "mower_running": "Running", "battery_label": "Battery", "current_speed": "Speed", @@ -784,6 +838,9 @@ "view_detail": "View details", "stat_energy": "Energy", "stat_control_mode": "Control mode", + "stat_emergency_stop": "E-stop status", + "emergency_stop_active": "E-stop on", + "emergency_stop_inactive": "E-stop off", "stat_chip_temp": "Chip temperature", "stat_blade_speed": "Blade speed", "stat_voltage": "Battery voltage", diff --git a/assets/languages/zh-CN.json b/assets/languages/zh-CN.json index 4e5f3915..0abddd71 100644 --- a/assets/languages/zh-CN.json +++ b/assets/languages/zh-CN.json @@ -336,6 +336,29 @@ }, "remote_control": { + "permission_checking": "查询中…", + "permission_sending": "申请中…", + "permission_waiting": "等待响应…", + "permission_unconfirmed": "结果未确认", + "permission_request_failed": "申请未成功", + "permission_invalid_device": "无法申请:未获取到目标设备", + "permission_auth_required": "登录信息失效,请重新登录", + "permission_query_invalid": "权限查询返回异常,请重试", + "permission_query_rejected": "权限查询未成功,请稍后重试", + "permission_query_timeout": "权限查询超时,请重试", + "permission_query_failed": "权限查询失败,请检查网络后重试", + "permission_tcp_disconnected": "申请未发送:TCP 未连接", + "permission_send_uncertain": "发送异常,未确认是否送达,请稍后重试", + "permission_sent": "申请已通过 TCP 发出,等待响应", + "permission_already_granted": "当前已拥有控制权", + "permission_granted": "已获得控制权", + "permission_denied": "对方拒绝了控制权申请", + "permission_not_granted": "控制权申请未成功", + "permission_connection_lost": "连接已断开,申请结果未确认", + "permission_result_timeout": "暂未收到控制权确认,请稍后重试", + "permission_handover_pending": "请先处理当前的权限交接请求", + "tcp_heartbeat": "遥控心跳:收到服务器心跳时闪亮", + "tcp_unavailable": "遥控连接暂不可用,请稍后重试", "controlling": "正在控制", "not_controlling": "未在控制", "permission_request_title": "权限变更", @@ -355,6 +378,30 @@ "left_right": "左右控制", "emergency_stop": "急停", "emergency_stopping": "急停中", + "emergency_submitting": "请求中", + "emergency_unknown": "状态未知", + "emergency_inactive": "未急停", + "emergency_status_unavailable": "未收到该机器的有效急停状态,暂不能下发", + "emergency_already_active": "当前车辆已处于急停状态,无需重复下发", + "emergency_already_released": "当前车辆未急停,无需重复解除", + "emergency_retry": "点击重试", + "emergency_request_sent": "急停请求已提交,设备执行待确认", + "emergency_release_sent": "解除急停请求已提交,设备执行待确认", + "emergency_request_failed": "请求失败或执行结果未确认,请核对车辆状态后重试", + "emergency_request_rejected": "操作失败,页面状态未切换,请重试", + "emergency_release_action": "解除急停", + "mower_last_operation": "上次操作:{operation}\n(松手回中不触发)", + "mower_operation_on": "开启", + "mower_operation_off": "关闭", + "mower_operation_none": "无", + "emergency_missing_sn": "未找到当前车辆 SN,急停请求未发送", + "emergency_confirm_title": "确认急停", + "emergency_confirm_message": "确定向车辆 {sn} 发送急停请求吗?确认后将进入急停操作状态。", + "emergency_release_title": "确认解除急停", + "emergency_release_message": "确定向车辆 {sn} 发送解除急停请求吗?请先确认周围人员和作业环境安全。", + "emergency_cancel": "取消", + "emergency_confirm_stop": "确认急停", + "emergency_confirm_release": "确认解除", "perm_unknown_device": "未知设备", "perm_unknown_platform": "未知平台", "permission_request_body": "{platform} 端正在请求控制权\n\n设备ID: {deviceId}\n\n是否同意释放控制权?", @@ -377,14 +424,15 @@ "view_map": "查看地图", "emergency_stop": "紧急停止", "emergency_stopping": "急停中", - "sheet_mower_title": "割刀升降", - "sheet_mower_hint": "左滑抬刀 · 右滑降刀 · 松手停", + "sheet_mower_title": "割刀开关", + "sheet_mower_hint": "左滑开启 · 右滑关闭 · 松手回中不触发", "sheet_chassis_title": "底盘升降", "sheet_chassis_hint": "左滑升 · 右滑降 · 松手停", "sheet_fire_title": "点火", "sheet_fire_hint": "左滑点火 · 右滑熄火 · 中间停", - "seg_mower_up": "抬刀", - "seg_mower_down": "降刀", + "seg_mower_up": "开启", + "seg_mower_down": "关闭", + "seg_mower_idle": "不触发", "seg_chassis_up": "升高", "seg_chassis_down": "降低", "seg_fire_up": "点火", @@ -435,6 +483,14 @@ "chassis_height": "底盘高度", "position_quality": "定位质量", "mower_status": "割刀状态", + "mower_stopped": "已停转", + "left_measured_rpm": "左轮实测", + "right_measured_rpm": "右轮实测", + "left_target_rpm": "左轮目标", + "right_target_rpm": "右轮目标", + "status_moving": "行驶中", + "status_stopped": "已停止", + "status_blocked": "受阻", "mower_running": "运行中", "battery_label": "电池电量", "current_speed": "当前速度", @@ -783,6 +839,9 @@ "view_detail": "查看详情", "stat_energy": "能源", "stat_control_mode": "控制模式", + "stat_emergency_stop": "急停状态", + "emergency_stop_active": "急停中", + "emergency_stop_inactive": "未急停", "stat_chip_temp": "芯片温度", "stat_blade_speed": "割刀转速", "stat_voltage": "电池电压", diff --git a/lib/components/device_status_modal.dart b/lib/components/device_status_modal.dart index e582106e..019055fd 100644 --- a/lib/components/device_status_modal.dart +++ b/lib/components/device_status_modal.dart @@ -280,6 +280,7 @@ class _DeviceStatusModalState extends State { Widget _buildOtherParamsTable(DeviceStatusUpdated state) { final status = state.status; + final l10n = AppLocalizations.of(context); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -415,6 +416,25 @@ class _DeviceStatusModalState extends State { ), ], ), + TableRow( + children: [ + _buildTableCell( + l10n.translate('device_detail_v2.stat_emergency_stop'), + ), + _buildTableCell( + status.emergencyStop == null + ? '--' + : l10n.translate( + status.emergencyStop! + ? 'device_detail_v2.emergency_stop_active' + : 'device_detail_v2.emergency_stop_inactive', + ), + textColor: status.emergencyStop == true + ? const Color(0xFFDC2626) + : null, + ), + ], + ), TableRow( children: [ _buildTableCell( @@ -443,7 +463,11 @@ class _DeviceStatusModalState extends State { ); } - Widget _buildTableCell(String text, {bool isHeader = false}) { + Widget _buildTableCell( + String text, { + bool isHeader = false, + Color? textColor, + }) { return TableCell( child: Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 6), @@ -452,7 +476,8 @@ class _DeviceStatusModalState extends State { textAlign: TextAlign.center, style: TextStyle( fontSize: 14, - color: isHeader ? const Color(0xFF333333) : const Color(0xFF666666), + color: textColor ?? + (isHeader ? const Color(0xFF333333) : const Color(0xFF666666)), fontWeight: isHeader ? FontWeight.bold : FontWeight.normal, ), ), diff --git a/lib/core/consts/http_api_consts.dart b/lib/core/consts/http_api_consts.dart index 920971ac..03b5ac09 100644 --- a/lib/core/consts/http_api_consts.dart +++ b/lib/core/consts/http_api_consts.dart @@ -59,6 +59,9 @@ class HttpApiConsts { // GET,2=自主任务,3=远程遥控;路径 modeChage 沿用后端协议拼写。 static String get hostModeChange => "$baseUrl/iot/host/modeChage"; + // GET,query: deviceId、eStop(1=请求急停,0=请求解除)。 + static String get hostEmergencyStopChange => "$baseUrl/iot/host/eStopChange"; + // 修改设备别名(只写 deviceAlias,deviceName 保持不变) static String get updateDeviceAlias => "$baseUrl/forward/device/updateDeviceAlias"; diff --git a/lib/core/di/injection.dart b/lib/core/di/injection.dart index 9d568ec2..6ac8c6c6 100644 --- a/lib/core/di/injection.dart +++ b/lib/core/di/injection.dart @@ -45,6 +45,10 @@ import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remot import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/diff_steer_usecase.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_control_permission_usecase.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../features/auth/data/datasources/auth_http_datasource.dart'; @@ -390,6 +394,17 @@ Future init() async { () => RequestControlPermissionUseCase(sl()), ); + // 独立急停接口:仅注册数据/领域层,不自动请求或接入页面。 + sl.registerLazySingleton(() => EmergencyStopRemoteDatasource(sl())); + sl.registerLazySingleton( + () => + DeviceEmergencyStopRepositoryImpl(sl()), + ); + sl.registerLazySingleton( + () => + RequestDeviceEmergencyStopUseCase(sl()), + ); + /// Home V2 sl.registerLazySingleton( () => HomeRemoteDataSourceImpl(), @@ -574,6 +589,7 @@ Future init() async { sl(), // TcpClient sl(), // NetMessageDispatcher sl(), // DeviceStatusBloc + requestEmergencyStop: sl(), ), ); diff --git a/lib/core/logging/control_permission_diagnostics.dart b/lib/core/logging/control_permission_diagnostics.dart new file mode 100644 index 00000000..4a2fe718 --- /dev/null +++ b/lib/core/logging/control_permission_diagnostics.dart @@ -0,0 +1,47 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +import 'remote_control_diagnostics.dart'; + +/// Passive tracing only. Identifiers stay local and never enter HTTP/TCP data. +class ControlPermissionDiagnostics { + static final Object _scopeKey = Object(); + + static Map? get context => + Zone.current[_scopeKey] as Map?; + + static T scope(Map fields, T Function() action) => + runZoned( + action, + zoneValues: {_scopeKey: Map.of(fields)}, + ); + + static Object? scalar(Object? value) => + value == null || value is String || value is num || value is bool + ? value + : '<${value.runtimeType}>'; + + /// Callers supply whitelisted fields, never tokens, headers, or raw packets. + static void event(String step, [Map fields = const {}]) { + try { + final trace = RemoteControlDiagnostics.instance; + final record = { + 'time': DateTime.now().toIso8601String(), + ...?context, + ...fields, + 'traceVersion': 1, + 'permissionStep': step, + }; + final startedUs = record['startedUs']; + if (startedUs is int) { + record['elapsedMs'] = (trace.elapsedUs - startedUs) ~/ 1000; + } + trace.event('permission_trace', record); + debugPrint('[权限链][$step] ${jsonEncode(record)}'); + } catch (_) { + // Logging cannot interrupt permission, motion, or safety handling. + } + } +} diff --git a/lib/core/logging/remote_control_diagnostics.dart b/lib/core/logging/remote_control_diagnostics.dart new file mode 100644 index 00000000..0db48d24 --- /dev/null +++ b/lib/core/logging/remote_control_diagnostics.dart @@ -0,0 +1,121 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:path_provider/path_provider.dart'; + +/// Passive motion tracing. This class never sends commands or awaits a network +/// operation. File writes are buffered and serialized separately from control. +class RemoteControlDiagnostics { + RemoteControlDiagnostics({Future Function(String)? append}) + : _appendOverride = append; + + static RemoteControlDiagnostics instance = RemoteControlDiagnostics(); + static final Object _frameKey = Object(); + final Future Function(String)? _appendOverride; + final Stopwatch _clock = Stopwatch()..start(); + final String _run = DateTime.now().microsecondsSinceEpoch.toString(); + final List _pending = []; + Future? _directory; + Future? _inFlight; + Timer? _flushTimer; + int _sequence = 0; + int _frameSequence = 0; + int _sessionSequence = 0; + int _dropped = 0; + String? activeDevice; + + int get elapsedUs => _clock.elapsedMicroseconds; + + void begin(String? device, Map configuration) { + activeDevice = device; + _sessionSequence++; + event('session_start', configuration); + } + + void end(String reason) { + event('session_end', {'reason': reason}); + activeDevice = null; + unawaited(flush()); + } + + /// Local correlation only; no identifiers are added to the wire protocol. + T frame(String source, Map fields, T Function() send) { + final context = { + 'session': _sessionSequence, + 'device': activeDevice, + 'frame': ++_frameSequence, + 'source': source, + ...fields, + }; + return runZoned(send, zoneValues: {_frameKey: context}); + } + + void event(String stage, Map fields) { + try { + final frame = Zone.current[_frameKey] as Map?; + final record = { + 'time': DateTime.now().toIso8601String(), + 'us': elapsedUs, + 'run': _run, + 'session': _sessionSequence, + 'seq': ++_sequence, + 'device': activeDevice, + if (frame != null) ...frame, + 'stage': stage, + ...fields, + }; + for (final key in record.keys.toList()) { + final value = record[key]; + if (value is double && !value.isFinite) record[key] = value.toString(); + } + // A stalled filesystem cannot grow memory without bounds or block control. + if (_pending.length >= 2000) { + _pending.removeAt(0); + _dropped++; + } + _pending.add('${jsonEncode(record)}\n'); + _flushTimer ??= Timer(const Duration(milliseconds: 500), () { + _flushTimer = null; + unawaited(flush()); + }); + } catch (_) { + // Diagnostics must never interrupt an input, control or safety callback. + } + } + + Future _append(String content) async { + final override = _appendOverride; + if (override != null) return override(content); + final directory = await (_directory ??= getApplicationDocumentsDirectory()); + final day = DateTime.now().toIso8601String().substring(0, 10); + await File( + '${directory.path}/remote_control_$day.jsonl', + ).writeAsString(content, mode: FileMode.append); + } + + Future flush() { + _flushTimer?.cancel(); + _flushTimer = null; + return _inFlight ??= _drain().whenComplete(() => _inFlight = null); + } + + Future _drain() async { + while (_pending.isNotEmpty) { + final dropped = _dropped; + _dropped = 0; + final batch = _pending.join(); + _pending.clear(); + try { + await _append( + '${dropped == 0 ? '' : '${jsonEncode({'stage': 'diagnostic_overflow', 'dropped': dropped})}\n'}$batch', + ); + } catch (_) { + // Mark missing records in the next successful write instead of silently + // making a logging failure look like a gap in TCP transmission. + _dropped += dropped + '\n'.allMatches(batch).length; + return; + } + } + } +} diff --git a/lib/core/network/mqtt/data/datasources/mower_realtime_datasource.dart b/lib/core/network/mqtt/data/datasources/mower_realtime_datasource.dart index 76c2b120..50f8a7ec 100644 --- a/lib/core/network/mqtt/data/datasources/mower_realtime_datasource.dart +++ b/lib/core/network/mqtt/data/datasources/mower_realtime_datasource.dart @@ -99,35 +99,37 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { controller = StreamController( onListen: () { // 先监听报文再订阅 Topic,接住订阅时立即到达的消息。 - messageSubscription = messages.where((msg) => msg.topic == topic).listen( - (message) { - try { - final json = jsonDecode(message.payload); - if (json is! Map) return; - final payload = json['data']; - final data = payload is Map ? payload : json; - final battery = HostRealtimeMessageEntity.parseBatteryPercentage( - data['battery_percentage'], - ); - lastBattery = battery ?? lastBattery; - controller.add( - ( - battery: lastBattery, - controlMode: data['control_mode']?.toString().trim() ?? '', - ), - ); - } on FormatException { - // 忽略格式异常的单帧,等待下一次上报。 - } - }, - onError: controller.addError, - onDone: controller.close, - ); - topicSubscription = mqttClient.subscribe(topic).catchError( - (Object error, StackTrace stackTrace) { - if (!controller.isClosed) controller.addError(error, stackTrace); - }, - ); + messageSubscription = messages + .where((msg) => msg.topic == topic) + .listen( + (message) { + try { + final json = jsonDecode(message.payload); + if (json is! Map) return; + final payload = json['data']; + final data = payload is Map ? payload : json; + final battery = + HostRealtimeMessageEntity.parseBatteryPercentage( + data['battery_percentage'], + ); + lastBattery = battery ?? lastBattery; + controller.add(( + battery: lastBattery, + controlMode: data['control_mode']?.toString().trim() ?? '', + )); + } on FormatException { + // 忽略格式异常的单帧,等待下一次上报。 + } + }, + onError: controller.addError, + onDone: controller.close, + ); + topicSubscription = mqttClient.subscribe(topic).catchError(( + Object error, + StackTrace stackTrace, + ) { + if (!controller.isClosed) controller.addError(error, stackTrace); + }); }, onCancel: () async { await messageSubscription?.cancel(); @@ -154,7 +156,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { // 🔥 同一设备重复调用:去重,不重复订阅(参照 DroneOsdDataSource 已验证的模式) if (_deviceSn == deviceSn && _subscription != null) { - debugPrint('${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn'); + debugPrint( + '${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn', + ); return; } @@ -164,7 +168,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { await mqttClient.unsubscribe(_locationTopic(_deviceSn!)); await mqttClient.unsubscribe(_routeTopic(_deviceSn!)); await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!)); - debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn'); + debugPrint( + '${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn', + ); } _deviceSn = deviceSn; @@ -173,15 +179,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { _routeMsgCount = 0; _hostMsgCount = 0; + // 先监听消息,接住订阅后立即到达的推送(包括 retained 消息)。 + _subscription ??= mqttClient.messageStream?.listen(_handleMessage); + await mqttClient.subscribe(_realtimeTopic(deviceSn)); await mqttClient.subscribe(_locationTopic(deviceSn)); await mqttClient.subscribe(_routeTopic(deviceSn)); await mqttClient.subscribe(_hostRealtimeTopic(deviceSn)); - // 消息流监听只建立一次,按 _deviceSn 过滤 - _subscription ??= mqttClient.messageStream?.listen(_handleMessage); - - debugPrint('${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn'); + debugPrint( + '${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn', + ); debugPrint(' 车辆实时: ${_realtimeTopic(deviceSn)}'); debugPrint(' 定位: ${_locationTopic(deviceSn)}'); debugPrint(' 路径规划: ${_routeTopic(deviceSn)}'); @@ -196,7 +204,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { await mqttClient.unsubscribe(_locationTopic(_deviceSn!)); await mqttClient.unsubscribe(_routeTopic(_deviceSn!)); await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!)); - debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn'); + debugPrint( + '${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn', + ); _deviceSn = null; } @@ -206,12 +216,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { // 🔥 防串台:只处理当前监听设备的主题(mower/ 和 device/ 前缀都要匹配) if (!message.topic.contains('mower/$sn/') && - !message.topic.contains('device/$sn/')) return; + !message.topic.contains('device/$sn/')) + return; - // 🔥 第一阶段:打印原始报文,确认格式后再完善解析 - debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] ──────── 收到消息 ────────'); - debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}'); - debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] payload: ${message.payload}'); + // 实时状态逐帧打印原始报文,在解析前确认急停字段是否实际下发。 + if (message.topic == _realtimeTopic(sn) || + message.topic == _hostRealtimeTopic(sn)) { + debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}'); + debugPrint('[MQTT-机器状态] payload 开始'); + debugPrint(message.payload, wrapWidth: 800); + debugPrint('[MQTT-机器状态] payload 结束'); + } try { final jsonData = jsonDecode(message.payload) as Map; @@ -224,9 +239,13 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { if (_vehicleMsgCount == 1) { debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 车辆实时首帧到达: $sn'); } - debugPrint('${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个'); + debugPrint( + '${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个', + ); for (final dp in vehicle.data) { - debugPrint('${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}'); + debugPrint( + '${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}', + ); } _vehicleController.add(vehicle); } @@ -238,7 +257,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { // 🔥 关键修复:坐标在 data 子对象中,不是顶层 final dataObj = jsonData['data'] as Map? ?? jsonData; final location = MowerLocationEntity.fromJson(dataObj); - debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}'); + // debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}'); _locationController.add(location); } else if (message.topic.endsWith(_hostRealtimeSuffix)) { // 🔥 主机实时(新增话题,纯附加):外层套信封,数据在 json.data,提取方式与定位一致 @@ -247,8 +266,14 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { debugPrint('${LogTime.now()} 🎉 [MQTT-主机实时] 首帧到达: $sn'); } final dataObj = jsonData['data'] as Map? ?? jsonData; - final host = HostRealtimeMessageEntity.fromJson(dataObj); - debugPrint('${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 急停=${host.emergencyStop} 运动=${host.motion}'); + final host = HostRealtimeMessageEntity.fromJson( + dataObj, + deviceSn: sn, + receivedAt: message.timestamp, + ); + debugPrint( + '${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} emergency_stop存在=${dataObj.containsKey('emergency_stop')} 原始值=${dataObj['emergency_stop']} 急停解析值=${host.emergencyStop} 运动=${host.motion}', + ); _hostRealtimeController.add(host); } else if (message.topic.endsWith(_routeSuffix)) { _routeMsgCount++; @@ -256,11 +281,15 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource { debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 路径规划首帧到达: $sn'); } final routeMsg = RouteStatusEntity.fromJson(jsonData); - debugPrint('${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}'); + debugPrint( + '${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}', + ); _routeController.add(routeMsg); } } catch (e) { - debugPrint('${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败: $e'); + debugPrint( + '${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败 topic=${message.topic}: $e', + ); } } diff --git a/lib/core/network/mqtt/domain/entities/host_realtime_message_entity.dart b/lib/core/network/mqtt/domain/entities/host_realtime_message_entity.dart index 319e2a2d..4d462596 100644 --- a/lib/core/network/mqtt/domain/entities/host_realtime_message_entity.dart +++ b/lib/core/network/mqtt/domain/entities/host_realtime_message_entity.dart @@ -5,6 +5,8 @@ import 'package:equatable/equatable.dart'; /// 报文外层套一层信封,真正数据在 `data` 子对象(由 DataSource 提取后传入)。 /// 字段与后端 Java 实体一一对应,采用防御式解析,缺字段用默认值兜底。 class HostRealtimeMessageEntity extends Equatable { + final String? deviceSn; + final DateTime? receivedAt; final double batteryPercentage; // 实时电量百分比 final double batteryVoltage; // 实时电压 final double leftMotorCurrent; // 实时左电机电流 @@ -19,7 +21,7 @@ class HostRealtimeMessageEntity extends Equatable { final double totalWorkDuration; // 累计作业时长 final double totalWorkDistance; // 累计作业里程 final String motion; // moving|stopped|blocked 运动状态 - final bool emergencyStop; // 急停状态 + final bool? emergencyStop; // 急停状态;null 表示未上报或值无效 final double leftTargetRpm; // 实时左电机目标转速 final double rightTargetRpm; // 实时右电机目标转速 final double leftMeasuredRpm; // 实时左电机测量转速 @@ -35,6 +37,8 @@ class HostRealtimeMessageEntity extends Equatable { final Map rawData; const HostRealtimeMessageEntity({ + this.deviceSn, + this.receivedAt, this.batteryPercentage = 0, this.batteryVoltage = 0, this.leftMotorCurrent = 0, @@ -49,7 +53,7 @@ class HostRealtimeMessageEntity extends Equatable { this.totalWorkDuration = 0, this.totalWorkDistance = 0, this.motion = '', - this.emergencyStop = false, + this.emergencyStop, this.leftTargetRpm = 0, this.rightTargetRpm = 0, this.leftMeasuredRpm = 0, @@ -64,9 +68,16 @@ class HostRealtimeMessageEntity extends Equatable { }); /// [data] 为报文 `data` 子对象(由 DataSource 提取,与 MowerLocationEntity 一致) - factory HostRealtimeMessageEntity.fromJson(Map data) { + factory HostRealtimeMessageEntity.fromJson( + Map data, { + String? deviceSn, + DateTime? receivedAt, + }) { return HostRealtimeMessageEntity( - batteryPercentage: parseBatteryPercentage(data['battery_percentage']) ?? 0, + deviceSn: deviceSn, + receivedAt: receivedAt, + batteryPercentage: + parseBatteryPercentage(data['battery_percentage']) ?? 0, batteryVoltage: _toDouble(data['battery_voltage']), leftMotorCurrent: _toDouble(data['left_motor_current']), rightMotorCurrent: _toDouble(data['right_motor_current']), @@ -115,40 +126,43 @@ class HostRealtimeMessageEntity extends Equatable { return double.tryParse(value.toString()) ?? 0; } - static bool _toBool(dynamic value) { - if (value == null) return false; + static bool? _toBool(dynamic value) { if (value is bool) return value; - if (value is num) return value != 0; - final s = value.toString().toLowerCase(); - return s == 'true' || s == '1'; + if (value == 1) return true; + if (value == 0) return false; + final s = value?.toString().trim().toLowerCase(); + if (s == 'true' || s == '1') return true; + if (s == 'false' || s == '0') return false; + return null; } @override List get props => [ - batteryPercentage, - batteryVoltage, - leftMotorCurrent, - rightMotorCurrent, - leftMotorTemperature, - rightMotorTemperature, - mainTemperature, - yaw, - pitch, - headingStatus, - totalWorkArea, - totalWorkDuration, - totalWorkDistance, - motion, - emergencyStop, - leftTargetRpm, - rightTargetRpm, - leftMeasuredRpm, - rightMeasuredRpm, - leftMotorRpm, - rightMotorRpm, - roll, - controlMode, - linearSpeed, - angularSpeed, - ]; + batteryPercentage, + batteryVoltage, + leftMotorCurrent, + rightMotorCurrent, + leftMotorTemperature, + rightMotorTemperature, + mainTemperature, + yaw, + pitch, + headingStatus, + totalWorkArea, + totalWorkDuration, + totalWorkDistance, + motion, + emergencyStop, + leftTargetRpm, + rightTargetRpm, + leftMeasuredRpm, + rightMeasuredRpm, + leftMotorRpm, + rightMotorRpm, + roll, + controlMode, + linearSpeed, + angularSpeed, + rawData, + ]; } diff --git a/lib/core/network/mqtt/domain/entities/real_time_message_entity.dart b/lib/core/network/mqtt/domain/entities/real_time_message_entity.dart index 62583fd2..0541867b 100644 --- a/lib/core/network/mqtt/domain/entities/real_time_message_entity.dart +++ b/lib/core/network/mqtt/domain/entities/real_time_message_entity.dart @@ -51,7 +51,7 @@ class DeviceDataPoint extends Equatable { factory DeviceDataPoint.fromJson(Map json) { return DeviceDataPoint( name: json['name'] as String? ?? '', - value: json['value'] as String? ?? '', + value: json['value']?.toString() ?? '', unit: json['unit'] as String? ?? '', ); } diff --git a/lib/core/network/tcp/control_frame_scheduler.dart b/lib/core/network/tcp/control_frame_scheduler.dart new file mode 100644 index 00000000..4500498a --- /dev/null +++ b/lib/core/network/tcp/control_frame_scheduler.dart @@ -0,0 +1,97 @@ +import 'dart:async'; + +/// One shared 0x00 sender. There is no FIFO of old movement commands: only +/// the latest normal command and one priority stop/emergency may be pending. +class ControlFrameScheduler { + ControlFrameScheduler({int Function()? nowUs}) : _nowUs = nowUs { + _clock.start(); + } + + /// Shared interval for both the control loop and the transport gate. + static const interval = Duration(milliseconds: 250); + final Stopwatch _clock = Stopwatch(); + final int Function()? _nowUs; + Timer? _timer; + _ControlWrite? _priority; + _ControlWrite? _latest; + int? _lastCompletedUs; + bool _writing = false; + + int get _now => _nowUs?.call() ?? _clock.elapsedMicroseconds; + + Future submit( + Future Function() write, { + required bool priority, + required bool Function() isCurrent, + }) { + // Preserve each request's diagnostic Zone even when a later request replaces + // the one that originally scheduled the timer. + final job = _ControlWrite(Zone.current.bindCallback(write), isCurrent); + if (priority) { + _latest?.complete(false); + _latest = null; + _priority?.complete(false); + _priority = job; + } else { + _latest?.complete(false); + _latest = job; + } + _pump(); + return job.result.future; + } + + void _pump() { + if (_writing || _timer != null) return; + final job = _priority ?? _latest; + if (job == null) return; + if (!job.isCurrent()) { + _remove(job); + job.complete(false); + _pump(); + return; + } + final remaining = _lastCompletedUs == null + ? 0 + : interval.inMicroseconds - (_now - _lastCompletedUs!); + if (remaining > 0) { + _timer = Timer(Duration(microseconds: remaining), () { + _timer = null; + _pump(); // Recheck the monotonic clock; never send an early timer tick. + }); + return; + } + _remove(job); + _writing = true; + unawaited(_write(job)); + } + + void _remove(_ControlWrite job) { + if (identical(_priority, job)) _priority = null; + if (identical(_latest, job)) _latest = null; + } + + Future _write(_ControlWrite job) async { + try { + job.complete(job.isCurrent() ? await job.write() : false); + } catch (_) { + job.complete(false); + } finally { + // Measuring after local flush completion is conservative: actual socket + // additions are at least one interval apart, including priority frames. + _lastCompletedUs = _now; + _writing = false; + _pump(); + } + } +} + +class _ControlWrite { + _ControlWrite(this.write, this.isCurrent); + final Future Function() write; + final bool Function() isCurrent; + final Completer result = Completer(); + + void complete(bool value) { + if (!result.isCompleted) result.complete(value); + } +} diff --git a/lib/core/network/tcp/tcp_client.dart b/lib/core/network/tcp/tcp_client.dart index dc95ae8a..470d4438 100644 --- a/lib/core/network/tcp/tcp_client.dart +++ b/lib/core/network/tcp/tcp_client.dart @@ -16,12 +16,57 @@ import '../../../features/devices/domain/entities/running_status_entity.dart'; import '../../../features/devices/domain/usecases/get_user_device_usecase.dart'; import '../../../features/devices/domain/usecases/switch_device_usecase.dart'; import '../../logging/i_logger_service.dart'; +import '../../logging/control_permission_diagnostics.dart'; +import '../../logging/remote_control_diagnostics.dart'; import '../../storage/user_storage.dart'; import '../protocol_decoder.dart'; import 'tcp_status_cubit.dart'; +import 'control_frame_scheduler.dart'; class TcpClient { Socket? _socket; + int _diagnosticPendingFlushes = 0; + int? _diagnosticLastMotionAddUs; + final ControlFrameScheduler _controlFrames = ControlFrameScheduler(); + final Set> _pendingSocketFlushes = {}; + Future? _lastRawFlush; + + /// Observe completion without awaiting, delaying or changing any sender. + void _observeDiagnosticFlush( + Future pending, + int command, + int beganUs, + ) { + final trace = RemoteControlDiagnostics.instance; + final connection = _connectionId; + _pendingSocketFlushes.add(pending); + _diagnosticPendingFlushes++; + pending.then( + (_) { + _diagnosticPendingFlushes--; + _pendingSocketFlushes.remove(pending); + trace.event('socket_flush_complete', { + 'cmd': command, + 'connection': connection, + 'durationUs': trace.elapsedUs - beganUs, + 'pendingFlushes': _diagnosticPendingFlushes, + 'serverReceiptConfirmed': false, + }); + }, + onError: (Object error, StackTrace stack) { + _diagnosticPendingFlushes--; + _pendingSocketFlushes.remove(pending); + trace.event('socket_flush_error', { + 'cmd': command, + 'connection': connection, + 'durationUs': trace.elapsedUs - beganUs, + 'errorType': error.runtimeType.toString(), + 'error': error.toString(), + }); + }, + ); + } + final _decoder = ProtocolDecoder(); // 使用 StreamController 将原始数据流暴露给外部,以便多个 DataSource 监听 final _controller = StreamController.broadcast(); @@ -47,8 +92,10 @@ class TcpClient { static const int _maxReconnectFlaps = 5; // 🔥 最大允许连续成功-断开次数 /// 🔥 重连耗尽回调:连续4次重连失败(含心跳超时)后触发,通知上层弹窗提示用户 VoidCallback? onReconnectExhausted; + /// 🔥 重连开始回调:显示"TCP重连中"提示 VoidCallback? onReconnectStarted; + /// 🔥 重连成功回调:显示"连接成功"提示 VoidCallback? onReconnectSuccess; static const Duration _heartbeatTimeout = Duration(seconds: 15); // 心跳超时时间 @@ -57,18 +104,19 @@ class TcpClient { int? _lastPort; bool isUserSwitch = false; // 用户是否切换设备 bool _isSwitching = false; - bool _connecting = false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争) + bool _connecting = + false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争) Completer? _connectionCompleter; // 🔥 用于通知连接就绪 int _connectionId = 0; // 🔥 连接代数:每次新建连接递增,旧socket回调发现ID不匹配则忽略 - + // 🔥 关键标志:记录客户端最后一次发送 0x03 认证包的时间 // 用于区分"自身认证触发的 have_logged_in"和"真正的异地登录" // 如果 have_logged_in 在发送 0x03 后短时间内到达,说明是服务端残留 session 导致的 DateTime? _lastAuthPacketSentAt; - + /// 检查当前的 have_logged_in 是否是自身 0x03 认证触发的 /// 返回 true 表示应忽略(是服务端残留 session 导致的误报) - /// + /// /// 🔥 恢复:用于登录阶段判断是否为服务端残留 session 导致的误报 /// 判断逻辑: /// 1. 如果 TCP 已断开 (_socket == null) → 一定是真正的异地登录,返回 false @@ -80,26 +128,28 @@ class TcpClient { debugPrint('🔍 [TCP] TCP 已断开,判定为真正的异地登录'); return false; } - + final sentAt = _lastAuthPacketSentAt; if (sentAt == null) { debugPrint('🔍 [TCP] 无认证时间戳,判定为真正的异地登录'); return false; } - + final elapsed = DateTime.now().difference(sentAt); // 🔥 缩短时间窗口到 2 秒,只过滤刚发送 0x03 时的误报 final isRecent = elapsed.inSeconds < 2; - + if (isRecent) { - debugPrint('🔍 [TCP] 距离上次认证 ${elapsed.inMilliseconds}ms (<2s),判定为自身认证触发(服务端残留 session)'); + debugPrint( + '🔍 [TCP] 距离上次认证 ${elapsed.inMilliseconds}ms (<2s),判定为自身认证触发(服务端残留 session)', + ); } else { debugPrint('🔍 [TCP] 距离上次认证 ${elapsed.inSeconds}s (>=2s),判定为真正的异地登录'); } - + return isRecent; } - + /// 清除认证时间戳(在真正的异地登录时调用) void clearAuthTimestamp() { _lastAuthPacketSentAt = null; @@ -139,18 +189,18 @@ class TcpClient { void forceDisconnect() { _logger.logWithLevel('🛑 [TCP] 强制断开并清除重连能力', shouldLog: true); _connectionId++; // 🔥 使旧socket回调失效 - + // 1. 停止心跳 stopHeartbeat(); - + // 2. 取消重连定时器 _reconnectTimer?.cancel(); _reconnectTimer = null; - + // 3. 清除 Host/Port,防止重连 _lastHost = null; _lastPort = null; - + // 4. 重置标志 isUserSwitch = false; _isSwitching = false; @@ -160,21 +210,21 @@ class TcpClient { _reconnectAttempt = 0; // 🔥 重置重连退避 _reconnectFailCount = 0; // 🔥 重置重连失败计数 _reconnectFlapCount = 0; // 🔥 重置连上又断计数 - + // 5. 销毁 Socket if (_socket != null) { _socket!.destroy(); _socket = null; _logger.logWithLevel('✅ [TCP] Socket 已物理销毁', shouldLog: true); } - + // 6. 更新状态 try { GetIt.I().setDisconnected(); } catch (e) { _logger.logWithLevel('❌ [TCP] TcpStatusCubit 未注册', shouldLog: false); } - + _logger.logWithLevel('✅ [TCP] 已彻底断开,下次登录需重新初始化', shouldLog: true); } @@ -189,27 +239,27 @@ class TcpClient { _lastPort = port; return; } - + // 🔥 关键修复:如果用户正在切换设备(connectBySwitch),不干扰 if (isUserSwitch) { debugPrint('✅ [TCP-connect] 用户正在切换设备,跳过 connect()'); _logger.logWithLevel('✅ [TCP-connect] 用户正在切换设备,跳过', shouldLog: true); return; } - + // 🔥 关键修复:如果已有连接正在进行中,不创建新连接 if (_connecting) { debugPrint('✅ [TCP-connect] 已有连接正在进行中,跳过'); _logger.logWithLevel('✅ [TCP-connect] 已有连接正在进行中,跳过', shouldLog: true); return; } - + _connecting = true; _connectionCompleter = Completer(); _connectionId++; // 🔥 新一代连接,旧socket的回调将自动失效 final myConnId = _connectionId; debugPrint('🔌 [TCP-connect] 设置 _connecting=true, connectionId=$myConnId'); - + _logger.logWithLevel('🔌 [TCP] 开始连接:$host:$port', shouldLog: true); // 更新连接状态为连接中 @@ -278,12 +328,19 @@ class TcpClient { // 必须在 _controller.add 之前检查,否则 AuthCubit 会判定为异地登录弹出退出弹窗 if (packet.command == 0x12 && wasReconnecting) { try { - final payloadStr = utf8.decode(packet.payload.length > 2 - ? packet.payload.sublist(0, packet.payload.length - 2) - : packet.payload); + final payloadStr = utf8.decode( + packet.payload.length > 2 + ? packet.payload.sublist(0, packet.payload.length - 2) + : packet.payload, + ); if (payloadStr.contains('have_logged_in')) { - debugPrint('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session'); - _logger.logWithLevel('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连', shouldLog: true); + debugPrint( + '🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session', + ); + _logger.logWithLevel( + '🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连', + shouldLog: true, + ); _handleReconnectSessionReset(myConnId); return; // 停止处理后续数据,不分发给任何监听器 } @@ -325,8 +382,13 @@ class TcpClient { onDone: () { // 🔥 关键修复:检查 connectionId,防止旧socket的回调污染新连接 if (myConnId != _connectionId) { - debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略'); - _logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true); + debugPrint( + '⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略', + ); + _logger.logWithLevel( + '⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', + shouldLog: true, + ); return; } if (!_isSwitching) { @@ -337,7 +399,9 @@ class TcpClient { }, onError: (e) { if (myConnId != _connectionId) { - debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略'); + debugPrint( + '⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略', + ); return; } _logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true); @@ -385,7 +449,10 @@ class TcpClient { void _handleDisconnect() { _connectionId++; // 🔥 使旧socket的所有回调立即失效,防止onDone/onError污染新连接 debugPrint('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId'); - _logger.logWithLevel('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId', shouldLog: true); + _logger.logWithLevel( + '🔌 [TCP] _handleDisconnect, connectionId→$_connectionId', + shouldLog: true, + ); stopHeartbeat(); _socket = null; @@ -394,7 +461,10 @@ class TcpClient { debugPrint('📊 [TCP] 连接断开次数: $_reconnectFlapCount/$_maxReconnectFlaps'); if (_reconnectFlapCount >= _maxReconnectFlaps) { debugPrint('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连,通知用户退出登录'); - _logger.logWithLevel('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连', shouldLog: true); + _logger.logWithLevel( + '🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连', + shouldLog: true, + ); onReconnectExhausted?.call(); return; } @@ -416,7 +486,10 @@ class TcpClient { // 🔥 限制总重连次数,防止网络不可达时无限重连 if (_reconnectAttempt >= _maxReconnectAttempts) { debugPrint('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连,通知用户退出登录'); - _logger.logWithLevel('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连', shouldLog: true); + _logger.logWithLevel( + '🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连', + shouldLog: true, + ); onReconnectExhausted?.call(); return; } @@ -424,7 +497,9 @@ class TcpClient { // 🔥 重连退避:5s → 10s → 20s → 30s(max) final delay = [5, 10, 20, 30][_reconnectAttempt.clamp(0, 3)]; _reconnectAttempt++; - _logger.logWithLevel('⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}'); + _logger.logWithLevel( + '⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}', + ); if (_lastHost == null || _lastPort == null) { _logger.logWithLevel('❌ 无法重连:Host 或 Port 为空!', shouldLog: true); return; @@ -446,32 +521,54 @@ class TcpClient { // 🔥 显示"TCP重连中"提示 onReconnectStarted?.call(); final reconnectStart = DateTime.now(); - final timeStr = '${reconnectStart.hour.toString().padLeft(2,'0')}:${reconnectStart.minute.toString().padLeft(2,'0')}:${reconnectStart.second.toString().padLeft(2,'0')}.${reconnectStart.millisecond.toString().padLeft(3,'0')}'; + final timeStr = + '${reconnectStart.hour.toString().padLeft(2, '0')}:${reconnectStart.minute.toString().padLeft(2, '0')}:${reconnectStart.second.toString().padLeft(2, '0')}.${reconnectStart.millisecond.toString().padLeft(3, '0')}'; debugPrint('⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)'); - _logger.logWithLevel('⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)', shouldLog: true); + _logger.logWithLevel( + '⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)', + shouldLog: true, + ); try { await connect(host: _lastHost!, port: _lastPort!); final connectDone = DateTime.now(); final connectMs = connectDone.difference(reconnectStart).inMilliseconds; - debugPrint('✅ [TCP-重连] ${connectDone.hour.toString().padLeft(2,'0')}:${connectDone.minute.toString().padLeft(2,'0')}:${connectDone.second.toString().padLeft(2,'0')}.${connectDone.millisecond.toString().padLeft(3,'0')} connect() 完成,耗时 ${connectMs}ms'); + debugPrint( + '✅ [TCP-重连] ${connectDone.hour.toString().padLeft(2, '0')}:${connectDone.minute.toString().padLeft(2, '0')}:${connectDone.second.toString().padLeft(2, '0')}.${connectDone.millisecond.toString().padLeft(3, '0')} connect() 完成,耗时 ${connectMs}ms', + ); _reconnectAttempt = 0; // 🔥 重连成功,重置退避计数 // 🔥 关键修复:等待5秒再调 HTTP switchDevice,给服务端时间完成相关操作 final delayStart = DateTime.now(); - debugPrint('⏳ [TCP-重连] ${delayStart.hour.toString().padLeft(2,'0')}:${delayStart.minute.toString().padLeft(2,'0')}:${delayStart.second.toString().padLeft(2,'0')}.${delayStart.millisecond.toString().padLeft(3,'0')} 开始等待5秒...'); + debugPrint( + '⏳ [TCP-重连] ${delayStart.hour.toString().padLeft(2, '0')}:${delayStart.minute.toString().padLeft(2, '0')}:${delayStart.second.toString().padLeft(2, '0')}.${delayStart.millisecond.toString().padLeft(3, '0')} 开始等待5秒...', + ); await Future.delayed(const Duration(milliseconds: 5000)); final afterDelay = DateTime.now(); final actualDelayMs = afterDelay.difference(delayStart).inMilliseconds; - debugPrint('⏳ [TCP-重连] ${afterDelay.hour.toString().padLeft(2,'0')}:${afterDelay.minute.toString().padLeft(2,'0')}:${afterDelay.second.toString().padLeft(2,'0')}.${afterDelay.millisecond.toString().padLeft(3,'0')} 等待结束,实际耗时 ${actualDelayMs}ms,开始调 HTTP switchDevice'); + debugPrint( + '⏳ [TCP-重连] ${afterDelay.hour.toString().padLeft(2, '0')}:${afterDelay.minute.toString().padLeft(2, '0')}:${afterDelay.second.toString().padLeft(2, '0')}.${afterDelay.millisecond.toString().padLeft(3, '0')} 等待结束,实际耗时 ${actualDelayMs}ms,开始调 HTTP switchDevice', + ); try { final remoteControlCubit = GetIt.I(); final targetDevice = remoteControlCubit.state.targetDevice; if (targetDevice != null) { - debugPrint('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}'); - _logger.logWithLevel('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}', shouldLog: true); - await switchDeviceUseCase.deviceRepository.switchDevice('app', targetDevice.deviceName); + debugPrint( + '🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}', + ); + _logger.logWithLevel( + '🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}', + shouldLog: true, + ); + await switchDeviceUseCase.deviceRepository.switchDevice( + 'app', + targetDevice.deviceName, + ); final switchDone = DateTime.now(); - final totalMs = switchDone.difference(reconnectStart).inMilliseconds; - debugPrint('✅ [TCP-重连] ${switchDone.hour.toString().padLeft(2,'0')}:${switchDone.minute.toString().padLeft(2,'0')}:${switchDone.second.toString().padLeft(2,'0')}.${switchDone.millisecond.toString().padLeft(3,'0')} HTTP switchDevice 成功,重连总耗时 ${totalMs}ms'); + final totalMs = switchDone + .difference(reconnectStart) + .inMilliseconds; + debugPrint( + '✅ [TCP-重连] ${switchDone.hour.toString().padLeft(2, '0')}:${switchDone.minute.toString().padLeft(2, '0')}:${switchDone.second.toString().padLeft(2, '0')}.${switchDone.millisecond.toString().padLeft(3, '0')} HTTP switchDevice 成功,重连总耗时 ${totalMs}ms', + ); } else { debugPrint('⚠️ [TCP-重连] targetDevice 为 null,跳过 switchDevice'); } @@ -479,7 +576,10 @@ class TcpClient { onReconnectSuccess?.call(); } catch (e) { debugPrint('❌ [TCP-重连] HTTP switchDevice 失败: $e'); - _logger.logWithLevel('❌ [TCP-重连] HTTP switchDevice 失败: $e', shouldLog: true); + _logger.logWithLevel( + '❌ [TCP-重连] HTTP switchDevice 失败: $e', + shouldLog: true, + ); } } catch (e) { debugPrint('❌ [TCP-重连] connect 失败: $e'); @@ -506,33 +606,42 @@ class TcpClient { return; } _logger.logWithLevel('⏰ 被动-定时器触发,开始执行重连...', shouldLog: true); - + // 🔥 修复:重连时使用 RemoteControlCubit.targetDevice,而不是记住的设备名 try { final remoteControlCubit = GetIt.I(); final targetDevice = remoteControlCubit.state.targetDevice; - + if (targetDevice != null) { - _logger.logWithLevel('🔄 [TCP] 重连使用 targetDevice: ${targetDevice.deviceName}', shouldLog: true); + _logger.logWithLevel( + '🔄 [TCP] 重连使用 targetDevice: ${targetDevice.deviceName}', + shouldLog: true, + ); connectBySwitch( - host: _lastHost!, - port: _lastPort!, + host: _lastHost!, + port: _lastPort!, deviceName: targetDevice.deviceName, ); } else { // 如果 targetDevice 为 null,使用传入的设备名作为兜底 - _logger.logWithLevel('⚠️ [TCP] targetDevice 为 null,使用传入的设备名: $devname', shouldLog: true); + _logger.logWithLevel( + '⚠️ [TCP] targetDevice 为 null,使用传入的设备名: $devname', + shouldLog: true, + ); connectBySwitch( - host: _lastHost!, - port: _lastPort!, + host: _lastHost!, + port: _lastPort!, deviceName: devname, ); } } catch (e) { - _logger.logWithLevel('❌ [TCP] 获取 targetDevice 失败,使用传入的设备名: $devname, 错误: $e', shouldLog: true); + _logger.logWithLevel( + '❌ [TCP] 获取 targetDevice 失败,使用传入的设备名: $devname, 错误: $e', + shouldLog: true, + ); connectBySwitch( - host: _lastHost!, - port: _lastPort!, + host: _lastHost!, + port: _lastPort!, deviceName: devname, ); } @@ -549,10 +658,111 @@ class TcpClient { _socket!.add(data); } - /// 🔥 断线丢帧日志节流时间戳:控制循环每 200ms 就会撞一次「未连接」, + /// Permission requests need an awaited write result. Other send paths stay intact. + /// Completion confirms local socket flushing, not server/Web receipt. + Future sendPermissionPacket(List packet) async { + final clock = Stopwatch()..start(); + final socket = _socket; + final connection = _connectionId; + var operation = 'wait_flush'; + var addAccepted = false; + ControlPermissionDiagnostics.event('socket权限写入开始', { + 'connection': connection, + 'connected': socket != null, + 'pendingFlushes': _pendingSocketFlushes.length, + 'packetBytes': packet.length, + }); + try { + if (socket == null) throw const SocketException('TCP not connected'); + await _waitForSocketFlushes(); + if (!identical(socket, _socket)) + throw const SocketException('TCP changed'); + operation = 'add'; + socket.add(packet); + addAccepted = true; + ControlPermissionDiagnostics.event('socket权限add完成', { + 'connection': connection, + 'waitMs': clock.elapsedMilliseconds, + 'serverReceiptConfirmed': false, + }); + final trace = RemoteControlDiagnostics.instance; + final beganUs = trace.elapsedUs; + operation = 'flush'; + final pending = socket.flush(); + _observeDiagnosticFlush(pending, 0x12, beganUs); + await pending; + if (!identical(socket, _socket)) { + throw const SocketException( + 'TCP connection changed during permission send', + ); + } + ControlPermissionDiagnostics.event('socket权限flush完成', { + 'connection': connection, + 'durationMs': clock.elapsedMilliseconds, + 'serverReceiptConfirmed': false, + }); + } catch (e) { + ControlPermissionDiagnostics.event('socket权限写入失败', { + 'connection': connection, + 'operation': operation, + 'addAccepted': addAccepted, + 'errorType': e.runtimeType.toString(), + 'durationMs': clock.elapsedMilliseconds, + }); + rethrow; + } + } + + /// 🔥 断线丢帧日志节流时间戳:控制循环每 250ms 就会撞一次「未连接」, /// 全量打印会淹掉日志文件,故 5 秒内只记一次(丢帧本身仍如实返回 false)。 DateTime? _lastSendDropLogAt; + Future _waitForSocketFlushes() async { + while (_pendingSocketFlushes.isNotEmpty) { + await Future.wait( + _pendingSocketFlushes.toList().map((pending) async { + try { + await pending; + } catch (_) {} + }), + ); + } + } + + /// The sole supported 0x00 path: newest movement, priority stop, >=250ms. + Future sendControlPayload( + List payload, { + bool priority = false, + bool Function()? isCurrent, + }) { + final socket = _socket; + final connection = _connectionId; + final bytes = List.of(payload); + bool current() => + socket != null && + identical(socket, _socket) && + connection == _connectionId && + (isCurrent?.call() ?? true); + return _controlFrames.submit( + () async { + await _waitForSocketFlushes(); + if (!current()) return false; + final accepted = _sendRawNow(0x00, bytes); + if (!accepted) return false; + final pending = _lastRawFlush; + if (pending == null) return false; + try { + await pending; + return current(); + } catch (_) { + return false; + } + }, + priority: priority, + isCurrent: current, + ); + } + /// 把一帧协议数据写入 socket。 /// /// 返回 `false` = 这一帧**根本没交给系统 socket**(未连接,或写入抛异常)。 @@ -561,7 +771,26 @@ class TcpClient { /// 而代码以为「已发送」——设备只保留了断开前最后一帧运动指令,正是 /// 「松手了车还在走」的一条隐藏通路。现在必须由调用方判断结果自行兜底。 bool sendRaw(int cmd, List payload) { + if (cmd == 0x00) { + // Legacy callers may not bypass the common motion gate. + unawaited(sendControlPayload(payload)); + return false; // Deferred requests must not claim a synchronous write. + } + return _sendRawNow(cmd, payload); + } + + bool _sendRawNow(int cmd, List payload) { + final trace = RemoteControlDiagnostics.instance; + final beganUs = trace.elapsedUs; + trace.event('socket_write_attempt', { + 'cmd': cmd, + 'connection': _connectionId, + 'connected': _socket != null, + 'pendingFlushes': _diagnosticPendingFlushes, + 'payloadBytes': payload.length, + }); if (_socket == null) { + trace.event('socket_not_connected', {'cmd': cmd, 'addAccepted': false}); final now = DateTime.now(); if (_lastSendDropLogAt == null || now.difference(_lastSendDropLogAt!) >= const Duration(seconds: 5)) { @@ -586,10 +815,30 @@ class TcpClient { ..addByte(0xAB); final packet = builder.takeBytes(); + var operation = 'add'; + var addAccepted = false; try { _socket!.add(packet); + addAccepted = true; + final addedUs = trace.elapsedUs; + trace.event('socket_add_accepted', { + 'cmd': cmd, + 'connection': _connectionId, + 'addAccepted': true, + 'addGapUs': cmd == 0x00 && _diagnosticLastMotionAddUs != null + ? addedUs - _diagnosticLastMotionAddUs! + : null, + 'pendingFlushes': _diagnosticPendingFlushes, + 'frameBytes': packet.length, + 'frameHex': _hex(packet), + 'serverReceiptConfirmed': false, + }); + if (cmd == 0x00) _diagnosticLastMotionAddUs = addedUs; // 🔥 关键修复:强制flush,确保数据立即发送 - _socket!.flush(); + operation = 'flush'; + final pending = _socket!.flush(); + _lastRawFlush = pending; + _observeDiagnosticFlush(pending, cmd, beganUs); // 联调日志:移到 add+flush 之后打印,证明这帧已真正交给系统 socket 发送缓冲 // ("发出去之后"才有参考价值;仍非后端 ACK,仅代表 App 侧写入成功)(联调结束可移除) _logger.logWithLevel( @@ -599,6 +848,15 @@ class TcpClient { ); return true; } catch (e) { + trace.event('socket_write_error', { + 'cmd': cmd, + 'connection': _connectionId, + 'operation': operation, + 'addAccepted': addAccepted, + 'pendingFlushes': _diagnosticPendingFlushes, + 'errorType': e.runtimeType.toString(), + 'error': e.toString(), + }); _logger.logWithLevel( '🔗 [联调-TCP] sendRaw ❌写入socket失败 cmd=0x${cmd.toRadixString(16).padLeft(2, '0')} err=$e', level: 'ERROR', @@ -621,7 +879,7 @@ class TcpClient { ..addByte(0xAA) ..addByte(0xAB); _socket!.add(builder.takeBytes()); - debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB'); + // debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB'); } /// 启动心跳:主动定时发送 + 超时检测 @@ -630,7 +888,10 @@ class TcpClient { void startHeartbeat({Duration interval = const Duration(seconds: 4)}) { if (_heartbeatTimer != null) return; // 防止重复启动 debugPrint('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)'); - _logger.logWithLevel('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)', shouldLog: true); + _logger.logWithLevel( + '⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)', + shouldLog: true, + ); // 🔥 主动定时发送心跳给服务端(每5秒) _heartbeatSendTimer?.cancel(); @@ -650,7 +911,9 @@ class TcpClient { final wasRunning = _heartbeatTimer != null; _heartbeatTimer?.cancel(); _heartbeatTimer = Timer(_heartbeatTimeout, () { - debugPrint('⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开'); + debugPrint( + '⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开', + ); _logger.logWithLevel('⚠️ [TCP] 心跳超时,判定连接断开', shouldLog: true); // 触发断开重连 if (_socket != null) { @@ -685,12 +948,12 @@ class TcpClient { _logger.logWithLevel('✅ [TCP] 正在连接中,跳过', shouldLog: true); return; } - + _connecting = true; _connectionCompleter = Completer(); _connectionId++; // 🔥 新一代连接,旧socket回调自动失效 final myConnId = _connectionId; - + try { // 更新状态为连接中 try { @@ -698,12 +961,12 @@ class TcpClient { } catch (e) { _logger.logWithLevel('❌ [TCP] TcpStatusCubit 未注册', shouldLog: false); } - + // 执行连接 _logger.logWithLevel('🔌 [TCP] 开始初始化连接:$host:$port', shouldLog: true); _lastHost = host; _lastPort = port; - + _socket = await Socket.connect( host, port, @@ -711,30 +974,30 @@ class TcpClient { ); _socket!.setOption(SocketOption.tcpNoDelay, true); _logger.logWithLevel('✅ [TCP] Socket 连接成功', shouldLog: true); - + // 更新状态为已连接 try { GetIt.I().setConnected(); } catch (e) { _logger.logWithLevel('❌ [TCP] TcpStatusCubit 未注册', shouldLog: false); } - + // 发送认证包 await _sendAuthPacket(); _logger.logWithLevel('✅ [TCP] 认证包已发送', shouldLog: true); - + // 启动心跳 startHeartbeat(); _logger.logWithLevel('✅ [TCP] 心跳已启动', shouldLog: true); - + // 设置数据监听(复用现有的监听逻辑) _setupDataListener(myConnId); - + _connecting = false; if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) { _connectionCompleter!.complete(); } - + _logger.logWithLevel('🎉 [TCP] TCP 初始化完成!', shouldLog: true); } catch (e) { _connecting = false; @@ -759,7 +1022,9 @@ class TcpClient { var packets = _decoder.decode(data); for (var packet in packets) { // 🔥 最根部日志:收到任何推送都打印 - debugPrint('📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}'); + debugPrint( + '📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}', + ); _logger.logWithLevel( '📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}', shouldLog: true, @@ -791,7 +1056,10 @@ class TcpClient { // 🔥 检查 connectionId,防止旧socket回调污染新连接 if (myConnId != _connectionId) { debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略'); - _logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true); + _logger.logWithLevel( + '⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', + shouldLog: true, + ); return; } if (!_isSwitching) { @@ -802,7 +1070,9 @@ class TcpClient { }, onError: (e) { if (myConnId != _connectionId) { - debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略'); + debugPrint( + '⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略', + ); return; } _logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true); @@ -936,14 +1206,16 @@ class TcpClient { username = user.username; token = user.token; final authString = '$username:app:$token'; - + // 🔥 关键日志:打印认证字符串,方便核对 Token debugPrint('🔑 [TCP] 正在发送认证包 (0x03)'); debugPrint(' - Username: $username'); - debugPrint(' - Token: ${token?.substring(0, token!.length > 10 ? 10 : token!.length)}...'); // 只打印前10位保护隐私 + debugPrint( + ' - Token: ${token?.substring(0, token!.length > 10 ? 10 : token!.length)}...', + ); // 只打印前10位保护隐私 debugPrint(' - Full Auth String: $authString'); _logger.logWithLevel('🔑 [TCP] 认证字符串: $authString', shouldLog: true); - + final authBytes = utf8.encode(authString); // 构造包结构:Head(2) + Cmd(1) + Payload(N) + CRC(2) + Foot(2) @@ -1036,52 +1308,77 @@ class TcpClient { required String deviceName, }) async { debugPrint('🔌 [TCP-connectBySwitch] ========== 开始连接 =========='); - debugPrint('🔌 [TCP-connectBySwitch] Host: $host, Port: $port, Device: $deviceName'); - + debugPrint( + '🔌 [TCP-connectBySwitch] Host: $host, Port: $port, Device: $deviceName', + ); + // 🔥 关键:取消之前的重连定时器,防止连接冲突 _reconnectTimer?.cancel(); _reconnectTimer = null; debugPrint('✅ [TCP-connectBySwitch] 已取消旧的重连定时器'); - + // 🔥 关键修复:如果已有连接正在进行中,等待连接就绪后只调 HTTP switchDevice if (_connecting) { debugPrint('✅ [TCP-connectBySwitch] 检测到 connect() 正在进行中,等待连接就绪...'); - _logger.logWithLevel('✅ [TCP-connectBySwitch] 连接进行中,等待后只做HTTP切换', shouldLog: true); + _logger.logWithLevel( + '✅ [TCP-connectBySwitch] 连接进行中,等待后只做HTTP切换', + shouldLog: true, + ); try { - if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) { - await _connectionCompleter!.future.timeout(const Duration(seconds: 10)); + if (_connectionCompleter != null && + !_connectionCompleter!.isCompleted) { + await _connectionCompleter!.future.timeout( + const Duration(seconds: 10), + ); } // 连接就绪,只做 HTTP switchDevice,不创建新 TCP 连接 - await switchDeviceUseCase.deviceRepository.switchDevice("app", deviceName); + await switchDeviceUseCase.deviceRepository.switchDevice( + "app", + deviceName, + ); debugPrint('✅ [TCP-connectBySwitch] 等待连接就绪后HTTP切换成功: $deviceName'); } catch (e) { debugPrint('❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e'); - _logger.logWithLevel('❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e', shouldLog: true); + _logger.logWithLevel( + '❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e', + shouldLog: true, + ); } return; } - + // 🔥 核心优化:如果 TCP 已连接,复用现有连接,只调 HTTP switchDevice // 不再销毁重建,避免推送空窗期导致延迟 if (_socket != null) { - debugPrint('✅ [TCP-connectBySwitch] 已有连接,复用现有连接,只调 HTTP switchDevice: $deviceName'); - _logger.logWithLevel('✅ [TCP-connectBySwitch] 复用连接,HTTP切换设备: $deviceName', shouldLog: true); + debugPrint( + '✅ [TCP-connectBySwitch] 已有连接,复用现有连接,只调 HTTP switchDevice: $deviceName', + ); + _logger.logWithLevel( + '✅ [TCP-connectBySwitch] 复用连接,HTTP切换设备: $deviceName', + shouldLog: true, + ); try { - await switchDeviceUseCase.deviceRepository.switchDevice("app", deviceName); + await switchDeviceUseCase.deviceRepository.switchDevice( + "app", + deviceName, + ); debugPrint('✅ [TCP-connectBySwitch] HTTP切换成功: $deviceName'); } catch (e) { debugPrint('❌ [TCP-connectBySwitch] HTTP切换失败: $e'); - _logger.logWithLevel('❌ [TCP-connectBySwitch] HTTP切换失败: $e', shouldLog: true); + _logger.logWithLevel( + '❌ [TCP-connectBySwitch] HTTP切换失败: $e', + shouldLog: true, + ); } return; } - + isUserSwitch = true; _connecting = true; // 🔥 防止 connect() 并发创建新连接 _connectionId++; // 🔥 新一代连接,旧socket回调自动失效 final myConnId = _connectionId; debugPrint('🔌 [TCP-connectBySwitch] 无现有连接,开始新建, connectionId=$myConnId'); - + // debugPrint('🔌被动 [TCP] 开始连接:$host:$port'); // ✅ 必须看到这条 _logger.logWithLevel('🔌被动 [TCP] 开始连接:$host:$port'); _lastHost = host; @@ -1156,8 +1453,13 @@ class TcpClient { onDone: () { // 🔥 检查 connectionId,防止旧socket回调污染新连接 if (myConnId != _connectionId) { - debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略'); - _logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true); + debugPrint( + '⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略', + ); + _logger.logWithLevel( + '⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', + shouldLog: true, + ); return; } debugPrint('onDone [TCP] 被动连接已断开!_isSwitching=$_isSwitching'); @@ -1170,7 +1472,9 @@ class TcpClient { }, onError: (e) { if (myConnId != _connectionId) { - debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略'); + debugPrint( + '⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略', + ); return; } _logger.logWithLevel('❌ 被动[TCP] 发生错误:$e'); @@ -1189,7 +1493,7 @@ class TcpClient { _connecting = false; // 🔥 连接失败,重置标志 rethrow; // 向上抛出连接异常 } - + // 🔥 重置 _connecting 和 isUserSwitch _connecting = false; isUserSwitch = false; // 🔥 关键:切换完成后重置,后续超时走普通重连路径 @@ -1246,7 +1550,7 @@ class TcpClient { // 🔥 修复:使用 RemoteControlCubit.targetDevice,而不是传入的 deviceName final remoteControlCubit = GetIt.I(); final targetDevice = remoteControlCubit.state.targetDevice; - + if (targetDevice != null) { debugPrint('🔀 [TCP] 使用 targetDevice 进行切换: ${targetDevice.deviceName}'); await switchDeviceUseCase.deviceRepository.switchDevice( @@ -1255,7 +1559,9 @@ class TcpClient { ); } else { // 兜底:如果 targetDevice 为 null,使用传入的 deviceName - debugPrint('⚠️ [TCP] targetDevice 为 null,使用传入的 deviceName: $deviceName'); + debugPrint( + '⚠️ [TCP] targetDevice 为 null,使用传入的 deviceName: $deviceName', + ); await switchDeviceUseCase.deviceRepository.switchDevice( "app", deviceName, @@ -1270,8 +1576,13 @@ class TcpClient { void _handleDisconnectBySwitch(String deviceName) { _connectionId++; // 🔥 使旧socket的所有回调立即失效 - debugPrint('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId'); - _logger.logWithLevel('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId', shouldLog: true); + debugPrint( + '🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId', + ); + _logger.logWithLevel( + '🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId', + shouldLog: true, + ); stopHeartbeat(); _socket = null; diff --git a/lib/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart b/lib/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart index 7c46ea98..29bd4ead 100644 --- a/lib/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart +++ b/lib/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart @@ -7,6 +7,7 @@ import '../../../../core/localization/app_localizations.dart'; import '../../domain/entities/device_control_mode.dart'; import '../../domain/usecases/device_control_mode_usecases.dart'; import '../cubit/control_mode_entry_cubit.dart'; +import 'mode_independent_control.dart'; Future showControlModeEntryDialog( BuildContext context, { @@ -15,6 +16,7 @@ Future showControlModeEntryDialog( String? deviceName, bool allowTargetSelection = false, bool cancelToPreview = false, + Widget? emergencyStopControl, ControlModeEntryCubit? cubit, }) async { final entry = @@ -34,6 +36,7 @@ Future showControlModeEntryDialog( backgroundColor: Colors.transparent, barrierColor: const Color(0x8C0B1B2B), isScrollControlled: true, + constraints: const BoxConstraints(maxWidth: 440), isDismissible: false, enableDrag: false, builder: (_) => BlocProvider.value( @@ -42,6 +45,7 @@ Future showControlModeEntryDialog( deviceName: deviceName, allowTargetSelection: allowTargetSelection, cancelToPreview: cancelToPreview, + emergencyStopControl: emergencyStopControl, ), ), ) ?? @@ -61,6 +65,7 @@ class ControlModeEntryGate extends StatefulWidget { this.deviceName, this.onReady, this.cancelToPreview = false, + this.emergencyStopControl, }); final String deviceId; final String? deviceName; @@ -68,6 +73,9 @@ class ControlModeEntryGate extends StatefulWidget { final Widget child; final VoidCallback? onReady; final bool cancelToPreview; + + /// 独立急停链路,不受控制模式确认限制。 + final Widget? emergencyStopControl; @override State createState() => _ControlModeEntryGateState(); } @@ -93,6 +101,7 @@ class _ControlModeEntryGateState extends State { deviceName: widget.deviceName, target: widget.target, cancelToPreview: widget.cancelToPreview, + emergencyStopControl: widget.emergencyStopControl, ); if (!mounted) return; if (accepted) { @@ -115,7 +124,7 @@ class _ControlModeEntryGateState extends State { children: [ ExcludeFocus( excluding: !_ready, - child: IgnorePointer(ignoring: !_ready, child: widget.child), + child: ControlModePointerGate(blocked: !_ready, child: widget.child), ), if (_cancelled && widget.cancelToPreview) _buildPreviewControls(context) @@ -208,6 +217,7 @@ class _ControlModeEntryDialog extends StatelessWidget { this.deviceName, this.allowTargetSelection = false, this.cancelToPreview = false, + this.emergencyStopControl, }); static const _navy = Color(0xFF1A2B4A); @@ -220,6 +230,7 @@ class _ControlModeEntryDialog extends StatelessWidget { final String? deviceName; final bool allowTargetSelection; final bool cancelToPreview; + final Widget? emergencyStopControl; Widget _modeCard({ required String label, @@ -228,7 +239,7 @@ class _ControlModeEntryDialog extends StatelessWidget { bool target = false, }) { return Container( - padding: const EdgeInsets.all(14), + padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: target ? _softBlue : const Color(0xFFF6FAFE), borderRadius: BorderRadius.circular(14), @@ -237,15 +248,15 @@ class _ControlModeEntryDialog extends StatelessWidget { child: Row( children: [ Container( - width: 40, - height: 40, + width: 30, + height: 30, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(12), ), - child: Icon(icon, color: _blue, size: 21), + child: Icon(icon, color: _blue, size: 18), ), - const SizedBox(width: 12), + const SizedBox(width: 8), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -258,7 +269,7 @@ class _ControlModeEntryDialog extends StatelessWidget { Text( value, style: const TextStyle( - fontSize: 16, + fontSize: 14, fontWeight: FontWeight.w700, color: _navy, ), @@ -341,7 +352,7 @@ class _ControlModeEntryDialog extends StatelessWidget { child: SafeArea( top: false, child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(18, 16, 18, 16), + padding: const EdgeInsets.fromLTRB(16, 10, 16, 12), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -354,12 +365,14 @@ class _ControlModeEntryDialog extends StatelessWidget { allowTargetSelection ? 'switch_title' : 'title', ), style: const TextStyle( - fontSize: 20, + fontSize: 17, fontWeight: FontWeight.w800, color: _navy, ), ), ), + if (emergencyStopControl != null) + emergencyStopControl!, IconButton( tooltip: cancelToPreview ? cancelText @@ -392,27 +405,37 @@ class _ControlModeEntryDialog extends StatelessWidget { ), ), const SizedBox(height: 16), - _modeCard( - label: tr('current'), - value: controlModeDisplayText( - l10n, - state.reading?.rawMode, - ), - icon: Icons.sensors_rounded, - ), - const SizedBox(height: 10), - // 自主任务选项继续停用,由后端处理;这里展示本次确认的目标。 - _modeCard( - label: tr( - allowTargetSelection ? 'selection_target' : 'target', - ), - value: - allowTargetSelection && - cubit.target == ControlModeTarget.remote - ? tr('switch_manual') - : targetText, - icon: Icons.swap_horiz_rounded, - target: true, + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: _modeCard( + label: tr('current'), + value: controlModeDisplayText( + l10n, + state.reading?.rawMode, + ), + icon: Icons.sensors_rounded, + ), + ), + const SizedBox(width: 8), + Expanded( + child: _modeCard( + label: tr( + allowTargetSelection + ? 'selection_target' + : 'target', + ), + value: + allowTargetSelection && + cubit.target == ControlModeTarget.remote + ? tr('switch_manual') + : targetText, + icon: Icons.swap_horiz_rounded, + target: true, + ), + ), + ], ), const SizedBox(height: 12), Container( @@ -438,7 +461,9 @@ class _ControlModeEntryDialog extends StatelessWidget { const SizedBox(width: 8), Expanded( child: Text( - note, + cubit.target == ControlModeTarget.remote + ? '$note\n${tr('remote_retry_hint')}' + : note, style: const TextStyle( fontSize: 12, height: 1.5, @@ -478,7 +503,7 @@ class _ControlModeEntryDialog extends StatelessWidget { style: TextButton.styleFrom(foregroundColor: _blue), ), ), - const SizedBox(height: 18), + const SizedBox(height: 12), Row( children: [ Expanded( @@ -487,7 +512,7 @@ class _ControlModeEntryDialog extends StatelessWidget { icon: const Icon(Icons.close_rounded, size: 18), style: OutlinedButton.styleFrom( foregroundColor: _blue, - minimumSize: const Size.fromHeight(48), + minimumSize: const Size.fromHeight(40), side: BorderSide( color: canCancel ? _blue : _border, width: 1.2, @@ -516,7 +541,7 @@ class _ControlModeEntryDialog extends StatelessWidget { 0xFFDCEBFA, ), disabledForegroundColor: _gray, - minimumSize: const Size.fromHeight(48), + minimumSize: const Size.fromHeight(40), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), diff --git a/lib/features/device_control_mode/presentation/widgets/mode_independent_control.dart b/lib/features/device_control_mode/presentation/widgets/mode_independent_control.dart new file mode 100644 index 00000000..91ff5300 --- /dev/null +++ b/lib/features/device_control_mode/presentation/widgets/mode_independent_control.dart @@ -0,0 +1,63 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// 保持控件原位,标记独立于模式确认的操作区(如急停、页面设置)。 +class ModeIndependentControl extends SingleChildRenderObjectWidget { + const ModeIndependentControl({super.key, required super.child}); + + @override + RenderProxyBox createRenderObject(BuildContext context) => + _IndependentRegion(); +} + +class _IndependentRegion extends RenderProxyBox {} + +/// 模式未确认时,只将指针事件交给原布局中明确标记的独立操作区。 +class ControlModePointerGate extends SingleChildRenderObjectWidget { + const ControlModePointerGate({ + super.key, + required this.blocked, + required super.child, + }); + final bool blocked; + + @override + RenderProxyBox createRenderObject(BuildContext context) => + _PointerGate(blocked); + + @override + void updateRenderObject( + BuildContext context, + covariant _PointerGate renderObject, + ) { + renderObject.blocked = blocked; + } +} + +class _PointerGate extends RenderProxyBox { + _PointerGate(this.blocked); + bool blocked; + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + if (!blocked) return super.hitTestChildren(result, position: position); + var hit = false; + void visit(RenderObject node) { + if (hit) return; + if (node is _IndependentRegion && node.attached && node.hasSize) { + hit = result.addWithPaintTransform( + transform: node.getTransformTo(this), + position: position, + hitTest: (result, position) => + node.hitTest(result, position: position), + ); + return; + } + node.visitChildren(visit); + } + + final content = child; + if (content != null) visit(content); + return hit; + } +} diff --git a/lib/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart b/lib/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart new file mode 100644 index 00000000..fb88bcfc --- /dev/null +++ b/lib/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart @@ -0,0 +1,43 @@ +import 'package:dio/dio.dart'; + +import '../../../../core/consts/http_api_consts.dart'; +import '../../domain/entities/emergency_stop_target.dart'; + +class EmergencyStopRemoteDatasource { + const EmergencyStopRemoteDatasource(this.dio); + // 注入统一 Dio,沿用登录鉴权和测试/生产环境配置。 + final Dio dio; + + Future request(String deviceId, EmergencyStopTarget target) async { + final response = await dio.get( + HttpApiConsts.hostEmergencyStopChange, + queryParameters: {'deviceId': deviceId, 'eStop': target.value}, + options: Options( + receiveTimeout: const Duration(seconds: 10), + headers: {'Cache-Control': 'no-store', 'Pragma': 'no-cache'}, + ), + ); + final body = response.data; + // 沿用相邻 /iot/host 接口的业务响应约定;未知响应不视为成功。 + if (response.statusCode != 200 || body is! Map || body['code'] == null) { + throw const EmergencyStopRemoteException('急停接口响应格式错误或请求失败'); + } + final data = body['data']; + if ('${body['code']}' != '200' || + data == false || + body['accepted'] == false || + (data is Map && data['accepted'] == false)) { + final message = body['msg']; + throw EmergencyStopRemoteException( + message is String && message.trim().isNotEmpty ? message : '急停请求未被接受', + rejected: true, + ); + } + } +} + +class EmergencyStopRemoteException implements Exception { + const EmergencyStopRemoteException(this.message, {this.rejected = false}); + final String message; + final bool rejected; +} diff --git a/lib/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart b/lib/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart new file mode 100644 index 00000000..62aa9e47 --- /dev/null +++ b/lib/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart @@ -0,0 +1,47 @@ +import 'package:dio/dio.dart'; +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../../domain/entities/emergency_stop_target.dart'; +import '../../domain/entities/emergency_stop_failure.dart'; +import '../../domain/repositories/device_emergency_stop_repository.dart'; +import '../datasources/emergency_stop_remote_datasource.dart'; + +class DeviceEmergencyStopRepositoryImpl + implements DeviceEmergencyStopRepository { + const DeviceEmergencyStopRepositoryImpl(this.remote); + final EmergencyStopRemoteDatasource remote; + + @override + Future> request( + String deviceId, + EmergencyStopTarget target, + ) async { + try { + await remote.request(deviceId, target); + return const Right(unit); + } on EmergencyStopRemoteException catch (error) { + return Left( + error.rejected + ? EmergencyStopRejectedFailure(error.message) + : ServerFailure(error.message), + ); + } on DioException catch (error) { + final status = error.response?.statusCode; + if (status == 401 || status == 403) { + return Left(EmergencyStopRejectedFailure('登录已失效或无权执行急停操作')); + } + if (error.type == DioExceptionType.connectionTimeout || + error.type == DioExceptionType.sendTimeout || + error.type == DioExceptionType.receiveTimeout) { + return Left(NetworkFailure('急停请求超时,执行结果未确认')); + } + if (error.response != null) { + return Left(ServerFailure('急停接口请求失败')); + } + return Left(NetworkFailure('急停请求连接异常,执行结果未确认')); + } catch (_) { + return Left(Failure('急停请求异常,执行结果未确认')); + } + } +} diff --git a/lib/features/device_emergency_stop/domain/entities/emergency_stop_failure.dart b/lib/features/device_emergency_stop/domain/entities/emergency_stop_failure.dart new file mode 100644 index 00000000..dd500258 --- /dev/null +++ b/lib/features/device_emergency_stop/domain/entities/emergency_stop_failure.dart @@ -0,0 +1,6 @@ +import '../../../../core/error/failure.dart'; + +/// 后端明确返回业务失败,区别于断线/超时导致的结果未知。 +class EmergencyStopRejectedFailure extends ServerFailure { + EmergencyStopRejectedFailure(super.message); +} diff --git a/lib/features/device_emergency_stop/domain/entities/emergency_stop_target.dart b/lib/features/device_emergency_stop/domain/entities/emergency_stop_target.dart new file mode 100644 index 00000000..4582b78b --- /dev/null +++ b/lib/features/device_emergency_stop/domain/entities/emergency_stop_target.dart @@ -0,0 +1,8 @@ +/// 请求目标,不代表设备已经执行;实际急停状态仍以设备反馈为准。 +enum EmergencyStopTarget { + engage(1), + release(0); + + const EmergencyStopTarget(this.value); + final int value; +} diff --git a/lib/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart b/lib/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart new file mode 100644 index 00000000..eb399d99 --- /dev/null +++ b/lib/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart @@ -0,0 +1,12 @@ +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../entities/emergency_stop_target.dart'; + +abstract class DeviceEmergencyStopRepository { + /// 成功仅表示接口接受请求,不确认车辆实际急停或解除。 + Future> request( + String deviceId, + EmergencyStopTarget target, + ); +} diff --git a/lib/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart b/lib/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart new file mode 100644 index 00000000..15ba680c --- /dev/null +++ b/lib/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart @@ -0,0 +1,19 @@ +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../entities/emergency_stop_target.dart'; +import '../repositories/device_emergency_stop_repository.dart'; + +class RequestDeviceEmergencyStopUseCase { + const RequestDeviceEmergencyStopUseCase(this.repository); + final DeviceEmergencyStopRepository repository; + + Future> call( + String deviceId, + EmergencyStopTarget target, + ) { + final id = deviceId.trim(); + if (id.isEmpty) return Future.value(Left(Failure('设备标识不能为空'))); + return repository.request(id, target); + } +} diff --git a/lib/features/devices/domain/entities/running_status_entity.dart b/lib/features/devices/domain/entities/running_status_entity.dart index 20043ad3..43258230 100644 --- a/lib/features/devices/domain/entities/running_status_entity.dart +++ b/lib/features/devices/domain/entities/running_status_entity.dart @@ -2,10 +2,13 @@ import 'package:equatable/equatable.dart'; import 'package:get_it/get_it.dart'; +import '../../../../core/network/mqtt/domain/entities/host_realtime_message_entity.dart'; import '../../../../core/logging/i_logger_service.dart'; class RunningStatusEntity extends Equatable { + static const _unchanged = Object(); + // === 基础电气信息 (字段 0-6) === final double voltage; // [0] 电压 (V) final double leftTargetSpeed; // [1] 左轮目标速度 @@ -50,6 +53,9 @@ class RunningStatusEntity extends Equatable { final double linearSpeed; // host 实时线速度 m/s(前进为正,后退为负) final double angularSpeed; // host 实时角速度 rad/s(左转为正,右转为负) final bool hostDataReceived; // 是否已收到 host 实时数据(未收到时 UI 显示"未知") + final bool? emergencyStop; // 本帧急停状态;null 表示没有有效上报 + /// 保留本帧字段是否存在,遥控 HUD 据此区分真实零值和未上报。 + final HostRealtimeMessageEntity? hostRealtime; const RunningStatusEntity({ this.voltage = 0.0, @@ -71,7 +77,7 @@ class RunningStatusEntity extends Equatable { this.latitude = 0.0, this.longitude = 0.0, this.timestamp = '', - this.knifeCuttingSpeed = '0', + this.knifeCuttingSpeed = '', this.controlMode = '', this.battery = '0', this.workingArea = '0', @@ -80,6 +86,8 @@ class RunningStatusEntity extends Equatable { this.linearSpeed = 0.0, this.angularSpeed = 0.0, this.hostDataReceived = false, + this.emergencyStop, + this.hostRealtime, }); /// 从字段数组创建实体 (核心解析方法) @@ -145,7 +153,7 @@ class RunningStatusEntity extends Equatable { // 扩展信息 (保持原始字符串,由调用方决定如何解析) timestamp: fields[18].trim(), - knifeCuttingSpeed: fields[19].trim().isNotEmpty ? fields[19].trim() : '0', + knifeCuttingSpeed: fields[19].trim(), // 空串原样保留:表示后端这一帧没带该字段,UI 据此显示「未知」 controlMode: fields[20].trim(), battery: fields[21].trim().isNotEmpty ? fields[21].trim() : '0', @@ -184,6 +192,8 @@ class RunningStatusEntity extends Equatable { double? linearSpeed, double? angularSpeed, bool? hostDataReceived, + Object? emergencyStop = _unchanged, + HostRealtimeMessageEntity? hostRealtime, }) { return RunningStatusEntity( voltage: voltage ?? this.voltage, @@ -214,6 +224,10 @@ class RunningStatusEntity extends Equatable { linearSpeed: linearSpeed ?? this.linearSpeed, angularSpeed: angularSpeed ?? this.angularSpeed, hostDataReceived: hostDataReceived ?? this.hostDataReceived, + hostRealtime: hostRealtime ?? this.hostRealtime, + emergencyStop: identical(emergencyStop, _unchanged) + ? this.emergencyStop + : emergencyStop as bool?, ); } @@ -247,6 +261,8 @@ class RunningStatusEntity extends Equatable { linearSpeed, angularSpeed, hostDataReceived, + emergencyStop, + hostRealtime, ]; @override diff --git a/lib/features/devices/presentation/bloc/device_status_bloc.dart b/lib/features/devices/presentation/bloc/device_status_bloc.dart index cd58b281..549da319 100644 --- a/lib/features/devices/presentation/bloc/device_status_bloc.dart +++ b/lib/features/devices/presentation/bloc/device_status_bloc.dart @@ -12,6 +12,7 @@ import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_e import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart'; import '../../../../core/logging/i_logger_service.dart'; +import '../../../../core/logging/remote_control_diagnostics.dart'; import '../../../../core/logging/log_time.dart'; import '../../../../core/network/net_message_dispatcher.dart'; import '../../../../core/network/tcp/tcp_client.dart'; @@ -60,6 +61,9 @@ class DeviceStatusBloc extends Bloc { /// 当前实时快照的设备身份,供入口模式确认使用(只读)。 String? get listeningDeviceSn => _currentListeningSn; + /// 仅由主机帧刷新,定位/其他状态不会延长急停状态有效期。 + ({String sn, bool? active, DateTime receivedAt})? emergencyStopReading; + // 🔥 MQTT机器状态收帧计数(用于链路日志) int _mqttVehicleFrameCount = 0; int _mqttLocationFrameCount = 0; @@ -125,7 +129,9 @@ class DeviceStatusBloc extends Bloc { final is02 = p.command == 0x02; if (is02) { _packetSeq++; - debugPrint('📥 [0x02] #$_packetSeq 收到原始TCP包 | payload长度=${p.payload.length} | ${DateTime.now().toString().substring(11, 19)}'); + debugPrint( + '📥 [0x02] #$_packetSeq 收到原始TCP包 | payload长度=${p.payload.length} | ${DateTime.now().toString().substring(11, 19)}', + ); } return is02; }) @@ -134,7 +140,9 @@ class DeviceStatusBloc extends Bloc { final result = utf8.decode(p.payload, allowMalformed: true); return result; } catch (e) { - debugPrint('❌ [0x02] #$_packetSeq 解码失败: $e, payload前20字节=${p.payload.take(20).toList()}'); + debugPrint( + '❌ [0x02] #$_packetSeq 解码失败: $e, payload前20字节=${p.payload.take(20).toList()}', + ); return ''; } }) @@ -150,7 +158,9 @@ class DeviceStatusBloc extends Bloc { final fields = message.trim().split(','); if (fields.length < 18) { - debugPrint('⚠️ [0x02] #$_packetSeq 字段不足:${fields.length},期望≥18, 原始数据前100字符=${message.substring(0, message.length > 100 ? 100 : message.length)}'); + debugPrint( + '⚠️ [0x02] #$_packetSeq 字段不足:${fields.length},期望≥18, 原始数据前100字符=${message.substring(0, message.length > 100 ? 100 : message.length)}', + ); // 🔥 错误不节流,立即emit以便UI显示错误 if (!isClosed) { emit(DeviceStatusError('字段不足,期望≥18,实际:${fields.length}')); @@ -161,7 +171,9 @@ class DeviceStatusBloc extends Bloc { final status = RunningStatusEntity.fromFields(fields); final gps = GPSEntity(status.latitude, status.longitude); - debugPrint('✅ [0x02] #$_packetSeq 解析成功 | 字段数=${fields.length} | 电压=${status.voltage}V 电量=${status.battery}% 控制模式=${status.controlMode} | 节流等待${_throttleDuration.inMilliseconds}ms'); + debugPrint( + '✅ [0x02] #$_packetSeq 解析成功 | 字段数=${fields.length} | 电压=${status.voltage}V 电量=${status.battery}% 控制模式=${status.controlMode} | 节流等待${_throttleDuration.inMilliseconds}ms', + ); // 🔥 缓存最新数据用于节流发射 _cachedStatus = RunningStatusEntity( @@ -228,11 +240,14 @@ class DeviceStatusBloc extends Bloc { return; } - debugPrint('${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn'); + debugPrint( + '${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn', + ); // 🔥 换设备兜底:SN 变化时清空上一个设备的缓存与状态, // 防止旧坐标通过 copyWith(base) 残留污染新设备数据(即使入口漏调 Reset 也能兜住) if (_currentListeningSn != deviceSn) { + emergencyStopReading = null; _throttleTimer?.cancel(); _throttleTimer = null; _cachedStatus = null; @@ -241,7 +256,9 @@ class DeviceStatusBloc extends Bloc { if (!isClosed) { emit(DeviceStatusInitial()); } - debugPrint('${LogTime.now()} 🧹 [DeviceStatusBloc] 切换设备,已清空旧缓存: $deviceSn'); + debugPrint( + '${LogTime.now()} 🧹 [DeviceStatusBloc] 切换设备,已清空旧缓存: $deviceSn', + ); } // 按SN订阅(数据源内部自动退旧订新、同SN去重) @@ -268,16 +285,27 @@ class DeviceStatusBloc extends Bloc { debugPrint( '${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_mqttVehicleFrameCount帧 type=${message.type} 数据点=${message.data.length}', ); - // TODO 第二阶段:将数据点映射到 RunningStatusEntity 字段,复用500ms节流emit + // 沿用车辆数据点现有 cuttingSpeed 字段;主机话题没有割刀反馈。 + // 缺失或非法时清空,不能把默认 0 当成设备已停刀。 + final cutterRpm = message.getValueByName('cuttingSpeed'); + final base = _cachedStatus ?? const RunningStatusEntity(); + _cachedStatus = base.copyWith( + knifeCuttingSpeed: cutterRpm != null && cutterRpm.isFinite + ? cutterRpm.toString() + : '', + ); + if (_throttleTimer == null || !_throttleTimer!.isActive) { + _throttleTimer = Timer(_throttleDuration, _emitCachedStatus); + } }); _mqttLocationSubscription ??= _mowerRealtimeRepo.locationStream.listen(( location, ) { _mqttLocationFrameCount++; - debugPrint( - '${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}', - ); + // debugPrint( + // '${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}', + // ); // 🔥 核心:用 MQTT location 数据更新缓存并节流 emit if (location.isValid) { @@ -310,6 +338,50 @@ class DeviceStatusBloc extends Bloc { _mqttHostSubscription ??= _mowerRealtimeRepo.hostRealtimeStream.listen(( host, ) { + final sn = _currentListeningSn; + if (host.deviceSn != null && host.deviceSn != sn) return; + if (sn != null) { + emergencyStopReading = ( + sn: sn, + active: host.emergencyStop, + receivedAt: host.receivedAt ?? DateTime.now(), + ); + } + final trace = RemoteControlDiagnostics.instance; + if (trace.activeDevice != null && + trace.activeDevice == _currentListeningSn) { + final raw = host.rawData; + trace.event('host_telemetry', { + 'telemetryDevice': _currentListeningSn, + 'linearMps': raw.containsKey('linear_speed') + ? host.linearSpeed + : null, + 'angularRadps': raw.containsKey('angular_speed') + ? host.angularSpeed + : null, + 'leftTargetRpm': raw.containsKey('left_target_rpm') + ? host.leftTargetRpm + : null, + 'rightTargetRpm': raw.containsKey('right_target_rpm') + ? host.rightTargetRpm + : null, + 'leftMeasuredRpm': raw.containsKey('left_measured_rpm') + ? host.leftMeasuredRpm + : null, + 'rightMeasuredRpm': raw.containsKey('right_measured_rpm') + ? host.rightMeasuredRpm + : null, + 'leftCurrent': raw.containsKey('left_motor_current') + ? host.leftMotorCurrent + : null, + 'rightCurrent': raw.containsKey('right_motor_current') + ? host.rightMotorCurrent + : null, + 'emergency': raw['emergency_stop'], + 'controlMode': raw['control_mode'], + 'motion': raw['motion'], + }); + } final base = _cachedStatus ?? RunningStatusEntity(); _cachedStatus = base.copyWith( voltage: host.batteryVoltage, @@ -331,6 +403,7 @@ class DeviceStatusBloc extends Bloc { // 代价:若 host 帧偶发漏带该字段,此栏会在真值与「未知」间跳动; // 现场若出现闪烁,说明 host 帧字段不稳定,应从后端侧解决而非在此兜底。 controlMode: host.controlMode, + emergencyStop: host.emergencyStop, workingArea: host.totalWorkArea.toString(), // 🔥 供全功能模式(pv_control)展示:累计作业里程 + host 已推数据标记 totalWorkDistance: host.totalWorkDistance, @@ -338,15 +411,19 @@ class DeviceStatusBloc extends Bloc { linearSpeed: host.linearSpeed, angularSpeed: host.angularSpeed, hostDataReceived: true, + hostRealtime: host, ); // 🔥 host 无坐标:GPS 缺省时用当前经纬度占位,保证能即时刷新(不覆盖 location 已写入的真坐标) - _cachedGps ??= GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude); - - debugPrint( - '${LogTime.now()} 🛰️ [MQTT-主机实时] 已合并 → 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 线速度=${host.linearSpeed}m/s 角速度=${host.angularSpeed}rad/s', + _cachedGps ??= GPSEntity( + _cachedStatus!.latitude, + _cachedStatus!.longitude, ); + // debugPrint( + // '${LogTime.now()} 🛰️ [MQTT-主机实时] 已合并 → 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 线速度=${host.linearSpeed}m/s 角速度=${host.angularSpeed}rad/s', + // ); + // 500ms 节流:与 location/车辆实时 发射链路一致 if (_throttleTimer == null || !_throttleTimer!.isActive) { _throttleTimer = Timer(_throttleDuration, () { @@ -355,7 +432,9 @@ class DeviceStatusBloc extends Bloc { } }); - debugPrint('${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn'); + debugPrint( + '${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn', + ); _logger.log('✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn'); } @@ -440,10 +519,12 @@ class DeviceStatusBloc extends Bloc { // 🔥 无论缓存是否有效,都必须 emit 触发 BlocBuilder 重建 if (!isClosed) { - emit(DeviceStatusUpdated( - _cachedStatus ?? RunningStatusEntity(), - _cachedGps ?? GPSEntity(0.0, 0.0), - )); + emit( + DeviceStatusUpdated( + _cachedStatus ?? RunningStatusEntity(), + _cachedGps ?? GPSEntity(0.0, 0.0), + ), + ); debugPrint('📤 [DeviceStatusBloc] 已 emit 完成信号,触发 UI 更新'); } @@ -473,17 +554,28 @@ class DeviceStatusBloc extends Bloc { int _fixStatusToQual(String? fixStatus, int fallback) { if (fixStatus == null) return fallback; switch (fixStatus) { - case 'no_fix': return 0; - case 'single': return 1; - case 'dgnss': return 2; - case 'ins': return 3; - case 'rtk_fixed': return 4; - case 'rtk_float': return 5; - case 'single_no_heading': return 6; - case 'dgnss_no_heading': return 7; - case 'rtk_fixed_no_heading': return 8; - case 'rtk_float_no_heading': return 9; - default: return fallback; + case 'no_fix': + return 0; + case 'single': + return 1; + case 'dgnss': + return 2; + case 'ins': + return 3; + case 'rtk_fixed': + return 4; + case 'rtk_float': + return 5; + case 'single_no_heading': + return 6; + case 'dgnss_no_heading': + return 7; + case 'rtk_fixed_no_heading': + return 8; + case 'rtk_float_no_heading': + return 9; + default: + return fallback; } } @@ -491,13 +583,14 @@ class DeviceStatusBloc extends Bloc { // 🔥 放宽:允许仅有机器状态(host 先到、GPS 未到)时也能刷新 UI void _emitCachedStatus() { if (_cachedStatus != null && !isClosed) { - final gps = _cachedGps ?? + final gps = + _cachedGps ?? GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude); // 控制模式为空串 = 后端从未给过,日志里显式标出来,免得和 0 混看 - final controlModeLog = _cachedStatus!.controlMode.isEmpty - ? '--(未收到)' - : _cachedStatus!.controlMode; - debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}'); + // final controlModeLog = _cachedStatus!.controlMode.isEmpty + // ? '--(未收到)' + // : _cachedStatus!.controlMode; + // debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}'); emit(DeviceStatusUpdated(_cachedStatus!, gps)); } } @@ -507,6 +600,7 @@ class DeviceStatusBloc extends Bloc { DeviceStatusReset event, Emitter emit, ) async { + emergencyStopReading = null; debugPrint('🔄 [DeviceStatusBloc] 收到重置事件:清空状态 - 当前状态:${state.runtimeType}'); _logger.log( '🔄 [DeviceStatusBloc] 收到重置事件:清空状态 - 当前状态:${state.runtimeType}', @@ -601,10 +695,12 @@ class DeviceStatusBloc extends Bloc { // 🔥 关键:无论缓存是否有效,都必须 emit 触发 BlocBuilder 重建 if (!isClosed) { - emit(DeviceStatusUpdated( - _cachedStatus ?? RunningStatusEntity(), - _cachedGps ?? GPSEntity(0.0, 0.0), - )); + emit( + DeviceStatusUpdated( + _cachedStatus ?? RunningStatusEntity(), + _cachedGps ?? GPSEntity(0.0, 0.0), + ), + ); debugPrint('📤 [DeviceStatusBloc] 已 emit 停止信号,触发 UI 更新'); } @@ -642,6 +738,7 @@ class DeviceStatusBloc extends Bloc { // 🔥 重置设备ID _currentDeviceId = null; _currentListeningSn = null; + emergencyStopReading = null; return Future.value(); } diff --git a/lib/features/pv_control/presentation/channel/pv_robot_command_channel.dart b/lib/features/pv_control/presentation/channel/pv_robot_command_channel.dart index efc59c94..b620c290 100644 --- a/lib/features/pv_control/presentation/channel/pv_robot_command_channel.dart +++ b/lib/features/pv_control/presentation/channel/pv_robot_command_channel.dart @@ -8,7 +8,7 @@ import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remot /// 由调用方决定注入哪一个实现,UI 与控制语义代码零改动。 /// /// 段位值统一沿用远程遥控编码:上=1、中=0、下=2 -/// (割刀 1 抬 / 2 降、底盘 1 升 / 2 降、点火 1 点火 / 2 熄火,0 都是停止)。 +/// 割刀段位由 Cubit 映射为开1/关0/不操作2;底盘、点火编码不变。 abstract interface class PvRobotCommandChannel { /// 前进 / 后退(左摇杆,-100~100,上推为正=前进)。 void sendDriveY(int y); @@ -19,19 +19,19 @@ abstract interface class PvRobotCommandChannel { /// 底盘升降。 void sendChassis(int cmd); - /// 割刀升降。 + /// 割刀滑块段位:1=上拨开启、2=下拨关闭、0=回中不操作。 void sendMower(int cmd); /// 点火 / 熄火。 void sendIgnition(int cmd); /// 紧急停止。 - void sendEmergencyStop(bool on); + Future sendEmergencyStop(bool on); /// 双轴归零(松手即停,安全底线)。 Future stopAllMovement(); - /// 进入控制态:查询一次控制权限,并开始持续下发控制帧(默认 100ms 控制循环)。 + /// 进入控制态:查询一次控制权限,并开始持续下发控制帧(默认 250ms 控制循环)。 void activate(); /// 退出控制态:归零、停止控制循环、释放控制权、复位权限。 @@ -58,22 +58,22 @@ class RemoteControlRobotChannel implements PvRobotCommandChannel { void sendChassis(int cmd) => _cubit.sendChassisCommand(cmd); @override - void sendMower(int cmd) => _cubit.sendMowerCommand(cmd); + void sendMower(int cmd) => _cubit.sendMowerSliderCommand(cmd); @override void sendIgnition(int cmd) => _cubit.sendFireCommand(cmd); @override - void sendEmergencyStop(bool on) => _cubit.updateEmergency(on); + Future sendEmergencyStop(bool on) => _cubit.updateEmergency(on); @override - Future stopAllMovement() => _cubit.stopAllMovement(); + Future stopAllMovement() => _cubit.stopAllMovement(reason: 'hud_stop'); @override void activate() { final cubit = _cubit; // 与远程遥控页一致:进控制态先「仅查询」一次控制权限(grabControl=false, - // 只把接口结果如实同步到 hasPermission,不发 TCP 抢占),再启动 100ms 控制循环。 + // 只把接口结果如实同步到 hasPermission,不发 TCP 抢占),再启动 250ms 控制循环。 // 无权限时控制循环会自动跳过发送,行为与极简模式完全相同。 final deviceName = cubit.state.targetDevice?.deviceName; if (deviceName != null && deviceName.isNotEmpty) { @@ -90,11 +90,11 @@ class RemoteControlRobotChannel implements PvRobotCommandChannel { @override Future deactivate() async { - // 先解除急停,避免 HUD 退出时残留 isEmergency=true, - // 让下一次进入(含极简远程遥控页)控制循环被锁住无法运动。 - _cubit.updateEmergency(false); + _cubit.cancelPermissionRequest(); + // 退出页面不再自动解除急停;只有明确的用户操作可发送 eStop=0。 + // 旧调用保留:_cubit.updateEmergency(false); // 停止指令无视权限强制发送,先归零再停循环,避免残留运动。 - await _cubit.stopAllMovement(); + await _cubit.stopAllMovement(reason: 'hud_deactivate'); _cubit.stopControlLoop(); // 与远程遥控页一致:退出释放远程控制权限(type=2),设备名取当前 targetDevice。 final deviceId = _cubit.state.targetDevice?.deviceName; diff --git a/lib/features/pv_control/presentation/models/pv_telemetry.dart b/lib/features/pv_control/presentation/models/pv_telemetry.dart index b90652b1..b9998257 100644 --- a/lib/features/pv_control/presentation/models/pv_telemetry.dart +++ b/lib/features/pv_control/presentation/models/pv_telemetry.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; +import '../../../devices/domain/entities/running_status_entity.dart'; -/// 光伏巡检机器人实时遥测数据(本批次为 Mock 假数据,后续可替换为 MQTT/TCP 真实来源) +/// 光伏巡检机器人遥测数据;状态值缺失时保留 null,由 UI 展示未知。 /// /// 采用不可变对象 + copyWith,便于后续接入真实数据流时局部更新字段。 @immutable @@ -15,7 +16,14 @@ class PvTelemetry { this.isAutoDriving = true, // 默认留空:具体文案由 UI 层按当前语言兜底(见 PvInfoColumn) this.taskStatus = '', - this.speed = 0.3, + this.speed, + this.leftMeasuredRpm, + this.rightMeasuredRpm, + this.leftTargetRpm, + this.rightTargetRpm, + this.mowerRpm, + this.motion, + this.emergencyStop, this.mileage, this.networkNormal = true, this.temperature, @@ -39,8 +47,58 @@ class PvTelemetry { final bool isAutoDriving; final String taskStatus; - /// 当前速度 m/s - final double speed; + /// 当前线速度 m/s;负数表示倒车,null 表示未有效上报。 + final double? speed; + final double? leftMeasuredRpm; + final double? rightMeasuredRpm; + final double? leftTargetRpm; + final double? rightTargetRpm; + + /// 车辆实时 cuttingSpeed / TCP 割刀转速;不使用本地启停指令推断。 + final double? mowerRpm; + final String? motion; + final bool? emergencyStop; + + /// 每次从当前状态生成新快照,缺失字段不会沿用上帧数值或默认零值。 + factory PvTelemetry.fromRunningStatus( + RunningStatusEntity? status, { + String deviceName = '', + bool obstacleAlert = false, + }) { + final raw = status?.hostRealtime?.rawData ?? const {}; + double? number(String field) { + final value = raw[field]; + final parsed = value is num + ? value.toDouble() + : double.tryParse(value?.toString() ?? ''); + return parsed != null && parsed.isFinite ? parsed : null; + } + + final cutter = double.tryParse(status?.knifeCuttingSpeed ?? ''); + final battery = number('battery_percentage'); + return PvTelemetry( + deviceName: deviceName, + obstacleAlert: obstacleAlert, + battery: battery != null && battery >= 0 && battery <= 100 + ? battery + : null, + mileage: number('total_work_distance'), + temperature: number('main_temperature'), + speed: number('linear_speed'), + leftMeasuredRpm: number('left_measured_rpm'), + rightMeasuredRpm: number('right_measured_rpm'), + leftTargetRpm: number('left_target_rpm'), + rightTargetRpm: number('right_target_rpm'), + mowerRpm: cutter != null && cutter.isFinite ? cutter : null, + motion: status?.hostRealtime?.motion, + emergencyStop: status?.emergencyStop, + controlMode: status?.controlMode, + fixStatus: status?.qual, + satelliteCount: status != null && status.satelliteCnt > 0 + ? status.satelliteCnt + : null, + ); + } /// 巡检里程(累计作业里程);null=未收到实时数据(显示"未知") final double? mileage; @@ -79,6 +137,13 @@ class PvTelemetry { bool? isAutoDriving, String? taskStatus, double? speed, + double? leftMeasuredRpm, + double? rightMeasuredRpm, + double? leftTargetRpm, + double? rightTargetRpm, + double? mowerRpm, + String? motion, + bool? emergencyStop, double? mileage, bool? networkNormal, double? temperature, @@ -98,6 +163,13 @@ class PvTelemetry { isAutoDriving: isAutoDriving ?? this.isAutoDriving, taskStatus: taskStatus ?? this.taskStatus, speed: speed ?? this.speed, + leftMeasuredRpm: leftMeasuredRpm ?? this.leftMeasuredRpm, + rightMeasuredRpm: rightMeasuredRpm ?? this.rightMeasuredRpm, + leftTargetRpm: leftTargetRpm ?? this.leftTargetRpm, + rightTargetRpm: rightTargetRpm ?? this.rightTargetRpm, + mowerRpm: mowerRpm ?? this.mowerRpm, + motion: motion ?? this.motion, + emergencyStop: emergencyStop ?? this.emergencyStop, mileage: mileage ?? this.mileage, networkNormal: networkNormal ?? this.networkNormal, temperature: temperature ?? this.temperature, diff --git a/lib/features/pv_control/presentation/pages/pv_control_page.dart b/lib/features/pv_control/presentation/pages/pv_control_page.dart index bfa9da02..65d16b2a 100644 --- a/lib/features/pv_control/presentation/pages/pv_control_page.dart +++ b/lib/features/pv_control/presentation/pages/pv_control_page.dart @@ -1,10 +1,13 @@ import 'dart:async'; import 'package:maibu_satabot_v2/features/device_control_mode/domain/entities/device_control_mode.dart'; import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart'; +import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/mode_independent_control.dart'; import 'dart:io'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; +import '../../../remote_control/presentation/widgets/emergency_stop_confirmation.dart'; +import '../../../remote_control/presentation/widgets/emergency_stop_button.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -12,13 +15,14 @@ import 'package:path_provider/path_provider.dart'; import 'package:maibu_satabot_v2/components/capsule_toast.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; -import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart'; import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart'; import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; +import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/remote_control_link_feedback.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart'; import 'package:maibu_satabot_v2/features/v2/local_camera/presentation/cubit/local_camera_cubit.dart'; import 'package:maibu_satabot_v2/features/v2/usb_camera/data/uvc_camera_service.dart'; @@ -75,7 +79,6 @@ class _PvControlPageState extends State { final GlobalKey _videoKey = GlobalKey(); /// 本批次使用 Mock 遥测数据 - final PvTelemetry _telemetry = const PvTelemetry(); /// 遥控指令传输通道:当前为 TCP 实现(委托 `RemoteControlCubit`), /// 以后接蓝牙 / 下位机只换一个实现类,HUD 与本页面代码零改动。 @@ -89,13 +92,11 @@ class _PvControlPageState extends State { /// 尾部那次 stopControlLoop() 会把刚起来的循环又关掉,HUD 就变成 /// “摇杆推了没反应”。故延后到 deactivate 收尾再起循环。 bool _deactivating = false; + bool _emergencyConfirming = false; /// deactivate 期间收到过重新进入控制态的请求。 bool _restartAfterDeactivate = false; - /// 急停开关态:HUD 急停钮每点一次翻转,经通道下发 updateEmergency。 - bool _emergencyOn = false; - /// 远程控制单例(HUD 与原远程遥控页共用它,指令通道内部也委托它)。 RemoteControlCubit get _cubit => sl(); @@ -147,41 +148,12 @@ class _PvControlPageState extends State { : AppLocalizations.of(context).translate('pv_control.no_device'); } - /// 实际下发的遥测:真实字段来自全局 [DeviceStatusBloc] 的 host 实时数据 - /// (电量/巡检里程/设备温度),未收到时置 null 由 UI 显示"未知"; - /// 开启「模拟障碍物信息」相当于收到机器告警推送,叠加 obstacleAlert。 + /// 使用当前设备的实时快照;未上报的字段由 UI 显示未知。 PvTelemetry _resolveTelemetry(DeviceStatusState dsState, String deviceName) { - double? battery; - double? mileage; - double? temp; - int? fixStatus; - int? satelliteCount; - String? controlMode; - if (dsState is DeviceStatusUpdated) { - final s = dsState.status; - // 定位质量:来自 location/post 的 fix_status(qual) - fixStatus = s.qual; - // 控制模式:与“设备数据监控”同一口径,只要收到状态就跟随,不加 host 门控 - controlMode = s.controlMode; - // 卫星数:realtime/post 尚未推送,无数据源时保持 null 显示"未知" - if (s.satelliteCnt > 0) satelliteCount = s.satelliteCnt; - // 以下三项来自 host 实时话题(device/{sn}/host/realTime/message) - if (s.hostDataReceived) { - battery = double.tryParse(s.battery); - mileage = s.totalWorkDistance; - temp = s.chipTemp; - } - } - return _telemetry.copyWith( - // 设备名用真实选中的设备,不再用 PvTelemetry 里写死的占位名 + return PvTelemetry.fromRunningStatus( + dsState is DeviceStatusUpdated ? dsState.status : null, deviceName: deviceName, obstacleAlert: _simObstacle, - battery: battery, - mileage: mileage, - temperature: temp, - fixStatus: fixStatus, - satelliteCount: satelliteCount, - controlMode: controlMode, ); } @@ -230,7 +202,7 @@ class _PvControlPageState extends State { if (widget.deviceId.isNotEmpty && token != null) { setState(() { _streamUrl = - 'webrtc://${TCPConsts.TCP_IP}/live/livestream/${widget.deviceId}?token=$token'; + 'webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/${widget.deviceId}?token=$token'; }); } else { debugPrint('❌ [PvControl] 视频URL初始化失败:deviceId 或 token 为空'); @@ -310,15 +282,43 @@ class _PvControlPageState extends State { ); } - void _onEmergencyStop() { - // HUD 急停钮为“点一下急停 / 再点一下恢复”的切换态(按钮自身不携带 on/off)。 - _emergencyOn = !_emergencyOn; - _channel.sendEmergencyStop(_emergencyOn); + Future _onEmergencyStop() async { + if (_emergencyConfirming || _cubit.state.isEmergencyRequestPending) return; + final sn = _cubit.state.targetDevice?.deviceName; + final on = !_cubit.state.isEmergency; + if (!_cubit.checkEmergencyRequest(on)) { + CapsuleToast.show( + AppLocalizations.of( + context, + ).translate('remote_control.${_cubit.state.emergencyFeedbackKey}'), + showCheck: false, + ); + return; + } + if (!_cubit.checkEmergencyRequest(on)) { + CapsuleToast.show( + AppLocalizations.of( + context, + ).translate('remote_control.${_cubit.state.emergencyFeedbackKey}'), + showCheck: false, + ); + return; + } + _emergencyConfirming = true; + bool confirmed; + try { + confirmed = await confirmEmergencyStop(context, engage: on, sn: sn ?? ''); + } finally { + _emergencyConfirming = false; + } + if (!confirmed || !mounted || sn != _cubit.state.targetDevice?.deviceName) { + return; + } + await _channel.sendEmergencyStop(on); + if (!mounted || sn != _cubit.state.targetDevice?.deviceName) return; final tr = AppLocalizations.of(context); CapsuleToast.show( - _emergencyOn - ? tr.translate('pv_control.toast_emergency_sent') - : tr.translate('pv_control.toast_emergency_released'), + tr.translate('remote_control.${_cubit.state.emergencyFeedbackKey}'), showCheck: false, ); } @@ -338,8 +338,7 @@ class _PvControlPageState extends State { return; } _controlActive = true; - // deactivate 会清除急停态,重新进入从“未急停”开始,与通道保持同步。 - _emergencyOn = false; + // 急停由共享 Cubit 保持,重新进入页面不自动解除。 _channel.activate(); } @@ -679,6 +678,7 @@ class _PvControlPageState extends State { deviceName: widget.deviceName, target: ControlModeTarget.remote, cancelToPreview: true, + emergencyStopControl: const EmergencyStopButton(), onReady: _startControl, child: _buildPage(context), ); @@ -863,15 +863,20 @@ class _PvTopNav extends StatelessWidget { ], ), ), - IconButton( - onPressed: onSettings, - visualDensity: VisualDensity.compact, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 32, minHeight: 32), - icon: const Icon( - Icons.settings, - color: PvColors.textSecondary, - size: 20, + RemoteControlHeartbeatIndicator( + heartbeats: sl().serverHeartbeats, + ), + ModeIndependentControl( + child: IconButton( + onPressed: onSettings, + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + icon: const Icon( + Icons.settings, + color: PvColors.textSecondary, + size: 20, + ), ), ), IconButton( diff --git a/lib/features/pv_control/presentation/widgets/pv_control_bar.dart b/lib/features/pv_control/presentation/widgets/pv_control_bar.dart index 7f8b474e..aabf288d 100644 --- a/lib/features/pv_control/presentation/widgets/pv_control_bar.dart +++ b/lib/features/pv_control/presentation/widgets/pv_control_bar.dart @@ -1,5 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; +import '../../../remote_control/presentation/bloc/remote_control_cubit.dart'; +import '../../../device_control_mode/presentation/widgets/mode_independent_control.dart'; import '../theme/pv_colors.dart'; @@ -48,9 +51,7 @@ class PvControlBar extends StatelessWidget { onTap: onPauseTask, ), ), - Expanded( - child: PvEmergencyStopButton(onTap: onEmergencyStop), - ), + Expanded(child: PvEmergencyStopButton(onTap: onEmergencyStop)), Expanded( child: _ControlButton( icon: Icons.videocam, @@ -160,9 +161,9 @@ class _PvEmergencyStopButtonState extends State with SingleTickerProviderStateMixin { late final AnimationController _controller; - /// 是否处于「急停中」:默认 false(正常态、不呼吸)。 - /// 点击一次进入急停(呼吸 + 「急停中」提示),再点一次解除恢复正常。 - bool _active = false; + bool get _active => + context.read().state.isEmergency && + context.read().state.hasEmergencyStatus; @override void initState() { @@ -179,19 +180,30 @@ class _PvEmergencyStopButtonState extends State super.dispose(); } - void _handleTap() { - setState(() => _active = !_active); - if (_active) { + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final state = context.watch().state; + final active = state.isEmergency && state.hasEmergencyStatus; + if (active && !_controller.isAnimating) { _controller.repeat(reverse: true); - } else { + } else if (!active && _controller.isAnimating) { _controller.stop(); _controller.value = 0; } + } + + void _handleTap() { + if (context.read().state.isEmergencyRequestPending) + return; widget.onTap(); } @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => + ModeIndependentControl(child: _buildButton(context)); + + Widget _buildButton(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (context, child) { @@ -214,7 +226,9 @@ class _PvEmergencyStopButtonState extends State ), boxShadow: [ BoxShadow( - color: PvColors.danger.withValues(alpha: 0.5 + 0.35 * t), + color: PvColors.danger.withValues( + alpha: 0.5 + 0.35 * t, + ), blurRadius: 18 + 12 * t, spreadRadius: 2 + 3 * t, ), @@ -232,9 +246,11 @@ class _PvEmergencyStopButtonState extends State fit: BoxFit.scaleDown, child: Text( AppLocalizations.of(context).translate( - _active - ? 'pv_control.emergency_stopping' - : 'pv_control.emergency_stop', + !context.read().state.hasEmergencyStatus + ? 'remote_control.emergency_unknown' + : _active + ? 'remote_control.emergency_stopping' + : 'remote_control.emergency_inactive', ), maxLines: 1, textAlign: TextAlign.center, diff --git a/lib/features/pv_control/presentation/widgets/pv_info_column.dart b/lib/features/pv_control/presentation/widgets/pv_info_column.dart index 53d45f5a..997ea55d 100644 --- a/lib/features/pv_control/presentation/widgets/pv_info_column.dart +++ b/lib/features/pv_control/presentation/widgets/pv_info_column.dart @@ -38,8 +38,9 @@ class PvInfoColumn extends StatelessWidget { label: AppLocalizations.of( context, ).translate('pv_control.current_speed'), - value: telemetry.speed.toStringAsFixed(1), - unit: 'm/s', + value: telemetry.speed?.toStringAsFixed(2) ?? + AppLocalizations.of(context).translate('pv_control.unknown'), + unit: telemetry.speed == null ? '' : 'm/s', )), const SizedBox(width: 6), Expanded(child: _MetricCard.icon( diff --git a/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart b/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart index 83e3aef6..504b21ac 100644 --- a/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart +++ b/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart @@ -3,12 +3,14 @@ import 'dart:math' as math; import 'package:cc_ui_kit/cc_ui_kit.dart'; import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/mode_independent_control.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:maibu_satabot_v2/components/capsule_toast.dart'; import 'package:maibu_satabot_v2/components/control_mode_text.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/entities/reverse_camera_data.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; @@ -22,6 +24,8 @@ import '../models/pv_video_source.dart'; import '../theme/pv_colors.dart'; import '../theme/pv_hud_theme.dart'; import '../channel/pv_robot_command_channel.dart'; +import '../../../remote_control/presentation/widgets/remote_control_link_feedback.dart'; +import '../../../remote_control/presentation/widgets/permission_request_feedback.dart'; import 'pv_control_bar.dart'; import 'pv_rear_view_card.dart'; import 'pv_local_rtsp_video.dart'; @@ -53,7 +57,7 @@ typedef _PvSheetSpec = ({ /// 计算缩放系数 [_sc],手机横屏(高约 360 → _sc≈0.64)时顶栏占比、字号、按钮 /// 全部等比缩小,平板(高约 600 → _sc≈1.07)时放大,从而在两种设备上还原版式。 /// -/// AR 障碍框、遥测数值为写死的假数据;控制指令(摇杆 / 割刀 / 底盘 / 点火 / 急停) +/// 状态卡由实时遥测驱动;控制指令(摇杆 / 割刀 / 底盘 / 点火 / 急停) /// 已通过 [PvRobotCommandChannel] 接入(TCP 实现委托远程遥控 Cubit,见 pv_robot_command_channel.dart)。 class PvManualControlView extends StatefulWidget { const PvManualControlView({ @@ -615,6 +619,10 @@ class _PvManualControlViewState extends State SizedBox(width: d(8)), // 「正在控制 / 未在控制」状态胶囊(与远程遥控顶栏同款、同逻辑) _buildControlStatusChip(), + RemoteControlHeartbeatIndicator( + heartbeats: sl().serverHeartbeats, + size: d(9), + ), // 中:链路信息(FittedBox 保证窄屏自动缩小不溢出) Expanded( child: Padding( @@ -686,10 +694,12 @@ class _PvManualControlViewState extends State active: _showSidePips, onTap: _toggleSidePips, ), - _navItem( - Icons.settings_outlined, - tr.translate('pv_control.nav_settings'), - onTap: widget.onSettings, + ModeIndependentControl( + child: _navItem( + Icons.settings_outlined, + tr.translate('pv_control.nav_settings'), + onTap: widget.onSettings, + ), ), SizedBox(width: d(4)), ], @@ -752,17 +762,18 @@ class _PvManualControlViewState extends State initialData: cubit.state, stream: cubit.stream, builder: (context, snapshot) { - final hasPermission = snapshot.data?.hasPermission ?? false; - final tr = AppLocalizations.of(context); - final color = hasPermission - ? PvHudColors.success - : PvHudColors.danger; + final permissionState = snapshot.data ?? cubit.state; + final hasPermission = permissionState.hasPermission; + final busy = permissionState.isPermissionRequestBusy; + final color = busy + ? Colors.orange + : hasPermission ? PvHudColors.success : PvHudColors.danger; final chip = Container( padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(3)), decoration: BoxDecoration( - color: hasPermission - ? PvHudColors.successBg - : PvHudColors.dangerBg, + color: busy + ? Colors.orange.withValues(alpha: 0.12) + : hasPermission ? PvHudColors.successBg : PvHudColors.dangerBg, borderRadius: BorderRadius.circular(d(20)), ), child: Row( @@ -775,9 +786,7 @@ class _PvManualControlViewState extends State ), SizedBox(width: d(4)), Text( - hasPermission - ? tr.translate('remote_control.controlling') - : tr.translate('remote_control.not_controlling'), + permissionStatusText(context, permissionState), maxLines: 1, style: s(PvHudType.caption, 11).copyWith( color: color, @@ -787,19 +796,16 @@ class _PvManualControlViewState extends State ], ), ); - return GestureDetector( + return PermissionRequestFeedback( + cubit: cubit, + child: Tooltip( + message: permissionStatusHint(context, permissionState), + child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - // 已在控制:无需重复抢占。 - if (hasPermission) return; - final targetDevice = cubit.state.targetDevice; - if (targetDevice == null) { - debugPrint('❌ [PV遥控] targetDevice 为空,无法请求权限'); - return; - } - debugPrint('🔑 [PV遥控] 👆 点击“未在控制”,请求抢占控制权'); + if (hasPermission || busy) return; cubit.requestControlPermissionS( - targetDevice.deviceName, + cubit.state.targetDevice?.deviceName ?? '', 'app', source: '手动点击', grabControl: true, @@ -816,6 +822,8 @@ class _PvManualControlViewState extends State ), child: chip, ), + ), + ), ); }, ); @@ -1348,12 +1356,26 @@ class _PvManualControlViewState extends State ); } - /// 状态卡:图标 + 标签 + 数值的竖排列表(设计稿左栏第二张卡)。 Widget _statusCard() { final tr = AppLocalizations.of(context); + final telemetry = widget.telemetry; + final unknown = tr.translate('pv_control.unknown'); + String speedText(double? value, String unit) => + value == null ? unknown : '${value.toStringAsFixed(2)} $unit'; + final motionKey = telemetry.emergencyStop == true + ? 'pv_control.emergency_stopping' + : switch (telemetry.motion) { + 'moving' => 'pv_control.status_moving', + 'stopped' => 'pv_control.status_stopped', + 'blocked' => 'pv_control.status_blocked', + _ => 'pv_control.unknown', + }; + final motionDanger = telemetry.emergencyStop == true || + telemetry.motion == 'blocked'; + final mowerRunning = telemetry.mowerRpm != null && telemetry.mowerRpm != 0; final batteryText = widget.telemetry.battery == null - ? tr.translate('pv_control.unknown') - : '${widget.telemetry.battery!.toStringAsFixed(0)}% (5.6 h)'; + ? unknown + : '${widget.telemetry.battery!.toStringAsFixed(0)}%'; final fixQuality = widget.telemetry.fixStatus == 4; return _panel( padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(6)), @@ -1362,30 +1384,59 @@ class _PvManualControlViewState extends State _statusRow( Icons.directions_car_filled_outlined, tr.translate('pv_control.vehicle_status'), - tr.translate('pv_control.status_normal'), - valueColor: PvHudColors.success, - capsule: true, + tr.translate(motionKey), + valueColor: motionDanger + ? PvHudColors.danger + : motionKey == 'pv_control.unknown' + ? PvHudColors.textSecondary + : PvHudColors.success, ), _statusRow( Icons.speed, tr.translate('pv_control.drive_speed'), - '1.2 m/s', + speedText(telemetry.speed, 'm/s'), + ), + _statusRow( + Icons.speed, + tr.translate('pv_control.left_measured_rpm'), + speedText(telemetry.leftMeasuredRpm, 'rpm'), + ), + _statusRow( + Icons.speed, + tr.translate('pv_control.right_measured_rpm'), + speedText(telemetry.rightMeasuredRpm, 'rpm'), + ), + _statusRow( + Icons.speed, + tr.translate('pv_control.left_target_rpm'), + speedText(telemetry.leftTargetRpm, 'rpm'), + ), + _statusRow( + Icons.speed, + tr.translate('pv_control.right_target_rpm'), + speedText(telemetry.rightTargetRpm, 'rpm'), ), _statusRow( Icons.settings_outlined, tr.translate('pv_control.gear'), - tr.translate('pv_control.gear_low'), + unknown, ), _statusRow( Icons.content_cut, tr.translate('pv_control.mower_status'), - tr.translate('pv_control.mower_running'), - valueColor: PvHudColors.success, + telemetry.mowerRpm == null + ? unknown + : tr.translate(mowerRunning + ? 'pv_control.mower_running' + : 'pv_control.mower_stopped'), + valueColor: mowerRunning + ? PvHudColors.success + : PvHudColors.textSecondary, ), _statusRow( Icons.height, tr.translate('pv_control.chassis_height'), - '120 mm', + unknown, ), _statusRow( Icons.battery_5_bar, @@ -1684,7 +1735,9 @@ class _PvManualControlViewState extends State child: CCJoystick( radius: radius, axisHint: AxisHint.forwardBackward, + onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields), skin: _joystickSkin(), + onPress: () => RemoteControlLinkNotice.showIfDisconnected(context), onValueChanged: (v) { final int y = v.y.toInt(); if (y == _lastDriveY) return; @@ -1705,7 +1758,9 @@ class _PvManualControlViewState extends State child: CCJoystick( radius: radius, axisHint: AxisHint.leftRight, + onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields), skin: _joystickSkin(), + onPress: () => RemoteControlLinkNotice.showIfDisconnected(context), onValueChanged: (v) { final int x = v.x.toInt().abs() < 1 ? 0 : v.x.toInt(); if (x == _lastDriveX) return; @@ -1931,7 +1986,7 @@ class _PvManualControlViewState extends State mid: 'assets/svgs/remote_scissors.svg', down: 'assets/svgs/remote_down.svg', segUp: 'pv_control.seg_mower_up', - segMid: 'pv_control.seg_stop', + segMid: 'pv_control.seg_mower_idle', segDown: 'pv_control.seg_mower_down', turns: 0, ), @@ -2065,6 +2120,7 @@ class _PvManualControlViewState extends State /// 长按起手:给一下中等强度震动做确认(手指按在按钮上就触发了,无反馈很 /// 容易被当成没响应),并亮气泡、从中位(停)开始。 void _onScrubStart(String sheetKey) { + RemoteControlLinkNotice.showIfDisconnected(context); _sheetCloseTimer?.cancel(); _sheetCloseTimer = null; HapticFeedback.mediumImpact(); diff --git a/lib/features/remote_control/data/datasources/remote_http_datasource.dart b/lib/features/remote_control/data/datasources/remote_http_datasource.dart index 4a21c10d..e808585f 100644 --- a/lib/features/remote_control/data/datasources/remote_http_datasource.dart +++ b/lib/features/remote_control/data/datasources/remote_http_datasource.dart @@ -4,18 +4,19 @@ import 'package:get_it/get_it.dart'; import '../../../../core/consts/http_api_consts.dart'; import '../../../../core/logging/i_logger_service.dart'; +import '../../../../core/logging/control_permission_diagnostics.dart'; import '../../../../core/storage/user_storage.dart'; +import '../../domain/entities/control_permission_failure.dart'; class RemoteHttpDatasource { final Dio _dio; final UserStorage _userStorage; // 🔥 新增字段 final ILoggerService _logger = GetIt.I(); - - RemoteHttpDatasource(this._dio, this._userStorage); + RemoteHttpDatasource(this._dio, this._userStorage); /// 示例:获取控制授权 (对应之前逻辑中的权限申请) -/* Future> requestControlAuth(String robotId) async { + /* Future> requestControlAuth(String robotId) async { try { final response = await _dio.post( '/robot/auth/request', @@ -27,71 +28,92 @@ class RemoteHttpDatasource { } }*/ - - /// 🔥 返回完整权限信息: {hasPermission, owner} - Future> requestRemoteControlViaHttp(String deviceName, String platform) async { - final logPrefix = '🔑 [RemoteHttp][获取权限接口]'; - final user = await _userStorage.getUser(); - if (user == null) { - debugPrint('❌ [RemoteHttp] 用户未登录,无法请求远程控制权限'); - _logger.logWithLevel('❌ [RemoteHttp] 用户未登录,无法请求远程控制权限', shouldLog: true); - return {'hasPermission': false, 'owner': null}; - } - final token = user.token; - - debugPrint('$logPrefix 开始请求远程控制权限 - deviceName: $deviceName, platform: $platform'); - _logger.logWithLevel( - '$logPrefix 开始请求远程控制权限 - deviceName: $deviceName, platform: $platform', - shouldLog: true, - ); - + /// Queries the existing endpoint. Unknown/error responses are not "no permission". + Future> requestRemoteControlViaHttp( + String deviceName, + String platform, + ) async { + final clock = Stopwatch()..start(); try { - final requestData = {'deviceId': deviceName, 'platform': platform}; - debugPrint('$logPrefix 请求地址: POST /forward/device/remoteControl'); - debugPrint('$logPrefix 实际请求体: $requestData'); - _logger.logWithLevel( - '$logPrefix 请求地址: POST /forward/device/remoteControl, 请求体: $requestData', - shouldLog: true, - ); - final response = await _dio.post( - '/forward/device/remoteControl', - options: Options( - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer ${token}', - }, - ), - data: requestData); - - debugPrint("$logPrefix HTTP响应状态码: ${response.statusCode}"); - _logger.logWithLevel("$logPrefix HTTP响应状态码: ${response.statusCode}", shouldLog: true); - - final responseData = response.data as Map; - debugPrint("$logPrefix 完整响应数据:$responseData"); - _logger.logWithLevel("$logPrefix 完整响应数据:$responseData", shouldLog: true); - - // 🔥 关键:先获取响应的 data 字段,再获取 remoteControl 和 owner - final dataField = responseData['data'] as Map?; - if (dataField != null) { - final bool hasRemoteControl = dataField['remoteControl'] as bool? ?? false; - final String? owner = dataField['owner'] as String?; - - debugPrint("$logPrefix 解析成功 - remoteControl=$hasRemoteControl, owner=$owner"); - _logger.logWithLevel( - "$logPrefix 解析成功 - remoteControl=$hasRemoteControl, owner=$owner", - shouldLog: true, - ); - // 🔥 返回完整权限信息 - return {'hasPermission': hasRemoteControl, 'owner': owner}; - } else { - debugPrint("$logPrefix 缺少 data 字段,响应结构异常"); - _logger.logWithLevel("$logPrefix 缺少 data 字段,响应结构异常", shouldLog: true); - return {'hasPermission': false, 'owner': null}; + final user = await _userStorage.getUser(); + if (user == null || user.token.trim().isEmpty) { + throw ControlPermissionFailure('permission_auth_required'); } + ControlPermissionDiagnostics.event('HTTP请求', { + 'method': 'POST', + 'path': '/forward/device/remoteControl', + 'requestDevice': deviceName, + 'platform': platform, + 'authorizationPresent': true, + }); + final response = await _dio.post( + '/forward/device/remoteControl', + options: Options( + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer ' + user.token, + }, + ), + data: {'deviceId': deviceName, 'platform': platform}, + ); + final body = response.data; + final responseData = body is Map ? body['data'] : null; + ControlPermissionDiagnostics.event('HTTP响应', { + 'httpStatus': response.statusCode, + 'durationMs': clock.elapsedMilliseconds, + 'businessCode': ControlPermissionDiagnostics.scalar( + body is Map ? body['code'] : null, + ), + 'dataType': responseData.runtimeType.toString(), + 'remoteControl': ControlPermissionDiagnostics.scalar( + responseData is Map ? responseData['remoteControl'] : null, + ), + 'owner': ControlPermissionDiagnostics.scalar( + responseData is Map ? responseData['owner'] : null, + ), + 'ownerFieldPresent': + responseData is Map && responseData.containsKey('owner'), + }); + if (body is! Map) { + throw ControlPermissionFailure('permission_query_invalid'); + } + final code = body['code']; + if (code != null && code.toString() != '200') { + throw ControlPermissionFailure( + code.toString() == '401' || code.toString() == '403' + ? 'permission_auth_required' + : 'permission_query_rejected', + ); + } + final data = body['data']; + if (data is! Map || + data['remoteControl'] is! bool || + (data['owner'] != null && data['owner'] is! String)) { + throw ControlPermissionFailure('permission_query_invalid'); + } + return {'hasPermission': data['remoteControl'], 'owner': data['owner']}; + } on DioException catch (e) { + ControlPermissionDiagnostics.event('HTTP网络异常', { + 'errorType': e.type.name, + 'httpStatus': e.response?.statusCode, + 'durationMs': clock.elapsedMilliseconds, + }); + if (e.response?.statusCode == 401 || e.response?.statusCode == 403) { + throw ControlPermissionFailure('permission_auth_required'); + } + if (e.type == DioExceptionType.connectionTimeout || + e.type == DioExceptionType.sendTimeout || + e.type == DioExceptionType.receiveTimeout) { + throw ControlPermissionFailure('permission_query_timeout'); + } + throw ControlPermissionFailure('permission_query_failed'); } catch (e) { - debugPrint('$logPrefix 请求远程控制权限失败:$e'); - _logger.logWithLevel('$logPrefix 请求远程控制权限失败:$e', level: 'ERROR', shouldLog: true); - return {'hasPermission': false, 'owner': null}; + ControlPermissionDiagnostics.event('HTTP业务异常', { + 'errorType': e.runtimeType.toString(), + 'feedback': e is ControlPermissionFailure ? e.feedbackKey : null, + 'durationMs': clock.elapsedMilliseconds, + }); + rethrow; } } @@ -116,21 +138,23 @@ class RemoteHttpDatasource { debugPrint('📤 [RemoteHttp] releaseControl 实际请求体: $requestData'); try { final response = await _dio.post( - HttpApiConsts.releaseControlUrl, - options: Options( - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer ${token}', - }, - ), - data: requestData); + HttpApiConsts.releaseControlUrl, + options: Options( + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer ${token}', + }, + ), + data: requestData, + ); final responseData = response.data as Map; debugPrint('📋 [RemoteHttp] releaseControl 响应: $responseData'); if (responseData['code'] == 200) { return true; } debugPrint( - '⚠️ [RemoteHttp] releaseControl 返回 code=${responseData['code']},释放未成功'); + '⚠️ [RemoteHttp] releaseControl 返回 code=${responseData['code']},释放未成功', + ); return false; } catch (e) { debugPrint('❌ [RemoteHttp] releaseControl 请求失败:$e'); @@ -138,5 +162,4 @@ class RemoteHttpDatasource { return false; } } - } diff --git a/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart b/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart index f745f2ee..a4eb069d 100644 --- a/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart +++ b/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart @@ -6,10 +6,12 @@ import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import '../../../../core/logging/i_logger_service.dart'; +import '../../../../core/logging/control_permission_diagnostics.dart'; import '../../../../core/network/protocol_decoder.dart'; import '../../../../core/network/tcp/tcp_client.dart'; import '../../../../core/protocol/machine_protocol_constants.dart'; import '../../../../core/storage/user_storage.dart'; +import '../../domain/entities/control_permission_failure.dart'; /// 远程遥控 TCP 数据源 /// 负责通过 TCP 协议发送控制指令和权限请求 @@ -20,82 +22,68 @@ class RemoteTcpDatasource { RemoteTcpDatasource(this._tcpClient, this._userStorage); - /// 发送 switch_control 权限请求(对应 Android 的 requestSwitchControl) - /// - /// 这是获取设备控制权的第一步: - /// 1. 先发送 TCP 0x12 指令携带 switch_control 请求 - /// 2. 等待服务端响应 - /// 3. 再调用 HTTP API 确认控制权 - Future sendSwitchControlRequest(String deviceName) async { + /// Sends the existing 0x12 request, with no protocol changes. + Future sendSwitchControlRequest( + String deviceName, { + bool Function()? isCurrent, + }) async { + ControlPermissionDiagnostics.event('TCP申请检查', { + 'device': deviceName, + 'tcpConnected': _tcpClient.isConnected, + }); if (!_tcpClient.isConnected) { - debugPrint('❌sendSwitchControlRequest [TCP] 无法发送权限请求:Socket 未连接'); - throw Exception('sendSwitchControlRequest TCP 未连接'); + throw ControlPermissionFailure('permission_tcp_disconnected'); } - + final user = await _userStorage.getUser(); + if (isCurrent != null && !isCurrent()) { + ControlPermissionDiagnostics.event('TCP申请取消', {'reason': '获取用户信息后申请已失效'}); + return; + } + if (user == null || user.token.trim().isEmpty) { + throw ControlPermissionFailure('permission_auth_required'); + } + if (!_tcpClient.isConnected) { + throw ControlPermissionFailure('permission_tcp_disconnected'); + } + final request = { + 'request': 'switch_control', + 'deviceId': deviceName, + 'userId': user.username, + 'platform': 'app', + 'token': user.token, + }; + final packet = buildSwitchControlPacket(utf8.encode(jsonEncode(request))); + ControlPermissionDiagnostics.event('TCP申请构造完成', { + 'cmd': '0x12', + 'request': 'switch_control', + 'device': deviceName, + 'platform': 'app', + 'tokenPresent': user.token.isNotEmpty, + 'packetBytes': packet.length, + }); try { - // 获取用户信息 - final user = await _userStorage.getUser(); - if (user == null || user.token == null) { - debugPrint( - '❌ sendSwitchControlRequest[TCP] 认证失败:用户未登录或 Token 为空,无法发送认证包', - ); - throw Exception('用户未登录或 Token 无效'); - } - - final username = user.username; - final token = user.token; - final currentDeviceId = deviceName; - - // 构造 JSON 请求体(参考 Android 代码) - final request = { - 'request': 'switch_control', - 'deviceId': currentDeviceId, - 'userId': username, - 'platform': 'app', - 'token': token, - }; - - final jsonStr = jsonEncode(request); - final jsonBytes = utf8.encode(jsonStr); - - debugPrint('sendSwitchControlRequest[TCP] 发送权限请求指令:$jsonStr'); + await _tcpClient + .sendPermissionPacket(packet) + .timeout(const Duration(seconds: 5)); + ControlPermissionDiagnostics.event('TCP申请本地完成', { + 'serverReceiptConfirmed': false, + 'note': '仅本地写入和flush完成,等待授权回包', + }); _logger.logWithLevel( - '🔑 [TCP][获取权限] 发送权限请求指令:$jsonStr', - shouldLog: true, - ); - - // 使用 0x12 指令发送(cmdGetAuth) - // 注意:根据你的协议文档,这里可能是 0x04 或 0x12 - // Android 代码中使用的是 0x12 - // _tcpClient.sendnew( - // // MachineProtocolConstants.cmdGetAuth, // 0x04 或 0x12,根据实际协议调整 - // jsonBytes, - // ); - // 构造完整的协议包 - final packet = buildSwitchControlPacket(jsonBytes); - - debugPrint( - 'sendSwitchControlRequest[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}', - ); - - // 发送数据包 - _tcpClient.sendnew(packet); - - debugPrint( - '✅ sendSwitchControlRequest[TCP] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})', - ); - _logger.logWithLevel( - '✅ [TCP][获取权限] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})', + '[ControlPermission] local socket write completed device=' + + deviceName + + ' cmd=0x12 bytes=' + + packet.length.toString() + + '; server/Web receipt unconfirmed', shouldLog: true, ); } catch (e) { - debugPrint('❌ sendSwitchControlRequest[TCP] 发送权限请求失败:$e'); - _logger.logWithLevel( - '❌ [TCP][获取权限] 发送权限请求失败:$e', - level: 'ERROR', - shouldLog: true, - ); - rethrow; + ControlPermissionDiagnostics.event('TCP申请本地异常', { + 'errorType': e.runtimeType.toString(), + 'delivery': 'unknown', + }); + // A partial write may already have reached the peer; do not claim "not sent". + throw ControlPermissionFailure('permission_send_uncertain'); } } @@ -129,9 +117,7 @@ class RemoteTcpDatasource { // TODO: 同意授权和拒绝授权 void sendSwitchControlResponse(bool agreed, String deviceId) { - debugPrint( - '📤 [进入了TCP层==== 被调用 - agreed=$agreed, deviceId=$deviceId', - ); + debugPrint('📤 [进入了TCP层==== 被调用 - agreed=$agreed, deviceId=$deviceId'); // 🔥 添加详细的连接状态日志 debugPrint( @@ -177,7 +163,10 @@ class RemoteTcpDatasource { // 构造完整的协议包 final packet = buildSwitchControlPacket(jsonBytes); - _logger.logWithLevel('TCP DataSource] JSON 数据: $jsonStr' ,shouldLog: true); + _logger.logWithLevel( + 'TCP DataSource] JSON 数据: $jsonStr', + shouldLog: true, + ); debugPrint( '📦 [TCP DataSource] 完整数据包(${packet.length}字节): ${packet.map((b) => '0x${b.toRadixString(16).padLeft(2, "0")}').join(' ')}', diff --git a/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart b/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart index 0bb75221..dcf713c5 100644 --- a/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart +++ b/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart @@ -1,9 +1,11 @@ import 'dart:async'; +import 'dart:typed_data'; import 'package:flutter/foundation.dart'; import 'package:get_it/get_it.dart'; import '../../../../core/logging/i_logger_service.dart'; +import '../../../../core/logging/remote_control_diagnostics.dart'; import '../../../../core/network/protocol_decoder.dart'; import '../../../../core/network/tcp/tcp_client.dart'; import '../../../../core/protocol/machine_protocol_codec.dart'; @@ -34,10 +36,14 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository { } @override - bool sendControlMachineCmd(MachineControlStatusEntity status) { - // 🔥 整个“换算 + 编码 + 写 socket”都包在 try 里:本方法被 200ms 控制循环 + Future sendControlMachineCmd( + MachineControlStatusEntity status, { + bool priority = false, + bool Function()? isCurrent, + }) async { + // 🔥 整个“换算 + 编码 + 写 socket”都包在 try 里:本方法被 250ms 控制循环 // 和停止风暴(一次 30 帧)高频调用,任何一帧抛异常都会变成 Timer 回调 - // 里的未捕获异常(每 200ms 刷一次),更糟的是会让 stopAllMovement 的 + // 里的未捕获异常(每 250ms 刷一次),更糟的是会让 stopAllMovement 的 // 停止帧中途断掉——车就停不下来。失败一律返回 false,由调用方统计 // “一共出网了几帧”(控制循环里本来就不关心返回值)。 try { @@ -56,6 +62,26 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository { emergency: status.isEmergency ? 1 : 0, ); + try { + final encoded = ByteData.sublistView(payload); + RemoteControlDiagnostics.instance.event('conversion', { + 'x': status.originX, + 'y': status.originY, + 'linearMps': linear, + 'angularRadps': angular, + 'encodedLinearMps': encoded.getFloat64(0, Endian.little), + 'encodedAngularRadps': encoded.getFloat64(8, Endian.little), + 'payloadBytes': payload.length, + 'payloadHex': _hex(payload), + 'lift': status.chassisLift, + 'mower': status.mowerSpeed, + 'ignition': status.ignitionStatus, + 'emergency': status.isEmergency, + }); + } catch (_) { + // Observing the encoded payload cannot prevent its transmission. + } + // 联调日志:三段式打印 ①滑块/摇杆原始数据 ②乘完系数的发送值 ③包装后的整帧字节(联调结束可移除) _logger.logWithLevel( '🔗 [联调-0x00] 遥控发送明细\n' @@ -73,9 +99,10 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository { // 3. 调用 TcpClient 发送指令 // 🔥 把写入结果如实上抛:false 代表本帧没交给系统 socket(未连接/写入异常), // 调用方(尤其 stopAllMovement 的停止风暴)需要知道“发出去了几个”。 - return _tcpClient.sendRaw( - MachineProtocolConstants.cmdRemoteControl, + return await _tcpClient.sendControlPayload( payload, + priority: priority, + isCurrent: isCurrent, ); } catch (e, s) { debugPrint('❌ [RemoteControl] 遥控指令构造/发送异常: $e'); @@ -96,63 +123,19 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository { Stream get responseStream => _tcpClient.packetStream; @override - void sendTcpPermissionRequest(String deviceName) { - // 🔥 RemoteTcpDatasource.sendSwitchControlRequest 在 TCP 未连接时是 throw 的, - // 而本方法是在 requestControlPermissionS 的 result.fold(async 回调) 里调的: - // fold 不会 await 那个回调的 Future,异常从这条路径出去就是彻底的未捕获 - // 异步异常(点“获取控制权”时断着 TCP 就会撞上)。抢占请求发不出去最坏 - // 只是等不到 0x12 回包,不该崩,故就地吞掉并留 ERROR 痕迹。 - try { - _remoteTcp.sendSwitchControlRequest(deviceName); - _logger.logWithLevel( - '🔑 [RemoteControl] TCP已发送权限请求', - shouldLog: true, - ); - } catch (e) { - debugPrint('❌ [RemoteControl] TCP 权限请求发送失败: $e'); - _logger.logWithLevel( - '❌ [RemoteControl] TCP 权限请求发送失败(未连接): $e', - level: 'ERROR', - shouldLog: true, - ); - } + Future sendTcpPermissionRequest( + String deviceName, { + bool Function()? isCurrent, + }) async { + // Await the actual write so failures reach the request UI. + await _remoteTcp.sendSwitchControlRequest(deviceName, isCurrent: isCurrent); } @override Future> requestControlPermission( String deviceName, String deviceId, - ) async { - try { - // 1. 先发送 HTTP 权限请求检查权限 - _logger.logWithLevel( - '🔑 [RemoteControl] 检查 HTTP 权限... deviceName=$deviceName, platform=$deviceId', - shouldLog: true, - ); - final result = await _remoteHttp.requestRemoteControlViaHttp( - deviceName, - deviceId, - ); - - // 2. 如果没有权限或权限为 null,才发送 TCP 请求 - final hasPermission = result['hasPermission'] as bool? ?? false; - _logger.logWithLevel( - '🔑 [RemoteControl] HTTP权限查询结果: hasPermission=$hasPermission, owner=${result['owner']}', - shouldLog: true, - ); - if (!hasPermission) { - _logger.logWithLevel('🔑 [RemoteControl] 无权限,发送 TCP 权限请求', shouldLog: true); - _remoteTcp.sendSwitchControlRequest(deviceName); - } else { - _logger.logWithLevel('✅ [RemoteControl] 已有权限,无需 TCP 请求', shouldLog: true); - } - - return result; - } catch (e) { - _logger.logWithLevel('❌ [RemoteControl] 权限请求失败:$e', level: 'ERROR', shouldLog: true); - rethrow; - } - } + ) => _remoteHttp.requestRemoteControlViaHttp(deviceName, deviceId); @override void respondPermission(bool agreed, String deviceId) { diff --git a/lib/features/remote_control/domain/entities/control_permission_failure.dart b/lib/features/remote_control/domain/entities/control_permission_failure.dart new file mode 100644 index 00000000..9cbf7410 --- /dev/null +++ b/lib/features/remote_control/domain/entities/control_permission_failure.dart @@ -0,0 +1,11 @@ +import '../../../../core/error/failure.dart'; + +/// A local failure classification; never adds fields to the wire protocol. +class ControlPermissionFailure extends Failure implements Exception { + final String feedbackKey; + + ControlPermissionFailure(this.feedbackKey) : super(feedbackKey); + + @override + String toString() => feedbackKey; +} diff --git a/lib/features/remote_control/domain/entities/machine_control_status_entity.dart b/lib/features/remote_control/domain/entities/machine_control_status_entity.dart index 5389b9b0..9f6cf3e5 100644 --- a/lib/features/remote_control/domain/entities/machine_control_status_entity.dart +++ b/lib/features/remote_control/domain/entities/machine_control_status_entity.dart @@ -4,7 +4,7 @@ class MachineControlStatusEntity extends Equatable { final int originX; final int originY; final int chassisLift; // 0:停, 1:上, 2:下 - final int mowerSpeed; // 0:停, 1:+, 2:- + final int mowerSpeed; // 0:关闭, 1:开启, 2:不操作 final int ignitionStatus; // 0:停, 1:火, 2:熄 final bool isEmergency; @@ -12,7 +12,7 @@ class MachineControlStatusEntity extends Equatable { this.originX = 0, this.originY = 0, this.chassisLift = 0, - this.mowerSpeed = 0, + this.mowerSpeed = 2, this.ignitionStatus = 0, this.isEmergency = false, }); diff --git a/lib/features/remote_control/domain/repositories/remote_control_repository.dart b/lib/features/remote_control/domain/repositories/remote_control_repository.dart index 94b60ad3..fd75bdb4 100644 --- a/lib/features/remote_control/domain/repositories/remote_control_repository.dart +++ b/lib/features/remote_control/domain/repositories/remote_control_repository.dart @@ -2,13 +2,16 @@ import '../../../../core/network/protocol_decoder.dart'; import '../../domain/entities/machine_control_status_entity.dart'; abstract class RemoteControlRepository { - /// 高频发送遥控指令 (被 Cubit 的 200ms 定时器调用) + /// 高频发送遥控指令 (被 Cubit 的 250ms 定时器调用) /// 负责将 Entity 转换为底层的 0x00 指令并发出 /// - /// 返回 `false` = 本帧未交给系统 socket(未连接或写入失败)。 - /// 🔥 安全路径(stopAllMovement / 急停帧)必须据此判断指令是否真出网, - /// 不可再假定「调用了就等于设备收到了」。 - bool sendControlMachineCmd(MachineControlStatusEntity status); + /// All 0x00 frames share the >=250ms sender. False also includes a stale or + /// superseded request; success is local completion, never a machine ACK. + Future sendControlMachineCmd( + MachineControlStatusEntity status, { + bool priority = false, + bool Function()? isCurrent, + }); /// 暴露解析后的回包流 (如 0x12 权限申请) /// UI 或 Cubit 监听此流来处理机器人主动推送的消息 @@ -19,10 +22,16 @@ abstract class RemoteControlRepository { /// 新增:请求控制权限 (HTTP接口返回完整权限信息) /// 返回: {hasPermission: bool, owner: String?} - Future> requestControlPermission(String deviceName, String deviceId); + Future> requestControlPermission( + String deviceName, + String deviceId, + ); /// 🔥 新增: 发送 TCP 0x12 权限请求指令 - void sendTcpPermissionRequest(String deviceName); + Future sendTcpPermissionRequest( + String deviceName, { + bool Function()? isCurrent, + }); /// 新增:响应控制权限 同意和拒绝(发送 0x05 指令) void respondPermission(bool bool, String deviceId); diff --git a/lib/features/remote_control/domain/usecase/request_control_permission_usecase.dart b/lib/features/remote_control/domain/usecase/request_control_permission_usecase.dart index d1c53661..c52fe014 100644 --- a/lib/features/remote_control/domain/usecase/request_control_permission_usecase.dart +++ b/lib/features/remote_control/domain/usecase/request_control_permission_usecase.dart @@ -4,24 +4,31 @@ import 'package:maibu_satabot_v2/core/error/failure.dart'; import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart'; import '../repositories/remote_control_repository.dart'; +import '../entities/control_permission_failure.dart'; -class RequestControlPermissionUseCase extends BaseUseCase, RequestControlPermissionParams> { +class RequestControlPermissionUseCase + extends BaseUseCase, RequestControlPermissionParams> { final RemoteControlRepository repository; RequestControlPermissionUseCase(this.repository); @override - Future>> call(RequestControlPermissionParams params) async { + Future>> call( + RequestControlPermissionParams params, + ) async { debugPrint( '🔑 [权限链][UseCase] 开始执行请求 - deviceName: ${params.deviceName}, platform: ${params.deviceId}', ); try { - final result = await repository.requestControlPermission(params.deviceName, params.deviceId); + final result = await repository.requestControlPermission( + params.deviceName, + params.deviceId, + ); debugPrint('🔑 [权限链][UseCase] 请求成功,返回: $result'); return right(result); } catch (e) { debugPrint('❌ [权限链][UseCase] 请求异常: $e'); - return left(Failure(e.toString())); + return left(e is ControlPermissionFailure ? e : Failure(e.toString())); } } } @@ -34,4 +41,4 @@ class RequestControlPermissionParams { required this.deviceName, required this.deviceId, }); -} \ No newline at end of file +} diff --git a/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart b/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart index b0eec3c0..a5d6b60b 100644 --- a/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart +++ b/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart @@ -9,6 +9,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:get_it/get_it.dart'; import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/network/tcp/control_frame_scheduler.dart'; import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; @@ -20,17 +21,24 @@ import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_ import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart'; import '../../../../core/logging/i_logger_service.dart'; +import '../../../../core/logging/control_permission_diagnostics.dart'; +import '../../../../core/logging/remote_control_diagnostics.dart'; +import '../../domain/usecase/diff_steer_usecase.dart'; import '../../../../core/network/net_message_dispatcher.dart'; import '../../../devices/domain/entities/running_status_entity.dart'; import '../../data/reverse_camera_source.dart'; import '../../domain/entities/machine_control_status_entity.dart'; +import '../../domain/entities/control_permission_failure.dart'; import '../../domain/entities/reverse_camera_data.dart'; import '../../domain/repositories/remote_control_repository.dart'; import '../../domain/usecase/remote_control_usecase.dart'; +import '../../../device_emergency_stop/domain/entities/emergency_stop_target.dart'; +import '../../../device_emergency_stop/domain/entities/emergency_stop_failure.dart'; +import '../../../device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart'; /// 远程控制核心 Cubit(全局单例,极简模式远程遥控页与新版 HUD 共用)。 /// -/// 🔥 自带前后台生命周期([WidgetsBindingObserver]):200ms 控制循环是 Dart VM 层的 +/// 🔥 自带前后台生命周期([WidgetsBindingObserver]):250ms 控制循环是 Dart VM 层的 /// Timer,退后台 / 锁屏后照旧跟发,而 main.dart 的全局回调只管会话标记与 TCP /// 重连、不碰循环,所以“切后台那一刻手指还压在摇杆上”就会留下非零轴值; /// 回前台 TCP 重连后车能自己走。本类自己接管:退后台挂起循环 + 归零, @@ -39,9 +47,30 @@ class RemoteControlCubit extends Cubit with WidgetsBindingObserver { final RemoteControlRepository _repository; final RequestControlPermissionUseCase _requestControlPermissionUseCase; + final RequestDeviceEmergencyStopUseCase _requestEmergencyStop; + Timer? _emergencyStatusTimer; + final DateTime Function() _emergencyNow; + static const emergencyStatusMaxAge = Duration(seconds: 10); + int _emergencyAttempt = 0; final DeviceRepository _deviceRepository; // 🔥 注入设备仓库 final TcpClient tcpClient; // 🔥 注入TCP客户端 + /// 只读复用既有连接,供顶部指示灯和操作提示使用。 + bool get isControlLinkConnected => tcpClient.isConnected; + late final Stream serverHeartbeats = tcpClient.packetStream + .where((packet) => packet.command == 0xFF) + .map((_) {}); Timer? _timer; + Timer? _permissionWaitTimer; + int _permissionAttempt = 0; + int _permissionRequestId = 0; + Map _permissionTrace = const {}; + bool _permissionSessionActive = false; + bool _permissionManual = false; + + // All timers/identifiers here are local; the 0x12 wire format is unchanged. + static const _permissionQueryTimeout = Duration(seconds: 10); + static const _permissionSendTimeout = Duration(seconds: 6); + static const _permissionResponseTimeout = Duration(seconds: 10); StreamSubscription? _kickOutSub; // 新增:用于管理监听生命周期 final NetMessageDispatcher dispatcher; final DeviceStatusBloc deviceStatusBloc; // 🔥 注入 DeviceStatusBloc @@ -54,6 +83,63 @@ class RemoteControlCubit extends Cubit // 🔥 参考Android版:使用成员变量存储摇杆值,避免state竞态 int _currentOriginX = 0; int _currentOriginY = 0; + int _motionGeneration = 0; + int _diagnosticLoop = 0; + int _diagnosticStop = 0; + int _diagnosticActiveStops = 0; + int? _diagnosticInputUs; + + Future _sendMotionFrame( + MachineControlStatusEntity frame, + String source, [ + Map details = const {}, + ]) { + final trace = RemoteControlDiagnostics.instance; + final generation = _motionGeneration; + final deviceName = state.targetDevice?.deviceName; + final priority = source != 'loop'; + return trace.frame( + source, + { + 'device': state.targetDevice?.deviceName, + 'loop': _diagnosticLoop, + 'inputAgeUs': _diagnosticInputUs == null + ? null + : trace.elapsedUs - _diagnosticInputUs!, + 'x': frame.originX, + 'y': frame.originY, + 'activeStops': _diagnosticActiveStops, + 'permissionId': _permissionTrace['permissionId'], + 'permissionAtEnqueue': state.hasPermission, + 'permissionPhase': state.permissionRequestPhase.name, + ...details, + }, + () async { + final result = await _repository.sendControlMachineCmd( + frame, + priority: priority, + isCurrent: () => + !isClosed && + deviceName != null && + (state.targetDevice?.deviceName == deviceName || + (priority && state.targetDevice == null)) && + (priority || + (generation == _motionGeneration && + _controlWanted && + !_suspendedByLifecycle && + state.hasPermission && + !state.isLocked && + !state.isEmergencyRequestPending && + !state.isEmergency)), + ); + trace.event('repository_result', { + 'returned': result, + 'priority': priority, + }); + return result; + }, + ); + } /// 业务侧是否期望处于“控制态”:[startControlLoop] 置真、[stopControlLoop] 置假。 /// 它代表“意图”,与定时器的实时存在与否解耦:被后台挂起时仍为真, @@ -87,18 +173,26 @@ class RemoteControlCubit extends Cubit this._deviceRepository, // 🔥 注入 this.tcpClient, // 🔥 注入TCP客户端 this.dispatcher, - this.deviceStatusBloc, // 🔥 注入 - ) : super( - RemoteControlState( - controlEntity: MachineControlStatusEntity(), - runningStatusModel: RunningStatusModel(), - ), - ) { + this.deviceStatusBloc, { // 🔥 注入 + required RequestDeviceEmergencyStopUseCase requestEmergencyStop, + DateTime Function()? emergencyNow, + }) : _requestEmergencyStop = requestEmergencyStop, + _emergencyNow = emergencyNow ?? DateTime.now, + super( + RemoteControlState( + controlEntity: MachineControlStatusEntity(), + runningStatusModel: RunningStatusModel(), + ), + ) { _initPacketListener(); // 🔥 门槛(hasReceivedStatusPush)与电压/电量/控制模式改由 TCP 0x02 驱动, // 与 MQTT 定位链路解耦;MQTT(DeviceStatusBloc) 仅继续负责定位。 // 回滚:注释下行、改回 _initDeviceStatusListener() 即可。 _initTcpStatusListener(); + _emergencyStatusTimer = Timer.periodic( + const Duration(seconds: 1), + (_) => refreshEmergencyStatus(), + ); // _initDeviceStatusListener(); // 🔥 旧:订阅 DeviceStatusBloc(MQTT),已停用 // 生命周期观察与本类同生同灭(close() 里成对移除):单例常驻, // 不挂在某个页面上,所以从别的路径进控态也能被护住。 @@ -175,64 +269,64 @@ class RemoteControlCubit extends Cubit _tcpStatusSub = tcpClient.packetStream .where((p) => p.command == 0x02) .listen((packet) async { - try { - final message = utf8.decode(packet.payload, allowMalformed: true); - if (message.trim().isEmpty) return; + try { + final message = utf8.decode(packet.payload, allowMalformed: true); + if (message.trim().isEmpty) return; - final fields = message.trim().split(','); - if (fields.length < 18) { - debugPrint('⚠️ [TCP-0x02门槛] 字段不足:${fields.length},期望≥18,跳过'); - return; - } + final fields = message.trim().split(','); + if (fields.length < 18) { + debugPrint('⚠️ [TCP-0x02门槛] 字段不足:${fields.length},期望≥18,跳过'); + return; + } - final status = RunningStatusEntity.fromFields(fields); - // 只存协议原始值('3'=远程/'0'=本地等),展示文案由 UI 按当前语言翻译 - final controlMode = status.controlMode; + final status = RunningStatusEntity.fromFields(fields); + // 只存协议原始值('3'=远程/'0'=本地等),展示文案由 UI 按当前语言翻译 + final controlMode = status.controlMode; - // 🔥 门槛:收到 TCP 0x02 即视为推送活跃(节流前刷新,轻量无阻塞) - _lastStatusPushTime = DateTime.now(); + // 🔥 门槛:收到 TCP 0x02 即视为推送活跃(节流前刷新,轻量无阻塞) + _lastStatusPushTime = DateTime.now(); - _cacheVoltage = status.voltage.toString(); - _cacheBattery = status.battery; - _cacheCtrlMode = controlMode; + _cacheVoltage = status.voltage.toString(); + _cacheBattery = status.battery; + _cacheCtrlMode = controlMode; - // 500ms节流,不到时间不刷新UI - final now = DateTime.now(); - if (_lastUiUpdateTime != null && - now.difference(_lastUiUpdateTime!) < - const Duration(milliseconds: 500)) { - // 节流期间仍需保证门槛标志已置位(否则首帧恰逢节流会导致门槛漏置) - if (!state.hasReceivedStatusPush && !isClosed) { - emit(state.copyWith(hasReceivedStatusPush: true)); + // 500ms节流,不到时间不刷新UI + final now = DateTime.now(); + if (_lastUiUpdateTime != null && + now.difference(_lastUiUpdateTime!) < + const Duration(milliseconds: 500)) { + // 节流期间仍需保证门槛标志已置位(否则首帧恰逢节流会导致门槛漏置) + if (!state.hasReceivedStatusPush && !isClosed) { + emit(state.copyWith(hasReceivedStatusPush: true)); + } + return; + } + _lastUiUpdateTime = now; + + // 🔥 ping 只在真正刷新UI时测(≤2Hz):0x02 原始推送可能高频, + // 若每帧 await getNetworkDelay 会造成大量并发 ping,移到节流后规避。 + final c = await getNetworkDelay(); + _cachePing = c; + + if (!isClosed) { + emit( + state.copyWith( + runningStatusModel: state.runningStatusModel.copyWith( + voltage: _cacheVoltage, + battery: _cacheBattery, + controlMode: _cacheCtrlMode, + ), + battery: int.tryParse(_cacheBattery ?? '') ?? 0, + ping: _cachePing, + hasReceivedStatusPush: true, // 🔥 门槛:TCP 0x02 到达即置位 + updateType: 'device_status', + ), + ); + } + } catch (e) { + debugPrint('❌ [TCP-0x02门槛] 解析异常:$e'); } - return; - } - _lastUiUpdateTime = now; - - // 🔥 ping 只在真正刷新UI时测(≤2Hz):0x02 原始推送可能高频, - // 若每帧 await getNetworkDelay 会造成大量并发 ping,移到节流后规避。 - final c = await getNetworkDelay(); - _cachePing = c; - - if (!isClosed) { - emit( - state.copyWith( - runningStatusModel: state.runningStatusModel.copyWith( - voltage: _cacheVoltage, - battery: _cacheBattery, - controlMode: _cacheCtrlMode, - ), - battery: int.tryParse(_cacheBattery ?? '') ?? 0, - ping: _cachePing, - hasReceivedStatusPush: true, // 🔥 门槛:TCP 0x02 到达即置位 - updateType: 'device_status', - ), - ); - } - } catch (e) { - debugPrint('❌ [TCP-0x02门槛] 解析异常:$e'); - } - }); + }); } // 🔥 超简单方法:传入 IP,得到 ping 值 @@ -351,6 +445,7 @@ class RemoteControlCubit extends Cubit _kickOutSub?.cancel(); // 防止重复监听 _kickOutSub = dispatcher.onCommand(0x12).listen((packet) { + _tracePermission('0x12到达', {'payloadBytes': packet.payload.length}); final timeNow = _getTimePrefix(); debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ✅ 收到 0x12 原始包'); /* debugPrint( @@ -361,99 +456,43 @@ class RemoteControlCubit extends Cubit shouldLog: true, ); - // 先解析JSON判断是否为响应格式 - String jsonStringForCheck; try { - if (packet.payload.length > 2) { - jsonStringForCheck = utf8.decode( - packet.payload.sublist(0, packet.payload.length - 2), + // The existing decoder includes CRC bytes in payload. Accept the same + // JSON without CRC as well, so a malformed variant is not misclassified. + dynamic jsonMap; + try { + jsonMap = jsonDecode( + utf8.decode(packet.payload.sublist(0, packet.payload.length - 2)), ); - } else { - jsonStringForCheck = utf8.decode(packet.payload); + } catch (_) { + jsonMap = jsonDecode(utf8.decode(packet.payload)); } - final jsonMap = jsonDecode(jsonStringForCheck); - final respondData = jsonMap['respond']; - - // 如果是响应格式,继续处理(更新权限状态) - // 如果是请求格式且弹窗已显示,忽略 - if (respondData == null && state.showPermissionRequestDialog) { - debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ⚠️ 弹窗已显示(状态),忽略请求'); + if (jsonMap is! Map) { + _tracePermission('忽略0x12', {'reason': 'JSON顶层不是对象'}); return; } - } catch (e) { - // 解析失败,继续处理 - } - - try { - // 🔥 关键:手动去掉最后 2 个 CRC 字节 - String jsonString; - if (packet.payload.length > 2) { - jsonString = utf8.decode( - packet.payload.sublist(0, packet.payload.length - 2), - ); - } else { - jsonString = utf8.decode(packet.payload); - } - - debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] JSON内容: $jsonString'); - _logger.logWithLevel( - '$timeNow 🔍 [RemoteControl] [0x12监听器] 去除CRC后的JSON: $jsonString', - shouldLog: true, - ); - - final jsonMap = jsonDecode(jsonString); - - // 🔥 区分两种数据格式 final requestType = jsonMap['request']; final platform = jsonMap['platform']; final respondData = jsonMap['respond']; - - debugPrint( - '$timeNow 🔍 [RemoteControl] [0x12监听器] requestType: $requestType, platform: $platform, hasRespond: ${respondData != null}', - ); + _tracePermission('0x12解析完成', { + 'requestType': requestType, + 'responsePresent': respondData is Map, + 'responseDevice': respondData is Map ? respondData['deviceId'] : null, + 'switchResult': respondData is Map + ? respondData['switchResult'] + : null, + 'holder': respondData is Map ? respondData['holder'] : null, + 'requestDevice': jsonMap['deviceId'], + 'requestPlatform': platform, + }); + if (respondData == null && state.showPermissionRequestDialog) { + _tracePermission('忽略0x12', {'reason': '交接弹窗已显示,忽略重复请求'}); + return; + } // 情况 1: 响应格式 - {"respond":{"switchResult":true,"deviceId":"...","holder":"you"}} - if (respondData != null && respondData is Map) { - // 🔥 收到响应格式,更新权限状态 - - final switchResult = respondData['switchResult']; - /* debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] 📊 收到切换结果响应'); - debugPrint( - '$timeNow 🔍 [RemoteControl] [0x12监听器] switchResult: $switchResult', - );*/ - _logger.logWithLevel( - '$timeNow 🔍 [RemoteControl] [0x12监听器] 📊 收到切换结果响应 - switchResult: $switchResult', - shouldLog: true, - ); - - if (!isClosed) { - if (switchResult == true) { - // 切换成功,当前 APP 获得控制权 - debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ✅ APP获得控制权'); - debugPrint( - '$timeNow 🔍 [RemoteControl] [0x12监听器] 设置 hasPermission = true', - ); - emit(state.copyWith(hasPermission: true)); - } else { - // 切换失败或拒绝,APP 失去控制权 - debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ❌ APP失去控制权'); - debugPrint( - '$timeNow 🔍 [RemoteControl] [0x12监听器] 设置 hasPermission = false', - ); - emit( - state.copyWith( - hasPermission: false, - // 🔥 修复:不强制关闭弹窗,让弹窗由用户操作控制 - ), - ); - // 🔥 失权即归零 + 补发全停:控制循环只是“跳过发送”, - // _currentOriginX/Y 会原样留着;只改 hasPermission 的话,重新 - // 拿回控制权的那一 tick 就会按失权前的推量原地发车。而且设备只认 - // “最后收到的运动帧”,光清本地值不会让已在跑的车停下 —— - // 故用 stopAllMovement(它的停止帧无视权限强制发送)。 - unawaited(stopAllMovement()); - } - } + if (respondData is Map) { + _handlePermissionResult(respondData); } // 情况 2: 请求格式 - {"request":"switch_control","deviceId":"...","platform":"web",...} else if (requestType == 'switch_control') { @@ -537,14 +576,16 @@ class RemoteControlCubit extends Cubit else if (requestType == 'have_logged_in') { // 🔥 关键修复:检查是否是自身 0x03 认证触发的 if (tcpClient.isOwnAuthTriggeredKick()) { - debugPrint('${_getTimePrefix()} 🛡️ [RemoteControl] 自身认证触发的 have_logged_in,忽略'); + debugPrint( + '${_getTimePrefix()} 🛡️ [RemoteControl] 自身认证触发的 have_logged_in,忽略', + ); _logger.logWithLevel( '${_getTimePrefix()} 🛡️ [RemoteControl] 自身认证触发的 have_logged_in,忽略', shouldLog: true, ); return; } - + debugPrint('${_getTimePrefix()} ⚠️ [RemoteControl] 检测到真正的异地登录'); _logger.logWithLevel( '${_getTimePrefix()} ⚠️ [RemoteControl] 检测到异地登录,打开弹窗提示', @@ -562,6 +603,10 @@ class RemoteControlCubit extends Cubit ); } } catch (e) { + _tracePermission('0x12解析失败', { + 'errorType': e.runtimeType.toString(), + 'payloadBytes': packet.payload.length, + }); debugPrint('${_getTimePrefix()} ❌ [RemoteControl] 解析失败:$e'); _logger.logWithLevel( '${_getTimePrefix()} ❌ [RemoteControl] 解析失败:$e', @@ -571,7 +616,7 @@ class RemoteControlCubit extends Cubit }); } - // 2. 开启 200ms 控制循环 (在进入遥控页面或点击“开始”时调用) + // 2. 开启 250ms 控制循环 (在进入遥控页面或点击“开始”时调用) /* void startControlLoop() { _timer?.cancel(); _timer = Timer.periodic(const Duration(milliseconds: 100), (timer) { @@ -594,7 +639,13 @@ class RemoteControlCubit extends Cubit /// 🔥 双轴归零(静默):只清本地摇杆值并同步 UI,**不发停止帧**。 /// 需要连发停止帧压住 TCP 积压时用 [stopAllMovement];这里用于“只是不能让 /// 残留值下次复活”的场景(失权 / 急停 / 进控态)。 - void _zeroAxesQuietly() { + void _zeroAxesQuietly({String reason = 'unspecified'}) { + _motionGeneration++; + RemoteControlDiagnostics.instance.event('axes_zero', { + 'reason': reason, + 'beforeX': _currentOriginX, + 'beforeY': _currentOriginY, + }); if (isClosed) return; if (_currentOriginX == 0 && _currentOriginY == 0) return; _currentOriginX = 0; @@ -629,7 +680,8 @@ class RemoteControlCubit extends Cubit ); // best-effort:socket 已被冻住时这些帧会被 sendRaw 如实判为失败(已有节流日志), // 但本地轴值已归零,回前台重启循环也只会发零速帧。 - unawaited(stopAllMovement()); + unawaited(stopAllMovement(reason: 'background')); + unawaited(RemoteControlDiagnostics.instance.flush()); } /// 🔥 回前台恢复控制循环:仅当业务侧仍处于控制态。 @@ -677,6 +729,28 @@ class RemoteControlCubit extends Cubit void startControlLoop({bool resetAxes = true}) { // 🔥 已 close 的循环既不该起也不该写状态(定时器 tick 里另有 isClosed 兜底)。 if (isClosed) return; + final trace = RemoteControlDiagnostics.instance; + if (trace.activeDevice == null || resetAxes) { + trace.begin(state.targetDevice?.deviceName, { + 'intervalMs': ControlFrameScheduler.interval.inMilliseconds, + 'allControlFramesMinIntervalMs': + ControlFrameScheduler.interval.inMilliseconds, + 'sender': 'shared_latest_with_priority_stop', + 'algorithm': 'linear_angular', + 'maxLinearMps': DiffSteerUseCase.maxLinearSpeed, + 'maxAngularRadps': DiffSteerUseCase.maxAngularSpeed, + 'stickFullScale': DiffSteerUseCase.stickFullScale, + 'encoding': 'float64_little_endian', + 'payloadBytes': 20, + 'speedGearImplemented': false, + }); + } + final loop = ++_diagnosticLoop; + trace.event('loop_start', { + 'loop': loop, + 'resetAxes': resetAxes, + 'suspended': _suspendedByLifecycle, + }); _timer?.cancel(); // 进控制态的唯一入口:记下意图(后台挂起期间也记,回前台靠它恢复)。 _controlWanted = true; @@ -688,7 +762,7 @@ class RemoteControlCubit extends Cubit } final logPrefix = '⏰ [RemoteControl] [控制循环]'; //debugPrint('$logPrefix ========================================='); - //debugPrint('$logPrefix 启动控制循环,间隔: 200ms'); + //debugPrint('$logPrefix 启动控制循环,间隔: 250ms'); ///debugPrint('$logPrefix ========================================='); // 🔥 安全兼容:进控制态一律从“零速”起步。 @@ -697,13 +771,34 @@ class RemoteControlCubit extends Cubit // 下发运动指令 —— 车自己开走。冷启动入口(路由 create / 旧页 initState / // HUD activate)都经这里,故在源头清一次。 if (resetAxes) { - _zeroAxesQuietly(); + _zeroAxesQuietly(reason: 'loop_start'); } // 🔥 启动模拟设备状态推送(用于测试) // startSimulation(); - _timer = Timer.periodic(const Duration(milliseconds: 200), (timer) { + var lastTickUs = trace.elapsedUs; + var lastTickNumber = 0; + _timer = Timer.periodic(ControlFrameScheduler.interval, (timer) { + final nowUs = trace.elapsedUs; + final gapUs = nowUs - lastTickUs; + trace.event('loop_tick', { + 'loop': loop, + 'tick': timer.tick, + 'tickGapUs': gapUs, + 'missedTimerTicks': timer.tick - lastTickNumber - 1, + 'x': _currentOriginX, + 'y': _currentOriginY, + 'uiX': state.controlEntity.originX, + 'uiY': state.controlEntity.originY, + 'permission': state.hasPermission, + 'locked': state.isLocked, + 'emergency': state.isEmergency, + 'connected': tcpClient.isConnected, + 'activeStops': _diagnosticActiveStops, + }); + lastTickUs = nowUs; + lastTickNumber = timer.tick; if (isClosed) { // debugPrint('$logPrefix ❌ Cubit已关闭,取消定时器'); timer.cancel(); @@ -716,6 +811,7 @@ class RemoteControlCubit extends Cubit // 两版行为一致且不依赖 UI。(退页时 resetPermissionState 会把它清掉, // 不会出现“带着锁定进 HUD 导致摇杆失灵”。) if (state.isLocked) { + trace.event('loop_skip', {'loop': loop, 'reason': 'locked'}); // debugPrint('$logPrefix 🔒 锁定状态,跳过发送 - isLocked=true'); return; } @@ -732,11 +828,18 @@ class RemoteControlCubit extends Cubit // 常规安全检查 if (!state.hasPermission) { + trace.event('loop_skip', { + 'loop': loop, + 'reason': 'no_permission', + 'permissionId': _permissionTrace['permissionId'], + 'permissionPhase': state.permissionRequestPhase.name, + }); // debugPrint('$logPrefix ⚠️ 无权限,跳过发送 - hasPermission=false'); return; } if (state.isEmergency) { + trace.event('loop_skip', {'loop': loop, 'reason': 'emergency'}); // debugPrint('$logPrefix 🚨 急停状态,跳过发送 - isEmergency=true'); return; } @@ -745,7 +848,13 @@ class RemoteControlCubit extends Cubit //debugPrint( // '$logPrefix 📤 发送控制指令: originX=${snapshot.originX}, originY=${snapshot.originY}, mower=${snapshot.mowerSpeed}, lift=${snapshot.chassisLift}, ignition=${snapshot.ignitionStatus}, emergency=${snapshot.isEmergency}', // ); - _repository.sendControlMachineCmd(snapshot); + unawaited( + _sendMotionFrame(snapshot, 'loop', { + 'loop': loop, + 'tick': timer.tick, + 'tickGapUs': gapUs, + }), + ); //debugPrint('$logPrefix ✅ 控制指令已发送'); }); } @@ -799,6 +908,13 @@ class RemoteControlCubit extends Cubit if (isClosed) return; // 🔥 参考Android版:直接更新成员变量 + final trace = RemoteControlDiagnostics.instance; + trace.event('origin_input', { + 'axis': 'forward', + 'before': _currentOriginY, + 'value': y, + }); + _diagnosticInputUs = trace.elapsedUs; _currentOriginY = y; // 同时更新state(用于UI显示) @@ -816,6 +932,13 @@ class RemoteControlCubit extends Cubit if (isClosed) return; // 🔥 参考Android版:直接更新成员变量 + final trace = RemoteControlDiagnostics.instance; + trace.event('origin_input', { + 'axis': 'turn', + 'before': _currentOriginX, + 'value': x, + }); + _diagnosticInputUs = trace.elapsedUs; _currentOriginX = x; // 同时更新state(用于UI显示) @@ -855,113 +978,57 @@ class RemoteControlCubit extends Cubit ); } - /// 🔥 安全方法:同时清零双轴,确保只发送一次完全停止指令 - Future stopAllMovement() async { - // 🔥 cubit 已 close(退登录/销毁单例)时:只清本地值就返回。 - // 本方法多处被 unawaited() 调走(后台挂起 / 失权 / 松手),它的 await 链 - // 比页面活得久,不拦住就会在已关闭对象上 emit,抛未捕获的 StateError。 - if (isClosed) { - _currentOriginX = 0; - _currentOriginY = 0; - return; - } - // debugPrint( - // '🛑 [stopAllMovement] 开始执行- 当前成员变量: originX=$_currentOriginX, originY=$_currentOriginY', - // ); - - // 🔥 参考Android版:直接清零成员变量 + /// Clear motion immediately and replace queued movement with one priority zero. + /// The common transport gate enforces >=250ms, including this safety frame. + Future stopAllMovement({String reason = 'unspecified'}) async { + final trace = RemoteControlDiagnostics.instance; + final stop = ++_diagnosticStop; + trace.event('stop_begin', { + 'stop': stop, + 'reason': reason, + 'beforeX': _currentOriginX, + 'beforeY': _currentOriginY, + 'activeStops': _diagnosticActiveStops, + }); + _motionGeneration++; _currentOriginX = 0; _currentOriginY = 0; - - // 🔥 关键修复:先暂停定时器,防止定时器在停止期间发送旧的运动指令 - _timer?.cancel(); - _timer = null; // 🔥 彻底清空,防止重复启用 - - final updatedEntity = state.controlEntity.copyWith(x: 0, y: 0); - - // 一次性更新双轴(即使无权限也要更新本地state) - emit(state.copyWith(controlEntity: updatedEntity)); - - // 🔥 摇杆归零:同步倒车影像为非倒车态(引导线自动隐藏) - _syncReverseCameraFromJoystick(); - - // 🔥 安全底线:停止指令必须无视权限强制发送! - // debugPrint('🛑 [stopAllMovement] 双轴归零,发送停止指令- originX=0, originY=0'); - final sentFrames = await _sendStopCommandRepeatedly( - updatedEntity, - ); // 等待所有指令发送完成 - if (sentFrames == 0) { - // 一帧都没出网(TCP 未连接):不能当“已停住”。本地轴值已归零, - // 重连后由控制循环发零速帧接管;这里留下一条可查证的 ERROR 痕迹。 - debugPrint('🛑 [stopAllMovement] ⚠️ 停止指令全部未出网(TCP 未连接)'); - _logger.logWithLevel( - '🛑 [stopAllMovement] ⚠️ 30 帧停止指令全部未出网(_socket=null),' - '本地轴值已归零,重连后由控制循环补发零速帧', - level: 'ERROR', - shouldLog: true, - ); + if (isClosed) return; + _diagnosticActiveStops++; + try { + final zero = state.controlEntity.copyWith(x: 0, y: 0); + emit(state.copyWith(controlEntity: zero)); + _syncReverseCameraFromJoystick(); + final accepted = await _sendMotionFrame(zero, 'stop', { + 'stop': stop, + 'reason': reason, + }); + trace.event('stop_result', { + 'stop': stop, + 'localWriteCompleted': accepted, + }); + // Keep the existing periodic loop alive. It repeats the latest zero state; + // there is no old stop burst or delayed restart to overwrite a new gesture. + } finally { + _diagnosticActiveStops--; + trace.event('stop_end', { + 'stop': stop, + 'activeStops': _diagnosticActiveStops, + 'currentX': _currentOriginX, + 'currentY': _currentOriginY, + }); } - - // 🔥 恢复定时器:仅当业务侧仍处于控制态。 - // 上面这 ~400ms 窗口里页面可能已 dispose(stopControlLoop 把意图关掉了), - // 无条件重启会让循环在没人控制的页面上空转到 cubit close;后台挂起期间 - // startControlLoop 自身也会拦住定时器,只留意图给回前台恢复。 - await Future.delayed(const Duration(milliseconds: 200)); - if (_controlWanted) { - // 🔥 热重启不清轴:上面这 ~450ms 里用户完全可能又把摇杆压回去了 - // (updateOriginX/Y 会把非零值写回 _currentOriginX/Y)。若在这里再 - // 调 _zeroAxesQuietly(),就会抹掉他手指正压着的目标量;而 UI 侧的 - // 去重基准(HUD 的 _lastDriveY / 旧版摇杆的 _lastSentY)仍是那个非零值, - // 于是“手指明明压在摇杆上、车却不动”,得再推一下才恢复。 - // 跨会话残留值的清理只在冷启动入口做(那里 resetAxes 默认 true)。 - startControlLoop(resetAxes: false); - } else { - debugPrint('🛑 [stopAllMovement] 已不在控制态,不重启循环'); - } - - // debugPrint('>>> [stopAllMovement] 执行完成'); - } - - /// 🔥 统一方法:连续发送停止指令,彻底清空TCP缓冲区。 - /// - /// 返回真正写入 socket 的帧数:sendRaw 在未连接时会直接失败, - /// 调用方据此判断“停止指令是不是真的发出去了”(安全路径必须知道这一点)。 - Future _sendStopCommandRepeatedly( - MachineControlStatusEntity stopEntity, - ) async { - // debugPrint( - // '🛑 [紧急停止] 开始连续发送 10 次停止指令- originX=${stopEntity.originX}, originY=${stopEntity.originY}', - // ); - // 🔥 本方法不做任何节流:停止帧必须一帧不少地发完。(旧注释写的“_lastStopTime - // 已在 stopAllMovement 里设置”是假信息 —— 全项目并没有这个变量,勿据此加节流。) - - int sentCount = 0; - // 🔥 关键修复:每次发送间隔5ms,避免TCP合并/丢弃 - for (int i = 0; i < 20; i++) { - if (_repository.sendControlMachineCmd(stopEntity)) sentCount++; - if (i % 5 == 0) { - // debugPrint('🛑 [紧急停止] 已发送第${i + 1}次'); - } - if (i < 19) { - await Future.delayed(const Duration(milliseconds: 5)); - } - } - - // 🔥 延迟后再发10次(双重保险,对抗网络抖动) - await Future.delayed(const Duration(milliseconds: 100)); - for (int i = 0; i < 10; i++) { - if (_repository.sendControlMachineCmd(stopEntity)) sentCount++; - if (i < 9) { - await Future.delayed(const Duration(milliseconds: 5)); - } - } - - // debugPrint('>>> [紧急停止] 所有20次停止指令已发出'); - return sentCount; } // 5. 停止控制循环 void stopControlLoop() { + _motionGeneration++; + RemoteControlDiagnostics.instance.event('loop_stop', { + 'loop': _diagnosticLoop, + 'x': _currentOriginX, + 'y': _currentOriginY, + }); + RemoteControlDiagnostics.instance.end('stop_control_loop'); // 🔥 退出控制态:意图一并关掉,否则 pending 中的 stopAllMovement 末尾 // 会把循环重新点着,回前台时也会错误地恢复一个已退页的控制循环。 _controlWanted = false; @@ -1015,7 +1082,9 @@ class RemoteControlCubit extends Cubit // 切换逻辑:如果当前是前视角(>=0),切换到后视角(-1);反之亦然 final newOriginY = currentOriginY >= 0 ? -1 : 1; - debugPrint('📷 [RemoteControlCubit] 切换前后视角: $currentOriginY -> $newOriginY'); + debugPrint( + '📷 [RemoteControlCubit] 切换前后视角: $currentOriginY -> $newOriginY', + ); final updatedEntity = state.controlEntity.copyWith(y: newOriginY); emit(state.copyWith(controlEntity: updatedEntity)); @@ -1034,9 +1103,7 @@ class RemoteControlCubit extends Cubit @visibleForTesting void emit(RemoteControlState state) { if (isClosed) { - debugPrint( - '⚠️ [RemoteControl] Cubit 已关闭,忽略一次 emit(异步回调迟到)', - ); + debugPrint('⚠️ [RemoteControl] Cubit 已关闭,忽略一次 emit(异步回调迟到)'); return; } super.emit(state); @@ -1044,6 +1111,9 @@ class RemoteControlCubit extends Cubit @override Future close() { + _emergencyStatusTimer?.cancel(); + RemoteControlDiagnostics.instance.end('cubit_close'); + _cancelPermissionAttempt(); // 与构造函数里的 addObserver 成对移除,否则回调会打在已关闭的对象上。 WidgetsBinding.instance.removeObserver(this); _timer?.cancel(); @@ -1086,26 +1156,173 @@ class RemoteControlCubit extends Cubit debugPrint('🚗 [倒车影像] 数据源已停止'); } + /// 显示状态只读当前车的主机实时推送,HTTP 回包不得覆盖。 + void refreshEmergencyStatus() { + if (isClosed) return; + final reading = deviceStatusBloc.emergencyStopReading; + final valid = + reading != null && + reading.sn == state.targetDevice?.deviceName.trim() && + reading.active != null && + !_emergencyNow().difference(reading.receivedAt).isNegative && + _emergencyNow().difference(reading.receivedAt) <= emergencyStatusMaxAge; + if (!valid) { + if (state.hasEmergencyStatus) + emit(state.copyWith(hasEmergencyStatus: false)); + return; + } + final active = reading.active!; + if (active != state.isEmergency) + _zeroAxesQuietly(reason: 'emergency_telemetry'); + emit( + state.copyWith( + hasEmergencyStatus: true, + isEmergency: active, + isLocked: active + ? true + : state.isEmergency + ? false + : state.isLocked, + ), + ); + } + + bool checkEmergencyRequest(bool on) { + refreshEmergencyStatus(); + if (state.isEmergencyRequestPending) return false; + final key = !state.hasEmergencyStatus + ? 'emergency_status_unavailable' + : state.isEmergency == on + ? (on ? 'emergency_already_active' : 'emergency_already_released') + : ''; + if (key.isEmpty) return true; + emit(state.copyWith(emergencyFeedbackKey: key)); + return false; + } + + /// UI → 用例 → 仓库 → HTTP;只提交请求,实际状态等待推送。 + Future updateEmergency(bool on) async { + if (isClosed || state.isEmergencyRequestPending) return false; + final sn = state.targetDevice?.deviceName.trim() ?? ''; + if (sn.isEmpty) { + emit( + state.copyWith( + emergencyRequestFailed: true, + emergencyFeedbackKey: 'emergency_missing_sn', + ), + ); + return false; + } + if (!checkEmergencyRequest(on)) return false; + final attempt = ++_emergencyAttempt; + final previousEmergency = state.isEmergency; + final previousLocked = state.isLocked; + _zeroAxesQuietly(reason: on ? 'http_emergency_on' : 'http_emergency_off'); + // 请求期间先抑制本地遥控;只有业务成功才切换急停显示状态。 + // TCP 实体不再写急停位,避免停止/退出帧再次夹带旧急停命令。 + emit( + state.copyWith( + isLocked: on ? true : state.isLocked, + controlEntity: state.controlEntity.copyWith( + x: 0, + y: 0, + mower: 0, + lift: 0, + emergency: false, + ), + isEmergencyRequestPending: true, + emergencyRequestFailed: false, + emergencyFeedbackKey: '', + ), + ); + bool isCurrent() => + !isClosed && + attempt == _emergencyAttempt && + state.targetDevice?.deviceName.trim() == sn; + try { + final result = await _requestEmergencyStop( + sn, + on ? EmergencyStopTarget.engage : EmergencyStopTarget.release, + ); + if (!isCurrent()) return false; + return result.fold( + (failure) { + RemoteControlDiagnostics.instance.event('emergency_http_failed', { + 'device': sn, + 'eStop': on ? 1 : 0, + 'message': failure.message, + }); + _zeroAxesQuietly(reason: 'http_emergency_failed'); + emit( + state.copyWith( + isLocked: failure is EmergencyStopRejectedFailure + ? (state.isEmergency || + (previousLocked && !previousEmergency)) + : true, + controlEntity: state.controlEntity.copyWith( + x: 0, + y: 0, + mower: 0, + lift: 0, + ), + isEmergencyRequestPending: false, + emergencyRequestFailed: true, + emergencyFeedbackKey: failure is EmergencyStopRejectedFailure + ? 'emergency_request_rejected' + : 'emergency_request_failed', + ), + ); + return false; + }, + (_) { + // 解除时再次清零,急停期间的迟到摇杆回调不能使车辆自行恢复运动。 + _zeroAxesQuietly(reason: 'http_emergency_accepted'); + emit( + state.copyWith( + isLocked: + state.isEmergency || (previousLocked && !previousEmergency), + isEmergencyRequestPending: false, + emergencyRequestFailed: false, + emergencyFeedbackKey: on + ? 'emergency_request_sent' + : 'emergency_release_sent', + ), + ); + return true; + }, + ); + } catch (_) { + if (isCurrent()) { + emit( + state.copyWith( + isEmergencyRequestPending: false, + emergencyRequestFailed: true, + emergencyFeedbackKey: 'emergency_request_failed', + ), + ); + } + return false; + } + } + + /* 旧 TCP 急停实现保留,已由上方 HTTP 用例替换;恢复前须确认协议兼容。 void updateEmergency(bool on) { // debugPrint('🚨 [急停] ${on ? "触发急停!" : "解除急停"}'); // 🔥 先归零双轴:急停只是让循环“跳过发送”,_currentOriginX/Y 仍原样留着; // 不归零的话,updateEmergency(false) 解除的那一 tick 就会按急停前的推量 // 原地复活(“急停→解除→车又自己走”)。触发与解除都清,语义变成 // “一旦碰过急停就必须重新推杆”。下面的全零急停帧会把已在跑的车压停。 - _zeroAxesQuietly(); - // ① 先置状态:急停时让 200ms 控制循环下一 tick 立刻停发运动指令; + _zeroAxesQuietly(reason: on ? 'emergency_on' : 'emergency_off'); + // ① 先置状态:急停时让 250ms 控制循环下一 tick 立刻停发运动指令; // 解除时循环恢复正常发送。 updateFunction(emergency: on); // ② 再绕过控制循环的 isEmergency 门控,直发带急停位的指令帧(双重保险): // - 按下:连发 emergency=1 + 全零,让设备明确收到「急停」,而不只靠「收不到指令」。 // - 取消:连发 emergency=0 + 全零,让设备明确「解除急停、恢复正常」。 - _sendEmergencyFrames(emergency: on); + unawaited(_sendEmergencyFrames(emergency: on)); } - /// 双重保险:绕过控制循环门控,直接连续补发若干帧带急停位的指令。 - /// - /// [emergency] true=显式急停(emergency 位=1),false=显式恢复正常(emergency 位=0)。 - /// 运动量一律全零,避免误带旧摇杆值;5ms 高频补发防丢包(安全路径,无视权限)。 + /// Emergency on/off uses the same priority >=250ms gate as every 0x00 frame. Future _sendEmergencyFrames({required bool emergency}) async { final frame = MachineControlStatusEntity( originX: 0, @@ -1115,25 +1332,16 @@ class RemoteControlCubit extends Cubit ignitionStatus: 0, isEmergency: emergency, ); - int sentFrames = 0; - for (int i = 0; i < 10; i++) { - if (isClosed) return; - if (_repository.sendControlMachineCmd(frame)) sentFrames++; - if (i < 9) { - await Future.delayed(const Duration(milliseconds: 5)); - } - } - // 🔥 急停帧也是安全路径:一帧都没出网时必须留下痕迹,否则“按了急停但 - // 设备没收到”会被当成已停住(与 stopAllMovement 同一口径)。 - if (sentFrames == 0) { - debugPrint('🚨 [急停] ⚠️ 急停帧全部未出网(TCP 未连接)emergency=$emergency'); - _logger.logWithLevel( - '🚨 [急停] ⚠️ 10 帧急停指令全部未出网(_socket=null),emergency=$emergency', - level: 'ERROR', - shouldLog: true, - ); - } + if (isClosed) return; + final accepted = await _sendMotionFrame(frame, 'emergency', { + 'emergency': emergency, + }); + RemoteControlDiagnostics.instance.event('emergency_result', { + 'emergency': emergency, + 'localWriteCompleted': accepted, + }); } + */ void respondPermission(bool agreed, String deviceId) { // 1. 关闭弹窗(立即关闭,防止重复点击) @@ -1182,160 +1390,366 @@ class RemoteControlCubit extends Cubit debugPrint('${_getTimePrefix()} ====权限弹窗响应结束====='); } - /// 请求控制权限(HTTP 查询接口 /forward/device/remoteControl) - /// - /// [grabControl] true = 查询后若无权限立即发 TCP 0x12 switch_control 抢占(手动点击时使用); - /// false = 仅查询,把接口 remoteControl 结果如实同步到 UI(进入页面时使用) + void _tracePermission(String step, [Map fields = const {}]) { + ControlPermissionDiagnostics.event(step, { + ...(ControlPermissionDiagnostics.context ?? _permissionTrace), + 'currentDevice': state.targetDevice?.deviceName, + 'phase': state.permissionRequestPhase.name, + 'hasPermission': state.hasPermission, + 'tcpConnected': tcpClient.isConnected, + ...fields, + }); + } + + void _permissionLog(String event) => + _tracePermission('状态记录', {'detail': event}); + + void _permissionPhase( + PermissionRequestPhase phase, { + String? feedback, + bool? hasPermission, + }) { + _tracePermission('状态更新', { + 'nextPhase': phase.name, + 'permissionBefore': state.hasPermission, + 'permissionAfter': hasPermission ?? state.hasPermission, + 'feedback': feedback, + }); + emit( + state.copyWith( + permissionRequestPhase: phase, + hasPermission: hasPermission, + permissionFeedbackKey: feedback ?? '', + permissionFeedbackId: feedback == null + ? state.permissionFeedbackId + : state.permissionFeedbackId + 1, + ), + ); + } + + bool _isCurrentPermissionAttempt(int attempt, String deviceName) => + !isClosed && + _permissionSessionActive && + _permissionAttempt == attempt && + state.targetDevice?.deviceName == deviceName; + + /// Cancel only the permission request; movement/release retain their existing flow. + void cancelPermissionRequest() { + _cancelPermissionAttempt(); + if (!isClosed) { + emit( + state.copyWith( + permissionRequestPhase: PermissionRequestPhase.idle, + permissionFeedbackKey: '', + ), + ); + } + } + + void _cancelPermissionAttempt() { + if (_permissionSessionActive || state.isPermissionRequestBusy) { + _tracePermission('申请会话取消'); + } + _permissionAttempt++; + _permissionWaitTimer?.cancel(); + _permissionWaitTimer = null; + _permissionSessionActive = false; + _permissionManual = false; + } + + void _finishPermissionAttempt( + PermissionRequestPhase phase, + String feedback, { + bool? hasPermission, + }) { + _tracePermission('申请结束', { + 'result': phase.name, + 'feedback': feedback, + 'permissionAfter': hasPermission ?? state.hasPermission, + }); + _permissionWaitTimer?.cancel(); + _permissionWaitTimer = null; + // Invalidate pending query/write continuations, including send timeouts. + _permissionAttempt++; + _permissionPhase(phase, feedback: feedback, hasPermission: hasPermission); + _permissionManual = false; + } + + void _waitForPermissionResult(int attempt, String deviceName) { + _tracePermission('等待授权回包', { + 'timeoutMs': _permissionResponseTimeout.inMilliseconds, + 'serverReceiptConfirmed': false, + }); + _permissionWaitTimer?.cancel(); + _permissionWaitTimer = Timer.periodic(const Duration(milliseconds: 250), ( + timer, + ) { + if (!_isCurrentPermissionAttempt(attempt, deviceName)) { + _tracePermission('停止等待', {'reason': '申请已结束或目标设备已变化'}); + timer.cancel(); + return; + } + if (!tcpClient.isConnected) { + _finishPermissionAttempt( + PermissionRequestPhase.failed, + 'permission_connection_lost', + ); + } else if (timer.tick * 250 >= + _permissionResponseTimeout.inMilliseconds) { + _finishPermissionAttempt( + PermissionRequestPhase.timedOut, + 'permission_result_timeout', + ); + } + }); + } + + /// Query on entry; send exactly one existing 0x12 request on a manual click. Future requestControlPermissionS( String deviceName, String deviceId, { String source = '自动', bool grabControl = false, }) async { - final timePrefix = _getTimePrefix(); - final logPrefix = '$timePrefix 🔑 [RemoteControl] [请求权限接口-$source]'; - debugPrint('$logPrefix ========================================='); - debugPrint('$logPrefix 开始请求控制权 (grabControl=$grabControl)'); - debugPrint('$logPrefix deviceName: $deviceName'); - debugPrint('$logPrefix platform: $deviceId'); - debugPrint( - '$logPrefix 当前状态 hasPermission=${state.hasPermission}, showDialog=${state.showPermissionRequestDialog}', - ); - _logger.logWithLevel( - '$logPrefix 开始请求控制权- deviceName: $deviceName, platform: $deviceId', - shouldLog: true, - ); - - // 1. 只有当弹窗不是因Web 端请求权限而显示时,才关闭弹窗 - // 避免 Web 端请求权限的弹窗被自动关闭(一闪而过的问题) - if (state.requestingPlatform == null) { - debugPrint('$logPrefix 关闭权限请求弹窗 (非Web端触发)'); - emit(state.copyWith(showPermissionRequestDialog: false)); - } else { - debugPrint('$logPrefix 保留弹窗 (Web端请求触发)'); + if (isClosed) return; + final triggerId = DateTime.now().microsecondsSinceEpoch.toString(); + _tracePermission('入口触发', { + 'triggerId': triggerId, + 'requestedDevice': deviceName, + 'requestedSource': source, + 'requestedManual': grabControl, + }); + if (deviceName.trim().isEmpty || + state.targetDevice?.deviceName != deviceName) { + _permissionPhase( + PermissionRequestPhase.failed, + feedback: 'permission_invalid_device', + ); + return; } - - // 2. 调用 UseCase 获取 HTTP 返回的完整权限信息 - debugPrint('$logPrefix 调用 HTTP 接口查询权限状态..'); - final result = await _requestControlPermissionUseCase( - RequestControlPermissionParams( - deviceName: deviceName, - deviceId: deviceId, - ), + if (state.isPermissionRequestBusy) { + // A manual click during the entry query reuses that query, never duplicates it. + if (grabControl && + state.permissionRequestPhase == PermissionRequestPhase.checking) { + _permissionManual = true; + _tracePermission('复用进行中的查询', {'reason': '手动点击合并到进页查询'}); + } else { + _tracePermission('忽略重复调用', {'reason': '申请正在发送或等待授权'}); + } + return; + } + if (grabControl && state.showPermissionRequestDialog) { + _permissionPhase( + PermissionRequestPhase.failed, + feedback: 'permission_handover_pending', + ); + return; + } + _permissionWaitTimer?.cancel(); + final attempt = ++_permissionAttempt; + _permissionRequestId++; + _permissionTrace = { + 'permissionId': + '${DateTime.now().microsecondsSinceEpoch}-$_permissionRequestId', + 'triggerId': triggerId, + 'requestNo': _permissionRequestId, + 'device': deviceName, + 'source': source, + 'manualAtStart': grabControl, + 'startedUs': RemoteControlDiagnostics.instance.elapsedUs, + 'permissionRule': 'manual_request_if_no_permission_or_owner_null', + }; + _permissionSessionActive = true; + _permissionManual = grabControl; + _permissionLog( + 'begin source=' + source + ' manual=' + grabControl.toString(), ); + _permissionPhase(PermissionRequestPhase.checking); - // 3. 处理结果 - result.fold( - (failure) { - final failLogPrefix = - '${_getTimePrefix()} 🔑 [RemoteControl] [请求权限接口-$source]'; - debugPrint('$failLogPrefix APP请求控制权限失败: ${failure.message}'); - _logger.logWithLevel( - '$failLogPrefix APP请求控制权限失败: ${failure.message}', - shouldLog: true, - ); - // 🔥 修复:HTTP请求失败时不要自动打开弹窗,避免形成循环 - // emit(state.copyWith(showPermissionRequestDialog: true)); - debugPrint('$failLogPrefix HTTP请求失败,不自动打开弹窗'); - }, - (permissionInfo) async { - final bool hasPermission = - permissionInfo['hasPermission'] as bool? ?? false; - final String? owner = permissionInfo['owner'] as String?; - final successLogPrefix = - '${_getTimePrefix()} 🔑 [RemoteControl] [请求权限接口-$source]'; - - debugPrint( - '$successLogPrefix APP HTTP返回 - hasPermission=$hasPermission, owner=$owner', - ); - _logger.logWithLevel( - '$successLogPrefix APP HTTP返回 - hasPermission=$hasPermission, owner=$owner', - shouldLog: true, - ); - - // 🔥 仅查询模式:不抢占,把接口 remoteControl 结果如实同步到 UI - if (!grabControl) { - debugPrint( - '$successLogPrefix 👀 仅查询模式,不发送TCP抢占,直接同步 remoteControl=$hasPermission', - ); - _logger.logWithLevel( - '$successLogPrefix 👀 仅查询模式,直接同步 remoteControl=$hasPermission', - shouldLog: true, - ); - if (state.hasPermission != hasPermission) { - emit(state.copyWith(hasPermission: hasPermission)); - } + return ControlPermissionDiagnostics.scope(_permissionTrace, () async { + try { + final result = await _requestControlPermissionUseCase( + RequestControlPermissionParams( + deviceName: deviceName, + deviceId: deviceId, + ), + ).timeout(_permissionQueryTimeout); + if (!_isCurrentPermissionAttempt(attempt, deviceName)) { + _tracePermission('忽略迟到HTTP结果', {'reason': '申请已结束或设备已变化'}); + return; } - // 🔥 抢占模式: 如果没有权限 或owner为null,则发送TCP 请求 - else if (!hasPermission || owner == null) { - debugPrint('$successLogPrefix ⚠️ APP无权限或owner为null,发送TCP请求...'); - _logger.logWithLevel( - '$successLogPrefix ⚠️ APP无权限或owner为null,发送TCP请求', - shouldLog: true, - ); - - // 🔥 发送TCP 0x12 权限请求指令 - _repository.sendTcpPermissionRequest(deviceName); - - // 等待 TCP 回包(通过监听器更新状态 - debugPrint('$successLogPrefix 📡 TCP请求已发送,等待回包确认'); - } else { - debugPrint('$successLogPrefix APP已有权限,直接更新UI'); - _logger.logWithLevel( - '$successLogPrefix APP已有权限,直接更新UI', - shouldLog: true, - ); - debugPrint( - '$successLogPrefix 当前 hasPermission 状态: ${state.hasPermission}', - ); - - // 🔥 正确的状态更新:使用最新状态 - if (state.hasPermission != true) { - debugPrint('$successLogPrefix 🔄 更新 hasPermission = true'); - emit(state.copyWith(hasPermission: true)); - debugPrint('$successLogPrefix ✅ hasPermission 状态已更新为 true'); - } else { - debugPrint('$successLogPrefix ⚠️ hasPermission 已是 true,无需更新'); - // 强制触发UI刷新:通过临时改变其他属性 - emit(state.copyWith(ping: state.ping + 1)); - emit(state.copyWith(ping: state.ping)); - } + final info = result.fold>( + (failure) => throw failure, + (value) => value, + ); + if (info['hasPermission'] is! bool) { + throw ControlPermissionFailure('permission_query_invalid'); } - }, - ); - debugPrint( - '${_getTimePrefix()} 🔑 [RemoteControl] [请求权限接口-$source] =========================================', - ); + final hasPermission = info['hasPermission'] == true; + _tracePermission('HTTP业务判定', { + 'remoteControl': info['hasPermission'], + 'owner': info['owner'], + 'ownerIsNull': info['owner'] == null, + 'manualAtDecision': _permissionManual, + }); + // Preserve the original manual-request rule: an unassigned owner still + // needs one 0x12 request, even when the HTTP remoteControl flag is true. + // Entry-only queries continue to display the HTTP result without grabbing. + if (hasPermission && (!_permissionManual || info['owner'] != null)) { + _tracePermission('跳过0x12', { + 'reason': _permissionManual ? 'HTTP已有权限且owner非空' : '进页仅查询,同步HTTP权限', + 'grantSource': 'http', + }); + _permissionPhase( + PermissionRequestPhase.granted, + hasPermission: true, + feedback: _permissionManual ? 'permission_already_granted' : null, + ); + _permissionManual = false; + return; + } + final lostPermission = state.hasPermission; + emit(state.copyWith(hasPermission: false)); + if (lostPermission) + unawaited(stopAllMovement(reason: 'http_permission_lost')); + if (!_permissionManual) { + _tracePermission('跳过0x12', {'reason': '进页仅查询,无权限时不自动抢占'}); + _permissionPhase(PermissionRequestPhase.idle); + return; + } + if (!tcpClient.isConnected) { + _finishPermissionAttempt( + PermissionRequestPhase.failed, + 'permission_tcp_disconnected', + ); + return; + } + _tracePermission('准备发送0x12', { + 'reason': hasPermission + ? 'HTTP有权限但owner为空,保留原逻辑申请' + : 'HTTP返回无权限,手动申请', + }); + _permissionPhase(PermissionRequestPhase.sending); + // The packet can return before flush completes. The response handler invalidates + // this attempt so a late write completion cannot overwrite its final result. + await _repository + .sendTcpPermissionRequest( + deviceName, + isCurrent: () => _isCurrentPermissionAttempt(attempt, deviceName), + ) + .timeout(_permissionSendTimeout); + if (!_isCurrentPermissionAttempt(attempt, deviceName)) { + _tracePermission('忽略迟到写入结果', {'reason': '可能已处理授权回包,或申请已取消;不覆盖当前结果'}); + return; + } + if (!tcpClient.isConnected) { + _finishPermissionAttempt( + PermissionRequestPhase.failed, + 'permission_connection_lost', + ); + return; + } + _permissionPhase( + PermissionRequestPhase.waiting, + feedback: 'permission_sent', + ); + _waitForPermissionResult(attempt, deviceName); + } catch (error) { + if (!_isCurrentPermissionAttempt(attempt, deviceName)) return; + final sending = + state.permissionRequestPhase == PermissionRequestPhase.sending; + final key = error is ControlPermissionFailure + ? error.feedbackKey + : sending + ? 'permission_send_uncertain' + : error is TimeoutException + ? 'permission_query_timeout' + : 'permission_query_failed'; + _tracePermission('申请异常', { + 'errorType': error.runtimeType.toString(), + 'feedback': key, + }); + _finishPermissionAttempt(PermissionRequestPhase.failed, key); + } + }); } - /// 🔥 退出遥控页时重置“会话级”状态(权限 / 弹窗 / 锁定 / 急停),避免单例残留 + /// Result notifications reuse the existing respond.switchResult protocol. + void _handlePermissionResult(Map respondData) { + RemoteControlDiagnostics.instance.event('permission_result', { + 'responseDevice': respondData['deviceId'], + 'switchResult': respondData['switchResult'], + 'holder': respondData['holder'], + }); + final deviceName = state.targetDevice?.deviceName; + final result = respondData['switchResult']; + _tracePermission('授权回包', { + 'responseDevice': respondData['deviceId'], + 'switchResult': result, + 'holder': respondData['holder'], + 'reason': respondData['reason'], + 'sessionActive': _permissionSessionActive, + 'deviceMatches': respondData['deviceId'] == deviceName, + 'replyCorrelation': 'current_local_attempt_only_no_wire_request_id', + }); + if (!_permissionSessionActive || + deviceName == null || + respondData['deviceId'] != deviceName || + result is! bool) { + _permissionLog( + 'ignored result: inactive session, device mismatch or invalid fields', + ); + return; + } + final holder = respondData['holder']; + if (result && holder != null && holder != 'you') { + _permissionLog('ignored result: success holder is not this client'); + return; + } + final notify = _permissionManual && state.isPermissionRequestBusy; + _permissionWaitTimer?.cancel(); + _permissionWaitTimer = null; + _permissionAttempt++; + _permissionManual = false; + _permissionPhase( + result ? PermissionRequestPhase.granted : PermissionRequestPhase.failed, + hasPermission: result, + feedback: notify + ? result + ? 'permission_granted' + : respondData['reason'] == 'holder_denied' + ? 'permission_denied' + : 'permission_not_granted' + : null, + ); + _tracePermission('授权回包已应用', { + 'grantSource': 'tcp_0x12', + 'permissionAfter': result, + }); + if (!result) unawaited(stopAllMovement(reason: 'tcp_permission_false')); + } + + /// 退出只重置权限/弹窗;急停保持,必须由用户明确确认解除。 void resetPermissionState() { + _cancelPermissionAttempt(); if (!isClosed) { emit( state.copyWith( hasPermission: false, + permissionRequestPhase: PermissionRequestPhase.idle, + permissionFeedbackKey: '', showPermissionRequestDialog: false, - // 🔥 锁定位一并复位:它是页面内的一次性 UI 态,残留到下一次会话 - // 会让控制循环被上面的 isLocked 门控整体拦住(新版 HUD 没有 - // 解锁按钮,到时候就是“推了不动”且无法自救)。 - isLocked: false, - // 🔥 急停位同样复位(只改状态,不再补发帧):旧版“点急停直接退页” - // 会把 isEmergency=true 留在单例上,而新版 HUD 的急停按钮是页面 - // 本地变量(_startControl 里置 false)——两边不一致时,HUD 显示 - // “未急停”但循环被 isEmergency 拦住,同样是“推了不动”。 - // 与新版 deactivate() 里的 updateEmergency(false) 同一口径;设备侧 - // 已收到退页时的全停帧,下次会话循环一开就会发 emergency=0 帧。 - // controlEntity 里的 emergency 位也要一并清:stopAllMovement 的停止 - // 帧用的是这个实体,残留会让下次会话松手时错发一串急停帧。 - isEmergency: false, - controlEntity: state.controlEntity.copyWith(emergency: false), + isLocked: state.isEmergency, + controlEntity: state.controlEntity.copyWith( + emergency: false, + mower: 2, + ), + lastMowerOperation: MowerLastOperation.none, ), ); - debugPrint( - '🔑 [RemoteControl] 已重置会话态 hasPermission=false, isLocked=false, isEmergency=false', - ); + debugPrint('🔑 [RemoteControl] 已重置权限;保留急停请求态 ${state.isEmergency}'); _logger.logWithLevel( - '🔑 [RemoteControl] 已重置会话态 hasPermission=false, isLocked=false, isEmergency=false', + '🔑 [RemoteControl] 已重置权限;保留急停请求态 ${state.isEmergency}', shouldLog: true, ); } @@ -1409,11 +1823,39 @@ class RemoteControlCubit extends Cubit updateFunction(lift: i); } - /// 发送割刀指令 + /// 滑块段位(上1/中0/下2)→ 割刀协议值(开1/不操作2/关0)。 + void sendMowerSliderCommand(int segment) { + sendMowerCommand(switch (segment) { + 1 => 1, + 2 => 0, + _ => 2, + }); + } + + /// 更新割刀协议字段,由既有 250ms 控制循环发送。 void sendMowerCommand(int i) { - // // debugPrint('>>> [割刀指令] ${i}'); - // _logger.logWithLevel('>>> [割刀指令] ${i}'); - updateFunction(mower: i); + if (isClosed || i < 0 || i > 2) return; + emit( + state.copyWith( + controlEntity: state.controlEntity.copyWith(mower: i), + lastMowerOperation: switch (i) { + 1 => MowerLastOperation.turnOn, + 0 => MowerLastOperation.turnOff, + _ => state.lastMowerOperation, + }, + ), + ); + } + + /// 新的遥控会话/车辆从“不操作”开始,不继承上一会话的开关提示。 + void resetMowerControl() { + if (isClosed) return; + emit( + state.copyWith( + controlEntity: state.controlEntity.copyWith(mower: 2), + lastMowerOperation: MowerLastOperation.none, + ), + ); } /// 发送点火指令 @@ -1441,13 +1883,13 @@ class RemoteControlCubit extends Cubit if (!state.hasReceivedStatusPush) return false; if (_lastStatusPushTime == null) return false; // 超过5秒未收到新推送,视为推送已中断 - return DateTime.now().difference(_lastStatusPushTime!) < const Duration(seconds: 5); + return DateTime.now().difference(_lastStatusPushTime!) < + const Duration(seconds: 5); } Future getNetworkDelay() async { try { - // 直接 Ping 你的服务器IP - final ping = Ping('1.95.137.212', count: 1, timeout: 1); + final ping = Ping(TCPConsts.TCP_IP, count: 1, timeout: 1); // 等待一次结果 final data = await ping.stream.first; @@ -1473,16 +1915,38 @@ class RemoteControlCubit extends Cubit /// 🔥 设置待控制的设备(从机器人列表点击进入时调用) void setTargetDevice(DeviceEntity device) async { + resetMowerControl(); debugPrint('🎯 [RemoteControl] ========== 开始设置目标设备 =========='); debugPrint('🎯 [RemoteControl] 设备名称: ${device.deviceName}'); - debugPrint('🎯 [RemoteControl] 当前TCP状态: ${tcpClient.isConnected ? "已连接" : "未连接"}'); + debugPrint( + '🎯 [RemoteControl] 当前TCP状态: ${tcpClient.isConnected ? "已连接" : "未连接"}', + ); // 🔥 关键修复:切换设备时清空所有缓存,防止显示上一个设备的数据 _clearAllCache(); debugPrint('✅ [RemoteControl] 已清空所有缓存数据'); debugPrint('📦 [RemoteControl] 更新targetDevice状态'); - emit(state.copyWith(targetDevice: device)); + if (state.targetDevice?.deviceName != device.deviceName) { + _cancelPermissionAttempt(); + _emergencyAttempt++; + emit( + state.copyWith( + targetDevice: device, + isEmergency: false, + hasEmergencyStatus: false, + isLocked: false, + isEmergencyRequestPending: false, + emergencyRequestFailed: false, + emergencyFeedbackKey: '', + hasPermission: false, + permissionRequestPhase: PermissionRequestPhase.idle, + permissionFeedbackKey: '', + ), + ); + } else { + emit(state.copyWith(targetDevice: device)); + } debugPrint('✅ [RemoteControl] targetDevice状态已更新'); // 🔥 关键修复:切换设备时重置 DeviceStatusBloc 状态并清空缓存, @@ -1492,7 +1956,7 @@ class RemoteControlCubit extends Cubit // 🔥 MQTT机器状态订阅:切换设备时订阅新设备的topic(与DevicesCubit.switchDevice相同逻辑) debugPrint('📡 [RemoteControl] 开始MQTT机器状态订阅: ${device.deviceName}'); deviceStatusBloc.startMqttRealtimeListening(device.deviceName); - + // 🔥 关键修复:TCP 已在登录时建立,设备切换只用 HTTP // 不再创建新 TCP 连接,避免重复发送 0x03 触发服务端推送 have_logged_in if (tcpClient.isConnected) { @@ -1528,14 +1992,30 @@ class RemoteControlCubit extends Cubit /// 🔥 清除待控制设备(退出远程控制页时调用) void clearTargetDevice() { + _emergencyAttempt++; // debugPrint('🧹 [RemoteControl] 清除待控制设备'); // _logger.logWithLevel('🧹 [RemoteControl] 清除待控制设备'); - + // 🔥 关键修复:退出页面时清空所有缓存,防止数据滞留 _clearAllCache(); debugPrint('✅ [RemoteControl] 已清空所有缓存数据'); - - emit(state.copyWith(targetDevice: null)); + + _cancelPermissionAttempt(); + emit( + state.copyWith( + clearTargetDevice: true, + hasEmergencyStatus: false, + controlEntity: state.controlEntity.copyWith(mower: 2), + lastMowerOperation: MowerLastOperation.none, + isEmergency: false, + isEmergencyRequestPending: false, + emergencyRequestFailed: false, + emergencyFeedbackKey: '', + hasPermission: false, + permissionRequestPhase: PermissionRequestPhase.idle, + permissionFeedbackKey: '', + ), + ); } /// 🔥 获取设备 @@ -1552,7 +2032,7 @@ class RemoteControlCubit extends Cubit _cachePing = null; _lastUiUpdateTime = null; _lastStatusPushTime = null; // 重置推送时间 - + // 🔥 同时重置 UI 状态为初始值 if (!isClosed) { emit( @@ -1568,12 +2048,15 @@ class RemoteControlCubit extends Cubit ), ); } - - debugPrint('🗑️ [RemoteControl] 缓存已清空 - voltage, battery, controlMode, ping'); + + debugPrint( + '🗑️ [RemoteControl] 缓存已清空 - voltage, battery, controlMode, ping', + ); } /// 🔥 退出登录时清空所有状态(比 _clearAllCache 更彻底,重置全部 state 字段) void clearAll() { + _emergencyAttempt++; _timer?.cancel(); _timer = null; _resumeTimer?.cancel(); @@ -1593,13 +2076,14 @@ class RemoteControlCubit extends Cubit _currentOriginY = 0; if (!isClosed) { - emit(RemoteControlState( - controlEntity: MachineControlStatusEntity(), - runningStatusModel: RunningStatusModel(), - )); + emit( + RemoteControlState( + controlEntity: MachineControlStatusEntity(), + runningStatusModel: RunningStatusModel(), + ), + ); } debugPrint('🗑️ [RemoteControl] clearAll - 所有状态已重置为初始值'); } - } diff --git a/lib/features/remote_control/presentation/bloc/remote_control_state.dart b/lib/features/remote_control/presentation/bloc/remote_control_state.dart index 61afffe7..25ad6793 100644 --- a/lib/features/remote_control/presentation/bloc/remote_control_state.dart +++ b/lib/features/remote_control/presentation/bloc/remote_control_state.dart @@ -7,12 +7,40 @@ import '../../domain/entities/reverse_camera_data.dart'; enum RemoteControlStatus { initial, controlling, error } +/// 本次遥控会话的最后一次用户操作,不代表设备已执行。 +enum MowerLastOperation { none, turnOn, turnOff } + +enum PermissionRequestPhase { + idle, + checking, + sending, + waiting, + granted, + failed, + timedOut, +} + class RemoteControlState extends Equatable { final RemoteControlStatus status; final MachineControlStatusEntity controlEntity; // 控制业务实体 + final MowerLastOperation lastMowerOperation; final String? errorMessage; final bool hasPermission; // 是否获得 0x12 权限 + final PermissionRequestPhase permissionRequestPhase; + final String permissionFeedbackKey; + final int permissionFeedbackId; + + bool get isPermissionRequestBusy => + permissionRequestPhase == PermissionRequestPhase.checking || + permissionRequestPhase == PermissionRequestPhase.sending || + permissionRequestPhase == PermissionRequestPhase.waiting; final bool isEmergency; + final bool hasEmergencyStatus; + + /// 本地急停请求状态,不代表已取得设备动作确认。 + final bool isEmergencyRequestPending; + final bool emergencyRequestFailed; + final String emergencyFeedbackKey; final bool isLocked; final int ping; final int battery; //电池量 @@ -42,9 +70,17 @@ class RemoteControlState extends Equatable { const RemoteControlState({ this.status = RemoteControlStatus.initial, required this.controlEntity, + this.lastMowerOperation = MowerLastOperation.none, this.errorMessage, this.hasPermission = false, + this.permissionRequestPhase = PermissionRequestPhase.idle, + this.permissionFeedbackKey = '', + this.permissionFeedbackId = 0, this.isEmergency = false, + this.hasEmergencyStatus = false, + this.isEmergencyRequestPending = false, + this.emergencyRequestFailed = false, + this.emergencyFeedbackKey = '', this.isLocked = false, this.ping = 0, this.battery = 0, @@ -70,9 +106,17 @@ class RemoteControlState extends Equatable { RemoteControlState copyWith({ RemoteControlStatus? status, MachineControlStatusEntity? controlEntity, + MowerLastOperation? lastMowerOperation, String? errorMessage, bool? hasPermission, + PermissionRequestPhase? permissionRequestPhase, + String? permissionFeedbackKey, + int? permissionFeedbackId, bool? isEmergency, + bool? hasEmergencyStatus, + bool? isEmergencyRequestPending, + bool? emergencyRequestFailed, + String? emergencyFeedbackKey, bool? isLocked, int? ping, int? battery, @@ -90,15 +134,28 @@ class RemoteControlState extends Equatable { bool? topRightIsExpanded, bool? obstacleRecognitionFlag, DeviceEntity? targetDevice, + bool clearTargetDevice = false, String? updateType, ReverseCameraData? reverseCamera, }) { return RemoteControlState( status: status ?? this.status, controlEntity: controlEntity ?? this.controlEntity, + lastMowerOperation: lastMowerOperation ?? this.lastMowerOperation, errorMessage: errorMessage ?? this.errorMessage, hasPermission: hasPermission ?? this.hasPermission, + permissionRequestPhase: + permissionRequestPhase ?? this.permissionRequestPhase, + permissionFeedbackKey: + permissionFeedbackKey ?? this.permissionFeedbackKey, + permissionFeedbackId: permissionFeedbackId ?? this.permissionFeedbackId, isEmergency: isEmergency ?? this.isEmergency, + hasEmergencyStatus: hasEmergencyStatus ?? this.hasEmergencyStatus, + isEmergencyRequestPending: + isEmergencyRequestPending ?? this.isEmergencyRequestPending, + emergencyRequestFailed: + emergencyRequestFailed ?? this.emergencyRequestFailed, + emergencyFeedbackKey: emergencyFeedbackKey ?? this.emergencyFeedbackKey, isLocked: isLocked ?? this.isLocked, ping: ping ?? this.ping, battery: battery ?? this.battery, @@ -113,11 +170,14 @@ class RemoteControlState extends Equatable { showRightPip: showRightPip ?? this.showRightPip, runningStatusModel: runningStatusModel ?? this.runningStatusModel, obstacleFlag: obstacleFlag ?? this.obstacleFlag, - hasReceivedStatusPush: hasReceivedStatusPush ?? this.hasReceivedStatusPush, + hasReceivedStatusPush: + hasReceivedStatusPush ?? this.hasReceivedStatusPush, topRightIsExpanded: topRightIsExpanded ?? this.topRightIsExpanded, obstacleRecognitionFlag: obstacleRecognitionFlag ?? this.obstacleRecognitionFlag, - targetDevice: targetDevice ?? this.targetDevice, + targetDevice: clearTargetDevice + ? null + : targetDevice ?? this.targetDevice, updateType: updateType, // 不使用 ??,因为我们想要 null 的时候就是 null reverseCamera: reverseCamera ?? this.reverseCamera, ); @@ -127,9 +187,17 @@ class RemoteControlState extends Equatable { List get props => [ status, controlEntity, + lastMowerOperation, errorMessage, hasPermission, + permissionRequestPhase, + permissionFeedbackKey, + permissionFeedbackId, isEmergency, + hasEmergencyStatus, + isEmergencyRequestPending, + emergencyRequestFailed, + emergencyFeedbackKey, isLocked, ping, battery, diff --git a/lib/features/remote_control/presentation/pages/remote_control_page.dart b/lib/features/remote_control/presentation/pages/remote_control_page.dart index aa794ae3..8d670707 100644 --- a/lib/features/remote_control/presentation/pages/remote_control_page.dart +++ b/lib/features/remote_control/presentation/pages/remote_control_page.dart @@ -8,7 +8,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; import 'package:maibu_satabot_v2/components/capsule_toast.dart'; -import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import '../../../../core/app/app_user_cubit.dart'; @@ -19,6 +19,7 @@ import '../bloc/remote_control_cubit.dart'; import '../bloc/remote_control_state.dart'; import '../widgets/center_control_area.dart'; import '../widgets/emergency_overlay.dart'; +import '../widgets/emergency_stop_button.dart'; import '../widgets/left_joystick_area.dart'; import '../widgets/right_joystick_area.dart'; import '../widgets/driving_guide_overlay.dart'; @@ -120,33 +121,30 @@ class _RemoteControlPageState extends State { // 🔥 离开安全模式:启动 90 秒倒计时 GetIt.I().exitSafeMode(); - // 释放远程控制权限(type=2:退出远程遥控页面释放) + // Schedule the priority zero before ending control; release only after the + // rate-limited stop finishes, so release cannot overtake the final stop. + final pendingStop = _controlSessionStarted + ? _cubit.stopAllMovement(reason: 'page_dispose') + : Future.value(); + if (_controlSessionStarted) _cubit.stopControlLoop(); final deviceId = _cubit.state.targetDevice?.deviceName; if (_controlSessionStarted && deviceId != null && deviceId.isNotEmpty) { - _cubit.releasePermission(deviceId: deviceId, type: 2).then((success) { - CapsuleToast.show( - success - ? _l10n.translate('remote_control.toast_released') - : _l10n.translate('remote_control.toast_release_failed'), - showCheck: success, - ); - }); + pendingStop + .then((_) => _cubit.releasePermission(deviceId: deviceId, type: 2)) + .then((success) { + CapsuleToast.show( + success + ? _l10n.translate('remote_control.toast_released') + : _l10n.translate('remote_control.toast_release_failed'), + showCheck: success, + ); + }); } _permissionSubscription?.cancel(); // 🔥 取消订阅 SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); - // 🔥 退页先把车真正停下:归零双轴 + 连发 30 帧停止指令。 - // 只靠 stopControlLoop() 断掉 200ms 循环是不够的:设备只认“最后收到的 - // 运动帧”,若手指还压在摇杆上就退出(没走松手归零),已下发的高速帧会 - // 让车继续跑到它自己的失联保护为止。与新版 HUD 折叠/退出的 deactivate() - // 同一口径。 - // 必须放在 stopControlLoop() 之前:stopAllMovement 末尾会按 _controlWanted - // 决定是否重启循环,这里同步把意图关掉,就不会在退页后留下无主定时器。 - if (_controlSessionStarted) { - unawaited(_cubit.stopAllMovement()); - _cubit.stopControlLoop(); - } + // The priority stop above uses the same >=250ms sender as normal movement. _cubit.stopReverseCameraMock(); // 🔥 停止倒车影像 Mock,避免定时器空转 // 🔥 重置权限状态,避免单例 hasPermission 残留导致下次进入不再查询接口 _cubit.resetPermissionState(); @@ -158,6 +156,7 @@ class _RemoteControlPageState extends State { deviceId: _modeDeviceId, target: ControlModeTarget.remote, cancelToPreview: true, + emergencyStopControl: const EmergencyStopButton(), onReady: () { if (_cubit.state.targetDevice?.deviceName != _modeDeviceId) return; _controlSessionStarted = true; @@ -229,7 +228,7 @@ class _RemoteControlPageState extends State { token != null && token.isNotEmpty) { _videoStreamUrl = - "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=$token"; + "webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/$deviceId?token=$token"; debugPrint('🎬 [WebRTC] URL构建成功: $_videoStreamUrl'); } else { _videoStreamUrl = ''; @@ -279,9 +278,11 @@ class _RemoteControlPageState extends State { ), BlocBuilder( - buildWhen: (p, c) => p.isEmergency != c.isEmergency, + buildWhen: (p, c) => + p.isEmergency != c.isEmergency || + p.hasEmergencyStatus != c.hasEmergencyStatus, builder: (context, state) { - return state.isEmergency + return state.isEmergency && state.hasEmergencyStatus ? const Positioned.fill(child: EmergencyOverlay()) : const SizedBox.shrink(); }, @@ -300,6 +301,8 @@ class _RemoteControlPageState extends State { }, buildWhen: (p, c) => p.hasPermission != c.hasPermission || + p.permissionRequestPhase != c.permissionRequestPhase || + p.permissionFeedbackId != c.permissionFeedbackId || p.isLocked != c.isLocked || p.topRightIsExpanded != c.topRightIsExpanded || p.obstacleRecognitionFlag != c.obstacleRecognitionFlag || diff --git a/lib/features/remote_control/presentation/widgets/center_control_area.dart b/lib/features/remote_control/presentation/widgets/center_control_area.dart index 505c9ead..993cc744 100644 --- a/lib/features/remote_control/presentation/widgets/center_control_area.dart +++ b/lib/features/remote_control/presentation/widgets/center_control_area.dart @@ -1,11 +1,13 @@ import 'package:cc_ui_kit/cc_ui_kit.dart'; import 'package:flutter/material.dart'; +import 'remote_control_link_feedback.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:maibu_satabot_v2/components/capsule_toast.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import '../bloc/remote_control_cubit.dart'; +import '../bloc/remote_control_state.dart'; import 'emergency_stop_button.dart'; class CenterControlArea extends StatelessWidget { @@ -43,7 +45,7 @@ class CenterControlArea extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ - _buildSliderBox(expandedWidth, 'chassis', true,context), + _buildSliderBox(expandedWidth, 'chassis', true, context), SizedBox(height: totalWidth * 0.01), ], ), @@ -60,7 +62,9 @@ class CenterControlArea extends StatelessWidget { SizedBox(height: totalWidth * 0.05), Text( - AppLocalizations.of(context).translate('remote_control.switch_view_hint'), + AppLocalizations.of( + context, + ).translate('remote_control.switch_view_hint'), style: const TextStyle(fontSize: 8, color: Colors.grey), ), ], @@ -73,7 +77,31 @@ class CenterControlArea extends StatelessWidget { width: expandedWidth, child: Column( mainAxisAlignment: MainAxisAlignment.end, - children: [_buildSliderBox(expandedWidth, 'mower', false,context)], + children: [ + _buildSliderBox(expandedWidth, 'mower', false, context), + const SizedBox(height: 6), + Text( + AppLocalizations.of( + context, + ).translate('remote_control.mower_last_operation', { + 'operation': AppLocalizations.of(context).translate( + switch (remoteState.lastMowerOperation) { + MowerLastOperation.turnOn => + 'remote_control.mower_operation_on', + MowerLastOperation.turnOff => + 'remote_control.mower_operation_off', + MowerLastOperation.none => + 'remote_control.mower_operation_none', + }, + ), + }), + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white.withValues(alpha: 0.65), + fontSize: 10, + ), + ), + ], ), ), ], @@ -83,12 +111,17 @@ class CenterControlArea extends StatelessWidget { ); } - Widget _buildSliderBox(double boxWidth, String deviceKey, bool isLeft,BuildContext context) { + Widget _buildSliderBox( + double boxWidth, + String deviceKey, + bool isLeft, + BuildContext context, + ) { // 🔥 使用deviceKey作为唯一标识,不依赖显示文本 - final label = deviceKey == 'chassis' + final label = deviceKey == 'chassis' ? AppLocalizations.of(context).translate('remote_control.chassis') : AppLocalizations.of(context).translate('remote_control.mower'); - + return SizedBox( width: boxWidth, child: Center( @@ -98,7 +131,7 @@ class CenterControlArea extends StatelessWidget { child: CCExpandSlider( label: label, svgStart: "assets/svgs/remote_up.svg", - svgCenter: deviceKey == 'mower' + svgCenter: deviceKey == 'mower' ? "assets/svgs/remote_scissors.svg" : "assets/svgs/remote_layers.svg", svgEnd: "assets/svgs/remote_down.svg", @@ -113,7 +146,12 @@ class CenterControlArea extends StatelessWidget { } // 🔥 新增:统一的业务逻辑分发方法 - void _handleSliderAction(String deviceKey, String action, BuildContext context) { + void _handleSliderAction( + String deviceKey, + String action, + BuildContext context, + ) { + RemoteControlLinkNotice.showIfDisconnected(context); debugPrint('🎯 [Slider 业务] deviceKey: $deviceKey, action: $action'); // 🔥 门槛检查:与摇杆一致,未收到 TCP 0x02 推送时禁止操作并提示。 @@ -133,7 +171,7 @@ class CenterControlArea extends StatelessWidget { _handleMowerAction(action, context); break; default: - debugPrint('⚠️ 未知的 deviceKey: $deviceKey'); + debugPrint('⚠️ 未知的 deviceKey: $deviceKey'); } // 🔥 在指令执行后触发震动反馈(增强手感) HapticFeedback.mediumImpact(); @@ -147,40 +185,34 @@ class CenterControlArea extends StatelessWidget { case "start": debugPrint('⬆️ 底盘 - 向上(例如:前进)'); // TODO: 发送底盘前进指令 - cubit.sendChassisCommand(1); + cubit.sendChassisCommand(1); break; case "center": debugPrint('️ 底盘 - 中间(例如:停止)'); // TODO: 发送底盘停止指令 - cubit.sendChassisCommand(0); + cubit.sendChassisCommand(0); break; case "end": debugPrint('⬇️ 底盘 - 向下(例如:后退)'); // TODO: 发送底盘后退指令 - cubit.sendChassisCommand(2); + cubit.sendChassisCommand(2); break; } } - // 🔥 割刀的业务逻辑(右滑块) + // 割刀开关(右滑块);段位映射由 Cubit 统一处理。 void _handleMowerAction(String action, BuildContext context) { final cubit = context.read(); switch (action) { case "start": - debugPrint('⬆️ 割刀 - 向上(例如:抬刀)'); - // TODO: 发送抬刀指令 - cubit.sendMowerCommand(1); + cubit.sendMowerSliderCommand(1); break; case "center": - debugPrint('⏹️ 割刀 - 中间(例如:保持)'); - // TODO: 发送保持指令 - cubit.sendMowerCommand(0); + cubit.sendMowerSliderCommand(0); break; case "end": - debugPrint('⬇️ 割刀 - 向下(例如:降刀)'); - // TODO: 发送降刀指令 - cubit.sendMowerCommand(2); + cubit.sendMowerSliderCommand(2); break; } } diff --git a/lib/features/remote_control/presentation/widgets/emergency_stop_button.dart b/lib/features/remote_control/presentation/widgets/emergency_stop_button.dart index d21fc457..c5b2954a 100644 --- a/lib/features/remote_control/presentation/widgets/emergency_stop_button.dart +++ b/lib/features/remote_control/presentation/widgets/emergency_stop_button.dart @@ -3,190 +3,141 @@ import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:vibration/vibration.dart'; -import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; +import '../../../../components/capsule_toast.dart'; +import '../../../../core/localization/app_localizations.dart'; import '../bloc/remote_control_cubit.dart'; +import 'emergency_stop_confirmation.dart'; +import '../../../device_control_mode/presentation/widgets/mode_independent_control.dart'; class EmergencyStopButton extends StatefulWidget { + const EmergencyStopButton({super.key, this.width = 120}); final double width; - const EmergencyStopButton({ - Key? key, - this.width = 120, - }) : super(key: key); @override State createState() => _EmergencyStopButtonState(); } -class _EmergencyStopButtonState extends State - with SingleTickerProviderStateMixin { - late AnimationController _progressController; - bool _isPressing = false; +class _EmergencyStopButtonState extends State { + bool _isConfirming = false; - @override - void initState() { - super.initState(); - _progressController = AnimationController( - vsync: this, - duration: const Duration(seconds: 3), - ); - - // 添加监听器,确保动画值变化时重建 UI - _progressController.addListener(() { - if (mounted) { - setState(() {}); - } - }); + Future _confirmAndSubmitEmergency(bool on) async { + final cubit = context.read(); + if (_isConfirming || cubit.state.isEmergencyRequestPending) return; + if (!cubit.checkEmergencyRequest(on)) { + CapsuleToast.show( + AppLocalizations.of( + context, + ).translate('remote_control.${cubit.state.emergencyFeedbackKey}'), + showCheck: false, + ); + return; + } + final sn = cubit.state.targetDevice?.deviceName; + _isConfirming = true; + bool confirmed; + try { + confirmed = await confirmEmergencyStop(context, engage: on, sn: sn ?? ''); + } finally { + _isConfirming = false; + } + if (!confirmed || !mounted || sn != cubit.state.targetDevice?.deviceName) { + return; + } + await cubit.updateEmergency(on); + if (!mounted || sn != cubit.state.targetDevice?.deviceName) return; + final key = cubit.state.emergencyFeedbackKey; + if (key.isNotEmpty) { + CapsuleToast.show( + AppLocalizations.of(context).translate('remote_control.$key'), + showCheck: false, + duration: const Duration(seconds: 3), + ); + } } @override - void dispose() { - _progressController.dispose(); - super.dispose(); - } - - void _resetProgress() { - setState(() => _isPressing = false); - _progressController.stop(); - _progressController.value = 0; - } - - - - @override - Widget build(BuildContext context) { - final isEmergencyActive = context - .watch() - .state - .isEmergency; + Widget build(BuildContext context) => + ModeIndependentControl(child: _buildButton(context)); + Widget _buildButton(BuildContext context) { + final state = context.watch().state; + final active = state.isEmergency; + final pending = state.isEmergencyRequestPending; final width = widget.width * 0.65; - final double indicatorSize = width + 20; - return SizedBox( - width: indicatorSize, - height: indicatorSize, - child: Stack( - alignment: Alignment.center, - children: [ - // 进度环 - 只在按压时显示 - AnimatedOpacity( - opacity: _isPressing ? 1.0 : 0.0, - duration: const Duration(milliseconds: 200), - child: SizedBox( - width: indicatorSize, - height: indicatorSize, - child: CircularProgressIndicator( - value: _progressController.value, - strokeWidth: 6, - color: Colors.red.withOpacity(0.9), - backgroundColor: Colors.red.withValues(alpha: 0.2), - ), + width: width + 20, + height: width + 20, + child: Center( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: pending + ? null + : () { + HapticFeedback.heavyImpact(); + _vibrate(); + _confirmAndSubmitEmergency(!active); + }, + child: Container( + width: width, + height: width, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: active + ? Colors.red.withValues(alpha: 0.5) + : const Color(0x80C53030), + boxShadow: active + ? [ + BoxShadow( + color: Colors.red.withValues(alpha: 0.5), + blurRadius: 20, + ), + ] + : [], ), - ), - - // 按钮主体 - GestureDetector( - onTap: () { - debugPrint('🔴 [点击] 触发急停'); - _triggerVibration(); - if (!isEmergencyActive) { - context.read().updateEmergency(true); - context.read().toggleLock(); - HapticFeedback.heavyImpact(); - } - }, - onLongPressStart: (_) { - debugPrint('🔴 [长按开始] isEmergency=$isEmergencyActive'); - _triggerVibration(); - if (isEmergencyActive && !_isPressing) { - setState(() => _isPressing = true); - debugPrint('🔴 [开始动画] 从 0 开始'); - _triggerVibration(); - _progressController.reset(); - _progressController.forward().then((_) { - debugPrint('🔴 [动画完成] _isPressing=$_isPressing'); - if (_isPressing && mounted) { - debugPrint('✅ [解除急停] 执行'); - _triggerVibration(); - context.read().updateEmergency(false); - context.read().toggleLock(); - HapticFeedback.vibrate(); - setState(() => _isPressing = false); - } - }); - } - }, - onLongPressEnd: (_) { - _triggerVibration(); - debugPrint('🔴 [长按结束]'); - if (_isPressing) { - _resetProgress(); - - } - }, - onLongPressCancel: () { - _triggerVibration(); - debugPrint('🔴 [长按取消]'); - if (_isPressing) { - _resetProgress(); - } - }, - child: Container( - width: width, - height: width, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: isEmergencyActive - ? Colors.red.withOpacity(0.5) - : const Color(0x80C53030), - boxShadow: isEmergencyActive - ? [ - BoxShadow( - color: Colors.red.withValues(alpha: 0.5), - blurRadius: 20, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SvgPicture.asset( + 'assets/svgs/remote_alert.svg', + width: width * 0.4, + colorFilter: ColorFilter.mode( + Colors.white.withValues(alpha: 0.5), + BlendMode.srcIn, ), - ] - : [], - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SvgPicture.asset( - 'assets/svgs/remote_alert.svg', - width: width * 0.4, + ), + const SizedBox(height: 6), + Text( + AppLocalizations.of(context).translate( + pending + ? 'remote_control.emergency_submitting' + : !state.hasEmergencyStatus + ? 'remote_control.emergency_unknown' + : active + ? 'remote_control.emergency_stopping' + : 'remote_control.emergency_inactive', + ), + style: TextStyle( color: Colors.white.withValues(alpha: 0.5), + fontSize: 14, + fontWeight: FontWeight.w900, ), - const SizedBox(height: 6), - Text( - isEmergencyActive - ? AppLocalizations.of(context).translate('remote_control.emergency_stopping') - : AppLocalizations.of(context).translate('remote_control.emergency_stop'), - style: TextStyle( - color: Colors.white.withValues(alpha: 0.5), - fontSize: 14, - fontWeight: FontWeight.w900, - ), - ), - ], - ), + ), + ], ), ), - ], + ), ), ); } - void _triggerVibration() { - Vibration.hasVibrator().then((hasVibrator) { - if (hasVibrator ?? false) { - Vibration.vibrate(duration: 50, amplitude: 380); - debugPrint(' 震动执行 - 10ms'); - } else { - debugPrint(' 设备不支持震动'); + Future _vibrate() async { + try { + if (await Vibration.hasVibrator()) { + await Vibration.vibrate(duration: 50, amplitude: 255); } - }).catchError((e) { - debugPrint('震动失败:$e'); - }); + } catch (_) { + // 无震动能力时仍可正常发起急停请求。 + } } } diff --git a/lib/features/remote_control/presentation/widgets/emergency_stop_confirmation.dart b/lib/features/remote_control/presentation/widgets/emergency_stop_confirmation.dart new file mode 100644 index 00000000..16dece94 --- /dev/null +++ b/lib/features/remote_control/presentation/widgets/emergency_stop_confirmation.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/localization/app_localizations.dart'; + +/// 只确认用户意图;关闭、返回或取消弹窗均不发送控制请求。 +Future confirmEmergencyStop( + BuildContext context, { + required bool engage, + required String sn, +}) async { + final tr = AppLocalizations.of(context); + return await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text( + tr.translate( + engage + ? 'remote_control.emergency_confirm_title' + : 'remote_control.emergency_release_title', + ), + ), + content: Text( + tr.translate( + engage + ? 'remote_control.emergency_confirm_message' + : 'remote_control.emergency_release_message', + {'sn': sn}, + ), + ), + actions: [ + TextButton( + key: const ValueKey('emergency-cancel'), + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(tr.translate('remote_control.emergency_cancel')), + ), + FilledButton( + key: const ValueKey('emergency-confirm'), + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text( + tr.translate( + engage + ? 'remote_control.emergency_confirm_stop' + : 'remote_control.emergency_confirm_release', + ), + ), + ), + ], + ), + ) ?? + false; +} diff --git a/lib/features/remote_control/presentation/widgets/left_joystick_area.dart b/lib/features/remote_control/presentation/widgets/left_joystick_area.dart index 333d0ca3..564b6226 100644 --- a/lib/features/remote_control/presentation/widgets/left_joystick_area.dart +++ b/lib/features/remote_control/presentation/widgets/left_joystick_area.dart @@ -1,6 +1,8 @@ +import '../../../../core/logging/remote_control_diagnostics.dart'; import 'dart:async'; import 'package:cc_ui_kit/cc_ui_kit.dart'; import 'package:flutter/material.dart'; +import 'remote_control_link_feedback.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:vibration/vibration.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; @@ -28,6 +30,10 @@ class _LeftJoystickAreaState extends State { /// 检查是否可以控制,不能则弹出提示 bool _checkCanControl(BuildContext context) { + if (!_hasShownNoPushDialog && + RemoteControlLinkNotice.showIfDisconnected(context)) { + _hasShownNoPushDialog = true; + } // 🔥 临时关闭「未收到推送不能控制」门槛,便于机器未开时用 Mock 假数据联调倒车影像。 // 联调完成后取消下面注释即可恢复。切勿删除本段逻辑。 // final cubit = context.read(); @@ -88,6 +94,7 @@ class _LeftJoystickAreaState extends State { child: CCJoystick( radius: widget.width, axisHint: AxisHint.forwardBackward, + onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields), onValueChanged: (value) { if (!_checkCanControl(context)) return; // 标记:正在触摸 @@ -135,7 +142,7 @@ class _LeftJoystickAreaState extends State { debugPrint('✅ 摇杆已停止 -> 强制 X=0, Y=0 停车'); // 🔥 使用安全方法,一次性清零双轴,确保只发送 (X=0, Y=0) - await context.read().stopAllMovement(); + await context.read().stopAllMovement(reason: 'forward_release'); } void _triggerVibration() { @@ -143,4 +150,4 @@ class _LeftJoystickAreaState extends State { if (has ?? false) Vibration.vibrate(duration: 12); }); } -} \ No newline at end of file +} diff --git a/lib/features/remote_control/presentation/widgets/permission_request_feedback.dart b/lib/features/remote_control/presentation/widgets/permission_request_feedback.dart new file mode 100644 index 00000000..6570848a --- /dev/null +++ b/lib/features/remote_control/presentation/widgets/permission_request_feedback.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../../../components/capsule_toast.dart'; +import '../../../../core/localization/app_localizations.dart'; +import '../bloc/remote_control_cubit.dart'; +import '../bloc/remote_control_state.dart'; + +/// Shared by both control entry points. Telemetry rebuilds never repeat a toast. +class PermissionRequestFeedback extends StatelessWidget { + const PermissionRequestFeedback({ + super.key, + required this.cubit, + required this.child, + }); + + final RemoteControlCubit cubit; + final Widget child; + + @override + Widget build(BuildContext context) => + BlocListener( + bloc: cubit, + listenWhen: (previous, current) => + previous.permissionFeedbackId != current.permissionFeedbackId && + current.permissionFeedbackKey.isNotEmpty, + listener: (context, state) => CapsuleToast.show( + AppLocalizations.of( + context, + ).translate('remote_control.' + state.permissionFeedbackKey), + duration: const Duration(seconds: 3), + showCheck: + state.permissionRequestPhase == PermissionRequestPhase.granted, + ), + child: child, + ); +} + +String permissionStatusText(BuildContext context, RemoteControlState state) { + final key = switch (state.permissionRequestPhase) { + PermissionRequestPhase.checking => 'permission_checking', + PermissionRequestPhase.sending => 'permission_sending', + PermissionRequestPhase.waiting => 'permission_waiting', + PermissionRequestPhase.timedOut => 'permission_unconfirmed', + PermissionRequestPhase.failed when !state.hasPermission => + 'permission_request_failed', + _ => state.hasPermission ? 'controlling' : 'not_controlling', + }; + return AppLocalizations.of(context).translate('remote_control.' + key); +} + +String permissionStatusHint(BuildContext context, RemoteControlState state) => + state.permissionFeedbackKey.isEmpty + ? permissionStatusText(context, state) + : AppLocalizations.of( + context, + ).translate('remote_control.' + state.permissionFeedbackKey); diff --git a/lib/features/remote_control/presentation/widgets/remote_control_link_feedback.dart b/lib/features/remote_control/presentation/widgets/remote_control_link_feedback.dart new file mode 100644 index 00000000..ae6973d1 --- /dev/null +++ b/lib/features/remote_control/presentation/widgets/remote_control_link_feedback.dart @@ -0,0 +1,106 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/components/capsule_toast.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; + +import '../bloc/remote_control_cubit.dart'; + +/// 只展示已有连接收到的心跳,不发送数据,也不参与重连或控制门控。 +class RemoteControlHeartbeatIndicator extends StatefulWidget { + const RemoteControlHeartbeatIndicator({ + super.key, + required this.heartbeats, + this.size = 10, + }); + + final Stream heartbeats; + final double size; + + @override + State createState() => + _RemoteControlHeartbeatIndicatorState(); +} + +class _RemoteControlHeartbeatIndicatorState + extends State { + StreamSubscription? _subscription; + Timer? _pulseTimer; + bool _lit = false; + + @override + void initState() { + super.initState(); + _listen(); + } + + @override + void didUpdateWidget(RemoteControlHeartbeatIndicator oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.heartbeats != widget.heartbeats) { + _subscription?.cancel(); + _pulseTimer?.cancel(); + _lit = false; + _listen(); + } + } + + void _listen() { + _subscription = widget.heartbeats.listen((_) { + if (!mounted) return; + _pulseTimer?.cancel(); + setState(() => _lit = true); + _pulseTimer = Timer(const Duration(milliseconds: 300), () { + if (mounted) setState(() => _lit = false); + }); + }); + } + + @override + void dispose() { + _subscription?.cancel(); + _pulseTimer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Tooltip( + message: AppLocalizations.of( + context, + ).translate('remote_control.tcp_heartbeat'), + child: Padding( + padding: const EdgeInsets.all(6), + child: AnimatedContainer( + duration: const Duration(milliseconds: 100), + width: widget.size, + height: widget.size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: _lit ? const Color(0xFF36C878) : const Color(0xFF86909C), + ), + ), + ), + ); +} + +/// 操作时读取现有 TCP 连接状态,仅提示,不拦截、不重连、不改变指令。 +class RemoteControlLinkNotice { + static DateTime? _lastShownAt; + + static bool showIfDisconnected(BuildContext context) { + if (sl().isControlLinkConnected) return false; + final now = DateTime.now(); + if (_lastShownAt == null || + now.difference(_lastShownAt!) >= const Duration(seconds: 2)) { + _lastShownAt = now; + CapsuleToast.show( + AppLocalizations.of( + context, + ).translate('remote_control.tcp_unavailable'), + showCheck: false, + ); + } + return true; + } +} diff --git a/lib/features/remote_control/presentation/widgets/right_joystick_area.dart b/lib/features/remote_control/presentation/widgets/right_joystick_area.dart index 02c89f03..10e5ee3c 100644 --- a/lib/features/remote_control/presentation/widgets/right_joystick_area.dart +++ b/lib/features/remote_control/presentation/widgets/right_joystick_area.dart @@ -1,5 +1,7 @@ +import '../../../../core/logging/remote_control_diagnostics.dart'; import 'package:cc_ui_kit/cc_ui_kit.dart'; import 'package:flutter/material.dart'; +import 'remote_control_link_feedback.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:vibration/vibration.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; @@ -27,6 +29,10 @@ class _RightJoystickAreaState extends State { /// 检查是否可以控制,不能则弹出提示 bool _checkCanControl(BuildContext context) { + if (!_hasShownNoPushDialog && + RemoteControlLinkNotice.showIfDisconnected(context)) { + _hasShownNoPushDialog = true; + } // 🔥 临时关闭「未收到推送不能控制」门槛,便于机器未开时用 Mock 假数据联调倒车影像。 // 联调完成后取消下面注释即可恢复。切勿删除本段逻辑。 // final cubit = context.read(); @@ -87,6 +93,7 @@ class _RightJoystickAreaState extends State { child: CCJoystick( radius: widget.width, axisHint: AxisHint.leftRight, + onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields), onValueChanged: (value) { if (!_checkCanControl(context)) return; int currentX = value.x.toInt(); @@ -107,7 +114,7 @@ class _RightJoystickAreaState extends State { _lastX = 0; // 🔥 使用安全方法,一次性清零双轴,确保只发送 (X=0, Y=0) - await context.read().stopAllMovement(); + await context.read().stopAllMovement(reason: 'turn_release'); }, ), ), @@ -128,4 +135,4 @@ class _RightJoystickAreaState extends State { void _triggerVibration() { Vibration.vibrate(duration: 12); } -} \ No newline at end of file +} diff --git a/lib/features/remote_control/presentation/widgets/top_status_bar.dart b/lib/features/remote_control/presentation/widgets/top_status_bar.dart index 66affe32..2f0aaa89 100644 --- a/lib/features/remote_control/presentation/widgets/top_status_bar.dart +++ b/lib/features/remote_control/presentation/widgets/top_status_bar.dart @@ -14,6 +14,8 @@ import '../../../../core/logging/i_logger_service.dart'; import '../../../devices/domain/entities/device_entity.dart'; import '../../../devices/presentation/bloc/devices_cubit.dart'; import '../../data/models/running_status_model.dart'; +import 'remote_control_link_feedback.dart'; +import 'permission_request_feedback.dart'; import '../bloc/remote_control_cubit.dart'; class TopStatusBar extends StatelessWidget { @@ -83,41 +85,37 @@ class TopStatusBar extends StatelessWidget { const SizedBox(width: 8), // 2. 控制状态 (对应 StatusChipLeft) - StatusChip( - text: remoteState.hasPermission - ? AppLocalizations.of( - context, - ).translate('remote_control.controlling') - : AppLocalizations.of( - context, - ).translate('remote_control.not_controlling'), - color: remoteState.hasPermission - ? const Color(0xFF1DB954) - : Colors.red, - icon: Icons.eighteen_mp, - breathing: !remoteState.hasPermission, - onTap: () { - if (!remoteState.hasPermission) { - // 🔥 点击后发起抢占:查权限 + 无权限则发 TCP switch_control - debugPrint('🔑 [TopStatusBar] 👆 用户手动点击“未在控制”,请求抢占控制权'); - final targetDevice = - _remoteControlCubit.state.targetDevice; - if (targetDevice != null) { + PermissionRequestFeedback( + cubit: _remoteControlCubit, + child: Tooltip( + message: permissionStatusHint(context, remoteState), + child: StatusChip( + text: permissionStatusText(context, remoteState), + color: remoteState.isPermissionRequestBusy + ? Colors.orange + : remoteState.hasPermission + ? const Color(0xFF1DB954) + : Colors.red, + icon: Icons.eighteen_mp, + breathing: !remoteState.hasPermission, + onTap: () { + if (remoteState.hasPermission || remoteState.isPermissionRequestBusy) return; _remoteControlCubit.requestControlPermissionS( - targetDevice.deviceName, + _remoteControlCubit.state.targetDevice?.deviceName ?? '', 'app', source: '手动点击', grabControl: true, ); - } else { - debugPrint('❌ [TopStatusBar] targetDevice 为空,无法请求权限'); - } - } - }, + }, + ), + ), ), const SizedBox(width: 8), // 3. 锁定状态 (对应 SmallFunctionButton) + RemoteControlHeartbeatIndicator( + heartbeats: _remoteControlCubit.serverHeartbeats, + ), _buildIconButton( remoteState.isLocked ? "assets/svgs/remote_lock.svg" @@ -476,6 +474,7 @@ class TopStatusBar extends StatelessWidget { // 🔥 新增:统一的业务逻辑分发方法 void _handleSliderAction(String label, String action, BuildContext context) { + RemoteControlLinkNotice.showIfDisconnected(context); debugPrint('🎯 [Slider 业务] label: $label, action: $action'); // 🔥 根据 label 区分不同的设备 diff --git a/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart b/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart index b7378362..b68f649e 100644 --- a/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart +++ b/lib/features/v2/device_list/presentation/pages/device_detail_page_v2.dart @@ -615,6 +615,20 @@ class _DeviceDetailPageV2State extends State { modeText, l10n.translate('device_detail_v2.stat_control_mode'), ), + _statCard( + Icons.emergency_outlined, + st?.emergencyStop == null + ? '--' + : l10n.translate( + st!.emergencyStop! + ? 'device_detail_v2.emergency_stop_active' + : 'device_detail_v2.emergency_stop_inactive', + ), + l10n.translate('device_detail_v2.stat_emergency_stop'), + valueColor: st?.emergencyStop == true + ? const Color(0xFFDC2626) + : _navy, + ), _statCard( Icons.thermostat_outlined, st == null ? '--' : '${st.chipTemp.toStringAsFixed(1)}°', @@ -678,25 +692,21 @@ class _DeviceDetailPageV2State extends State { behavior: HitTestBehavior.opaque, child: Column( children: [ - Row( - children: [ - Expanded(child: tiles[0]), - const SizedBox(width: 10), - Expanded(child: tiles[1]), - const SizedBox(width: 10), - Expanded(child: tiles[2]), - ], - ), - const SizedBox(height: 8), - Row( - children: [ - Expanded(child: tiles[3]), - const SizedBox(width: 10), - Expanded(child: tiles[4]), - const SizedBox(width: 10), - Expanded(child: tiles[5]), - ], - ), + for (var row = 0; row < tiles.length; row += 3) ...[ + if (row > 0) const SizedBox(height: 8), + Row( + children: [ + for (var column = 0; column < 3; column++) ...[ + if (column > 0) const SizedBox(width: 10), + Expanded( + child: row + column < tiles.length + ? tiles[row + column] + : const SizedBox.shrink(), + ), + ], + ], + ), + ], ], ), ), @@ -733,6 +743,7 @@ class _DeviceDetailPageV2State extends State { String value, String label, { double valueFontSize = 16, + Color? valueColor, }) { return Container( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4), @@ -752,7 +763,7 @@ class _DeviceDetailPageV2State extends State { style: TextStyle( fontSize: valueFontSize, fontWeight: FontWeight.w800, - color: _navy, + color: valueColor ?? _navy, ), ), const SizedBox(height: 2), diff --git a/packages/cc_ui_kit/lib/src/cc_joystick.dart b/packages/cc_ui_kit/lib/src/cc_joystick.dart index efe3e075..a4882b4a 100644 --- a/packages/cc_ui_kit/lib/src/cc_joystick.dart +++ b/packages/cc_ui_kit/lib/src/cc_joystick.dart @@ -63,6 +63,8 @@ class CCJoystick extends StatefulWidget { final AxisHint axisHint; final Function(JoystickValue) onValueChanged; final VoidCallback? onPress; + /// Optional observer only; failures in diagnostics cannot affect gestures. + final void Function(String event, Map fields)? onDiagnostic; final Future Function()? onPanEnd; // 🔥 修复:改为异步回调 final double radius; @@ -74,6 +76,7 @@ class CCJoystick extends StatefulWidget { required this.axisHint, required this.onValueChanged, this.onPress, + this.onDiagnostic, this.onPanEnd, // 🔥 新增 this.radius = 80, this.skin, @@ -89,6 +92,16 @@ class _CustomJoystickState extends State late AnimationController _floatController; bool _isPanning = false; // 🔥 跟踪是否正在拖拽 + void _diagnose(String event, [Map fields = const {}]) { + try { + widget.onDiagnostic?.call(event, { + 'axis': widget.axisHint.name, + 'panning': _isPanning, + ...fields, + }); + } catch (_) {} + } + @override void initState() { super.initState(); @@ -116,7 +129,10 @@ class _CustomJoystickState extends State y = ((-_offset.dy / widget.radius) * 100).clamp(-100, 100).toInt(); } - widget.onValueChanged(JoystickValue(_applyDeadZone(x), _applyDeadZone(y))); + final outputX = _applyDeadZone(x); + final outputY = _applyDeadZone(y); + _diagnose('value', {'rawX': x, 'rawY': y, 'x': outputX, 'y': outputY}); + widget.onValueChanged(JoystickValue(outputX, outputY)); } int _applyDeadZone(int value, {int deadZone = 5}) { @@ -130,16 +146,17 @@ class _CustomJoystickState extends State onPointerUp: (_) async { if (_isPanning) { debugPrint('🛡️ [兜底] 全局指针抬起,强制归零'); - await _handlePanEnd(); + await _handlePanEnd(reason: 'pointer_up'); } }, onPointerCancel: (_) async { - await _handlePanEnd(); + await _handlePanEnd(reason: 'pointer_cancel'); }, child: GestureDetector( behavior: HitTestBehavior.opaque, onPanStart: (_) { _isPanning = true; + _diagnose('gesture_start'); widget.onPress?.call(); }, onPanUpdate: (details) { @@ -165,12 +182,12 @@ class _CustomJoystickState extends State }, onPanEnd: (_) async { debugPrint('✋ [正常] onPanEnd 触发'); - await _handlePanEnd(); + await _handlePanEnd(reason: 'pan_end'); }, onPanCancel: () async { // 🔥 新增:处理手势取消(如来电中断) debugPrint('⚠️ [异常] onPanCancel 触发'); - await _handlePanEnd(); + await _handlePanEnd(reason: 'pan_cancel'); }, child: AnimatedBuilder( animation: _floatController, @@ -192,7 +209,8 @@ class _CustomJoystickState extends State } // 🔥 统一的松手处理逻辑 - Future _handlePanEnd() async { + Future _handlePanEnd({required String reason}) async { + _diagnose('gesture_end', {'reason': reason, 'willStop': _isPanning}); if (!_isPanning) return; _isPanning = false; setState(() => _offset = Offset.zero); // 归位 diff --git a/test/control_frame_scheduler_test.dart b/test/control_frame_scheduler_test.dart new file mode 100644 index 00000000..bec75585 --- /dev/null +++ b/test/control_frame_scheduler_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:maibu_satabot_v2/core/network/tcp/control_frame_scheduler.dart'; + +void main() { + testWidgets('movement waits 250ms and replaces pending older input', ( + tester, + ) async { + var nowUs = 0; + final scheduler = ControlFrameScheduler(nowUs: () => nowUs); + final writes = []; + Future write(int input) async { + writes.add(input); + return true; + } + + final first = scheduler.submit( + () => write(10), + priority: false, + isCurrent: () => true, + ); + await tester.pump(); + expect(await first, isTrue); + nowUs = 100000; + await tester.pump(const Duration(milliseconds: 100)); + final replaced = scheduler.submit( + () => write(20), + priority: false, + isCurrent: () => true, + ); + nowUs = 200000; + await tester.pump(const Duration(milliseconds: 100)); + final latest = scheduler.submit( + () => write(30), + priority: false, + isCurrent: () => true, + ); + expect(await replaced, isFalse); + expect(writes, [10]); + nowUs = 249000; + await tester.pump(const Duration(milliseconds: 49)); + expect(writes, [10]); + nowUs = 250000; + await tester.pump(const Duration(milliseconds: 1)); + expect(await latest, isTrue); + expect(writes, [10, 30]); + }); + + testWidgets('priority zero replaces movement and shares the 250ms gate', ( + tester, + ) async { + var nowUs = 0; + final scheduler = ControlFrameScheduler(nowUs: () => nowUs); + final writes = []; + Future write(int input) async { + writes.add(input); + return true; + } + + scheduler.submit(() => write(50), priority: false, isCurrent: () => true); + await tester.pump(); + nowUs = 100000; + await tester.pump(const Duration(milliseconds: 100)); + final movement = scheduler.submit( + () => write(75), + priority: false, + isCurrent: () => true, + ); + nowUs = 150000; + await tester.pump(const Duration(milliseconds: 50)); + final stop = scheduler.submit( + () => write(0), + priority: true, + isCurrent: () => true, + ); + expect(await movement, isFalse); + nowUs = 249000; + await tester.pump(const Duration(milliseconds: 99)); + expect(writes, [50]); + nowUs = 250000; + await tester.pump(const Duration(milliseconds: 1)); + expect(await stop, isTrue); + expect(writes, [50, 0]); + }); +} diff --git a/test/control_mode_entry_widget_test.dart b/test/control_mode_entry_widget_test.dart index e4b07841..69320e4c 100644 --- a/test/control_mode_entry_widget_test.dart +++ b/test/control_mode_entry_widget_test.dart @@ -10,6 +10,7 @@ import 'package:maibu_satabot_v2/features/device_control_mode/domain/entities/de import 'package:maibu_satabot_v2/features/device_control_mode/domain/usecases/device_control_mode_usecases.dart'; import 'package:maibu_satabot_v2/features/device_control_mode/presentation/cubit/control_mode_entry_cubit.dart'; import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart'; +import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/mode_independent_control.dart'; import 'support/control_mode_fakes.dart'; final _translations = {}; @@ -215,6 +216,94 @@ void main() { expect(drives, 1); }); + testWidgets('independent emergency and settings stay usable before mode confirmation', ( + tester, + ) async { + repo.initial = '2'; + sl.registerSingleton(WatchDeviceControlModeUseCase(repo)); + sl.registerSingleton(ChangeDeviceControlModeUseCase(repo)); + var stops = 0; + var originalStops = 0; + var drives = 0; + var activations = 0; + await tester.pumpWidget( + app( + ControlModeEntryGate( + deviceId: 'SN002', + target: ControlModeTarget.remote, + cancelToPreview: true, + emergencyStopControl: TextButton( + onPressed: () => stops++, + child: const Text('independent stop'), + ), + onReady: () => activations++, + child: Scaffold( + body: Column( + children: [ + ModeIndependentControl( + child: TextButton( + key: const Key('original-stop'), + onPressed: () => originalStops++, + child: const Text('original stop'), + ), + ), + Builder( + builder: (context) => ModeIndependentControl( + child: IconButton( + key: const Key('independent-settings'), + icon: const Icon(Icons.settings), + onPressed: () => showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('video settings'), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('close settings'), + ), + ], + ), + ), + ), + ), + ), + TextButton( + key: const Key('blocked-drive'), + onPressed: () => drives++, + child: const Text('drive'), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + // 模式弹窗内急停可用,不会触发模式切换或激活遥控。 + await tester.tap(find.text('independent stop').last); + expect(stops, 1); + expect(repo.requests, isEmpty); + expect(activations, 0); + await tester.tap(find.byIcon(Icons.close_rounded).first); + await tester.pumpAndSettle(); + expect(find.text('independent stop'), findsNothing); + await tester.tap(find.byKey(const Key('original-stop'))); + expect(originalStops, 1); + expect(stops, 1); + await tester.tap(find.byKey(const Key('independent-settings'))); + await tester.pumpAndSettle(); + expect(find.text('video settings'), findsOneWidget); + await tester.tap(find.text('close settings')); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const Key('blocked-drive')), + warnIfMissed: false, + ); + expect(drives, 0); + expect(activations, 0); + expect(repo.requests, isEmpty); + }); + testWidgets('取消遥控模式确认返回来源页,不激活控制或下发切换', (tester) async { repo.initial = '2'; sl.registerSingleton(WatchDeviceControlModeUseCase(repo)); diff --git a/test/device_emergency_stop_status_test.dart b/test/device_emergency_stop_status_test.dart new file mode 100644 index 00000000..e7d35f82 --- /dev/null +++ b/test/device_emergency_stop_status_test.dart @@ -0,0 +1,154 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/data/datasources/mower_realtime_datasource.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/data/repositories/mower_realtime_repository_impl.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/host_realtime_message_entity.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_entity.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/interfaces/mqtt_client.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_message.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/task_message_repository.dart'; +import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart'; +import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/entities/running_status_entity.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart'; + +class _MqttClient extends Fake implements MqttClient { + final messages = StreamController.broadcast(); + + @override + Stream get messageStream => messages.stream; + @override + Future subscribe(String topic) async {} + @override + Future unsubscribe(String topic) async {} + + void send(Map data, {String sn = 'robot-1'}) { + messages.add( + MqttMessage( + topic: 'device/$sn/host/realTime/message', + payload: jsonEncode({'data': data}), + ), + ); + } +} + +class _Tasks extends Fake implements TaskMessageRepository { + @override + Stream get taskArriveStream => const Stream.empty(); + @override + Stream get taskStatusStream => const Stream.empty(); +} + +class _Logger extends Fake implements ILoggerService { + @override + void log( + String message, { + bool isWarning = false, + Map? data, + }) {} +} + +class _TcpClient extends Fake implements TcpClient {} + +class _Dispatcher extends Fake implements NetMessageDispatcher {} + +void main() { + test('missing and invalid emergency states stay unknown', () { + expect(HostRealtimeMessageEntity.fromJson({}).emergencyStop, isNull); + for (final raw in [null, '', 'unknown', 2, -1, [], {}]) { + expect( + HostRealtimeMessageEntity.fromJson({ + 'emergency_stop': raw, + }).emergencyStop, + isNull, + ); + } + for (final raw in [true, 1, '1', 'true']) { + expect( + HostRealtimeMessageEntity.fromJson({ + 'emergency_stop': raw, + }).emergencyStop, + isTrue, + ); + } + for (final raw in [false, 0, '0', 'false']) { + expect( + HostRealtimeMessageEntity.fromJson({ + 'emergency_stop': raw, + }).emergencyStop, + isFalse, + ); + } + }); + + test( + 'location copies preserve emergency state and missing reports clear it', + () { + const stopped = RunningStatusEntity(emergencyStop: true); + expect(stopped.copyWith(latitude: 31.2).emergencyStop, isTrue); + final released = stopped.copyWith(emergencyStop: false); + expect(released.emergencyStop, isFalse); + expect(released, isNot(stopped)); + expect(released.copyWith(emergencyStop: null).emergencyStop, isNull); + }, + ); + + testWidgets( + 'host reports update detail state without GPS and reset on device change', + (tester) async { + final mqtt = _MqttClient(); + final source = MowerRealtimeDataSourceImpl(mqtt); + sl.registerSingleton(_Logger()); + sl.registerSingleton(_Tasks()); + sl.registerSingleton( + MowerRealtimeRepositoryImpl(source), + ); + final bloc = DeviceStatusBloc(_Dispatcher(), client: _TcpClient()); + addTearDown(() async { + await bloc.close(); + await source.stopListening(); + source.dispose(); + await mqtt.messages.close(); + await sl.reset(); + }); + + bloc.startMqttRealtimeListening('robot-1'); + await tester.pump(); + for (final data in >[ + {'emergency_stop': false}, + {'emergency_stop': true}, + {'emergency_stop': 0}, + {}, + ]) { + mqtt.send(data); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); + expect( + (bloc.state as DeviceStatusUpdated).status.emergencyStop, + data.containsKey('emergency_stop') + ? data['emergency_stop'] != 0 && data['emergency_stop'] != false + : null, + ); + } + + mqtt.send({'emergency_stop': true}); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); + bloc.startMqttRealtimeListening('robot-2'); + await tester.pump(); + expect(bloc.state, isA()); + mqtt.send({'emergency_stop': true}); + mqtt.send({'control_mode': 1}, sn: 'robot-2'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); + expect((bloc.state as DeviceStatusUpdated).status.emergencyStop, isNull); + }, + ); +} diff --git a/test/device_emergency_stop_test.dart b/test/device_emergency_stop_test.dart new file mode 100644 index 00000000..a380f29b --- /dev/null +++ b/test/device_emergency_stop_test.dart @@ -0,0 +1,141 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/error/failure.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_target.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart'; + +void main() { + late Dio dio; + late RequestDeviceEmergencyStopUseCase request; + late List requests; + dynamic body; + int status = 200; + DioExceptionType? errorType; + + setUp(() { + requests = []; + body = {'code': 200}; + status = 200; + errorType = null; + dio = Dio(); + // Resolve locally: these tests never contact a backend or a machine. + dio.interceptors.add( + InterceptorsWrapper( + onRequest: (options, handler) { + requests.add(options); + if (errorType != null) { + handler.reject( + DioException(requestOptions: options, type: errorType!), + ); + } else { + handler.resolve( + Response( + requestOptions: options, + statusCode: status, + data: body, + ), + ); + } + }, + ), + ); + request = RequestDeviceEmergencyStopUseCase( + DeviceEmergencyStopRepositoryImpl(EmergencyStopRemoteDatasource(dio)), + ); + }); + + tearDown(() => dio.close(force: true)); + + for (final target in EmergencyStopTarget.values) { + test( + '${target.name} uses GET query parameters in selected environment', + () async { + expect(requests, isEmpty); + final result = await request(' DEVICE-1 ', target); + expect(result.isRight(), isTrue); + final options = requests.single; + expect(options.method, 'GET'); + expect(options.data, isNull); + expect(options.queryParameters, { + 'deviceId': 'DEVICE-1', + 'eStop': target == EmergencyStopTarget.engage ? 1 : 0, + }); + expect(options.uri.path, '/iot/host/eStopChange'); + expect(options.uri.origin, EnvConfig.baseUrl); + const environment = String.fromEnvironment('ENV', defaultValue: 'test'); + expect(options.uri.port, environment == 'prod' ? 8081 : 59003); + expect(options.headers['Cache-Control'], 'no-store'); + // API request completion has no device-state result attached to it. + }, + ); + } + + test('empty device ID fails without sending a request', () async { + final result = await request(' ', EmergencyStopTarget.engage); + expect(result.isLeft(), isTrue); + expect(requests, isEmpty); + }); + + test( + 'string business success code follows existing host convention', + () async { + body = {'code': '200', 'data': true}; + expect( + (await request('DEVICE-1', EmergencyStopTarget.engage)).isRight(), + isTrue, + ); + }, + ); + + final invalidResponses = { + 'empty response': null, + 'text response': 'ok', + 'missing business code': {'data': true}, + 'business rejection': {'code': 500}, + 'explicit failure': {'code': 200, 'data': false}, + 'top-level rejection': {'code': 200, 'accepted': false}, + 'device rejection': { + 'code': 200, + 'data': {'accepted': false}, + }, + }; + for (final response in invalidResponses.entries) { + test('${response.key} is not reported as accepted', () async { + body = response.value; + final result = await request('DEVICE-1', EmergencyStopTarget.release); + expect(result.isLeft(), isTrue); + result.fold( + (failure) => expect(failure, isA()), + (_) => fail('Unexpected success'), + ); + }); + } + + test('HTTP failure is not masked by a successful business code', () async { + status = 500; + expect( + (await request('DEVICE-1', EmergencyStopTarget.engage)).isLeft(), + isTrue, + ); + }); + + for (final type in [ + DioExceptionType.connectionTimeout, + DioExceptionType.sendTimeout, + DioExceptionType.receiveTimeout, + DioExceptionType.connectionError, + ]) { + test('${type.name} remains unconfirmed and is not retried', () async { + errorType = type; + final result = await request('DEVICE-1', EmergencyStopTarget.release); + result.fold( + (failure) => expect(failure, isA()), + (_) => fail('Unexpected success'), + ); + expect(requests, hasLength(1)); + }); + } +} diff --git a/test/pv_realtime_telemetry_test.dart b/test/pv_realtime_telemetry_test.dart new file mode 100644 index 00000000..ab00ccf4 --- /dev/null +++ b/test/pv_realtime_telemetry_test.dart @@ -0,0 +1,193 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/data/datasources/mower_realtime_datasource.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/data/repositories/mower_realtime_repository_impl.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/host_realtime_message_entity.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_entity.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/interfaces/mqtt_client.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_message.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/task_message_repository.dart'; +import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart'; +import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/entities/running_status_entity.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/models/pv_telemetry.dart'; + +class _Mqtt extends Fake implements MqttClient { + final messages = StreamController.broadcast(); + @override + Stream get messageStream => messages.stream; + @override + Future subscribe(String topic) async {} + @override + Future unsubscribe(String topic) async {} + + void send(String topic, Object data) => messages.add( + MqttMessage(topic: topic, payload: jsonEncode({'data': data})), + ); +} + +class _Tasks extends Fake implements TaskMessageRepository { + @override + Stream get taskArriveStream => const Stream.empty(); + @override + Stream get taskStatusStream => const Stream.empty(); +} + +class _Logger extends Fake implements ILoggerService { + @override + void log( + String message, { + bool isWarning = false, + Map? data, + }) {} +} + +class _Tcp extends Fake implements TcpClient {} + +class _Dispatcher extends Fake implements NetMessageDispatcher {} + +void main() { + test('missing reports stay unknown and reported zero is a real value', () { + final empty = PvTelemetry.fromRunningStatus(const RunningStatusEntity()); + expect(empty.speed, isNull); + expect(empty.leftMeasuredRpm, isNull); + expect(empty.mowerRpm, isNull); + expect(empty.battery, isNull); + final zero = PvTelemetry.fromRunningStatus( + RunningStatusEntity( + knifeCuttingSpeed: '0', + hostRealtime: HostRealtimeMessageEntity.fromJson({ + 'linear_speed': 0, + 'left_measured_rpm': '0', + 'battery_percentage': 0, + }), + ), + ); + expect(zero.speed, 0); + expect(zero.leftMeasuredRpm, 0); + expect(zero.rightMeasuredRpm, isNull); + expect(zero.mowerRpm, 0); + expect(zero.battery, 0); + }); + + test('invalid numbers stay unknown, signed wheel speeds preserve units', () { + final telemetry = PvTelemetry.fromRunningStatus( + RunningStatusEntity( + knifeCuttingSpeed: 'NaN', + hostRealtime: HostRealtimeMessageEntity.fromJson({ + 'linear_speed': -0.25, + 'left_measured_rpm': -22.5, + 'right_measured_rpm': 'bad', + 'left_target_rpm': -25, + 'right_target_rpm': 'Infinity', + 'battery_percentage': 101, + }), + ), + ); + expect(telemetry.speed, -0.25); + expect(telemetry.leftMeasuredRpm, -22.5); + expect(telemetry.leftTargetRpm, -25); + expect(telemetry.rightMeasuredRpm, isNull); + expect(telemetry.rightTargetRpm, isNull); + expect(telemetry.mowerRpm, isNull); + expect(telemetry.battery, isNull); + }); + + testWidgets( + 'MQTT reaches HUD without GPS, clears missing values and resets devices', + (tester) async { + final mqtt = _Mqtt(); + final source = MowerRealtimeDataSourceImpl(mqtt); + sl.registerSingleton(_Logger()); + sl.registerSingleton(_Tasks()); + sl.registerSingleton( + MowerRealtimeRepositoryImpl(source), + ); + final bloc = DeviceStatusBloc(_Dispatcher(), client: _Tcp()); + addTearDown(() async { + await bloc.close(); + await source.stopListening(); + source.dispose(); + await mqtt.messages.close(); + await sl.reset(); + }); + PvTelemetry snapshot() => PvTelemetry.fromRunningStatus( + bloc.state is DeviceStatusUpdated + ? (bloc.state as DeviceStatusUpdated).status + : null, + ); + Future flush() async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); + } + + const hostTopic = 'device/robot-1/host/realTime/message'; + const vehicleTopic = 'mower/robot-1/property/realtime/post'; + bloc.startMqttRealtimeListening('robot-1'); + await tester.pump(); + mqtt.send(hostTopic, { + 'linear_speed': -0.3, + 'left_measured_rpm': -10, + 'right_measured_rpm': -11, + 'left_target_rpm': -12, + 'right_target_rpm': -13, + 'motion': 'moving', + 'battery_percentage': 75, + }); + mqtt.send(vehicleTopic, [ + {'name': 'cuttingSpeed', 'value': 2400, 'unit': 'rpm'}, + ]); + await flush(); + expect(snapshot().speed, -0.3); + expect(snapshot().leftMeasuredRpm, -10); + expect(snapshot().rightMeasuredRpm, -11); + expect(snapshot().leftTargetRpm, -12); + expect(snapshot().rightTargetRpm, -13); + expect(snapshot().mowerRpm, 2400); + expect(snapshot().motion, 'moving'); + + mqtt.send(vehicleTopic, [ + {'name': 'cuttingSpeed', 'value': '0', 'unit': 'rpm'}, + ]); + await flush(); + expect(snapshot().mowerRpm, 0); + expect(snapshot().speed, -0.3); + mqtt.send(hostTopic, {'linear_speed': 0, 'left_measured_rpm': 0}); + await flush(); + expect(snapshot().speed, 0); + expect(snapshot().rightMeasuredRpm, isNull); + expect(snapshot().leftTargetRpm, isNull); + expect(snapshot().battery, isNull); + + // Both frames parse to the same legacy numeric defaults. Presence must still emit. + mqtt.send(hostTopic, {}); + await flush(); + expect(snapshot().speed, isNull); + expect(snapshot().leftMeasuredRpm, isNull); + expect(snapshot().mowerRpm, 0); + mqtt.send(vehicleTopic, [ + {'name': 'voltage', 'value': '48', 'unit': 'V'}, + ]); + await flush(); + expect(snapshot().speed, isNull); + expect(snapshot().leftMeasuredRpm, isNull); + expect(snapshot().mowerRpm, isNull); + + bloc.startMqttRealtimeListening('robot-2'); + await tester.pump(); + mqtt.send(hostTopic, {'linear_speed': 1}); + mqtt.send('device/robot-2/host/realTime/message', {'control_mode': 3}); + await flush(); + expect(snapshot().speed, isNull); + expect(snapshot().mowerRpm, isNull); + }, + ); +} diff --git a/test/remote_control_diagnostics_test.dart b/test/remote_control_diagnostics_test.dart new file mode 100644 index 00000000..98d08daf --- /dev/null +++ b/test/remote_control_diagnostics_test.dart @@ -0,0 +1,135 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart'; +import 'package:maibu_satabot_v2/core/protocol/machine_protocol_codec.dart'; +import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/diff_steer_usecase.dart'; + +List> records(List batches) => batches + .join() + .split('\n') + .where((line) => line.isNotEmpty) + .map((line) => jsonDecode(line) as Map) + .toList(); + +void main() { + test( + 'frame correlation survives asynchronous completion and a new session', + () async { + final batches = []; + final trace = RemoteControlDiagnostics( + append: (s) async => batches.add(s), + ); + trace.begin('SN-1', {'intervalMs': 250}); + final completion = Completer(); + late Future observed; + final result = trace.frame('loop', {'tick': 2}, () { + trace.event('conversion', {'linearMps': 1.0}); + observed = completion.future.then( + (_) => trace.event('socket_flush_complete', {}), + ); + return true; + }); + trace.begin('SN-2', {'intervalMs': 250}); + completion.complete(); + await observed; + await trace.flush(); + final lines = records(batches); + final conversion = lines.singleWhere((r) => r['stage'] == 'conversion'); + final flushed = lines.singleWhere( + (r) => r['stage'] == 'socket_flush_complete', + ); + expect(result, isTrue); + expect(flushed['frame'], conversion['frame']); + expect(flushed['session'], conversion['session']); + expect(flushed['device'], 'SN-1'); + expect(flushed['source'], 'loop'); + }, + ); + + test('file writes are serialized and preserve event order', () async { + final batches = []; + final held = Completer(); + var active = 0; + var maxActive = 0; + final trace = RemoteControlDiagnostics( + append: (s) async { + active++; + if (active > maxActive) maxActive = active; + await held.future; + batches.add(s); + active--; + }, + ); + trace.event('first', {}); + final writing = trace.flush(); + trace.event('second', {}); + final again = trace.flush(); + held.complete(); + await Future.wait([writing, again]); + await trace.flush(); + expect(maxActive, 1); + expect(records(batches).map((r) => r['stage']), ['first', 'second']); + }); + + test( + 'disk failures do not interrupt control and missing records are marked', + () async { + final batches = []; + var fail = true; + final trace = RemoteControlDiagnostics( + append: (s) async { + if (fail) throw StateError('test disk failure'); + batches.add(s); + }, + ); + final result = trace.frame('stop', {}, () { + trace.event('socket_write_attempt', {}); + return false; + }); + await trace.flush(); + fail = false; + trace.event('next', {}); + await trace.flush(); + expect(result, isFalse); + expect(records(batches).first, { + 'stage': 'diagnostic_overflow', + 'dropped': 1, + }); + }, + ); + + test('buffer is bounded and discarded records are explicit', () async { + final batches = []; + final trace = RemoteControlDiagnostics(append: (s) async => batches.add(s)); + for (var i = 0; i < 2010; i++) { + trace.event('tick', {'tick': i}); + } + await trace.flush(); + final lines = records(batches); + expect(lines.length, 2001); + expect(lines.first['dropped'], 10); + expect(lines[1]['tick'], 10); + expect(lines.last['tick'], 2009); + }); + + test( + 'current velocity conversion and float64 little-endian payload stay intact', + () { + final algorithm = DiffSteerUseCase(); + for (final y in [-100, -50, 0, 50, 100]) { + final speeds = algorithm.calculate(0, y); + final payload = MachineProtocolCodec.encodeRemoteControlPayload( + linear: speeds['linear']!, + angular: speeds['angular']!, + ); + final decoded = ByteData.sublistView(payload); + expect(payload.length, 20); + expect(decoded.getFloat64(0, Endian.little), y / 100); + expect(decoded.getFloat64(8, Endian.little), 0); + } + }, + ); +} diff --git a/test/remote_control_permission_test.dart b/test/remote_control_permission_test.dart new file mode 100644 index 00000000..ee4e1cc7 --- /dev/null +++ b/test/remote_control_permission_test.dart @@ -0,0 +1,824 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; +import 'package:maibu_satabot_v2/features/remote_control/domain/entities/machine_control_status_entity.dart'; +import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/emergency_stop_button.dart'; +import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/emergency_overlay.dart'; +import 'package:get_it/get_it.dart'; +import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart'; +import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart'; +import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart'; +import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart'; +import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart'; +import 'package:fpdart/fpdart.dart'; +import 'package:maibu_satabot_v2/core/error/failure.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_target.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_failure.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart'; +import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; +import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; +import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart'; +import 'package:maibu_satabot_v2/features/remote_control/domain/entities/control_permission_failure.dart'; +import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart'; +import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_control_permission_usecase.dart'; +import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; +import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart'; + +class _Logger implements ILoggerService { + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +class _LoadedLocalizations extends LocalizationsDelegate { + const _LoadedLocalizations(this.value); + final AppLocalizations value; + @override + bool isSupported(Locale locale) => true; + @override + Future load(Locale locale) => SynchronousFuture(value); + @override + bool shouldReload(_LoadedLocalizations old) => false; +} + +class _Devices implements DeviceRepository { + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +class _Status implements DeviceStatusBloc { + static ({String sn, bool? active, DateTime receivedAt})? reading; + @override + ({String sn, bool? active, DateTime receivedAt})? get emergencyStopReading => + reading; + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +class _Tcp implements TcpClient { + final packets = StreamController.broadcast(sync: true); + bool connected = true; + @override + bool get isConnected => connected; + @override + Stream get packetStream => packets.stream; + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +class _Dispatcher implements NetMessageDispatcher { + _Dispatcher(this.tcp); + final _Tcp tcp; + @override + Stream onCommand(int command) => + tcp.packetStream.where((p) => p.command == command); + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +class _Repository implements RemoteControlRepository { + int motionSends = 0; + final sentFrames = []; + @override + Future sendControlMachineCmd( + MachineControlStatusEntity status, { + bool priority = false, + bool Function()? isCurrent, + }) async { + if (isCurrent != null && !isCurrent()) return false; + motionSends++; + sentFrames.add(status); + return true; + } + + int queries = 0; + int sends = 0; + Map info = {'hasPermission': false, 'owner': 'web'}; + Completer>? query; + Completer? write; + ControlPermissionFailure? queryError; + ControlPermissionFailure? sendError; + @override + Future> requestControlPermission( + String deviceName, + String deviceId, + ) async { + queries++; + if (queryError != null) throw queryError!; + return query?.future ?? info; + } + + @override + Future sendTcpPermissionRequest( + String deviceName, { + bool Function()? isCurrent, + }) async { + if (isCurrent != null && !isCurrent()) return; + sends++; + if (sendError != null) throw sendError!; + await write?.future; + } + + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +class _Cubit extends RemoteControlCubit { + _Cubit(_Repository repo, _Tcp tcp, _Emergency emergency) + : super( + repo, + RequestControlPermissionUseCase(repo), + _Devices(), + tcp, + _Dispatcher(tcp), + _Status(), + requestEmergencyStop: RequestDeviceEmergencyStopUseCase(emergency), + emergencyNow: () => TestWidgetsFlutterBinding.instance.clock.now(), + ); + int stops = 0; + @override + Future stopAllMovement({String reason = 'unspecified'}) async { + stops++; + } +} + +class _Emergency implements DeviceEmergencyStopRepository { + bool autoReport = true; + void Function()? onReport; + final calls = <(String, EmergencyStopTarget)>[]; + Either result = const Right(unit); + Completer>? pending; + @override + Future> request( + String deviceId, + EmergencyStopTarget target, + ) async { + calls.add((deviceId, target)); + final response = await (pending?.future ?? Future.value(result)); + if (autoReport && response.isRight()) { + _Status.reading = ( + sn: deviceId, + active: target == EmergencyStopTarget.engage, + receivedAt: TestWidgetsFlutterBinding.instance.clock.now(), + ); + onReport?.call(); + } + return response; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late _Emergency emergency; + void scenario( + String name, + Future Function(WidgetTester, _Cubit, _Repository, _Tcp) body, + ) { + testWidgets(name, (tester) async { + GetIt.I.registerSingleton(_Logger()); + RemoteControlDiagnostics.instance = RemoteControlDiagnostics( + append: (_) async {}, + ); + final repo = _Repository(); + final tcp = _Tcp(); + emergency = _Emergency(); + _Status.reading = ( + sn: 'SN-1', + active: false, + receivedAt: tester.binding.clock.now(), + ); + final cubit = _Cubit(repo, tcp, emergency); + emergency.onReport = cubit.refreshEmergencyStatus; + cubit.emit( + cubit.state.copyWith( + targetDevice: DeviceEntity( + deviceName: 'SN-1', + productId: 1, + productName: '', + tenantId: 1, + tenantName: '', + ), + ), + ); + try { + cubit.refreshEmergencyStatus(); + await body(tester, cubit, repo, tcp); + } finally { + await cubit.close(); + await RemoteControlDiagnostics.instance.flush(); + await tcp.packets.close(); + await tester.pump(const Duration(seconds: 20)); + await tester.pumpWidget(const SizedBox.shrink()); + await GetIt.I.reset(); + } + }); + } + + Future request(_Cubit c) => + c.requestControlPermissionS('SN-1', 'app', grabControl: true); + void respond( + _Tcp tcp, + dynamic result, { + String device = 'SN-1', + String? reason, + bool crc = true, + }) { + tcp.packets.add( + RawPacket( + command: 0x12, + payload: Uint8List.fromList([ + ...utf8.encode( + jsonEncode({ + 'respond': { + 'deviceId': device, + 'switchResult': result, + 'holder': 'you', + if (reason != null) 'reason': reason, + }, + }), + ), + if (crc) ...[0, 0], + ]), + ), + ); + } + + scenario('entry only queries and never sends', (t, c, r, tcp) async { + await c.requestControlPermissionS('SN-1', 'app'); + expect(r.queries, 1); + expect(r.sends, 0); + expect(emergency.calls, isEmpty); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.idle); + }); + scenario('manual request sends once and blocks repeat taps', ( + t, + c, + r, + tcp, + ) async { + await request(c); + await request(c); + expect(r.queries, 1); + expect(r.sends, 1); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting); + expect(c.state.permissionFeedbackKey, 'permission_sent'); + expect(c.state.hasPermission, isFalse); + }); + scenario('send notice waits for actual write completion', ( + t, + c, + r, + tcp, + ) async { + r.write = Completer(); + final pending = request(c); + await t.pump(); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.sending); + expect(c.state.permissionFeedbackKey, isNot('permission_sent')); + r.write!.complete(); + await pending; + expect(c.state.permissionFeedbackKey, 'permission_sent'); + }); + scenario( + 'manual request with HTTP permission and no owner still sends once', + (t, c, r, tcp) async { + r.info = {'hasPermission': true, 'owner': null}; + await request(c); + expect(r.sends, 1); + expect(c.state.hasPermission, isFalse); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting); + respond(tcp, true); + expect(c.state.hasPermission, isTrue); + }, + ); + scenario('query errors preserve their classification and never send', ( + t, + c, + r, + tcp, + ) async { + r.queryError = ControlPermissionFailure('permission_query_invalid'); + await request(c); + expect(r.sends, 0); + expect(c.state.permissionFeedbackKey, 'permission_query_invalid'); + expect(c.state.isPermissionRequestBusy, isFalse); + }); + scenario('disconnected socket reports not sent', (t, c, r, tcp) async { + tcp.connected = false; + await request(c); + expect(r.sends, 0); + expect(c.state.permissionFeedbackKey, 'permission_tcp_disconnected'); + }); + scenario('write failure reaches the UI', (t, c, r, tcp) async { + r.sendError = ControlPermissionFailure('permission_send_uncertain'); + await request(c); + expect(c.state.permissionFeedbackKey, 'permission_send_uncertain'); + expect(c.state.isPermissionRequestBusy, isFalse); + }); + scenario('matching success updates control and cancels timeout', ( + t, + c, + r, + tcp, + ) async { + await request(c); + respond(tcp, true); + await t.pump(); + expect(c.state.hasPermission, isTrue); + expect(c.state.permissionFeedbackKey, 'permission_granted'); + await t.pump(const Duration(seconds: 11)); + expect(c.state.permissionFeedbackKey, 'permission_granted'); + }); + scenario('fast response cannot be overwritten by a late write completion', ( + t, + c, + r, + tcp, + ) async { + r.write = Completer(); + final pending = request(c); + await t.pump(); + respond(tcp, true); + r.write!.complete(); + await pending; + expect(c.state.hasPermission, isTrue); + expect(c.state.permissionFeedbackKey, 'permission_granted'); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.granted); + }); + scenario('wrong-device and invalid results cannot grant control', ( + t, + c, + r, + tcp, + ) async { + await request(c); + respond(tcp, true, device: 'SN-2'); + respond(tcp, null); + await t.pump(); + expect(c.state.hasPermission, isFalse); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting); + }); + scenario('explicit denial differs from a generic unsuccessful result', ( + t, + c, + r, + tcp, + ) async { + await request(c); + respond(tcp, false); + await t.pump(); + expect(c.state.permissionFeedbackKey, 'permission_not_granted'); + expect(c.stops, 1); + await request(c); + respond(tcp, false, reason: 'holder_denied'); + await t.pump(); + expect(c.state.permissionFeedbackKey, 'permission_denied'); + }); + scenario('result without CRC is accepted', (t, c, r, tcp) async { + await request(c); + respond(tcp, true, crc: false); + await t.pump(); + expect(c.state.hasPermission, isTrue); + }); + scenario('no response times out and permits retry', (t, c, r, tcp) async { + await request(c); + await t.pump(const Duration(seconds: 11)); + expect(c.state.permissionFeedbackKey, 'permission_result_timeout'); + expect(c.state.hasPermission, isFalse); + expect(c.state.isPermissionRequestBusy, isFalse); + await request(c); + expect(r.sends, 2); + }); + scenario('disconnect while waiting is reported as unconfirmed', ( + t, + c, + r, + tcp, + ) async { + await request(c); + tcp.connected = false; + await t.pump(const Duration(milliseconds: 250)); + expect(c.state.permissionFeedbackKey, 'permission_connection_lost'); + }); + scenario('exit invalidates an outstanding query and late TCP result', ( + t, + c, + r, + tcp, + ) async { + r.query = Completer>(); + final pending = request(c); + await t.pump(); + c.resetPermissionState(); + r.query!.complete({'hasPermission': true, 'owner': 'app'}); + await pending; + respond(tcp, true); + await t.pump(); + expect(c.state.hasPermission, isFalse); + expect(c.state.permissionRequestPhase, PermissionRequestPhase.idle); + expect(r.sends, 0); + }); + scenario('query timeout cannot send a late request', (t, c, r, tcp) async { + r.query = Completer>(); + final pending = request(c); + await t.pump(const Duration(seconds: 11)); + await pending; + expect(c.state.permissionFeedbackKey, 'permission_query_timeout'); + r.query!.complete({'hasPermission': false, 'owner': 'web'}); + await t.pump(); + expect(r.sends, 0); + }); + + scenario('e-stop uses current SN without TCP or control permission', ( + t, + c, + r, + tcp, + ) async { + tcp.connected = false; + c.updateFunction(mower: 1, lift: 1); + expect(await c.updateEmergency(true), isTrue); + expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]); + expect(r.motionSends, 0); + expect(c.state.isEmergency, isTrue); + expect(c.state.isLocked, isTrue); + expect(c.state.controlEntity.isEmergency, isFalse); + expect(c.state.controlEntity.mowerSpeed, 0); + expect(c.state.controlEntity.chassisLift, 0); + expect(c.state.emergencyFeedbackKey, 'emergency_request_sent'); + }); + + scenario('release sends zero and clears local state only after API success', ( + t, + c, + r, + tcp, + ) async { + await c.updateEmergency(true); + emergency.pending = Completer>(); + final release = c.updateEmergency(false); + expect(c.state.isEmergency, isTrue); + expect(c.state.isLocked, isTrue); + expect(c.state.isEmergencyRequestPending, isTrue); + // A late joystick callback must not revive old movement after release. + c.updateFunction(mower: 0); + emergency.pending!.complete(const Right(unit)); + expect(await release, isTrue); + expect(emergency.calls.last, ('SN-1', EmergencyStopTarget.release)); + expect(c.state.isEmergency, isFalse); + expect(c.state.isLocked, isFalse); + expect(c.state.controlEntity.originX, 0); + expect(c.state.controlEntity.originY, 0); + expect(c.state.emergencyFeedbackKey, 'emergency_release_sent'); + expect(r.motionSends, 0); + }); + + scenario('repeat taps and release while sending cannot duplicate requests', ( + t, + c, + r, + tcp, + ) async { + emergency.pending = Completer>(); + final first = c.updateEmergency(true); + expect(await c.updateEmergency(true), isFalse); + expect(await c.updateEmergency(false), isFalse); + expect(emergency.calls, hasLength(1)); + emergency.pending!.complete(const Right(unit)); + await first; + }); + + scenario('failed stop keeps local inhibit and permits retry', ( + t, + c, + r, + tcp, + ) async { + emergency.result = Left(NetworkFailure('timeout')); + expect(await c.updateEmergency(true), isFalse); + expect(c.state.isEmergency, isFalse); + expect(c.state.isLocked, isTrue); + expect(c.state.emergencyRequestFailed, isTrue); + emergency.result = const Right(unit); + expect(await c.updateEmergency(true), isTrue); + expect(emergency.calls, hasLength(2)); + }); + + scenario('business failure during stop keeps normal UI and permits retry', ( + t, + c, + r, + tcp, + ) async { + c.emit(c.state.copyWith(hasPermission: true)); + c.startControlLoop(); + emergency.pending = Completer>(); + final sending = c.updateEmergency(true); + expect(c.state.isEmergencyRequestPending, isTrue); + expect(c.state.isEmergency, isFalse); + c.toggleLock(); + await t.pump(const Duration(milliseconds: 200)); + expect(r.motionSends, 0); + emergency.pending!.complete(Left(EmergencyStopRejectedFailure('设备模式切换失败'))); + expect(await sending, isFalse); + expect(c.state.isEmergency, isFalse); + expect(c.state.isLocked, isFalse); + expect(c.state.isEmergencyRequestPending, isFalse); + expect(c.state.emergencyFeedbackKey, 'emergency_request_rejected'); + emergency.pending = null; + expect(await c.updateEmergency(true), isTrue); + expect(c.state.isEmergency, isTrue); + }); + + scenario('business failure during release keeps previous e-stop state', ( + t, + c, + r, + tcp, + ) async { + await c.updateEmergency(true); + emergency.result = Left(EmergencyStopRejectedFailure('设备模式切换失败')); + expect(await c.updateEmergency(false), isFalse); + expect(c.state.isEmergency, isTrue); + expect(c.state.isLocked, isTrue); + expect(c.state.isEmergencyRequestPending, isFalse); + expect(c.state.emergencyRequestFailed, isTrue); + }); + + scenario('missing SN does not send an e-stop request', (t, c, r, tcp) async { + c.clearTargetDevice(); + expect(await c.updateEmergency(true), isFalse); + expect(emergency.calls, isEmpty); + expect(c.state.emergencyFeedbackKey, 'emergency_missing_sn'); + }); + + scenario('exiting session does not request release or clear local e-stop', ( + t, + c, + r, + tcp, + ) async { + await c.updateEmergency(true); + c.resetPermissionState(); + expect(emergency.calls, hasLength(1)); + expect(c.state.isEmergency, isTrue); + expect(c.state.isLocked, isTrue); + }); + + scenario('late e-stop reply cannot apply after target was cleared', ( + t, + c, + r, + tcp, + ) async { + emergency.pending = Completer>(); + final pending = c.updateEmergency(true); + c.clearTargetDevice(); + emergency.pending!.complete(const Right(unit)); + expect(await pending, isFalse); + expect(c.state.targetDevice, isNull); + expect(c.state.isEmergency, isFalse); + expect(c.state.isEmergencyRequestPending, isFalse); + }); + + scenario('motion loop waits 250ms and sends the latest input', ( + t, + c, + r, + tcp, + ) async { + c.emit(c.state.copyWith(hasPermission: true)); + c.startControlLoop(); + c.updateOriginY(25); + await t.pump(const Duration(milliseconds: 200)); + expect(r.sentFrames, isEmpty); + c.updateOriginY(75); + await t.pump(const Duration(milliseconds: 49)); + expect(r.sentFrames, isEmpty); + await t.pump(const Duration(milliseconds: 1)); + expect(r.sentFrames.map((frame) => frame.originY), [75]); + c.updateOriginY(50); + await t.pump(const Duration(milliseconds: 250)); + expect(r.sentFrames.map((frame) => frame.originY), [75, 50]); + }); + + scenario('mower hold repeats every 250ms and release keeps last operation', ( + t, + c, + r, + tcp, + ) async { + expect(c.state.controlEntity.mowerSpeed, 2); + c.emit(c.state.copyWith(hasPermission: true)); + c.startControlLoop(); + c.sendMowerSliderCommand(1); + await t.pump(const Duration(milliseconds: 750)); + expect(r.sentFrames.map((frame) => frame.mowerSpeed), [1, 1, 1]); + expect(c.state.lastMowerOperation, MowerLastOperation.turnOn); + c.sendMowerSliderCommand(0); + await t.pump(const Duration(milliseconds: 250)); + expect(r.sentFrames.last.mowerSpeed, 2); + expect(c.state.lastMowerOperation, MowerLastOperation.turnOn); + c.sendMowerSliderCommand(2); + await t.pump(const Duration(milliseconds: 250)); + expect(r.sentFrames.last.mowerSpeed, 0); + expect(c.state.lastMowerOperation, MowerLastOperation.turnOff); + c.sendMowerSliderCommand(0); + await t.pump(const Duration(milliseconds: 250)); + expect(r.sentFrames.last.mowerSpeed, 2); + expect(c.state.lastMowerOperation, MowerLastOperation.turnOff); + expect(c.state.controlEntity.chassisLift, 0); + expect(c.state.controlEntity.ignitionStatus, 0); + }); + + scenario('mower session reset clears last operation and pending command', ( + t, + c, + r, + tcp, + ) async { + c.sendMowerSliderCommand(1); + c.resetPermissionState(); + expect(c.state.lastMowerOperation, MowerLastOperation.none); + expect(c.state.controlEntity.mowerSpeed, 2); + c.sendMowerSliderCommand(2); + c.resetMowerControl(); + expect(c.state.lastMowerOperation, MowerLastOperation.none); + expect(c.state.controlEntity.mowerSpeed, 2); + c.sendMowerSliderCommand(1); + c.clearTargetDevice(); + expect(c.state.targetDevice, isNull); + expect(c.state.lastMowerOperation, MowerLastOperation.none); + expect(c.state.controlEntity.mowerSpeed, 2); + }); + + scenario('telemetry controls UI and API success cannot change it', ( + t, + c, + r, + tcp, + ) async { + emergency.autoReport = false; + expect(c.state.hasEmergencyStatus, isTrue); + expect(c.state.isEmergency, isFalse); + expect(await c.updateEmergency(true), isTrue); + expect(c.state.isEmergency, isFalse); + _Status.reading = ( + sn: 'SN-1', + active: true, + receivedAt: t.binding.clock.now(), + ); + c.refreshEmergencyStatus(); + expect(c.state.isEmergency, isTrue); + expect(await c.updateEmergency(true), isFalse); + expect(emergency.calls, hasLength(1)); + expect(await c.updateEmergency(false), isTrue); + expect(c.state.isEmergency, isTrue); + _Status.reading = ( + sn: 'SN-1', + active: false, + receivedAt: t.binding.clock.now(), + ); + c.refreshEmergencyStatus(); + expect(c.state.isEmergency, isFalse); + }); + + scenario('telemetry missing stale or from another SN blocks commands', ( + t, + c, + r, + tcp, + ) async { + for (final reading in <({String sn, bool? active, DateTime receivedAt})?>[ + null, + (sn: 'SN-1', active: null, receivedAt: t.binding.clock.now()), + (sn: 'SN-2', active: false, receivedAt: t.binding.clock.now()), + ( + sn: 'SN-1', + active: false, + receivedAt: t.binding.clock.now().subtract(const Duration(seconds: 11)), + ), + ]) { + _Status.reading = reading; + c.refreshEmergencyStatus(); + expect(c.state.hasEmergencyStatus, isFalse); + expect(await c.updateEmergency(true), isFalse); + expect(await c.updateEmergency(false), isFalse); + } + expect(emergency.calls, isEmpty); + }); + + Future mountButton(WidgetTester t, _Cubit c) async { + final translations = AppLocalizations(AppLocalizations.english); + await t.runAsync(translations.load); + await t.pumpWidget( + MaterialApp( + localizationsDelegates: [_LoadedLocalizations(translations)], + supportedLocales: AppLocalizations.supportedLocales, + locale: AppLocalizations.english, + home: BlocProvider.value( + value: c, + child: Scaffold( + body: BlocBuilder( + builder: (context, state) => Stack( + children: [ + if (state.isEmergency) + const Positioned.fill(child: EmergencyOverlay()), + const Center(child: EmergencyStopButton(width: 180)), + ], + ), + ), + ), + ), + ), + ); + await t.pumpAndSettle(); + } + + Future confirmDialog(WidgetTester t) async { + await t.pump(const Duration(milliseconds: 400)); + await t.tap(find.byKey(const ValueKey('emergency-confirm'))); + await t.pump(); + await t.pump(const Duration(milliseconds: 400)); + } + + scenario('button confirmation sends stop and release and removes breathing', ( + t, + c, + r, + tcp, + ) async { + await mountButton(t, c); + await t.tap(find.byType(EmergencyStopButton)); + await t.pump(); + expect(emergency.calls, isEmpty); + expect(find.byType(AlertDialog), findsOneWidget); + await confirmDialog(t); + await t.pump(); + expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]); + expect(find.byType(EmergencyOverlay), findsOneWidget); + await t.tap(find.byType(EmergencyStopButton)); + await t.pump(); + expect(emergency.calls, hasLength(1)); + expect(find.byType(AlertDialog), findsOneWidget); + await confirmDialog(t); + expect(emergency.calls.last, ('SN-1', EmergencyStopTarget.release)); + expect(emergency.calls, hasLength(2)); + expect(find.byType(EmergencyOverlay), findsNothing); + expect(r.motionSends, 0); + }); + + scenario( + 'cancel stop confirmation sends nothing and does not start breathing', + (t, c, r, tcp) async { + await mountButton(t, c); + await t.tap(find.byType(EmergencyStopButton)); + await t.pump(const Duration(milliseconds: 400)); + expect(emergency.calls, isEmpty); + await t.tap(find.byKey(const ValueKey('emergency-cancel'))); + await t.pump(const Duration(milliseconds: 400)); + expect(emergency.calls, isEmpty); + expect(c.state.isEmergency, isFalse); + expect(find.byType(EmergencyOverlay), findsNothing); + }, + ); + + scenario('cancel release confirmation keeps e-stop without sending zero', ( + t, + c, + r, + tcp, + ) async { + await mountButton(t, c); + await t.tap(find.byType(EmergencyStopButton)); + await t.pump(); + await confirmDialog(t); + await t.tap(find.byType(EmergencyStopButton)); + await t.pump(const Duration(milliseconds: 400)); + await t.tap(find.byKey(const ValueKey('emergency-cancel'))); + await t.pump(const Duration(milliseconds: 400)); + expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]); + expect(c.state.isEmergency, isTrue); + expect(find.byType(EmergencyOverlay), findsOneWidget); + }); + + scenario('changing target while confirming never sends to another vehicle', ( + t, + c, + r, + tcp, + ) async { + await mountButton(t, c); + await t.tap(find.byType(EmergencyStopButton)); + await t.pump(); + c.clearTargetDevice(); + await confirmDialog(t); + expect(emergency.calls, isEmpty); + }); +}