绑定设备+覆盖模式+控制显示bug+在线更新

This commit is contained in:
2026-09-01 08:59:20 +08:00
parent 0fa67a127b
commit 61bce2c1cf
49 changed files with 2424 additions and 720 deletions

View File

@@ -7,10 +7,12 @@ import 'package:maibu_satabot_v2/features/devices/domain/entities/running_status
import 'package:maibu_satabot_v2/features/devices/domain/entities/gps_entity.dart';
import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart';
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/task_message_repository.dart';
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart';
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_entity.dart';
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart';
import '../../../../core/logging/i_logger_service.dart';
import '../../../../core/logging/log_time.dart';
import '../../../../core/network/net_message_dispatcher.dart';
import '../../../../core/network/tcp/tcp_client.dart';
import 'device_status_event.dart';
@@ -20,6 +22,10 @@ import 'devices_cubit.dart';
// 定义全局的TaskMessageRepository获取方式
TaskMessageRepository get _taskMessageRepo => GetIt.I<TaskMessageRepository>();
// 🔥 MQTT机器状态数据源(替代TCP 0x02)
MowerRealtimeRepository get _mowerRealtimeRepo =>
GetIt.I<MowerRealtimeRepository>();
class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
final NetMessageDispatcher _dispatcher;
final TcpClient tcpClient; // 🔥 新增:直接访问 TcpClient
@@ -30,6 +36,10 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
StreamSubscription? _mqttArriveSubscription;
StreamSubscription? _mqttStatusSubscription;
// 🔥 MQTT机器状态订阅(车辆实时+定位,替代TCP 0x02)
StreamSubscription? _mqttVehicleSubscription;
StreamSubscription? _mqttLocationSubscription;
// 🔥 节流相关:500ms节流控制0x02数据推送频率
Timer? _throttleTimer;
static const _throttleDuration = Duration(milliseconds: 500);
@@ -42,11 +52,17 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 🔥 当前监听的设备ID
String? _currentDeviceId;
// 🔥 MQTT机器状态收帧计数(用于链路日志)
int _mqttVehicleFrameCount = 0;
int _mqttLocationFrameCount = 0;
DeviceStatusBloc(this._dispatcher, {TcpClient? client})
: tcpClient = client ?? GetIt.I<TcpClient>(),
super(DeviceStatusInitial()) {
// 🔥 核心改动:直接在构造函数中建立TCP监听,类似RemoteControlCubit
_initDirectTcpListener();
// 🔥 已停用:机器状态数据源已改为MQTT(见 startMqttRealtimeListening,
// 由用户切换设备时触发)。TCP监听逻辑保留,回滚时取消下行注释即可。
// _initDirectTcpListener();
// 🔥 初始化MQTT到达点监听
_initMqttArriveListener();
@@ -191,6 +207,86 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
_logger.log('✅ [DeviceStatusBloc] 直接TCP监听器已建立完成');
}
/// 🔥 MQTT机器状态监听(替代TCP 0x02数据源)
///
/// [deviceSn] 与TCP时代 switchDevice / connectBySwitch 的设备号获取方式一致
/// (即 DeviceEntity.deviceName),由用户点击设备列表切换设备时调用。
///
/// 第一阶段:订阅并打印原始报文;确认格式后在第二阶段解析为
/// RunningStatusEntity + GPSEntity,复用现有500ms节流逻辑。
void startMqttRealtimeListening(String deviceSn) {
if (deviceSn.isEmpty) {
debugPrint('${LogTime.now()} ⚠️ [DeviceStatusBloc] MQTT订阅跳过:设备SN为空');
return;
}
debugPrint('${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn');
// 按SN订阅(数据源内部自动退旧订新、同SN去重)
_mowerRealtimeRepo.startListening(deviceSn: deviceSn).then((result) {
result.fold(
(failure) => debugPrint(
'${LogTime.now()} ❌ [DeviceStatusBloc] MQTT机器状态订阅失败: ${failure.message}',
),
(_) => debugPrint(
'${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态订阅完成: $deviceSn',
),
);
});
// 切换设备时重置收帧计数,便于观察新设备的首帧与频率
_mqttVehicleFrameCount = 0;
_mqttLocationFrameCount = 0;
// 流监听只建立一次,第一阶段仅打印解析结果验证链路
_mqttVehicleSubscription ??= _mowerRealtimeRepo.vehicleStream.listen((
message,
) {
_mqttVehicleFrameCount++;
debugPrint(
'${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_mqttVehicleFrameCount帧 type=${message.type} 数据点=${message.data.length}',
);
// TODO 第二阶段:将数据点映射到 RunningStatusEntity 字段,复用500ms节流emit
});
_mqttLocationSubscription ??= _mowerRealtimeRepo.locationStream.listen((
location,
) {
_mqttLocationFrameCount++;
debugPrint(
'${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}',
);
// 🔥 核心:用 MQTT location 数据更新缓存并节流 emit
if (location.isValid) {
// 更新 _cachedGps
_cachedGps = GPSEntity(location.latitude!, location.longitude!);
// 更新 _cachedStatus 中的航向角和坐标(复用已有缓存或新建空壳)
final base = _cachedStatus ?? RunningStatusEntity();
_cachedStatus = base.copyWith(
latitude: location.latitude!,
longitude: location.longitude!,
yaw: location.heading ?? base.yaw,
);
// 500ms节流:与 TCP 0x02 时代逻辑一致
if (_throttleTimer == null || !_throttleTimer!.isActive) {
_throttleTimer = Timer(_throttleDuration, () {
_emitCachedStatus();
});
}
} else {
debugPrint(
'${LogTime.now()} ⚠️ [MQTT-location] 坐标无效,跳过 - lat=${location.latitude}, lng=${location.longitude}',
);
}
});
debugPrint('${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn');
_logger.log('✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn');
}
// 🔥 初始化MQTT到达点监听
void _initMqttArriveListener() {
debugPrint('🔗 [DeviceStatusBloc] 初始化MQTT到达点监听器');
@@ -304,7 +400,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
// 🔥 节流发射:500ms到期后发射缓存的最新数据
void _emitCachedStatus() {
if (_cachedStatus != null && _cachedGps != null && !isClosed) {
debugPrint('📤 [0x02] 节流发射 | 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${_cachedGps!.latitude}, ${_cachedGps!.longitude}) | ${DateTime.now().toString().substring(11, 19)}');
debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${_cachedGps!.latitude}, ${_cachedGps!.longitude}) yaw=${_cachedStatus!.yaw} | ${DateTime.now().toString().substring(11, 19)}');
emit(DeviceStatusUpdated(_cachedStatus!, _cachedGps!));
}
}
@@ -423,6 +519,12 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
_mqttStatusSubscription?.cancel();
_mqttStatusSubscription = null;
// 🔥 清理MQTT机器状态订阅
_mqttVehicleSubscription?.cancel();
_mqttVehicleSubscription = null;
_mqttLocationSubscription?.cancel();
_mqttLocationSubscription = null;
// 🔥 清理节流timer和缓存
_throttleTimer?.cancel();
_throttleTimer = null;

