优化了tcp实时更新对UI线程的压力和对用弹窗的重复弹窗的影响。

更换了路径规划的的经纬度的字段名和取操作的名字更换。
This commit is contained in:
2026-06-08 13:35:36 +08:00
parent 7c9734d918
commit 354f7d6290
8 changed files with 445 additions and 276 deletions

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:dart_ping/dart_ping.dart';
import 'package:flutter/cupertino.dart';
@@ -39,13 +40,12 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
int _currentOriginX = 0;
int _currentOriginY = 0;
// 🔥 权限请求冷却期机制 - 防止Web端持续发送请求导致弹窗不断显示
DateTime? _lastPermissionResponseTime; // 记录上次响应权限请求的时间
static const _coolDownDuration = Duration(seconds: 5); // 冷却期5秒
// 🔥 同步锁 - 防止状态更新期间接收新请求导致重复弹窗
// 🔥 权限请求处理标志位 - 防止竞态条件,避免重复显示弹窗
bool _isProcessingPermissionRequest = false;
// 🔥 模拟数据推送定时器
// Timer? _simulationTimer;
// 🔥 获取带时间戳的日志前缀
String _getTimePrefix() {
final now = DateTime.now();
@@ -69,40 +69,138 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
}
// 🔥 新增:订阅 DeviceStatusBloc 的状态流,而不是直接监听TCP
// 类全局变量
DateTime? _lastUiUpdateTime;
String? _cacheVoltage;
String? _cacheBattery;
String? _cacheCtrlMode;
int? _cachePing;
void _initDeviceStatusListener() {
// // _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 c = await getNetworkDelay();
final c = getNetworkDelay();
_cacheVoltage = voltage.toString();
_cacheBattery = battery.toString();
_cacheCtrlMode = controlMode;
_cachePing = c;
// 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: voltage.toString(),
battery: battery.toString(),
controlMode: controlMode,
voltage: _cacheVoltage,
battery: _cacheBattery,
controlMode: _cacheCtrlMode,
),
battery: int.tryParse(battery) ?? 0,
ping: await c,
battery: int.tryParse(_cacheBattery ?? '') ?? 0,
ping: _cachePing,
// 🔥 标记为设备状态更新
updateType: 'device_status',
),
);
// // _logger.logWithLevel('✅ [RemoteControl] 从 DeviceStatusBloc 收到更新: 电压=$voltage, 电量=$battery, 模式=$controlMode');
}
});
// _logger.logWithLevel('>>> [RemoteControl] ✅ DeviceStatusBloc 订阅已建立完成');
}
// 🔥 超简单方法:传入 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');
@@ -141,14 +239,37 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
_kickOutSub = dispatcher.onCommand(0x12).listen((packet) {
final timeNow = _getTimePrefix();
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ✅ 收到 0x12 原始包');
debugPrint(
/* debugPrint(
'$timeNow 🔍 [RemoteControl] [0x12监听器] payload长度: ${packet.payload.length}',
);
);*/
_logger.logWithLevel(
'$timeNow 🔍 [RemoteControl] [0x12监听器] 收到 0x12 原始包,payload长度=${packet.payload.length}',
shouldLog: true,
);
// 先解析JSON判断是否为响应格式
String jsonStringForCheck;
try {
if (packet.payload.length > 2) {
jsonStringForCheck = utf8.decode(
packet.payload.sublist(0, packet.payload.length - 2),
);
} else {
jsonStringForCheck = utf8.decode(packet.payload);
}
final jsonMap = jsonDecode(jsonStringForCheck);
final respondData = jsonMap['respond'];
// 如果是响应格式,继续处理(更新权限状态)
// 如果是请求格式且弹窗已显示,忽略
if (respondData == null && state.showPermissionRequestDialog) {
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] ⚠️ 弹窗已显示(状态),忽略请求');
return;
}
} catch (e) {
// 解析失败,继续处理
}
try {
// 🔥 关键:手动去掉最后 2 个 CRC 字节
String jsonString;
@@ -179,11 +300,13 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
// 情况 1: 响应格式 - {"respond":{"switchResult":true,"deviceId":"...","holder":"you"}}
if (respondData != null && respondData is Map) {
// 🔥 收到响应格式,更新权限状态
final switchResult = respondData['switchResult'];
debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] 📊 收到切换结果响应');
/* debugPrint('$timeNow 🔍 [RemoteControl] [0x12监听器] 📊 收到切换结果响应');
debugPrint(
'$timeNow 🔍 [RemoteControl] [0x12监听器] switchResult: $switchResult',
);
);*/
_logger.logWithLevel(
'$timeNow 🔍 [RemoteControl] [0x12监听器] 📊 收到切换结果响应 - switchResult: $switchResult',
shouldLog: true,
@@ -218,6 +341,15 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
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');
@@ -235,28 +367,32 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
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 {
// 🔥 只有当弹窗还没显示时才弹出,防止重复弹窗叠加
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不匹配,忽略');
@@ -284,7 +420,8 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
'${_getTimePrefix()} ⚠️ [RemoteControl] 检测到异地登录,打开弹窗提示',
shouldLog: true,
);
if (!isClosed) {
// 🔥 只有当弹窗还没显示时才弹出
if (!isClosed && !state.showPermissionRequestDialog) {
emit(state.copyWith(showPermissionRequestDialog: true));
}
} else {
@@ -331,6 +468,9 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
//debugPrint('$logPrefix 启动控制循环,间隔: 100ms');
///debugPrint('$logPrefix =========================================');
// 🔥 启动模拟设备状态推送(用于测试)
// startSimulation();
_timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
if (isClosed) {
// debugPrint('$logPrefix ❌ Cubit已关闭,取消定时器');
@@ -538,27 +678,16 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
}
void respondPermission(bool agreed, String deviceId) {
// 🔥 记录响应时间,开启冷却期
_lastPermissionResponseTime = DateTime.now();
//debugPrint('$logPrefix 开启权限请求冷却期,持续${_coolDownDuration.inSeconds}秒');
// 1. 关闭弹窗(立即关闭,防止重复点击)
emit(state.copyWith(showPermissionRequestDialog: false));
// 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;
}
@@ -577,9 +706,7 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
state.copyWith(hasPermission: true, showPermissionRequestDialog: false),
);
}
debugPrint(
'${_getTimePrefix()} ====权限弹窗响应结束=====',
);
debugPrint('${_getTimePrefix()} ====权限弹窗响应结束=====');
}
Future<void> requestControlPermissionS(
@@ -625,12 +752,13 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
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));
// 🔥 修复:HTTP请求失败时不要自动打开弹窗,避免形成循环
// emit(state.copyWith(showPermissionRequestDialog: true));
debugPrint('$failLogPrefix HTTP请求失败,不自动打开弹窗');
},
(permissionInfo) async {
final bool hasPermission =
@@ -689,7 +817,11 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
);
}
/// 🔥 权限弹窗确认后调用- 发送TCP响应 + HTTP确认最终权限状态
/// 🔥 重置弹窗状态 - 在弹窗关闭后调用(已简化,不再需要标志位)
void resetPermissionCoolDown() {
// 标志位已移除,此方法保留以保持向后兼容性
}
Future<void> confirmPermissionResponse(
String deviceName,
String platform,
@@ -702,11 +834,12 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
debugPrint('$logPrefix 用户操作: ${agreed ? "同意" : "拒绝"}');
debugPrint('$logPrefix deviceName: $deviceName');
debugPrint('$logPrefix platform: $platform');
respondPermission(agreed, deviceName);
// 2. 调用 HTTP 接口获取最终权限状态
debugPrint('$logPrefix 📡 调用 HTTP 接口确认最终权限状态..');
/* final result = await _requestControlPermissionUseCase(
/* final result = await _requestControlPermissionUseCase(
RequestControlPermissionParams(
deviceName: deviceName,
deviceId: platform,
@@ -714,7 +847,7 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
);*/
// 3. 根据 HTTP 返回的真实权限状态更新UI
/* result.fold(
/* result.fold(
(failure) {
final failLogPrefix = '${_getTimePrefix()} 🔑 [RemoteControl] [权限确认]';
debugPrint('$failLogPrefix APP HTTP请求失败: ${failure.message}');
@@ -734,7 +867,7 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
'$successLogPrefix 🔄 正在更新UI - hasPermission: ${state.hasPermission} -> $hasPermission',
);
// 🔥 直接用HTTP 返回的权限状态覆盖
emit(state.copyWith(hasPermission: hasPermission));
// emit(state.copyWith(hasPermission: hasPermission));
debugPrint(
'$successLogPrefix 📊 UI已同步完成- 当前 hasPermission=$hasPermission',
);

View File

@@ -14,8 +14,8 @@ class RemoteControlState extends Equatable {
final bool isEmergency;
final bool isLocked;
final int ping;
final int battery;//电池量
final int voltage;//电压
final int battery; //电池量
final int voltage; //电压
final String permissionPlatform;
final String currentPlatform;
final bool showPermissionRequestDialog;
@@ -28,8 +28,11 @@ class RemoteControlState extends Equatable {
final bool obstacleRecognitionFlag; // 障碍物识别标志位(这是UI显示的)
final String obstacleFlag; //障碍物标志位
final DeviceEntity? targetDevice; // 🔥 待控制的设备
final RunningStatusModel runningStatusModel;
final DeviceEntity? targetDevice;
// 🔥 状态更新类型标记 - 用于区分是设备状态更新还是弹窗状态更新
final String? updateType;
const RemoteControlState({
this.status = RemoteControlStatus.initial,
@@ -53,6 +56,7 @@ class RemoteControlState extends Equatable {
this.topRightIsExpanded = false,
this.obstacleRecognitionFlag = true,
this.targetDevice,
this.updateType,
});
// 便利 UI 更新部分属性
@@ -78,7 +82,7 @@ class RemoteControlState extends Equatable {
bool? topRightIsExpanded,
bool? obstacleRecognitionFlag,
DeviceEntity? targetDevice,
String? updateType,
}) {
return RemoteControlState(
status: status ?? this.status,
@@ -101,9 +105,10 @@ class RemoteControlState extends Equatable {
runningStatusModel: runningStatusModel ?? this.runningStatusModel,
obstacleFlag: obstacleFlag ?? this.obstacleFlag,
topRightIsExpanded: topRightIsExpanded ?? this.topRightIsExpanded,
obstacleRecognitionFlag: obstacleRecognitionFlag ?? this.obstacleRecognitionFlag,
obstacleRecognitionFlag:
obstacleRecognitionFlag ?? this.obstacleRecognitionFlag,
targetDevice: targetDevice ?? this.targetDevice,
updateType: updateType, // 不使用 ??,因为我们想要 null 的时候就是 null
);
}
@@ -130,8 +135,6 @@ class RemoteControlState extends Equatable {
topRightIsExpanded,
obstacleRecognitionFlag,
targetDevice,
updateType,
];
}
}