完善遥控权限、控制发送和急停反馈

This commit is contained in:
2026-11-21 14:37:46 +08:00
parent c284aefc7d
commit 9a8a42a0a1
55 changed files with 5009 additions and 1308 deletions

View File

@@ -59,6 +59,9 @@ class HttpApiConsts {
// GET,2=自主任务,3=远程遥控;路径 modeChage 沿用后端协议拼写。
static String get hostModeChange => "$baseUrl/iot/host/modeChage";
// GET,query: deviceId、eStop(1=请求急停,0=请求解除)。
static String get hostEmergencyStopChange => "$baseUrl/iot/host/eStopChange";
// 修改设备别名(只写 deviceAlias,deviceName 保持不变)
static String get updateDeviceAlias =>
"$baseUrl/forward/device/updateDeviceAlias";

View File

@@ -45,6 +45,10 @@ import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remot
import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart';
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/diff_steer_usecase.dart';
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_control_permission_usecase.dart';
import 'package:maibu_satabot_v2/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart';
import 'package:maibu_satabot_v2/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart';
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart';
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../features/auth/data/datasources/auth_http_datasource.dart';
@@ -390,6 +394,17 @@ Future<void> init() async {
() => RequestControlPermissionUseCase(sl()),
);
// 独立急停接口:仅注册数据/领域层,不自动请求或接入页面。
sl.registerLazySingleton(() => EmergencyStopRemoteDatasource(sl<Dio>()));
sl.registerLazySingleton<DeviceEmergencyStopRepository>(
() =>
DeviceEmergencyStopRepositoryImpl(sl<EmergencyStopRemoteDatasource>()),
);
sl.registerLazySingleton(
() =>
RequestDeviceEmergencyStopUseCase(sl<DeviceEmergencyStopRepository>()),
);
/// Home V2
sl.registerLazySingleton<HomeRemoteDataSource>(
() => HomeRemoteDataSourceImpl(),
@@ -574,6 +589,7 @@ Future<void> init() async {
sl<TcpClient>(), // TcpClient
sl(), // NetMessageDispatcher
sl(), // DeviceStatusBloc
requestEmergencyStop: sl<RequestDeviceEmergencyStopUseCase>(),
),
);

View File

@@ -0,0 +1,47 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'remote_control_diagnostics.dart';
/// Passive tracing only. Identifiers stay local and never enter HTTP/TCP data.
class ControlPermissionDiagnostics {
static final Object _scopeKey = Object();
static Map<String, Object?>? get context =>
Zone.current[_scopeKey] as Map<String, Object?>?;
static T scope<T>(Map<String, Object?> fields, T Function() action) =>
runZoned(
action,
zoneValues: {_scopeKey: Map<String, Object?>.of(fields)},
);
static Object? scalar(Object? value) =>
value == null || value is String || value is num || value is bool
? value
: '<${value.runtimeType}>';
/// Callers supply whitelisted fields, never tokens, headers, or raw packets.
static void event(String step, [Map<String, Object?> fields = const {}]) {
try {
final trace = RemoteControlDiagnostics.instance;
final record = <String, Object?>{
'time': DateTime.now().toIso8601String(),
...?context,
...fields,
'traceVersion': 1,
'permissionStep': step,
};
final startedUs = record['startedUs'];
if (startedUs is int) {
record['elapsedMs'] = (trace.elapsedUs - startedUs) ~/ 1000;
}
trace.event('permission_trace', record);
debugPrint('[权限链][$step] ${jsonEncode(record)}');
} catch (_) {
// Logging cannot interrupt permission, motion, or safety handling.
}
}
}

View File

@@ -0,0 +1,121 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
/// Passive motion tracing. This class never sends commands or awaits a network
/// operation. File writes are buffered and serialized separately from control.
class RemoteControlDiagnostics {
RemoteControlDiagnostics({Future<void> Function(String)? append})
: _appendOverride = append;
static RemoteControlDiagnostics instance = RemoteControlDiagnostics();
static final Object _frameKey = Object();
final Future<void> Function(String)? _appendOverride;
final Stopwatch _clock = Stopwatch()..start();
final String _run = DateTime.now().microsecondsSinceEpoch.toString();
final List<String> _pending = [];
Future<Directory>? _directory;
Future<void>? _inFlight;
Timer? _flushTimer;
int _sequence = 0;
int _frameSequence = 0;
int _sessionSequence = 0;
int _dropped = 0;
String? activeDevice;
int get elapsedUs => _clock.elapsedMicroseconds;
void begin(String? device, Map<String, Object?> configuration) {
activeDevice = device;
_sessionSequence++;
event('session_start', configuration);
}
void end(String reason) {
event('session_end', {'reason': reason});
activeDevice = null;
unawaited(flush());
}
/// Local correlation only; no identifiers are added to the wire protocol.
T frame<T>(String source, Map<String, Object?> fields, T Function() send) {
final context = <String, Object?>{
'session': _sessionSequence,
'device': activeDevice,
'frame': ++_frameSequence,
'source': source,
...fields,
};
return runZoned(send, zoneValues: {_frameKey: context});
}
void event(String stage, Map<String, Object?> fields) {
try {
final frame = Zone.current[_frameKey] as Map<String, Object?>?;
final record = <String, Object?>{
'time': DateTime.now().toIso8601String(),
'us': elapsedUs,
'run': _run,
'session': _sessionSequence,
'seq': ++_sequence,
'device': activeDevice,
if (frame != null) ...frame,
'stage': stage,
...fields,
};
for (final key in record.keys.toList()) {
final value = record[key];
if (value is double && !value.isFinite) record[key] = value.toString();
}
// A stalled filesystem cannot grow memory without bounds or block control.
if (_pending.length >= 2000) {
_pending.removeAt(0);
_dropped++;
}
_pending.add('${jsonEncode(record)}\n');
_flushTimer ??= Timer(const Duration(milliseconds: 500), () {
_flushTimer = null;
unawaited(flush());
});
} catch (_) {
// Diagnostics must never interrupt an input, control or safety callback.
}
}
Future<void> _append(String content) async {
final override = _appendOverride;
if (override != null) return override(content);
final directory = await (_directory ??= getApplicationDocumentsDirectory());
final day = DateTime.now().toIso8601String().substring(0, 10);
await File(
'${directory.path}/remote_control_$day.jsonl',
).writeAsString(content, mode: FileMode.append);
}
Future<void> flush() {
_flushTimer?.cancel();
_flushTimer = null;
return _inFlight ??= _drain().whenComplete(() => _inFlight = null);
}
Future<void> _drain() async {
while (_pending.isNotEmpty) {
final dropped = _dropped;
_dropped = 0;
final batch = _pending.join();
_pending.clear();
try {
await _append(
'${dropped == 0 ? '' : '${jsonEncode({'stage': 'diagnostic_overflow', 'dropped': dropped})}\n'}$batch',
);
} catch (_) {
// Mark missing records in the next successful write instead of silently
// making a logging failure look like a gap in TCP transmission.
_dropped += dropped + '\n'.allMatches(batch).length;
return;
}
}
}
}

View File

@@ -99,35 +99,37 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
controller = StreamController(
onListen: () {
// 先监听报文再订阅 Topic,接住订阅时立即到达的消息。
messageSubscription = messages.where((msg) => msg.topic == topic).listen(
(message) {
try {
final json = jsonDecode(message.payload);
if (json is! Map) return;
final payload = json['data'];
final data = payload is Map ? payload : json;
final battery = HostRealtimeMessageEntity.parseBatteryPercentage(
data['battery_percentage'],
);
lastBattery = battery ?? lastBattery;
controller.add(
(
battery: lastBattery,
controlMode: data['control_mode']?.toString().trim() ?? '',
),
);
} on FormatException {
// 忽略格式异常的单帧,等待下一次上报。
}
},
onError: controller.addError,
onDone: controller.close,
);
topicSubscription = mqttClient.subscribe(topic).catchError(
(Object error, StackTrace stackTrace) {
if (!controller.isClosed) controller.addError(error, stackTrace);
},
);
messageSubscription = messages
.where((msg) => msg.topic == topic)
.listen(
(message) {
try {
final json = jsonDecode(message.payload);
if (json is! Map) return;
final payload = json['data'];
final data = payload is Map ? payload : json;
final battery =
HostRealtimeMessageEntity.parseBatteryPercentage(
data['battery_percentage'],
);
lastBattery = battery ?? lastBattery;
controller.add((
battery: lastBattery,
controlMode: data['control_mode']?.toString().trim() ?? '',
));
} on FormatException {
// 忽略格式异常的单帧,等待下一次上报。
}
},
onError: controller.addError,
onDone: controller.close,
);
topicSubscription = mqttClient.subscribe(topic).catchError((
Object error,
StackTrace stackTrace,
) {
if (!controller.isClosed) controller.addError(error, stackTrace);
});
},
onCancel: () async {
await messageSubscription?.cancel();
@@ -154,7 +156,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
// 🔥 同一设备重复调用:去重,不重复订阅(参照 DroneOsdDataSource 已验证的模式)
if (_deviceSn == deviceSn && _subscription != null) {
debugPrint('${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn');
debugPrint(
'${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn',
);
return;
}
@@ -164,7 +168,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn');
debugPrint(
'${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn',
);
}
_deviceSn = deviceSn;
@@ -173,15 +179,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
_routeMsgCount = 0;
_hostMsgCount = 0;
// 先监听消息,接住订阅后立即到达的推送(包括 retained 消息)。
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
await mqttClient.subscribe(_realtimeTopic(deviceSn));
await mqttClient.subscribe(_locationTopic(deviceSn));
await mqttClient.subscribe(_routeTopic(deviceSn));
await mqttClient.subscribe(_hostRealtimeTopic(deviceSn));
// 消息流监听只建立一次,按 _deviceSn 过滤
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
debugPrint('${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn');
debugPrint(
'${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn',
);
debugPrint(' 车辆实时: ${_realtimeTopic(deviceSn)}');
debugPrint(' 定位: ${_locationTopic(deviceSn)}');
debugPrint(' 路径规划: ${_routeTopic(deviceSn)}');
@@ -196,7 +204,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn');
debugPrint(
'${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn',
);
_deviceSn = null;
}
@@ -206,12 +216,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
// 🔥 防串台:只处理当前监听设备的主题(mower/ 和 device/ 前缀都要匹配)
if (!message.topic.contains('mower/$sn/') &&
!message.topic.contains('device/$sn/')) return;
!message.topic.contains('device/$sn/'))
return;
// 🔥 第一阶段:打印原始报文,确认格式后再完善解析
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] ──────── 收到消息 ────────');
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] payload: ${message.payload}');
// 实时状态逐帧打印原始报文,在解析前确认急停字段是否实际下发。
if (message.topic == _realtimeTopic(sn) ||
message.topic == _hostRealtimeTopic(sn)) {
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
debugPrint('[MQTT-机器状态] payload 开始');
debugPrint(message.payload, wrapWidth: 800);
debugPrint('[MQTT-机器状态] payload 结束');
}
try {
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
@@ -224,9 +239,13 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
if (_vehicleMsgCount == 1) {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 车辆实时首帧到达: $sn');
}
debugPrint('${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个');
debugPrint(
'${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个',
);
for (final dp in vehicle.data) {
debugPrint('${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}');
debugPrint(
'${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}',
);
}
_vehicleController.add(vehicle);
}
@@ -238,7 +257,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
// 🔥 关键修复:坐标在 data 子对象中,不是顶层
final dataObj = jsonData['data'] as Map<String, dynamic>? ?? jsonData;
final location = MowerLocationEntity.fromJson(dataObj);
debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}');
// debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}');
_locationController.add(location);
} else if (message.topic.endsWith(_hostRealtimeSuffix)) {
// 🔥 主机实时(新增话题,纯附加):外层套信封,数据在 json.data,提取方式与定位一致
@@ -247,8 +266,14 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
debugPrint('${LogTime.now()} 🎉 [MQTT-主机实时] 首帧到达: $sn');
}
final dataObj = jsonData['data'] as Map<String, dynamic>? ?? jsonData;
final host = HostRealtimeMessageEntity.fromJson(dataObj);
debugPrint('${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 急停=${host.emergencyStop} 运动=${host.motion}');
final host = HostRealtimeMessageEntity.fromJson(
dataObj,
deviceSn: sn,
receivedAt: message.timestamp,
);
debugPrint(
'${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} emergency_stop存在=${dataObj.containsKey('emergency_stop')} 原始值=${dataObj['emergency_stop']} 急停解析值=${host.emergencyStop} 运动=${host.motion}',
);
_hostRealtimeController.add(host);
} else if (message.topic.endsWith(_routeSuffix)) {
_routeMsgCount++;
@@ -256,11 +281,15 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 路径规划首帧到达: $sn');
}
final routeMsg = RouteStatusEntity.fromJson(jsonData);
debugPrint('${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}');
debugPrint(
'${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}',
);
_routeController.add(routeMsg);
}
} catch (e) {
debugPrint('${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败: $e');
debugPrint(
'${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败 topic=${message.topic}: $e',
);
}
}