View File

@@ -34,21 +34,17 @@ class DeviceTaskCubit extends Cubit<DeviceTaskState> {
final userCubit = GetIt.I<AppUserCubit>();
final user = userCubit.state.user;
if (user == null) {
emit(state.copyWith(
isLoading: false,
errorMessage: '用户未登录',
));
emit(state.copyWith(isLoading: false, errorMessage: '用户未登录'));
return;
}
// 获取场站ID
// 获取场站信息(siteId 和 orgId 都从当前场站取)
final siteCubit = GetIt.I<SiteCubit>();
final siteId = siteCubit.state.selectedSite?.id;
final selectedSite = siteCubit.state.selectedSite;
final siteId = selectedSite?.id;
final orgId = selectedSite?.orgId ?? 0;
if (siteId == null) {
emit(state.copyWith(
isLoading: false,
errorMessage: '未选择场站',
));
emit(state.copyWith(isLoading: false, errorMessage: '未选择场站'));
return;
}
@@ -57,125 +53,153 @@ class DeviceTaskCubit extends Cubit<DeviceTaskState> {
GetDeviceTaskPoolParams(
userId: user.userId ?? '',
siteId: siteId,
orgId: user.orgId ?? 0,
orgId: orgId,
),
);
result.fold(
(failure) {
_logger.logWithLevel('❌ 获取任务池失败: ${failure.message}');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
},
(taskList) {
// 🔥 过滤出当前设备 + 活跃状态的任务(NEW, EXECUTING, PAUSE)
// 🔥 过滤出当前设备 + 活跃状态的任务(NEW, EXECUTING, PAUSE, CANCELING, FAILED)
final activeTasks = taskList.where((task) {
// 1. 设备号匹配
if (task.deviceId != deviceId) return false;
// 2. 状态过滤:只保留新建、执行中、暂停中的任务
// 2. 状态过滤:保留新建、执行中、暂停中、取消中、执行失败的任务
final status = task.taskStatus;
return status == 'NEW' || // 新建
status == 'EXECUTING' || // 执行中
status == 'PAUSE'; // 暂停中
return status == 'NEW' || // 新建
status == 'EXECUTING' || // 执行中
status == 'PAUSE' || // 暂停中
status == 'CANCELING' || // 取消中(用户可处理)
status == 'FAILED'; // 执行失败(用户可恢复或取消)
}).toList();
_logger.logWithLevel(
'✅ 找到 ${activeTasks.length} 个活跃任务',
'✅ [fetchAndFilterTask] deviceId=$deviceId, 任务池总数=${taskList.length}, 过滤后活跃任务数=${activeTasks.length}',
);
for (final t in taskList) {
_logger.logWithLevel(
' - taskId=${t.id}, deviceId=${t.deviceId}, status=${t.taskStatus}',
);
}
// 🔥 如果有多个任务,保存所有选项供用户选择
// 如果只有1个,直接选中
final currentTask = activeTasks.isNotEmpty ? activeTasks.first : null;
emit(state.copyWith(
isLoading: false,
taskPool: taskList,
currentTask: currentTask,
currentTaskId: currentTask?.id,
activeTasks: activeTasks,
));
emit(
state.copyWith(
isLoading: false,
taskPool: taskList,
currentTask: currentTask,
currentTaskId: currentTask?.id,
activeTasks: activeTasks,
),
);
},
);
} catch (e) {
_logger.logWithLevel('❌ 获取任务池异常: $e');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
}
}
/// 取消任务
Future<void> cancelTask(String deviceId) async {
Future<void> cancelTask(String deviceId, {bool forceCancel = true}) async {
final taskId = state.currentTaskId;
if (taskId == null) {
emit(state.copyWith(errorMessage: '无可用任务'));
return;
}
emit(state.copyWith(
isLoading: true,
operationType: DeviceTaskOperationType.cancel,
));
emit(
state.copyWith(
isLoading: true,
operationType: DeviceTaskOperationType.cancel,
),
);
try {
final userCubit = GetIt.I<AppUserCubit>();
final user = userCubit.state.user;
final siteCubit = GetIt.I<SiteCubit>();
final siteId = siteCubit.state.selectedSite?.id;
final selectedSite = siteCubit.state.selectedSite;
final siteId = selectedSite?.id;
final orgId = selectedSite?.orgId ?? 0;
if (user == null || siteId == null) {
emit(state.copyWith(
isLoading: false,
errorMessage: '参数不完整',
operationType: DeviceTaskOperationType.none,
));
emit(
state.copyWith(
isLoading: false,
errorMessage: '参数不完整',
operationType: DeviceTaskOperationType.none,
),
);
return;
}
final params = CancelTaskParams(
deviceId: deviceId,
taskId: taskId,
orgId: user.orgId ?? 0,
orgId: orgId,
siteId: siteId,
forceCancel: forceCancel,
);
_logger.logWithLevel('[取消任务] 请求: POST /iot/deviceTask/cancelTask');
_logger.logWithLevel('[取消任务] 参数: deviceId=$deviceId, taskId=$taskId, orgId=${user.orgId ?? 0}, siteId=$siteId');
_logger.logWithLevel(
'[取消任务] 参数: deviceId=$deviceId, taskId=$taskId, orgId=$orgId, siteId=$siteId, forceCancel=$forceCancel',
);
final result = await _cancelTaskUseCase.call(params);
result.fold(
(failure) {
_logger.logWithLevel('[取消任务] 响应失败: ${failure.message}');
_logger.logWithLevel('❌ 取消任务失败: ${failure.message}');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
},
(success) {
_logger.logWithLevel('[取消任务] 响应成功: $success');
_logger.logWithLevel('✅ 取消任务成功');
emit(state.copyWith(
isLoading: false,
operationType: DeviceTaskOperationType.none,
));
emit(
state.copyWith(
isLoading: false,
operationType: DeviceTaskOperationType.none,
),
);
},
);
} catch (e) {
_logger.logWithLevel('❌ 取消任务异常: $e');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
}
}
@@ -187,64 +211,78 @@ class DeviceTaskCubit extends Cubit<DeviceTaskState> {
return;
}
emit(state.copyWith(
isLoading: true,
operationType: DeviceTaskOperationType.pause,
));
emit(
state.copyWith(
isLoading: true,
operationType: DeviceTaskOperationType.pause,
),
);
try {
final userCubit = GetIt.I<AppUserCubit>();
final user = userCubit.state.user;
final siteCubit = GetIt.I<SiteCubit>();
final siteId = siteCubit.state.selectedSite?.id;
final selectedSite = siteCubit.state.selectedSite;
final siteId = selectedSite?.id;
final orgId = selectedSite?.orgId ?? 0;
if (user == null || siteId == null) {
emit(state.copyWith(
isLoading: false,
errorMessage: '参数不完整',
operationType: DeviceTaskOperationType.none,
));
emit(
state.copyWith(
isLoading: false,
errorMessage: '参数不完整',
operationType: DeviceTaskOperationType.none,
),
);
return;
}
final params2 = PauseTaskParams(
deviceId: deviceId,
taskId: taskId,
orgId: user.orgId ?? 0,
orgId: orgId,
siteId: siteId,
);
_logger.logWithLevel('[暂停任务] 请求: POST /iot/deviceTask/pauseTask');
_logger.logWithLevel('[暂停任务] 参数: deviceId=$deviceId, taskId=$taskId, orgId=${user.orgId ?? 0}, siteId=$siteId');
_logger.logWithLevel(
'[暂停任务] 参数: deviceId=$deviceId, taskId=$taskId, orgId=$orgId, siteId=$siteId',
);
final result = await _pauseTaskUseCase.call(params2);
result.fold(
(failure) {
_logger.logWithLevel('[暂停任务] 响应失败: ${failure.message}');
_logger.logWithLevel('❌ 暂停任务失败: ${failure.message}');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
},
(success) {
_logger.logWithLevel('[暂停任务] 响应成功: $success');
_logger.logWithLevel('✅ 暂停任务成功');
emit(state.copyWith(
isLoading: false,
operationType: DeviceTaskOperationType.none,
));
emit(
state.copyWith(
isLoading: false,
operationType: DeviceTaskOperationType.none,
),
);
},
);
} catch (e) {
_logger.logWithLevel('❌ 暂停任务异常: $e');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
}
}
@@ -256,88 +294,111 @@ class DeviceTaskCubit extends Cubit<DeviceTaskState> {
return;
}
emit(state.copyWith(
isLoading: true,
operationType: DeviceTaskOperationType.recovery,
));
emit(
state.copyWith(
isLoading: true,
operationType: DeviceTaskOperationType.recovery,
),
);
try {
final userCubit = GetIt.I<AppUserCubit>();
final user = userCubit.state.user;
final siteCubit = GetIt.I<SiteCubit>();
final siteId = siteCubit.state.selectedSite?.id;
final selectedSite = siteCubit.state.selectedSite;
final siteId = selectedSite?.id;
final orgId = selectedSite?.orgId ?? 0;
if (user == null || siteId == null) {
emit(state.copyWith(
isLoading: false,
errorMessage: '参数不完整',
operationType: DeviceTaskOperationType.none,
));
emit(
state.copyWith(
isLoading: false,
errorMessage: '参数不完整',
operationType: DeviceTaskOperationType.none,
),
);
return;
}
final params3 = RecoveryTaskParams(
deviceId: deviceId,
taskId: taskId,
orgId: user.orgId ?? 0,
orgId: orgId,
siteId: siteId,
);
_logger.logWithLevel('[恢复任务] 请求: POST /iot/deviceTask/recoveryTask');
_logger.logWithLevel('[恢复任务] 参数: deviceId=$deviceId, taskId=$taskId, orgId=${user.orgId ?? 0}, siteId=$siteId');
_logger.logWithLevel(
'[恢复任务] 参数: deviceId=$deviceId, taskId=$taskId, orgId=$orgId, siteId=$siteId',
);
final result = await _recoveryTaskUseCase.call(params3);
result.fold(
(failure) {
_logger.logWithLevel('[恢复任务] 响应失败: ${failure.message}');
_logger.logWithLevel('❌ 恢复任务失败: ${failure.message}');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(failure.message),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
},
(data) {
_logger.logWithLevel('[恢复任务] 响应成功: $data');
_logger.logWithLevel('✅ 恢复任务成功: $data');
emit(state.copyWith(
isLoading: false,
operationType: DeviceTaskOperationType.none,
));
emit(
state.copyWith(
isLoading: false,
operationType: DeviceTaskOperationType.none,
),
);
},
);
} catch (e) {
_logger.logWithLevel('❌ 恢复任务异常: $e');
emit(state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
));
emit(
state.copyWith(
isLoading: false,
errorMessage: ErrorHandler.getErrorMessage(e),
operationType: DeviceTaskOperationType.none,
shouldShowError: true, // 🔥 标记需要显示错误弹窗
),
);
}
}
/// 更新当前任务ID(当选择新航线时调用)
void updateCurrentTaskId(int taskId) {
emit(state.copyWith(currentTaskId: taskId));
_logger.logWithLevel('🔄 更新当前任务ID: $taskId');
// 🔥 只有 activeTasks 非空时才设置 currentTask,避免信息栏一直显示
DeviceTaskEntity? taskEntity;
if (state.activeTasks.isNotEmpty) {
taskEntity = state.activeTasks.firstWhere(
(t) => t.id == taskId,
orElse: () => DeviceTaskEntity(
id: taskId,
deviceId: '',
taskStatus: 'EXECUTING',
taskStatusTranslate: '执行中',
),
);
}
emit(state.copyWith(currentTaskId: taskId, currentTask: taskEntity));
_logger.logWithLevel(
'🔄 更新当前任务ID: $taskId, activeTasks: ${state.activeTasks.length}, currentTask: ${taskEntity?.taskStatus ?? "null"}',
);
}
/// 🔥 手动选择任务(用户从弹窗中选择)
void selectTask(DeviceTaskEntity task) {
_logger.logWithLevel('✅ 用户选择任务ID: ${task.id}, 状态: ${task.taskStatus}');
emit(state.copyWith(
currentTask: task,
currentTaskId: task.id,
));
emit(state.copyWith(currentTask: task, currentTaskId: task.id));
}
/// 清除当前任务
void clearCurrentTask() {
emit(state.copyWith(
currentTask: null,
currentTaskId: null,
));
emit(state.copyWith(currentTask: null, currentTaskId: null));
_logger.logWithLevel('🧹 清除当前任务');
}

