完善自主作业下发、暂停恢复和轨迹保留
This commit is contained in:
@@ -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()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user