接入设备故障告警和场站实时任务进度
This commit is contained in:
@@ -0,0 +1,240 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/network/mqtt/domain/entities/mower_task_status_entity.dart';
|
||||
import '../../../core/network/mqtt/domain/repositories/mower_realtime_repository.dart';
|
||||
import '../../device_alarms/presentation/cubit/device_alarms_cubit.dart';
|
||||
import '../../device_alarms/presentation/cubit/device_alarms_state.dart';
|
||||
|
||||
typedef _TaskUpdate = ({
|
||||
int? siteId,
|
||||
String sn,
|
||||
MowerTaskStatusEntity? report,
|
||||
Object? error,
|
||||
});
|
||||
|
||||
/// 设备 Tab 的场站共享订阅。告警和任务状态使用同一份完整车辆名单,
|
||||
/// 不受列表分页、搜索、在线状态或详情面板开关影响。
|
||||
class SiteDeviceRealtimeSubscriptions {
|
||||
SiteDeviceRealtimeSubscriptions(this.alarms, this.tasks) {
|
||||
_alarmSubscription = alarms.stream.listen(_syncSite);
|
||||
_syncSite(alarms.state);
|
||||
}
|
||||
|
||||
final DeviceAlarmsCubit alarms;
|
||||
final MowerRealtimeRepository tasks;
|
||||
late final StreamSubscription<DeviceAlarmsState> _alarmSubscription;
|
||||
final _subscriptions = <String, StreamSubscription<MowerTaskStatusEntity>>{};
|
||||
final _tokens = <String, Object>{};
|
||||
final _latest = <String, MowerTaskStatusEntity>{};
|
||||
final _failed = <String>{};
|
||||
final _updates = StreamController<_TaskUpdate>.broadcast(sync: true);
|
||||
Future<void> _reconciling = Future.value();
|
||||
Future<void>? _checking;
|
||||
int? _checkingSite;
|
||||
int? _siteId;
|
||||
int _version = 0;
|
||||
bool _closed = false;
|
||||
Set<String> _targets = {};
|
||||
|
||||
void _syncSite(DeviceAlarmsState state) {
|
||||
if (_closed) return;
|
||||
if (state.siteId != _siteId) {
|
||||
final previousSite = _siteId;
|
||||
final oldSns = _subscriptions.keys.toList();
|
||||
_siteId = state.siteId;
|
||||
++_version;
|
||||
_tokens.clear();
|
||||
_latest.clear();
|
||||
_failed.clear();
|
||||
_targets = {};
|
||||
for (final sn in oldSns) {
|
||||
_updates.add((siteId: previousSite, sn: sn, report: null, error: null));
|
||||
}
|
||||
_queueReconcile();
|
||||
}
|
||||
if (!state.isLoading && !state.loadFailed) {
|
||||
final targets = state.deviceSns.toSet();
|
||||
if (!setEquals(targets, _targets)) {
|
||||
_targets = targets;
|
||||
_queueReconcile();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _queueReconcile() {
|
||||
final version = _version;
|
||||
final siteId = _siteId;
|
||||
final targets = _targets.toSet();
|
||||
_reconciling = _reconciling
|
||||
.then((_) async {
|
||||
if (_closed || version != _version) return;
|
||||
final retired = _subscriptions.keys
|
||||
.where(
|
||||
(sn) =>
|
||||
!targets.contains(sn) ||
|
||||
_failed.contains(sn) ||
|
||||
!_tokens.containsKey(sn),
|
||||
)
|
||||
.toList();
|
||||
for (final sn in retired) {
|
||||
_tokens.remove(sn);
|
||||
_latest.remove(sn);
|
||||
_failed.remove(sn);
|
||||
_updates.add((siteId: siteId, sn: sn, report: null, error: null));
|
||||
await _subscriptions.remove(sn)?.cancel();
|
||||
debugPrint('[场站任务状态] 释放 topic=mower/$sn/task/status/post');
|
||||
}
|
||||
if (_closed || version != _version) return;
|
||||
for (final sn in targets) {
|
||||
if (_subscriptions.containsKey(sn)) continue;
|
||||
final token = Object();
|
||||
_tokens[sn] = token;
|
||||
bool active() =>
|
||||
!_closed &&
|
||||
version == _version &&
|
||||
identical(_tokens[sn], token);
|
||||
void fail(Object error) {
|
||||
if (!active()) return;
|
||||
_failed.add(sn);
|
||||
_updates.add((
|
||||
siteId: siteId,
|
||||
sn: sn,
|
||||
report: null,
|
||||
error: error,
|
||||
));
|
||||
}
|
||||
|
||||
try {
|
||||
debugPrint(
|
||||
'[场站任务状态] 订阅 site=$siteId topic=mower/$sn/task/status/post',
|
||||
);
|
||||
_subscriptions[sn] = tasks
|
||||
.watchTaskStatus(sn)
|
||||
.listen(
|
||||
(report) {
|
||||
if (!active()) return;
|
||||
final previous = _latest[sn];
|
||||
if (previous != null &&
|
||||
previous.taskId == report.taskId &&
|
||||
previous.timestamp != null &&
|
||||
report.timestamp != null &&
|
||||
report.timestamp! < previous.timestamp!) {
|
||||
return;
|
||||
}
|
||||
_failed.remove(sn);
|
||||
_latest[sn] = report;
|
||||
_updates.add((
|
||||
siteId: siteId,
|
||||
sn: sn,
|
||||
report: report,
|
||||
error: null,
|
||||
));
|
||||
},
|
||||
onError: (Object error) => fail(error),
|
||||
onDone: () => fail(StateError('Task status stream closed')),
|
||||
);
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catchError((Object error) {
|
||||
debugPrint('[场站任务状态] 同步订阅失败: $error');
|
||||
});
|
||||
return _reconciling;
|
||||
}
|
||||
|
||||
/// 每次进入设备 Tab 和打开详情都检查全部设备;复用健康订阅,补齐异常项。
|
||||
Future<void> ensureSubscriptions(int? siteId, {bool refresh = false}) {
|
||||
if (_closed) return Future.value();
|
||||
final checking = _checking;
|
||||
if (checking != null && _checkingSite == siteId) return checking;
|
||||
_checkingSite = siteId;
|
||||
final pending = _ensure(siteId, refresh: refresh);
|
||||
_checking = pending;
|
||||
return pending.whenComplete(() {
|
||||
if (identical(_checking, pending)) _checking = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _ensure(int? siteId, {required bool refresh}) async {
|
||||
debugPrint('[场站订阅][CHECK] site=$siteId refresh=$refresh');
|
||||
await alarms.loadSite(siteId, force: refresh);
|
||||
// 告警入口可能已启动相同场站的异步加载,等待其完整车辆清单。
|
||||
if (!_closed && alarms.state.siteId == siteId && alarms.state.isLoading) {
|
||||
try {
|
||||
await alarms.stream.firstWhere(
|
||||
(state) => state.siteId != siteId || !state.isLoading,
|
||||
);
|
||||
} on StateError {
|
||||
if (_closed || alarms.isClosed) return;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
if (_closed || alarms.state.siteId != siteId) return;
|
||||
await alarms.ensureSubscriptions();
|
||||
if (_closed || alarms.state.siteId != siteId) return;
|
||||
_syncSite(alarms.state);
|
||||
await _queueReconcile();
|
||||
debugPrint(
|
||||
'[场站任务状态][CHECK_DONE] site=$_siteId devices=${_targets.length} '
|
||||
'subscribed=${_subscriptions.length} failed=${_failed.length}',
|
||||
);
|
||||
}
|
||||
|
||||
/// 详情只读取共享缓存/更新;取消详情监听不会释放场站的 MQTT 订阅。
|
||||
Stream<MowerTaskStatusEntity?> watchTaskStatus({
|
||||
required int? siteId,
|
||||
required String deviceSn,
|
||||
}) {
|
||||
final sn = deviceSn.trim();
|
||||
return Stream.multi((controller) {
|
||||
var active = true;
|
||||
final listener = _updates.stream.listen((update) {
|
||||
if (update.siteId != siteId || update.sn != sn) return;
|
||||
if (update.error != null) {
|
||||
controller.addError(update.error!);
|
||||
} else {
|
||||
controller.add(update.report);
|
||||
}
|
||||
}, onDone: controller.close);
|
||||
controller.onCancel = () {
|
||||
active = false;
|
||||
return listener.cancel();
|
||||
};
|
||||
if (_siteId == siteId && _latest.containsKey(sn)) {
|
||||
controller.add(_latest[sn]);
|
||||
}
|
||||
// 场站切换后的旧页面只能清空显示,不能把共享订阅切回旧场站。
|
||||
if (_siteId != null && _siteId != siteId) {
|
||||
controller.add(null);
|
||||
return;
|
||||
}
|
||||
unawaited(
|
||||
ensureSubscriptions(
|
||||
siteId,
|
||||
refresh: siteId != null && !_targets.contains(sn),
|
||||
).catchError((Object error, StackTrace stack) {
|
||||
if (active) controller.addError(error, stack);
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
if (_closed) return;
|
||||
_closed = true;
|
||||
++_version;
|
||||
_tokens.clear();
|
||||
await _alarmSubscription.cancel();
|
||||
await _reconciling;
|
||||
await Future.wait(
|
||||
_subscriptions.values.map((subscription) => subscription.cancel()),
|
||||
);
|
||||
_subscriptions.clear();
|
||||
_latest.clear();
|
||||
await _updates.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user