View File

@@ -16,6 +16,7 @@ import 'package:maibu_satabot_v2/features/devices/domain/usecases/update_devicen
import '../../../../core/consts/tcp_consts.dart';
import '../../../../core/logging/i_logger_service.dart';
import '../../../../core/logging/log_time.dart';
import '../../../../core/network/tcp/tcp_client.dart';
import '../../../../core/network/mqtt/domain/repositories/task_message_repository.dart';
import '../../data/models/device_add_path_point_model.dart';
@@ -268,6 +269,7 @@ class DevicesCubit extends Cubit<DevicesState> {
/// 切换设备
Future<void> switchDevice(DeviceEntity device) async {
debugPrint('${LogTime.now()} 👆 [DevicesCubit] 开始切换设备: ${device.deviceName}');
// 保持现有列表,只改 loading
emit(state.copyWith(isLoading: true));
@@ -276,6 +278,7 @@ class DevicesCubit extends Cubit<DevicesState> {
result.fold(
// 失败处理
(l) {
debugPrint('${LogTime.now()} ❌ [DevicesCubit] 切换设备失败: ${device.deviceName}, 原因: ${l.message}');
emit(state.copyWith(isLoading: false, errorMessage: l.message));
selectDevice(device);
},
@@ -288,7 +291,12 @@ class DevicesCubit extends Cubit<DevicesState> {
// 重置设备状态 Bloc,清除旧设备图表数据
_deviceStatusBloc.add(DeviceStatusReset());
debugPrint('✅ 新设备切换完成(HTTP-only,无新TCP连接): ${device.deviceName}');
// 🔥 机器状态数据源已切换为MQTT:用与TCP相同的方式获取设备号(deviceName),
// 订阅 mower/{sn}/property/* 主题(内部自动退订旧设备、同SN去重)
debugPrint('${LogTime.now()} 📡 [DevicesCubit] HTTP切换成功,开始MQTT订阅: ${device.deviceName}');
_deviceStatusBloc.startMqttRealtimeListening(device.deviceName);
debugPrint('${LogTime.now()} ✅ 新设备切换完成(HTTP-only,无新TCP连接): ${device.deviceName}');
emit(state.copyWith(isLoading: false, selectedDevice: device));
},
@@ -378,7 +386,7 @@ class DevicesCubit extends Cubit<DevicesState> {
emit(state.copyWith(isLoading: false, errorMessage: failure.message));
},
(records) {
// print('🔍 [DevicesCubit] 加载成功,记录数: ${records.length}');
print('🔍 [DevicesCubit] selectBySiteId 加载成功,记录数: ${records.length}');
// 将 WorkRecordEntity 转换为 Map<String, dynamic> 以兼容现有UI
final mappedRecords = records.map((record) {
// 🔥 核心修复:根据 jsonData 类型决定存储方式
@@ -390,14 +398,27 @@ class DevicesCubit extends Cubit<DevicesState> {
} else if (record.jsonData is WorkRecordJsonData) {
jsonDataStr = _workRecordJsonDataToJson(record.jsonData as WorkRecordJsonData);
}
return <String, dynamic>{
final mapped = <String, dynamic>{
'id': record.id.toString(),
'workName': record.workName,
'imgUrl': record.imgUrl ?? '',
'jsonData': jsonDataStr,
};
print(' ├─ [${record.workName}] id=${record.id}, jsonData长度=${jsonDataStr?.length ?? "null"}');
// 打印 jsonData 内部的 path/outer 信息
if (jsonDataStr != null && jsonDataStr.isNotEmpty) {
try {
final decoded = jsonDecode(jsonDataStr);
if (decoded is Map) {
print(' │ path类型=${decoded['path']?.runtimeType}, outer类型=${decoded['outer']?.runtimeType}, planModel=${decoded['planModel']}');
if (decoded['path'] is List) print(' │ path长度=${(decoded['path'] as List).length}');
if (decoded['outer'] is List) print(' │ outer长度=${(decoded['outer'] as List).length}');
}
} catch (_) {}
}
return mapped;
}).toList();
// print('🔍 [DevicesCubit] 转换后的数据: $mappedRecords');
print('🔍 [DevicesCubit] 转换完成,emit workRecords 数量: ${mappedRecords.length}');
emit(state.copyWith(isLoading: false, workRecords: mappedRecords));
},
);
@@ -439,15 +460,36 @@ class DevicesCubit extends Cubit<DevicesState> {
/// 加载指定作业名的路径数据
Future<void> loadSelectedPath(String workName) async {
emit(state.copyWith(isLoading: true));
debugPrint('📡 [loadSelectedPath] 开始查询, workName=$workName');
try {
final result = await _selectWorkRecordUseCase.call(workName);
result.fold(
(failure) => emit(
state.copyWith(isLoading: false, errorMessage: failure.message),
),
(data) => emit(state.copyWith(isLoading: false, pathData: data)),
(failure) {
debugPrint('❌ [loadSelectedPath] 接口失败: ${failure.message}');
emit(
state.copyWith(isLoading: false, errorMessage: failure.message),
);
},
(data) {
debugPrint('✅ [loadSelectedPath] 接口成功, 记录数: ${data.length}');
if (data.isNotEmpty) {
final first = data.first;
debugPrint(' ├─ 第一条记录 keys: ${first.keys.toList()}');
debugPrint(' ├─ path 类型: ${first['path']?.runtimeType}, 长度: ${(first['path'] as List?)?.length ?? "null"}');
debugPrint(' ├─ outer 类型: ${first['outer']?.runtimeType}, 长度: ${(first['outer'] as List?)?.length ?? "null"}');
debugPrint(' └─ planModel: ${first['planModel']}');
if (first['path'] is List && (first['path'] as List).isNotEmpty) {
debugPrint(' └─ path[0]: ${(first['path'] as List).first}');
}
if (first['outer'] is List && (first['outer'] as List).isNotEmpty) {
debugPrint(' └─ outer[0]: ${(first['outer'] as List).first}');
}
}
emit(state.copyWith(isLoading: false, pathData: data));
},
);
} catch (e) {
debugPrint('❌ [loadSelectedPath] 异常: $e');
emit(state.copyWith(isLoading: false, errorMessage: e.toString()));
}
}