集成双 MQTT 客户端实现设备实时数据监控(未测试)

1.集成两个独立的 MQTT 客户端,支持 WebSocket 和 TCP 协议
2.实现无人机/机场 OSD 实时监控(ws://1.95.137.212:8083/mqtt)
3.实现任务状态消息订阅(tcp://1.95.137.212:59020)
4.采用清洁架构设计,分层清晰(Domain → Data → Presentation)
This commit is contained in:
2026-06-18 16:41:02 +08:00
parent a6143f2ba7
commit 06718ed957
27 changed files with 1645 additions and 27 deletions

View File

@@ -4,6 +4,7 @@ import '../../../../core/app/app_user_cubit.dart';
import '../../../../core/logging/i_logger_service.dart';
import '../../../../core/network/error_handler.dart';
import '../../../../features/v2/site/presentation/cubit/site_cubit.dart';
import '../../domain/entities/device_task_entity.dart'; // 🔥 新增
import '../../domain/usecases/cancel_task_usecase.dart';
import '../../domain/usecases/get_device_task_pool_usecase.dart';
import '../../domain/usecases/pause_task_usecase.dart';
@@ -70,23 +71,32 @@ class DeviceTaskCubit extends Cubit<DeviceTaskState> {
));
},
(taskList) {
// 过滤出当前设备的任务
final deviceTasks = taskList
.where((task) => task.deviceId == deviceId)
.toList();
// 取第一个任务(或根据业务逻辑选择)
final currentTask = deviceTasks.isNotEmpty ? deviceTasks.first : null;
// 🔥 过滤出当前设备 + 活跃状态的任务(NEW, EXECUTING, PAUSE)
final activeTasks = taskList.where((task) {
// 1. 设备号匹配
if (task.deviceId != deviceId) return false;
// 2. 状态过滤:只保留新建、执行中、暂停中的任务
final status = task.taskStatus;
return status == 'NEW' || // 新建
status == 'EXECUTING' || // 执行中
status == 'PAUSE'; // 暂停中
}).toList();
_logger.logWithLevel(
'✅ 找到 ${deviceTasks.length} 个任务,当前任务ID: ${currentTask?.id}',
'✅ 找到 ${activeTasks.length} 个活跃任务',
);
// 🔥 如果有多个任务,保存所有选项供用户选择
// 如果只有1个,直接选中
final currentTask = activeTasks.isNotEmpty ? activeTasks.first : null;
emit(state.copyWith(
isLoading: false,
taskPool: taskList,
currentTask: currentTask,
currentTaskId: currentTask?.id,
activeTasks: activeTasks, // 🔥 保存所有活跃任务列表
));
},
);
@@ -304,6 +314,15 @@ class DeviceTaskCubit extends Cubit<DeviceTaskState> {
_logger.logWithLevel('🔄 更新当前任务ID: $taskId');
}
/// 🔥 手动选择任务(用户从弹窗中选择)
void selectTask(DeviceTaskEntity task) {
_logger.logWithLevel('✅ 用户选择任务ID: ${task.id}, 状态: ${task.taskStatus}');
emit(state.copyWith(
currentTask: task,
currentTaskId: task.id,
));
}
/// 清除当前任务
void clearCurrentTask() {
emit(state.copyWith(

View File

@@ -12,6 +12,7 @@ class DeviceTaskState extends Equatable {
final List<DeviceTaskEntity> taskPool;
final DeviceTaskEntity? currentTask;
final int? currentTaskId;
final List<DeviceTaskEntity> activeTasks; // 🔥 活跃任务列表(供用户选择)
final bool isLoading;
final String? errorMessage;
final DeviceTaskOperationType operationType;
@@ -21,6 +22,7 @@ class DeviceTaskState extends Equatable {
this.taskPool = const [],
this.currentTask,
this.currentTaskId,
this.activeTasks = const [], // 🔥 默认空列表
this.isLoading = false,
this.errorMessage,
this.operationType = DeviceTaskOperationType.none,
@@ -31,6 +33,7 @@ class DeviceTaskState extends Equatable {
List<DeviceTaskEntity>? taskPool,
DeviceTaskEntity? currentTask,
int? currentTaskId,
List<DeviceTaskEntity>? activeTasks, // 🔥 新增
bool? isLoading,
String? errorMessage,
DeviceTaskOperationType? operationType,
@@ -40,6 +43,7 @@ class DeviceTaskState extends Equatable {
taskPool: taskPool ?? this.taskPool,
currentTask: currentTask ?? this.currentTask,
currentTaskId: currentTaskId ?? this.currentTaskId,
activeTasks: activeTasks ?? this.activeTasks, // 🔥 新增
isLoading: isLoading ?? this.isLoading,
errorMessage: errorMessage,
operationType: operationType ?? this.operationType,
@@ -52,6 +56,7 @@ class DeviceTaskState extends Equatable {
taskPool,
currentTask,
currentTaskId,
activeTasks, // 🔥 新增
isLoading,
errorMessage,
operationType,

View File

@@ -13,6 +13,7 @@ import '../../../../core/app/app_user_cubit.dart';
import '../../../../core/router/route_paths.dart';
import '../../../devices/presentation/bloc/devices_cubit.dart';
import '../../../devices/presentation/bloc/devices_state.dart';
import '../../../remote_control/presentation/bloc/remote_control_cubit.dart'; // 🔥 添加 RemoteControlCubit
// 导入你的主题文件以获取 offWhite
// import 'package:maibu_satabot_v2/core/theme/app_theme.dart';
@@ -126,11 +127,18 @@ class ImmersionHeader extends StatelessWidget {
children: [
_buildCircleIcon(Icons.sync, () {
// 1. 触发 Cubit 请求最新设备列表
// 假设你的 username 存储在 AuthCubit 或类似的全局状态中
final username =
context.read<AppUserCubit>().state.user?.username ??
"";
context.read<DevicesCubit>().fetchAllDevices(username);
// 🔥 修复:检查是否已有 targetDevice
final remoteControlState = context.read<RemoteControlCubit>().state;
if (remoteControlState.targetDevice == null) {
debugPrint('🔄 [ImmersionHeader] 无 targetDevice,开始加载设备列表');
context.read<DevicesCubit>().fetchAllDevices(username);
} else {
debugPrint('✅ [ImmersionHeader] 已有 targetDevice: ${remoteControlState.targetDevice!.deviceName},跳过加载');
}
// 2. 弹出窗口(窗口内部会根据状态显示转圈或列表)
_showDeviceSwitcher(context);

View File

@@ -36,6 +36,9 @@ import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_statu
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_state.dart';
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_task_entity.dart'; // 🔥 新增
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_task_cubit.dart'; // 🔥 新增
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_task_state.dart'; // 🔥 新增
import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart';
import 'package:maibu_satabot_v2/features/home/presentation/widgets/BottomDirectionLine.dart';
import 'package:maibu_satabot_v2/features/home/presentation/widgets/common/commonFn.dart';
@@ -1978,6 +1981,102 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
);
}
/// 🔥 显示任务选择弹窗
Future<DeviceTaskEntity?> _showTaskSelectionDialog(
List<DeviceTaskEntity> tasks,
) async {
return showDialog<DeviceTaskEntity>(
context: context,
barrierDismissible: false,
builder: (dialogContext) => AlertDialog(
title: const Text('选择任务'),
content: SizedBox(
width: double.maxFinite,
child: ListView.builder(
shrinkWrap: true,
itemCount: tasks.length,
itemBuilder: (context, index) {
final task = tasks[index];
// 状态标签颜色
Color statusColor;
String statusText;
switch (task.taskStatus) {
case 'NEW':
statusColor = Colors.blue;
statusText = '新建';
break;
case 'EXECUTING':
statusColor = Colors.green;
statusText = '执行中';
break;
case 'PAUSE':
statusColor = Colors.orange;
statusText = '暂停中';
break;
default:
statusColor = Colors.grey;
statusText = task.taskStatusTranslate;
}
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
title: Text('任务 #${task.id}'),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('设备号: ${task.deviceId}'),
Row(
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: statusColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(4),
),
child: Text(
statusText,
style: TextStyle(
color: statusColor,
fontSize: 12,
),
),
),
if (task.createTime != null) ...[
const SizedBox(width: 8),
Text(
task.createTime!,
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
],
],
),
],
),
onTap: () {
Navigator.pop(dialogContext, task);
},
),
);
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, null),
child: const Text('取消'),
),
],
),
);
}
/// 开始作业
void _startWork() async {
// 🔥 V2 适配:使用接口方式执行作业,不再使用 TCP
@@ -2010,13 +2109,53 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
return;
}
// 5. 打印请求参数日志
// 🔥 5. 先过滤出活跃任务,让用户选择
debugPrint('🔍 [开始作业] 正在查询活跃任务...');
final taskCubit = sl<DeviceTaskCubit>();
await taskCubit.fetchAndFilterTask(deviceId);
// 等待一下让状态更新
await Future.delayed(const Duration(milliseconds: 100));
final activeTasks = taskCubit.state.activeTasks;
debugPrint('✅ [开始作业] 找到 ${activeTasks.length} 个活跃任务');
if (activeTasks.isEmpty) {
_showPageToast(
message: "当前设备没有活跃任务(新建/执行中/暂停中)",
type: ToastType.warn,
);
return;
}
// 🔥 6. 如果有多条任务,显示选择弹窗
DeviceTaskEntity? selectedTask;
if (activeTasks.length > 1) {
debugPrint('⚠️ [开始作业] 有多个活跃任务,显示选择弹窗');
selectedTask = await _showTaskSelectionDialog(activeTasks);
if (selectedTask == null) {
// 用户取消选择
debugPrint('❌ [开始作业] 用户取消选择任务');
return;
}
// 用户选择了任务,更新 cubit
taskCubit.selectTask(selectedTask);
} else {
// 只有1条任务,直接使用
selectedTask = activeTasks.first;
debugPrint('✅ [开始作业] 自动选择唯一任务 #${selectedTask.id}');
}
debugPrint('📋 [开始作业] 最终选择的任务ID: ${selectedTask.id}, 状态: ${selectedTask.taskStatus}');
// 7. 打印请求参数日志
debugPrint('🚀 [开始作业] 请求参数:');
debugPrint(' ├─ deviceId: $deviceId');
debugPrint(' ├─ routeId: $routeId');
debugPrint(' ├─ taskId: ${selectedTask.id}');
debugPrint(' └─ siteId: $siteId');
// 6. 更新UI状态
// 8. 更新UI状态
setState(() {
isStopWork = false;
isStartWork = true;
@@ -2026,11 +2165,11 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
gctracePoint?.clear();
});
// 7. 更新应用状态
// 9. 更新应用状态
context.read<DevicesCubit>().updateAppState(AppState.routePlanning);
try {
// 8. 调用接口创建设备任务
// 10. 调用接口创建设备任务
final result = await sl<CreateDeviceTaskUseCase>().execute(
deviceId: deviceId,
routeId: routeId,
@@ -2107,18 +2246,63 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
/// 暂停作业
void _pauseWork() async {
// 🔥 获取设备ID和taskId
final targetDevice = context.read<RemoteControlCubit>().state.targetDevice;
final deviceId = targetDevice?.deviceName;
if (deviceId == null || deviceId.isEmpty) {
_showPageToast(message: "请先选择一个设备", type: ToastType.info);
return;
}
final taskCubit = sl<DeviceTaskCubit>();
final taskId = taskCubit.state.currentTaskId;
if (taskId == null) {
_showPageToast(message: "无可用任务", type: ToastType.warn);
return;
}
debugPrint('⏸️ [暂停作业] deviceId: $deviceId, taskId: $taskId');
setState(() {
isStartWork = false; // 🔥 关键:停止作业标志
_workStatus = WorkStatus.paused;
});
_saveDataToLocal(); // 🔥 保存暂停状态
// 🔥 调用接口暂停任务(注释掉原有的 TCP 方式)
try {
await taskCubit.pauseTask(deviceId);
_showPageToast(message: "作业已暂停", type: ToastType.success);
} catch (e) {
debugPrint('❌ [暂停作业] 异常: $e');
_showPageToast(message: "暂停失败: $e", type: ToastType.error);
}
// 原有的 TCP 方式(已注释)
//context.read<DevicesCubit>().updateAppState(AppState.none);
await context.read<DevicesCubit>().pauseRoutePlanning();
//await context.read<DevicesCubit>().pauseRoutePlanning();
}
void _stopWork() async {
_logger.log('按下停止按钮');
// 🔥 获取设备ID和taskId
final targetDevice = context.read<RemoteControlCubit>().state.targetDevice;
final deviceId = targetDevice?.deviceName;
if (deviceId == null || deviceId.isEmpty) {
_showPageToast(message: "请先选择一个设备", type: ToastType.info);
return;
}
final taskCubit = sl<DeviceTaskCubit>();
final taskId = taskCubit.state.currentTaskId;
if (taskId == null) {
_showPageToast(message: "无可用任务", type: ToastType.warn);
return;
}
debugPrint('⏹️ [停止作业] deviceId: $deviceId, taskId: $taskId');
if (mounted) {
setState(() {
isStartWork = false;
@@ -2133,7 +2317,18 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
});
}
await context.read<DevicesCubit>().stopRoutePlanning();
// 🔥 调用接口取消任务(注释掉原有的 TCP 方式)
try {
await taskCubit.cancelTask(deviceId);
_showPageToast(message: "作业已停止", type: ToastType.success);
} catch (e) {
debugPrint('❌ [停止作业] 异常: $e');
_showPageToast(message: "停止失败: $e", type: ToastType.error);
}
// 原有的 TCP 方式(已注释)
//await context.read<DevicesCubit>().stopRoutePlanning();
_saveDataToLocal();
await Future.delayed(const Duration(milliseconds: 300));
if (mounted) {
@@ -2152,12 +2347,40 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
/// 继续作业
void _resumeWork() async {
// 🔥 获取设备ID和taskId
final targetDevice = context.read<RemoteControlCubit>().state.targetDevice;
final deviceId = targetDevice?.deviceName;
if (deviceId == null || deviceId.isEmpty) {
_showPageToast(message: "请先选择一个设备", type: ToastType.info);
return;
}
final taskCubit = sl<DeviceTaskCubit>();
final taskId = taskCubit.state.currentTaskId;
if (taskId == null) {
_showPageToast(message: "无可用任务", type: ToastType.warn);
return;
}
debugPrint('▶️ [继续作业] deviceId: $deviceId, taskId: $taskId');
setState(() {
_workStatus = WorkStatus.working;
});
_saveDataToLocal(); // 🔥 保存暂停状态
context.read<DevicesCubit>().updateAppState(AppState.routePlanning);
await context.read<DevicesCubit>().resumeRoutePlanning();
// 🔥 调用接口恢复任务(注释掉原有的 TCP 方式)
try {
await taskCubit.recoveryTask(deviceId);
_showPageToast(message: "作业已恢复", type: ToastType.success);
} catch (e) {
debugPrint('❌ [继续作业] 异常: $e');
_showPageToast(message: "恢复失败: $e", type: ToastType.error);
}
// 原有的 TCP 方式(已注释)
//context.read<DevicesCubit>().updateAppState(AppState.routePlanning);
//await context.read<DevicesCubit>().resumeRoutePlanning();
}
void _showDeleteConfirmDialog(PlotData plot, Function(PlotData) onDelete) {
@@ -2284,7 +2507,147 @@ class _MapPageEnterpriseState extends State<MapPageEnterprise> {
const SizedBox(height: 16),
// 2. 错误提示(如果加载失败)
// 🔥 3. 当前任务信息显示(可点击重新选择)
BlocBuilder<DeviceTaskCubit, DeviceTaskState>(
builder: (context, taskState) {
final currentTask = taskState.currentTask;
if (currentTask == null) {
return const SizedBox.shrink();
}
// 状态标签颜色
Color statusColor;
String statusText;
switch (currentTask.taskStatus) {
case 'NEW':
statusColor = Colors.blue;
statusText = '新建';
break;
case 'EXECUTING':
statusColor = Colors.green;
statusText = '执行中';
break;
case 'PAUSE':
statusColor = Colors.orange;
statusText = '暂停中';
break;
default:
statusColor = Colors.grey;
statusText = currentTask.taskStatusTranslate;
}
return GestureDetector(
onTap: () async {
// 🔥 点击后显示所有活跃任务供用户选择
final activeTasks = taskState.activeTasks;
if (activeTasks.isEmpty) {
_showPageToast(
message: "没有可用的任务",
type: ToastType.warn,
);
return;
}
final selectedTask = await _showTaskSelectionDialog(
activeTasks,
);
if (selectedTask != null) {
// 用户选择了新任务,更新 cubit
sl<DeviceTaskCubit>().selectTask(selectedTask);
_showPageToast(
message: "已切换到任务 #${selectedTask.id}",
type: ToastType.success,
);
}
},
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFF5F7FA),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: const Color(0xFF165DFF).withOpacity(0.2),
),
),
child: Row(
children: [
Icon(
Icons.assignment_outlined,
color: const Color(0xFF165DFF),
size: 20,
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'当前任务: #${currentTask.id}',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Color(0xFF1D2129),
),
),
const SizedBox(height: 4),
Row(
children: [
Text(
'设备: ${currentTask.deviceId}',
style: const TextStyle(
fontSize: 12,
color: Color(0xFF4E5969),
),
),
const SizedBox(width: 12),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: statusColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(
4,
),
),
child: Text(
statusText,
style: TextStyle(
color: statusColor,
fontSize: 11,
fontWeight: FontWeight.w500,
),
),
),
],
),
],
),
),
Icon(
Icons.swap_horiz,
color: const Color(0xFF165DFF),
size: 18,
),
const SizedBox(width: 4),
const Text(
'切换',
style: TextStyle(
fontSize: 12,
color: Color(0xFF165DFF),
),
),
],
),
),
);
},
),
const SizedBox(height: 16),
// 4. 错误提示(如果加载失败)
if (startWorkList.isEmpty || headingStatus == 0)
Row(
crossAxisAlignment: CrossAxisAlignment.start,

View File

@@ -10,6 +10,7 @@ import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubi
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_state.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart';
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; // 🔥 添加 RemoteControlCubit
class MachineDetailsPage extends StatefulWidget {
final DeviceEntity? device;
@@ -157,7 +158,15 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
Navigator.pop(context);
if (context.mounted) {
final username = context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
// 🔥 修复:检查是否已有 targetDevice
final remoteControlState = context.read<RemoteControlCubit>().state;
if (remoteControlState.targetDevice == null) {
debugPrint('🔄 [MachineDetails] 无 targetDevice,开始加载设备列表');
context.read<DevicesCubit>().fetchAllDevices(username);
} else {
debugPrint('✅ [MachineDetails] 已有 targetDevice: ${remoteControlState.targetDevice!.deviceName},跳过加载');
}
}
},
),
@@ -187,7 +196,14 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
Navigator.pop(context);
if (context.mounted) {
final username = context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
// 🔥 修复:检查是否已有 targetDevice
final remoteControlState = context.read<RemoteControlCubit>().state;
if (remoteControlState.targetDevice == null) {
debugPrint('🔄 [MachineDetails AppBar] 无 targetDevice,开始加载设备列表');
context.read<DevicesCubit>().fetchAllDevices(username);
} else {
debugPrint('✅ [MachineDetails AppBar] 已有 targetDevice: ${remoteControlState.targetDevice!.deviceName},跳过加载');
}
}
},
),
@@ -612,7 +628,15 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context).translate('machine_details.unbind_success').replaceAll('%s', _deviceName)), backgroundColor: Colors.green, duration: const Duration(seconds: 2)));
final username = context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
// 🔥 修复:检查是否已有 targetDevice
final remoteControlState = context.read<RemoteControlCubit>().state;
if (remoteControlState.targetDevice == null) {
debugPrint('🔄 [MachineDetails Unbind] 无 targetDevice,开始加载设备列表');
context.read<DevicesCubit>().fetchAllDevices(username);
} else {
debugPrint('✅ [MachineDetails Unbind] 已有 targetDevice: ${remoteControlState.targetDevice!.deviceName},跳过加载');
}
}
} else if (state.errorMessage?.isNotEmpty == true && !state.isLoading) {
if (context.mounted) {
@@ -636,9 +660,9 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
}
// 处理结果:放宽条件,只要无错误信息就认为成功(不管loading)
print(
"处理修改名称结果,operationType: ${state.operationType}, isLoading: ${state.isLoading}, errorMessage: ${state.errorMessage},state.errorMessage?.isEmpty: ${state.errorMessage?.isEmpty}",
);
// print(
// "处理修改名称结果,operationType: ${state.operationType}, isLoading: ${state.isLoading}, errorMessage: ${state.errorMessage},state.errorMessage?.isEmpty: ${state.errorMessage?.isEmpty}",
// );
// 核心修改:去掉!state.isLoading的判断
if (state.errorMessage?.isEmpty == true) {

View File

@@ -0,0 +1,86 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/foundation.dart';
import '../../../../../../core/network/mqtt/domain/repositories/task_message_repository.dart';
import 'device_realtime_event.dart';
import 'device_realtime_state.dart';
class DeviceRealtimeBloc extends Bloc<DeviceRealtimeEvent, DeviceRealtimeState> {
final TaskMessageRepository _taskMessageRepository;
StreamSubscription? _realtimeSubscription;
String? _currentDeviceId;
DeviceRealtimeBloc(this._taskMessageRepository) : super(const DeviceRealtimeInitial()) {
on<DeviceRealtimeStartListen>(_onStartListen);
on<DeviceRealtimeStopListen>(_onStopListen);
on<DeviceRealtimeDataUpdated>(_onDataUpdated);
}
Future<void> _onStartListen(
DeviceRealtimeStartListen event,
Emitter<DeviceRealtimeState> emit,
) async {
if (_currentDeviceId == event.deviceId && state is DeviceRealtimeLoaded) {
debugPrint('⚠️ [DeviceRealtimeBloc] 已在监听该设备,跳过');
return;
}
emit(const DeviceRealtimeLoading());
final result = await _taskMessageRepository.startListening(
deviceId: event.deviceId,
);
result.fold(
(failure) {
emit(DeviceRealtimeError(failure.message));
},
(_) {
_currentDeviceId = event.deviceId;
_realtimeSubscription?.cancel();
_realtimeSubscription = _taskMessageRepository.realTimeMessageStream.listen(
(message) {
add(DeviceRealtimeDataUpdated(message.toJson()));
},
onError: (error) {
debugPrint('❌ [DeviceRealtimeBloc] 实时数据流错误: $error');
},
);
debugPrint('✅ [DeviceRealtimeBloc] 开始监听设备: ${event.deviceId}');
},
);
}
void _onStopListen(
DeviceRealtimeStopListen event,
Emitter<DeviceRealtimeState> emit,
) {
_realtimeSubscription?.cancel();
_realtimeSubscription = null;
_taskMessageRepository.stopListening();
_currentDeviceId = null;
debugPrint('🔕 [DeviceRealtimeBloc] 停止监听');
emit(const DeviceRealtimeInitial());
}
void _onDataUpdated(
DeviceRealtimeDataUpdated event,
Emitter<DeviceRealtimeState> emit,
) {
final newState = DeviceRealtimeLoaded.fromRealtimeMessage(event.realtimeData);
emit(newState);
debugPrint('📊 [DeviceRealtimeBloc] 数据更新 - 电压: ${newState.voltage}V, 电量: ${newState.battery}%');
}
@override
Future<void> close() {
_realtimeSubscription?.cancel();
_taskMessageRepository.stopListening();
return super.close();
}
}

View File

@@ -0,0 +1,30 @@
import 'package:equatable/equatable.dart';
abstract class DeviceRealtimeEvent extends Equatable {
const DeviceRealtimeEvent();
@override
List<Object?> get props => [];
}
class DeviceRealtimeStartListen extends DeviceRealtimeEvent {
final String deviceId;
const DeviceRealtimeStartListen(this.deviceId);
@override
List<Object?> get props => [deviceId];
}
class DeviceRealtimeStopListen extends DeviceRealtimeEvent {
const DeviceRealtimeStopListen();
}
class DeviceRealtimeDataUpdated extends DeviceRealtimeEvent {
final Map<String, dynamic> realtimeData;
const DeviceRealtimeDataUpdated(this.realtimeData);
@override
List<Object?> get props => [realtimeData];
}

View File

@@ -0,0 +1,146 @@
import 'package:equatable/equatable.dart';
abstract class DeviceRealtimeState extends Equatable {
const DeviceRealtimeState();
@override
List<Object?> get props => [];
}
class DeviceRealtimeInitial extends DeviceRealtimeState {
const DeviceRealtimeInitial();
}
class DeviceRealtimeLoading extends DeviceRealtimeState {
const DeviceRealtimeLoading();
}
class DeviceRealtimeLoaded extends DeviceRealtimeState {
final Map<String, dynamic> realtimeData;
final double? voltage;
final double? battery;
final double? latitude;
final double? longitude;
final double? yaw;
final double? pitch;
final double? roll;
final double? leftMotorTemp;
final double? rightMotorTemp;
final double? chipTemp;
final double? cuttingSpeed;
final int? satelliteCnt;
final int? controlMode;
const DeviceRealtimeLoaded({
required this.realtimeData,
this.voltage,
this.battery,
this.latitude,
this.longitude,
this.yaw,
this.pitch,
this.roll,
this.leftMotorTemp,
this.rightMotorTemp,
this.chipTemp,
this.cuttingSpeed,
this.satelliteCnt,
this.controlMode,
});
factory DeviceRealtimeLoaded.fromRealtimeMessage(Map<String, dynamic> rawData) {
final data = rawData['data'] as List<dynamic>? ?? [];
double? getValueByName(String name) {
final item = data.firstWhere(
(item) => item['name'] == name,
orElse: () => null,
);
if (item == null) return null;
return double.tryParse(item['value'].toString());
}
int? getIntValueByName(String name) {
final value = getValueByName(name);
return value?.toInt();
}
return DeviceRealtimeLoaded(
realtimeData: rawData,
voltage: getValueByName('voltage'),
battery: getValueByName('battery'),
latitude: getValueByName('latitude'),
longitude: getValueByName('longitude'),
yaw: getValueByName('yaw'),
pitch: getValueByName('pitch'),
roll: getValueByName('roll'),
leftMotorTemp: getValueByName('leftMotorTemp'),
rightMotorTemp: getValueByName('rightMotorTemp'),
chipTemp: getValueByName('chipTemp'),
cuttingSpeed: getValueByName('cuttingSpeed'),
satelliteCnt: getIntValueByName('satelliteCnt'),
controlMode: getIntValueByName('controlMode'),
);
}
DeviceRealtimeLoaded copyWith({
Map<String, dynamic>? realtimeData,
double? voltage,
double? battery,
double? latitude,
double? longitude,
double? yaw,
double? pitch,
double? roll,
double? leftMotorTemp,
double? rightMotorTemp,
double? chipTemp,
double? cuttingSpeed,
int? satelliteCnt,
int? controlMode,
}) {
return DeviceRealtimeLoaded(
realtimeData: realtimeData ?? this.realtimeData,
voltage: voltage ?? this.voltage,
battery: battery ?? this.battery,
latitude: latitude ?? this.latitude,
longitude: longitude ?? this.longitude,
yaw: yaw ?? this.yaw,
pitch: pitch ?? this.pitch,
roll: roll ?? this.roll,
leftMotorTemp: leftMotorTemp ?? this.leftMotorTemp,
rightMotorTemp: rightMotorTemp ?? this.rightMotorTemp,
chipTemp: chipTemp ?? this.chipTemp,
cuttingSpeed: cuttingSpeed ?? this.cuttingSpeed,
satelliteCnt: satelliteCnt ?? this.satelliteCnt,
controlMode: controlMode ?? this.controlMode,
);
}
@override
List<Object?> get props => [
realtimeData,
voltage,
battery,
latitude,
longitude,
yaw,
pitch,
roll,
leftMotorTemp,
rightMotorTemp,
chipTemp,
cuttingSpeed,
satelliteCnt,
controlMode,
];
}
class DeviceRealtimeError extends DeviceRealtimeState {
final String message;
const DeviceRealtimeError(this.message);
@override
List<Object?> get props => [message];
}