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

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

@@ -12,6 +12,7 @@ import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_e
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart';
import '../../../../core/logging/i_logger_service.dart';
import '../../../../core/logging/remote_control_diagnostics.dart';
import '../../../../core/logging/log_time.dart';
import '../../../../core/network/net_message_dispatcher.dart';
import '../../../../core/network/tcp/tcp_client.dart';
@@ -60,6 +61,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
/// 当前实时快照的设备身份,供入口模式确认使用(只读)。
String? get listeningDeviceSn => _currentListeningSn;
/// 仅由主机帧刷新,定位/其他状态不会延长急停状态有效期。
({String sn, bool? active, DateTime receivedAt})? emergencyStopReading;
// 🔥 MQTT机器状态收帧计数(用于链路日志)
int _mqttVehicleFrameCount = 0;
int _mqttLocationFrameCount = 0;
@@ -125,7 +129,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
final is02 = p.command == 0x02;
if (is02) {
_packetSeq++;
debugPrint('📥 [0x02] #$_packetSeq 收到原始TCP包 | payload长度=${p.payload.length} | ${DateTime.now().toString().substring(11, 19)}');
debugPrint(
'📥 [0x02] #$_packetSeq 收到原始TCP包 | payload长度=${p.payload.length} | ${DateTime.now().toString().substring(11, 19)}',
);
}
return is02;
})
@@ -134,7 +140,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
final result = utf8.decode(p.payload, allowMalformed: true);
return result;
} catch (e) {
debugPrint('❌ [0x02] #$_packetSeq 解码失败: $e, payload前20字节=${p.payload.take(20).toList()}');
debugPrint(
'❌ [0x02] #$_packetSeq 解码失败: $e, payload前20字节=${p.payload.take(20).toList()}',
);
return '';
}
})
@@ -150,7 +158,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
final fields = message.trim().split(',');
if (fields.length < 18) {
debugPrint('⚠️ [0x02] #$_packetSeq 字段不足:${fields.length},期望≥18, 原始数据前100字符=${message.substring(0, message.length > 100 ? 100 : message.length)}');
debugPrint(
'⚠️ [0x02] #$_packetSeq 字段不足:${fields.length},期望≥18, 原始数据前100字符=${message.substring(0, message.length > 100 ? 100 : message.length)}',
);
// 🔥 错误不节流,立即emit以便UI显示错误
if (!isClosed) {
emit(DeviceStatusError('字段不足,期望≥18,实际:${fields.length}'));
@@ -161,7 +171,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
final status = RunningStatusEntity.fromFields(fields);
final gps = GPSEntity(status.latitude, status.longitude);
debugPrint('✅ [0x02] #$_packetSeq 解析成功 | 字段数=${fields.length} | 电压=${status.voltage}V 电量=${status.battery}% 控制模式=${status.controlMode} | 节流等待${_throttleDuration.inMilliseconds}ms');
debugPrint(
'✅ [0x02] #$_packetSeq 解析成功 | 字段数=${fields.length} | 电压=${status.voltage}V 电量=${status.battery}% 控制模式=${status.controlMode} | 节流等待${_throttleDuration.inMilliseconds}ms',
);
// 🔥 缓存最新数据用于节流发射
_cachedStatus = RunningStatusEntity(
@@ -228,11 +240,14 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
return;
}
debugPrint('${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn');
debugPrint(
'${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn',
);
// 🔥 换设备兜底:SN 变化时清空上一个设备的缓存与状态,
// 防止旧坐标通过 copyWith(base) 残留污染新设备数据(即使入口漏调 Reset 也能兜住)
if (_currentListeningSn != deviceSn) {
emergencyStopReading = null;
_throttleTimer?.cancel();
_throttleTimer = null;
_cachedStatus = null;
@@ -241,7 +256,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
if (!isClosed) {
emit(DeviceStatusInitial());
}
debugPrint('${LogTime.now()} 🧹 [DeviceStatusBloc] 切换设备,已清空旧缓存: $deviceSn');
debugPrint(
'${LogTime.now()} 🧹 [DeviceStatusBloc] 切换设备,已清空旧缓存: $deviceSn',
);
}
// 按SN订阅(数据源内部自动退旧订新、同SN去重)
@@ -268,16 +285,27 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
debugPrint(
'${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_mqttVehicleFrameCount帧 type=${message.type} 数据点=${message.data.length}',
);
// TODO 第二阶段:将数据点映射到 RunningStatusEntity 字段,复用500ms节流emit
// 沿用车辆数据点现有 cuttingSpeed 字段;主机话题没有割刀反馈。
// 缺失或非法时清空,不能把默认 0 当成设备已停刀。
final cutterRpm = message.getValueByName('cuttingSpeed');
final base = _cachedStatus ?? const RunningStatusEntity();
_cachedStatus = base.copyWith(
knifeCuttingSpeed: cutterRpm != null && cutterRpm.isFinite
? cutterRpm.toString()
: '',
);
if (_throttleTimer == null || !_throttleTimer!.isActive) {
_throttleTimer = Timer(_throttleDuration, _emitCachedStatus);
}
});
_mqttLocationSubscription ??= _mowerRealtimeRepo.locationStream.listen((
location,
) {
_mqttLocationFrameCount++;
debugPrint(
'${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}',
);
// debugPrint(
// '${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}',
// );
// 🔥 核心:用 MQTT location 数据更新缓存并节流 emit
if (location.isValid) {
@@ -310,6 +338,50 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
_mqttHostSubscription ??= _mowerRealtimeRepo.hostRealtimeStream.listen((
host,
) {
final sn = _currentListeningSn;
if (host.deviceSn != null && host.deviceSn != sn) return;
if (sn != null) {
emergencyStopReading = (
sn: sn,
active: host.emergencyStop,
receivedAt: host.receivedAt ?? DateTime.now(),
);
}
final trace = RemoteControlDiagnostics.instance;
if (trace.activeDevice != null &&
trace.activeDevice == _currentListeningSn) {
final raw = host.rawData;
trace.event('host_telemetry', {
'telemetryDevice': _currentListeningSn,
'linearMps': raw.containsKey('linear_speed')
? host.linearSpeed
: null,
'angularRadps': raw.containsKey('angular_speed')
? host.angularSpeed
: null,
'leftTargetRpm': raw.containsKey('left_target_rpm')
? host.leftTargetRpm
: null,
'rightTargetRpm': raw.containsKey('right_target_rpm')
? host.rightTargetRpm
: null,
'leftMeasuredRpm': raw.containsKey('left_measured_rpm')
? host.leftMeasuredRpm
: null,
'rightMeasuredRpm': raw.containsKey('right_measured_rpm')
? host.rightMeasuredRpm
: null,
'leftCurrent': raw.containsKey('left_motor_current')
? host.leftMotorCurrent
: null,
'rightCurrent': raw.containsKey('right_motor_current')
? host.rightMotorCurrent
: null,
'emergency': raw['emergency_stop'],
'controlMode': raw['control_mode'],
'motion': raw['motion'],
});
}
final base = _cachedStatus ?? RunningStatusEntity();
_cachedStatus = base.copyWith(
voltage: host.batteryVoltage,
@@ -331,6 +403,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 代价:若 host 帧偶发漏带该字段,此栏会在真值与「未知」间跳动;
// 现场若出现闪烁,说明 host 帧字段不稳定,应从后端侧解决而非在此兜底。
controlMode: host.controlMode,
emergencyStop: host.emergencyStop,
workingArea: host.totalWorkArea.toString(),
// 🔥 供全功能模式(pv_control)展示:累计作业里程 + host 已推数据标记
totalWorkDistance: host.totalWorkDistance,
@@ -338,15 +411,19 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
linearSpeed: host.linearSpeed,
angularSpeed: host.angularSpeed,
hostDataReceived: true,
hostRealtime: host,
);
// 🔥 host 无坐标:GPS 缺省时用当前经纬度占位,保证能即时刷新(不覆盖 location 已写入的真坐标)
_cachedGps ??= GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude);
debugPrint(
'${LogTime.now()} 🛰️ [MQTT-主机实时] 已合并 → 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 线速度=${host.linearSpeed}m/s 角速度=${host.angularSpeed}rad/s',
_cachedGps ??= GPSEntity(
_cachedStatus!.latitude,
_cachedStatus!.longitude,
);
// debugPrint(
// '${LogTime.now()} 🛰️ [MQTT-主机实时] 已合并 → 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 线速度=${host.linearSpeed}m/s 角速度=${host.angularSpeed}rad/s',
// );
// 500ms 节流:与 location/车辆实时 发射链路一致
if (_throttleTimer == null || !_throttleTimer!.isActive) {
_throttleTimer = Timer(_throttleDuration, () {
@@ -355,7 +432,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
}
});
debugPrint('${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn');
debugPrint(
'${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn',
);
_logger.log('✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn');
}
@@ -440,10 +519,12 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 🔥 无论缓存是否有效,都必须 emit 触发 BlocBuilder 重建
if (!isClosed) {
emit(DeviceStatusUpdated(
_cachedStatus ?? RunningStatusEntity(),
_cachedGps ?? GPSEntity(0.0, 0.0),
));
emit(
DeviceStatusUpdated(
_cachedStatus ?? RunningStatusEntity(),
_cachedGps ?? GPSEntity(0.0, 0.0),
),
);
debugPrint('📤 [DeviceStatusBloc] 已 emit 完成信号,触发 UI 更新');
}
@@ -473,17 +554,28 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
int _fixStatusToQual(String? fixStatus, int fallback) {
if (fixStatus == null) return fallback;
switch (fixStatus) {
case 'no_fix': return 0;
case 'single': return 1;
case 'dgnss': return 2;
case 'ins': return 3;
case 'rtk_fixed': return 4;
case 'rtk_float': return 5;
case 'single_no_heading': return 6;
case 'dgnss_no_heading': return 7;
case 'rtk_fixed_no_heading': return 8;
case 'rtk_float_no_heading': return 9;
default: return fallback;
case 'no_fix':
return 0;
case 'single':
return 1;
case 'dgnss':
return 2;
case 'ins':
return 3;
case 'rtk_fixed':
return 4;
case 'rtk_float':
return 5;
case 'single_no_heading':
return 6;
case 'dgnss_no_heading':
return 7;
case 'rtk_fixed_no_heading':
return 8;
case 'rtk_float_no_heading':
return 9;
default:
return fallback;
}
}
@@ -491,13 +583,14 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 🔥 放宽:允许仅有机器状态(host 先到、GPS 未到)时也能刷新 UI
void _emitCachedStatus() {
if (_cachedStatus != null && !isClosed) {
final gps = _cachedGps ??
final gps =
_cachedGps ??
GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude);
// 控制模式为空串 = 后端从未给过,日志里显式标出来,免得和 0 混看
final controlModeLog = _cachedStatus!.controlMode.isEmpty
? '--(未收到)'
: _cachedStatus!.controlMode;
debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}');
// final controlModeLog = _cachedStatus!.controlMode.isEmpty
// ? '--(未收到)'
// : _cachedStatus!.controlMode;
// debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}');
emit(DeviceStatusUpdated(_cachedStatus!, gps));
}
}
@@ -507,6 +600,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
DeviceStatusReset event,
Emitter<DeviceStatusState> emit,
) async {
emergencyStopReading = null;
debugPrint('🔄 [DeviceStatusBloc] 收到重置事件:清空状态 - 当前状态:${state.runtimeType}');
_logger.log(
'🔄 [DeviceStatusBloc] 收到重置事件:清空状态 - 当前状态:${state.runtimeType}',
@@ -601,10 +695,12 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 🔥 关键:无论缓存是否有效,都必须 emit 触发 BlocBuilder 重建
if (!isClosed) {
emit(DeviceStatusUpdated(
_cachedStatus ?? RunningStatusEntity(),
_cachedGps ?? GPSEntity(0.0, 0.0),
));
emit(
DeviceStatusUpdated(
_cachedStatus ?? RunningStatusEntity(),
_cachedGps ?? GPSEntity(0.0, 0.0),
),
);
debugPrint('📤 [DeviceStatusBloc] 已 emit 停止信号,触发 UI 更新');
}
@@ -642,6 +738,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 🔥 重置设备ID
_currentDeviceId = null;
_currentListeningSn = null;
emergencyStopReading = null;
return Future.value();
}