对接远程遥控

This commit is contained in:
2026-06-05 19:06:21 +08:00
parent d8879dad62
commit 7c9734d918
53 changed files with 4683 additions and 1612 deletions

View File

@@ -0,0 +1 @@
enum ControlMode { TCP, BLE, LOCAL, NONE, OTHER }

View File

@@ -1,4 +1,4 @@
import 'dart:async';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -7,9 +7,12 @@ 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/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_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';
@@ -22,6 +25,7 @@ import '../../domain/usecase/remote_control_usecase.dart';
class RemoteControlCubit extends Cubit<RemoteControlState> {
final RemoteControlRepository _repository;
final RequestControlPermissionUseCase _requestControlPermissionUseCase;
final DeviceRepository _deviceRepository; // 🔥 注入设备仓库
Timer? _timer;
StreamSubscription? _kickOutSub; // 新增:用于管理监听生命周期
final NetMessageDispatcher dispatcher;
@@ -30,16 +34,28 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
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;
// 🔥 权限请求冷却期机制 - 防止Web端持续发送请求导致弹窗不断显示
DateTime? _lastPermissionResponseTime; // 记录上次响应权限请求的时间
static const _coolDownDuration = Duration(seconds: 5); // 冷却期5秒
// 🔥 同步锁 - 防止状态更新期间接收新请求导致重复弹窗
bool _isProcessingPermissionRequest = false;
// 🔥 获取带时间戳的日志前缀
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.dispatcher,
this.deviceStatusBloc, // 🔥 注入
) : super(
@@ -52,54 +68,55 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
_initDeviceStatusListener(); // 🔥 改为订阅 DeviceStatusBloc
}
// 🔥 新增:订阅 DeviceStatusBloc 的状态流,而不是直接监听 TCP
// 🔥 新增:订阅 DeviceStatusBloc 的状态流,而不是直接监听TCP
void _initDeviceStatusListener() {
_logger.logWithLevel('>>> [RemoteControl] begin 订阅 DeviceStatusBloc 状态流');
// // _logger.logWithLevel('>>> [RemoteControl] begin 订阅 DeviceStatusBloc 状态流');
_deviceStatusSub?.cancel();
_deviceStatusSub = deviceStatusBloc.stream.listen((deviceState) async {
if (deviceState is DeviceStatusUpdated) {
final voltage = deviceState.status.voltage;
final battery = deviceState.status.battery;
final controlMode = deviceState.status.controlMode == '3' ? '远程模式' : '本地模式';
final controlMode = deviceState.status.controlMode == '3'
? '远程模式'
: '本地模式';
final c = getNetworkDelay();
emit(state.copyWith(
runningStatusModel: state.runningStatusModel.copyWith(
voltage: voltage.toString(),
battery: battery.toString(),
controlMode: controlMode,
emit(
state.copyWith(
runningStatusModel: state.runningStatusModel.copyWith(
voltage: voltage.toString(),
battery: battery.toString(),
controlMode: controlMode,
),
battery: int.tryParse(battery) ?? 0,
ping: await c,
),
battery: int.tryParse(battery) ?? 0,
ping: await c,
));
);
_logger.logWithLevel('✅ [RemoteControl] 从 DeviceStatusBloc 收到更新: 电压=$voltage, 电量=$battery, 模式=$controlMode');
// // _logger.logWithLevel('✅ [RemoteControl] 从 DeviceStatusBloc 收到更新: 电压=$voltage, 电量=$battery, 模式=$controlMode');
}
});
_logger.logWithLevel('>>> [RemoteControl] ✅ DeviceStatusBloc 订阅已建立完成');
// _logger.logWithLevel('>>> [RemoteControl] ✅ DeviceStatusBloc 订阅已建立完成');
}
// 🔥 超简单方法:传入 IP,得到 ping 值
// 🔥 辅助方法:更新运行状态
void _updateStatusFromDevice(RunningStatusModel newStatus) {
debugPrint('✅ [_updateStatusFromDevice] 收到运行状态更新:$newStatus');
// // debugPrint('✅ [_updateStatusFromDevice] 收到运行状态更新:$newStatus');
if (!isClosed) {
emit(state.copyWith(
runningStatusModel: newStatus,
voltage: int.tryParse(newStatus.voltage) ?? 0,
battery: int.tryParse(newStatus.battery) ?? 0,
));
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}%');
// debugPrint('✅ [更新运行状态] 电压:${newStatus.voltage}V, 电量:${newStatus.battery}%');
// _logger.logWithLevel('✅ [更新运行状态] 电压:${newStatus.voltage}V, 电量:${newStatus.battery}%');
}
}
@@ -114,25 +131,40 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
// });
// }
Future<void> _initPacketListener() async {
//print('>>> [RemoteControl] begin 初始化 0x12 监听器');
_logger.logWithLevel('>>> [RemoteControl] begin 0x12 监听器');
final logPrefix = '${_getTimePrefix()} 🔍 [RemoteControl] [0x12监听器]';
debugPrint('$logPrefix =========================================');
debugPrint('$logPrefix 开始初始化 0x12 监听器');
_logger.logWithLevel('$logPrefix 开始初始化 0x12 监听器', shouldLog: true);
_kickOutSub?.cancel(); // 防止重复监听
_kickOutSub = dispatcher.onCommand(0x12).listen((packet) {
//print('>>> [RemoteControl] 收到 0x12 原始包,payload 长度=${packet.payload.length}');
_logger.logWithLevel('>>> [RemoteControl] 收到 0x12 原始包,payload 长度=${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 {
// 🔥 关键:手动去掉最后 2 个 CRC 字节
String jsonString;
if (packet.payload.length > 2) {
jsonString = utf8.decode(packet.payload.sublist(0, packet.payload.length - 2));
jsonString = utf8.decode(
packet.payload.sublist(0, packet.payload.length - 2),
);
} else {
jsonString = utf8.decode(packet.payload);
}
//print('>>> [RemoteControl] 去除 CRC 后的 JSON: $jsonString');
_logger.logWithLevel('>>> [RemoteControl] 去除 CRC 后的 JSON: $jsonString');
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] JSON内容: $jsonString');
_logger.logWithLevel(
'$timeNow 🔍 [RemoteControl] [0x12监听器] 去除CRC后的JSON: $jsonString',
shouldLog: true,
);
final jsonMap = jsonDecode(jsonString);
@@ -141,69 +173,139 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
final platform = jsonMap['platform'];
final respondData = jsonMap['respond'];
//print('>>> [RemoteControl] 📋 requestType=$requestType, platform=$platform');
_logger.logWithLevel('>>> [RemoteControl] 📋 requestType=$requestType, platform=$platform');
debugPrint(
'$timeNow 🔍 [RemoteControl] [0x12监听器] requestType: $requestType, platform: $platform, hasRespond: ${respondData != null}',
);
// 情况 1: 响应格式 - {"respond":{"switchResult":true,"deviceId":"...","holder":"you"}}
if (respondData != null && respondData is Map) {
final switchResult = respondData['switchResult'];
//print('>>> [RemoteControl] 📊 收到切换结果响应:switchResult = $switchResult');
_logger.logWithLevel('>>> [RemoteControl] 📊 收到切换结果响应:switchResult = $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 失去控制权
emit(state.copyWith(hasPermission: true, showPermissionRequestDialog: false));
print('>>> [RemoteControl] ✅ 权限已切');
// 切换成功,当前 APP 获得控制权
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ✅ APP获得控制权');
debugPrint(
'$timeNow 🔍 [RemoteControl] [0x12监听器] 设置 hasPermission = true',
);
emit(state.copyWith(hasPermission: true));
} else {
// 切换失败或拒绝,保持当前状态
emit(state.copyWith(showPermissionRequestDialog: false));
print('>>> [RemoteControl] ❌ 权限切换失败/被拒绝');
// 切换失败或拒绝,APP 失去控制权
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ❌ APP失去控制权');
debugPrint(
'$timeNow 🔍 [RemoteControl] [0x12监听器] 设置 hasPermission = false',
);
emit(
state.copyWith(
hasPermission: false,
// 🔥 修复:不强制关闭弹窗,让弹窗由用户操作控制
),
);
}
}
}
// 情况 2: 请求格式 - {"request":"switch_control","deviceId":"...","platform":"web",...}
else if (requestType == 'switch_control') {
final requestDeviceId = jsonMap['deviceId'];
final webLogPrefix =
'${_getTimePrefix()} 🚨 [RemoteControl] [Web端权限请求]';
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') {
//print('>>> [RemoteControl] 🚨 $platform 端请求控制权,打开弹窗询问用户');
_logger.logWithLevel('>>> [RemoteControl] 🚨 $platform 端请求控制权,打开弹窗询问用户');
if (!isClosed) {
emit(state.copyWith(showPermissionRequestDialog: true));
// 🔥 验证设备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 设备ID匹配,弹出权限请求对话框',
shouldLog: true,
);
if (!isClosed) {
emit(
state.copyWith(
showPermissionRequestDialog: true,
requestingDeviceId: requestDeviceId?.toString(),
requestingPlatform: platform.toString(),
),
);
}
} else {
debugPrint('$webLogPrefix ⚠️ 弹窗已显示,忽略重复请求');
_logger.logWithLevel(
'$webLogPrefix ⚠️ 弹窗已显示,忽略重复请求',
shouldLog: true,
);
}
} else {
debugPrint('$webLogPrefix ⚠️ 设备ID不匹配,忽略');
debugPrint(
'$webLogPrefix currentDeviceId: $currentDeviceId, requestDeviceId: $requestDeviceId',
);
_logger.logWithLevel(
'$webLogPrefix ⚠️ 设备ID不匹配,忽略请求',
shouldLog: true,
);
}
} else {
//print('>>> [RemoteControl] ℹ️ APP 自己的请求回显,忽略不弹窗');
_logger.logWithLevel('>>> [RemoteControl] ℹ️ APP 自己的请求回显,忽略不弹窗');
debugPrint('$webLogPrefix ℹ️ APP自己的请求回显或platform为空,忽略不弹窗');
_logger.logWithLevel(
'$webLogPrefix ℹ️ APP自己的请求回显,忽略',
shouldLog: true,
);
}
debugPrint('$webLogPrefix =========================================');
}
// 情况 3: 异地登录通知 - {"request":"have_logged_in",...}
else if (requestType == 'have_logged_in') {
//print('>>> [RemoteControl] ⚠️ 检测到异地登录,打开弹窗提示');
_logger.logWithLevel('>>> [RemoteControl] ⚠️ 检测到异地登录,打开弹窗提示');
debugPrint('${_getTimePrefix()} ⚠️ [RemoteControl] 检测到异地登录');
_logger.logWithLevel(
'${_getTimePrefix()} ⚠️ [RemoteControl] 检测到异地登录,打开弹窗提示',
shouldLog: true,
);
if (!isClosed) {
emit(state.copyWith(showPermissionRequestDialog: true));
}
}
else {
// print('>>> [RemoteControl] ℹ️ 未知类型的 0x12 包,忽略');
_logger.logWithLevel('>>> [RemoteControl] ℹ️ 未知类型的 0x12 包,忽略');
} else {
debugPrint('${_getTimePrefix()} ℹ️ [RemoteControl] 未知类型的 0x12 包,忽略');
_logger.logWithLevel(
'${_getTimePrefix()} ℹ️ [RemoteControl] 未知类型的 0x12 包,忽略',
shouldLog: true,
);
}
} catch (e) {
//print('>>> [RemoteControl] ❌ 解析失败:$e');
_logger.logWithLevel('>>> [RemoteControl] ❌ 解析失败:$e');
debugPrint('${_getTimePrefix()} ❌ [RemoteControl] 解析失败:$e');
_logger.logWithLevel(
'${_getTimePrefix()} ❌ [RemoteControl] 解析失败:$e',
shouldLog: true,
);
}
});
final c = getNetworkDelay();
emit(state.copyWith(
ping: await c, // 这里直接使用异步返回的数值
));
//print('>>> [RemoteControl] ✅ 0x12 监听器已建立完成');
_logger.logWithLevel('>>> [RemoteControl] ✅ 0x12 监听器已建立完成');
}
// 2. 开启 100ms 控制循环 (在进入遥控页面或点击“开始”时调用)
/* void startControlLoop() {
/* void startControlLoop() {
_timer?.cancel();
_timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
// 🔥 关键修复:每次循环都重新读取最新的 state
@@ -211,21 +313,27 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
// 🔥 安全检查:无权限或急停时不发送
if (!state.hasPermission || state.isEmergency) {
debugPrint('⚠️ [定时器] 跳过发送 - hasPermission=${state.hasPermission}, isEmergency=${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}');
// debugPrint('⏰ [定时器] 发送控制指令 - originX=${currentEntity.originX}, originY=${currentEntity.originY}');
// _logger.logWithLevel('真实的发送的实体 - originX: ${currentEntity.originX}, originY: ${currentEntity.originY}');
_repository.sendControlMachineCmd(currentEntity);
});
emit(state.copyWith(status: RemoteControlStatus.controlling));
}*/
void startControlLoop() {
_timer?.cancel();
final logPrefix = '⏰ [RemoteControl] [控制循环]';
//debugPrint('$logPrefix =========================================');
//debugPrint('$logPrefix 启动控制循环,间隔: 100ms');
///debugPrint('$logPrefix =========================================');
_timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
if (isClosed) {
// debugPrint('$logPrefix ❌ Cubit已关闭,取消定时器');
timer.cancel();
return;
}
@@ -239,28 +347,34 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
ignitionStatus: state.controlEntity.ignitionStatus,
isEmergency: state.isEmergency,
);
// 常规安全检查
if (!state.hasPermission) {
debugPrint('⚠️ [定时器] 无权限,跳过发送');
// debugPrint('$logPrefix ⚠️ 无权限,跳过发送 - hasPermission=false');
return;
}
if (state.isEmergency) {
debugPrint('🚨 [定时器] 急停状态,跳过发送');
// debugPrint('$logPrefix 🚨 急停状态,跳过发送 - isEmergency=true');
return;
}
_logger.logWithLevel('[定时器] 发送控制指令 - originX=${snapshot.originX}, originY=${snapshot.originY}');
debugPrint('📤 [定时器] 准备发送 - originX=${snapshot.originX}, originY=${snapshot.originY}');
// 发送控制指令
//debugPrint(
// '$logPrefix 📤 发送控制指令: originX=${snapshot.originX}, originY=${snapshot.originY}, mower=${snapshot.mowerSpeed}, lift=${snapshot.chassisLift}, ignition=${snapshot.ignitionStatus}, emergency=${snapshot.isEmergency}',
// );
_repository.sendControlMachineCmd(snapshot);
//debugPrint('$logPrefix ✅ 控制指令已发送');
});
}
//通过方法拿最新 state
//通过方法拿最新 state
MachineControlStatusEntity _getCurrentControlEntity() {
// 🔥 关键修复:必须copyWith创建新对象,避免引用竞态条件
final entity = state.controlEntity;
_logger.logWithLevel('真实的发送的实体 - originX: ${entity.originX}, originY: ${entity.originY}');
// _logger.logWithLevel(
// '真实的发送的实体 - originX: ${entity.originX}, originY: ${entity.originY}',
// );
return entity.copyWith(); // 返回副本,不是引用
}
@@ -275,8 +389,10 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
// 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');
// 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,
@@ -284,85 +400,93 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
emergency: emergency,
);
//emit(state.copyWith(controlEntity: updatedEntity));
emit(state.copyWith(
controlEntity: updatedEntity,
isEmergency: emergency ?? state.isEmergency,
));
debugPrint('✅ [updateFunction] 状态已更新并 emit');
_logger.logWithLevel('✅ [updateFunction] 状态已更新并 emit');
emit(
state.copyWith(
controlEntity: updatedEntity,
isEmergency: emergency ?? state.isEmergency,
),
);
// debugPrint('>>> [updateFunction] 状态已更新到emit');
// _logger.logWithLevel('>>> [updateFunction] 状态已更新到emit');
}
void updateOriginY(int y) {
debugPrint('📥 [updateOriginY] 被调用 - y=$y');
// debugPrint('📥 [updateOriginY] 被调用- y=$y');
// 🔥 参考Android版:直接更新成员变量
_currentOriginY = y;
// 同时更新state(用于UI显示)
final updatedEntity = state.controlEntity.copyWith(y: y);
emit(state.copyWith(controlEntity: updatedEntity));
debugPrint('📝 [updateOriginY] state已更新 - originY=$y');
// debugPrint('📝 [updateOriginY] state已更新- originY=$y');
}
void updateOriginX(int x) {
debugPrint('📥 [updateOriginX] 被调用 - x=$x');
// debugPrint('📥 [updateOriginX] 被调用- x=$x');
// 🔥 参考Android版:直接更新成员变量
_currentOriginX = x;
// 同时更新state(用于UI显示)
final updatedEntity = state.controlEntity.copyWith(x: x);
emit(state.copyWith(controlEntity: updatedEntity));
debugPrint('📝 [updateOriginX] state已更新 - originX=$x');
// debugPrint('📝 [updateOriginX] state已更新- originX=$x');
}
/// 🔥 安全方法:同时清零双轴,确保只发送一次完全停止指令
Future<void> stopAllMovement() async {
debugPrint('🛑 [stopAllMovement] 开始执行 - 当前成员变量: originX=$_currentOriginX, originY=$_currentOriginY');
// debugPrint(
// '🛑 [stopAllMovement] 开始执行- 当前成员变量: originX=$_currentOriginX, originY=$_currentOriginY',
// );
// 🔥 参考Android版:直接清零成员变量
_currentOriginX = 0;
_currentOriginY = 0;
// 🔥 关键修复:先暂停定时器,防止定时器在停止期间发送旧的运动指令
_timer?.cancel();
_timer = null; // 🔥 彻底清空,防止重复启动
_timer = null; // 🔥 彻底清空,防止重复启用
final updatedEntity = state.controlEntity.copyWith(x: 0, y: 0);
// 一次性更新双轴(即使无权限也要更新本地state)
emit(state.copyWith(controlEntity: updatedEntity));
// 🔥 安全底线:停止指令必须无视权限强制发送!
debugPrint('🛑 [stopAllMovement] 双轴归零,发送停止指令 - originX=0, originY=0');
await _sendStopCommandRepeatedly(updatedEntity); // ✅ 等待所有指令发送完成
// debugPrint('🛑 [stopAllMovement] 双轴归零,发送停止指令- originX=0, originY=0');
await _sendStopCommandRepeatedly(updatedEntity); // 等待所有指令发送完成
// 🔥 恢复定时器
await Future.delayed(const Duration(milliseconds: 200));
startControlLoop();
debugPrint('✅ [stopAllMovement] 执行完成');
// debugPrint('>>> [stopAllMovement] 执行完成');
}
/// 🔥 统一方法:连续发送30次停止指令,彻底清空TCP缓冲区
Future<void> _sendStopCommandRepeatedly(MachineControlStatusEntity stopEntity) async {
debugPrint('🛑 [紧急停止] 开始连续发送30次停止指令 - originX=${stopEntity.originX}, originY=${stopEntity.originY}');
// 🔥 注意:_lastStopTime 已经在 stopAllMovement() 中设置了,这里不需要再设置
/// 🔥 统一方法:连续发送10次停止指令,彻底清空TCP缓冲区
Future<void> _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++) {
_repository.sendControlMachineCmd(stopEntity);
sentCount++;
if (i % 5 == 0) {
debugPrint('🛑 [紧急停止] 已发送第${i + 1}次');
// debugPrint('🛑 [紧急停止] 已发送第${i + 1}次');
}
if (i < 19) {
await Future.delayed(const Duration(milliseconds: 5));
}
}
// 🔥 延迟后再发送10次(双重保险,对抗网络抖动)
// 🔥 延迟后再发10次(双重保险,对抗网络抖动)
await Future.delayed(const Duration(milliseconds: 100));
for (int i = 0; i < 10; i++) {
_repository.sendControlMachineCmd(stopEntity);
@@ -371,8 +495,8 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
await Future.delayed(const Duration(milliseconds: 5));
}
}
debugPrint('✅ [紧急停止] 所有30次停止指令已发出');
// debugPrint('>>> [紧急停止] 所有20次停止指令已发出');
}
// 5. 停止控制循环
@@ -396,7 +520,8 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
}
void toggleLeftPip() => emit(state.copyWith(showLeftPip: !state.showLeftPip));
void toggleRightPip() => emit(state.copyWith(showRightPip: !state.showRightPip));
void toggleRightPip() =>
emit(state.copyWith(showRightPip: !state.showRightPip));
@override
Future<void> close() {
@@ -408,34 +533,85 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
void updateChassisLift(int i) {}
void updateEmergency(bool bool) {
debugPrint('🚨 [急停] ${bool ? "触发急停!" : "解除急停"}');
// debugPrint('🚨 [急停] ${bool ? "触发急停!" : "解除急停"}');
updateFunction(emergency: bool);
}
void respondPermission(bool bool, String deviceId) {
void respondPermission(bool agreed, String deviceId) {
// 🔥 记录响应时间,开启冷却期
_lastPermissionResponseTime = DateTime.now();
//debugPrint('$logPrefix 开启权限请求冷却期,持续${_coolDownDuration.inSeconds}秒');
// 1. 关闭弹窗(立即关闭,防止重复点击)
emit(state.copyWith(showPermissionRequestDialog: false));
// 2. 发送响应到服务端
_repository.respondPermission(bool, deviceId);
// 3. 根据用户选择更新控制状态
if (bool) {
// 用户同意 → APP 失去控制权,Web 端获得控制权
emit(state.copyWith(hasPermission: false));
//路由到首页home
} else {
// 用户拒绝 → APP 继续保持控制权
emit(state.copyWith(hasPermission: true));
// 2. 发送响应到服务器
//debugPrint('$logPrefix 📤 发送权限响应命令到服务器');
try {
// 🔥 关键调用:发送 TCP 指令
debugPrint('{_coolDownDuration.inSeconds}秒');
_repository.respondPermission(agreed, deviceId);
} catch (e) {
debugPrint(' ❌ TCP权限响应指令发送失败: $e');
debugPrint(' ❌ 错误类型: ${e.runtimeType}');
_logger.logWithLevel(' TCP权限响应指令发送失败 $e', shouldLog: true);
// 即使发送失败,也要更新状态
rethrow;
}
// 3. 根据用户选择更新控制状态
if (agreed) {
emit(
state.copyWith(
hasPermission: false,
showPermissionRequestDialog: false,
),
);
} else {
// 用户拒绝 APP 继续保持控制权
// 🔥 必须同时设置 showPermissionRequestDialog: false,防止状态回退
emit(
state.copyWith(hasPermission: true, showPermissionRequestDialog: false),
);
}
debugPrint(
'${_getTimePrefix()} ====权限弹窗响应结束=====',
);
}
void requestControlPermissionS(String deviceName, String deviceId) async {
// 1. 关闭弹窗
emit(state.copyWith(showPermissionRequestDialog: false));
Future<void> requestControlPermissionS(
String deviceName,
String deviceId, {
String source = '自动',
}) async {
final timePrefix = _getTimePrefix();
final logPrefix = '$timePrefix 🔑 [RemoteControl] [请求权限接口-$source]';
debugPrint('$logPrefix =========================================');
debugPrint('$logPrefix 开始请求控制权');
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,
);
// 2. 调用 UseCase
// 1. 只有当弹窗不是因Web 端请求权限而显示时,才关闭弹窗
// 避免 Web 端请求权限的弹窗被自动关闭(一闪而过的问题)
if (state.requestingPlatform == null) {
debugPrint('$logPrefix 关闭权限请求弹窗 (非Web端触发)');
emit(state.copyWith(showPermissionRequestDialog: false));
} else {
debugPrint('$logPrefix 保留弹窗 (Web端请求触发)');
}
// 2. 调用 UseCase 获取 HTTP 返回的完整权限信息
debugPrint('$logPrefix 调用 HTTP 接口查询权限状态..');
final result = await _requestControlPermissionUseCase(
RequestControlPermissionParams(
deviceName: deviceName,
@@ -445,51 +621,158 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
// 3. 处理结果
result.fold(
(failure) {
//print('❌ [RemoteControl] 请求控制权限失败:${failure.message}');
_logger.logWithLevel('❌ [RemoteControl] 请求控制权限失败:${failure.message}');
// 可以在这里显示错误提示或重新打开弹窗
(failure) {
final failLogPrefix =
'${_getTimePrefix()} 🔑 [RemoteControl] [请求权限接口-$source]';
debugPrint('$failLogPrefix APP请求控制权限失败: ${failure.message}');
debugPrint('$failLogPrefix 重新打开权限请求弹窗');
_logger.logWithLevel(
'$failLogPrefix APP请求控制权限失败: ${failure.message}',
shouldLog: true,
);
emit(state.copyWith(showPermissionRequestDialog: true));
},
(success) {
// 更新状态
//print('✅ [RemoteControl] 请求控制权限成功:$success');
_logger.logWithLevel('✅ [RemoteControl] 请求控制权限成功:$success',shouldLog: true);
///处理result
if(success){
emit(state.copyWith(hasPermission: true));
}else{
emit(state.copyWith(hasPermission: false));
}
print('✅ c:$success');
// 权限申请已发送,等待 0x12 回包更新状态
(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,
);
// 🔥 关键逻辑: 如果没有权限 或owner为null,则发送TCP 请求
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));
}
}
},
);
debugPrint(
'${_getTimePrefix()} 🔑 [RemoteControl] [请求权限接口-$source] =========================================',
);
}
/// 发送底盘指令
/// 🔥 权限弹窗确认后调用- 发送TCP响应 + HTTP确认最终权限状态
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}');
// // debugPrint('>>> [底盘指令] ${i}');
// _logger.logWithLevel('>>> [底盘指令] ${i}');
updateFunction(lift: i);
}
/// 发送割刀指令
/// 发送割刀指令
void sendMowerCommand(int i) {
// debugPrint(' [割刀指令] ${i}');
_logger.logWithLevel(' [割刀指令] ${i}');
// // debugPrint('>>> [割刀指令] ${i}');
// _logger.logWithLevel('>>> [割刀指令] ${i}');
updateFunction(mower: i);
}
/// 发送点火指令
/// 发送点火指令
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(mower:0, lift: 0, ignition: i, emergency: false);
// debugPrint('>>> [点火指令] ${i}');
// _logger.logWithLevel('>>> [点火指令] ${i}');
updateFunction(ignition: i);
}
// 发送障碍物识别指令
// 发送障碍物识别指令
void toggleObstacleRecognition() {
emit(state.copyWith(obstacleRecognitionFlag: !state.obstacleRecognitionFlag));
emit(
state.copyWith(obstacleRecognitionFlag: !state.obstacleRecognitionFlag),
);
}
void toggleTopLeftExpand() {
@@ -498,14 +781,14 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
Future<int> getNetworkDelay() async {
try {
// 直接 Ping 你的服务器 IP
// 直接 Ping 你的服务器IP
final ping = Ping('1.95.137.212', count: 1, timeout: 1);
// 等待一次结果
final data = await ping.stream.first;
if (data.response != null && data.response!.time != null) {
// 返回和 cmd 一样的毫秒值
// 返回和cmd 一样的毫秒值
return data.response!.time!.inMilliseconds;
} else {
return 9999;
@@ -514,14 +797,38 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
return 9999;
}
}
//app退出远程遥控界面释放权限
//app退出远程遥控界面释放权限
Future<bool> releasePermission(String platform) async {
return await _repository.releasePermission(platform);
}
/// 🔥 设置待控制的设备(从机器人列表点击进入时调用)
void setTargetDevice(DeviceEntity device) {
// debugPrint('🎯 [RemoteControl] 设置待控制设备 ${device.deviceName}');
// _logger.logWithLevel('🎯 [RemoteControl] 设置待控制设备 ${device.deviceName}');
// 🔥 通知后端订阅该设备
_deviceRepository.switchDevice("app", device.deviceName).then((result) {
result.fold(
(failure) {
// debugPrint('>>> [RemoteControl] 切换设备失败: ${failure.message}');
// _logger.logWithLevel('>>> [RemoteControl] 切换设备失败: ${failure.message}');
},
(success) {
// debugPrint('>>> [RemoteControl] 切换设备成功, code: $success');
// _logger.logWithLevel('>>> [RemoteControl] 切换设备成功, code: $success');
},
);
});
emit(state.copyWith(targetDevice: device));
}
/// 🔥 清除待控制设备(退出远程控制页时调用)
void clearTargetDevice() {
// debugPrint('🧹 [RemoteControl] 清除待控制设备');
// _logger.logWithLevel('🧹 [RemoteControl] 清除待控制设备');
emit(state.copyWith(targetDevice: null));
}
}

View File

@@ -1,19 +1,16 @@
import 'package:equatable/equatable.dart';
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
import 'package:maibu_satabot_v2/features/remote_control/data/models/running_status_model.dart';
import '../../domain/entities/machine_control_status_entity.dart';
enum RemoteControlStatus { initial, controlling, error }
enum ControlMode { TCP, BLE, LOCAL, NONE, OTHER }
class RemoteControlState extends Equatable {
final RemoteControlStatus status;
final MachineControlStatusEntity controlEntity; // 控制业务实体
final RunningStatusModel runningStatusModel;
//状态业务实体
final String? errorMessage;
final bool hasPermission; // 是否获得了 0x12 权限
final bool hasPermission; // 是否获得 0x12 权限
final bool isEmergency;
final bool isLocked;
final int ping;
@@ -22,6 +19,8 @@ class RemoteControlState extends Equatable {
final String permissionPlatform;
final String currentPlatform;
final bool showPermissionRequestDialog;
final String? requestingDeviceId; // 🔥 请求权限的设备ID
final String? requestingPlatform; // 🔥 请求权限的平台
final bool showLeftPip;
final bool showRightPip;
@@ -29,6 +28,8 @@ class RemoteControlState extends Equatable {
final bool obstacleRecognitionFlag; // 障碍物识别标志位(这是UI显示的)
final String obstacleFlag; //障碍物标志位
final DeviceEntity? targetDevice; // 🔥 待控制的设备
final RunningStatusModel runningStatusModel;
const RemoteControlState({
this.status = RemoteControlStatus.initial,
@@ -43,15 +44,18 @@ class RemoteControlState extends Equatable {
this.permissionPlatform = '',
this.currentPlatform = '',
this.showPermissionRequestDialog = false,
this.requestingDeviceId,
this.requestingPlatform,
this.showLeftPip = true,
this.showRightPip = true,
this.obstacleFlag = '',
required this.runningStatusModel,
this.topRightIsExpanded = false,
this.obstacleRecognitionFlag = true,
this.targetDevice,
});
// 方便 UI 更新部分属性
// 便利 UI 更新部分属性
RemoteControlState copyWith({
RemoteControlStatus? status,
MachineControlStatusEntity? controlEntity,
@@ -65,12 +69,15 @@ class RemoteControlState extends Equatable {
String? permissionPlatform,
String? currentPlatform,
bool? showPermissionRequestDialog,
String? requestingDeviceId,
String? requestingPlatform,
bool? showLeftPip,
bool? showRightPip,
RunningStatusModel? runningStatusModel,
String? obstacleFlag,
bool? topRightIsExpanded,
bool? obstacleRecognitionFlag,
DeviceEntity? targetDevice,
}) {
return RemoteControlState(
@@ -87,12 +94,15 @@ class RemoteControlState extends Equatable {
currentPlatform: currentPlatform ?? this.currentPlatform,
showPermissionRequestDialog:
showPermissionRequestDialog ?? this.showPermissionRequestDialog,
requestingDeviceId: requestingDeviceId ?? this.requestingDeviceId,
requestingPlatform: requestingPlatform ?? this.requestingPlatform,
showLeftPip: showLeftPip ?? this.showLeftPip,
showRightPip: showRightPip ?? this.showRightPip,
runningStatusModel: runningStatusModel ?? this.runningStatusModel,
obstacleFlag: obstacleFlag ?? this.obstacleFlag,
topRightIsExpanded: topRightIsExpanded ?? this.topRightIsExpanded,
obstacleRecognitionFlag: obstacleRecognitionFlag ?? this.obstacleRecognitionFlag,
targetDevice: targetDevice ?? this.targetDevice,
);
}
@@ -111,14 +121,17 @@ class RemoteControlState extends Equatable {
permissionPlatform,
currentPlatform,
showPermissionRequestDialog,
requestingDeviceId,
requestingPlatform,
showLeftPip,
showRightPip,
runningStatusModel,
obstacleFlag,
topRightIsExpanded,
obstacleRecognitionFlag,
targetDevice,
];
}
}

View File

@@ -0,0 +1,27 @@
class RunningStatusModel {
final String controlMode;
final String voltage;
final String deviceName;
final String deviceId;
const RunningStatusModel({
this.controlMode = '',
this.voltage = '0',
this.deviceName = '',
this.deviceId = '',
});
RunningStatusModel copyWith({
String? controlMode,
String? voltage,
String? deviceName,
String? deviceId,
}) {
return RunningStatusModel(
controlMode: controlMode ?? this.controlMode,
voltage: voltage ?? this.voltage,
deviceName: deviceName ?? this.deviceName,
deviceId: deviceId ?? this.deviceId,
);
}
}

View File

@@ -9,6 +9,7 @@ import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import '../../../../core/app/app_user_cubit.dart';
import '../../../../core/router/route_paths.dart';
import '../../../devices/domain/entities/device_entity.dart';
import '../../../devices/presentation/bloc/devices_cubit.dart';
import '../bloc/remote_control_cubit.dart';
import '../bloc/remote_control_state.dart';
@@ -30,40 +31,79 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
String _videoStreamUrl = "";
late RemoteControlCubit _cubit;
DevicesCubit? _devicesCubit;
StreamSubscription? _permissionSubscription; // 🔥 权限监听订阅
bool _isShowingPermissionDialog = false; // 🔥 防止弹窗重复显示
bool _isLoadingPermission = true; // 🔥 标记是否正在加载权限状态
@override
void didChangeDependencies() {
super.didChangeDependencies();
_cubit = context.read<RemoteControlCubit>();
_devicesCubit = context.read<DevicesCubit>();
// 🔥 监听权限弹窗状态变化 (只订阅一次)
if (_permissionSubscription == null) {
_permissionSubscription = _cubit.stream.listen((state) {
// 🔥 加强防重复逻辑:只在状态真正变化且不在显示弹窗时才显示
if (mounted &&
state.showPermissionRequestDialog &&
!_isShowingPermissionDialog) {
_isShowingPermissionDialog = true;
debugPrint('🔔 [权限弹窗] 检测到 showPermissionRequestDialog=true,准备显示弹窗');
// 使用微任务确保标志位已设置
Future.microtask(() {
_showPermissionDialog(state).then((_) {
debugPrint('🔔 [权限弹窗] 弹窗已关闭,重置标志位');
_isShowingPermissionDialog = false; // 弹窗关闭后重置标志
});
});
}
});
}
}
@override
void initState() {
super.initState();
// 1. 锁定横屏
SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
// 2. 隐藏状态栏和虚拟按键
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
WidgetsBinding.instance.addPostFrameCallback((_) {
final remoteCubit = context.read<RemoteControlCubit>();
final devicesCubit = context.read<DevicesCubit>();
// debugPrint('🔍 [RemoteControl] initState - targetDevice: ${remoteCubit.state.targetDevice}');
// 🔥 检查 targetDevice 是否存在
if (remoteCubit.state.targetDevice == null) {
// debugPrint('❌ [RemoteControl] targetDevice 为空,无法进入远程控制');
return;
}
// 🔥 弹窗显示当前控制的设备信息
_showTargetDeviceDialog(context, remoteCubit.state.targetDevice!);
// 🔥 只在控制循环未启动时才启动
remoteCubit.startControlLoop();
// debugPrint('✅ [RemoteControl] 控制循环已启动');
});
}
@override
void dispose() {
// 释放远程控制权限
// _cubit.releasePermission("app");
_cubit.releasePermission("app");
//print("远程控制要推出啦");
final deviceState = _devicesCubit?.state;
if (deviceState?.selectedDevice != null) {
// _cubit.releasePermission("app");
}
//final deviceState = _devicesCubit?.state;
//if (deviceState?.selectedDevice != null) {
// _cubit.releasePermission("app");
// }
_permissionSubscription?.cancel(); // 🔥 取消订阅
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
_cubit.stopControlLoop();
@@ -77,12 +117,36 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
final deviceState = context.watch<DevicesCubit>().state;
final currentDevice = deviceState.selectedDevice;
final remoteCubit = context.read<RemoteControlCubit>();
final hasPermission = remoteCubit.state.hasPermission;
///context.read<RemoteControlCubit>().requestControlPermissionS(currentDevice!.deviceName, "app");
if (currentDevice == null) {
return _buildOfflineScaffold();
}
context.read<RemoteControlCubit>().requestControlPermissionS(currentDevice!.deviceName, "app");
// 🔥 只在没有权限时自动请求,避免重复调用
if (!hasPermission && _isLoadingPermission) {
// 🔥 只使用 targetDevice
final deviceName = remoteCubit.state.targetDevice?.deviceName;
if (deviceName != null && deviceName.isNotEmpty) {
// debugPrint('🔑 [RemoteControl] 检测到无权限,自动发送权限请求 - deviceName: $deviceName');
setState(() => _isLoadingPermission = false); // 🔥 标记为已请求
remoteCubit.requestControlPermissionS(deviceName, "app").then((_) {
if (mounted) {
setState(() => _isLoadingPermission = false); // 🔥 请求完成后重置
}
});
} else {
// debugPrint('❌ [RemoteControl] 无法发送权限请求 - targetDevice 为空');
// debugPrint(' targetDevice: ${remoteCubit.state.targetDevice}');
setState(() => _isLoadingPermission = false);
}
} else {
// debugPrint('✅ [RemoteControl] 已有权限或已请求过,跳过');
}
return Scaffold(
backgroundColor: Colors.black,
@@ -92,24 +156,50 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
Positioned.fill(
child: BlocBuilder<RemoteControlCubit, RemoteControlState>(
// 只有当显示隐藏状态改变时才重构,内部的拖拽由组件自身 State 处理,不影响这里
buildWhen: (p, c) => p.showLeftPip != c.showLeftPip || p.showRightPip != c.showRightPip,
buildWhen: (p, c) =>
p.showLeftPip != c.showLeftPip ||
p.showRightPip != c.showRightPip,
builder: (context, state) {
final deviceId = context.watch<DevicesCubit>().state.selectedDevice?.deviceName;
if (deviceId != null && userState.user != null && userState.user!.token != null) {
_videoStreamUrl = "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=${userState.user!.token}";
// 🔥 只从 targetDevice 获取 deviceId
final targetDevice = context
.watch<RemoteControlCubit>()
.state
.targetDevice;
final deviceId = targetDevice?.deviceName;
// debugPrint('🔍 [WebRTC检查] targetDevice: $targetDevice, deviceId: $deviceId');
// debugPrint('🔍 [WebRTC检查] user: ${userState.user != null}, token: ${userState.user?.token != null}');
if (deviceId != null &&
userState.user != null &&
userState.user!.token != null) {
_videoStreamUrl =
"webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=${userState.user!.token}";
// debugPrint('🎬 [WebRTC] URL构建成功: $_videoStreamUrl');
} else {
_videoStreamUrl = '';
// debugPrint('❌ [WebRTC] URL构建失败 - deviceId: $deviceId, hasUser: ${userState.user != null}, hasToken: ${userState.user?.token != null}');
}
final int originY = context.watch<RemoteControlCubit>().state.controlEntity.originY;
debugPrint("${originY},originY");
final int originY = context
.watch<RemoteControlCubit>()
.state
.controlEntity
.originY;
// debugPrint("${originY},originY");
return WebRTCLocalPlayer(
// 这里的 URL 拼接根据你的后端规则
// streamUrl: "webrtc://${TCPConsts.TCP_IP}/live/livestream/${currentDevice.deviceName}?token=${userState.user!.token}",
streamUrl: _videoStreamUrl,
showLeftPip: state.showLeftPip, // 从 Cubit 状态中读取
showRightPip: state.showRightPip, // 从 Cubit 状态中读取
isFrontMain: context.watch<RemoteControlCubit>().state.controlEntity.originY >= 0,
isFrontMain:
context
.watch<RemoteControlCubit>()
.state
.controlEntity
.originY >=
0,
);
},
),
@@ -118,14 +208,44 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
BlocBuilder<RemoteControlCubit, RemoteControlState>(
buildWhen: (p, c) => p.isEmergency != c.isEmergency,
builder: (context, state) {
return state.isEmergency ? const Positioned.fill(child: EmergencyOverlay()) : const SizedBox.shrink();
return state.isEmergency
? const Positioned.fill(child: EmergencyOverlay())
: const SizedBox.shrink();
},
),
SafeArea(
child: Column(
children: [
const TopStatusBar(),
// 🔥 用 BlocConsumer 包裹,确保 hasPermission 变化时重建
BlocConsumer<RemoteControlCubit, RemoteControlState>(
listenWhen: (p, c) => p.hasPermission != c.hasPermission,
listener: (context, state) {
debugPrint(
'🔍 [RemoteControlPage] BlocConsumer listener - hasPermission=${state.hasPermission}',
);
},
buildWhen: (p, c) =>
p.hasPermission != c.hasPermission ||
p.isLocked != c.isLocked ||
p.topRightIsExpanded != c.topRightIsExpanded ||
p.obstacleRecognitionFlag != c.obstacleRecognitionFlag ||
p.showLeftPip != c.showLeftPip ||
p.showRightPip != c.showRightPip ||
p.ping != c.ping ||
p.runningStatusModel.voltage !=
c.runningStatusModel.voltage ||
p.runningStatusModel.controlMode !=
c.runningStatusModel.controlMode ||
p.battery != c.battery,
builder: (context, state) {
// 🔥 调试日志:确认 BlocBuilder 接收到的状态值
/* debugPrint(
'🔍 [RemoteControlPage] BlocConsumer builder - hasPermission=${state.hasPermission}',
);*/
return TopStatusBar(remoteState: state);
},
),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
@@ -133,7 +253,10 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
final double centerAreaWidth = constraints.maxWidth * 0.5;
// 关键:使用 BlocBuilder 局部刷新摇杆,不要 watch 整个 Page
return BlocBuilder<RemoteControlCubit, RemoteControlState>(
return BlocBuilder<
RemoteControlCubit,
RemoteControlState
>(
// 只有 isLocked 改变时才重构摇杆区域,摇杆坐标改变由内部处理
buildWhen: (p, c) => p.isLocked != c.isLocked,
builder: (context, remoteState) {
@@ -148,7 +271,10 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
width: sideAreaWidth,
child: Align(
alignment: Alignment.bottomCenter,
child: LeftJoystickArea(isLocked: remoteState.isLocked, width: sideAreaWidth * 0.45),
child: LeftJoystickArea(
isLocked: remoteState.isLocked,
width: sideAreaWidth * 0.45,
),
),
),
@@ -157,7 +283,9 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
width: centerAreaWidth,
child: Align(
alignment: Alignment.bottomCenter,
child: CenterControlArea(totalWidth: centerAreaWidth),
child: CenterControlArea(
totalWidth: centerAreaWidth,
),
),
),
@@ -166,7 +294,10 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
width: sideAreaWidth,
child: Align(
alignment: Alignment.bottomCenter,
child: RightJoystickArea(isLocked: remoteState.isLocked, width: sideAreaWidth * 0.45),
child: RightJoystickArea(
isLocked: remoteState.isLocked,
width: sideAreaWidth * 0.45,
),
),
),
],
@@ -180,15 +311,152 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
],
),
),
// 权限弹窗
BlocBuilder<RemoteControlCubit, RemoteControlState>(
buildWhen: (p, c) => p.showPermissionRequestDialog != c.showPermissionRequestDialog,
builder: (context, state) {
if (state.showPermissionRequestDialog) {
return _buildPermissionDialog(context, state);
],
),
);
}
// 🔥 显示权限请求弹窗 (使用 showDialog 替代 Overlay)
Future<void> _showPermissionDialog(RemoteControlState state) async {
debugPrint('🔔 [权限弹窗] _showPermissionDialog 被调用');
final requestingDeviceId = state.requestingDeviceId ?? '未知设备';
final requestingPlatform = state.requestingPlatform ?? '未知平台';
final dialogContent =
'$requestingPlatform 端正在请求控制权\n\n'
'设备ID: $requestingDeviceId\n\n'
'是否同意释放控制权?';
debugPrint(
'🔔 [权限弹窗] 准备显示弹窗 - requestingPlatform=$requestingPlatform, requestingDeviceId=$requestingDeviceId',
);
showDialog(
context: context,
barrierDismissible: false, // 禁止点击外部关闭
builder: (dialogContext) => AlertDialog(
title: Text(
AppLocalizations.of(
dialogContext,
).translate('remote_control.permission_request_title'),
),
content: Text(dialogContent),
actions: [
TextButton(
onPressed: () async {
// debugPrint('👆 [权限弹窗] 用户点击了拒绝按钮');
final deviceId =
context
.read<DevicesCubit>()
.state
.selectedDevice
?.deviceName ??
"";
final remoteCubit = context.read<RemoteControlCubit>();
// 🔥 添加详细状态日志 - 检查为什么TCP指令发不出去
// debugPrint('👆 [权限弹窗] ====================状态检查====================');
// debugPrint('👆 [权限弹窗] showPermissionRequestDialog: ${remoteCubit.state.showPermissionRequestDialog}');
// debugPrint('👆 [权限弹窗] targetDevice: ${remoteCubit.state.targetDevice}');
// debugPrint('👆 [权限弹窗] requestingDeviceId: ${remoteCubit.state.requestingDeviceId}');
// debugPrint('👆 [权限弹窗] hasPermission: ${remoteCubit.state.hasPermission}');
// debugPrint('👆 [权限弹窗] ==============================================');
/* debugPrint(
'📋 [权限弹窗] targetDevice=${remoteCubit.state.targetDevice}',
);*/
// 🔥 先发送 TCP 响应,等完成后再关闭弹窗
// debugPrint('🔑 [权限弹窗] 用户拒绝,调用 confirmPermissionResponse');
final targetDevice = remoteCubit.state.targetDevice;
if (targetDevice != null) {
debugPrint(
'✅ [权限弹窗] targetDevice 不为空,开始调用 confirmPermissionResponse',
);
await remoteCubit.confirmPermissionResponse(
targetDevice.deviceName,
'app',
false,
);
// debugPrint('✅ [权限弹窗] TCP响应已发送,准备关闭弹窗');
} else {
debugPrint(
'❌ [权限弹窗] targetDevice 为空,无法调用 confirmPermissionResponse',
);
}
return const SizedBox.shrink();
// 🔥 关闭弹窗(在 TCP 发送完成后)
Navigator.pop(dialogContext);
},
child: Text(
AppLocalizations.of(
dialogContext,
).translate('remote_control.refuse'),
),
),
TextButton(
onPressed: () async {
debugPrint('👆 [权限弹窗] 用户点击了同意按钮');
final deviceId =
context
.read<DevicesCubit>()
.state
.selectedDevice
?.deviceName ??
"";
final remoteCubit = context.read<RemoteControlCubit>();
// 🔥 添加详细状态日志 - 检查为什么TCP指令发不出去
/* debugPrint(
'👆 [权限弹窗] ====================状态检查====================',
);
debugPrint(
'👆 [权限弹窗] showPermissionRequestDialog: ${remoteCubit.state.showPermissionRequestDialog}',
);
debugPrint(
'👆 [权限弹窗] targetDevice: ${remoteCubit.state.targetDevice}',
);
debugPrint(
'👆 [权限弹窗] requestingDeviceId: ${remoteCubit.state.requestingDeviceId}',
);
debugPrint(
'👆 [权限弹窗] hasPermission: ${remoteCubit.state.hasPermission}',
);
debugPrint(
'👆 [权限弹窗] ==============================================',
);
debugPrint(
'📋 [权限弹窗] targetDevice=${remoteCubit.state.targetDevice}',
);*/
// 🔥 先发送 TCP 响应,等完成后再关闭弹窗
debugPrint('🔑 [权限弹窗] 用户同意,调用 confirmPermissionResponse');
final targetDevice = remoteCubit.state.targetDevice;
if (targetDevice != null) {
debugPrint(
'✅ [权限弹窗] targetDevice 不为空',
);
await remoteCubit.confirmPermissionResponse(
targetDevice.deviceName,
'app',
true,
);
debugPrint('✅ [权限弹窗] TCP响应已发送,准备关闭弹窗');
} else {
debugPrint(
'❌ [权限弹窗] targetDevice 为空,无法调用 confirmPermissionResponse',
);
}
// 🔥 关闭弹窗(在 TCP 发送完成后)
Navigator.pop(dialogContext);
},
child: Text(
AppLocalizations.of(
dialogContext,
).translate('remote_control.agree'),
),
),
],
),
@@ -204,36 +472,51 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
children: [
const Icon(Icons.signal_wifi_off, color: Colors.white, size: 60),
const SizedBox(height: 20),
Text(AppLocalizations.of(context).translate('remote_control.device_disconnected'), style: const TextStyle(color: Colors.white, fontSize: 18)),
Text(
AppLocalizations.of(
context,
).translate('remote_control.device_disconnected'),
style: const TextStyle(color: Colors.white, fontSize: 18),
),
const SizedBox(height: 20),
ElevatedButton(onPressed: () => context.pop(), child: Text(AppLocalizations.of(context).translate('remote_control.back'))),
ElevatedButton(
onPressed: () => context.pop(),
child: Text(
AppLocalizations.of(context).translate('remote_control.back'),
),
),
],
),
),
);
}
Widget _buildPermissionDialog(BuildContext context, RemoteControlState state) {
final deviceId = context.read<DevicesCubit>().state.selectedDevice?.deviceName ?? "";
return Container(
color: Colors.black54,
child: AlertDialog(
title: Text(AppLocalizations.of(context).translate('remote_control.permission_request_title')),
// content: Text("${state.permissionPlatform}端正请求控制权,同意释放吗?"),
content: Text(AppLocalizations.of(context).translate('remote_control.permission_request_content')),
/// 🔥 显示当前控制设备的弹窗
void _showTargetDeviceDialog(BuildContext context, DeviceEntity device) {
showDialog(
context: context,
barrierDismissible: true,
builder: (ctx) => AlertDialog(
title: const Text('🎮 远程控制'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'设备名称: ${device.deviceName}',
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 8),
Text(
'设备ID: ${device.deviceName}',
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
],
),
actions: [
TextButton(onPressed: () => context.read<RemoteControlCubit>().respondPermission(false, deviceId), child: Text(AppLocalizations.of(context).translate('remote_control.refuse'))),
TextButton(
onPressed: () {
context.read<RemoteControlCubit>().respondPermission(true, deviceId);
// 🔥 用户同意,延迟跳转到首页
// Future.delayed(const Duration(milliseconds: 1000), () {
// if (context.mounted) {
// context.go(RoutePaths.home);
// }
// });
},
child: Text(AppLocalizations.of(context).translate('remote_control.agree')),
onPressed: () => Navigator.pop(ctx),
child: const Text('确定'),
),
],
),

View File

@@ -3,24 +3,44 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/control_mode.dart';
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart';
import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/status_chip.dart';
import 'package:cc_ui_kit/cc_ui_kit.dart';
import '../../../../core/di/injection.dart';
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 '../bloc/remote_control_cubit.dart';
class TopStatusBar extends StatelessWidget {
const TopStatusBar({super.key});
/// 🔥 从父组件传入状态,不依赖 context.watch
final RemoteControlState remoteState;
const TopStatusBar({super.key, required this.remoteState});
@override
Widget build(BuildContext context) {
// 监听全局设备状态
final deviceState = context.watch<DevicesCubit>().state;
final device = deviceState.selectedDevice;
// 🔥 添加调试日志:确认接收到的状态值
//debugPrint('🔍 [TopStatusBar] build - isLocked=${remoteState.isLocked}');
// 监听全局设备状态 (DevicesCubit 需要 watch,因为设备选择可能变化)
// 🔥 使用 try-catch 保护,防止 BlocProvider 缺失导致整个 widget 树崩溃(白屏)
DeviceEntity? device;
try {
final deviceState = context.watch<DevicesCubit>().state;
device = deviceState.selectedDevice;
} catch (e) {
debugPrint('⚠️ [TopStatusBar] 读取 DevicesCubit 失败: $e');
// DevicesCubit 不可用时使用 targetDevice 作为降级方案
try {
device = context.read<RemoteControlCubit>().state.targetDevice;
} catch (e2) {
debugPrint('⚠️ [TopStatusBar] 读取 targetDevice 也失败: $e2');
}
}
var _remoteControlCubit = context.read<RemoteControlCubit>();
ControlMode _parseControlMode(String modeString) {
switch (modeString.toUpperCase()) {
@@ -39,124 +59,171 @@ class TopStatusBar extends StatelessWidget {
}
}
// 监听局部遥控状态
final remoteState = context.watch<RemoteControlCubit>().state;
return Padding(
padding: const EdgeInsets.fromLTRB(1, 12, 1, 12),
child: Row(
children: [
// 1. 返回按钮 (对应 SimpleSmallFunctionButton)
_buildIconButton("assets/svgs/remote_back.svg", () => context.pop()),
const SizedBox(width: 8),
child: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// 1. 返回按钮 (对应 SimpleSmallFunctionButton)
_buildIconButton("assets/svgs/remote_back.svg", () {
// 🔥 兼容两种导航栈:GoRouter 和 Navigator
if (Navigator.of(context).canPop()) {
Navigator.of(context).pop();
} else {
context.pop();
}
}),
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) {
// 弹出请求权限对话框逻辑
context.read<RemoteControlCubit>().togglePermissionDialog(true);
}
},
),
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) {
// 🔥 点击后重新请求权限,和刚进入页面时的逻辑一致
debugPrint('🔑 [TopStatusBar] 👆 用户手动点击“未在控制”,重新请求权限');
final targetDevice =
_remoteControlCubit.state.targetDevice;
if (targetDevice != null) {
_remoteControlCubit.requestControlPermissionS(
targetDevice.deviceName,
'app',
source: '手动点击',
);
} else {
debugPrint('❌ [TopStatusBar] targetDevice 为空,无法请求权限');
}
}
},
),
const SizedBox(width: 8),
// 3. 锁定状态 (对应 SmallFunctionButton)
_buildIconButton(
remoteState.isLocked
? "assets/svgs/remote_lock.svg"
: "assets/svgs/remote_lock_open.svg",
() => context.read<RemoteControlCubit>().toggleLock(),
isSelected: remoteState.isLocked,
),
const SizedBox(width: 8),
// 3. 锁定状态 (对应 SmallFunctionButton)
_buildIconButton(
remoteState.isLocked
? "assets/svgs/remote_lock.svg"
: "assets/svgs/remote_lock_open.svg",
() => context.read<RemoteControlCubit>().toggleLock(),
isSelected: remoteState.isLocked,
),
const SizedBox(width: 8),
// 4. 刷新按钮
_buildIconButton("assets/svgs/remote_refresh.svg", () {}),
// const SizedBox(width: 8),
// 5. 火技能按钮 (对应 SmallFunctionButton)
//_buildIconButton("assets/svgs/fire.svg", () {}),
_buildSliderBox(AppLocalizations.of(context).translate('remote_control.fire_skill'), false,context),
// 4. 刷新按钮
_buildIconButton("assets/svgs/remote_refresh.svg", () {}),
// const SizedBox(width: 8),
// 5. 火技能按钮 (对应 SmallFunctionButton)
//_buildIconButton("assets/svgs/fire.svg", () {}),
_buildSliderBox(
AppLocalizations.of(
context,
).translate('remote_control.fire_skill'),
false,
context,
),
// const Spacer(), // 移除 Spacer,改用 MainAxisAlignment.spaceBetween
_buildExpandIconButton(
iconPath: "assets/svgs/remote_expand.svg",
selectedIconPath: "assets/svgs/remote_unexpand.svg",
isSelected: remoteState.topRightIsExpanded,
onTap: () {
_remoteControlCubit.toggleTopLeftExpand();
},
),
const Spacer(),
_buildExpandIconButton(
iconPath: "assets/svgs/remote_expand.svg",
selectedIconPath: "assets/svgs/remote_unexpand.svg",
isSelected: remoteState.topRightIsExpanded,
onTap: (){
_remoteControlCubit.toggleTopLeftExpand();
},
),
AnimatedSize(
duration: const Duration(milliseconds: 100),
curve: Curves.easeInOut,
child: Row(
children: !remoteState.topRightIsExpanded
? [
const SizedBox(width: 8),
_buildSwitchIconButton(
iconPath:
"assets/svgs/remote_recognition_off.svg",
selectedIconPath:
"assets/svgs/remote_recognition_on.svg",
isSelected: remoteState.obstacleRecognitionFlag,
onTap: () {
_remoteControlCubit
.toggleObstacleRecognition();
},
),
const SizedBox(width: 8),
_buildSwitchIconButton(
iconPath:
"assets/svgs/remote_video_left_off.svg",
selectedIconPath:
"assets/svgs/remote_video_left.svg",
isSelected: remoteState.showLeftPip,
onTap: () {
_remoteControlCubit.toggleLeftPip();
},
),
const SizedBox(width: 8),
_buildSwitchIconButton(
iconPath:
"assets/svgs/remote_video_right_off.svg",
selectedIconPath:
"assets/svgs/remote_video_right.svg",
isSelected: remoteState.showRightPip,
onTap: () {
_remoteControlCubit.toggleRightPip();
},
),
const SizedBox(width: 8),
_buildControlModeChip(
remoteState.runningStatusModel.controlMode,
context,
),
const SizedBox(width: 8),
_buildVoltageChip(
remoteState.runningStatusModel.voltage,
),
const SizedBox(width: 8),
_buildPingChip(remoteState.ping),
const SizedBox(width: 8),
]
: [], // 折叠时数组为空
),
),
// TODO
// _buildControlModeChip( _parseControlMode(remoteState.runningStatusModel.controlMode)),
AnimatedSize(
duration: const Duration(milliseconds: 100),
curve: Curves.easeInOut,
child: Row(
children: !remoteState.topRightIsExpanded
? [
const SizedBox(width: 8),
_buildSwitchIconButton(
iconPath: "assets/svgs/remote_recognition_off.svg",
selectedIconPath: "assets/svgs/remote_recognition_on.svg",
isSelected: remoteState.obstacleRecognitionFlag,
onTap: (){
_remoteControlCubit.toggleObstacleRecognition();
},
),
const SizedBox(width: 8),
_buildSwitchIconButton(
iconPath: "assets/svgs/remote_video_left_off.svg",
selectedIconPath: "assets/svgs/remote_video_left.svg",
isSelected: remoteState.showLeftPip,
onTap: (){
_remoteControlCubit.toggleLeftPip();
},
),
const SizedBox(width: 8),
_buildSwitchIconButton(
iconPath: "assets/svgs/remote_video_right_off.svg",
selectedIconPath: "assets/svgs/remote_video_right.svg",
isSelected: remoteState.showRightPip,
onTap: (){
_remoteControlCubit.toggleRightPip();
},
),
const SizedBox(width: 8),
_buildControlModeChip(remoteState.runningStatusModel.controlMode, context),
const SizedBox(width: 8),
_buildVoltageChip(remoteState.runningStatusModel.voltage),
const SizedBox(width: 8),
_buildPingChip(remoteState.ping),
const SizedBox(width: 8),
]
: [], // 折叠时数组为空
// const SizedBox(width: 8),
//_buildVoltageChip(remoteState.voltage),
// const SizedBox(width: 8),
// 5. 信号延迟 (对应 pingStatusChip)
//_buildPingChip(remoteState.ping),
// const SizedBox(width: 8),
// 6. 电量 (对应 StatusChipRight)
_buildBatteryChip(remoteState.battery),
const SizedBox(width: 8),
],
),
),
),
// TODO
// _buildControlModeChip( _parseControlMode(remoteState.runningStatusModel.controlMode)),
// const SizedBox(width: 8),
//_buildVoltageChip(remoteState.voltage),
// const SizedBox(width: 8),
// 5. 信号延迟 (对应 pingStatusChip)
//_buildPingChip(remoteState.ping),
// const SizedBox(width: 8),
// 6. 电量 (对应 StatusChipRight)
_buildBatteryChip(remoteState.battery),
const SizedBox(width: 8),
],
);
},
),
);
}
@@ -218,12 +285,12 @@ class TopStatusBar extends StatelessWidget {
),
boxShadow: isSelected
? [
BoxShadow(
color: const Color(0xFF0078D4).withOpacity(0.4),
blurRadius: 8,
offset: const Offset(0, 2),
),
]
BoxShadow(
color: const Color(0xFF0078D4).withOpacity(0.4),
blurRadius: 8,
offset: const Offset(0, 2),
),
]
: null,
),
padding: const EdgeInsets.all(7),
@@ -250,9 +317,11 @@ class TopStatusBar extends StatelessWidget {
Widget _buildControlModeChip(String mode, BuildContext context) {
String displayText;
if(mode == ''){
displayText = AppLocalizations.of(context).translate('remote_control.mode_none');
}else{
if (mode == '') {
displayText = AppLocalizations.of(
context,
).translate('remote_control.mode_none');
} else {
displayText = mode;
}
// switch (mode) {
@@ -302,10 +371,7 @@ class TopStatusBar extends StatelessWidget {
// 选中时为深蓝色,未选中时为半透明灰色
color: Colors.grey.withOpacity(0.4),
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: Colors.white.withOpacity(0.3),
width: 0.5,
),
border: Border.all(color: Colors.white.withOpacity(0.3), width: 0.5),
boxShadow: null,
),
padding: const EdgeInsets.all(7),
@@ -318,7 +384,6 @@ class TopStatusBar extends StatelessWidget {
);
}
Widget _buildVoltageChip(String voltage) {
return StatusChip(
text: "$voltage V",
@@ -363,9 +428,9 @@ class TopStatusBar extends StatelessWidget {
Widget _buildSliderBox(String label, bool isLeft, BuildContext context) {
// 1. 核心尺寸调整:足够宽的容器解决拥挤,高度匹配状态栏
const double boxWidth = 66; // 水平宽度放大,容纳左右图标
const double boxHeight = 32; // 高度和其他按钮保持一致
const double iconSize = 20; // 图标尺寸放大,避免过小拥挤
const double boxWidth = 66; // 水平宽度放大,容纳左右图标
const double boxHeight = 32; // 高度和其他按钮保持一致
const double iconSize = 20; // 图标尺寸放大,避免过小拥挤
return SizedBox(
width: boxWidth,
@@ -376,26 +441,37 @@ class TopStatusBar extends StatelessWidget {
quarterTurns: 1, // 旋转90度(竖向→横向),若方向反了可改为3
child: SizedBox(
// 旋转后宽高互换,这里给CCExpandSlider足够的显示空间
width: boxHeight, // 旋转后对应原高度
height: boxWidth, // 旋转后对应原宽度(足够长,不拥挤)
width: boxHeight, // 旋转后对应原高度
height: boxWidth, // 旋转后对应原宽度(足够长,不拥挤)
child: CCExpandSlider(
label: " ",
// 3. 图标适配旋转后的方向(仍用上下箭头,旋转后变为左右)因为外边旋转了 90度 参数传递也要转换
svgStart: "assets/svgs/remote_flame_plus.svg", // 旋转后→左箭头assets/svgs/remote_flame_minus.svg
svgStart:
"assets/svgs/remote_flame_plus.svg", // 旋转后→左箭头assets/svgs/remote_flame_minus.svg
svgCenter: "assets/svgs/remote_flame.svg",
svgEnd: "assets/svgs/remote_flame_minus.svg", // 旋转后→右箭头assets/svgs/remote_flame_plus.svg
svgEnd:
"assets/svgs/remote_flame_minus.svg", // 旋转后→右箭头assets/svgs/remote_flame_plus.svg
// 4. 放大图标尺寸,解决拥挤
iconSize: iconSize,
// 保留原有业务逻辑
onStart: () =>_handleSliderAction(label, "end", context),//_handleSliderAction(label, "start", context)
onStart: () => _handleSliderAction(
label,
"end",
context,
), //_handleSliderAction(label, "start", context)
onCenter: () => _handleSliderAction(label, "center", context),
onEnd: () => _handleSliderAction(label, "start", context),//_handleSliderAction(label, "end", context)
onEnd: () => _handleSliderAction(
label,
"start",
context,
), //_handleSliderAction(label, "end", context)
),
),
),
),
);
}
// 🔥 新增:统一的业务逻辑分发方法
void _handleSliderAction(String label, String action, BuildContext context) {
debugPrint('🎯 [Slider 业务] label: $label, action: $action');
@@ -412,17 +488,17 @@ class TopStatusBar extends StatelessWidget {
case "start":
debugPrint('2熄火');
// TODO: 发送 🔥点火指令
cubit.sendFireCommand(2);
cubit.sendFireCommand(2);
break;
case "center":
debugPrint('️0熄火');
// TODO: 发送点火停止指令
cubit.sendFireCommand(0);
cubit.sendFireCommand(0);
break;
case "end":
debugPrint('1点火)');
// TODO: 发送熄火后退指令
cubit.sendFireCommand(1);
cubit.sendFireCommand(1);
break;
}
}

View File

@@ -53,6 +53,13 @@ class _WebRTCLocalPlayerState extends State<WebRTCLocalPlayer> {
}
Future<void> _initWebRTCConnection() async {
// 🔥 安全检查: URL 为空时不初始化
if (widget.streamUrl.isEmpty) {
debugPrint('⚠️ [WebRTC] streamUrl 为空,跳过初始化');
setState(() => _isInitialized = true); // 🔥 标记为已初始化,避免卡loading
return;
}
_peerConnection = await createPeerConnection({
"sdpSemantics": "unified-plan",
"iceServers": [
@@ -86,7 +93,15 @@ class _WebRTCLocalPlayerState extends State<WebRTCLocalPlayer> {
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
await _peerConnection!.setRemoteDescription(RTCSessionDescription(data['sdp'], 'answer'));
final sdp = data['sdp'];
// 🔥 安全检查: SDP 不能为 null
if (sdp != null && sdp is String && sdp.isNotEmpty) {
await _peerConnection!.setRemoteDescription(RTCSessionDescription(sdp, 'answer'));
debugPrint('✅ [WebRTC] setRemoteDescription 成功');
} else {
debugPrint('❌ [WebRTC] SDP 为空或无效,跳过 setRemoteDescription');
}
}
} catch (e) {
debugPrint("信令错误: $e");