366 lines
13 KiB
Dart
366 lines
13 KiB
Dart
import 'dart:async';
|
||
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||
|
||
import '../../domain/entities/device_alarm.dart';
|
||
import '../../domain/entities/device_alarm_target.dart';
|
||
import '../../domain/usecases/device_alarm_usecases.dart';
|
||
import '../../domain/usecases/load_site_alarm_targets_usecase.dart';
|
||
import 'device_alarms_state.dart';
|
||
|
||
/// 设备 Tab 管理场站订阅;详情和弹窗只读取数据,不创建自己的订阅。
|
||
class DeviceAlarmsCubit extends Cubit<DeviceAlarmsState> {
|
||
DeviceAlarmsCubit(this.watchAlarms, this.handleAlarm, this.loadTargets)
|
||
: super(const DeviceAlarmsState());
|
||
|
||
final WatchDeviceAlarmsUseCase watchAlarms;
|
||
final HandleDeviceAlarmUseCase handleAlarm;
|
||
final LoadSiteAlarmTargetsUseCase loadTargets;
|
||
final _subscriptions = <String, StreamSubscription<List<DeviceAlarm>>>{};
|
||
final _tokens = <String, Object>{};
|
||
final _targets = <String, DeviceAlarmTarget>{};
|
||
final _closedIds = <int>{};
|
||
final _historyIds = <int>{};
|
||
Future<void> _releasing = Future.value();
|
||
int _siteVersion = 0;
|
||
int _loadVersion = 0;
|
||
bool _closing = false;
|
||
|
||
Future<void> loadSite(int? siteId, {bool force = false}) async {
|
||
if (isClosed || _closing) {
|
||
debugPrintSynchronously('[场站告警] 跳过订阅:状态已关闭 site=$siteId');
|
||
return;
|
||
}
|
||
if (!force && state.siteId == siteId) {
|
||
if (siteId == null) {
|
||
debugPrintSynchronously('[场站告警][WAIT_SITE] 尚未选中场站,等待场站加载');
|
||
}
|
||
logSnapshot('相同场站跳过重复加载');
|
||
return;
|
||
}
|
||
debugPrintSynchronously(
|
||
'[场站告警] 切换/刷新场站 old=${state.siteId} new=$siteId force=$force',
|
||
);
|
||
final version = ++_loadVersion;
|
||
if (state.siteId != siteId) {
|
||
++_siteVersion;
|
||
_closedIds.clear();
|
||
_historyIds.clear();
|
||
_targets.clear();
|
||
emit(DeviceAlarmsState(siteId: siteId, isLoading: siteId != null));
|
||
// 先使旧回调失效并退订旧场站,才获取/订阅新场站。
|
||
await _release(_subscriptions.keys.toList());
|
||
} else {
|
||
emit(state.copyWith(isLoading: true, loadFailed: false));
|
||
await _releasing;
|
||
}
|
||
if (!_isCurrentLoad(version)) return;
|
||
if (siteId == null) {
|
||
debugPrintSynchronously('[场站告警] 当前未选场站,未发起任何告警topic订阅');
|
||
emit(const DeviceAlarmsState());
|
||
return;
|
||
}
|
||
|
||
try {
|
||
final targets = await loadTargets(siteId);
|
||
if (!_isCurrentLoad(version)) {
|
||
debugPrintSynchronously('[场站告警] 忽略旧场站设备列表 site=$siteId');
|
||
return;
|
||
}
|
||
final bySn = {for (final target in targets) target.sn: target};
|
||
debugPrintSynchronously(
|
||
'[场站告警] 设备列表 site=$siteId 车辆数=${bySn.length} SN=${bySn.keys.join(',')}',
|
||
);
|
||
final renewing = _subscriptions.keys
|
||
.where((sn) => !bySn.containsKey(sn) || state.failedSns.contains(sn))
|
||
.toList();
|
||
await _release(renewing);
|
||
if (!_isCurrentLoad(version)) return;
|
||
_targets
|
||
..clear()
|
||
..addAll(bySn);
|
||
final records = state.alarms
|
||
.where((alarm) => bySn.containsKey(alarm.sourceSn))
|
||
.toList();
|
||
final ids = {...records.map((alarm) => alarm.id), ..._historyIds};
|
||
emit(
|
||
state.copyWith(
|
||
isLoading: false,
|
||
loadFailed: false,
|
||
alarms: List.unmodifiable(records),
|
||
deviceSns: Set.unmodifiable(bySn.keys),
|
||
receivedSns: Set.unmodifiable(
|
||
state.receivedSns.where(bySn.containsKey),
|
||
),
|
||
failedSns: const {},
|
||
handlingIds: Set.unmodifiable(state.handlingIds.intersection(ids)),
|
||
handleErrors: Map.unmodifiable({
|
||
for (final entry in state.handleErrors.entries)
|
||
if (ids.contains(entry.key)) entry.key: entry.value,
|
||
}),
|
||
),
|
||
);
|
||
for (final sn in bySn.keys) {
|
||
if (!_subscriptions.containsKey(sn)) _subscribe(sn);
|
||
}
|
||
logSnapshot('场站订阅计划已建立');
|
||
} catch (error) {
|
||
if (_isCurrentLoad(version)) {
|
||
debugPrintSynchronously('[场站告警] 设备列表加载失败 site=$siteId: $error');
|
||
emit(state.copyWith(isLoading: false, loadFailed: true));
|
||
}
|
||
}
|
||
}
|
||
|
||
bool _isCurrentLoad(int version) =>
|
||
!isClosed && !_closing && version == _loadVersion;
|
||
|
||
void _subscribe(String sn) {
|
||
debugPrintSynchronously(
|
||
'[场站告警] 订阅 site=${state.siteId} topic=device/$sn/error/post',
|
||
);
|
||
final token = Object();
|
||
_tokens[sn] = token;
|
||
bool active() => !isClosed && !_closing && identical(_tokens[sn], token);
|
||
void failed() {
|
||
if (active()) {
|
||
emit(
|
||
state.copyWith(failedSns: Set.unmodifiable({...state.failedSns, sn})),
|
||
);
|
||
}
|
||
}
|
||
|
||
try {
|
||
_subscriptions[sn] = watchAlarms(sn).listen(
|
||
(alarms) {
|
||
if (active()) _receive(sn, alarms);
|
||
},
|
||
onError: (Object error, StackTrace stack) {
|
||
debugPrintSynchronously('[场站告警] 订阅/接收异常 SN=$sn error=$error');
|
||
failed();
|
||
},
|
||
onDone: failed,
|
||
);
|
||
} catch (error) {
|
||
debugPrintSynchronously('[场站告警] 创建订阅失败 SN=$sn error=$error');
|
||
failed();
|
||
}
|
||
}
|
||
|
||
void _receive(String sn, List<DeviceAlarm> alarms) {
|
||
debugPrintSynchronously(
|
||
'[场站告警] 更新告警 site=${state.siteId} SN=$sn 条数=${alarms.length} IDs=${alarms.map((alarm) => alarm.id).join(',')}',
|
||
);
|
||
final merged = {for (final alarm in state.alarms) alarm.recordKey: alarm};
|
||
for (final incoming in alarms) {
|
||
var alarm = incoming.copyWith(
|
||
sourceSn: sn,
|
||
deviceName: incoming.deviceName.isEmpty ? _targets[sn]?.name : null,
|
||
);
|
||
if (alarm.isClosed && alarm.id > 0) _closedIds.add(alarm.id);
|
||
if (_closedIds.contains(alarm.id)) alarm = alarm.closed();
|
||
merged[alarm.recordKey] = alarm;
|
||
}
|
||
final sorted = merged.values.toList()
|
||
..sort((a, b) {
|
||
final byTime = (b.alarmTime ?? DateTime(1970)).compareTo(
|
||
a.alarmTime ?? DateTime(1970),
|
||
);
|
||
return byTime != 0 ? byTime : b.id.compareTo(a.id);
|
||
});
|
||
emit(
|
||
state.copyWith(
|
||
alarms: List.unmodifiable(sorted),
|
||
closedIds: Set.unmodifiable(_closedIds),
|
||
receivedSns: Set.unmodifiable({...state.receivedSns, sn}),
|
||
failedSns: Set.unmodifiable({...state.failedSns}..remove(sn)),
|
||
handleErrors: Map.unmodifiable({
|
||
for (final entry in state.handleErrors.entries)
|
||
if (!_closedIds.contains(entry.key)) entry.key: entry.value,
|
||
}),
|
||
),
|
||
);
|
||
}
|
||
|
||
Future<void> _release(List<String> sns) {
|
||
final subscriptions = <StreamSubscription<List<DeviceAlarm>>>[];
|
||
for (final sn in sns) {
|
||
debugPrintSynchronously('[场站告警] 释放订阅 topic=device/$sn/error/post');
|
||
_tokens.remove(sn);
|
||
final subscription = _subscriptions.remove(sn);
|
||
if (subscription != null) subscriptions.add(subscription);
|
||
}
|
||
_releasing = _releasing
|
||
.then((_) async {
|
||
await Future.wait(
|
||
subscriptions.map((subscription) => subscription.cancel()),
|
||
);
|
||
})
|
||
.catchError((Object error) {
|
||
debugPrintSynchronously('[场站告警] 释放订阅失败: $error');
|
||
});
|
||
return _releasing;
|
||
}
|
||
|
||
Future<void> retry() => loadSite(state.siteId, force: true);
|
||
|
||
/// 弹窗入口统一检查;复用健康监听,仅在缺失/异常时重查场站并补订阅。
|
||
Future<void> ensureSubscriptions({String? deviceSn}) async {
|
||
final sn = deviceSn?.trim();
|
||
final siteId = state.siteId;
|
||
final siteVersion = _siteVersion;
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_START] site=$siteId scope=${sn ?? 'ALL'} '
|
||
'loading=${state.isLoading} loadFailed=${state.loadFailed}',
|
||
);
|
||
if (isClosed || _closing || siteId == null) {
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_SKIP] site=$siteId closed=$isClosed closing=$_closing '
|
||
'reason=${siteId == null ? '尚未选中场站' : '告警状态已关闭'}',
|
||
);
|
||
return;
|
||
}
|
||
final requested = sn == null ? _targets.keys.toSet() : {sn};
|
||
var needsRepair = state.loadFailed || requested.isEmpty;
|
||
for (final target in requested) {
|
||
final exists = _subscriptions.containsKey(target);
|
||
final failed = state.failedSns.contains(target);
|
||
final inSite = _targets.containsKey(target);
|
||
final count = state.forDevice(target).alarms.length;
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_TOPIC] site=$siteId SN=$target '
|
||
'topic=device/$target/error/post inSite=$inSite '
|
||
'localListener=$exists failed=$failed '
|
||
'received=${state.receivedSns.contains(target)} cachedRecords=$count '
|
||
'action=${exists && !failed ? 'REUSE' : 'REPAIR'} '
|
||
'broker确认请看SUB_ACK',
|
||
wrapWidth: 800,
|
||
);
|
||
if (!exists || failed || !inSite) needsRepair = true;
|
||
}
|
||
if (state.isLoading) {
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_WAIT] site=$siteId 场站设备/订阅正在加载,复用进行中的加载',
|
||
);
|
||
return;
|
||
}
|
||
if (needsRepair) {
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_REPAIR] site=$siteId scope=${sn ?? 'ALL'} 重新获取场站车辆并补订阅',
|
||
);
|
||
await loadSite(siteId, force: true);
|
||
}
|
||
if (isClosed || _closing || siteVersion != _siteVersion) {
|
||
debugPrintSynchronously('[场站告警][CHECK_STALE] 检查期间已切换场站,忽略旧结果');
|
||
return;
|
||
}
|
||
final checked = sn == null ? _targets.keys.toSet() : {sn};
|
||
for (final target in checked) {
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_RESULT] site=$siteId topic=device/$target/error/post '
|
||
'inSite=${_targets.containsKey(target)} '
|
||
'localListener=${_subscriptions.containsKey(target)} '
|
||
'failed=${state.failedSns.contains(target)}',
|
||
);
|
||
}
|
||
debugPrintSynchronously(
|
||
'[场站告警][CHECK_DONE] site=$siteId checked=${checked.length} '
|
||
'loadFailed=${state.loadFailed} scopedRecords=${state.forDevice(sn).alarms.length}',
|
||
);
|
||
logSnapshot('点击告警入口检查结束', deviceSn: sn);
|
||
}
|
||
|
||
void logSnapshot(String reason, {String? deviceSn}) {
|
||
debugPrintSynchronously(
|
||
'[场站告警] $reason site=${state.siteId} loading=${state.isLoading} '
|
||
'loadFailed=${state.loadFailed} subscribedSN=${_subscriptions.keys.join(',')} '
|
||
'failedSN=${state.failedSns.join(',')} detailSN=$deviceSn '
|
||
'allRecords=${state.alarms.length} scopedRecords=${state.forDevice(deviceSn).alarms.length}',
|
||
wrapWidth: 800,
|
||
);
|
||
final sns = _subscriptions.keys.toList()..sort();
|
||
debugPrintSynchronously(
|
||
'[场站告警][TOPIC_LIST] site=${state.siteId} count=${sns.length}',
|
||
);
|
||
for (final sn in sns) {
|
||
debugPrintSynchronously('[场站告警][TOPIC_LIST] topic=device/$sn/error/post');
|
||
}
|
||
}
|
||
|
||
String? deviceIdForSn(String sn) => _targets[sn.trim()]?.deviceId;
|
||
|
||
Future<void> handle(int alarmId, {int? historySiteId}) async {
|
||
if (isClosed || _closing || state.handlingIds.contains(alarmId)) return;
|
||
if (alarmId <= 0 || _closedIds.contains(alarmId)) return;
|
||
final alarm = state.alarms
|
||
.where((alarm) => alarm.id == alarmId)
|
||
.firstOrNull;
|
||
if (alarm == null &&
|
||
(historySiteId == null || historySiteId != state.siteId)) {
|
||
return;
|
||
}
|
||
if (alarm?.isClosed ?? false) return;
|
||
if (historySiteId != null && historySiteId != state.siteId) return;
|
||
if (historySiteId != null) _historyIds.add(alarmId);
|
||
final siteVersion = _siteVersion;
|
||
debugPrintSynchronously(
|
||
'[场站告警] 处理告警 site=${state.siteId} SN=${alarm?.sourceSn} alarmId=$alarmId history=${historySiteId != null}',
|
||
);
|
||
emit(
|
||
state.copyWith(
|
||
handlingIds: Set.unmodifiable({...state.handlingIds, alarmId}),
|
||
handleErrors: Map.unmodifiable(
|
||
{...state.handleErrors}..remove(alarmId),
|
||
),
|
||
),
|
||
);
|
||
final result = await handleAlarm(alarmId);
|
||
if (isClosed || _closing || siteVersion != _siteVersion) {
|
||
debugPrintSynchronously('[场站告警] 忽略旧场站处理结果 alarmId=$alarmId');
|
||
return;
|
||
}
|
||
result.fold(
|
||
(failure) => emit(
|
||
state.copyWith(
|
||
handlingIds: Set.unmodifiable(
|
||
{...state.handlingIds}..remove(alarmId),
|
||
),
|
||
handleErrors: Map.unmodifiable({
|
||
...state.handleErrors,
|
||
if (!_closedIds.contains(alarmId)) alarmId: failure.message,
|
||
}),
|
||
),
|
||
),
|
||
(_) {
|
||
debugPrintSynchronously('[场站告警] 处理成功 alarmId=$alarmId,更新共享状态');
|
||
_closedIds.add(alarmId);
|
||
emit(
|
||
state.copyWith(
|
||
closedIds: Set.unmodifiable(_closedIds),
|
||
alarms: List.unmodifiable([
|
||
for (final item in state.alarms)
|
||
item.id == alarmId ? item.closed() : item,
|
||
]),
|
||
handlingIds: Set.unmodifiable(
|
||
{...state.handlingIds}..remove(alarmId),
|
||
),
|
||
handleErrors: Map.unmodifiable(
|
||
{...state.handleErrors}..remove(alarmId),
|
||
),
|
||
),
|
||
);
|
||
},
|
||
);
|
||
}
|
||
|
||
@override
|
||
Future<void> close() async {
|
||
_closing = true;
|
||
++_siteVersion;
|
||
++_loadVersion;
|
||
await _release(_subscriptions.keys.toList());
|
||
return super.close();
|
||
}
|
||
}
|