完善自主作业下发、暂停恢复和轨迹保留
This commit is contained in:
@@ -2406,6 +2406,11 @@
|
||||
"task_query_failed": "Could not load tasks",
|
||||
"other_route_active": "The device has a task for another route ({route}). Handle it in the task queue first.",
|
||||
"dispatch_failed": "Could not dispatch work",
|
||||
"dispatch_mode_title": "Set work mode",
|
||||
"dispatch_mode_description": "Set autonomous work mode before dispatching the task. The task will be dispatched once the mode is set.",
|
||||
"dispatch_mode_confirm": "Set mode",
|
||||
"dispatch_mode_sending": "Setting mode…",
|
||||
"dispatch_mode_failed": "Could not set the work mode. Please try again.",
|
||||
"dispatched_route": "Work dispatched: {route}",
|
||||
"no_pausing_task": "No task can be paused",
|
||||
"pause_title": "Confirm pause",
|
||||
|
||||
@@ -92,6 +92,7 @@
|
||||
"app_name": "飒沓·星枢",
|
||||
|
||||
"device_control_mode": {
|
||||
"remote_retry_hint": "如果遥控失败,请退出后重试",
|
||||
"cancel_to_preview": "取消并预览",
|
||||
"preview_status": "画面预览,确认模式后可遥控",
|
||||
"confirm_mode": "确认模式",
|
||||
@@ -2407,6 +2408,11 @@
|
||||
"task_query_failed": "任务查询失败",
|
||||
"other_route_active": "设备上已有其它路线的任务({route}),请先在「任务队列」处理",
|
||||
"dispatch_failed": "作业下发失败",
|
||||
"dispatch_mode_title": "下发作业模式",
|
||||
"dispatch_mode_description": "请先手动下发自主作业模式,成功后将继续下发任务。",
|
||||
"dispatch_mode_confirm": "下发模式",
|
||||
"dispatch_mode_sending": "正在下发模式…",
|
||||
"dispatch_mode_failed": "模式下发失败,请重试。",
|
||||
"dispatched_route": "作业已下发:{route}",
|
||||
"no_pausing_task": "当前没有可暂停的任务",
|
||||
"pause_title": "暂停作业 · 确认",
|
||||
@@ -2534,7 +2540,7 @@
|
||||
"stop": "停止作业",
|
||||
"view_status": "查看状态",
|
||||
"robot_status_opened": "已展开「机器人信息」运行状态",
|
||||
"resume": "继续 / 断点续作",
|
||||
"resume": "恢复任务",
|
||||
"view_records": "查看作业记录",
|
||||
"new_task": "选择新任务",
|
||||
"camera_front": "前置",
|
||||
|
||||
25
lib/core/di/adapters/device_task_control_adapter.dart
Normal file
25
lib/core/di/adapters/device_task_control_adapter.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
import '../../../features/autonomous_work/domain/entities/work_session_models.dart';
|
||||
import '../../../features/devices/presentation/bloc/device_task_cubit.dart';
|
||||
|
||||
/// 只在装配边界连接现有 Cubit,不复制暂停/恢复的接口、参数或错误处理。
|
||||
class DeviceTaskControlAdapter {
|
||||
DeviceTaskControlAdapter(this.cubit);
|
||||
|
||||
final DeviceTaskCubit cubit;
|
||||
|
||||
Future<WorkResult<bool>> call({
|
||||
required String deviceId,
|
||||
required int taskId,
|
||||
required bool resume,
|
||||
}) async {
|
||||
if (cubit.state.isLoading) return const WorkResult.fail('任务操作中,请稍后重试');
|
||||
cubit.updateCurrentTaskId(taskId);
|
||||
if (resume) {
|
||||
await cubit.recoveryTask(deviceId);
|
||||
} else {
|
||||
await cubit.pauseTask(deviceId);
|
||||
}
|
||||
final error = cubit.state.errorMessage;
|
||||
return error == null ? const WorkResult.ok(true) : WorkResult.fail(error);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import '../../features/consecutive_tasks/domain/usecases/create_consecutive_task
|
||||
import '../../features/consecutive_tasks/presentation/cubit/area_task_create_cubit.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'adapters/device_control_mode_realtime_adapter.dart';
|
||||
import 'adapters/device_task_control_adapter.dart';
|
||||
import '../../features/device_control_mode/data/datasources/control_mode_remote_datasource.dart';
|
||||
import '../../features/device_control_mode/data/repositories/device_control_mode_repository_impl.dart';
|
||||
import '../../features/device_control_mode/domain/repositories/device_control_mode_repository.dart';
|
||||
@@ -751,8 +752,13 @@ Future<void> init() async {
|
||||
/// 10.1 自主作业业务门面(一套功能多套环境实现)
|
||||
/// 切换环境:AutonomousWorkGatewayFactory.overrideWith(...) 或
|
||||
/// flutter run --dart-define=AUTONOMOUS_WORK_SCENE=local_demo
|
||||
sl.registerLazySingleton(
|
||||
() => DeviceTaskControlAdapter(sl<DeviceTaskCubit>()),
|
||||
);
|
||||
sl.registerLazySingleton<AutonomousWorkGateway>(
|
||||
() => AutonomousWorkGatewayFactory.current(),
|
||||
() => AutonomousWorkGatewayFactory.current(
|
||||
controlTask: sl<DeviceTaskControlAdapter>().call,
|
||||
),
|
||||
);
|
||||
sl.registerLazySingleton(
|
||||
() => DeviceControlModeRealtimeAdapter(sl<DeviceStatusBloc>()),
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import '../../domain/repositories/autonomous_work_gateway.dart';
|
||||
import '../../domain/entities/work_session_models.dart';
|
||||
import 'local_demo_work_gateway.dart';
|
||||
import 'path_planning_work_gateway.dart';
|
||||
|
||||
/// 可选的环境实现清单。新增 B 环境时在这里加一项。
|
||||
enum AutonomousWorkScene {
|
||||
pathPlanning,
|
||||
localDemo,
|
||||
}
|
||||
enum AutonomousWorkScene { pathPlanning, localDemo }
|
||||
|
||||
/// 环境选择 + 实例构建。
|
||||
///
|
||||
@@ -34,17 +32,20 @@ class AutonomousWorkGatewayFactory {
|
||||
}
|
||||
}
|
||||
|
||||
static AutonomousWorkGateway build(AutonomousWorkScene scene) {
|
||||
static AutonomousWorkGateway build(
|
||||
AutonomousWorkScene scene, {
|
||||
WorkTaskControl? controlTask,
|
||||
}) {
|
||||
switch (scene) {
|
||||
case AutonomousWorkScene.localDemo:
|
||||
return LocalDemoWorkGateway();
|
||||
case AutonomousWorkScene.pathPlanning:
|
||||
return PathPlanningWorkGateway();
|
||||
return PathPlanningWorkGateway(controlTask: controlTask);
|
||||
}
|
||||
}
|
||||
|
||||
static AutonomousWorkGateway current() =>
|
||||
_override ?? build(resolveScene());
|
||||
static AutonomousWorkGateway current({WorkTaskControl? controlTask}) =>
|
||||
_override ?? build(resolveScene(), controlTask: controlTask);
|
||||
|
||||
/// 运行期替换实现(单测、灰度、特定业务线)
|
||||
static void overrideWith(AutonomousWorkGateway gateway) {
|
||||
|
||||
@@ -20,15 +20,20 @@ import '../../domain/entities/return_plan_models.dart';
|
||||
import '../../domain/repositories/autonomous_work_gateway.dart';
|
||||
|
||||
/// 新版作业门面:沿用旧版协议和 HTTP 接口,独立维护任务状态与 MQTT 订阅。
|
||||
/// 不写旧版 Cubit 或缓存。
|
||||
/// 暂停/恢复通过装配层复用旧版控制器,任务快照和缓存仍由本门面维护。
|
||||
class PathPlanningWorkGateway
|
||||
implements
|
||||
AutonomousWorkGateway,
|
||||
WorkTaskHistorySource,
|
||||
WorkTaskQueueSource {
|
||||
PathPlanningWorkGateway({V2WorkTaskTracker? tracker})
|
||||
: _injectedTracker = tracker;
|
||||
WorkTaskQueueSource,
|
||||
WorkTaskGeometrySource {
|
||||
PathPlanningWorkGateway({
|
||||
V2WorkTaskTracker? tracker,
|
||||
WorkTaskControl? controlTask,
|
||||
}) : _injectedTracker = tracker,
|
||||
_controlTask = controlTask;
|
||||
final V2WorkTaskTracker? _injectedTracker;
|
||||
final WorkTaskControl? _controlTask;
|
||||
V2WorkTaskTracker? _ownedTracker;
|
||||
String? _trackerOwner;
|
||||
V2WorkTaskTracker get _tracker {
|
||||
@@ -42,6 +47,7 @@ class PathPlanningWorkGateway
|
||||
resolveScope: (deviceId) => resolveScope(deviceId: deviceId),
|
||||
userId: () => sl<AppUserCubit>().state.user?.userId ?? '',
|
||||
store: V2WorkStore(owner),
|
||||
controlTask: _controlTask ?? (throw StateError('未装配现有任务控制器')),
|
||||
);
|
||||
}
|
||||
return _ownedTracker!;
|
||||
@@ -431,10 +437,13 @@ class PathPlanningWorkGateway
|
||||
/// tempObstaclePoints.center{lat,lng}/size_x/size_y/source。
|
||||
ReturnPlanDraft _returnDraftFromJson(Map<String, dynamic> m) {
|
||||
LatLng? parseLatLng(dynamic node) {
|
||||
if (node is String) {
|
||||
try { node = jsonDecode(node); } catch (_) { return null; }
|
||||
}
|
||||
if (node is! Map) return null;
|
||||
final lat = node['lat'] ?? node['latitude'];
|
||||
final lng = node['lng'] ?? node['lon'] ?? node['longitude'];
|
||||
if (lat is! num || lng is! num ||
|
||||
final lat = double.tryParse('${node['lat'] ?? node['latitude']}');
|
||||
final lng = double.tryParse('${node['lng'] ?? node['lon'] ?? node['longitude']}');
|
||||
if (lat == null || lng == null ||
|
||||
!lat.isFinite || !lng.isFinite ||
|
||||
lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
|
||||
return LatLng(lat.toDouble(), lng.toDouble());
|
||||
@@ -511,6 +520,18 @@ class PathPlanningWorkGateway
|
||||
Stream<WorkTaskSnapshot?> watchTaskChanges({required String deviceId}) =>
|
||||
_tracker.watch(deviceId, allTasks: true);
|
||||
@override
|
||||
void recordTaskGeometry({
|
||||
required String deviceId,
|
||||
required String taskId,
|
||||
List<LatLng>? recordedPoints,
|
||||
List<LatLng>? plannedRoute,
|
||||
}) => _tracker.recordGeometry(
|
||||
deviceId: deviceId,
|
||||
taskId: taskId,
|
||||
recordedPoints: recordedPoints,
|
||||
plannedRoute: plannedRoute,
|
||||
);
|
||||
@override
|
||||
Future<WorkResult<WorkTaskSnapshot>> startWork(WorkStartRequest request) =>
|
||||
_tracker.start(request);
|
||||
@override
|
||||
|
||||
@@ -15,7 +15,7 @@ import '../../devices/domain/usecases/create_device_task_usecase.dart';
|
||||
import '../domain/entities/work_session_models.dart';
|
||||
import 'v2_work_store.dart';
|
||||
|
||||
/// 新版专用任务状态。独立 MQTT 连接和缓存,不修改旧版 Cubit、订阅或完成标记。
|
||||
/// 新版任务快照使用独立 MQTT 和缓存,暂停/恢复通过注入端口复用现有控制器。
|
||||
class V2WorkTaskTracker {
|
||||
V2WorkTaskTracker({
|
||||
required this.repository,
|
||||
@@ -23,6 +23,7 @@ class V2WorkTaskTracker {
|
||||
required this.resolveScope,
|
||||
required this.userId,
|
||||
required this.store,
|
||||
required this.controlTask,
|
||||
MqttClient? mqtt,
|
||||
WorkTraceDiagnostics? diagnostics,
|
||||
}) : mqtt = mqtt ?? MqttClientImpl(clientName: 'v2WorkTaskClient'),
|
||||
@@ -33,6 +34,7 @@ class V2WorkTaskTracker {
|
||||
final Future<WorkScope> Function(String deviceId) resolveScope;
|
||||
final String Function() userId;
|
||||
final V2WorkStore store;
|
||||
final WorkTaskControl controlTask;
|
||||
final MqttClient mqtt;
|
||||
final WorkTraceDiagnostics diagnostics;
|
||||
Timer? _traceSummaryTimer;
|
||||
@@ -48,6 +50,8 @@ class V2WorkTaskTracker {
|
||||
final _watchers = <String, int>{};
|
||||
final _topics = <String>{};
|
||||
final _pendingPool = <String, DateTime>{};
|
||||
// HTTP 操作已成功、设备状态尚未回流时,保留本次操作的目标状态。
|
||||
final _pendingControlStates = <String, WorkRunState>{};
|
||||
StreamSubscription<MqttMessage>? _messages;
|
||||
Future<void> _mqttWork = Future<void>.value();
|
||||
Future<void>? _restored;
|
||||
@@ -173,6 +177,12 @@ class V2WorkTaskTracker {
|
||||
completedPoints: previous?.taskId == snapshot.taskId
|
||||
? previous?.completedPoints
|
||||
: null,
|
||||
recordedPoints: previous?.taskId == snapshot.taskId
|
||||
? previous?.recordedPoints
|
||||
: null,
|
||||
plannedRoute: previous?.taskId == snapshot.taskId
|
||||
? previous?.plannedRoute
|
||||
: null,
|
||||
routeName: previous?.taskId == snapshot.taskId
|
||||
? previous?.routeName
|
||||
: null,
|
||||
@@ -188,16 +198,12 @@ class V2WorkTaskTracker {
|
||||
}
|
||||
}
|
||||
final previous = _current[deviceId];
|
||||
// 新建任务可能尚未进入池,短暂空响应不能丢掉已经确认的 taskId。
|
||||
// 任务池短暂缺失不能丢掉已经确认的任务及其路线。
|
||||
if (previous != null &&
|
||||
!_history.containsKey(_id(previous)) &&
|
||||
!active.containsKey(previous.taskId)) {
|
||||
final pendingAt = _pendingPool[_id(previous)];
|
||||
if (pendingAt != null &&
|
||||
DateTime.now().difference(pendingAt) <
|
||||
const Duration(seconds: 30)) {
|
||||
active[previous.taskId] = previous;
|
||||
}
|
||||
// 缺失一条任务池记录不能当作完成,也不能清掉仍在作业的路线。
|
||||
active[previous.taskId] = previous;
|
||||
}
|
||||
_active[deviceId] = active;
|
||||
diagnostics.log('任务池', {
|
||||
@@ -334,30 +340,20 @@ class V2WorkTaskTracker {
|
||||
return const WorkResult.fail('任务正在停止,请等待设备确认');
|
||||
}
|
||||
final id = int.tryParse(task.taskId);
|
||||
final scope = await resolveScope(deviceId);
|
||||
final siteId = (task.extras['siteId'] as int?) ?? scope.siteId;
|
||||
final orgId = (task.extras['orgId'] as int?) ?? scope.orgId ?? 0;
|
||||
if (id == null || siteId == null) return const WorkResult.fail('任务或场站无效');
|
||||
if (id == null) return const WorkResult.fail('任务无效');
|
||||
String? error;
|
||||
if (operation == 'pause') {
|
||||
final result = await repository.pauseTask(
|
||||
if (operation == 'pause' || operation == 'resume') {
|
||||
final result = await controlTask(
|
||||
deviceId: deviceId,
|
||||
taskId: id,
|
||||
orgId: orgId,
|
||||
siteId: siteId,
|
||||
resume: operation == 'resume',
|
||||
);
|
||||
result.fold((f) => error = f.message, (ok) {
|
||||
if (!ok) error = '暂停失败';
|
||||
});
|
||||
} else if (operation == 'resume') {
|
||||
final result = await repository.recoveryTask(
|
||||
deviceId: deviceId,
|
||||
taskId: id,
|
||||
orgId: orgId,
|
||||
siteId: siteId,
|
||||
);
|
||||
result.fold((f) => error = f.message, (_) {});
|
||||
if (!result.isOk) error = result.error ?? '任务操作失败';
|
||||
} else {
|
||||
final scope = await resolveScope(deviceId);
|
||||
final siteId = (task.extras['siteId'] as int?) ?? scope.siteId;
|
||||
final orgId = (task.extras['orgId'] as int?) ?? scope.orgId ?? 0;
|
||||
if (siteId == null) return const WorkResult.fail('场站无效');
|
||||
final result = await repository.cancelTask(
|
||||
deviceId: deviceId,
|
||||
taskId: id,
|
||||
@@ -374,6 +370,16 @@ class V2WorkTaskTracker {
|
||||
final latest =
|
||||
_history[_id(task)] ?? _active[deviceId]?[task.taskId] ?? task;
|
||||
if (latest.state == WorkRunState.finished) return WorkResult.ok(latest);
|
||||
if (operation == 'pause' || operation == 'resume') {
|
||||
final expected = operation == 'pause'
|
||||
? WorkRunState.paused
|
||||
: WorkRunState.running;
|
||||
if (latest.state == expected) {
|
||||
_pendingControlStates.remove(_id(task));
|
||||
} else {
|
||||
_pendingControlStates[_id(task)] = expected;
|
||||
}
|
||||
}
|
||||
final updated = latest.copyWith(
|
||||
state: operation == 'pause'
|
||||
? WorkRunState.paused
|
||||
@@ -399,6 +405,31 @@ class V2WorkTaskTracker {
|
||||
}
|
||||
}
|
||||
|
||||
void recordGeometry({
|
||||
required String deviceId,
|
||||
required String taskId,
|
||||
List<LatLng>? recordedPoints,
|
||||
List<LatLng>? plannedRoute,
|
||||
}) {
|
||||
final task = _active[deviceId]?[taskId] ?? _current[deviceId];
|
||||
if (task == null ||
|
||||
task.taskId != taskId ||
|
||||
task.state == WorkRunState.finished ||
|
||||
_history.containsKey(_id(task))) {
|
||||
return;
|
||||
}
|
||||
final updated = task.copyWith(
|
||||
recordedPoints: recordedPoints == null
|
||||
? null
|
||||
: List.unmodifiable(recordedPoints),
|
||||
plannedRoute: plannedRoute == null ? null : List.unmodifiable(plannedRoute),
|
||||
);
|
||||
_active.putIfAbsent(deviceId, () => {})[taskId] = updated;
|
||||
if (_current[deviceId]?.taskId == taskId) _current[deviceId] = updated;
|
||||
// 不回推页面重建;离开后重新监听时从任务快照和原有本地缓存恢复。
|
||||
unawaited(_save());
|
||||
}
|
||||
|
||||
void _publish(
|
||||
WorkTaskSnapshot task, {
|
||||
bool select = false,
|
||||
@@ -413,6 +444,7 @@ class V2WorkTaskTracker {
|
||||
_revision++;
|
||||
final tasks = _active.putIfAbsent(task.deviceId, () => {});
|
||||
if (task.state == WorkRunState.finished) {
|
||||
_pendingControlStates.remove(_id(task));
|
||||
tasks.remove(task.taskId);
|
||||
_history[_id(task)] = task;
|
||||
} else {
|
||||
@@ -465,6 +497,27 @@ class V2WorkTaskTracker {
|
||||
WorkTaskSnapshot incoming,
|
||||
WorkTaskSnapshot? previous,
|
||||
) {
|
||||
final expected = _pendingControlStates[_id(incoming)];
|
||||
if (expected != null) {
|
||||
if (incoming.state == expected ||
|
||||
incoming.state == WorkRunState.finished ||
|
||||
incoming.state == WorkRunState.failed) {
|
||||
_pendingControlStates.remove(_id(incoming));
|
||||
} else if (previous != null && previous.state == expected) {
|
||||
diagnostics.log('状态合并', {
|
||||
'deviceId': incoming.deviceId,
|
||||
'taskId': incoming.taskId,
|
||||
'receivedStatus': incoming.rawStatus,
|
||||
'keptStatus': previous.rawStatus,
|
||||
'reason': '暂停或恢复请求已成功,等待对应状态回执,忽略旧状态回退',
|
||||
});
|
||||
return incoming.copyWith(
|
||||
state: previous.state,
|
||||
rawStatus: previous.rawStatus,
|
||||
executionStarted: previous.executionStarted,
|
||||
);
|
||||
}
|
||||
}
|
||||
final started =
|
||||
incoming.executionStarted || (previous?.executionStarted ?? false);
|
||||
if (started &&
|
||||
@@ -869,6 +922,14 @@ class V2WorkTaskTracker {
|
||||
for (final p in task.completedPoints)
|
||||
{'lat': p.latitude, 'lng': p.longitude},
|
||||
],
|
||||
'recordedPoints': [
|
||||
for (final p in task.recordedPoints)
|
||||
{'lat': p.latitude, 'lng': p.longitude},
|
||||
],
|
||||
'plannedRoute': [
|
||||
for (final p in task.plannedRoute)
|
||||
{'lat': p.latitude, 'lng': p.longitude},
|
||||
],
|
||||
};
|
||||
|
||||
static WorkTaskSnapshot? _decode(dynamic raw) {
|
||||
@@ -894,6 +955,14 @@ class V2WorkTaskTracker {
|
||||
for (final p in raw['completedPoints'] as List? ?? [])
|
||||
LatLng((p['lat'] as num).toDouble(), (p['lng'] as num).toDouble()),
|
||||
],
|
||||
recordedPoints: [
|
||||
for (final p in raw['recordedPoints'] as List? ?? [])
|
||||
LatLng((p['lat'] as num).toDouble(), (p['lng'] as num).toDouble()),
|
||||
],
|
||||
plannedRoute: [
|
||||
for (final p in raw['plannedRoute'] as List? ?? [])
|
||||
LatLng((p['lat'] as num).toDouble(), (p['lng'] as num).toDouble()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import 'package:latlong2/latlong.dart';
|
||||
|
||||
/// 暂停/恢复由装配层连接现有任务控制器,业务状态层不依赖具体 Cubit。
|
||||
typedef WorkTaskControl =
|
||||
Future<WorkResult<bool>> Function({
|
||||
required String deviceId,
|
||||
required int taskId,
|
||||
required bool resume,
|
||||
});
|
||||
|
||||
/// 跨环境统一的作业运行态:UI 只认这一套枚举。
|
||||
/// 各环境自己的任务状态码(NEW/EXECUTING/PAUSE/… 或别的后端字段)
|
||||
/// 由各自的 gateway 实现映射到这里,页面不感知原始状态码。
|
||||
@@ -112,6 +120,8 @@ class WorkTaskSnapshot {
|
||||
this.plannedArea,
|
||||
this.extras = const <String, dynamic>{},
|
||||
this.completedPoints = const <LatLng>[],
|
||||
this.recordedPoints = const <LatLng>[],
|
||||
this.plannedRoute = const <LatLng>[],
|
||||
this.executionStarted = false,
|
||||
});
|
||||
|
||||
@@ -133,6 +143,9 @@ class WorkTaskSnapshot {
|
||||
|
||||
/// 当前任务的 MQTT 到达点,独立于设备定位轨迹。
|
||||
final List<LatLng> completedPoints;
|
||||
/// 页面重建后仍需恢复的实际行走轨迹与设备下发的规划路线。
|
||||
final List<LatLng> recordedPoints;
|
||||
final List<LatLng> plannedRoute;
|
||||
|
||||
/// 已确认开始过本任务(开始流程成功、执行状态或有效到达点)。
|
||||
/// 独立于后台原始状态,允许 NEW 推送延迟;暂停和结束仍由 state 控制。
|
||||
@@ -153,6 +166,8 @@ class WorkTaskSnapshot {
|
||||
String? routeName,
|
||||
double? progress,
|
||||
List<LatLng>? completedPoints,
|
||||
List<LatLng>? recordedPoints,
|
||||
List<LatLng>? plannedRoute,
|
||||
bool? executionStarted,
|
||||
}) {
|
||||
return WorkTaskSnapshot(
|
||||
@@ -168,6 +183,8 @@ class WorkTaskSnapshot {
|
||||
plannedArea: plannedArea,
|
||||
extras: extras,
|
||||
completedPoints: completedPoints ?? this.completedPoints,
|
||||
recordedPoints: recordedPoints ?? this.recordedPoints,
|
||||
plannedRoute: plannedRoute ?? this.plannedRoute,
|
||||
executionStarted: executionStarted ?? this.executionStarted,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,16 @@ abstract interface class WorkTaskQueueSource {
|
||||
Stream<WorkTaskSnapshot?> watchTaskChanges({required String deviceId});
|
||||
}
|
||||
|
||||
/// 地图只回传几何,保存与恢复由既有任务状态层负责。
|
||||
abstract interface class WorkTaskGeometrySource {
|
||||
void recordTaskGeometry({
|
||||
required String deviceId,
|
||||
required String taskId,
|
||||
List<LatLng>? recordedPoints,
|
||||
List<LatLng>? plannedRoute,
|
||||
});
|
||||
}
|
||||
|
||||
/// 自主作业的业务门面。
|
||||
///
|
||||
/// 一套页面功能,多套环境实现:
|
||||
|
||||
@@ -192,7 +192,14 @@ class DeviceTaskDatasourceImpl implements DeviceTaskDatasource {
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
if (data['code'] == 200) {
|
||||
_logger.logWithLevel('[recoveryTask] 结果: 成功, data=${jsonEncode(data['data'])}');
|
||||
return data['data'] as Map<String, dynamic>? ?? {};
|
||||
final payload = data['data'];
|
||||
// 恢复接口可能只返回布尔确认,不能把 true 强转成任务对象。
|
||||
if (payload == null || payload == true) return {};
|
||||
if (payload is Map) return Map<String, dynamic>.from(payload);
|
||||
if (payload == false) {
|
||||
throw Exception('恢复任务未成功,请确认设备状态后重试');
|
||||
}
|
||||
throw Exception('恢复任务响应格式异常,请稍后重试');
|
||||
} else {
|
||||
_logger.logWithLevel('[recoveryTask] 业务失败: code=${data['code']}, msg=${data['msg']}');
|
||||
throw Exception(data['msg'] ?? '恢复任务失败');
|
||||
|
||||
@@ -22,7 +22,11 @@ class CreateDeviceTaskUseCase {
|
||||
);
|
||||
return Right(taskId);
|
||||
} catch (e) {
|
||||
return Left(DeviceFailure.networkError(message: e.toString()));
|
||||
final errorMessage = e.toString();
|
||||
if (errorMessage.contains('当前设备切换模式失败')) {
|
||||
return Left(DeviceFailure('请检查遥控器模式后重试'));
|
||||
}
|
||||
return Left(DeviceFailure.networkError(message: errorMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,14 +7,16 @@ class WorkTraceInput {
|
||||
required this.recording,
|
||||
required this.visible,
|
||||
this.completedPoints = const [],
|
||||
this.recordedPoints = const [],
|
||||
});
|
||||
final String? taskId;
|
||||
final bool recording;
|
||||
final bool visible;
|
||||
final List<LatLng> completedPoints;
|
||||
final List<LatLng> recordedPoints;
|
||||
}
|
||||
|
||||
/// 新版作业绿线:首个到达点前累计定位,之后保留到达点并接一段实时车位。
|
||||
/// 新版作业绿线:用到达点恢复历史,用实时定位持续累计本次已走路线。
|
||||
/// 不写任务历史、不下发指令,也不依赖旧版 TracePoint 的可变状态。
|
||||
class WorkTraceRecorder {
|
||||
WorkTraceRecorder({this.maxGpsPoints = 600, this.minimumStepMeters = 0.3})
|
||||
@@ -29,16 +31,12 @@ class WorkTraceRecorder {
|
||||
bool _recording = false;
|
||||
final _gpsPoints = <LatLng>[];
|
||||
List<LatLng> _completed = const [];
|
||||
LatLng? _tail;
|
||||
bool _hasLivePositions = false;
|
||||
|
||||
bool get hasCompletedPoints => _completed.isNotEmpty;
|
||||
List<LatLng> get points {
|
||||
if (!_visible) return const [];
|
||||
if (_completed.isEmpty) return List.unmodifiable(_gpsPoints);
|
||||
return List.unmodifiable([
|
||||
..._completed,
|
||||
if (_tail != null && _tail != _completed.last) _tail!,
|
||||
]);
|
||||
return List.unmodifiable(_gpsPoints.isEmpty ? _completed : _gpsPoints);
|
||||
}
|
||||
|
||||
void synchronize({required String deviceId, required WorkTraceInput input}) {
|
||||
@@ -53,34 +51,39 @@ class WorkTraceRecorder {
|
||||
(input.taskId?.isNotEmpty ?? false);
|
||||
_recording = _visible && input.recording;
|
||||
if (!_visible) {
|
||||
_gpsPoints.clear();
|
||||
_completed = const [];
|
||||
_tail = null;
|
||||
// 同一任务暂时隐藏或状态切换不丢历史;换任务、明确清轨迹时才 reset。
|
||||
return;
|
||||
}
|
||||
if (_gpsPoints.isEmpty && input.recordedPoints.isNotEmpty) {
|
||||
_gpsPoints.addAll(input.recordedPoints.where(_valid));
|
||||
_hasLivePositions = _gpsPoints.isNotEmpty;
|
||||
}
|
||||
final completed = <LatLng>[];
|
||||
for (final point in input.completedPoints) {
|
||||
if (_valid(point) && (completed.isEmpty || completed.last != point)) {
|
||||
completed.add(point);
|
||||
}
|
||||
}
|
||||
if (_completed.isEmpty && completed.isNotEmpty) _gpsPoints.clear();
|
||||
_completed = List.unmodifiable(completed);
|
||||
if (completed.length >= _completed.length) {
|
||||
_completed = List.unmodifiable(completed);
|
||||
// 没有实时定位时用到达点恢复轨迹;收到实时定位后不再用迟到的
|
||||
// 到达点替换本地路线,避免暂停/恢复后旧路线消失或只剩一条尾线。
|
||||
if (!_hasLivePositions && completed.isNotEmpty) {
|
||||
_gpsPoints
|
||||
..clear()
|
||||
..addAll(completed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool addPosition(LatLng point) {
|
||||
if (!_recording || !_valid(point)) return false;
|
||||
if (_completed.isNotEmpty) {
|
||||
if (_tail == point) return false;
|
||||
_tail = point;
|
||||
return true;
|
||||
}
|
||||
if (_gpsPoints.isNotEmpty &&
|
||||
_distance(_gpsPoints.last, point) < minimumStepMeters) {
|
||||
return false;
|
||||
}
|
||||
_gpsPoints.add(point);
|
||||
_tail = point;
|
||||
_hasLivePositions = true;
|
||||
if (_gpsPoints.length > maxGpsPoints) {
|
||||
_gpsPoints.removeRange(0, _gpsPoints.length - maxGpsPoints);
|
||||
}
|
||||
@@ -102,6 +105,6 @@ class WorkTraceRecorder {
|
||||
_recording = false;
|
||||
_gpsPoints.clear();
|
||||
_completed = const [];
|
||||
_tail = null;
|
||||
_hasLivePositions = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,9 @@ class PvWorkMap extends StatefulWidget {
|
||||
this.recordLocationTrace = true,
|
||||
this.workTrace,
|
||||
this.taskTrace,
|
||||
this.savedRoute = const <LatLng>[],
|
||||
this.onTaskTraceChanged,
|
||||
this.onTaskRouteChanged,
|
||||
this.expectedTaskId,
|
||||
this.traceDiagnosticsEnabled = false,
|
||||
this.showDevice = true,
|
||||
@@ -164,6 +167,9 @@ class PvWorkMap extends StatefulWidget {
|
||||
final bool recordLocationTrace;
|
||||
final List<LatLng>? workTrace;
|
||||
final WorkTraceInput? taskTrace;
|
||||
final List<LatLng> savedRoute;
|
||||
final ValueChanged<List<LatLng>>? onTaskTraceChanged;
|
||||
final ValueChanged<List<LatLng>>? onTaskRouteChanged;
|
||||
final String? expectedTaskId;
|
||||
final bool traceDiagnosticsEnabled;
|
||||
final bool showDevice;
|
||||
@@ -196,7 +202,13 @@ class _PvWorkMapState extends State<PvWorkMap> {
|
||||
return;
|
||||
}
|
||||
_taskTraceRecorder.synchronize(deviceId: widget.deviceSn, input: input);
|
||||
if (_pos != null) _taskTraceRecorder.addPosition(_pos!);
|
||||
if (_route.isEmpty && widget.savedRoute.isNotEmpty && input.visible) {
|
||||
_route = List.of(widget.savedRoute);
|
||||
_routeTaskId = int.tryParse(widget.expectedTaskId ?? '') ?? -1;
|
||||
}
|
||||
if (_pos != null && _taskTraceRecorder.addPosition(_pos!)) {
|
||||
widget.onTaskTraceChanged?.call(_taskTraceRecorder.points);
|
||||
}
|
||||
}
|
||||
|
||||
void _logTraceRender(List<LatLng> points) {
|
||||
@@ -405,6 +417,7 @@ class _PvWorkMapState extends State<PvWorkMap> {
|
||||
}
|
||||
_route = [for (final p in msg.data) LatLng(p.lat, p.lng)];
|
||||
});
|
||||
widget.onTaskRouteChanged?.call(List.of(_route));
|
||||
}
|
||||
|
||||
/// 定位推送来了:攒轨迹 + 按需把机器移到正中间
|
||||
@@ -446,7 +459,9 @@ class _PvWorkMapState extends State<PvWorkMap> {
|
||||
_pos = p;
|
||||
widget.onDevicePosition?.call(p);
|
||||
if (widget.taskTrace != null) {
|
||||
_taskTraceRecorder.addPosition(p);
|
||||
if (_taskTraceRecorder.addPosition(p)) {
|
||||
widget.onTaskTraceChanged?.call(_taskTraceRecorder.points);
|
||||
}
|
||||
} else if (widget.recordLocationTrace) {
|
||||
_appendTrace(p);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realt
|
||||
import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/domain/entities/work_session_models.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/domain/entities/device_control_mode.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/domain/usecases/device_control_mode_usecases.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/running_status_entity.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';
|
||||
@@ -485,6 +487,7 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
// ===== 底部操作栏动作(全部走 gateway,状态由真实任务回流驱动)=====
|
||||
|
||||
Future<void> _startWork() async {
|
||||
if (_busy) return;
|
||||
final route = _route;
|
||||
if (route == null) {
|
||||
CapsuleToast.show(
|
||||
@@ -556,10 +559,27 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
return;
|
||||
}
|
||||
|
||||
final deviceId = _deviceId;
|
||||
final modeSent = await showWorkConfirmDialog(
|
||||
context,
|
||||
title: _l10n.translate('autonomous_work.dispatch_mode_title'),
|
||||
desc: _l10n.translate('autonomous_work.dispatch_mode_description'),
|
||||
checks: const [],
|
||||
confirmLabel: _l10n.translate('autonomous_work.dispatch_mode_confirm'),
|
||||
onConfirm: () async {
|
||||
final result = await sl<ChangeDeviceControlModeUseCase>()(
|
||||
deviceId,
|
||||
ControlModeTarget.autonomous,
|
||||
);
|
||||
return result.fold((failure) => failure.message, (_) => null);
|
||||
},
|
||||
);
|
||||
if (modeSent != true || !mounted) return;
|
||||
|
||||
// ③ 下发(复用已有任务或新建)
|
||||
final result = await _gateway.startWork(
|
||||
WorkStartRequest(
|
||||
deviceId: _deviceId,
|
||||
deviceId: deviceId,
|
||||
route: route,
|
||||
reuseTaskId: reuse?.taskId,
|
||||
),
|
||||
@@ -1025,6 +1045,22 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
return _buildPage(context);
|
||||
}
|
||||
|
||||
void _recordTaskGeometry({
|
||||
List<LatLng>? recordedPoints,
|
||||
List<LatLng>? plannedRoute,
|
||||
}) {
|
||||
final task = _session;
|
||||
final gateway = _gateway;
|
||||
if (task == null || gateway is! WorkTaskGeometrySource) return;
|
||||
final geometrySource = gateway as WorkTaskGeometrySource;
|
||||
geometrySource.recordTaskGeometry(
|
||||
deviceId: _deviceId,
|
||||
taskId: task.taskId,
|
||||
recordedPoints: recordedPoints,
|
||||
plannedRoute: plannedRoute,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPage(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF26331F),
|
||||
@@ -1042,9 +1078,15 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
expectedTaskId: _session?.taskId,
|
||||
traceDiagnosticsEnabled: true,
|
||||
recordLocationTrace: false,
|
||||
savedRoute: _session?.plannedRoute ?? const <LatLng>[],
|
||||
onTaskTraceChanged: (points) =>
|
||||
_recordTaskGeometry(recordedPoints: points),
|
||||
onTaskRouteChanged: (points) =>
|
||||
_recordTaskGeometry(plannedRoute: points),
|
||||
taskTrace: WorkTraceInput(
|
||||
taskId: _session?.taskId,
|
||||
completedPoints: _session?.completedPoints ?? const <LatLng>[],
|
||||
recordedPoints: _session?.recordedPoints ?? const <LatLng>[],
|
||||
recording: _session?.canRecordTrace ?? false,
|
||||
visible:
|
||||
_phase == WorkRunState.running ||
|
||||
@@ -1754,39 +1796,6 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
),
|
||||
),
|
||||
),
|
||||
// 底部按钮(固定,不被滚动区顶走)
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
px,
|
||||
m.tiny ? 4 : 8,
|
||||
px,
|
||||
m.tiny ? 4 : (compact ? 12 : 14),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: () =>
|
||||
_pushPortrait(RobotSensorPageV2(robot: widget.robot)),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
height: m.tiny ? 26 : (compact ? 34 : 38),
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: kWtSoftBlue,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Text(
|
||||
_l10n.translate('autonomous_work.view_sensors'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: m.fsx(12, 9),
|
||||
fontWeight: FontWeight.w800,
|
||||
color: kWtBlue,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
@@ -13,9 +13,11 @@ Future<bool?> showWorkConfirmDialog(
|
||||
required List<String> checks,
|
||||
required String confirmLabel,
|
||||
bool danger = false,
|
||||
Future<String?> Function()? onConfirm,
|
||||
}) {
|
||||
return showDialog<bool>(
|
||||
context: context,
|
||||
barrierDismissible: onConfirm == null,
|
||||
barrierColor: const Color(0x8C0B1B2B),
|
||||
builder: (dialogContext) => _WorkConfirmDialog(
|
||||
title: title,
|
||||
@@ -23,17 +25,19 @@ Future<bool?> showWorkConfirmDialog(
|
||||
checks: checks,
|
||||
confirmLabel: confirmLabel,
|
||||
danger: danger,
|
||||
onConfirm: onConfirm,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _WorkConfirmDialog extends StatelessWidget {
|
||||
class _WorkConfirmDialog extends StatefulWidget {
|
||||
const _WorkConfirmDialog({
|
||||
required this.title,
|
||||
required this.desc,
|
||||
required this.checks,
|
||||
required this.confirmLabel,
|
||||
required this.danger,
|
||||
required this.onConfirm,
|
||||
});
|
||||
|
||||
final String title;
|
||||
@@ -41,6 +45,44 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
final List<String> checks;
|
||||
final String confirmLabel;
|
||||
final bool danger;
|
||||
final Future<String?> Function()? onConfirm;
|
||||
|
||||
@override
|
||||
State<_WorkConfirmDialog> createState() => _WorkConfirmDialogState();
|
||||
}
|
||||
|
||||
class _WorkConfirmDialogState extends State<_WorkConfirmDialog> {
|
||||
bool _submitting = false;
|
||||
String? _error;
|
||||
|
||||
Future<void> _confirm() async {
|
||||
if (_submitting) return;
|
||||
final action = widget.onConfirm;
|
||||
if (action == null) {
|
||||
Navigator.of(context).pop(true);
|
||||
return;
|
||||
}
|
||||
final l10n = AppLocalizations.of(context);
|
||||
setState(() {
|
||||
_submitting = true;
|
||||
_error = null;
|
||||
});
|
||||
String? error;
|
||||
try {
|
||||
error = await action();
|
||||
} catch (_) {
|
||||
error = l10n.translate('autonomous_work.dispatch_mode_failed');
|
||||
}
|
||||
if (!mounted || ModalRoute.of(context)?.isCurrent != true) return;
|
||||
if (error == null) {
|
||||
Navigator.of(context).pop(true);
|
||||
} else {
|
||||
setState(() {
|
||||
_submitting = false;
|
||||
_error = error;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
static const Color _navy = Color(0xFF1A2B4A);
|
||||
static const Color _gray2 = Color(0xFF5C6B84);
|
||||
@@ -54,7 +96,7 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final accent = danger ? _danger : _blue;
|
||||
final accent = widget.danger ? _danger : _blue;
|
||||
return Dialog(
|
||||
backgroundColor: Colors.transparent,
|
||||
insetPadding: const EdgeInsets.symmetric(horizontal: 80, vertical: 24),
|
||||
@@ -82,7 +124,7 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
title,
|
||||
widget.title,
|
||||
style: const TextStyle(
|
||||
fontSize: 19,
|
||||
fontWeight: FontWeight.w800,
|
||||
@@ -91,7 +133,9 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
InkWell(
|
||||
onTap: () => Navigator.of(context).pop(false),
|
||||
onTap: _submitting
|
||||
? null
|
||||
: () => Navigator.of(context).pop(false),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Container(
|
||||
width: 32,
|
||||
@@ -117,7 +161,7 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
desc,
|
||||
widget.desc,
|
||||
style: const TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.6,
|
||||
@@ -125,19 +169,23 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
for (final check in checks) ...[
|
||||
for (final check in widget.checks) ...[
|
||||
_checkRow(check, l10n),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
l10n.translate('autonomous_work.confirmation_demo_note'),
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.6,
|
||||
color: Color(0xFFA8B3C5),
|
||||
if (widget.checks.isNotEmpty) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
l10n.translate('autonomous_work.confirmation_demo_note'),
|
||||
style: const TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.6,
|
||||
color: Color(0xFFA8B3C5),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (_error case final error?)
|
||||
Text(error, style: const TextStyle(color: _danger)),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -149,16 +197,20 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
Expanded(
|
||||
child: _button(
|
||||
label: l10n.translate('common.back'),
|
||||
onTap: () => Navigator.of(context).pop(false),
|
||||
onTap: _submitting
|
||||
? null
|
||||
: () => Navigator.of(context).pop(false),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _button(
|
||||
label: confirmLabel,
|
||||
label: _submitting
|
||||
? l10n.translate('autonomous_work.dispatch_mode_sending')
|
||||
: widget.confirmLabel,
|
||||
filled: true,
|
||||
color: accent,
|
||||
onTap: () => Navigator.of(context).pop(true),
|
||||
onTap: _submitting ? null : _confirm,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -208,7 +260,7 @@ class _WorkConfirmDialog extends StatelessWidget {
|
||||
|
||||
Widget _button({
|
||||
required String label,
|
||||
required VoidCallback onTap,
|
||||
required VoidCallback? onTap,
|
||||
bool filled = false,
|
||||
Color color = _blue,
|
||||
}) {
|
||||
|
||||
77
test/device_task_control_adapter_test.dart
Normal file
77
test/device_task_control_adapter_test.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/adapters/device_task_control_adapter.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';
|
||||
|
||||
class FakeDeviceTaskCubit implements DeviceTaskCubit {
|
||||
@override
|
||||
DeviceTaskState state = const DeviceTaskState();
|
||||
final calls = <String>[];
|
||||
String? failure;
|
||||
|
||||
@override
|
||||
void updateCurrentTaskId(int taskId) {
|
||||
state = state.copyWith(currentTaskId: taskId);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pauseTask(String deviceId) async {
|
||||
calls.add('pause/$deviceId/${state.currentTaskId}');
|
||||
state = state.copyWith(errorMessage: failure);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> recoveryTask(String deviceId) async {
|
||||
calls.add('recovery/$deviceId/${state.currentTaskId}');
|
||||
state = state.copyWith(errorMessage: failure);
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'reuses the existing Cubit pause and recovery with the selected task ID',
|
||||
() async {
|
||||
final cubit = FakeDeviceTaskCubit();
|
||||
final adapter = DeviceTaskControlAdapter(cubit);
|
||||
expect(
|
||||
(await adapter(deviceId: 'SN-1', taskId: 42, resume: false)).isOk,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
(await adapter(deviceId: 'SN-1', taskId: 42, resume: true)).isOk,
|
||||
isTrue,
|
||||
);
|
||||
expect(cubit.calls, ['pause/SN-1/42', 'recovery/SN-1/42']);
|
||||
},
|
||||
);
|
||||
|
||||
test('returns the error reported by the existing Cubit', () async {
|
||||
final cubit = FakeDeviceTaskCubit()..failure = '恢复失败';
|
||||
final result = await DeviceTaskControlAdapter(cubit)(
|
||||
deviceId: 'SN-1',
|
||||
taskId: 42,
|
||||
resume: true,
|
||||
);
|
||||
expect(result.isOk, isFalse);
|
||||
expect(result.error, '恢复失败');
|
||||
});
|
||||
|
||||
test(
|
||||
'does not replace the active task while the shared Cubit is busy',
|
||||
() async {
|
||||
final cubit = FakeDeviceTaskCubit()
|
||||
..state = const DeviceTaskState(isLoading: true, currentTaskId: 41);
|
||||
final result = await DeviceTaskControlAdapter(cubit)(
|
||||
deviceId: 'SN-1',
|
||||
taskId: 42,
|
||||
resume: false,
|
||||
);
|
||||
expect(result.isOk, isFalse);
|
||||
expect(cubit.state.currentTaskId, 41);
|
||||
expect(cubit.calls, isEmpty);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -94,6 +94,18 @@ class FakeTasks implements DeviceTaskRepository {
|
||||
String? error;
|
||||
int? operatedTask;
|
||||
bool? force;
|
||||
final controls = <String>[];
|
||||
|
||||
Future<WorkResult<bool>> controlTask({
|
||||
required String deviceId,
|
||||
required int taskId,
|
||||
required bool resume,
|
||||
}) async {
|
||||
operatedTask = taskId;
|
||||
controls.add(resume ? 'resume' : 'pause');
|
||||
return error == null ? const WorkResult.ok(true) : WorkResult.fail(error!);
|
||||
}
|
||||
|
||||
static DeviceTaskEntity entity({
|
||||
int id = 42,
|
||||
String state = 'EXECUTING',
|
||||
@@ -204,6 +216,7 @@ void main() {
|
||||
resolveScope: (_) async => const WorkScope(siteId: 2, orgId: 3),
|
||||
userId: () => 'test-user',
|
||||
store: V2WorkStore('test-user'),
|
||||
controlTask: tasks.controlTask,
|
||||
mqtt: mqtt,
|
||||
diagnostics: WorkTraceDiagnostics(
|
||||
now: () => DateTime(2026, 11, 5),
|
||||
@@ -476,6 +489,89 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'pause and resume wait for matching status before accepting old states',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'pause',
|
||||
);
|
||||
mqtt.status('EXECUTING');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.paused);
|
||||
// 任务池仍返回旧 EXECUTING,也不能把恢复入口切回暂停。
|
||||
await tracker.load('MC700-test');
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.paused);
|
||||
mqtt.status('PAUSE');
|
||||
await flush();
|
||||
await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'resume',
|
||||
);
|
||||
mqtt.status('PAUSE');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.running);
|
||||
mqtt.status('EXECUTING');
|
||||
await flush();
|
||||
// 收到恢复回执后,设备新的暂停仍正常生效。
|
||||
mqtt.status('PAUSE');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.paused);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'pause failure keeps running and failed resume keeps the restore action',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
tasks.error = 'offline';
|
||||
expect(
|
||||
(await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'pause',
|
||||
)).isOk,
|
||||
isFalse,
|
||||
);
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.running);
|
||||
tasks.error = null;
|
||||
await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'pause',
|
||||
);
|
||||
tasks.error = 'offline';
|
||||
expect(
|
||||
(await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'resume',
|
||||
)).isOk,
|
||||
isFalse,
|
||||
);
|
||||
mqtt.status('EXECUTING');
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.paused);
|
||||
},
|
||||
);
|
||||
|
||||
test('pending pause still accepts task completion', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'pause',
|
||||
);
|
||||
mqtt.status('FINISH');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.finished);
|
||||
});
|
||||
|
||||
test(
|
||||
'pause resume stop use current task ID and stop cleans subscriptions',
|
||||
() async {
|
||||
@@ -489,6 +585,7 @@ void main() {
|
||||
current = (await tracker.command('MC700-test', current, 'cancel')).data!;
|
||||
await flush();
|
||||
expect(tasks.operatedTask, 42);
|
||||
expect(tasks.controls, ['pause', 'resume']);
|
||||
expect(tasks.force, isTrue);
|
||||
expect(current.rawStatus, 'CANCELED');
|
||||
expect(
|
||||
@@ -546,6 +643,7 @@ void main() {
|
||||
resolveScope: (_) async => const WorkScope(siteId: 2, orgId: 3),
|
||||
userId: () => 'test-user',
|
||||
store: V2WorkStore('test-user'),
|
||||
controlTask: tasks.controlTask,
|
||||
mqtt: mqtt,
|
||||
diagnostics: WorkTraceDiagnostics(write: traceLogs.add),
|
||||
);
|
||||
@@ -615,7 +713,7 @@ void main() {
|
||||
mqtt.arrive({'lat': b.latitude, 'lng': b.longitude}, taskId: 100);
|
||||
sync();
|
||||
trace.addPosition(c);
|
||||
expect(trace.points, [b, c]);
|
||||
expect(trace.points, [a, b, c]);
|
||||
expect(tracker.current('MC700-test')!.completedPoints, [b]);
|
||||
await tracker.command(
|
||||
'MC700-test',
|
||||
@@ -625,7 +723,7 @@ void main() {
|
||||
mqtt.status('NEW', taskId: 100);
|
||||
sync();
|
||||
expect(trace.addPosition(a), isFalse);
|
||||
expect(trace.points, [b, c]);
|
||||
expect(trace.points, [a, b, c]);
|
||||
mqtt.status('FINISH', taskId: 100);
|
||||
sync();
|
||||
expect(trace.points, isEmpty);
|
||||
|
||||
@@ -53,7 +53,7 @@ void main() {
|
||||
expect(recorder.hasCompletedPoints, isFalse);
|
||||
});
|
||||
|
||||
test('首个到达点切换为到达点加最新车位,不保留之前的GPS折线', () {
|
||||
test('首个到达点不清除之前的GPS折线,后续定位继续累计', () {
|
||||
sync();
|
||||
recorder.addPosition(a);
|
||||
recorder.addPosition(b);
|
||||
@@ -62,7 +62,7 @@ void main() {
|
||||
expect(recorder.points, [a, b]);
|
||||
recorder.addPosition(c);
|
||||
recorder.addPosition(d);
|
||||
expect(recorder.points, [a, d]);
|
||||
expect(recorder.points, [a, b, c, d]);
|
||||
});
|
||||
|
||||
test('仅收到一个到达点时,下一次定位就能组成绿色线段', () {
|
||||
@@ -82,7 +82,7 @@ void main() {
|
||||
expect(recorder.addPosition(c), isFalse);
|
||||
});
|
||||
|
||||
test('暂停冻结尾点,恢复后接入当前位置', () {
|
||||
test('暂停保留旧路线,恢复后从原路线继续累计', () {
|
||||
sync(completed: [a]);
|
||||
recorder.addPosition(b);
|
||||
sync(recording: false, completed: [a]);
|
||||
@@ -90,10 +90,10 @@ void main() {
|
||||
expect(recorder.points, [a, b]);
|
||||
sync(completed: [a]);
|
||||
expect(recorder.addPosition(c), isTrue);
|
||||
expect(recorder.points, [a, c]);
|
||||
expect(recorder.points, [a, b, c]);
|
||||
});
|
||||
|
||||
test('结束隐藏并清空,不能带着旧GPS开始下一次记录', () {
|
||||
test('暂时隐藏保留同任务轨迹,显式重置后才清空', () {
|
||||
sync();
|
||||
recorder.addPosition(a);
|
||||
recorder.addPosition(b);
|
||||
@@ -101,7 +101,11 @@ void main() {
|
||||
expect(recorder.points, isEmpty);
|
||||
sync();
|
||||
recorder.addPosition(c);
|
||||
expect(recorder.points, [c]);
|
||||
expect(recorder.points, [a, b, c]);
|
||||
recorder.reset();
|
||||
sync();
|
||||
recorder.addPosition(d);
|
||||
expect(recorder.points, [d]);
|
||||
});
|
||||
|
||||
test('切换任务或设备清理之前的GPS和到达点', () {
|
||||
|
||||
Reference in New Issue
Block a user