View File

@@ -5,6 +5,8 @@ import 'package:equatable/equatable.dart';
/// 报文外层套一层信封,真正数据在 `data` 子对象(由 DataSource 提取后传入)。
/// 字段与后端 Java 实体一一对应,采用防御式解析,缺字段用默认值兜底。
class HostRealtimeMessageEntity extends Equatable {
final String? deviceSn;
final DateTime? receivedAt;
final double batteryPercentage; // 实时电量百分比
final double batteryVoltage; // 实时电压
final double leftMotorCurrent; // 实时左电机电流
@@ -19,7 +21,7 @@ class HostRealtimeMessageEntity extends Equatable {
final double totalWorkDuration; // 累计作业时长
final double totalWorkDistance; // 累计作业里程
final String motion; // moving|stopped|blocked 运动状态
final bool emergencyStop; // 急停状态
final bool? emergencyStop; // 急停状态;null 表示未上报或值无效
final double leftTargetRpm; // 实时左电机目标转速
final double rightTargetRpm; // 实时右电机目标转速
final double leftMeasuredRpm; // 实时左电机测量转速
@@ -35,6 +37,8 @@ class HostRealtimeMessageEntity extends Equatable {
final Map<String, dynamic> rawData;
const HostRealtimeMessageEntity({
this.deviceSn,
this.receivedAt,
this.batteryPercentage = 0,
this.batteryVoltage = 0,
this.leftMotorCurrent = 0,
@@ -49,7 +53,7 @@ class HostRealtimeMessageEntity extends Equatable {
this.totalWorkDuration = 0,
this.totalWorkDistance = 0,
this.motion = '',
this.emergencyStop = false,
this.emergencyStop,
this.leftTargetRpm = 0,
this.rightTargetRpm = 0,
this.leftMeasuredRpm = 0,
@@ -64,9 +68,16 @@ class HostRealtimeMessageEntity extends Equatable {
});
/// [data] 为报文 `data` 子对象(由 DataSource 提取,与 MowerLocationEntity 一致)
factory HostRealtimeMessageEntity.fromJson(Map<String, dynamic> data) {
factory HostRealtimeMessageEntity.fromJson(
Map<String, dynamic> data, {
String? deviceSn,
DateTime? receivedAt,
}) {
return HostRealtimeMessageEntity(
batteryPercentage: parseBatteryPercentage(data['battery_percentage']) ?? 0,
deviceSn: deviceSn,
receivedAt: receivedAt,
batteryPercentage:
parseBatteryPercentage(data['battery_percentage']) ?? 0,
batteryVoltage: _toDouble(data['battery_voltage']),
leftMotorCurrent: _toDouble(data['left_motor_current']),
rightMotorCurrent: _toDouble(data['right_motor_current']),
@@ -115,40 +126,43 @@ class HostRealtimeMessageEntity extends Equatable {
return double.tryParse(value.toString()) ?? 0;
}
static bool _toBool(dynamic value) {
if (value == null) return false;
static bool? _toBool(dynamic value) {
if (value is bool) return value;
if (value is num) return value != 0;
final s = value.toString().toLowerCase();
return s == 'true' || s == '1';
if (value == 1) return true;
if (value == 0) return false;
final s = value?.toString().trim().toLowerCase();
if (s == 'true' || s == '1') return true;
if (s == 'false' || s == '0') return false;
return null;
}
@override
List<Object?> get props => [
batteryPercentage,
batteryVoltage,
leftMotorCurrent,
rightMotorCurrent,
leftMotorTemperature,
rightMotorTemperature,
mainTemperature,
yaw,
pitch,
headingStatus,
totalWorkArea,
totalWorkDuration,
totalWorkDistance,
motion,
emergencyStop,
leftTargetRpm,
rightTargetRpm,
leftMeasuredRpm,
rightMeasuredRpm,
leftMotorRpm,
rightMotorRpm,
roll,
controlMode,
linearSpeed,
angularSpeed,
];
batteryPercentage,
batteryVoltage,
leftMotorCurrent,
rightMotorCurrent,
leftMotorTemperature,
rightMotorTemperature,
mainTemperature,
yaw,
pitch,
headingStatus,
totalWorkArea,
totalWorkDuration,
totalWorkDistance,
motion,
emergencyStop,
leftTargetRpm,
rightTargetRpm,
leftMeasuredRpm,
rightMeasuredRpm,
leftMotorRpm,
rightMotorRpm,
roll,
controlMode,
linearSpeed,
angularSpeed,
rawData,
];
}

View File

@@ -51,7 +51,7 @@ class DeviceDataPoint extends Equatable {
factory DeviceDataPoint.fromJson(Map<String, dynamic> json) {
return DeviceDataPoint(
name: json['name'] as String? ?? '',
value: json['value'] as String? ?? '',
value: json['value']?.toString() ?? '',
unit: json['unit'] as String? ?? '',
);
}

View 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);
}
}

View File

@@ -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;