Files
flutterApp/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart

2090 lines
82 KiB
Dart
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:dart_ping/dart_ping.dart';
import 'package:flutter/cupertino.dart';
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';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_event.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart';
import 'package:maibu_satabot_v2/features/remote_control/data/models/running_status_model.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_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]):250ms 控制循环是 Dart VM 层的
/// Timer,退后台 / 锁屏后照旧跟发,而 main.dart 的全局回调只管会话标记与 TCP
/// 重连、不碰循环,所以“切后台那一刻手指还压在摇杆上”就会留下非零轴值;
/// 回前台 TCP 重连后车能自己走。本类自己接管:退后台挂起循环 + 归零,
/// 回前台且仍在控制态则重启(与 LocalCameraCubit 的自管生命周期同一取向)。
class RemoteControlCubit extends Cubit<RemoteControlState>
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<void> serverHeartbeats = tcpClient.packetStream
.where((packet) => packet.command == 0xFF)
.map<void>((_) {});
Timer? _timer;
Timer? _permissionWaitTimer;
int _permissionAttempt = 0;
int _permissionRequestId = 0;
Map<String, Object?> _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
StreamSubscription? _deviceStatusSub; // 🔥 订阅 DeviceStatusBloc 的状态流(MQTT,已停用)
StreamSubscription? _tcpStatusSub; // 🔥 订阅 TCP 0x02 机器状态推送(门槛 + 电压/电量/控制模式)
static const platform = MethodChannel('com.maibu.satabot/ping');
int _currentPing = 50;
final ILoggerService _logger = GetIt.I<ILoggerService>();
// 🔥 参考Android版:使用成员变量存储摇杆值,避免state竞态
int _currentOriginX = 0;
int _currentOriginY = 0;
int _motionGeneration = 0;
int _diagnosticLoop = 0;
int _diagnosticStop = 0;
int _diagnosticActiveStops = 0;
int? _diagnosticInputUs;
Future<bool> _sendMotionFrame(
MachineControlStatusEntity frame,
String source, [
Map<String, Object?> 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] 置假。
/// 它代表“意图”,与定时器的实时存在与否解耦:被后台挂起时仍为真,
/// 回前台靠它判断要不要自动重启循环;stopAllMovement 末尾也靠它判断该不该重调。
bool _controlWanted = false;
/// 因退到后台(inactive/paused/hidden)而临时挂起控制循环。
/// 挂起期间所有 startControlLoop 调用只记意图、不起定时器,回前台再恢复。
bool _suspendedByLifecycle = false;
// 🔥 权限请求处理标志位 - 防止竞态条件,避免重复显示弹窗
bool _isProcessingPermissionRequest = false;
// 🔥 模拟数据推送定时器
// Timer? _simulationTimer;
// 🔥 倒车影像数据源(现为 Mock;嵌入式就绪后,把 startReverseCameraMock 里的
// MockReverseCameraSource 换成解析真实回包的 Mqtt/Tcp 源即可,UI 不用动)。
ReverseCameraSource? _reverseCameraSource;
StreamSubscription<ReverseCameraData>? _reverseCameraSub;
// 🔥 获取带时间戳的日志前缀
String _getTimePrefix() {
final now = DateTime.now();
return '[${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}.${now.millisecond.toString().padLeft(3, '0')}]';
}
RemoteControlCubit(
this._repository,
this._requestControlPermissionUseCase,
this._deviceRepository, // 🔥 注入
this.tcpClient, // 🔥 注入TCP客户端
this.dispatcher,
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() 里成对移除):单例常驻,
// 不挂在某个页面上,所以从别的路径进控态也能被护住。
WidgetsBinding.instance.addObserver(this);
}
// 🔥 新增:订阅 DeviceStatusBloc 的状态流,而不是直接监听TCP
// 类全局变量
DateTime? _lastUiUpdateTime;
String? _cacheVoltage;
String? _cacheBattery;
String? _cacheCtrlMode;
int? _cachePing;
DateTime? _lastStatusPushTime; // 最后一次收到设备状态推送的时间
// 🔥 已停用:门槛与电压/电量/控制模式改由 TCP 0x02 驱动(见 _initTcpStatusListener)。
// 保留本方法用于回滚——恢复构造函数中的调用即可重新走 MQTT(DeviceStatusUpdated)。
// ignore: unused_element
void _initDeviceStatusListener() {
_deviceStatusSub?.cancel();
_deviceStatusSub = deviceStatusBloc.stream.listen((deviceState) async {
if (deviceState is DeviceStatusUpdated) {
// 第一步:所有数据先存入缓存,不管来多频繁都存最新值
final voltage = deviceState.status.voltage;
final battery = deviceState.status.battery;
// 只存协议原始值('3'=远程/'0'=本地等),展示文案由 UI 按当前语言翻译
final controlMode = deviceState.status.controlMode;
final c = await getNetworkDelay();
_cacheVoltage = voltage.toString();
_cacheBattery = battery.toString();
_cacheCtrlMode = controlMode;
_cachePing = c;
_lastStatusPushTime = DateTime.now(); // 记录最后一次推送时间
// 500ms节流,不到时间不刷新UI
final now = DateTime.now();
if (_lastUiUpdateTime != null &&
now.difference(_lastUiUpdateTime!) <
const Duration(milliseconds: 500)) {
return;
}
_lastUiUpdateTime = now;
// 间隔达标,统一一次刷新UI
emit(
state.copyWith(
runningStatusModel: state.runningStatusModel.copyWith(
voltage: _cacheVoltage,
battery: _cacheBattery,
controlMode: _cacheCtrlMode,
),
battery: int.tryParse(_cacheBattery ?? '') ?? 0,
ping: _cachePing,
hasReceivedStatusPush: true, // 标记已收到设备状态推送
// 🔥 标记为设备状态更新
updateType: 'device_status',
),
);
}
});
}
/// 🔥 门槛 + 运行状态专用监听:直接监听 TCP 0x02 机器状态推送。
///
/// 与 MQTT 定位链路彻底解耦:
/// - 门槛 hasReceivedStatusPush / _lastStatusPushTime 由 TCP 0x02 驱动;
/// - 电压/电量/控制模式 直接由 0x02 报文的 fromFields 解析(fields[0]/[21]/[20]);
/// - MQTT(DeviceStatusBloc) 仅继续负责定位,不再影响本页门槛与三个值。
void _initTcpStatusListener() {
_tcpStatusSub?.cancel();
_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;
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;
// 🔥 门槛:收到 TCP 0x02 即视为推送活跃(节流前刷新,轻量无阻塞)
_lastStatusPushTime = DateTime.now();
_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));
}
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 值
// 🔥 模拟设备状态更新 - 用于测试
// void simulateDeviceStatusUpdate({
// String? voltage,
// String? battery,
// String? controlMode,
// int? ping,
// // 🔥 是否随机生成数据
// bool random = false,
// }) {
// // 如果开启随机模式,生成随机数据
// final rand = Random();
/* if (random) {
voltage = (22.0 + rand.nextDouble() * 4.0).toStringAsFixed(
1,
); // 22.0-26.0V
battery = (rand.nextInt(100) + 1).toString(); // 1-100%
controlMode = rand.nextBool() ? '远程模式' : '本地模式';
ping = rand.nextInt(150) + 20; // 20-170ms
} */
/* debugPrint(
'🔧 [模拟设备状态更新] voltage=$voltage V, battery=$battery%, controlMode=$controlMode, ping=$ping ms',
); */
// 更新缓存
/* if (voltage != null) _cacheVoltage = voltage;
if (battery != null) _cacheBattery = battery;
if (controlMode != null) _cacheCtrlMode = controlMode;
if (ping != null) _cachePing = ping;
// 直接触发状态更新(跳过节流,立即更新)
emit(
state.copyWith(
runningStatusModel: state.runningStatusModel.copyWith(
voltage: _cacheVoltage,
battery: _cacheBattery,
controlMode: _cacheCtrlMode,
),
battery: int.tryParse(_cacheBattery ?? '') ?? 0,
ping: _cachePing,
// 🔥 标记为设备状态更新
updateType: 'device_status',
),
);
} */
// 🔥 开始模拟设备状态推送(随机数据)
/* void startSimulation({int intervalMs = 500}) {
// 如果已经在运行,先停止
stopSimulation();
// debugPrint('🔔 [模拟推送] 开始模拟设备状态推送,间隔:${intervalMs}ms');
// 立即发送一次初始数据
simulateDeviceStatusUpdate(random: true);
// 定时推送随机数据
_simulationTimer = Timer.periodic(Duration(milliseconds: intervalMs), (
timer,
) {
if (!isClosed) {
simulateDeviceStatusUpdate(random: true);
} else {
stopSimulation();
}
});
} */
// 🔥 停止模拟设备状态推送
/* void stopSimulation() {
if (_simulationTimer != null) {
_simulationTimer!.cancel();
_simulationTimer = null;
debugPrint('🔔 [模拟推送] 已停止模拟设备状态推送');
}
} */
// 🔥 辅助方法:更新运行状态
void _updateStatusFromDevice(RunningStatusModel newStatus) {
// // debugPrint('✅ [_updateStatusFromDevice] 收到运行状态更新:$newStatus');
if (!isClosed) {
emit(
state.copyWith(
runningStatusModel: newStatus,
voltage: int.tryParse(newStatus.voltage) ?? 0,
battery: int.tryParse(newStatus.battery) ?? 0,
),
);
// debugPrint('✅ [更新运行状态] 电压:${newStatus.voltage}V, 电量:${newStatus.battery}%');
// _logger.logWithLevel('✅ [更新运行状态] 电压:${newStatus.voltage}V, 电量:${newStatus.battery}%');
}
}
// 🔥 辅助方法:更新运行状态
// 1. 初始化回包监听 (如 0x12 权限)
// void _initPacketListener() {
// _repository.responseStream.listen((packet) {
// if (packet.command == 0x12) {
// // 根据负载判断是否有权限,更新状态
// emit(state.copyWith(hasPermission: true));
// }
// });
// }
Future<void> _initPacketListener() async {
final logPrefix = '${_getTimePrefix()} 🔍 [RemoteControl] [0x12监听器]';
debugPrint('$logPrefix =========================================');
debugPrint('$logPrefix 开始初始化 0x12 监听器');
_logger.logWithLevel('$logPrefix 开始初始化 0x12 监听器', shouldLog: true);
_kickOutSub?.cancel(); // 防止重复监听
_kickOutSub = dispatcher.onCommand(0x12).listen((packet) {
_tracePermission('0x12到达', {'payloadBytes': packet.payload.length});
final timeNow = _getTimePrefix();
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ✅ 收到 0x12 原始包');
/* debugPrint(
'$timeNow 🔍 [RemoteControl] [0x12监听器] payload长度: ${packet.payload.length}',
);*/
_logger.logWithLevel(
'$timeNow 🔍 [RemoteControl] [0x12监听器] 收到 0x12 原始包,payload长度=${packet.payload.length}',
shouldLog: true,
);
try {
// 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)),
);
} catch (_) {
jsonMap = jsonDecode(utf8.decode(packet.payload));
}
if (jsonMap is! Map) {
_tracePermission('忽略0x12', {'reason': 'JSON顶层不是对象'});
return;
}
final requestType = jsonMap['request'];
final platform = jsonMap['platform'];
final respondData = jsonMap['respond'];
_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 is Map) {
_handlePermissionResult(respondData);
}
// 情况 2: 请求格式 - {"request":"switch_control","deviceId":"...","platform":"web",...}
else if (requestType == 'switch_control') {
final requestDeviceId = jsonMap['deviceId'];
final webLogPrefix =
'${_getTimePrefix()} 🚨 [RemoteControl] [Web端权限请求]';
// 🔥 新增:记录收到请求的时间,便于排查是否为后端持续推送
debugPrint(
'$webLogPrefix ⚡️⚡️⚡️ 收到Web端权限请求 - ${DateTime.now().toString()}',
);
_logger.logWithLevel(
'$webLogPrefix ⚡️⚡️⚡️ 收到Web端权限请求 - ${DateTime.now().toString()}',
shouldLog: true,
);
debugPrint('$webLogPrefix =========================================');
debugPrint('$webLogPrefix 收到 switch_control 请求');
debugPrint('$webLogPrefix platform: $platform');
debugPrint('$webLogPrefix requestDeviceId: $requestDeviceId');
_logger.logWithLevel(
'$webLogPrefix 收到 switch_control 请求 - platform: $platform, deviceId: $requestDeviceId',
shouldLog: true,
);
// 🔥 关键判断:只有当是其他平台(web)请求时才弹窗
if (platform != null && platform.toString().toLowerCase() != 'app') {
// 🔥 验证设备ID是否与当前控制的 targetDevice 一致
final currentDeviceId = state.targetDevice?.deviceName;
debugPrint('$webLogPrefix 当前控制设备ID: $currentDeviceId');
if (currentDeviceId != null && requestDeviceId == currentDeviceId) {
debugPrint('$webLogPrefix 设备ID匹配');
// 🔥 只有当弹窗还没显示时才弹出,防止重复弹窗叠加
if (state.showPermissionRequestDialog) {
debugPrint('$webLogPrefix ⚠️ 弹窗已显示,忽略重复请求');
_logger.logWithLevel(
'$webLogPrefix ⚠️ 弹窗已显示,忽略重复请求',
shouldLog: true,
);
return;
}
debugPrint('$webLogPrefix 弹出权限请求对话框');
_logger.logWithLevel(
'$webLogPrefix 设备ID匹配,弹出权限请求对话框',
shouldLog: true,
);
if (!isClosed) {
emit(
state.copyWith(
showPermissionRequestDialog: true,
requestingDeviceId: requestDeviceId?.toString(),
requestingPlatform: platform.toString(),
// 🔥 标记为弹窗状态更新
updateType: 'permission_dialog',
),
);
}
} else {
debugPrint('$webLogPrefix ⚠️ 设备ID不匹配,忽略');
debugPrint(
'$webLogPrefix currentDeviceId: $currentDeviceId, requestDeviceId: $requestDeviceId',
);
_logger.logWithLevel(
'$webLogPrefix ⚠️ 设备ID不匹配,忽略请求',
shouldLog: true,
);
}
} else {
debugPrint('$webLogPrefix ℹ️ APP自己的请求回显或platform为空,忽略不弹窗');
_logger.logWithLevel(
'$webLogPrefix ℹ️ APP自己的请求回显,忽略',
shouldLog: true,
);
}
debugPrint('$webLogPrefix =========================================');
}
// 情况 3: 异地登录通知 - {"request":"have_logged_in",...}
else if (requestType == 'have_logged_in') {
// 🔥 关键修复:检查是否是自身 0x03 认证触发的
if (tcpClient.isOwnAuthTriggeredKick()) {
debugPrint(
'${_getTimePrefix()} 🛡️ [RemoteControl] 自身认证触发的 have_logged_in,忽略',
);
_logger.logWithLevel(
'${_getTimePrefix()} 🛡️ [RemoteControl] 自身认证触发的 have_logged_in,忽略',
shouldLog: true,
);
return;
}
debugPrint('${_getTimePrefix()} ⚠️ [RemoteControl] 检测到真正的异地登录');
_logger.logWithLevel(
'${_getTimePrefix()} ⚠️ [RemoteControl] 检测到异地登录,打开弹窗提示',
shouldLog: true,
);
// 🔥 只有当弹窗还没显示时才弹出
if (!isClosed && !state.showPermissionRequestDialog) {
emit(state.copyWith(showPermissionRequestDialog: true));
}
} else {
debugPrint('${_getTimePrefix()} ℹ️ [RemoteControl] 未知类型的 0x12 包,忽略');
_logger.logWithLevel(
'${_getTimePrefix()} ℹ️ [RemoteControl] 未知类型的 0x12 包,忽略',
shouldLog: true,
);
}
} catch (e) {
_tracePermission('0x12解析失败', {
'errorType': e.runtimeType.toString(),
'payloadBytes': packet.payload.length,
});
debugPrint('${_getTimePrefix()} ❌ [RemoteControl] 解析失败:$e');
_logger.logWithLevel(
'${_getTimePrefix()} ❌ [RemoteControl] 解析失败:$e',
shouldLog: true,
);
}
});
}
// 2. 开启 250ms 控制循环 (在进入遥控页面或点击“开始”时调用)
/* void startControlLoop() {
_timer?.cancel();
_timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
// 🔥 关键修复:每次循环都重新读取最新的 state
final currentEntity = state.controlEntity;
// 🔥 安全检查:无权限或急停时不发送
if (!state.hasPermission || state.isEmergency) {
// debugPrint('⚠️ [定时器] 跳过发送 - hasPermission=${state.hasPermission}, isEmergency=${state.isEmergency}');
return;
}
// debugPrint('⏰ [定时器] 发送控制指令 - originX=${currentEntity.originX}, originY=${currentEntity.originY}');
// _logger.logWithLevel('真实的发送的实体 - originX: ${currentEntity.originX}, originY: ${currentEntity.originY}');
_repository.sendControlMachineCmd(currentEntity);
});
emit(state.copyWith(status: RemoteControlStatus.controlling));
}*/
/// 🔥 双轴归零(静默):只清本地摇杆值并同步 UI,**不发停止帧**。
/// 需要连发停止帧压住 TCP 积压时用 [stopAllMovement];这里用于“只是不能让
/// 残留值下次复活”的场景(失权 / 急停 / 进控态)。
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;
_currentOriginY = 0;
emit(
state.copyWith(controlEntity: state.controlEntity.copyWith(x: 0, y: 0)),
);
_syncReverseCameraFromJoystick();
}
/// 回前台重启循环的延迟定时器(避开 TCP 重连窗口),close() 需成对取消。
Timer? _resumeTimer;
/// 🔥 退后台挂起控制循环:停定时器 + 归零 + 尽力补发一次全停。
///
/// 为什么不能只做“跳过发送”:系统不保证会给 [GestureDetector] 发 ACTION_CANCEL,
/// 下拉通知栏 / 进多任务预览(只到 inactive)时摇杆的三重松手兜底可能一个都没
/// 触发,非零轴值就这样留在单例上;回前台 reconnectAfterResume 把 socket 重建后,
/// 循环下一 tick 就会用这个没人碰的残留值发车。
void _suspendControlLoop() {
if (!_controlWanted || _suspendedByLifecycle) return;
// 先置挂起位:下方 stopAllMovement 末尾会调 startControlLoop,必须被拦住。
_suspendedByLifecycle = true;
_resumeTimer?.cancel();
_resumeTimer = null;
_timer?.cancel();
_timer = null;
debugPrint('🌙 [RemoteControl] [生命周期] 退后台:挂起控制循环 + 双轴归零');
_logger.logWithLevel(
'🌙 [RemoteControl] [生命周期] 退后台:挂起控制循环 + 双轴归零',
shouldLog: true,
);
// best-effort:socket 已被冻住时这些帧会被 sendRaw 如实判为失败(已有节流日志),
// 但本地轴值已归零,回前台重启循环也只会发零速帧。
unawaited(stopAllMovement(reason: 'background'));
unawaited(RemoteControlDiagnostics.instance.flush());
}
/// 🔥 回前台恢复控制循环:仅当业务侧仍处于控制态。
void _resumeControlLoop() {
if (!_suspendedByLifecycle) return;
_suspendedByLifecycle = false;
if (!_controlWanted) {
// 后台期间用户已退页 / 折叠(stopControlLoop 已把意图关掉),不复活。
debugPrint('☀️ [RemoteControl] [生命周期] 回前台:已不在控制态,不重启循环');
return;
}
debugPrint('☀️ [RemoteControl] [生命周期] 回前台:延迟重启控制循环');
// 错开重连窗口:main.dart 的 _handleResume 要先等 500ms 才
// reconnectAfterResume();立刻起循环只会把首批指令打在空 socket 上被丢弃。
_resumeTimer?.cancel();
_resumeTimer = Timer(const Duration(milliseconds: 800), () {
if (isClosed || !_controlWanted || _suspendedByLifecycle) return;
startControlLoop();
});
}
@override
// 形参不跟父类叫 state:在 Cubit 里它会遮蔽 cubit 自己的 state getter,
// 后来人误用会拿到 AppLifecycleState 而不是 RemoteControlState。
// ignore: avoid_renaming_method_parameters
void didChangeAppLifecycleState(AppLifecycleState lifecycle) {
switch (lifecycle) {
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
case AppLifecycleState.hidden:
_suspendControlLoop();
break;
case AppLifecycleState.resumed:
_resumeControlLoop();
break;
case AppLifecycleState.detached:
// 进程即将销毁,无需也不应在这里做异步 IO。
break;
}
}
/// [resetAxes] 是否在起循环前把双轴静默归零。默认 true(冷启动:路由 / 旧页
/// initState / HUD activate / 回前台恢复);[stopAllMovement] 末尾的热重启必须
/// 传 false,理由见那里。
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;
if (_suspendedByLifecycle) {
// 🔥 后台挂起期间任何人调进来都只记意图、不起定时器:否则
// stopAllMovement 末尾、或后台里走完的权限流程会把循环重新点着。
debugPrint('🌙 [RemoteControl] [控制循环] 已挂起,仅记录控制意图不起定时器');
return;
}
final logPrefix = '⏰ [RemoteControl] [控制循环]';
//debugPrint('$logPrefix =========================================');
//debugPrint('$logPrefix 启动控制循环,间隔: 250ms');
///debugPrint('$logPrefix =========================================');
// 🔥 安全兼容:进控制态一律从“零速”起步。
// originX/Y 存在本单例的成员变量上,上一次会话若是“按住摇杆直接退页 /
// 切视图”(没走松手归零路径),残留的非零值会让本次刚进页面就持续
// 下发运动指令 —— 车自己开走。冷启动入口(路由 create / 旧页 initState /
// HUD activate)都经这里,故在源头清一次。
if (resetAxes) {
_zeroAxesQuietly(reason: 'loop_start');
}
// 🔥 启动模拟设备状态推送(用于测试)
// startSimulation();
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();
return;
}
// 🔥 锁定态门控(与 hasPermission / isEmergency 同层):旧版只在摇杆区域套
// IgnorePointer(ignoring: isLocked),靠 UI 遮挡;但 isLocked 住在单例里,会
// 跨页面残留,而新版 HUD 没有锁定入口也不读这个位。锁上一律不发运动帧,
// 两版行为一致且不依赖 UI。(退页时 resetPermissionState 会把它清掉,
// 不会出现“带着锁定进 HUD 导致摇杆失灵”。)
if (state.isLocked) {
trace.event('loop_skip', {'loop': loop, 'reason': 'locked'});
// debugPrint('$logPrefix 🔒 锁定状态,跳过发送 - isLocked=true');
return;
}
// 🔥 参考Android版:直接读取成员变量,避免state竞态
final snapshot = MachineControlStatusEntity(
originX: _currentOriginX,
originY: _currentOriginY,
chassisLift: state.controlEntity.chassisLift,
mowerSpeed: state.controlEntity.mowerSpeed,
ignitionStatus: state.controlEntity.ignitionStatus,
isEmergency: state.isEmergency,
);
// 常规安全检查
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;
}
// 发送控制指令
//debugPrint(
// '$logPrefix 📤 发送控制指令: originX=${snapshot.originX}, originY=${snapshot.originY}, mower=${snapshot.mowerSpeed}, lift=${snapshot.chassisLift}, ignition=${snapshot.ignitionStatus}, emergency=${snapshot.isEmergency}',
// );
unawaited(
_sendMotionFrame(snapshot, 'loop', {
'loop': loop,
'tick': timer.tick,
'tickGapUs': gapUs,
}),
);
//debugPrint('$logPrefix ✅ 控制指令已发送');
});
}
//通过方法拿最新 state
MachineControlStatusEntity _getCurrentControlEntity() {
// 🔥 关键修复:必须copyWith创建新对象,避免引用竞态条件
final entity = state.controlEntity;
// _logger.logWithLevel(
// '真实的发送的实体 - originX: ${entity.originX}, originY: ${entity.originY}',
// );
return entity.copyWith(); // 返回副本,不是引用
}
// 3. 更新摇杆数据
void updateJoystick(double x, double y) {
final updatedEntity = state.controlEntity.copyWith(
x: x.toInt(),
y: y.toInt(),
);
emit(state.copyWith(controlEntity: updatedEntity));
}
// 4. 更新功能开关 (比如割刀速度、灯光、点火等)
void updateFunction({int? mower, int? lift, int? ignition, bool? emergency}) {
// debugPrint('🔧 [updateFunction] 调用 - mower: $mower, lift: $lift, ignition: $ignition, emergency: $emergency');
// _logger.logWithLevel(
// '🔧 [updateFunction] 调用 - mower: $mower, lift: $lift, ignition: $ignition, emergency: $emergency',
// );
final updatedEntity = state.controlEntity.copyWith(
mower: mower,
lift: lift,
ignition: ignition,
emergency: emergency,
);
//emit(state.copyWith(controlEntity: updatedEntity));
emit(
state.copyWith(
controlEntity: updatedEntity,
isEmergency: emergency ?? state.isEmergency,
),
);
// debugPrint('>>> [updateFunction] 状态已更新到emit');
// _logger.logWithLevel('>>> [updateFunction] 状态已更新到emit');
}
void updateOriginY(int y) {
// debugPrint('📥 [updateOriginY] 被调用- y=$y');
// 🔥 页面销毁后可能还有迟到的 pointer 回调(CCJoystick 内部有 await),
// 不拦住就会在已 close 的对象上 emit。
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显示)
final updatedEntity = state.controlEntity.copyWith(y: y);
emit(state.copyWith(controlEntity: updatedEntity));
// debugPrint('📝 [updateOriginY] state已更新- originY=$y');
// 🔥 倒车影像:用当前摇杆(左杆前后)实时驱动引导线
_syncReverseCameraFromJoystick();
}
void updateOriginX(int x) {
// debugPrint('📥 [updateOriginX] 被调用- x=$x');
// 🔥 同 updateOriginY:防页面销毁后迟到的摇杆回调打到已 close 的对象。
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显示)
final updatedEntity = state.controlEntity.copyWith(x: x);
emit(state.copyWith(controlEntity: updatedEntity));
// debugPrint('📝 [updateOriginX] state已更新- originX=$x');
// 🔥 倒车影像:用当前摇杆(右杆转向)实时驱动引导线摆动
_syncReverseCameraFromJoystick();
}
/// 🔥 开发阶段:暂用本地摇杆数据合成倒车影像(不依赖嵌入式回传)。
///
/// 激活规则(摇杆输出范围 -100~100,上推为正=前进、下拉为负=倒车,右杆为左右转向):
/// - 倒车(y<0) 或 正在转向(x≠0) → 显示引导线;纯前进直行或松手归零 → 自动收起。
/// - originX(-100~100) → steeringAngle(-45°~45°),驱动引导线左右摆动。
/// - 摇杆无测距传感器 → rearDistanceCm=null(颜色固定为绿)。
/// 嵌入式就绪后,删除本方法及 updateOriginX/Y 里的调用,改回 startReverseCameraMock 接入真实数据源。
void _syncReverseCameraFromJoystick() {
if (isClosed) return;
final int y = _currentOriginY;
final int x = _currentOriginX;
// 🔥 智能激活:倒车 或 正在转向 都显示引导线(解决“只动右杆不显示”)
final bool guideActive = y < 0 || x != 0;
final int gear = guideActive ? 2 : (y > 0 ? 1 : 0);
final double steering = (x.clamp(-100, 100) / 100.0) * 45.0;
final double speed = (y.abs().clamp(0, 100) / 100.0);
emit(
state.copyWith(
reverseCamera: ReverseCameraData(
gear: gear,
steeringAngle: steering,
speed: speed,
rearDistanceCm: null,
),
),
);
}
/// Clear motion immediately and replace queued movement with one priority zero.
/// The common transport gate enforces >=250ms, including this safety frame.
Future<void> 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;
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,
});
}
}
// 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;
_resumeTimer?.cancel();
_resumeTimer = null;
_timer?.cancel();
_timer = null;
emit(state.copyWith(status: RemoteControlStatus.initial));
}
void toggleLock() {
final willLock = !state.isLocked;
emit(state.copyWith(isLocked: willLock));
// 🔥 锁定瞬间归零 + 连发停止帧(与失权 / 急停同一道理):
// IgnorePointer 只拦住以后的推杆,手指正压在摇杆上那一划的
// _currentOriginX/Y 仍会留在单例上;而设备只认“最后收到的运动帧”,
// 光拦不发不会让已在跑的车停下。
if (willLock) {
unawaited(stopAllMovement());
}
}
void togglePermissionDialog(bool show) {
emit(state.copyWith(showPermissionRequestDialog: show));
}
void requestControlPermission() {
// 1. 关闭弹窗
emit(state.copyWith(showPermissionRequestDialog: false));
}
void toggleLeftPip() => emit(state.copyWith(showLeftPip: !state.showLeftPip));
void toggleRightPip() =>
emit(state.copyWith(showRightPip: !state.showRightPip));
// 🔥 切换前后视角(双击屏幕触发)
//
// 这是**纯 UI 层面的翻转**:WebRTCLocalPlayer 用 `isFrontMain: originY >= 0`
// 决定主画面算“前视”还是“后视”(见 remote_control_page 的双击入口)。
//
// 🔥 以前它还会 `_repository.sendControlMachineCmd(updatedEntity)` 直发一帧:
// ① 它绕过了控制循环的 hasPermission / isEmergency 两道门控,无权限或急停时
// 也能把指令弄到设备上;
// ② y=±1 经 diffSteer 换算后是非零线速度,等于双击一下屏幕车会动一下;
// ③ 控制循环读的是成员变量 _currentOriginY,不认这个改动,发出去也是脏值。
// 故只保留状态更新(视角照常生效),不再往设备发帧。
void toggleCameraView() {
if (isClosed) return;
final currentOriginY = state.controlEntity.originY;
// 🔥 originY >= 0 表示前视角,< 0 表示后视角
// 切换逻辑:如果当前是前视角(>=0),切换到后视角(-1);反之亦然
final newOriginY = currentOriginY >= 0 ? -1 : 1;
debugPrint(
'📷 [RemoteControlCubit] 切换前后视角: $currentOriginY -> $newOriginY',
);
final updatedEntity = state.controlEntity.copyWith(y: newOriginY);
emit(state.copyWith(controlEntity: updatedEntity));
}
// 🔥 全局护栏:close 之后的 emit 一律吃下,不让它抛 StateError。
//
// bloc 9.2.1 的 Cubit.emit 在已关闭时会 `throw StateError('Cannot emit new
// states after calling close')`(见 bloc_base.dart)。本 Cubit 是单例,而且
// 到处都是“比页面活得久”的异步回调(0x12 监听 / TCP 重连 / stopAllMovement 的
// await 链 / unawaited 全停),靠逐个加 isClosed 守卫总会有漏网的一条:
// 退登录把单例关掉后,一条迟到的回包就能在控制台抛未捕获异常(调试时直接红屏)。
// 因此这里集中拦:状态丢了就丢了(对象已无人监听),但绝不让异常外渗。
@override
@protected
@visibleForTesting
void emit(RemoteControlState state) {
if (isClosed) {
debugPrint('⚠️ [RemoteControl] Cubit 已关闭,忽略一次 emit(异步回调迟到)');
return;
}
super.emit(state);
}
@override
Future<void> close() {
_emergencyStatusTimer?.cancel();
RemoteControlDiagnostics.instance.end('cubit_close');
_cancelPermissionAttempt();
// 与构造函数里的 addObserver 成对移除,否则回调会打在已关闭的对象上。
WidgetsBinding.instance.removeObserver(this);
_timer?.cancel();
_kickOutSub?.cancel(); // 🔥 0x12 监听:不取消会留着回调打在已 close 的对象上
_kickOutSub = null; // 且下次重新 init 后会叠出第二个监听器(重复弹窗)
_resumeTimer?.cancel();
_resumeTimer = null;
_controlWanted = false;
_suspendedByLifecycle = false;
_deviceStatusSub?.cancel(); // 🔥 取消订阅 DeviceStatusBloc
_tcpStatusSub?.cancel(); // 🔥 取消订阅 TCP 0x02 门槛监听
_reverseCameraSub?.cancel(); // 🔥 取消订阅倒车影像数据流
_reverseCameraSource?.stop();
return super.close();
}
void updateChassisLift(int i) {}
/// 🔥 启动倒车影像数据流(开发期用 Mock 造假数据,机器未开也能联调动画)。
/// 由遥控页 initState 调用;嵌入式就绪后只需替换这里传入的实现类。
void startReverseCameraMock() {
if (_reverseCameraSub != null) return; // 已启动,避免重复订阅
final source = MockReverseCameraSource();
_reverseCameraSource = source;
_reverseCameraSub = source.dataStream.listen((ReverseCameraData data) {
if (isClosed) return;
emit(state.copyWith(reverseCamera: data));
});
source.start();
debugPrint('🚗 [倒车影像] Mock 数据源已启动(嵌入式真数据接入前的联调用)');
}
/// 🔥 停止倒车影像数据流(退出遥控页调用,避免定时器空转)。
void stopReverseCameraMock() {
_reverseCameraSub?.cancel();
_reverseCameraSub = null;
_reverseCameraSource?.stop();
_reverseCameraSource = null;
emit(state.copyWith(reverseCamera: const ReverseCameraData.idle()));
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<bool> 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(reason: on ? 'emergency_on' : 'emergency_off');
// ① 先置状态:急停时让 250ms 控制循环下一 tick 立刻停发运动指令;
// 解除时循环恢复正常发送。
updateFunction(emergency: on);
// ② 再绕过控制循环的 isEmergency 门控,直发带急停位的指令帧(双重保险):
// - 按下:连发 emergency=1 + 全零,让设备明确收到「急停」,而不只靠「收不到指令」。
// - 取消:连发 emergency=0 + 全零,让设备明确「解除急停、恢复正常」。
unawaited(_sendEmergencyFrames(emergency: on));
}
/// Emergency on/off uses the same priority >=250ms gate as every 0x00 frame.
Future<void> _sendEmergencyFrames({required bool emergency}) async {
final frame = MachineControlStatusEntity(
originX: 0,
originY: 0,
chassisLift: 0,
mowerSpeed: 0,
ignitionStatus: 0,
isEmergency: emergency,
);
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. 关闭弹窗(立即关闭,防止重复点击)
emit(state.copyWith(showPermissionRequestDialog: false));
// 2. 发送响应到服务器
// 🔥 不 rethrow:这里处于权限弹窗的按钮回调中间,异常一旦飞出去,
// 调用方的 `resetPermissionCoolDown()` / `togglePermissionDialog(false)` /
// `Navigator.pop()` 全都不会执行,barrierDismissible:false 的模态弹窗就
// 死在屏幕上(只能物理返回),同时附带一条未捕获异步异常。
// 发送失败时只做到这里为止:弹窗标志已复位(第 1 步),而权限态
// 不往下改——响应根本没出网,服务端仍认为本端持有控制权,保持原值才是
// 两边一致的状态;下次 activate / 走仅查询会从 HTTP 拿到真实结果。
try {
_repository.respondPermission(agreed, deviceId);
} catch (e) {
debugPrint(' ❌ TCP权限响应指令发送失败(不抛出,保证弹窗能关闭): $e');
debugPrint(' ❌ 错误类型: ${e.runtimeType}');
_logger.logWithLevel(
' ❌ TCP权限响应指令发送失败(不抛出,保证弹窗能关闭): $e',
level: 'ERROR',
shouldLog: true,
);
debugPrint('${_getTimePrefix()} ====权限弹窗响应提前结束====');
return;
}
// 3. 根据用户选择更新控制状态
if (agreed) {
emit(
state.copyWith(
hasPermission: false,
showPermissionRequestDialog: false,
),
);
// 🔥 主动让权同样要归零 + 全停(理由同 0x12 失权分支):用户“同意”的瞬间
// 可能手指还压在摇杆上,不归零则下次拿回控制权时会按旧推量复活。
unawaited(stopAllMovement());
} else {
// 用户拒绝 APP 继续保持控制权
// 🔥 必须同时设置 showPermissionRequestDialog: false,防止状态回退
emit(
state.copyWith(hasPermission: true, showPermissionRequestDialog: false),
);
}
debugPrint('${_getTimePrefix()} ====权限弹窗响应结束=====');
}
void _tracePermission(String step, [Map<String, Object?> 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<void> requestControlPermissionS(
String deviceName,
String deviceId, {
String source = '自动',
bool grabControl = false,
}) async {
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;
}
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);
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;
}
final info = result.fold<Map<String, dynamic>>(
(failure) => throw failure,
(value) => value,
);
if (info['hasPermission'] is! bool) {
throw ControlPermissionFailure('permission_query_invalid');
}
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,
isLocked: state.isEmergency,
controlEntity: state.controlEntity.copyWith(
emergency: false,
mower: 2,
),
lastMowerOperation: MowerLastOperation.none,
),
);
debugPrint('🔑 [RemoteControl] 已重置权限;保留急停请求态 ${state.isEmergency}');
_logger.logWithLevel(
'🔑 [RemoteControl] 已重置权限;保留急停请求态 ${state.isEmergency}',
shouldLog: true,
);
}
}
/// 🔥 重置弹窗状态 - 在弹窗关闭后调用(已简化,不再需要标志位)
void resetPermissionCoolDown() {
// 标志位已移除,此方法保留以保持向后兼容性
}
Future<void> confirmPermissionResponse(
String deviceName,
String platform,
bool agreed,
) async {
final timePrefix = _getTimePrefix();
final logPrefix = '$timePrefix 🔑 [RemoteControl] [权限确认]';
debugPrint('$logPrefix ========进入TCP发送=================================');
debugPrint('$logPrefix ⚡️ confirmPermissionResponse 方法被调用');
debugPrint('$logPrefix 用户操作: ${agreed ? "同意" : "拒绝"}');
debugPrint('$logPrefix deviceName: $deviceName');
debugPrint('$logPrefix platform: $platform');
respondPermission(agreed, deviceName);
// 2. 调用 HTTP 接口获取最终权限状态
debugPrint('$logPrefix 📡 调用 HTTP 接口确认最终权限状态..');
/* final result = await _requestControlPermissionUseCase(
RequestControlPermissionParams(
deviceName: deviceName,
deviceId: platform,
),
);*/
// 3. 根据 HTTP 返回的真实权限状态更新UI
/* result.fold(
(failure) {
final failLogPrefix = '${_getTimePrefix()} 🔑 [RemoteControl] [权限确认]';
debugPrint('$failLogPrefix APP HTTP请求失败: ${failure.message}');
debugPrint('$failLogPrefix ⚠️ 保持当前状态不变');
},
(permissionInfo) {
final bool hasPermission =
permissionInfo['hasPermission'] as bool? ?? false;
final String? owner = permissionInfo['owner'] as String?;
final successLogPrefix =
'${_getTimePrefix()} 🔑 [RemoteControl] [权限确认]';
debugPrint(
'$successLogPrefix APP HTTP返回真实权限状态 hasPermission=$hasPermission, owner=$owner',
);
debugPrint(
'$successLogPrefix 🔄 正在更新UI - hasPermission: ${state.hasPermission} -> $hasPermission',
);
// 🔥 直接用HTTP 返回的权限状态覆盖
// emit(state.copyWith(hasPermission: hasPermission));
debugPrint(
'$successLogPrefix 📊 UI已同步完成- 当前 hasPermission=$hasPermission',
);
},
);*/
debugPrint(
'${_getTimePrefix()} 🔑 [RemoteControl] [权限确认] =========================================',
);
}
/// 发送底盘指令
void sendChassisCommand(int i) {
// // debugPrint('>>> [底盘指令] ${i}');
// _logger.logWithLevel('>>> [底盘指令] ${i}');
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) {
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,
),
);
}
/// 发送点火指令
void sendFireCommand(int i) {
//void updateFunction({int? mower, int? lift, int? ignition, bool? emergency})
// updateFunction(mower:0, lift: 0, ignition: i, emergency: false);
// debugPrint('>>> [点火指令] ${i}');
// _logger.logWithLevel('>>> [点火指令] ${i}');
updateFunction(ignition: i);
}
// 发送障碍物识别指令
void toggleObstacleRecognition() {
emit(
state.copyWith(obstacleRecognitionFlag: !state.obstacleRecognitionFlag),
);
}
void toggleTopLeftExpand() {
emit(state.copyWith(topRightIsExpanded: !state.topRightIsExpanded));
}
/// 检查设备状态推送是否活跃(5秒内有推送视为活跃)
bool isStatusPushActive() {
if (!state.hasReceivedStatusPush) return false;
if (_lastStatusPushTime == null) return false;
// 超过5秒未收到新推送,视为推送已中断
return DateTime.now().difference(_lastStatusPushTime!) <
const Duration(seconds: 5);
}
Future<int> getNetworkDelay() async {
try {
final ping = Ping(TCPConsts.TCP_IP, count: 1, timeout: 1);
// 等待一次结果
final data = await ping.stream.first;
if (data.response != null && data.response!.time != null) {
// 返回和cmd 一样的毫秒值
return data.response!.time!.inMilliseconds;
} else {
return 9999;
}
} catch (e) {
return 9999;
}
}
//app退出远程遥控界面释放权限(type=2),退出机器人详情页释放权限(type=1)
Future<bool> releasePermission({
required String deviceId,
required int type,
}) async {
return await _repository.releasePermission(deviceId: deviceId, type: type);
}
/// 🔥 设置待控制的设备(从机器人列表点击进入时调用)
void setTargetDevice(DeviceEntity device) async {
resetMowerControl();
debugPrint('🎯 [RemoteControl] ========== 开始设置目标设备 ==========');
debugPrint('🎯 [RemoteControl] 设备名称: ${device.deviceName}');
debugPrint(
'🎯 [RemoteControl] 当前TCP状态: ${tcpClient.isConnected ? "已连接" : "未连接"}',
);
// 🔥 关键修复:切换设备时清空所有缓存,防止显示上一个设备的数据
_clearAllCache();
debugPrint('✅ [RemoteControl] 已清空所有缓存数据');
debugPrint('📦 [RemoteControl] 更新targetDevice状态');
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 状态并清空缓存,
// 清除上一个设备的坐标/状态,防止路径规划显示旧车位置(与 switchDevice 对齐)
deviceStatusBloc.add(DeviceStatusReset());
// 🔥 MQTT机器状态订阅:切换设备时订阅新设备的topic(与DevicesCubit.switchDevice相同逻辑)
debugPrint('📡 [RemoteControl] 开始MQTT机器状态订阅: ${device.deviceName}');
deviceStatusBloc.startMqttRealtimeListening(device.deviceName);
// 🔥 关键修复:TCP 已在登录时建立,设备切换只用 HTTP
// 不再创建新 TCP 连接,避免重复发送 0x03 触发服务端推送 have_logged_in
if (tcpClient.isConnected) {
debugPrint('✅ [RemoteControl] TCP已连接,使用HTTP切换设备: ${device.deviceName}');
_deviceRepository.switchDevice("app", device.deviceName).then((result) {
result.fold(
(failure) {
debugPrint('❌ [RemoteControl] HTTP切换设备失败: ${failure.message}');
},
(success) {
debugPrint('✅ [RemoteControl] HTTP切换设备成功, code: $success');
},
);
});
} else {
// TCP未连接(登录时的初始化可能失败或还在进行中)
// 兜底:使用 connectBySwitch 建立连接
debugPrint('🔌 [RemoteControl] TCP未连接,兜底调用 connectBySwitch');
try {
await tcpClient.connectBySwitch(
host: TCPConsts.TCP_IP,
port: TCPConsts.TCP_PORT,
deviceName: device.deviceName,
);
debugPrint('✅ [RemoteControl] TCP兜底连接成功!');
} catch (e) {
debugPrint('❌ [RemoteControl] TCP兜底连接失败: $e');
}
}
debugPrint('🎯 [RemoteControl] ========== 目标设备设置完成 ==========');
}
/// 🔥 清除待控制设备(退出远程控制页时调用)
void clearTargetDevice() {
_emergencyAttempt++;
// debugPrint('🧹 [RemoteControl] 清除待控制设备');
// _logger.logWithLevel('🧹 [RemoteControl] 清除待控制设备');
// 🔥 关键修复:退出页面时清空所有缓存,防止数据滞留
_clearAllCache();
debugPrint('✅ [RemoteControl] 已清空所有缓存数据');
_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: '',
),
);
}
/// 🔥 获取设备
DeviceEntity? getSelectedDevice() {
return state.targetDevice;
}
/// 🔥 清空所有缓存数据(解决数据滞留和跨设备数据显示问题)
void _clearAllCache() {
_cacheVoltage = null;
_cacheBattery = null;
_cacheCtrlMode = null;
_cachePing = null;
_lastUiUpdateTime = null;
_lastStatusPushTime = null; // 重置推送时间
// 🔥 同时重置 UI 状态为初始值
if (!isClosed) {
emit(
state.copyWith(
runningStatusModel: state.runningStatusModel.copyWith(
voltage: '--',
battery: '--',
controlMode: '--',
),
battery: 0,
ping: null,
hasReceivedStatusPush: false, // 重置推送接收标志
),
);
}
debugPrint(
'🗑️ [RemoteControl] 缓存已清空 - voltage, battery, controlMode, ping',
);
}
/// 🔥 退出登录时清空所有状态(比 _clearAllCache 更彻底,重置全部 state 字段)
void clearAll() {
_emergencyAttempt++;
_timer?.cancel();
_timer = null;
_resumeTimer?.cancel();
_resumeTimer = null;
// 🔥 退出登录:控制意图与后台挂起位一并清掉,否则回前台会恢复一个
// 已不属于任何页面的控制循环。
_controlWanted = false;
_suspendedByLifecycle = false;
_cacheVoltage = null;
_cacheBattery = null;
_cacheCtrlMode = null;
_cachePing = null;
_lastUiUpdateTime = null;
_lastStatusPushTime = null;
_currentOriginX = 0;
_currentOriginY = 0;
if (!isClosed) {
emit(
RemoteControlState(
controlEntity: MachineControlStatusEntity(),
runningStatusModel: RunningStatusModel(),
),
);
}
debugPrint('🗑️ [RemoteControl] clearAll - 所有状态已重置为初始值');
}
}