完善遥控权限、控制发送和急停反馈
This commit is contained in:
97
lib/core/network/tcp/control_frame_scheduler.dart
Normal file
97
lib/core/network/tcp/control_frame_scheduler.dart
Normal file
@@ -0,0 +1,97 @@
|
||||
import 'dart:async';
|
||||
|
||||
/// One shared 0x00 sender. There is no FIFO of old movement commands: only
|
||||
/// the latest normal command and one priority stop/emergency may be pending.
|
||||
class ControlFrameScheduler {
|
||||
ControlFrameScheduler({int Function()? nowUs}) : _nowUs = nowUs {
|
||||
_clock.start();
|
||||
}
|
||||
|
||||
/// Shared interval for both the control loop and the transport gate.
|
||||
static const interval = Duration(milliseconds: 250);
|
||||
final Stopwatch _clock = Stopwatch();
|
||||
final int Function()? _nowUs;
|
||||
Timer? _timer;
|
||||
_ControlWrite? _priority;
|
||||
_ControlWrite? _latest;
|
||||
int? _lastCompletedUs;
|
||||
bool _writing = false;
|
||||
|
||||
int get _now => _nowUs?.call() ?? _clock.elapsedMicroseconds;
|
||||
|
||||
Future<bool> submit(
|
||||
Future<bool> Function() write, {
|
||||
required bool priority,
|
||||
required bool Function() isCurrent,
|
||||
}) {
|
||||
// Preserve each request's diagnostic Zone even when a later request replaces
|
||||
// the one that originally scheduled the timer.
|
||||
final job = _ControlWrite(Zone.current.bindCallback(write), isCurrent);
|
||||
if (priority) {
|
||||
_latest?.complete(false);
|
||||
_latest = null;
|
||||
_priority?.complete(false);
|
||||
_priority = job;
|
||||
} else {
|
||||
_latest?.complete(false);
|
||||
_latest = job;
|
||||
}
|
||||
_pump();
|
||||
return job.result.future;
|
||||
}
|
||||
|
||||
void _pump() {
|
||||
if (_writing || _timer != null) return;
|
||||
final job = _priority ?? _latest;
|
||||
if (job == null) return;
|
||||
if (!job.isCurrent()) {
|
||||
_remove(job);
|
||||
job.complete(false);
|
||||
_pump();
|
||||
return;
|
||||
}
|
||||
final remaining = _lastCompletedUs == null
|
||||
? 0
|
||||
: interval.inMicroseconds - (_now - _lastCompletedUs!);
|
||||
if (remaining > 0) {
|
||||
_timer = Timer(Duration(microseconds: remaining), () {
|
||||
_timer = null;
|
||||
_pump(); // Recheck the monotonic clock; never send an early timer tick.
|
||||
});
|
||||
return;
|
||||
}
|
||||
_remove(job);
|
||||
_writing = true;
|
||||
unawaited(_write(job));
|
||||
}
|
||||
|
||||
void _remove(_ControlWrite job) {
|
||||
if (identical(_priority, job)) _priority = null;
|
||||
if (identical(_latest, job)) _latest = null;
|
||||
}
|
||||
|
||||
Future<void> _write(_ControlWrite job) async {
|
||||
try {
|
||||
job.complete(job.isCurrent() ? await job.write() : false);
|
||||
} catch (_) {
|
||||
job.complete(false);
|
||||
} finally {
|
||||
// Measuring after local flush completion is conservative: actual socket
|
||||
// additions are at least one interval apart, including priority frames.
|
||||
_lastCompletedUs = _now;
|
||||
_writing = false;
|
||||
_pump();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ControlWrite {
|
||||
_ControlWrite(this.write, this.isCurrent);
|
||||
final Future<bool> Function() write;
|
||||
final bool Function() isCurrent;
|
||||
final Completer<bool> result = Completer<bool>();
|
||||
|
||||
void complete(bool value) {
|
||||
if (!result.isCompleted) result.complete(value);
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,57 @@ import '../../../features/devices/domain/entities/running_status_entity.dart';
|
||||
import '../../../features/devices/domain/usecases/get_user_device_usecase.dart';
|
||||
import '../../../features/devices/domain/usecases/switch_device_usecase.dart';
|
||||
import '../../logging/i_logger_service.dart';
|
||||
import '../../logging/control_permission_diagnostics.dart';
|
||||
import '../../logging/remote_control_diagnostics.dart';
|
||||
import '../../storage/user_storage.dart';
|
||||
import '../protocol_decoder.dart';
|
||||
import 'tcp_status_cubit.dart';
|
||||
import 'control_frame_scheduler.dart';
|
||||
|
||||
class TcpClient {
|
||||
Socket? _socket;
|
||||
int _diagnosticPendingFlushes = 0;
|
||||
int? _diagnosticLastMotionAddUs;
|
||||
final ControlFrameScheduler _controlFrames = ControlFrameScheduler();
|
||||
final Set<Future<dynamic>> _pendingSocketFlushes = {};
|
||||
Future<dynamic>? _lastRawFlush;
|
||||
|
||||
/// Observe completion without awaiting, delaying or changing any sender.
|
||||
void _observeDiagnosticFlush(
|
||||
Future<dynamic> pending,
|
||||
int command,
|
||||
int beganUs,
|
||||
) {
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final connection = _connectionId;
|
||||
_pendingSocketFlushes.add(pending);
|
||||
_diagnosticPendingFlushes++;
|
||||
pending.then<void>(
|
||||
(_) {
|
||||
_diagnosticPendingFlushes--;
|
||||
_pendingSocketFlushes.remove(pending);
|
||||
trace.event('socket_flush_complete', {
|
||||
'cmd': command,
|
||||
'connection': connection,
|
||||
'durationUs': trace.elapsedUs - beganUs,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
},
|
||||
onError: (Object error, StackTrace stack) {
|
||||
_diagnosticPendingFlushes--;
|
||||
_pendingSocketFlushes.remove(pending);
|
||||
trace.event('socket_flush_error', {
|
||||
'cmd': command,
|
||||
'connection': connection,
|
||||
'durationUs': trace.elapsedUs - beganUs,
|
||||
'errorType': error.runtimeType.toString(),
|
||||
'error': error.toString(),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
final _decoder = ProtocolDecoder();
|
||||
// 使用 StreamController 将原始数据流暴露给外部,以便多个 DataSource 监听
|
||||
final _controller = StreamController<RawPacket>.broadcast();
|
||||
@@ -47,8 +92,10 @@ class TcpClient {
|
||||
static const int _maxReconnectFlaps = 5; // 🔥 最大允许连续成功-断开次数
|
||||
/// 🔥 重连耗尽回调:连续4次重连失败(含心跳超时)后触发,通知上层弹窗提示用户
|
||||
VoidCallback? onReconnectExhausted;
|
||||
|
||||
/// 🔥 重连开始回调:显示"TCP重连中"提示
|
||||
VoidCallback? onReconnectStarted;
|
||||
|
||||
/// 🔥 重连成功回调:显示"连接成功"提示
|
||||
VoidCallback? onReconnectSuccess;
|
||||
static const Duration _heartbeatTimeout = Duration(seconds: 15); // 心跳超时时间
|
||||
@@ -57,18 +104,19 @@ class TcpClient {
|
||||
int? _lastPort;
|
||||
bool isUserSwitch = false; // 用户是否切换设备
|
||||
bool _isSwitching = false;
|
||||
bool _connecting = false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争)
|
||||
bool _connecting =
|
||||
false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争)
|
||||
Completer<void>? _connectionCompleter; // 🔥 用于通知连接就绪
|
||||
int _connectionId = 0; // 🔥 连接代数:每次新建连接递增,旧socket回调发现ID不匹配则忽略
|
||||
|
||||
|
||||
// 🔥 关键标志:记录客户端最后一次发送 0x03 认证包的时间
|
||||
// 用于区分"自身认证触发的 have_logged_in"和"真正的异地登录"
|
||||
// 如果 have_logged_in 在发送 0x03 后短时间内到达,说明是服务端残留 session 导致的
|
||||
DateTime? _lastAuthPacketSentAt;
|
||||
|
||||
|
||||
/// 检查当前的 have_logged_in 是否是自身 0x03 认证触发的
|
||||
/// 返回 true 表示应忽略(是服务端残留 session 导致的误报)
|
||||
///
|
||||
///
|
||||
/// 🔥 恢复:用于登录阶段判断是否为服务端残留 session 导致的误报
|
||||
/// 判断逻辑:
|
||||
/// 1. 如果 TCP 已断开 (_socket == null) → 一定是真正的异地登录,返回 false
|
||||
@@ -80,26 +128,28 @@ class TcpClient {
|
||||
debugPrint('🔍 [TCP] TCP 已断开,判定为真正的异地登录');
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
final sentAt = _lastAuthPacketSentAt;
|
||||
if (sentAt == null) {
|
||||
debugPrint('🔍 [TCP] 无认证时间戳,判定为真正的异地登录');
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
final elapsed = DateTime.now().difference(sentAt);
|
||||
// 🔥 缩短时间窗口到 2 秒,只过滤刚发送 0x03 时的误报
|
||||
final isRecent = elapsed.inSeconds < 2;
|
||||
|
||||
|
||||
if (isRecent) {
|
||||
debugPrint('🔍 [TCP] 距离上次认证 ${elapsed.inMilliseconds}ms (<2s),判定为自身认证触发(服务端残留 session)');
|
||||
debugPrint(
|
||||
'🔍 [TCP] 距离上次认证 ${elapsed.inMilliseconds}ms (<2s),判定为自身认证触发(服务端残留 session)',
|
||||
);
|
||||
} else {
|
||||
debugPrint('🔍 [TCP] 距离上次认证 ${elapsed.inSeconds}s (>=2s),判定为真正的异地登录');
|
||||
}
|
||||
|
||||
|
||||
return isRecent;
|
||||
}
|
||||
|
||||
|
||||
/// 清除认证时间戳(在真正的异地登录时调用)
|
||||
void clearAuthTimestamp() {
|
||||
_lastAuthPacketSentAt = null;
|
||||
@@ -139,18 +189,18 @@ class TcpClient {
|
||||
void forceDisconnect() {
|
||||
_logger.logWithLevel('🛑 [TCP] 强制断开并清除重连能力', shouldLog: true);
|
||||
_connectionId++; // 🔥 使旧socket回调失效
|
||||
|
||||
|
||||
// 1. 停止心跳
|
||||
stopHeartbeat();
|
||||
|
||||
|
||||
// 2. 取消重连定时器
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = null;
|
||||
|
||||
|
||||
// 3. 清除 Host/Port,防止重连
|
||||
_lastHost = null;
|
||||
_lastPort = null;
|
||||
|
||||
|
||||
// 4. 重置标志
|
||||
isUserSwitch = false;
|
||||
_isSwitching = false;
|
||||
@@ -160,21 +210,21 @@ class TcpClient {
|
||||
_reconnectAttempt = 0; // 🔥 重置重连退避
|
||||
_reconnectFailCount = 0; // 🔥 重置重连失败计数
|
||||
_reconnectFlapCount = 0; // 🔥 重置连上又断计数
|
||||
|
||||
|
||||
// 5. 销毁 Socket
|
||||
if (_socket != null) {
|
||||
_socket!.destroy();
|
||||
_socket = null;
|
||||
_logger.logWithLevel('✅ [TCP] Socket 已物理销毁', shouldLog: true);
|
||||
}
|
||||
|
||||
|
||||
// 6. 更新状态
|
||||
try {
|
||||
GetIt.I<TcpStatusCubit>().setDisconnected();
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('❌ [TCP] TcpStatusCubit 未注册', shouldLog: false);
|
||||
}
|
||||
|
||||
|
||||
_logger.logWithLevel('✅ [TCP] 已彻底断开,下次登录需重新初始化', shouldLog: true);
|
||||
}
|
||||
|
||||
@@ -189,27 +239,27 @@ class TcpClient {
|
||||
_lastPort = port;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 🔥 关键修复:如果用户正在切换设备(connectBySwitch),不干扰
|
||||
if (isUserSwitch) {
|
||||
debugPrint('✅ [TCP-connect] 用户正在切换设备,跳过 connect()');
|
||||
_logger.logWithLevel('✅ [TCP-connect] 用户正在切换设备,跳过', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 🔥 关键修复:如果已有连接正在进行中,不创建新连接
|
||||
if (_connecting) {
|
||||
debugPrint('✅ [TCP-connect] 已有连接正在进行中,跳过');
|
||||
_logger.logWithLevel('✅ [TCP-connect] 已有连接正在进行中,跳过', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
_connecting = true;
|
||||
_connectionCompleter = Completer<void>();
|
||||
_connectionId++; // 🔥 新一代连接,旧socket的回调将自动失效
|
||||
final myConnId = _connectionId;
|
||||
debugPrint('🔌 [TCP-connect] 设置 _connecting=true, connectionId=$myConnId');
|
||||
|
||||
|
||||
_logger.logWithLevel('🔌 [TCP] 开始连接:$host:$port', shouldLog: true);
|
||||
|
||||
// 更新连接状态为连接中
|
||||
@@ -278,12 +328,19 @@ class TcpClient {
|
||||
// 必须在 _controller.add 之前检查,否则 AuthCubit 会判定为异地登录弹出退出弹窗
|
||||
if (packet.command == 0x12 && wasReconnecting) {
|
||||
try {
|
||||
final payloadStr = utf8.decode(packet.payload.length > 2
|
||||
? packet.payload.sublist(0, packet.payload.length - 2)
|
||||
: packet.payload);
|
||||
final payloadStr = utf8.decode(
|
||||
packet.payload.length > 2
|
||||
? packet.payload.sublist(0, packet.payload.length - 2)
|
||||
: packet.payload,
|
||||
);
|
||||
if (payloadStr.contains('have_logged_in')) {
|
||||
debugPrint('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session');
|
||||
_logger.logWithLevel('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连', shouldLog: true);
|
||||
debugPrint(
|
||||
'🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连',
|
||||
shouldLog: true,
|
||||
);
|
||||
_handleReconnectSessionReset(myConnId);
|
||||
return; // 停止处理后续数据,不分发给任何监听器
|
||||
}
|
||||
@@ -325,8 +382,13 @@ class TcpClient {
|
||||
onDone: () {
|
||||
// 🔥 关键修复:检查 connectionId,防止旧socket的回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略',
|
||||
shouldLog: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_isSwitching) {
|
||||
@@ -337,7 +399,9 @@ class TcpClient {
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略');
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
@@ -385,7 +449,10 @@ class TcpClient {
|
||||
void _handleDisconnect() {
|
||||
_connectionId++; // 🔥 使旧socket的所有回调立即失效,防止onDone/onError污染新连接
|
||||
debugPrint('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🔌 [TCP] _handleDisconnect, connectionId→$_connectionId',
|
||||
shouldLog: true,
|
||||
);
|
||||
stopHeartbeat();
|
||||
|
||||
_socket = null;
|
||||
@@ -394,7 +461,10 @@ class TcpClient {
|
||||
debugPrint('📊 [TCP] 连接断开次数: $_reconnectFlapCount/$_maxReconnectFlaps');
|
||||
if (_reconnectFlapCount >= _maxReconnectFlaps) {
|
||||
debugPrint('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连,通知用户退出登录');
|
||||
_logger.logWithLevel('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连',
|
||||
shouldLog: true,
|
||||
);
|
||||
onReconnectExhausted?.call();
|
||||
return;
|
||||
}
|
||||
@@ -416,7 +486,10 @@ class TcpClient {
|
||||
// 🔥 限制总重连次数,防止网络不可达时无限重连
|
||||
if (_reconnectAttempt >= _maxReconnectAttempts) {
|
||||
debugPrint('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连,通知用户退出登录');
|
||||
_logger.logWithLevel('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连',
|
||||
shouldLog: true,
|
||||
);
|
||||
onReconnectExhausted?.call();
|
||||
return;
|
||||
}
|
||||
@@ -424,7 +497,9 @@ class TcpClient {
|
||||
// 🔥 重连退避:5s → 10s → 20s → 30s(max)
|
||||
final delay = [5, 10, 20, 30][_reconnectAttempt.clamp(0, 3)];
|
||||
_reconnectAttempt++;
|
||||
_logger.logWithLevel('⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}');
|
||||
_logger.logWithLevel(
|
||||
'⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}',
|
||||
);
|
||||
if (_lastHost == null || _lastPort == null) {
|
||||
_logger.logWithLevel('❌ 无法重连:Host 或 Port 为空!', shouldLog: true);
|
||||
return;
|
||||
@@ -446,32 +521,54 @@ class TcpClient {
|
||||
// 🔥 显示"TCP重连中"提示
|
||||
onReconnectStarted?.call();
|
||||
final reconnectStart = DateTime.now();
|
||||
final timeStr = '${reconnectStart.hour.toString().padLeft(2,'0')}:${reconnectStart.minute.toString().padLeft(2,'0')}:${reconnectStart.second.toString().padLeft(2,'0')}.${reconnectStart.millisecond.toString().padLeft(3,'0')}';
|
||||
final timeStr =
|
||||
'${reconnectStart.hour.toString().padLeft(2, '0')}:${reconnectStart.minute.toString().padLeft(2, '0')}:${reconnectStart.second.toString().padLeft(2, '0')}.${reconnectStart.millisecond.toString().padLeft(3, '0')}';
|
||||
debugPrint('⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)');
|
||||
_logger.logWithLevel('⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
await connect(host: _lastHost!, port: _lastPort!);
|
||||
final connectDone = DateTime.now();
|
||||
final connectMs = connectDone.difference(reconnectStart).inMilliseconds;
|
||||
debugPrint('✅ [TCP-重连] ${connectDone.hour.toString().padLeft(2,'0')}:${connectDone.minute.toString().padLeft(2,'0')}:${connectDone.second.toString().padLeft(2,'0')}.${connectDone.millisecond.toString().padLeft(3,'0')} connect() 完成,耗时 ${connectMs}ms');
|
||||
debugPrint(
|
||||
'✅ [TCP-重连] ${connectDone.hour.toString().padLeft(2, '0')}:${connectDone.minute.toString().padLeft(2, '0')}:${connectDone.second.toString().padLeft(2, '0')}.${connectDone.millisecond.toString().padLeft(3, '0')} connect() 完成,耗时 ${connectMs}ms',
|
||||
);
|
||||
_reconnectAttempt = 0; // 🔥 重连成功,重置退避计数
|
||||
// 🔥 关键修复:等待5秒再调 HTTP switchDevice,给服务端时间完成相关操作
|
||||
final delayStart = DateTime.now();
|
||||
debugPrint('⏳ [TCP-重连] ${delayStart.hour.toString().padLeft(2,'0')}:${delayStart.minute.toString().padLeft(2,'0')}:${delayStart.second.toString().padLeft(2,'0')}.${delayStart.millisecond.toString().padLeft(3,'0')} 开始等待5秒...');
|
||||
debugPrint(
|
||||
'⏳ [TCP-重连] ${delayStart.hour.toString().padLeft(2, '0')}:${delayStart.minute.toString().padLeft(2, '0')}:${delayStart.second.toString().padLeft(2, '0')}.${delayStart.millisecond.toString().padLeft(3, '0')} 开始等待5秒...',
|
||||
);
|
||||
await Future.delayed(const Duration(milliseconds: 5000));
|
||||
final afterDelay = DateTime.now();
|
||||
final actualDelayMs = afterDelay.difference(delayStart).inMilliseconds;
|
||||
debugPrint('⏳ [TCP-重连] ${afterDelay.hour.toString().padLeft(2,'0')}:${afterDelay.minute.toString().padLeft(2,'0')}:${afterDelay.second.toString().padLeft(2,'0')}.${afterDelay.millisecond.toString().padLeft(3,'0')} 等待结束,实际耗时 ${actualDelayMs}ms,开始调 HTTP switchDevice');
|
||||
debugPrint(
|
||||
'⏳ [TCP-重连] ${afterDelay.hour.toString().padLeft(2, '0')}:${afterDelay.minute.toString().padLeft(2, '0')}:${afterDelay.second.toString().padLeft(2, '0')}.${afterDelay.millisecond.toString().padLeft(3, '0')} 等待结束,实际耗时 ${actualDelayMs}ms,开始调 HTTP switchDevice',
|
||||
);
|
||||
try {
|
||||
final remoteControlCubit = GetIt.I<RemoteControlCubit>();
|
||||
final targetDevice = remoteControlCubit.state.targetDevice;
|
||||
if (targetDevice != null) {
|
||||
debugPrint('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}');
|
||||
_logger.logWithLevel('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}', shouldLog: true);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice('app', targetDevice.deviceName);
|
||||
debugPrint(
|
||||
'🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}',
|
||||
shouldLog: true,
|
||||
);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
'app',
|
||||
targetDevice.deviceName,
|
||||
);
|
||||
final switchDone = DateTime.now();
|
||||
final totalMs = switchDone.difference(reconnectStart).inMilliseconds;
|
||||
debugPrint('✅ [TCP-重连] ${switchDone.hour.toString().padLeft(2,'0')}:${switchDone.minute.toString().padLeft(2,'0')}:${switchDone.second.toString().padLeft(2,'0')}.${switchDone.millisecond.toString().padLeft(3,'0')} HTTP switchDevice 成功,重连总耗时 ${totalMs}ms');
|
||||
final totalMs = switchDone
|
||||
.difference(reconnectStart)
|
||||
.inMilliseconds;
|
||||
debugPrint(
|
||||
'✅ [TCP-重连] ${switchDone.hour.toString().padLeft(2, '0')}:${switchDone.minute.toString().padLeft(2, '0')}:${switchDone.second.toString().padLeft(2, '0')}.${switchDone.millisecond.toString().padLeft(3, '0')} HTTP switchDevice 成功,重连总耗时 ${totalMs}ms',
|
||||
);
|
||||
} else {
|
||||
debugPrint('⚠️ [TCP-重连] targetDevice 为 null,跳过 switchDevice');
|
||||
}
|
||||
@@ -479,7 +576,10 @@ class TcpClient {
|
||||
onReconnectSuccess?.call();
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-重连] HTTP switchDevice 失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-重连] HTTP switchDevice 失败: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP-重连] HTTP switchDevice 失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-重连] connect 失败: $e');
|
||||
@@ -506,33 +606,42 @@ class TcpClient {
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('⏰ 被动-定时器触发,开始执行重连...', shouldLog: true);
|
||||
|
||||
|
||||
// 🔥 修复:重连时使用 RemoteControlCubit.targetDevice,而不是记住的设备名
|
||||
try {
|
||||
final remoteControlCubit = GetIt.I<RemoteControlCubit>();
|
||||
final targetDevice = remoteControlCubit.state.targetDevice;
|
||||
|
||||
|
||||
if (targetDevice != null) {
|
||||
_logger.logWithLevel('🔄 [TCP] 重连使用 targetDevice: ${targetDevice.deviceName}', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🔄 [TCP] 重连使用 targetDevice: ${targetDevice.deviceName}',
|
||||
shouldLog: true,
|
||||
);
|
||||
connectBySwitch(
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
deviceName: targetDevice.deviceName,
|
||||
);
|
||||
} else {
|
||||
// 如果 targetDevice 为 null,使用传入的设备名作为兜底
|
||||
_logger.logWithLevel('⚠️ [TCP] targetDevice 为 null,使用传入的设备名: $devname', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⚠️ [TCP] targetDevice 为 null,使用传入的设备名: $devname',
|
||||
shouldLog: true,
|
||||
);
|
||||
connectBySwitch(
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
deviceName: devname,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('❌ [TCP] 获取 targetDevice 失败,使用传入的设备名: $devname, 错误: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP] 获取 targetDevice 失败,使用传入的设备名: $devname, 错误: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
connectBySwitch(
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
deviceName: devname,
|
||||
);
|
||||
}
|
||||
@@ -549,10 +658,111 @@ class TcpClient {
|
||||
_socket!.add(data);
|
||||
}
|
||||
|
||||
/// 🔥 断线丢帧日志节流时间戳:控制循环每 200ms 就会撞一次「未连接」,
|
||||
/// Permission requests need an awaited write result. Other send paths stay intact.
|
||||
/// Completion confirms local socket flushing, not server/Web receipt.
|
||||
Future<void> sendPermissionPacket(List<int> packet) async {
|
||||
final clock = Stopwatch()..start();
|
||||
final socket = _socket;
|
||||
final connection = _connectionId;
|
||||
var operation = 'wait_flush';
|
||||
var addAccepted = false;
|
||||
ControlPermissionDiagnostics.event('socket权限写入开始', {
|
||||
'connection': connection,
|
||||
'connected': socket != null,
|
||||
'pendingFlushes': _pendingSocketFlushes.length,
|
||||
'packetBytes': packet.length,
|
||||
});
|
||||
try {
|
||||
if (socket == null) throw const SocketException('TCP not connected');
|
||||
await _waitForSocketFlushes();
|
||||
if (!identical(socket, _socket))
|
||||
throw const SocketException('TCP changed');
|
||||
operation = 'add';
|
||||
socket.add(packet);
|
||||
addAccepted = true;
|
||||
ControlPermissionDiagnostics.event('socket权限add完成', {
|
||||
'connection': connection,
|
||||
'waitMs': clock.elapsedMilliseconds,
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final beganUs = trace.elapsedUs;
|
||||
operation = 'flush';
|
||||
final pending = socket.flush();
|
||||
_observeDiagnosticFlush(pending, 0x12, beganUs);
|
||||
await pending;
|
||||
if (!identical(socket, _socket)) {
|
||||
throw const SocketException(
|
||||
'TCP connection changed during permission send',
|
||||
);
|
||||
}
|
||||
ControlPermissionDiagnostics.event('socket权限flush完成', {
|
||||
'connection': connection,
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
} catch (e) {
|
||||
ControlPermissionDiagnostics.event('socket权限写入失败', {
|
||||
'connection': connection,
|
||||
'operation': operation,
|
||||
'addAccepted': addAccepted,
|
||||
'errorType': e.runtimeType.toString(),
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
});
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔥 断线丢帧日志节流时间戳:控制循环每 250ms 就会撞一次「未连接」,
|
||||
/// 全量打印会淹掉日志文件,故 5 秒内只记一次(丢帧本身仍如实返回 false)。
|
||||
DateTime? _lastSendDropLogAt;
|
||||
|
||||
Future<void> _waitForSocketFlushes() async {
|
||||
while (_pendingSocketFlushes.isNotEmpty) {
|
||||
await Future.wait(
|
||||
_pendingSocketFlushes.toList().map((pending) async {
|
||||
try {
|
||||
await pending;
|
||||
} catch (_) {}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sole supported 0x00 path: newest movement, priority stop, >=250ms.
|
||||
Future<bool> sendControlPayload(
|
||||
List<int> payload, {
|
||||
bool priority = false,
|
||||
bool Function()? isCurrent,
|
||||
}) {
|
||||
final socket = _socket;
|
||||
final connection = _connectionId;
|
||||
final bytes = List<int>.of(payload);
|
||||
bool current() =>
|
||||
socket != null &&
|
||||
identical(socket, _socket) &&
|
||||
connection == _connectionId &&
|
||||
(isCurrent?.call() ?? true);
|
||||
return _controlFrames.submit(
|
||||
() async {
|
||||
await _waitForSocketFlushes();
|
||||
if (!current()) return false;
|
||||
final accepted = _sendRawNow(0x00, bytes);
|
||||
if (!accepted) return false;
|
||||
final pending = _lastRawFlush;
|
||||
if (pending == null) return false;
|
||||
try {
|
||||
await pending;
|
||||
return current();
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
priority: priority,
|
||||
isCurrent: current,
|
||||
);
|
||||
}
|
||||
|
||||
/// 把一帧协议数据写入 socket。
|
||||
///
|
||||
/// 返回 `false` = 这一帧**根本没交给系统 socket**(未连接,或写入抛异常)。
|
||||
@@ -561,7 +771,26 @@ class TcpClient {
|
||||
/// 而代码以为「已发送」——设备只保留了断开前最后一帧运动指令,正是
|
||||
/// 「松手了车还在走」的一条隐藏通路。现在必须由调用方判断结果自行兜底。
|
||||
bool sendRaw(int cmd, List<int> payload) {
|
||||
if (cmd == 0x00) {
|
||||
// Legacy callers may not bypass the common motion gate.
|
||||
unawaited(sendControlPayload(payload));
|
||||
return false; // Deferred requests must not claim a synchronous write.
|
||||
}
|
||||
return _sendRawNow(cmd, payload);
|
||||
}
|
||||
|
||||
bool _sendRawNow(int cmd, List<int> payload) {
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final beganUs = trace.elapsedUs;
|
||||
trace.event('socket_write_attempt', {
|
||||
'cmd': cmd,
|
||||
'connection': _connectionId,
|
||||
'connected': _socket != null,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'payloadBytes': payload.length,
|
||||
});
|
||||
if (_socket == null) {
|
||||
trace.event('socket_not_connected', {'cmd': cmd, 'addAccepted': false});
|
||||
final now = DateTime.now();
|
||||
if (_lastSendDropLogAt == null ||
|
||||
now.difference(_lastSendDropLogAt!) >= const Duration(seconds: 5)) {
|
||||
@@ -586,10 +815,30 @@ class TcpClient {
|
||||
..addByte(0xAB);
|
||||
|
||||
final packet = builder.takeBytes();
|
||||
var operation = 'add';
|
||||
var addAccepted = false;
|
||||
try {
|
||||
_socket!.add(packet);
|
||||
addAccepted = true;
|
||||
final addedUs = trace.elapsedUs;
|
||||
trace.event('socket_add_accepted', {
|
||||
'cmd': cmd,
|
||||
'connection': _connectionId,
|
||||
'addAccepted': true,
|
||||
'addGapUs': cmd == 0x00 && _diagnosticLastMotionAddUs != null
|
||||
? addedUs - _diagnosticLastMotionAddUs!
|
||||
: null,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'frameBytes': packet.length,
|
||||
'frameHex': _hex(packet),
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
if (cmd == 0x00) _diagnosticLastMotionAddUs = addedUs;
|
||||
// 🔥 关键修复:强制flush,确保数据立即发送
|
||||
_socket!.flush();
|
||||
operation = 'flush';
|
||||
final pending = _socket!.flush();
|
||||
_lastRawFlush = pending;
|
||||
_observeDiagnosticFlush(pending, cmd, beganUs);
|
||||
// 联调日志:移到 add+flush 之后打印,证明这帧已真正交给系统 socket 发送缓冲
|
||||
// ("发出去之后"才有参考价值;仍非后端 ACK,仅代表 App 侧写入成功)(联调结束可移除)
|
||||
_logger.logWithLevel(
|
||||
@@ -599,6 +848,15 @@ class TcpClient {
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
trace.event('socket_write_error', {
|
||||
'cmd': cmd,
|
||||
'connection': _connectionId,
|
||||
'operation': operation,
|
||||
'addAccepted': addAccepted,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'errorType': e.runtimeType.toString(),
|
||||
'error': e.toString(),
|
||||
});
|
||||
_logger.logWithLevel(
|
||||
'🔗 [联调-TCP] sendRaw ❌写入socket失败 cmd=0x${cmd.toRadixString(16).padLeft(2, '0')} err=$e',
|
||||
level: 'ERROR',
|
||||
@@ -621,7 +879,7 @@ class TcpClient {
|
||||
..addByte(0xAA)
|
||||
..addByte(0xAB);
|
||||
_socket!.add(builder.takeBytes());
|
||||
debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB');
|
||||
// debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB');
|
||||
}
|
||||
|
||||
/// 启动心跳:主动定时发送 + 超时检测
|
||||
@@ -630,7 +888,10 @@ class TcpClient {
|
||||
void startHeartbeat({Duration interval = const Duration(seconds: 4)}) {
|
||||
if (_heartbeatTimer != null) return; // 防止重复启动
|
||||
debugPrint('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)');
|
||||
_logger.logWithLevel('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
// 🔥 主动定时发送心跳给服务端(每5秒)
|
||||
_heartbeatSendTimer?.cancel();
|
||||
@@ -650,7 +911,9 @@ class TcpClient {
|
||||
final wasRunning = _heartbeatTimer != null;
|
||||
_heartbeatTimer?.cancel();
|
||||
_heartbeatTimer = Timer(_heartbeatTimeout, () {
|
||||
debugPrint('⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开');
|
||||
debugPrint(
|
||||
'⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开',
|
||||
);
|
||||
_logger.logWithLevel('⚠️ [TCP] 心跳超时,判定连接断开', shouldLog: true);
|
||||
// 触发断开重连
|
||||
if (_socket != null) {
|
||||
@@ -685,12 +948,12 @@ class TcpClient {
|
||||
_logger.logWithLevel('✅ [TCP] 正在连接中,跳过', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
_connecting = true;
|
||||
_connectionCompleter = Completer<void>();
|
||||
_connectionId++; // 🔥 新一代连接,旧socket回调自动失效
|
||||
final myConnId = _connectionId;
|
||||
|
||||
|
||||
try {
|
||||
// 更新状态为连接中
|
||||
try {
|
||||
@@ -698,12 +961,12 @@ class TcpClient {
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('❌ [TCP] TcpStatusCubit 未注册', shouldLog: false);
|
||||
}
|
||||
|
||||
|
||||
// 执行连接
|
||||
_logger.logWithLevel('🔌 [TCP] 开始初始化连接:$host:$port', shouldLog: true);
|
||||
_lastHost = host;
|
||||
_lastPort = port;
|
||||
|
||||
|
||||
_socket = await Socket.connect(
|
||||
host,
|
||||
port,
|
||||
@@ -711,30 +974,30 @@ class TcpClient {
|
||||
);
|
||||
_socket!.setOption(SocketOption.tcpNoDelay, true);
|
||||
_logger.logWithLevel('✅ [TCP] Socket 连接成功', shouldLog: true);
|
||||
|
||||
|
||||
// 更新状态为已连接
|
||||
try {
|
||||
GetIt.I<TcpStatusCubit>().setConnected();
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('❌ [TCP] TcpStatusCubit 未注册', shouldLog: false);
|
||||
}
|
||||
|
||||
|
||||
// 发送认证包
|
||||
await _sendAuthPacket();
|
||||
_logger.logWithLevel('✅ [TCP] 认证包已发送', shouldLog: true);
|
||||
|
||||
|
||||
// 启动心跳
|
||||
startHeartbeat();
|
||||
_logger.logWithLevel('✅ [TCP] 心跳已启动', shouldLog: true);
|
||||
|
||||
|
||||
// 设置数据监听(复用现有的监听逻辑)
|
||||
_setupDataListener(myConnId);
|
||||
|
||||
|
||||
_connecting = false;
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
_connectionCompleter!.complete();
|
||||
}
|
||||
|
||||
|
||||
_logger.logWithLevel('🎉 [TCP] TCP 初始化完成!', shouldLog: true);
|
||||
} catch (e) {
|
||||
_connecting = false;
|
||||
@@ -759,7 +1022,9 @@ class TcpClient {
|
||||
var packets = _decoder.decode(data);
|
||||
for (var packet in packets) {
|
||||
// 🔥 最根部日志:收到任何推送都打印
|
||||
debugPrint('📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}');
|
||||
debugPrint(
|
||||
'📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}',
|
||||
shouldLog: true,
|
||||
@@ -791,7 +1056,10 @@ class TcpClient {
|
||||
// 🔥 检查 connectionId,防止旧socket回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略',
|
||||
shouldLog: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_isSwitching) {
|
||||
@@ -802,7 +1070,9 @@ class TcpClient {
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
@@ -936,14 +1206,16 @@ class TcpClient {
|
||||
username = user.username;
|
||||
token = user.token;
|
||||
final authString = '$username:app:$token';
|
||||
|
||||
|
||||
// 🔥 关键日志:打印认证字符串,方便核对 Token
|
||||
debugPrint('🔑 [TCP] 正在发送认证包 (0x03)');
|
||||
debugPrint(' - Username: $username');
|
||||
debugPrint(' - Token: ${token?.substring(0, token!.length > 10 ? 10 : token!.length)}...'); // 只打印前10位保护隐私
|
||||
debugPrint(
|
||||
' - Token: ${token?.substring(0, token!.length > 10 ? 10 : token!.length)}...',
|
||||
); // 只打印前10位保护隐私
|
||||
debugPrint(' - Full Auth String: $authString');
|
||||
_logger.logWithLevel('🔑 [TCP] 认证字符串: $authString', shouldLog: true);
|
||||
|
||||
|
||||
final authBytes = utf8.encode(authString);
|
||||
|
||||
// 构造包结构:Head(2) + Cmd(1) + Payload(N) + CRC(2) + Foot(2)
|
||||
@@ -1036,52 +1308,77 @@ class TcpClient {
|
||||
required String deviceName,
|
||||
}) async {
|
||||
debugPrint('🔌 [TCP-connectBySwitch] ========== 开始连接 ==========');
|
||||
debugPrint('🔌 [TCP-connectBySwitch] Host: $host, Port: $port, Device: $deviceName');
|
||||
|
||||
debugPrint(
|
||||
'🔌 [TCP-connectBySwitch] Host: $host, Port: $port, Device: $deviceName',
|
||||
);
|
||||
|
||||
// 🔥 关键:取消之前的重连定时器,防止连接冲突
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = null;
|
||||
debugPrint('✅ [TCP-connectBySwitch] 已取消旧的重连定时器');
|
||||
|
||||
|
||||
// 🔥 关键修复:如果已有连接正在进行中,等待连接就绪后只调 HTTP switchDevice
|
||||
if (_connecting) {
|
||||
debugPrint('✅ [TCP-connectBySwitch] 检测到 connect() 正在进行中,等待连接就绪...');
|
||||
_logger.logWithLevel('✅ [TCP-connectBySwitch] 连接进行中,等待后只做HTTP切换', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP-connectBySwitch] 连接进行中,等待后只做HTTP切换',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
await _connectionCompleter!.future.timeout(const Duration(seconds: 10));
|
||||
if (_connectionCompleter != null &&
|
||||
!_connectionCompleter!.isCompleted) {
|
||||
await _connectionCompleter!.future.timeout(
|
||||
const Duration(seconds: 10),
|
||||
);
|
||||
}
|
||||
// 连接就绪,只做 HTTP switchDevice,不创建新 TCP 连接
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice("app", deviceName);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
"app",
|
||||
deviceName,
|
||||
);
|
||||
debugPrint('✅ [TCP-connectBySwitch] 等待连接就绪后HTTP切换成功: $deviceName');
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 🔥 核心优化:如果 TCP 已连接,复用现有连接,只调 HTTP switchDevice
|
||||
// 不再销毁重建,避免推送空窗期导致延迟
|
||||
if (_socket != null) {
|
||||
debugPrint('✅ [TCP-connectBySwitch] 已有连接,复用现有连接,只调 HTTP switchDevice: $deviceName');
|
||||
_logger.logWithLevel('✅ [TCP-connectBySwitch] 复用连接,HTTP切换设备: $deviceName', shouldLog: true);
|
||||
debugPrint(
|
||||
'✅ [TCP-connectBySwitch] 已有连接,复用现有连接,只调 HTTP switchDevice: $deviceName',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP-connectBySwitch] 复用连接,HTTP切换设备: $deviceName',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice("app", deviceName);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
"app",
|
||||
deviceName,
|
||||
);
|
||||
debugPrint('✅ [TCP-connectBySwitch] HTTP切换成功: $deviceName');
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-connectBySwitch] HTTP切换失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-connectBySwitch] HTTP切换失败: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP-connectBySwitch] HTTP切换失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
isUserSwitch = true;
|
||||
_connecting = true; // 🔥 防止 connect() 并发创建新连接
|
||||
_connectionId++; // 🔥 新一代连接,旧socket回调自动失效
|
||||
final myConnId = _connectionId;
|
||||
debugPrint('🔌 [TCP-connectBySwitch] 无现有连接,开始新建, connectionId=$myConnId');
|
||||
|
||||
|
||||
// debugPrint('🔌被动 [TCP] 开始连接:$host:$port'); // ✅ 必须看到这条
|
||||
_logger.logWithLevel('🔌被动 [TCP] 开始连接:$host:$port');
|
||||
_lastHost = host;
|
||||
@@ -1156,8 +1453,13 @@ class TcpClient {
|
||||
onDone: () {
|
||||
// 🔥 检查 connectionId,防止旧socket回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略',
|
||||
shouldLog: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
debugPrint('onDone [TCP] 被动连接已断开!_isSwitching=$_isSwitching');
|
||||
@@ -1170,7 +1472,9 @@ class TcpClient {
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ 被动[TCP] 发生错误:$e');
|
||||
@@ -1189,7 +1493,7 @@ class TcpClient {
|
||||
_connecting = false; // 🔥 连接失败,重置标志
|
||||
rethrow; // 向上抛出连接异常
|
||||
}
|
||||
|
||||
|
||||
// 🔥 重置 _connecting 和 isUserSwitch
|
||||
_connecting = false;
|
||||
isUserSwitch = false; // 🔥 关键:切换完成后重置,后续超时走普通重连路径
|
||||
@@ -1246,7 +1550,7 @@ class TcpClient {
|
||||
// 🔥 修复:使用 RemoteControlCubit.targetDevice,而不是传入的 deviceName
|
||||
final remoteControlCubit = GetIt.I<RemoteControlCubit>();
|
||||
final targetDevice = remoteControlCubit.state.targetDevice;
|
||||
|
||||
|
||||
if (targetDevice != null) {
|
||||
debugPrint('🔀 [TCP] 使用 targetDevice 进行切换: ${targetDevice.deviceName}');
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
@@ -1255,7 +1559,9 @@ class TcpClient {
|
||||
);
|
||||
} else {
|
||||
// 兜底:如果 targetDevice 为 null,使用传入的 deviceName
|
||||
debugPrint('⚠️ [TCP] targetDevice 为 null,使用传入的 deviceName: $deviceName');
|
||||
debugPrint(
|
||||
'⚠️ [TCP] targetDevice 为 null,使用传入的 deviceName: $deviceName',
|
||||
);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
"app",
|
||||
deviceName,
|
||||
@@ -1270,8 +1576,13 @@ class TcpClient {
|
||||
|
||||
void _handleDisconnectBySwitch(String deviceName) {
|
||||
_connectionId++; // 🔥 使旧socket的所有回调立即失效
|
||||
debugPrint('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId', shouldLog: true);
|
||||
debugPrint(
|
||||
'🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId',
|
||||
shouldLog: true,
|
||||
);
|
||||
stopHeartbeat();
|
||||
|
||||
_socket = null;
|
||||
|
||||
Reference in New Issue
Block a user